change_controller.js 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const stdDataAddType = {
  10. withParent: 1,
  11. child: 2,
  12. next: 3,
  13. };
  14. const moment = require('moment');
  15. const sendToWormhole = require('stream-wormhole');
  16. const fs = require('fs');
  17. const path = require('path');
  18. const audit = require('../const/audit');
  19. const codeRuleConst = require('../const/code_rule');
  20. const changeConst = require('../const/change');
  21. const accountGroup = require('../const/account_group').group;
  22. const shenpiConst = require('../const/shenpi');
  23. const tenderMenu = require('../../config/menu').tenderMenu;
  24. const measureType = require('../const/tender').measureType;
  25. const spreadConst = require('../const/spread');
  26. // const tenderMenu = require('../../config/menu').tenderMenu;
  27. module.exports = app => {
  28. class ChangeController extends app.BaseController {
  29. /**
  30. * 构造函数
  31. *
  32. * @param {Object} ctx - egg全局变量
  33. * @return {void}
  34. */
  35. constructor(ctx) {
  36. super(ctx);
  37. ctx.showProject = true;
  38. ctx.showTender = true;
  39. ctx.showTitle = true;
  40. }
  41. async _filterChanges(ctx, status = 0) {
  42. const tenderId = ctx.params.id;
  43. ctx.session.sessionUser.tenderId = tenderId;
  44. const tender = await this.service.tender.getDataById(tenderId);
  45. // const tenderList = await this.service.tender.getList();
  46. const page = ctx.page;
  47. const pageSize = ctx.pageSize;
  48. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  49. const orders = ctx.query.order ? ctx.query.order : 0;
  50. const changes = await ctx.service.change.getListByStatus(tender.id, status, 1, sorts, orders);
  51. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  52. let page_total = 0;
  53. const tp = await ctx.service.change.getTp(tender.id, status);
  54. if (changes !== null) {
  55. let i = 0;
  56. for (const c of changes) {
  57. page_total = ctx.helper.add(page_total, c.total_price);
  58. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  59. // 根据审批人对当前变更令的状态取不同的展示方式。
  60. let changeAudit = '';
  61. let auditStatus = 0;
  62. switch (c.status) {
  63. case 1:
  64. auditStatus = 1;
  65. break;
  66. case 2:
  67. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  68. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  69. break;
  70. case 3:
  71. case 4:
  72. auditStatus = 0;
  73. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  74. break;
  75. case 5:
  76. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  77. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  78. const back_changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  79. c.stageChangeNum = this.ctx.helper.sum(back_changeUsedData.map(x => { return Math.abs(x.qty); }));
  80. break;
  81. case 6:
  82. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  83. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  84. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  85. break;
  86. case 9:
  87. auditStatus = 9;
  88. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  89. c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  90. break;
  91. default:
  92. break;
  93. }
  94. changes[i].changeAudit = changeAudit;
  95. changes[i].auditStatus = auditStatus;
  96. i++;
  97. }
  98. }
  99. // 分页相关
  100. const pageInfo = {
  101. page,
  102. pageSizeSelect: 1,
  103. pageSize,
  104. total_num: total,
  105. total: Math.ceil(total / pageSize),
  106. queryData: JSON.stringify(ctx.urlInfo.query),
  107. };
  108. const filter = JSON.parse(JSON.stringify(audit.filter));
  109. filter.count = [];
  110. filter.count[filter.status.pending] = await ctx.service.change.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  111. filter.count[filter.status.uncheck] = await ctx.service.change.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  112. filter.count[filter.status.checking] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  113. filter.count[filter.status.checked] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  114. filter.count[filter.status.checkNo] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  115. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  116. for (const rule of codeRule) {
  117. switch (rule.rule_type) {
  118. case codeRuleConst.measure.ruleType.dealCode:
  119. rule.preview = ctx.tender.info.deal_info.dealCode;
  120. break;
  121. case codeRuleConst.measure.ruleType.tenderName:
  122. rule.preview = tender.name;
  123. break;
  124. case codeRuleConst.measure.ruleType.inDate:
  125. rule.preview = moment().format('YYYY');
  126. break;
  127. case codeRuleConst.measure.ruleType.text:
  128. rule.preview = rule.text;
  129. break;
  130. case codeRuleConst.measure.ruleType.addNo:
  131. const s = '0000000000';
  132. rule.preview = s.substr(s.length - rule.format);
  133. break;
  134. default: break;
  135. }
  136. }
  137. const changePlanList = await ctx.service.changePlan.getAllDataByCondition({ where: { tid: tender.id, status: audit.changePlan.status.checked } });
  138. const allPlanCodes = await ctx.service.change.getAllDataByCondition({
  139. columns: ['plan_code'],
  140. where: {
  141. tid: tender.id,
  142. },
  143. });
  144. const apLists = allPlanCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allPlanCodes, 'plan_code')) : [];
  145. const renderData = {
  146. uid: ctx.session.sessionUser.accountId,
  147. moment,
  148. tender,
  149. // tenderList,
  150. pageInfo,
  151. changes,
  152. page_total,
  153. tp,
  154. filter,
  155. status,
  156. codeRule,
  157. dealCode: ctx.tender.info.deal_info.dealCode,
  158. auditConst: audit.flow,
  159. changeConst,
  160. ruleType: codeRuleConst.ruleType.change,
  161. ruleConst: codeRuleConst.measure,
  162. tenderMenu: this.menu.tenderMenu,
  163. preUrl: '/tender/' + tenderId,
  164. tpUnit: ctx.tender.info.decimal.tp,
  165. changePlanList,
  166. apLists,
  167. };
  168. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  169. }
  170. /**
  171. * 变更管理 页面 (Get)
  172. *
  173. * @param {Object} ctx - egg全局变量
  174. * @return {void}
  175. */
  176. async index(ctx) {
  177. try {
  178. await this._filterChanges(ctx);
  179. } catch (err) {
  180. this.log(err);
  181. ctx.redirect('/dashboard');
  182. }
  183. }
  184. /**
  185. *
  186. * @param {Object} ctx - egg全局变量
  187. * @return {void}
  188. */
  189. async newCode(ctx) {
  190. const responseData = {
  191. err: 0,
  192. msg: '',
  193. data: '',
  194. };
  195. try {
  196. const tenderId = ctx.params.id;
  197. if (!tenderId) {
  198. throw '当前未打开标段';
  199. }
  200. const tenderData = await ctx.service.tender.getDataById(tenderId);
  201. const data = JSON.parse(ctx.request.body.data);
  202. let cCodeRule;
  203. let cConnector;
  204. let changeCount = 0;
  205. if (data && data.type) {
  206. const c_code_rules = tenderData.c_code_rules !== null ? JSON.parse(tenderData.c_code_rules) : null;
  207. cCodeRule = c_code_rules && c_code_rules[data.type + '_rule'] ? c_code_rules[data.type + '_rule'] : [];
  208. cConnector = c_code_rules && c_code_rules[data.type + '_connector'] ? c_code_rules[data.type + '_connector'] : null;
  209. if (data.type === codeRuleConst.ruleField[codeRuleConst.ruleType.apply]) {
  210. changeCount = await ctx.service.changeApply.count({ tid: tenderId });
  211. } else {
  212. changeCount = await ctx.service.changeProject.count({ tid: tenderId, type: codeRuleConst.ruleType[data.type] });
  213. }
  214. } else {
  215. cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  216. cConnector = tenderData.c_connector;
  217. changeCount = await ctx.service.change.count({ tid: tenderId });
  218. }
  219. const code = [];
  220. for (const rule of cCodeRule) {
  221. switch (rule.rule_type) {
  222. case codeRuleConst.measure.ruleType.dealCode:
  223. code.push(ctx.tender.info.deal_info.dealCode);
  224. break;
  225. case codeRuleConst.measure.ruleType.tenderName:
  226. code.push(tenderData.name);
  227. break;
  228. case codeRuleConst.measure.ruleType.text:
  229. code.push(rule.text);
  230. break;
  231. case codeRuleConst.measure.ruleType.inDate:
  232. code.push(moment().format('YYYY'));
  233. break;
  234. case codeRuleConst.measure.ruleType.addNo:
  235. let s = '0000000000';
  236. const count = rule.start + changeCount;
  237. s = s + count;
  238. code.push(s.substr(s.length - rule.format));
  239. break;
  240. default: break;
  241. }
  242. }
  243. responseData.data = code.join(cConnector !== null && cConnector !== 3 ? codeRuleConst.measure.connectorString[cConnector] : '');
  244. } catch (err) {
  245. responseData.err = 1;
  246. responseData.msg = err;
  247. }
  248. ctx.body = responseData;
  249. }
  250. /**
  251. * 新增变更 (Post)
  252. *
  253. * @param {Object} ctx - egg全局变量
  254. * @return {void}
  255. */
  256. async add(ctx) {
  257. try {
  258. const tenderId = ctx.params.id;
  259. if (!tenderId) {
  260. throw '当前未打开标段';
  261. }
  262. const data = JSON.parse(ctx.request.body.data);
  263. if (!data.code || data.code === '') {
  264. throw '变更令号不能为空';
  265. }
  266. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.plan_code, data.name);
  267. ctx.body = { err: 0, msg: '', data: change };
  268. } catch (err) {
  269. this.log(err);
  270. ctx.body = { err: 1, msg: err.toString() };
  271. }
  272. }
  273. /**
  274. * 变更管理 状态筛选 页面 (Get)
  275. * @param {Object} ctx - egg全局变量
  276. * @return {void}
  277. */
  278. async status(ctx) {
  279. try {
  280. const status = parseInt(ctx.params.status);
  281. await this._filterChanges(ctx, status);
  282. } catch (err) {
  283. this.logger.error(err);
  284. ctx.redirect('/tender/' + ctx.params.id + '/change');
  285. }
  286. }
  287. /**
  288. * 变更信息 页面 (Get)
  289. *
  290. * @param {Object} ctx - egg全局变量
  291. * @return {void}
  292. */
  293. async info(ctx) {
  294. try {
  295. const whiteList = this.ctx.app.config.multipart.whitelist;
  296. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  297. ctx.session.sessionUser.tenderId = tenderid;
  298. const tender = await ctx.service.tender.getDataById(tenderid);
  299. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  300. // 后台判断当前人查看info状态
  301. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  302. // 获取附件列表
  303. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  304. // 获取其他变更令数据
  305. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  306. // 根据auditStatus获取审批人列表
  307. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  308. // 获取已选清单
  309. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  310. // 获取用户人验证手机号
  311. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  312. const auth_mobile = pa.auth_mobile;
  313. const renderData = {
  314. uid: ctx.session.sessionUser.accountId,
  315. tender,
  316. change,
  317. othersChange,
  318. changeConst,
  319. auditStatus,
  320. auditConst: audit.flow,
  321. ledgerConsts: audit.ledger.status,
  322. attList,
  323. whiteList,
  324. auditList,
  325. changeList,
  326. tpUnit: change.tp_decimal !== null ? change.tp_decimal : ctx.tender.info.decimal.tp,
  327. upUnit: change.up_decimal !== null ? change.up_decimal : ctx.tender.info.decimal.up,
  328. authMobile: auth_mobile,
  329. shenpiConst,
  330. };
  331. // 根据auditStatus状态获取的不同的数据
  332. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  333. renderData.changeUnits = changeConst.units;
  334. renderData.precision = ctx.tender.info.precision;
  335. // renderData.accountGroup = accountGroup;
  336. // 获取所有项目参与者
  337. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  338. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  339. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  340. });
  341. renderData.accountList = accountList;
  342. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  343. renderData.accountGroup = unitList.map(item => {
  344. const groupList = accountList.filter(item1 => item1.company === item.name);
  345. return { groupName: item.name, groupList };
  346. });
  347. // 重新上报获取审批流程
  348. if (auditStatus === 2 || auditStatus === 9) {
  349. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  350. // 展示页右侧审批流程列表
  351. const auditList3 = [];
  352. for (let time = 1; time <= change.times - 1; time++) {
  353. const auditTimeList = [];
  354. let max_sort = 1;
  355. for (const al of auditList2) {
  356. if (al.times === time) {
  357. auditTimeList.push(al);
  358. if (al.usite > max_sort) {
  359. max_sort = al.usite;
  360. }
  361. }
  362. }
  363. for (const i in auditTimeList) {
  364. auditTimeList[i].max_sort = max_sort;
  365. }
  366. auditList3.push(auditTimeList);
  367. }
  368. renderData.auditList3 = auditList3;
  369. }
  370. // 根据清单获取提交数据和计算总金额
  371. const changeListData = [];
  372. const changeWhiteListData = [];
  373. let ototalCost = 0;
  374. let ctotalCost = 0;
  375. for (const cl of changeList) {
  376. const cLArray = [
  377. cl.code,
  378. cl.name,
  379. cl.bwmx,
  380. cl.unit,
  381. cl.unit_price,
  382. cl.oamount,
  383. cl.camount,
  384. cl.detail,
  385. cl.lid,
  386. cl.xmj_code,
  387. cl.xmj_jldy,
  388. cl.gcl_id,
  389. ];
  390. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  391. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  392. if (cl.lid !== '0') {
  393. changeListData.push(cLArray.join('*;*'));
  394. } else {
  395. changeWhiteListData.push(cLArray.join('*;*'));
  396. }
  397. }
  398. renderData.changeListData = changeListData.join('^_^');
  399. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  400. renderData.ototalCost = ototalCost;
  401. renderData.ctotalCost = ctotalCost;
  402. // 获取公司列表
  403. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  404. renderData.companyList = companyList;
  405. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  406. // 展示页左侧审批流程列表和清单审批列表数据
  407. const times = change.status === audit.flow.status.back ?
  408. change.times - 1 : change.times;
  409. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  410. // 展示页右侧审批流程列表
  411. const auditList3 = [];
  412. for (let time = 1; time <= times; time++) {
  413. const auditTimeList = [];
  414. let max_sort = 1;
  415. for (const al of auditList) {
  416. if (al.times === time) {
  417. auditTimeList.push(al);
  418. if (al.usite > max_sort) {
  419. max_sort = al.usite;
  420. }
  421. }
  422. }
  423. for (const i in auditTimeList) {
  424. auditTimeList[i].max_sort = max_sort;
  425. }
  426. auditList3.push(auditTimeList);
  427. }
  428. renderData.auditList3 = auditList3;
  429. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  430. renderData.changeList = changeList;
  431. let ototalCost = 0;
  432. let ctotalCost = 0;
  433. let stotalCost = 0;
  434. const auditTotalCost = [];
  435. for (const cl of changeList) {
  436. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  437. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  438. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  439. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  440. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  441. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  442. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  443. auditTotalCost.push(audit_amount);
  444. }
  445. renderData.ototalCost = ototalCost;
  446. renderData.ctotalCost = ctotalCost;
  447. renderData.stotalCost = stotalCost;
  448. // 清单表页赋值
  449. for (const [index, au] of auditList2.entries()) {
  450. if (au.usite !== 0) {
  451. au.list_amount = [];
  452. au.totalCost = 0;
  453. for (const [auindex, at] of auditTotalCost.entries()) {
  454. au.list_amount.push(at[index - 1]);
  455. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  456. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  457. }
  458. }
  459. }
  460. renderData.auditList2 = auditList2;
  461. } else if (auditStatus === 6) {
  462. // 展示页左侧审批流程列表和清单审批列表数据
  463. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  464. renderData.auditList2 = auditList2;
  465. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  466. for (const i in auditList3) {
  467. auditList3[i].max_sort = auditList2.length - 1;
  468. }
  469. renderData.auditList3 = auditList3;
  470. // 展示页右侧审批流程列表
  471. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  472. const auditList4 = [];
  473. for (let time = 1; time <= change.times; time++) {
  474. const auditTimeList = [];
  475. let max_sort = 1;
  476. for (const al of auditList5) {
  477. if (al.times === time) {
  478. auditTimeList.push(al);
  479. if (al.usite > max_sort) {
  480. max_sort = al.usite;
  481. }
  482. }
  483. }
  484. for (const i in auditTimeList) {
  485. auditTimeList[i].max_sort = max_sort;
  486. }
  487. if (auditTimeList.length > 0) {
  488. auditList4.push(auditTimeList);
  489. }
  490. }
  491. renderData.auditList4 = auditList4;
  492. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  493. renderData.changeList = changeList;
  494. let ototalCost = 0;
  495. let ctotalCost = 0;
  496. const auditTotalCost = [];
  497. const auditUnit = [];
  498. for (const cl of changeList) {
  499. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  500. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  501. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  502. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  503. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  504. auditTotalCost.push(audit_amount);
  505. }
  506. renderData.ototalCost = ototalCost;
  507. renderData.ctotalCost = ctotalCost;
  508. // 清单表页赋值
  509. for (const [index, au] of auditList.entries()) {
  510. if (au.usite !== 0) {
  511. au.list_amount = [];
  512. au.totalCost = 0;
  513. if (au.uid === renderData.uid) {
  514. for (const [auindex, at] of auditTotalCost.entries()) {
  515. // if (at[index - 2] !== undefined) {
  516. // au.list_amount.push(at[index - 2]);
  517. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  518. // } else if (at[index - 2] === undefined) {
  519. // au.list_amount.push(changeList[auindex].camount);
  520. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  521. // }
  522. au.list_amount.push(changeList[auindex].spamount);
  523. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  524. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  525. }
  526. } else {
  527. for (const [auindex, at] of auditTotalCost.entries()) {
  528. au.list_amount.push(at[index - 1]);
  529. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  530. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  531. }
  532. }
  533. }
  534. }
  535. }
  536. renderData.auditList = auditList;
  537. // 获取是否已存在调用变更令
  538. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  539. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  540. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  541. } catch (err) {
  542. this.log(err);
  543. ctx.redirect('/tender/' + ctx.params.id + '/change');
  544. }
  545. }
  546. /**
  547. * 变更信息 新版本页面 (Get)
  548. *
  549. * @param {Object} ctx - egg全局变量
  550. * @return {void}
  551. */
  552. async information(ctx) {
  553. try {
  554. const whiteList = this.ctx.app.config.multipart.whitelist;
  555. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  556. const change = ctx.change;
  557. // 后台判断当前人查看info状态
  558. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  559. // 获取附件列表
  560. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  561. // 获取其他变更令数据
  562. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  563. // 根据auditStatus获取审批人列表
  564. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  565. // 获取变更方案的清单
  566. let planList = [];
  567. let showPlanBtn = false;
  568. if (ctx.session.sessionProject.page_show.openChangePlan) {
  569. const planInfo = change.plan_code ? await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, code: change.plan_code }) : null;
  570. showPlanBtn = change.plan_code !== null && change.plan_code !== '';
  571. if (planInfo && planInfo.id) {
  572. planList = await ctx.service.changePlanList.getAllDataByCondition({ where: { cpid: planInfo.id } });
  573. }
  574. }
  575. // 工程变更类别读取
  576. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  577. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  578. // 获取用户人验证手机号
  579. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  580. const auth_mobile = pa.auth_mobile;
  581. const renderData = {
  582. tender,
  583. change,
  584. othersChange,
  585. changeConst,
  586. changeClass: fun_set.change_class,
  587. auditStatus,
  588. auditConst: audit.flow,
  589. ledgerConsts: audit.ledger.status,
  590. attList,
  591. whiteList,
  592. auditList,
  593. showPlanBtn,
  594. planList,
  595. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  596. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  597. authMobile: auth_mobile,
  598. shenpiConst,
  599. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  600. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  601. precision: ctx.tender.info.precision,
  602. };
  603. // 根据auditStatus状态获取的不同的数据
  604. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  605. renderData.changeUnits = changeConst.units;
  606. // renderData.accountGroup = accountGroup;
  607. // 获取所有项目参与者
  608. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  609. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  610. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  611. });
  612. renderData.accountList = accountList;
  613. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  614. renderData.accountGroup = unitList.map(item => {
  615. const groupList = accountList.filter(item1 => item1.company === item.name);
  616. return { groupName: item.name, groupList };
  617. });
  618. // 重新上报获取审批流程
  619. if (auditStatus === 2 || auditStatus === 9) {
  620. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  621. // 展示页右侧审批流程列表
  622. const auditList3 = [];
  623. for (let time = 1; time <= change.times - 1; time++) {
  624. const auditTimeList = [];
  625. let max_sort = 1;
  626. for (const al of auditList2) {
  627. if (al.times === time) {
  628. auditTimeList.push(al);
  629. if (al.usite > max_sort) {
  630. max_sort = al.usite;
  631. }
  632. }
  633. }
  634. for (const i in auditTimeList) {
  635. auditTimeList[i].max_sort = max_sort;
  636. }
  637. auditList3.push(auditTimeList);
  638. }
  639. renderData.auditList3 = auditList3;
  640. }
  641. // 获取公司列表
  642. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  643. renderData.companyList = companyList;
  644. // 获取已选清单
  645. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  646. renderData.changeList = changeList;
  647. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  648. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  649. // 判断是否更新变更类别
  650. if (ctx.helper._.findIndex(fun_set.change_class, { value: change.class, checked: true }) === -1) {
  651. renderData.change.class = ctx.helper._.find(fun_set.change_class, { checked: true }).value;
  652. await ctx.service.change.saveInfo({ class: ctx.helper._.find(fun_set.change_class, { checked: true }).value });
  653. }
  654. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7 || auditStatus === 8) {
  655. // 展示页左侧审批流程列表和清单审批列表数据
  656. const times = change.status === audit.flow.status.back ?
  657. change.times - 1 : change.times;
  658. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  659. // 展示页右侧审批流程列表
  660. const auditList3 = [];
  661. for (let time = 1; time <= times; time++) {
  662. const auditTimeList = [];
  663. let max_sort = 1;
  664. for (const al of auditList) {
  665. if (al.times === time) {
  666. auditTimeList.push(al);
  667. if (al.usite > max_sort) {
  668. max_sort = al.usite;
  669. }
  670. }
  671. }
  672. for (const i in auditTimeList) {
  673. auditTimeList[i].max_sort = max_sort;
  674. }
  675. auditList3.push(auditTimeList);
  676. }
  677. renderData.auditList3 = auditList3;
  678. // 获取已选清单
  679. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  680. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  681. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  682. for (const cl of changeList) {
  683. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  684. // 清单表页赋值
  685. for (const [index, au] of auditList2.entries()) {
  686. if (au.usite !== 0) {
  687. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  688. }
  689. }
  690. cl.changed_amount = (change.status === audit.flow.status.backnew || change.status === audit.flow.status.checking || change.status === audit.flow.status.checked) && audit_amount !== '' ? audit_amount[audit_amount.length - 1] : cl.camount;
  691. // cl.changed_amount = ctx.helper.add(cl.oamount ? parseFloat(cl.oamount) : 0, changed_amount ? parseFloat(changed_amount) : 0);
  692. }
  693. renderData.changeList = changeList;
  694. renderData.auditList2 = auditList2;
  695. } else if (auditStatus === 6) {
  696. // 展示页左侧审批流程列表和清单审批列表数据
  697. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  698. renderData.auditList2 = auditList2;
  699. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  700. for (const i in auditList3) {
  701. auditList3[i].max_sort = auditList2.length - 1;
  702. }
  703. renderData.auditList3 = auditList3;
  704. // 展示页右侧审批流程列表
  705. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  706. const auditList4 = [];
  707. for (let time = 1; time <= change.times; time++) {
  708. const auditTimeList = [];
  709. let max_sort = 1;
  710. for (const al of auditList5) {
  711. if (al.times === time) {
  712. auditTimeList.push(al);
  713. if (al.usite > max_sort) {
  714. max_sort = al.usite;
  715. }
  716. }
  717. }
  718. for (const i in auditTimeList) {
  719. auditTimeList[i].max_sort = max_sort;
  720. }
  721. if (auditTimeList.length > 0) {
  722. auditList4.push(auditTimeList);
  723. }
  724. }
  725. renderData.auditList4 = auditList4;
  726. // 获取已选清单
  727. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  728. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  729. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  730. for (const cl of changeList) {
  731. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  732. // 清单表页赋值
  733. for (const [index, au] of auditList2.entries()) {
  734. if (au.usite !== 0) {
  735. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  736. }
  737. }
  738. cl.changed_amount = (change.status === audit.flow.status.backnew || change.status === audit.flow.status.checking || change.status === audit.flow.status.checked) && audit_amount !== '' ? audit_amount[audit_amount.length - 1] : cl.camount;
  739. // cl.changed_amount = ctx.helper.add(cl.oamount ? parseFloat(cl.oamount) : 0, changed_amount ? parseFloat(changed_amount) : 0);
  740. }
  741. renderData.changeList = changeList;
  742. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  743. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  744. }
  745. renderData.auditList = auditList;
  746. // 获取是否已存在调用变更令
  747. let changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  748. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  749. return item.qty !== null;
  750. }), ['sorder'], ['desc']);
  751. const useChangeUsedData = [];
  752. if (changeUsedData.length > 0) { // 防止未创建期时调用
  753. // const stage = await this.ctx.service.stage.getLastestStage(ctx.tender.id, true);
  754. for (const cu of changeUsedData) {
  755. // if (cu.sorder !== 0 ||
  756. // (cu.sorder === 0 && !(stage.status === audit.stage.status.uncheck || stage.status === audit.stage.status.checkNo))) {
  757. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  758. if (index !== -1) {
  759. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  760. } else {
  761. useChangeUsedData.push(cu);
  762. }
  763. // }
  764. }
  765. }
  766. renderData.changeUsedData = useChangeUsedData;
  767. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  768. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  769. } catch (err) {
  770. this.log(err);
  771. ctx.redirect('/tender/' + ctx.params.id + '/change');
  772. }
  773. }
  774. /**
  775. * 变更清单 - 操作 (Ajax)
  776. * @param ctx
  777. * @return {Promise<void>}
  778. */
  779. async saveListsData(ctx) {
  780. try {
  781. const data = JSON.parse(ctx.request.body.data);
  782. const responseData = {
  783. err: 0,
  784. msg: '',
  785. data: {},
  786. };
  787. switch (data.type) {
  788. case 'add':
  789. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  790. break;
  791. case 'batchadd':
  792. responseData.data = await ctx.service.changeAuditList.batchAdd(data);
  793. break;
  794. case 'del':
  795. await ctx.service.changeAuditList.del(data);
  796. break;
  797. case 'update':
  798. await ctx.service.changeAuditList.save(data.updateData);
  799. break;
  800. case 'paste':
  801. await ctx.service.changeAuditList.saveDatas(data.updateData);
  802. // 取所有工料表
  803. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  804. break;
  805. case 'ledger_list':
  806. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData, data.postData);
  807. // 取所有工料表
  808. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  809. usedList: await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, ctx.change.cid) };
  810. break;
  811. case 'remove_list':
  812. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  813. // 取所有工料表
  814. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  815. break;
  816. case 'update_list':
  817. await ctx.service.changeAuditList.saveDatas(data.updateData);
  818. // 取所有工料表
  819. // responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  820. break;
  821. case 'info':
  822. await ctx.service.change.saveInfo(data.updateData);
  823. // 取所有工料表
  824. responseData.data = '保存成功';
  825. break;
  826. case 'paste_amount_rows':
  827. await ctx.service.changeAuditList.saveDatas(data.updateData);
  828. const changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  829. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  830. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  831. for (const cl of changeList) {
  832. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  833. // 清单表页赋值
  834. for (const [index, au] of auditList2.entries()) {
  835. if (au.usite !== 0) {
  836. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  837. }
  838. }
  839. }
  840. // 取所有工料表
  841. responseData.data = changeList;
  842. break;
  843. case 'update_tp':
  844. await ctx.service.change.saveInfo(data.updateData);
  845. break;
  846. case 'order_by':
  847. const result = await ctx.service.change.saveOrderBy(data.updateData, data.newLedgerList);
  848. responseData.data = result;
  849. break;
  850. case 'changeOrder':
  851. await ctx.service.changeAuditList.changeOrder(data.postData);
  852. break;
  853. default: throw '参数有误';
  854. }
  855. ctx.body = responseData;
  856. } catch (err) {
  857. this.log(err);
  858. ctx.body = { err: 1, msg: err.toString(), data: null };
  859. }
  860. }
  861. /**
  862. * 上报和重新上报
  863. * @param ctx
  864. * @return {Promise<void>}
  865. */
  866. async startAudit(ctx) {
  867. try {
  868. // 检查权限等
  869. if (!ctx.change) {
  870. throw '数据错误';
  871. }
  872. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  873. throw '您无权上报该变更令数据';
  874. }
  875. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back || ctx.change.status === audit.flow.status.revise)) {
  876. throw '该变更令当前无法上报';
  877. }
  878. // 判断是否是修订,判断有无审批人员作弊
  879. if ((ctx.change.status === audit.flow.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  880. // 获取上一次的审批人流程
  881. const lastUserList = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times - 1);
  882. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  883. // 判断上一次审批是否为非原报为审批人
  884. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  885. // 判断条件修订可上报条件
  886. // 1.有原报,有其他人 可以添加原报作为审核人,但是不能只原报上报
  887. // 2.有原报,无其他人 可以添加原报作为审核人,可以只原报上报
  888. // 3.无原报,有其他人 不可以添加原报
  889. const noYBUidList = ctx.change.status === audit.flow.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  890. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  891. throw '该变更令不能指定原报人为单独审批人';
  892. }
  893. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  894. throw '该变更令不能指定原报为审批人,请移除';
  895. }
  896. }
  897. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  898. ctx.redirect(ctx.request.header.referer);
  899. } catch (err) {
  900. this.log(err);
  901. ctx.session.postError = err.toString();
  902. ctx.redirect(ctx.request.header.referer);
  903. }
  904. }
  905. // 审批相关
  906. /**
  907. * 添加审批人
  908. * @param ctx
  909. * @return {Promise<void>}
  910. */
  911. async addAudit(ctx) {
  912. try {
  913. const data = JSON.parse(ctx.request.body.data);
  914. const id = this.app._.toInteger(data.auditorId);
  915. if (isNaN(id) || id <= 0) {
  916. throw '参数错误';
  917. }
  918. // 检查权限等
  919. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  920. throw '您无权添加审核人';
  921. }
  922. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  923. throw '当前不允许添加审核人';
  924. }
  925. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  926. // 检查审核人是否已存在
  927. const exist = this.app._.find(auditorList, { uid: id });
  928. if (exist) {
  929. throw '该审核人已存在,请勿重复添加';
  930. }
  931. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  932. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  933. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  934. if (!result) {
  935. throw '添加审核人失败';
  936. }
  937. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  938. const auditors = null;
  939. ctx.body = { err: 0, msg: '', data: auditors };
  940. } catch (err) {
  941. this.log(err);
  942. ctx.body = { err: 1, msg: err.toString(), data: null };
  943. }
  944. }
  945. /**
  946. * 移除审批人
  947. * @param ctx
  948. * @return {Promise<void>}
  949. */
  950. async deleteAudit(ctx) {
  951. try {
  952. const data = JSON.parse(ctx.request.body.data);
  953. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  954. if (isNaN(id) || id <= 0) {
  955. throw '参数错误';
  956. }
  957. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  958. if (!result) {
  959. throw '移除审核人失败';
  960. }
  961. const auditors = null;
  962. ctx.body = { err: 0, msg: '', data: auditors };
  963. } catch (err) {
  964. ctx.body = { err: 1, msg: err.toString(), data: null };
  965. }
  966. }
  967. async defaultBills(ctx) {
  968. try {
  969. // 判断是否台账修订中,修订中则不获取changeLedger及changePos值
  970. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  971. const data = JSON.parse(ctx.request.body.data);
  972. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  973. const changeLedgerData = !ctx.session.sessionProject.page_show.openChangeRevise ? [] : (lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changeLedger.getData(ctx.tender.id));
  974. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  975. const changePosData = !ctx.session.sessionProject.page_show.openChangeRevise ? [] : (lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changePos.getPosData({ tid: ctx.tender.id }));
  976. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  977. // 标记ledger,搜索需求
  978. if (changePosData.length > 0) {
  979. const cplIdList = ctx.helper._.uniq(ctx.helper._.map(changePosData, 'lid'));
  980. const cLIdList = ctx.helper._.map(changeLedgerData, 'id');
  981. const ledgerIdList = [];
  982. for (const cp of cplIdList) {
  983. if (ctx.helper._.indexOf(cLIdList, cp) === -1) {
  984. ledgerIdList.push(cp);
  985. }
  986. }
  987. if (ledgerIdList.length > 0) {
  988. for (const lid of ledgerIdList) {
  989. const data = ctx.helper._.find(ledgerData, { id: lid });
  990. data.cid = 1;
  991. }
  992. }
  993. }
  994. ctx.body = { err: 0, msg: '', data: { bills: ctx.helper._.concat(ledgerData, changeLedgerData), pos: ctx.helper._.concat(posData, changePosData), dealBills } };
  995. } catch (err) {
  996. this.log(err);
  997. ctx.body = { err: 1, msg: err.toString(), data: [] };
  998. }
  999. }
  1000. /**
  1001. * 变更令上报和保存
  1002. * @param {Object} ctx - egg全局变量
  1003. * @return {void}
  1004. */
  1005. async save(ctx) {
  1006. // 变更令信息
  1007. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1008. try {
  1009. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  1010. if (!result) {
  1011. throw '上报失败';
  1012. }
  1013. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  1014. ctx.body = { err: 0, msg: '保存成功' };
  1015. } else {
  1016. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  1017. }
  1018. } catch (err) {
  1019. this.log(err);
  1020. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  1021. ctx.body = { err: 1, msg: err.toString() };
  1022. } else {
  1023. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  1024. }
  1025. }
  1026. }
  1027. /**
  1028. * 变更令审批
  1029. * @param {Object} ctx - egg全局变量
  1030. * @return {void}
  1031. */
  1032. async approval(ctx) {
  1033. try {
  1034. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  1035. if (!changeData) {
  1036. throw '变更令数据错误';
  1037. }
  1038. const status = parseInt(ctx.request.body.status);
  1039. let result = false;
  1040. const pid = this.ctx.session.sessionProject.id;
  1041. switch (status) {
  1042. case 3:// 审批通过
  1043. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  1044. break;
  1045. case 4:// 审批终止
  1046. result = await ctx.service.change.approvalStop(ctx.request.body);
  1047. break;
  1048. case 5:// 审批退回到原报人
  1049. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  1050. break;
  1051. case 6:// 审批退回到上一个审批人
  1052. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  1053. break;
  1054. default:break;
  1055. }
  1056. if (!result) {
  1057. throw '审批失败';
  1058. }
  1059. ctx.redirect(ctx.request.header.referer);
  1060. } catch (err) {
  1061. console.log(err);
  1062. ctx.redirect(ctx.request.header.referer);
  1063. }
  1064. }
  1065. /**
  1066. * 变更公司管理
  1067. * @param {Object} ctx - egg全局变量
  1068. * @return {void}
  1069. */
  1070. async updateCompany(ctx) {
  1071. const responseData = {
  1072. err: 0,
  1073. msg: '',
  1074. data: '',
  1075. };
  1076. try {
  1077. const data = JSON.parse(ctx.request.body.data);
  1078. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1079. throw '参数有误';
  1080. }
  1081. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1082. responseData.data = { add: addCompany, select: selectCompany };
  1083. } catch (err) {
  1084. responseData.err = 1;
  1085. responseData.msg = err;
  1086. }
  1087. ctx.body = responseData;
  1088. }
  1089. /**
  1090. * 上传附件
  1091. * @param {Object} ctx - egg全局变量
  1092. * @return {void}
  1093. */
  1094. async uploadFile(ctx) {
  1095. const responseData = {
  1096. err: 0,
  1097. msg: '',
  1098. data: [],
  1099. };
  1100. let stream;
  1101. try {
  1102. const parts = ctx.multipart({ autoFields: true });
  1103. const files = [];
  1104. let index = 0;
  1105. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1106. const extra_upload = change.status === audit.flow.status.checked;
  1107. while ((stream = await parts()) !== undefined) {
  1108. // 判断用户是否选择上传文件
  1109. if (!stream.filename) {
  1110. throw '请选择上传的文件!';
  1111. }
  1112. // const create_time = Date.parse(new Date()) / 1000;
  1113. // const fileInfo = path.parse(stream.filename);
  1114. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  1115. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  1116. // // 判断文件夹是否存在,不存在则直接创建文件夹
  1117. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  1118. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  1119. // }
  1120. // // 保存文件
  1121. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1122. const fileInfo = path.parse(stream.filename);
  1123. const create_time = Date.parse(new Date()) / 1000;
  1124. // const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1125. const filepath = `app/public/upload/${parts.field.tid}/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1126. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1127. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  1128. await sendToWormhole(stream);
  1129. // 保存数据到att表
  1130. const fileData = {
  1131. in_time: create_time,
  1132. filename: fileInfo.name,
  1133. fileext: fileInfo.ext,
  1134. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1135. filepath,
  1136. extra_upload,
  1137. };
  1138. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1139. if (!result) {
  1140. throw '导入数据库保存失败';
  1141. }
  1142. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1143. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1144. fileData.uid = ctx.session.sessionUser.accountId;
  1145. fileData.id = result.insertId;
  1146. fileData.orginpath = ctx.app.config.fujianOssPath + filepath;
  1147. delete fileData.filepath;
  1148. if (!ctx.helper.canPreview(fileData.fileext)) {
  1149. fileData.filepath = `/change/download/file/${fileData.id}`;
  1150. } else {
  1151. fileData.filepath = ctx.app.config.fujianOssPath + filepath;
  1152. }
  1153. files.push(fileData);
  1154. ++index;
  1155. }
  1156. responseData.data = files;
  1157. } catch (err) {
  1158. this.log(err);
  1159. // 失败需要消耗掉stream 以防卡死
  1160. if (stream) {
  1161. await sendToWormhole(stream);
  1162. }
  1163. this.setMessage(err.toString(), this.messageType.ERROR);
  1164. }
  1165. ctx.body = responseData;
  1166. }
  1167. /**
  1168. * 下载附件
  1169. * @param {Object} ctx - egg全局变量
  1170. * @return {void}
  1171. */
  1172. async downloadFile(ctx) {
  1173. const id = ctx.params.id;
  1174. if (id) {
  1175. try {
  1176. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1177. if (fileInfo !== undefined && fileInfo !== '') {
  1178. // const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1179. // 解决中文无法下载问题
  1180. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1181. let disposition = '';
  1182. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1183. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1184. } else if (userAgent.indexOf('firefox') >= 0) {
  1185. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1186. } else {
  1187. /* safari等其他非主流浏览器只能自求多福了 */
  1188. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1189. }
  1190. ctx.response.set({
  1191. 'Content-Type': 'application/octet-stream',
  1192. 'Content-Disposition': disposition,
  1193. 'Content-Length': fileInfo.filesize,
  1194. });
  1195. // ctx.body = await fs.createReadStream(fileName);
  1196. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1197. } else {
  1198. throw '不存在该文件';
  1199. }
  1200. } catch (err) {
  1201. this.log(err);
  1202. this.setMessage(err.toString(), this.messageType.ERROR);
  1203. }
  1204. }
  1205. }
  1206. /**
  1207. * 批量下载 - 压缩成zip文件返回
  1208. * @param {Oject} ctx - 全局上下文
  1209. */
  1210. async downloadZip(ctx) {
  1211. const time = Date.now();
  1212. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1213. const responseData = {
  1214. err: 0,
  1215. msg: '',
  1216. };
  1217. try {
  1218. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1219. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1220. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1221. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1222. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1223. // 解决中文无法下载问题
  1224. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1225. let disposition = '';
  1226. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1227. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1228. } else if (userAgent.indexOf('firefox') >= 0) {
  1229. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1230. } else {
  1231. /* safari等其他非主流浏览器只能自求多福了 */
  1232. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1233. }
  1234. ctx.response.set({
  1235. 'Content-Type': 'application/octet-stream',
  1236. 'Content-Disposition': disposition,
  1237. 'Content-Length': size,
  1238. });
  1239. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1240. ctx.body = readStream;
  1241. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1242. readStream.on('close', () => {
  1243. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1244. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1245. }
  1246. });
  1247. // fs的错误不能被try catch捕捉
  1248. readStream.on('error', err => {
  1249. this.log(err);
  1250. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1251. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1252. }
  1253. responseData.err = 1;
  1254. responseData.msg = err.toString();
  1255. ctx.body = responseData;
  1256. });
  1257. } catch (err) {
  1258. this.log(err);
  1259. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1260. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1261. }
  1262. this.setMessage(err.toString(), this.messageType.ERROR);
  1263. responseData.err = 1;
  1264. responseData.msg = err.toString();
  1265. ctx.body = responseData;
  1266. }
  1267. }
  1268. /**
  1269. * 删除附件
  1270. * @param {Object} ctx - egg全局变量
  1271. * @return {void}
  1272. */
  1273. async deleteFile(ctx) {
  1274. const responseData = {
  1275. err: 0,
  1276. msg: '',
  1277. data: '',
  1278. };
  1279. try {
  1280. const data = JSON.parse(ctx.request.body.data);
  1281. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1282. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1283. if (!fileInfo || !Object.keys(fileInfo).length) {
  1284. throw '该文件不存在';
  1285. }
  1286. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1287. throw '无权限删除';
  1288. }
  1289. if (fileInfo !== undefined && fileInfo !== '') {
  1290. // 先删除文件
  1291. // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1292. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  1293. // 再删除数据库
  1294. await ctx.service.changeAtt.deleteById(data.id);
  1295. responseData.data = '';
  1296. } else {
  1297. throw '不存在该文件';
  1298. }
  1299. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1300. // throw '参数有误';
  1301. // }
  1302. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1303. // responseData.data = { add: addCompany, select: selectCompany };
  1304. } catch (err) {
  1305. responseData.err = 1;
  1306. responseData.msg = err;
  1307. }
  1308. ctx.body = responseData;
  1309. }
  1310. /**
  1311. * 查看附件
  1312. * @param {Object} ctx - egg全局变量
  1313. * @return {void}
  1314. */
  1315. async checkFile(ctx) {
  1316. const responseData = { err: 0, msg: '' };
  1317. const id = parseInt(ctx.params.id);
  1318. if (id) {
  1319. try {
  1320. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1321. if (fileInfo && Object.keys(fileInfo).length) {
  1322. let filepath = fileInfo.filepath;
  1323. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1324. filepath = `/change/download/file/${fileInfo.id}`;
  1325. } else {
  1326. filepath = filepath.replace(/^app|\/app/, '');
  1327. }
  1328. fileInfo.filepath && (responseData.data = { filepath });
  1329. }
  1330. } catch (error) {
  1331. this.log(error);
  1332. this.setMessage(error.toString(), this.messageType.ERROR);
  1333. responseData.err = 1;
  1334. responseData.msg = error.toString();
  1335. }
  1336. }
  1337. ctx.body = responseData;
  1338. }
  1339. /**
  1340. * 删除变更令
  1341. * @param {Object} ctx - egg全局变量
  1342. * @return {void}
  1343. */
  1344. async delete(ctx) {
  1345. try {
  1346. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1347. if (!result) {
  1348. throw '删除变更令失败';
  1349. }
  1350. ctx.redirect(ctx.request.header.referer);
  1351. } catch (err) {
  1352. console.log(err);
  1353. ctx.redirect(ctx.request.header.referer);
  1354. }
  1355. }
  1356. /**
  1357. * 变更令重新审批
  1358. * @param {Object} ctx - egg全局变量
  1359. * @return {void}
  1360. */
  1361. async checkAgain(ctx) {
  1362. try {
  1363. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1364. if (!changeData) {
  1365. throw '变更令数据错误';
  1366. }
  1367. // 获取终审
  1368. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1369. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1370. throw '您无权进行该操作';
  1371. }
  1372. if (ctx.session.sessionUser.loginStatus === 0) {
  1373. const code = ctx.request.body.code;
  1374. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1375. if (!pa.auth_mobile) {
  1376. throw '未绑定手机号';
  1377. }
  1378. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1379. const cacheCode = await app.redis.get(cacheKey);
  1380. // console.log(cacheCode);
  1381. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1382. throw '验证码不正确!';
  1383. }
  1384. }
  1385. // 获取是否已存在调用变更令
  1386. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1387. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  1388. if (stageChangeNum !== 0) {
  1389. throw '该变更令已被调用,无法重新审批';
  1390. }
  1391. // 重新审批
  1392. const result = await ctx.service.change.checkAgain(changeData.cid);
  1393. if (!result) {
  1394. throw '重新审批失败';
  1395. }
  1396. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1397. ctx.body = {
  1398. err: 0,
  1399. url: ctx.request.header.referer,
  1400. msg: '',
  1401. };
  1402. } catch (err) {
  1403. console.log(err);
  1404. // ctx.redirect(ctx.request.header.referer);
  1405. ctx.body = {
  1406. err: 1,
  1407. // url: ctx.request.header.referer,
  1408. msg: err,
  1409. };
  1410. }
  1411. }
  1412. /**
  1413. * 变更令修订重新上报
  1414. * @param {Object} ctx - egg全局变量
  1415. * @return {void}
  1416. */
  1417. async checkRevise(ctx) {
  1418. try {
  1419. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1420. if (!changeData) {
  1421. throw '变更令数据错误';
  1422. }
  1423. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== changeData.uid) {
  1424. throw '您无权进行该操作';
  1425. }
  1426. if (ctx.session.sessionUser.loginStatus === 0) {
  1427. const code = ctx.request.body.code;
  1428. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1429. if (!pa.auth_mobile) {
  1430. throw '未绑定手机号';
  1431. }
  1432. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1433. const cacheCode = await app.redis.get(cacheKey);
  1434. // console.log(cacheCode);
  1435. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1436. throw '验证码不正确!';
  1437. }
  1438. }
  1439. // 获取是否已存在调用变更令
  1440. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1441. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  1442. // if (stageChangeNum !== 0) {
  1443. // throw '该变更令已被调用,无法重新审批';
  1444. // }
  1445. // 重新审批
  1446. const result = await ctx.service.change.checkRevise(changeData.cid);
  1447. if (!result) {
  1448. throw '修订发起失败';
  1449. }
  1450. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1451. ctx.body = {
  1452. err: 0,
  1453. url: ctx.request.header.referer,
  1454. msg: '',
  1455. };
  1456. } catch (err) {
  1457. console.log(err);
  1458. // ctx.redirect(ctx.request.header.referer);
  1459. ctx.body = {
  1460. err: 1,
  1461. // url: ctx.request.header.referer,
  1462. msg: err,
  1463. };
  1464. }
  1465. }
  1466. /**
  1467. * 获取变更清单
  1468. * @param ctx
  1469. * @return {Promise<void>}
  1470. */
  1471. async bills(ctx) {
  1472. try {
  1473. const data = JSON.parse(ctx.request.body.data);
  1474. const responseData = { err: 0, msg: '', data: [] };
  1475. switch (data.type) {
  1476. case 'gather':
  1477. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1478. break;
  1479. default:
  1480. throw '查询的数据不存在';
  1481. }
  1482. ctx.body = responseData;
  1483. } catch (err) {
  1484. this.log(err);
  1485. this.ajaxErrorBody(err, '获取变更清单失败');
  1486. }
  1487. }
  1488. /**
  1489. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1490. * @param ctx
  1491. * @return {Promise<void>}
  1492. */
  1493. async checkCodeRepeat(ctx) {
  1494. const responseData = {
  1495. err: 0,
  1496. msg: '',
  1497. data: '',
  1498. };
  1499. try {
  1500. const tenderId = ctx.params.id;
  1501. const cid = ctx.params.cid;
  1502. const data = JSON.parse(ctx.request.body.data);
  1503. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1504. if (result) {
  1505. throw '该变更令号(批复编号)已使用';
  1506. }
  1507. } catch (err) {
  1508. responseData.err = 1;
  1509. responseData.msg = err;
  1510. }
  1511. ctx.body = responseData;
  1512. }
  1513. /**
  1514. * 拷贝其他变更令
  1515. * @param {object} ctx - 全局上下文
  1516. */
  1517. async copyChange(ctx) {
  1518. const responseData = {
  1519. err: 0,
  1520. msg: '',
  1521. data: '',
  1522. };
  1523. try {
  1524. const cid = ctx.params.cid;
  1525. const copy_cid = JSON.parse(ctx.request.body.data);
  1526. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1527. if (!result) {
  1528. responseData.err = 1;
  1529. responseData.msg = '拷贝失败!';
  1530. }
  1531. } catch (error) {
  1532. responseData.err = 1;
  1533. responseData.msg = error;
  1534. }
  1535. ctx.body = responseData;
  1536. }
  1537. /**
  1538. * 修订 详细页面(Get)
  1539. * @param ctx
  1540. * @return {Promise<void>}
  1541. */
  1542. async reviseInfo(ctx) {
  1543. try {
  1544. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1545. throw '该功能已关闭';
  1546. }
  1547. const change = ctx.change;
  1548. let edit = true;
  1549. let changing = false;
  1550. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1551. // throw '本条变更审批中或已完成,无法操作台账数据';
  1552. edit = false;
  1553. changing = true;
  1554. }
  1555. let revising = false;
  1556. // 判断是否在修订中,是则无法操作本页
  1557. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1558. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1559. // throw '台账修订中,无法操作台账数据';
  1560. edit = false;
  1561. revising = true;
  1562. }
  1563. const renderData = await this._getDefaultReviseInfoData(ctx, change, edit);
  1564. // 台账只读、使用数据
  1565. renderData.readOnly = !edit;
  1566. renderData.changing = changing;
  1567. renderData.revising = revising;
  1568. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1569. } catch (err) {
  1570. this.log(err);
  1571. ctx.redirect(ctx.request.header.referer);
  1572. }
  1573. }
  1574. async _getDefaultReviseInfoData(ctx, change, edit) {
  1575. const [ledgerSpread, posSpread] = this._getSpreadSetting(change, edit);
  1576. const sjsRela = await this.ctx.service.project.getTenderSjsRela(ctx.session.sessionProject.id, ctx.tender.info.display.exMemo);
  1577. this.ctx.helper.refreshSpreadShow(sjsRela.ledgerCol, [ledgerSpread, posSpread]);
  1578. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1579. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1580. return {
  1581. change,
  1582. tender: ctx.tender.data,
  1583. ledgerSpread, posSpread, tenderMenu, measureType,
  1584. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1585. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1586. stdBills,
  1587. auditConst: audit.flow,
  1588. audit: audit.flow,
  1589. stdChapters,
  1590. };
  1591. }
  1592. /**
  1593. * 获取SpreadSetting
  1594. * @private
  1595. */
  1596. _getSpreadSetting(change, edit) {
  1597. const _ = this.app._;
  1598. function removeFieldCols(setting, cols) {
  1599. _.remove(setting.cols, function(c) {
  1600. return cols.indexOf(c.field) > -1;
  1601. });
  1602. }
  1603. const tender = this.ctx.tender;
  1604. const setting = tender.data.measure_type === measureType.tz.value
  1605. ? (tender.info.display.ledger.clQty ? spreadConst.withCl : spreadConst.withoutCl)
  1606. : (tender.info.display.ledger.clQty ? spreadConst.withClGcl : spreadConst.withoutClGcl);
  1607. const ledger = JSON.parse(JSON.stringify(setting.ledger));
  1608. const pos = setting.pos ? JSON.parse(JSON.stringify(setting.pos)) : spreadConst.blank;
  1609. // if (change.status === audit.flow.status.checking || change.status === audit.flow.status.checked) {
  1610. // ledger.readOnly = true;
  1611. // pos.readOnly = true;
  1612. // }
  1613. if (!edit) {
  1614. ledger.readOnly = true;
  1615. pos.readOnly = true;
  1616. }
  1617. if (tender.data.measure_type === measureType.tz.value) {
  1618. removeFieldCols(ledger, spreadConst.filterCols.dealCols);
  1619. }
  1620. if (!tender.info.display.ledger.dgnQty) {
  1621. removeFieldCols(ledger, spreadConst.filterCols.dgnCols);
  1622. }
  1623. return [ledger, pos];
  1624. }
  1625. async updateRevise(ctx) {
  1626. try {
  1627. if (!ctx.tender.data) throw '标段数据错误';
  1628. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1629. throw '该功能已关闭';
  1630. }
  1631. const data = JSON.parse(ctx.request.body.data);
  1632. if (!data.postType || !data.postData) throw '数据错误';
  1633. const responseData = { err: 0, msg: '', data: {} };
  1634. const change = ctx.change;
  1635. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1636. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1637. }
  1638. // 判断是否在修订中,是则无法操作本页
  1639. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1640. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1641. throw '台账修订中,无法操作新增部位数据';
  1642. }
  1643. // const revise = await this.checkRevise(ctx);
  1644. //
  1645. switch (data.postType) {
  1646. case 'add':
  1647. case 'delete':
  1648. case 'up-move':
  1649. case 'down-move':
  1650. case 'up-level':
  1651. case 'down-level':
  1652. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1653. break;
  1654. case 'update':
  1655. ctx.helper.checkDgnQtyPrecision(data.postData);
  1656. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1657. break;
  1658. case 'paste-block':
  1659. responseData.data = await this._pasteBlock(ctx, data.postData);
  1660. break;
  1661. case 'add-std':
  1662. responseData.data = await this._addStd(ctx, data.postData);
  1663. break;
  1664. case 'add-deal':
  1665. responseData.data = await this._addDeal(ctx, data.postData);
  1666. break;
  1667. // case 'batch-insert':
  1668. // responseData.data = await this._batchInsert(ctx, data.postData);
  1669. // break;
  1670. case 'pos':
  1671. responseData.data = await this._updatePos(ctx, data);
  1672. break;
  1673. default:
  1674. throw '未知操作';
  1675. }
  1676. ctx.body = responseData;
  1677. } catch (err) {
  1678. this.log(err);
  1679. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1680. }
  1681. }
  1682. async _billsBase(ctx, type, data) {
  1683. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1684. if (type !== 'add') {
  1685. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1686. }
  1687. switch (type) {
  1688. case 'add':
  1689. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1690. case 'delete':
  1691. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1692. case 'up-move':
  1693. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1694. case 'down-move':
  1695. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1696. case 'up-level':
  1697. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1698. case 'down-level':
  1699. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1700. default:
  1701. throw '未知操作';
  1702. }
  1703. }
  1704. /**
  1705. * 复制粘贴整块
  1706. *
  1707. * @param ctx
  1708. * @return {Promise<void>}
  1709. */
  1710. async _pasteBlock(ctx, data) {
  1711. if ((isNaN(data.id) || data.id <= 0) ||
  1712. (!data.tid && data.tid <= 0) ||
  1713. (!data.block || data.block.length <= 0)) throw '参数错误';
  1714. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1715. }
  1716. /**
  1717. * 从标准项目表添加数据
  1718. * @param ctx
  1719. * @return {Promise<void>}
  1720. */
  1721. async _addStd(ctx, data) {
  1722. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1723. // todo 校验项目是否使用该库的权限
  1724. let stdLib,
  1725. addType;
  1726. switch (data.stdType) {
  1727. case 'xmj':
  1728. stdLib = ctx.service.stdXmj;
  1729. addType = stdDataAddType.withParent;
  1730. break;
  1731. case 'gcl':
  1732. stdLib = ctx.service.stdGcl;
  1733. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1734. if (selectNode.b_code) {
  1735. addType = stdDataAddType.next;
  1736. } else {
  1737. addType = stdDataAddType.child;
  1738. }
  1739. break;
  1740. default:
  1741. throw '未知标准库';
  1742. }
  1743. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1744. switch (addType) {
  1745. case stdDataAddType.child:
  1746. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1747. case stdDataAddType.next:
  1748. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1749. case stdDataAddType.withParent:
  1750. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1751. default:
  1752. throw '未知添加方式';
  1753. }
  1754. }
  1755. /**
  1756. * 从签约清单添加节点
  1757. * @param ctx
  1758. * @return {Promise<void>}
  1759. */
  1760. async _addDeal(ctx, data) {
  1761. if (!data.type || !data.dealBills) throw '数据错误';
  1762. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1763. if (data.type === 'child') {
  1764. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1765. } else if (data.type === 'next') {
  1766. data.dealBills.ccid = ctx.change.cid;
  1767. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1768. }
  1769. throw '数据错误';
  1770. }
  1771. /**
  1772. * 批量插入数据
  1773. *
  1774. * data = {id, batchData, batchType}
  1775. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1776. * data.batchData = [{name, children}] -- 项目节列表
  1777. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1778. *
  1779. * @param ctx
  1780. * @return {Promise<void>}
  1781. */
  1782. async _batchInsert(ctx, data) {
  1783. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1784. switch (data.batchType) {
  1785. case 'child':
  1786. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1787. case 'next':
  1788. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1789. default:
  1790. throw '参数错误';
  1791. }
  1792. }
  1793. async _updatePos(ctx, data) {
  1794. await this.checkMeasureType(measureType.tz.value);
  1795. if (!data.posPostType) throw '数据错误';
  1796. switch (data.posPostType) {
  1797. case 'add':
  1798. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1799. case 'update':
  1800. if (data.postData instanceof Array) {
  1801. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1802. }
  1803. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1804. case 'delete':
  1805. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1806. case 'paste':
  1807. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1808. default:
  1809. throw '未知操作';
  1810. }
  1811. }
  1812. async _filterChangesProject(ctx, status = 0) {
  1813. const tenderId = ctx.params.id;
  1814. ctx.session.sessionUser.tenderId = tenderId;
  1815. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1816. // const tender = ctx.tender;
  1817. // const tenderList = await this.service.tender.getList();
  1818. const page = ctx.page;
  1819. const pageSize = ctx.pageSize;
  1820. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1821. const orders = ctx.query.order ? ctx.query.order : 0;
  1822. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1823. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1824. for (const c of changes) {
  1825. c.curAuditor = await ctx.service.changeProjectAudit.getAuditorByStatus(c.id, c.status, c.times);
  1826. }
  1827. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1828. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1829. ? JSON.parse(accountInfo.permission) : null;
  1830. // 分页相关
  1831. const pageInfo = {
  1832. page,
  1833. pageSizeSelect: 1,
  1834. pageSize,
  1835. total_num: total,
  1836. total: Math.ceil(total / pageSize),
  1837. queryData: JSON.stringify(ctx.urlInfo.query),
  1838. };
  1839. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  1840. filter.count = [];
  1841. filter.count[filter.status.pending] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1842. filter.count[filter.status.uncheck] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  1843. filter.count[filter.status.checking] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  1844. filter.count[filter.status.checked] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1845. filter.count[filter.status.checkNo] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1846. let codeRule = [];
  1847. let c_connector = '1';
  1848. let c_rule_first = 1;
  1849. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  1850. if (tender.c_code_rules) {
  1851. const c_code_rules = JSON.parse(tender.c_code_rules);
  1852. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  1853. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  1854. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  1855. }
  1856. for (const rule of codeRule) {
  1857. switch (rule.rule_type) {
  1858. case codeRuleConst.measure.ruleType.dealCode:
  1859. rule.preview = ctx.tender.info.deal_info.dealCode;
  1860. break;
  1861. case codeRuleConst.measure.ruleType.tenderName:
  1862. rule.preview = tender.name;
  1863. break;
  1864. case codeRuleConst.measure.ruleType.inDate:
  1865. rule.preview = moment().format('YYYY');
  1866. break;
  1867. case codeRuleConst.measure.ruleType.text:
  1868. rule.preview = rule.text;
  1869. break;
  1870. case codeRuleConst.measure.ruleType.addNo:
  1871. const s = '0000000000';
  1872. rule.preview = s.substr(s.length - rule.format);
  1873. break;
  1874. default: break;
  1875. }
  1876. }
  1877. const renderData = {
  1878. uid: ctx.session.sessionUser.accountId,
  1879. userPermission,
  1880. tender,
  1881. pageInfo,
  1882. changes,
  1883. status,
  1884. rule_type,
  1885. codeRule,
  1886. c_connector,
  1887. c_rule_first,
  1888. filter,
  1889. ruleType: codeRuleConst.ruleType[rule_type],
  1890. dealCode: ctx.tender.info.deal_info.dealCode,
  1891. auditConst: audit.changeProject,
  1892. ruleConst: codeRuleConst.measure,
  1893. changeConst,
  1894. tenderMenu: this.menu.tenderMenu,
  1895. preUrl: '/tender/' + tender.id,
  1896. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  1897. };
  1898. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  1899. }
  1900. /**
  1901. * 变更立项列表 页面 (Get)
  1902. *
  1903. * @param {Object} ctx - egg全局变量
  1904. * @return {void}
  1905. */
  1906. async project(ctx) {
  1907. try {
  1908. await this._filterChangesProject(ctx);
  1909. } catch (err) {
  1910. this.log(err);
  1911. ctx.redirect('/dashboard');
  1912. }
  1913. }
  1914. /**
  1915. * 新增变更立项 (Post)
  1916. *
  1917. * @param {Object} ctx - egg全局变量
  1918. * @return {void}
  1919. */
  1920. async projectAdd(ctx) {
  1921. try {
  1922. const tenderId = ctx.params.id;
  1923. if (!tenderId) {
  1924. throw '当前未打开标段';
  1925. }
  1926. const data = JSON.parse(ctx.request.body.data);
  1927. if (!data.code || data.code === '' || !data.name || data.name === '') {
  1928. throw '变更立项书编号不能为空';
  1929. }
  1930. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  1931. ctx.body = { err: 0, msg: '', data: change };
  1932. } catch (err) {
  1933. this.log(err);
  1934. ctx.body = { err: 1, msg: err.toString() };
  1935. }
  1936. }
  1937. /**
  1938. * 删除变更立项
  1939. * @param {Object} ctx - egg全局变量
  1940. * @return {void}
  1941. */
  1942. async projectDelete(ctx) {
  1943. try {
  1944. const result = await ctx.service.changeProject.delete(ctx.request.body.cpid);
  1945. if (!result) {
  1946. throw '删除变更立项失败';
  1947. }
  1948. ctx.redirect(ctx.request.header.referer);
  1949. } catch (err) {
  1950. console.log(err);
  1951. ctx.redirect(ctx.request.header.referer);
  1952. }
  1953. }
  1954. /**
  1955. * 变更管理 状态筛选 页面 (Get)
  1956. * @param {Object} ctx - egg全局变量
  1957. * @return {void}
  1958. */
  1959. async projectStatus(ctx) {
  1960. try {
  1961. const status = parseInt(ctx.params.status);
  1962. await this._filterChangesProject(ctx, status);
  1963. } catch (err) {
  1964. this.logger.error(err);
  1965. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  1966. }
  1967. }
  1968. /**
  1969. * 获取审批界面所需的 原报、审批人数据等
  1970. * @param ctx
  1971. * @return {Promise<void>}
  1972. * @private
  1973. */
  1974. async _getChangeProjectAuditViewData(ctx) {
  1975. const auditConst = audit.changeProject;
  1976. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  1977. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  1978. ctx.change.auditHistory = [];
  1979. if (times >= 1) {
  1980. for (let i = 1; i <= times; i++) {
  1981. ctx.change.auditHistory.push(await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, i));
  1982. }
  1983. }
  1984. // 获取审批流程中左边列表
  1985. ctx.change.auditors2 = ctx.change.status === auditConst.status.back && ctx.change.uid !== ctx.session.sessionUser.accountId ?
  1986. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times) :
  1987. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  1988. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.back) {
  1989. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  1990. }
  1991. ctx.change.xsAuditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  1992. }
  1993. // 变更类别获取及更新
  1994. async _getOrUpdateClass(ctx, serviceName) {
  1995. // 工程变更类别读取
  1996. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  1997. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  1998. if (ctx.change.status === audit[serviceName].status.uncheck ||
  1999. (serviceName === 'changeProject' && ctx.change.status === audit[serviceName].status.back) ||
  2000. (serviceName !== 'changeProject' && ctx.change.status === audit[serviceName].status.checkNo)) {
  2001. const classInfo = ctx.helper._.find(fun_set.change_class, function(item) {
  2002. return item.checked && (item.name === ctx.change.class || item.new_name === ctx.change.class);
  2003. });
  2004. if (!classInfo) {
  2005. const classInfo2 = ctx.helper._.find(fun_set.change_class, { checked: true });
  2006. ctx.change.class = classInfo2.new_name ? classInfo2.new_name : classInfo2.name;
  2007. await ctx.service[serviceName].defaultUpdate({
  2008. id: ctx.change.id,
  2009. class: ctx.change.class,
  2010. });
  2011. } else if (classInfo && classInfo.new_name && ctx.change.class !== classInfo.new_name) {
  2012. ctx.change.class = classInfo.new_name;
  2013. await ctx.service[serviceName].defaultUpdate({
  2014. id: ctx.change.id,
  2015. class: ctx.change.class,
  2016. });
  2017. }
  2018. }
  2019. return fun_set.change_class;
  2020. }
  2021. async projectInformation(ctx) {
  2022. try {
  2023. const whiteList = this.ctx.app.config.multipart.whitelist;
  2024. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2025. // 获取附件列表
  2026. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2027. await this._getChangeProjectAuditViewData(ctx);
  2028. const changeClass = await this._getOrUpdateClass(ctx, 'changeProject');
  2029. // 判断并更新
  2030. const renderData = {
  2031. tender,
  2032. change: ctx.change,
  2033. changeConst,
  2034. changeClass,
  2035. auditConst: audit.changeProject,
  2036. fileList,
  2037. whiteList,
  2038. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/project') ? ctx.request.headers.referer : null,
  2039. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project_information),
  2040. preUrl: '/tender/' + ctx.tender.id + '/change/project/' + ctx.change.id + '/information',
  2041. };
  2042. // if ((ctx.change.status === audit.changeProject.status.uncheck || ctx.change.status === audit.changeProject.status.back) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  2043. // data.accountGroup = accountGroup;
  2044. // 获取所有项目参与者
  2045. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  2046. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  2047. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  2048. });
  2049. renderData.accountList = accountList;
  2050. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  2051. renderData.accountGroup = unitList.map(item => {
  2052. const groupList = accountList.filter(item1 => item1.company === item.name);
  2053. return { groupName: item.name, groupList };
  2054. });
  2055. // }
  2056. await this.layout('change/project_information.ejs', renderData, 'change/project_information_modal.ejs');
  2057. } catch (err) {
  2058. this.log(err);
  2059. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2060. }
  2061. }
  2062. // 审批相关
  2063. /**
  2064. * 添加审批人
  2065. * @param ctx
  2066. * @return {Promise<void>}
  2067. */
  2068. async addProjectAudit(ctx) {
  2069. try {
  2070. const auditConst = audit.changeProject;
  2071. const data = JSON.parse(ctx.request.body.data);
  2072. const id = this.app._.toInteger(data.auditorId);
  2073. if (isNaN(id) || id <= 0) {
  2074. throw '参数错误';
  2075. }
  2076. // 检查权限等
  2077. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2078. throw '您无权添加审核人';
  2079. }
  2080. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2081. throw '当前不允许添加审核人';
  2082. }
  2083. // 判断是否是协审人,是则无法添加到审批人中
  2084. const xsAuditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2085. const xsAidList = this.app._.map(xsAuditorList, 'aid');
  2086. if (this.app._.indexOf(xsAidList, id) !== -1) {
  2087. throw '该用户已添加到协审人列表中,请删除该协审人再添加';
  2088. }
  2089. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2090. // 检查审核人是否已存在
  2091. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2092. if (exist) {
  2093. throw '该审核人已存在,请勿重复添加';
  2094. }
  2095. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  2096. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  2097. const result = await ctx.service.changeProjectAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  2098. if (!result) {
  2099. throw '添加审核人失败';
  2100. }
  2101. const auditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2102. ctx.body = { err: 0, msg: '', data: auditors };
  2103. } catch (err) {
  2104. this.log(err);
  2105. ctx.body = { err: 1, msg: err.toString(), data: null };
  2106. }
  2107. }
  2108. /**
  2109. * 移除审批人
  2110. * @param ctx
  2111. * @return {Promise<void>}
  2112. */
  2113. async deleteProjectAudit(ctx) {
  2114. try {
  2115. const data = JSON.parse(ctx.request.body.data);
  2116. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2117. if (isNaN(id) || id <= 0) {
  2118. throw '参数错误';
  2119. }
  2120. const result = await ctx.service.changeProjectAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2121. if (!result) {
  2122. throw '移除审核人失败';
  2123. }
  2124. const auditors = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2125. ctx.body = { err: 0, msg: '', data: auditors };
  2126. } catch (err) {
  2127. ctx.body = { err: 1, msg: err.toString(), data: null };
  2128. }
  2129. }
  2130. /**
  2131. * 添加协审人
  2132. * @param ctx
  2133. * @return {Promise<void>}
  2134. */
  2135. async addProjectXsAudit(ctx) {
  2136. try {
  2137. const auditConst = audit.changeProject;
  2138. const data = JSON.parse(ctx.request.body.data);
  2139. const id = this.app._.toInteger(data.auditorId);
  2140. if (isNaN(id) || id <= 0) {
  2141. throw '参数错误';
  2142. }
  2143. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  2144. const spAuditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times);
  2145. const aidLists = this.app._.map(spAuditors, 'aid');
  2146. // 检查权限等
  2147. if (this.app._.indexOf(aidLists, ctx.session.sessionUser.accountId) === -1) {
  2148. throw '您无权添加协审人';
  2149. }
  2150. // 如果已经是审批人则无法添加此人为协审
  2151. if (this.app._.indexOf(aidLists, id) !== -1) {
  2152. throw '该用户为审批人或原报,无需添加至协审人';
  2153. }
  2154. const auditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2155. // 检查审核人是否已存在
  2156. const exist = this.app._.find(auditorList, { aid: id });
  2157. if (exist) {
  2158. throw '该协审人已存在,请勿重复添加';
  2159. }
  2160. const result = await ctx.service.changeProjectXsAudit.addAuditor(ctx.change.id, id);
  2161. if (!result) {
  2162. throw '添加协审人失败';
  2163. }
  2164. const auditors = await ctx.service.changeProjectXsAudit.getOneAudit(ctx.change.id, id);
  2165. ctx.body = { err: 0, msg: '', data: auditors };
  2166. } catch (err) {
  2167. this.log(err);
  2168. ctx.body = { err: 1, msg: err.toString(), data: null };
  2169. }
  2170. }
  2171. /**
  2172. * 移除协审人
  2173. * @param ctx
  2174. * @return {Promise<void>}
  2175. */
  2176. async deleteProjectXsAudit(ctx) {
  2177. try {
  2178. const data = JSON.parse(ctx.request.body.data);
  2179. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2180. if (isNaN(id) || id <= 0) {
  2181. throw '参数错误';
  2182. }
  2183. const result = await ctx.service.changeProjectXsAudit.deleteAuditor(ctx.change.id, id);
  2184. if (!result) {
  2185. throw '移除协审人失败';
  2186. }
  2187. const auditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2188. ctx.body = { err: 0, msg: '', data: auditors };
  2189. } catch (err) {
  2190. ctx.body = { err: 1, msg: err.toString(), data: null };
  2191. }
  2192. }
  2193. /**
  2194. * 上传附件
  2195. * @param {*} ctx 上下文
  2196. */
  2197. async uploadProjectFile(ctx) {
  2198. let stream;
  2199. try {
  2200. const auditConst = audit.changeProject;
  2201. // this._checkAdvanceFileCanModify(ctx);
  2202. const parts = this.ctx.multipart({
  2203. autoFields: true,
  2204. });
  2205. const files = [];
  2206. const create_time = Date.parse(new Date()) / 1000;
  2207. let idx = 0;
  2208. const extra_upload = ctx.change.status === auditConst.status.checked;
  2209. while ((stream = await parts()) !== undefined) {
  2210. if (!stream.filename) {
  2211. // 如果没有传入直接返回
  2212. return;
  2213. }
  2214. const fileInfo = path.parse(stream.filename);
  2215. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_project/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2216. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2217. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2218. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2219. ++idx;
  2220. stream && (await sendToWormhole(stream));
  2221. }
  2222. const in_time = new Date();
  2223. const payload = files.map(file => {
  2224. let idx;
  2225. if (Array.isArray(parts.field.name)) {
  2226. idx = parts.field.name.findIndex(name => name === file.name);
  2227. } else {
  2228. idx = 'isString';
  2229. }
  2230. const newFile = {
  2231. tid: ctx.tender.id,
  2232. cpid: ctx.change.id,
  2233. uid: ctx.session.sessionUser.accountId,
  2234. filename: file.name,
  2235. fileext: file.ext,
  2236. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2237. filepath: file.filepath,
  2238. upload_time: in_time,
  2239. extra_upload,
  2240. };
  2241. return newFile;
  2242. });
  2243. // 执行文件信息写入数据库
  2244. await ctx.service.changeProjectAtt.saveFileMsgToDb(payload);
  2245. // 将最新的当前标段的所有文件信息返回
  2246. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2247. ctx.body = { err: 0, msg: '', data };
  2248. } catch (err) {
  2249. stream && (await sendToWormhole(stream));
  2250. this.log(err);
  2251. ctx.body = { err: 1, msg: err.toString(), data: null };
  2252. }
  2253. }
  2254. /**
  2255. * 删除附件
  2256. * @param {Ojbect} ctx 上下文
  2257. */
  2258. async deleteProjectFile(ctx) {
  2259. try {
  2260. const { id } = JSON.parse(ctx.request.body.data);
  2261. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2262. if (fileInfo || Object.keys(fileInfo).length) {
  2263. // 先删除文件
  2264. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2265. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2266. // 再删除数据库
  2267. await ctx.service.changeProjectAtt.delete(id);
  2268. } else {
  2269. throw '不存在该文件';
  2270. }
  2271. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2272. ctx.body = { err: 0, msg: '请求成功', data };
  2273. } catch (err) {
  2274. this.log(err);
  2275. ctx.body = { err: 1, msg: err.toString(), data: null };
  2276. }
  2277. }
  2278. /**
  2279. * 下载附件
  2280. * @param {Object} ctx - egg全局变量
  2281. * @return {void}
  2282. */
  2283. async downloadProjectFile(ctx) {
  2284. const id = ctx.params.fid;
  2285. if (id) {
  2286. try {
  2287. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2288. if (fileInfo !== undefined && fileInfo !== '') {
  2289. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2290. // 解决中文无法下载问题
  2291. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2292. let disposition = '';
  2293. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2294. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2295. } else if (userAgent.indexOf('firefox') >= 0) {
  2296. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2297. } else {
  2298. /* safari等其他非主流浏览器只能自求多福了 */
  2299. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2300. }
  2301. ctx.response.set({
  2302. 'Content-Type': 'application/octet-stream',
  2303. 'Content-Disposition': disposition,
  2304. 'Content-Length': fileInfo.filesize,
  2305. });
  2306. // ctx.body = await fs.createReadStream(fileName);
  2307. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2308. } else {
  2309. throw '不存在该文件';
  2310. }
  2311. } catch (err) {
  2312. this.log(err);
  2313. this.setMessage(err.toString(), this.messageType.ERROR);
  2314. }
  2315. }
  2316. }
  2317. async projectInformationSave(ctx) {
  2318. try {
  2319. const data = JSON.parse(ctx.request.body.data);
  2320. if (data.name === 'code') {
  2321. const info = await ctx.service.changeProject.isRepeat(ctx.change.id, data.val, ctx.tender.id, ctx.change.type);
  2322. if (info) {
  2323. throw '该编号已存在';
  2324. }
  2325. }
  2326. const result = await ctx.service.changeProject.saveInfo(ctx.change.id, data);
  2327. if (!result) {
  2328. throw '修改失败';
  2329. }
  2330. ctx.body = { err: 0, msg: '请求成功', data: null };
  2331. } catch (err) {
  2332. this.log(err);
  2333. ctx.body = { err: 1, msg: err.toString(), data: null };
  2334. }
  2335. }
  2336. /**
  2337. * 上报和重新上报
  2338. * @param ctx
  2339. * @return {Promise<void>}
  2340. */
  2341. async startProjectAudit(ctx) {
  2342. try {
  2343. const auditConst = audit.changeProject;
  2344. // 检查权限等
  2345. if (!ctx.change) {
  2346. throw '数据错误';
  2347. }
  2348. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2349. throw '您无权上报该期数据';
  2350. }
  2351. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2352. throw '该材料调差期数据当前无法上报';
  2353. }
  2354. await ctx.service.changeProjectAudit.start(ctx.change.id, ctx.change.times);
  2355. ctx.redirect(ctx.request.header.referer);
  2356. } catch (err) {
  2357. this.log(err);
  2358. ctx.session.postError = err.toString();
  2359. ctx.redirect(ctx.request.header.referer);
  2360. }
  2361. }
  2362. /**
  2363. * 审批
  2364. * @param ctx
  2365. * @return {Promise<void>}
  2366. */
  2367. async checkProjectAudit(ctx) {
  2368. try {
  2369. const auditConst = audit.changeProject;
  2370. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2371. throw '当前材料调差期数据有误';
  2372. }
  2373. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  2374. throw '您无权进行该操作';
  2375. }
  2376. const data = {
  2377. checkType: parseInt(ctx.request.body.checkType),
  2378. opinion: ctx.request.body.opinion,
  2379. };
  2380. if (!data.checkType || isNaN(data.checkType)) {
  2381. throw '提交数据错误';
  2382. }
  2383. // if (data.checkType === auditConst.status.checkNo) {
  2384. // if (!data.checkType || isNaN(data.checkType)) {
  2385. // throw '提交数据错误';
  2386. // }
  2387. // }
  2388. await ctx.service.changeProjectAudit.check(ctx.change.id, data, ctx.change.times);
  2389. ctx.redirect(ctx.request.header.referer);
  2390. } catch (err) {
  2391. this.log(err);
  2392. ctx.session.postError = err.toString();
  2393. ctx.redirect(ctx.request.header.referer);
  2394. }
  2395. }
  2396. async _filterChangesApply(ctx, status = 0) {
  2397. const tenderId = ctx.params.id;
  2398. ctx.session.sessionUser.tenderId = tenderId;
  2399. const tender = await this.service.tender.getDataById(ctx.tender.id);
  2400. // const tender = ctx.tender;
  2401. // const tenderList = await this.service.tender.getList();
  2402. const page = ctx.page;
  2403. const pageSize = ctx.pageSize;
  2404. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  2405. const orders = ctx.query.order ? ctx.query.order : 0;
  2406. const changes = await ctx.service.changeApply.getListByStatus(tender.id, status, 1, sorts, orders);
  2407. const total = await ctx.service.changeApply.getCountByStatus(tender.id, status);
  2408. let page_total = 0;
  2409. const tp = await ctx.service.changeApply.getTp(tender.id, status);
  2410. for (const c of changes) {
  2411. c.curAuditor = await ctx.service.changeApplyAudit.getAuditorByStatus(c.id, c.status, c.times);
  2412. page_total = ctx.helper.add(page_total, c.total_price);
  2413. }
  2414. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  2415. // 分页相关
  2416. const pageInfo = {
  2417. page,
  2418. pageSizeSelect: 1,
  2419. pageSize,
  2420. total_num: total,
  2421. total: Math.ceil(total / pageSize),
  2422. queryData: JSON.stringify(ctx.urlInfo.query),
  2423. };
  2424. const filter = JSON.parse(JSON.stringify(audit.changeApply.filter));
  2425. filter.count = [];
  2426. filter.count[filter.status.pending] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2427. filter.count[filter.status.uncheck] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  2428. filter.count[filter.status.checking] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  2429. filter.count[filter.status.checked] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2430. // filter.count[filter.status.checkNo] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2431. let codeRule = [];
  2432. let c_connector = '1';
  2433. let c_rule_first = 1;
  2434. const rule_type = 'apply';
  2435. if (tender.c_code_rules) {
  2436. const c_code_rules = JSON.parse(tender.c_code_rules);
  2437. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  2438. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  2439. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  2440. }
  2441. for (const rule of codeRule) {
  2442. switch (rule.rule_type) {
  2443. case codeRuleConst.measure.ruleType.dealCode:
  2444. rule.preview = ctx.tender.info.deal_info.dealCode;
  2445. break;
  2446. case codeRuleConst.measure.ruleType.tenderName:
  2447. rule.preview = tender.name;
  2448. break;
  2449. case codeRuleConst.measure.ruleType.inDate:
  2450. rule.preview = moment().format('YYYY');
  2451. break;
  2452. case codeRuleConst.measure.ruleType.text:
  2453. rule.preview = rule.text;
  2454. break;
  2455. case codeRuleConst.measure.ruleType.addNo:
  2456. const s = '0000000000';
  2457. rule.preview = s.substr(s.length - rule.format);
  2458. break;
  2459. default: break;
  2460. }
  2461. }
  2462. const changeProjectList = await ctx.service.changeProject.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeProject.status.checked } });
  2463. const allProjectCodes = await ctx.service.changeApply.getAllDataByCondition({
  2464. columns: ['project_code'],
  2465. where: {
  2466. tid: tender.id,
  2467. },
  2468. });
  2469. const pcLists = allProjectCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allProjectCodes, 'project_code')) : [];
  2470. const renderData = {
  2471. uid: ctx.session.sessionUser.accountId,
  2472. tender,
  2473. pageInfo,
  2474. changes,
  2475. status,
  2476. rule_type,
  2477. codeRule,
  2478. c_connector,
  2479. c_rule_first,
  2480. filter,
  2481. apply_username: tender_userInfo ? tender_userInfo.name : null,
  2482. ruleType: codeRuleConst.ruleType[rule_type],
  2483. dealCode: ctx.tender.info.deal_info.dealCode,
  2484. auditConst: audit.changeApply,
  2485. ruleConst: codeRuleConst.measure,
  2486. changeConst,
  2487. changeProjectList,
  2488. pcLists,
  2489. tp,
  2490. page_total,
  2491. tenderMenu: this.menu.tenderMenu,
  2492. preUrl: '/tender/' + tender.id,
  2493. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply),
  2494. };
  2495. await this.layout('change/apply.ejs', renderData, 'change/apply_modal.ejs');
  2496. }
  2497. /**
  2498. * 变更申请列表 页面 (Get)
  2499. *
  2500. * @param {Object} ctx - egg全局变量
  2501. * @return {void}
  2502. */
  2503. async apply(ctx) {
  2504. try {
  2505. await this._filterChangesApply(ctx);
  2506. } catch (err) {
  2507. this.log(err);
  2508. ctx.redirect('/dashboard');
  2509. }
  2510. }
  2511. /**
  2512. * 变更管理 状态筛选 页面 (Get)
  2513. * @param {Object} ctx - egg全局变量
  2514. * @return {void}
  2515. */
  2516. async applyStatus(ctx) {
  2517. try {
  2518. const status = parseInt(ctx.params.status);
  2519. await this._filterChangesApply(ctx, status);
  2520. } catch (err) {
  2521. this.logger.error(err);
  2522. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2523. }
  2524. }
  2525. /**
  2526. * 新增变更立项 (Post)
  2527. *
  2528. * @param {Object} ctx - egg全局变量
  2529. * @return {void}
  2530. */
  2531. async applyAdd(ctx) {
  2532. try {
  2533. const tenderId = ctx.params.id;
  2534. if (!tenderId) {
  2535. throw '当前未打开标段';
  2536. }
  2537. const data = JSON.parse(ctx.request.body.data);
  2538. if (!data.code || data.code === '') {
  2539. throw '变更申请编号不能为空';
  2540. }
  2541. const change = await ctx.service.changeApply.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.project_code, data.name);
  2542. ctx.body = { err: 0, msg: '', data: change };
  2543. } catch (err) {
  2544. this.log(err);
  2545. ctx.body = { err: 1, msg: err.toString() };
  2546. }
  2547. }
  2548. /**
  2549. * 删除变更立项
  2550. * @param {Object} ctx - egg全局变量
  2551. * @return {void}
  2552. */
  2553. async applyDelete(ctx) {
  2554. try {
  2555. const result = await ctx.service.changeApply.delete(ctx.request.body.caid);
  2556. if (!result) {
  2557. throw '删除变更立项失败';
  2558. }
  2559. ctx.redirect(ctx.request.header.referer);
  2560. } catch (err) {
  2561. console.log(err);
  2562. ctx.redirect(ctx.request.header.referer);
  2563. }
  2564. }
  2565. /**
  2566. * 获取审批界面所需的 原报、审批人数据等
  2567. * @param ctx
  2568. * @return {Promise<void>}
  2569. * @private
  2570. */
  2571. async _getChangeApplyAuditViewData(ctx) {
  2572. const auditConst = audit.changeApply;
  2573. const times = ctx.change.status === auditConst.status.checkNo ? ctx.change.times - 1 : ctx.change.times;
  2574. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  2575. ctx.change.auditHistory = [];
  2576. if (times >= 1) {
  2577. for (let i = 1; i <= times; i++) {
  2578. ctx.change.auditHistory.push(await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, i));
  2579. }
  2580. }
  2581. // 获取审批流程中左边列表
  2582. ctx.change.auditors2 = ctx.change.status === auditConst.status.checkNo && ctx.change.uid !== ctx.session.sessionUser.accountId ?
  2583. await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, times) :
  2584. await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2585. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.checkNo) {
  2586. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2587. }
  2588. }
  2589. async applyInformation(ctx) {
  2590. try {
  2591. const whiteList = this.ctx.app.config.multipart.whitelist;
  2592. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2593. await this._getChangeApplyAuditViewData(ctx);
  2594. // 获取清单列表
  2595. const changeList = await ctx.service.changeApplyList.getList(ctx.change.id);
  2596. // 获取附件列表
  2597. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2598. const changeClass = await this._getOrUpdateClass(ctx, 'changeApply');
  2599. const renderData = {
  2600. tender,
  2601. change: ctx.change,
  2602. listRule: tender.c_apply_list_rule ? JSON.parse(tender.c_apply_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  2603. changeList,
  2604. changeConst,
  2605. changeClass,
  2606. auditConst: audit.changeApply,
  2607. fileList,
  2608. whiteList,
  2609. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  2610. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  2611. changeUnits: changeConst.units,
  2612. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  2613. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') && !this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information') ? ctx.request.headers.referer : null,
  2614. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information),
  2615. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information',
  2616. };
  2617. if ((ctx.change.status === audit.changeApply.status.uncheck || ctx.change.status === audit.changeApply.status.checkNo) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  2618. // data.accountGroup = accountGroup;
  2619. // 获取所有项目参与者
  2620. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  2621. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  2622. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  2623. });
  2624. renderData.accountList = accountList;
  2625. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  2626. renderData.accountGroup = unitList.map(item => {
  2627. const groupList = accountList.filter(item1 => item1.company === item.name);
  2628. return { groupName: item.name, groupList };
  2629. });
  2630. }
  2631. await this.layout('change/apply_information.ejs', renderData, 'change/apply_information_modal.ejs');
  2632. } catch (err) {
  2633. this.log(err);
  2634. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2635. }
  2636. }
  2637. async applyInformationNotice(ctx) {
  2638. try {
  2639. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2640. // 获取附件列表
  2641. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2642. await this._getChangeApplyAuditViewData(ctx);
  2643. const renderData = {
  2644. tender,
  2645. change: ctx.change,
  2646. changeConst,
  2647. auditConst: audit.changeApply,
  2648. fileList,
  2649. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') ? ctx.request.headers.referer : null,
  2650. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information_notice),
  2651. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information/notice',
  2652. };
  2653. await this.layout('change/apply_information_notice.ejs', renderData, 'change/apply_information_notice_modal.ejs');
  2654. } catch (err) {
  2655. this.log(err);
  2656. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2657. }
  2658. }
  2659. // 审批相关
  2660. /**
  2661. * 添加审批人
  2662. * @param ctx
  2663. * @return {Promise<void>}
  2664. */
  2665. async addApplyAudit(ctx) {
  2666. try {
  2667. const auditConst = audit.changeApply;
  2668. const data = JSON.parse(ctx.request.body.data);
  2669. const id = this.app._.toInteger(data.auditorId);
  2670. if (isNaN(id) || id <= 0) {
  2671. throw '参数错误';
  2672. }
  2673. // 检查权限等
  2674. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2675. throw '您无权添加审核人';
  2676. }
  2677. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2678. throw '当前不允许添加审核人';
  2679. }
  2680. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2681. // 检查审核人是否已存在
  2682. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2683. if (exist) {
  2684. throw '该审核人已存在,请勿重复添加';
  2685. }
  2686. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  2687. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  2688. const result = await ctx.service.changeApplyAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  2689. if (!result) {
  2690. throw '添加审核人失败';
  2691. }
  2692. const auditors = await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2693. ctx.body = { err: 0, msg: '', data: auditors };
  2694. } catch (err) {
  2695. this.log(err);
  2696. ctx.body = { err: 1, msg: err.toString(), data: null };
  2697. }
  2698. }
  2699. /**
  2700. * 移除审批人
  2701. * @param ctx
  2702. * @return {Promise<void>}
  2703. */
  2704. async deleteApplyAudit(ctx) {
  2705. try {
  2706. const data = JSON.parse(ctx.request.body.data);
  2707. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2708. if (isNaN(id) || id <= 0) {
  2709. throw '参数错误';
  2710. }
  2711. const result = await ctx.service.changeApplyAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2712. if (!result) {
  2713. throw '移除审核人失败';
  2714. }
  2715. const auditors = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2716. ctx.body = { err: 0, msg: '', data: auditors };
  2717. } catch (err) {
  2718. ctx.body = { err: 1, msg: err.toString(), data: null };
  2719. }
  2720. }
  2721. /**
  2722. * 上传附件
  2723. * @param {*} ctx 上下文
  2724. */
  2725. async uploadApplyFile(ctx) {
  2726. let stream;
  2727. try {
  2728. const auditConst = audit.changeApply;
  2729. // this._checkAdvanceFileCanModify(ctx);
  2730. const parts = this.ctx.multipart({
  2731. autoFields: true,
  2732. });
  2733. const files = [];
  2734. const create_time = Date.parse(new Date()) / 1000;
  2735. let idx = 0;
  2736. const extra_upload = ctx.change.status === auditConst.status.checked;
  2737. while ((stream = await parts()) !== undefined) {
  2738. if (!stream.filename) {
  2739. // 如果没有传入直接返回
  2740. return;
  2741. }
  2742. const fileInfo = path.parse(stream.filename);
  2743. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_apply/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2744. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2745. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2746. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2747. ++idx;
  2748. stream && (await sendToWormhole(stream));
  2749. }
  2750. const in_time = new Date();
  2751. const payload = files.map(file => {
  2752. let idx;
  2753. if (Array.isArray(parts.field.name)) {
  2754. idx = parts.field.name.findIndex(name => name === file.name);
  2755. } else {
  2756. idx = 'isString';
  2757. }
  2758. const newFile = {
  2759. tid: ctx.tender.id,
  2760. caid: ctx.change.id,
  2761. uid: ctx.session.sessionUser.accountId,
  2762. type: parts.field.type,
  2763. filename: file.name,
  2764. fileext: file.ext,
  2765. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2766. filepath: file.filepath,
  2767. upload_time: in_time,
  2768. extra_upload,
  2769. };
  2770. return newFile;
  2771. });
  2772. // 执行文件信息写入数据库
  2773. await ctx.service.changeApplyAtt.saveFileMsgToDb(payload);
  2774. // 将最新的当前标段的所有文件信息返回
  2775. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2776. ctx.body = { err: 0, msg: '', data };
  2777. } catch (err) {
  2778. stream && (await sendToWormhole(stream));
  2779. this.log(err);
  2780. ctx.body = { err: 1, msg: err.toString(), data: null };
  2781. }
  2782. }
  2783. /**
  2784. * 删除附件
  2785. * @param {Ojbect} ctx 上下文
  2786. */
  2787. async deleteApplyFile(ctx) {
  2788. try {
  2789. const { id } = JSON.parse(ctx.request.body.data);
  2790. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2791. if (fileInfo || Object.keys(fileInfo).length) {
  2792. // 先删除文件
  2793. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2794. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2795. // 再删除数据库
  2796. await ctx.service.changeApplyAtt.delete(id);
  2797. } else {
  2798. throw '不存在该文件';
  2799. }
  2800. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2801. ctx.body = { err: 0, msg: '请求成功', data };
  2802. } catch (err) {
  2803. this.log(err);
  2804. ctx.body = { err: 1, msg: err.toString(), data: null };
  2805. }
  2806. }
  2807. /**
  2808. * 下载附件
  2809. * @param {Object} ctx - egg全局变量
  2810. * @return {void}
  2811. */
  2812. async downloadApplyFile(ctx) {
  2813. const id = ctx.params.fid;
  2814. if (id) {
  2815. try {
  2816. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2817. if (fileInfo !== undefined && fileInfo !== '') {
  2818. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2819. // 解决中文无法下载问题
  2820. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2821. let disposition = '';
  2822. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2823. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2824. } else if (userAgent.indexOf('firefox') >= 0) {
  2825. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2826. } else {
  2827. /* safari等其他非主流浏览器只能自求多福了 */
  2828. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2829. }
  2830. ctx.response.set({
  2831. 'Content-Type': 'application/octet-stream',
  2832. 'Content-Disposition': disposition,
  2833. 'Content-Length': fileInfo.filesize,
  2834. });
  2835. // ctx.body = await fs.createReadStream(fileName);
  2836. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2837. } else {
  2838. throw '不存在该文件';
  2839. }
  2840. } catch (err) {
  2841. this.log(err);
  2842. this.setMessage(err.toString(), this.messageType.ERROR);
  2843. }
  2844. }
  2845. }
  2846. async applyInformationSave(ctx) {
  2847. try {
  2848. const data = JSON.parse(ctx.request.body.data);
  2849. if (data.name === 'code') {
  2850. const info = await ctx.service.changeApply.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  2851. if (info) {
  2852. throw '该编号已存在';
  2853. }
  2854. }
  2855. const result = await ctx.service.changeApply.saveInfo(ctx.change.id, data);
  2856. if (!result) {
  2857. throw '修改失败';
  2858. }
  2859. ctx.body = { err: 0, msg: '请求成功', data: null };
  2860. } catch (err) {
  2861. this.log(err);
  2862. ctx.body = { err: 1, msg: err.toString(), data: null };
  2863. }
  2864. }
  2865. /**
  2866. * 上报和重新上报
  2867. * @param ctx
  2868. * @return {Promise<void>}
  2869. */
  2870. async startApplyAudit(ctx) {
  2871. try {
  2872. const auditConst = audit.changeApply;
  2873. // 检查权限等
  2874. if (!ctx.change) {
  2875. throw '数据错误';
  2876. }
  2877. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2878. throw '您无权上报该期数据';
  2879. }
  2880. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2881. throw '该材料调差期数据当前无法上报';
  2882. }
  2883. await ctx.service.changeApplyAudit.start(ctx.change.id, ctx.change.times);
  2884. ctx.redirect(ctx.request.header.referer);
  2885. } catch (err) {
  2886. this.log(err);
  2887. ctx.session.postError = err.toString();
  2888. ctx.redirect(ctx.request.header.referer);
  2889. }
  2890. }
  2891. /**
  2892. * 审批
  2893. * @param ctx
  2894. * @return {Promise<void>}
  2895. */
  2896. async checkApplyAudit(ctx) {
  2897. try {
  2898. const auditConst = audit.changeApply;
  2899. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2900. throw '当前材料调差期数据有误';
  2901. }
  2902. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  2903. throw '您无权进行该操作';
  2904. }
  2905. const data = {
  2906. checkType: parseInt(ctx.request.body.checkType),
  2907. opinion: ctx.request.body.opinion,
  2908. };
  2909. if (!data.checkType || isNaN(data.checkType)) {
  2910. throw '提交数据错误';
  2911. }
  2912. if (ctx.request.body.notice_uid) {
  2913. data.notice_code = ctx.request.body.notice_code;
  2914. data.notice_uid = ctx.request.body.notice_uid;
  2915. }
  2916. // if (data.checkType === auditConst.status.checkNo) {
  2917. // if (!data.checkType || isNaN(data.checkType)) {
  2918. // throw '提交数据错误';
  2919. // }
  2920. // }
  2921. await ctx.service.changeApplyAudit.check(ctx.change.id, data, ctx.change.times);
  2922. ctx.redirect(ctx.request.header.referer);
  2923. } catch (err) {
  2924. this.log(err);
  2925. ctx.session.postError = err.toString();
  2926. ctx.redirect(ctx.request.header.referer);
  2927. }
  2928. }
  2929. /**
  2930. * 变更清单 - 操作 (Ajax)
  2931. * @param ctx
  2932. * @return {Promise<void>}
  2933. */
  2934. async saveApplyListsData(ctx) {
  2935. try {
  2936. const data = JSON.parse(ctx.request.body.data);
  2937. const responseData = {
  2938. err: 0,
  2939. msg: '',
  2940. data: {},
  2941. };
  2942. switch (data.type) {
  2943. case 'add':
  2944. responseData.data = await ctx.service.changeApplyList.add(data.updateData);
  2945. break;
  2946. case 'batchadd':
  2947. responseData.data = await ctx.service.changeApplyList.batchAdd(data);
  2948. break;
  2949. case 'del':
  2950. await ctx.service.changeApplyList.del(data.ids);
  2951. // 取所有工料表
  2952. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  2953. break;
  2954. case 'update':
  2955. // if (data.updateData.code === '' || data.updateData.code === null) {
  2956. // throw '请先输入编号';
  2957. // }
  2958. await ctx.service.changeApplyList.save(data.updateData);
  2959. break;
  2960. case 'paste':
  2961. await ctx.service.changeApplyList.saveDatas(data.updateData);
  2962. // 取所有工料表
  2963. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  2964. break;
  2965. case 'list_rule':
  2966. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_apply_list_rule: data.postData });
  2967. if (!result) {
  2968. throw '修改失败';
  2969. }
  2970. break;
  2971. // case 'update_tp':
  2972. // await ctx.service.changeApply.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  2973. // break;
  2974. default: throw '参数有误';
  2975. }
  2976. ctx.body = responseData;
  2977. } catch (err) {
  2978. this.log(err);
  2979. ctx.body = { err: 1, msg: err.toString(), data: null };
  2980. }
  2981. }
  2982. // 变更方案
  2983. async _filterChangesPlan(ctx, status = 0) {
  2984. const tenderId = ctx.params.id;
  2985. ctx.session.sessionUser.tenderId = tenderId;
  2986. const tender = await this.service.tender.getDataById(ctx.tender.id);
  2987. // const tender = ctx.tender;
  2988. // const tenderList = await this.service.tender.getList();
  2989. const page = ctx.page;
  2990. const pageSize = ctx.pageSize;
  2991. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  2992. const orders = ctx.query.order ? ctx.query.order : 0;
  2993. const changes = await ctx.service.changePlan.getListByStatus(tender.id, status, 1, sorts, orders);
  2994. const total = await ctx.service.changePlan.getCountByStatus(tender.id, status);
  2995. let page_total = 0;
  2996. const tp = await ctx.service.changePlan.getTp(tender.id, status);
  2997. for (const c of changes) {
  2998. c.curAuditor = await ctx.service.changePlanAudit.getAuditorByStatus(c.id, c.status, c.times);
  2999. page_total = ctx.helper.add(page_total, c.total_price);
  3000. }
  3001. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  3002. // 分页相关
  3003. const pageInfo = {
  3004. page,
  3005. pageSizeSelect: 1,
  3006. pageSize,
  3007. total_num: total,
  3008. total: Math.ceil(total / pageSize),
  3009. queryData: JSON.stringify(ctx.urlInfo.query),
  3010. };
  3011. const filter = JSON.parse(JSON.stringify(audit.changePlan.filter));
  3012. filter.count = [];
  3013. filter.count[filter.status.pending] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  3014. filter.count[filter.status.uncheck] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  3015. filter.count[filter.status.checking] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  3016. filter.count[filter.status.checked] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  3017. // filter.count[filter.status.checkNo] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  3018. let codeRule = [];
  3019. let c_connector = '1';
  3020. let c_rule_first = 1;
  3021. const rule_type = 'plan';
  3022. if (tender.c_code_rules) {
  3023. const c_code_rules = JSON.parse(tender.c_code_rules);
  3024. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  3025. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  3026. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  3027. }
  3028. for (const rule of codeRule) {
  3029. switch (rule.rule_type) {
  3030. case codeRuleConst.measure.ruleType.dealCode:
  3031. rule.preview = ctx.tender.info.deal_info.dealCode;
  3032. break;
  3033. case codeRuleConst.measure.ruleType.tenderName:
  3034. rule.preview = tender.name;
  3035. break;
  3036. case codeRuleConst.measure.ruleType.inDate:
  3037. rule.preview = moment().format('YYYY');
  3038. break;
  3039. case codeRuleConst.measure.ruleType.text:
  3040. rule.preview = rule.text;
  3041. break;
  3042. case codeRuleConst.measure.ruleType.addNo:
  3043. const s = '0000000000';
  3044. rule.preview = s.substr(s.length - rule.format);
  3045. break;
  3046. default: break;
  3047. }
  3048. }
  3049. const changeApplyList = await ctx.service.changeApply.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeApply.status.checked } });
  3050. const allApplyCodes = await ctx.service.changePlan.getAllDataByCondition({
  3051. columns: ['apply_code'],
  3052. where: {
  3053. tid: tender.id,
  3054. },
  3055. });
  3056. const acLists = allApplyCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allApplyCodes, 'apply_code')) : [];
  3057. const renderData = {
  3058. uid: ctx.session.sessionUser.accountId,
  3059. tender,
  3060. pageInfo,
  3061. changes,
  3062. status,
  3063. rule_type,
  3064. codeRule,
  3065. c_connector,
  3066. c_rule_first,
  3067. filter,
  3068. plan_username: tender_userInfo ? tender_userInfo.name : null,
  3069. ruleType: codeRuleConst.ruleType[rule_type],
  3070. dealCode: ctx.tender.info.deal_info.dealCode,
  3071. auditConst: audit.changePlan,
  3072. ruleConst: codeRuleConst.measure,
  3073. changeConst,
  3074. changeApplyList,
  3075. acLists,
  3076. page_total,
  3077. tp,
  3078. tenderMenu: this.menu.tenderMenu,
  3079. preUrl: '/tender/' + tender.id,
  3080. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan),
  3081. };
  3082. await this.layout('change/plan.ejs', renderData, 'change/plan_modal.ejs');
  3083. }
  3084. /**
  3085. * 变更申请列表 页面 (Get)
  3086. *
  3087. * @param {Object} ctx - egg全局变量
  3088. * @return {void}
  3089. */
  3090. async plan(ctx) {
  3091. try {
  3092. await this._filterChangesPlan(ctx);
  3093. } catch (err) {
  3094. this.log(err);
  3095. ctx.redirect('/dashboard');
  3096. }
  3097. }
  3098. /**
  3099. * 变更管理 状态筛选 页面 (Get)
  3100. * @param {Object} ctx - egg全局变量
  3101. * @return {void}
  3102. */
  3103. async planStatus(ctx) {
  3104. try {
  3105. const status = parseInt(ctx.params.status);
  3106. await this._filterChangesPlan(ctx, status);
  3107. } catch (err) {
  3108. this.logger.error(err);
  3109. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3110. }
  3111. }
  3112. /**
  3113. * 新增变更立项 (Post)
  3114. *
  3115. * @param {Object} ctx - egg全局变量
  3116. * @return {void}
  3117. */
  3118. async planAdd(ctx) {
  3119. try {
  3120. const tenderId = ctx.params.id;
  3121. if (!tenderId) {
  3122. throw '当前未打开标段';
  3123. }
  3124. const data = JSON.parse(ctx.request.body.data);
  3125. if (!data.code || data.code === '') {
  3126. throw '变更方案编号不能为空';
  3127. }
  3128. const change = await ctx.service.changePlan.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.apply_code, data.name);
  3129. ctx.body = { err: 0, msg: '', data: change };
  3130. } catch (err) {
  3131. this.log(err);
  3132. ctx.body = { err: 1, msg: err.toString() };
  3133. }
  3134. }
  3135. /**
  3136. * 删除变更立项
  3137. * @param {Object} ctx - egg全局变量
  3138. * @return {void}
  3139. */
  3140. async planDelete(ctx) {
  3141. try {
  3142. const result = await ctx.service.changePlan.delete(ctx.request.body.cpid);
  3143. if (!result) {
  3144. throw '删除变更方案失败';
  3145. }
  3146. ctx.redirect(ctx.request.header.referer);
  3147. } catch (err) {
  3148. console.log(err);
  3149. ctx.redirect(ctx.request.header.referer);
  3150. }
  3151. }
  3152. /**
  3153. * 获取审批界面所需的 原报、审批人数据等
  3154. * @param ctx
  3155. * @return {Promise<void>}
  3156. * @private
  3157. */
  3158. async _getChangePlanAuditViewData(ctx) {
  3159. const auditConst = audit.changePlan;
  3160. const times = ctx.change.status === auditConst.status.checkNo ? ctx.change.times - 1 : ctx.change.times;
  3161. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  3162. ctx.change.auditHistory = [];
  3163. if (times >= 1) {
  3164. for (let i = 1; i <= times; i++) {
  3165. ctx.change.auditHistory.push(await ctx.service.changePlanAudit.getAuditors(ctx.change.id, i));
  3166. }
  3167. }
  3168. // 获取审批流程中左边列表
  3169. ctx.change.auditors2 = ctx.change.status === auditConst.status.checkNo && ctx.change.uid !== ctx.session.sessionUser.accountId ?
  3170. await ctx.service.changePlanAudit.getAuditorsWithOwner(ctx.change.id, times) :
  3171. await ctx.service.changePlanAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  3172. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.checkNo) {
  3173. ctx.change.auditorList = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3174. }
  3175. }
  3176. async planInformation(ctx) {
  3177. try {
  3178. const whiteList = this.ctx.app.config.multipart.whitelist;
  3179. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  3180. await this._getChangePlanAuditViewData(ctx);
  3181. // 获取附件列表
  3182. const fileList = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3183. // 获取清单列表
  3184. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3185. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3186. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3187. ctx.change.listAudits = listAudits;
  3188. for (const cl of changeList) {
  3189. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3190. // 清单表页赋值
  3191. for (const [index, au] of listAudits.entries()) {
  3192. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  3193. }
  3194. }
  3195. }
  3196. const changeClass = await this._getOrUpdateClass(ctx, 'changePlan');
  3197. const renderData = {
  3198. tender,
  3199. change: ctx.change,
  3200. listRule: tender.c_plan_list_rule ? JSON.parse(tender.c_plan_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  3201. changeList,
  3202. changeClass,
  3203. changeConst,
  3204. auditConst: audit.changePlan,
  3205. fileList,
  3206. whiteList,
  3207. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  3208. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  3209. changeUnits: changeConst.units,
  3210. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  3211. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/plan') && !this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information') ? ctx.request.headers.referer : null,
  3212. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan_information),
  3213. preUrl: '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information',
  3214. };
  3215. if ((ctx.change.status === audit.changePlan.status.uncheck || ctx.change.status === audit.changePlan.status.checkNo) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  3216. // data.accountGroup = accountGroup;
  3217. // 获取所有项目参与者
  3218. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  3219. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  3220. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  3221. });
  3222. renderData.accountList = accountList;
  3223. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  3224. renderData.accountGroup = unitList.map(item => {
  3225. const groupList = accountList.filter(item1 => item1.company === item.name);
  3226. return { groupName: item.name, groupList };
  3227. });
  3228. }
  3229. await this.layout('change/plan_information.ejs', renderData, 'change/plan_information_modal.ejs');
  3230. } catch (err) {
  3231. this.log(err);
  3232. ctx.redirect('/tender/' + ctx.params.id + '/change');
  3233. }
  3234. }
  3235. // 审批相关
  3236. /**
  3237. * 添加审批人
  3238. * @param ctx
  3239. * @return {Promise<void>}
  3240. */
  3241. async addPlanAudit(ctx) {
  3242. try {
  3243. const auditConst = audit.changePlan;
  3244. const data = JSON.parse(ctx.request.body.data);
  3245. const id = this.app._.toInteger(data.auditorId);
  3246. if (isNaN(id) || id <= 0) {
  3247. throw '参数错误';
  3248. }
  3249. // 检查权限等
  3250. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3251. throw '您无权添加审核人';
  3252. }
  3253. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3254. throw '当前不允许添加审核人';
  3255. }
  3256. ctx.change.auditorList = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3257. // 检查审核人是否已存在
  3258. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3259. if (exist) {
  3260. throw '该审核人已存在,请勿重复添加';
  3261. }
  3262. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3263. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3264. const result = await ctx.service.changePlanAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3265. if (!result) {
  3266. throw '添加审核人失败';
  3267. }
  3268. const auditors = await ctx.service.changePlanAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  3269. ctx.body = { err: 0, msg: '', data: auditors };
  3270. } catch (err) {
  3271. this.log(err);
  3272. ctx.body = { err: 1, msg: err.toString(), data: null };
  3273. }
  3274. }
  3275. /**
  3276. * 移除审批人
  3277. * @param ctx
  3278. * @return {Promise<void>}
  3279. */
  3280. async deletePlanAudit(ctx) {
  3281. try {
  3282. const data = JSON.parse(ctx.request.body.data);
  3283. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3284. if (isNaN(id) || id <= 0) {
  3285. throw '参数错误';
  3286. }
  3287. const result = await ctx.service.changePlanAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3288. if (!result) {
  3289. throw '移除审核人失败';
  3290. }
  3291. const auditors = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3292. ctx.body = { err: 0, msg: '', data: auditors };
  3293. } catch (err) {
  3294. ctx.body = { err: 1, msg: err.toString(), data: null };
  3295. }
  3296. }
  3297. /**
  3298. * 上传附件
  3299. * @param {*} ctx 上下文
  3300. */
  3301. async uploadPlanFile(ctx) {
  3302. let stream;
  3303. try {
  3304. const auditConst = audit.changePlan;
  3305. // this._checkAdvanceFileCanModify(ctx);
  3306. const parts = this.ctx.multipart({
  3307. autoFields: true,
  3308. });
  3309. const files = [];
  3310. const create_time = Date.parse(new Date()) / 1000;
  3311. let idx = 0;
  3312. const extra_upload = ctx.change.status === auditConst.status.checked;
  3313. while ((stream = await parts()) !== undefined) {
  3314. if (!stream.filename) {
  3315. // 如果没有传入直接返回
  3316. return;
  3317. }
  3318. const fileInfo = path.parse(stream.filename);
  3319. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_plan/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3320. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3321. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3322. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3323. ++idx;
  3324. stream && (await sendToWormhole(stream));
  3325. }
  3326. const in_time = new Date();
  3327. const payload = files.map(file => {
  3328. let idx;
  3329. if (Array.isArray(parts.field.name)) {
  3330. idx = parts.field.name.findIndex(name => name === file.name);
  3331. } else {
  3332. idx = 'isString';
  3333. }
  3334. const newFile = {
  3335. tid: ctx.tender.id,
  3336. cpid: ctx.change.id,
  3337. uid: ctx.session.sessionUser.accountId,
  3338. filename: file.name,
  3339. fileext: file.ext,
  3340. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3341. filepath: file.filepath,
  3342. upload_time: in_time,
  3343. extra_upload,
  3344. };
  3345. return newFile;
  3346. });
  3347. // 执行文件信息写入数据库
  3348. await ctx.service.changePlanAtt.saveFileMsgToDb(payload);
  3349. // 将最新的当前标段的所有文件信息返回
  3350. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3351. ctx.body = { err: 0, msg: '', data };
  3352. } catch (err) {
  3353. stream && (await sendToWormhole(stream));
  3354. this.log(err);
  3355. ctx.body = { err: 1, msg: err.toString(), data: null };
  3356. }
  3357. }
  3358. /**
  3359. * 删除附件
  3360. * @param {Ojbect} ctx 上下文
  3361. */
  3362. async deletePlanFile(ctx) {
  3363. try {
  3364. const { id } = JSON.parse(ctx.request.body.data);
  3365. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3366. if (fileInfo || Object.keys(fileInfo).length) {
  3367. // 先删除文件
  3368. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  3369. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  3370. // 再删除数据库
  3371. await ctx.service.changePlanAtt.delete(id);
  3372. } else {
  3373. throw '不存在该文件';
  3374. }
  3375. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3376. ctx.body = { err: 0, msg: '请求成功', data };
  3377. } catch (err) {
  3378. this.log(err);
  3379. ctx.body = { err: 1, msg: err.toString(), data: null };
  3380. }
  3381. }
  3382. /**
  3383. * 下载附件
  3384. * @param {Object} ctx - egg全局变量
  3385. * @return {void}
  3386. */
  3387. async downloadPlanFile(ctx) {
  3388. const id = ctx.params.fid;
  3389. if (id) {
  3390. try {
  3391. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3392. if (fileInfo !== undefined && fileInfo !== '') {
  3393. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  3394. // 解决中文无法下载问题
  3395. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  3396. let disposition = '';
  3397. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  3398. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  3399. } else if (userAgent.indexOf('firefox') >= 0) {
  3400. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  3401. } else {
  3402. /* safari等其他非主流浏览器只能自求多福了 */
  3403. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  3404. }
  3405. ctx.response.set({
  3406. 'Content-Type': 'application/octet-stream',
  3407. 'Content-Disposition': disposition,
  3408. 'Content-Length': fileInfo.filesize,
  3409. });
  3410. // ctx.body = await fs.createReadStream(fileName);
  3411. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  3412. } else {
  3413. throw '不存在该文件';
  3414. }
  3415. } catch (err) {
  3416. this.log(err);
  3417. this.setMessage(err.toString(), this.messageType.ERROR);
  3418. }
  3419. }
  3420. }
  3421. async planInformationSave(ctx) {
  3422. try {
  3423. const data = JSON.parse(ctx.request.body.data);
  3424. if (data.name === 'code') {
  3425. const info = await ctx.service.changePlan.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  3426. if (info) {
  3427. throw '该编号已存在';
  3428. }
  3429. }
  3430. const result = await ctx.service.changePlan.saveInfo(ctx.change.id, data);
  3431. if (!result) {
  3432. throw '修改失败';
  3433. }
  3434. ctx.body = { err: 0, msg: '请求成功', data: null };
  3435. } catch (err) {
  3436. this.log(err);
  3437. ctx.body = { err: 1, msg: err.toString(), data: null };
  3438. }
  3439. }
  3440. /**
  3441. * 上报和重新上报
  3442. * @param ctx
  3443. * @return {Promise<void>}
  3444. */
  3445. async startPlanAudit(ctx) {
  3446. try {
  3447. const auditConst = audit.changePlan;
  3448. // 检查权限等
  3449. if (!ctx.change) {
  3450. throw '数据错误';
  3451. }
  3452. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3453. throw '您无权上报该期数据';
  3454. }
  3455. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3456. throw '该材料调差期数据当前无法上报';
  3457. }
  3458. await ctx.service.changePlanAudit.start(ctx.change.id, ctx.change.times);
  3459. ctx.redirect(ctx.request.header.referer);
  3460. } catch (err) {
  3461. this.log(err);
  3462. ctx.session.postError = err.toString();
  3463. ctx.redirect(ctx.request.header.referer);
  3464. }
  3465. }
  3466. /**
  3467. * 审批
  3468. * @param ctx
  3469. * @return {Promise<void>}
  3470. */
  3471. async checkPlanAudit(ctx) {
  3472. try {
  3473. const auditConst = audit.changePlan;
  3474. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  3475. throw '当前材料调差期数据有误';
  3476. }
  3477. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  3478. throw '您无权进行该操作';
  3479. }
  3480. const data = {
  3481. checkType: parseInt(ctx.request.body.checkType),
  3482. opinion: ctx.request.body.opinion,
  3483. };
  3484. if (!data.checkType || isNaN(data.checkType)) {
  3485. throw '提交数据错误';
  3486. }
  3487. // if (data.checkType === auditConst.status.checkNo) {
  3488. // if (!data.checkType || isNaN(data.checkType)) {
  3489. // throw '提交数据错误';
  3490. // }
  3491. // }
  3492. await ctx.service.changePlanAudit.check(ctx.change.id, data, ctx.change.times);
  3493. ctx.redirect(ctx.request.header.referer);
  3494. } catch (err) {
  3495. this.log(err);
  3496. console.log(err);
  3497. ctx.session.postError = err.toString();
  3498. ctx.redirect(ctx.request.header.referer);
  3499. }
  3500. }
  3501. /**
  3502. * 变更清单 - 操作 (Ajax)
  3503. * @param ctx
  3504. * @return {Promise<void>}
  3505. */
  3506. async savePlanListsData(ctx) {
  3507. try {
  3508. const data = JSON.parse(ctx.request.body.data);
  3509. const responseData = {
  3510. err: 0,
  3511. msg: '',
  3512. data: {},
  3513. };
  3514. switch (data.type) {
  3515. case 'add':
  3516. responseData.data = await ctx.service.changePlanList.add(data.updateData);
  3517. break;
  3518. case 'batchadd':
  3519. responseData.data = await ctx.service.changePlanList.batchAdd(data);
  3520. break;
  3521. case 'del':
  3522. await ctx.service.changePlanList.del(data.ids);
  3523. // 取所有工料表
  3524. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  3525. break;
  3526. case 'update':
  3527. // if (data.updateData.code === '' || data.updateData.code === null) {
  3528. // throw '请先输入编号';
  3529. // }
  3530. await ctx.service.changePlanList.save(data.updateData);
  3531. break;
  3532. case 'paste':
  3533. await ctx.service.changePlanList.saveDatas(data.updateData);
  3534. // 取所有工料表
  3535. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  3536. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3537. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3538. for (const cl of responseData.data) {
  3539. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3540. // 清单表页赋值
  3541. for (const [index, au] of listAudits.entries()) {
  3542. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  3543. }
  3544. }
  3545. }
  3546. break;
  3547. case 'list_rule':
  3548. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_plan_list_rule: data.postData });
  3549. if (!result) {
  3550. throw '修改失败';
  3551. }
  3552. break;
  3553. case 'paste_amount_rows':
  3554. await ctx.service.changePlanList.saveDatas(data.updateData);
  3555. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3556. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3557. for (const cl of changeList) {
  3558. // 清单表页赋值
  3559. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3560. // 清单表页赋值
  3561. for (const [index, au] of listAudits.entries()) {
  3562. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  3563. }
  3564. }
  3565. // 取所有工料表
  3566. responseData.data = changeList;
  3567. break;
  3568. // case 'update_tp':
  3569. // await ctx.service.changePlan.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  3570. // break;
  3571. default: throw '参数有误';
  3572. }
  3573. ctx.body = responseData;
  3574. } catch (err) {
  3575. this.log(err);
  3576. ctx.body = { err: 1, msg: err.toString(), data: null };
  3577. }
  3578. }
  3579. }
  3580. return ChangeController;
  3581. };