change_controller.js 222 KB

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