change_controller.js 220 KB

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