change_controller.js 220 KB

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