change_controller.js 205 KB

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