change_controller.js 225 KB

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