change_controller.js 214 KB

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