change_controller.js 211 KB

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