change_controller.js 211 KB

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