change_controller.js 201 KB

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