change_controller.js 204 KB

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