change_controller.js 221 KB

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