change_controller.js 216 KB

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