change_controller.js 225 KB

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