change_controller.js 212 KB

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