change_controller.js 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245
  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. // 获取原报dsk数据
  1423. const accountInfo = await ctx.service.projectAccount.getDataById(change.uid);
  1424. renderData.dskAccountData = accountInfo && accountInfo.dsk_account ? JSON.parse(accountInfo.dsk_account) : {};
  1425. renderData.dskProjects = accountInfo && accountInfo.dsk_account && accountInfo.dsk_projects ? JSON.parse(accountInfo.dsk_projects) : [];
  1426. // 台账只读、使用数据
  1427. renderData.readOnly = !edit;
  1428. renderData.changing = changing;
  1429. renderData.revising = revising;
  1430. renderData.isYb = change.uid === ctx.session.sessionUser.accountId;
  1431. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1432. } catch (err) {
  1433. this.log(err);
  1434. ctx.redirect(ctx.request.header.referer);
  1435. }
  1436. }
  1437. async _getDefaultReviseInfoData(ctx, change, edit) {
  1438. const [ledgerSpread, posSpread] = await spreadSetting.getLedgerSpreadSetting(ctx, change.tid, edit);
  1439. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1440. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1441. return {
  1442. change,
  1443. tender: ctx.tender.data,
  1444. ledgerSpread, posSpread, tenderMenu, measureType,
  1445. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1446. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1447. stdBills,
  1448. auditConst: audit.flow,
  1449. audit: audit.flow,
  1450. stdChapters,
  1451. nodeType: stdConst.nodeType,
  1452. settleStatus: ctx.service.settle.settleStatus,
  1453. };
  1454. }
  1455. async updateRevise(ctx) {
  1456. try {
  1457. if (!ctx.tender.data) throw '标段数据错误';
  1458. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1459. throw '该功能已关闭';
  1460. }
  1461. const data = JSON.parse(ctx.request.body.data);
  1462. if (!data.postType || !data.postData) throw '数据错误';
  1463. const responseData = { err: 0, msg: '', data: {} };
  1464. const change = ctx.change;
  1465. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1466. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1467. }
  1468. // 判断是否在修订中,是则无法操作本页
  1469. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1470. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1471. throw '台账修订中,无法操作新增部位数据';
  1472. }
  1473. // const revise = await this.checkRevise(ctx);
  1474. //
  1475. switch (data.postType) {
  1476. case 'add':
  1477. case 'delete':
  1478. case 'up-move':
  1479. case 'down-move':
  1480. case 'up-level':
  1481. case 'down-level':
  1482. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1483. break;
  1484. case 'update':
  1485. ctx.helper.checkDgnQtyPrecision(data.postData);
  1486. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1487. break;
  1488. case 'paste-block':
  1489. responseData.data = await this._pasteBlock(ctx, data.postData);
  1490. break;
  1491. case 'add-std':
  1492. responseData.data = await this._addStd(ctx, data.postData);
  1493. break;
  1494. case 'add-deal':
  1495. responseData.data = await this._addDeal(ctx, data.postData);
  1496. break;
  1497. // case 'batch-insert':
  1498. // responseData.data = await this._batchInsert(ctx, data.postData);
  1499. // break;
  1500. case 'pos':
  1501. responseData.data = await this._updatePos(ctx, data);
  1502. break;
  1503. default:
  1504. throw '未知操作';
  1505. }
  1506. ctx.body = responseData;
  1507. } catch (err) {
  1508. console.log(err);
  1509. this.log(err);
  1510. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1511. }
  1512. }
  1513. async _billsBase(ctx, type, data) {
  1514. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1515. if (type !== 'add') {
  1516. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1517. }
  1518. switch (type) {
  1519. case 'add':
  1520. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1521. case 'delete':
  1522. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1523. case 'up-move':
  1524. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1525. case 'down-move':
  1526. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1527. case 'up-level':
  1528. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1529. case 'down-level':
  1530. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1531. default:
  1532. throw '未知操作';
  1533. }
  1534. }
  1535. /**
  1536. * 复制粘贴整块
  1537. *
  1538. * @param ctx
  1539. * @return {Promise<void>}
  1540. */
  1541. async _pasteBlock(ctx, data) {
  1542. if ((isNaN(data.id) || data.id <= 0) ||
  1543. (!data.tid && data.tid <= 0) ||
  1544. (!data.block || data.block.length <= 0)) throw '参数错误';
  1545. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1546. }
  1547. /**
  1548. * 从标准项目表添加数据
  1549. * @param ctx
  1550. * @return {Promise<void>}
  1551. */
  1552. async _addStd(ctx, data) {
  1553. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1554. // todo 校验项目是否使用该库的权限
  1555. let stdLib,
  1556. addType;
  1557. switch (data.stdType) {
  1558. case 'xmj':
  1559. stdLib = ctx.service.stdXmj;
  1560. addType = stdDataAddType.withParent;
  1561. break;
  1562. case 'gcl':
  1563. stdLib = ctx.service.stdGcl;
  1564. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1565. if (selectNode.b_code) {
  1566. addType = stdDataAddType.next;
  1567. } else {
  1568. addType = stdDataAddType.child;
  1569. }
  1570. break;
  1571. default:
  1572. throw '未知标准库';
  1573. }
  1574. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1575. switch (addType) {
  1576. case stdDataAddType.child:
  1577. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1578. case stdDataAddType.next:
  1579. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1580. case stdDataAddType.withParent:
  1581. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1582. default:
  1583. throw '未知添加方式';
  1584. }
  1585. }
  1586. /**
  1587. * 从签约清单添加节点
  1588. * @param ctx
  1589. * @return {Promise<void>}
  1590. */
  1591. async _addDeal(ctx, data) {
  1592. if (!data.type || !data.dealBills) throw '数据错误';
  1593. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1594. if (data.dealBills.quantity && data.dealBills.unit) {
  1595. const precision = ctx.helper.findPrecision(ctx.tender.info.precision, data.dealBills.unit);
  1596. data.dealBills.quantity = ctx.helper.round(data.dealBills.quantity, precision.value);
  1597. data.dealBills.sgfh_qty = data.dealBills.quantity;
  1598. data.dealBills.total_price = ctx.helper.mul(data.dealBills.quantity, data.dealBills.unit_price, ctx.tender.info.decimal.tp);
  1599. data.dealBills.sgfh_tp = data.dealBills.total_price;
  1600. }
  1601. if (data.type === 'child') {
  1602. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1603. } else if (data.type === 'next') {
  1604. data.dealBills.ccid = ctx.change.cid;
  1605. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1606. }
  1607. throw '数据错误';
  1608. }
  1609. /**
  1610. * 批量插入数据
  1611. *
  1612. * data = {id, batchData, batchType}
  1613. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1614. * data.batchData = [{name, children}] -- 项目节列表
  1615. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1616. *
  1617. * @param ctx
  1618. * @return {Promise<void>}
  1619. */
  1620. async _batchInsert(ctx, data) {
  1621. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1622. switch (data.batchType) {
  1623. case 'child':
  1624. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1625. case 'next':
  1626. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1627. default:
  1628. throw '参数错误';
  1629. }
  1630. }
  1631. async _updatePos(ctx, data) {
  1632. await this.checkMeasureType(measureType.tz.value);
  1633. if (!data.posPostType) throw '数据错误';
  1634. switch (data.posPostType) {
  1635. case 'add':
  1636. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1637. case 'update':
  1638. if (data.postData instanceof Array) {
  1639. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1640. }
  1641. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1642. case 'delete':
  1643. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1644. case 'paste':
  1645. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1646. default:
  1647. throw '未知操作';
  1648. }
  1649. }
  1650. async _filterChangesProject(ctx, status = 0) {
  1651. const tenderId = ctx.params.id;
  1652. ctx.session.sessionUser.tenderId = tenderId;
  1653. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1654. // const tender = ctx.tender;
  1655. // const tenderList = await this.service.tender.getList();
  1656. const page = ctx.page;
  1657. const pageSize = ctx.pageSize;
  1658. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1659. const orders = ctx.query.order ? ctx.query.order : 0;
  1660. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1661. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1662. for (const c of changes) {
  1663. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  1664. c.curAuditors = await ctx.service.changeProjectAudit.getAuditorsByStatus(c.id, c.status, c.times);
  1665. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  1666. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  1667. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  1668. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  1669. await ctx.service.changeProject.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  1670. }
  1671. }
  1672. }
  1673. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1674. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1675. ? JSON.parse(accountInfo.permission) : null;
  1676. // 分页相关
  1677. const pageInfo = {
  1678. page,
  1679. pageSizeSelect: 1,
  1680. pageSize,
  1681. total_num: total,
  1682. total: Math.ceil(total / pageSize),
  1683. queryData: JSON.stringify(ctx.urlInfo.query),
  1684. };
  1685. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  1686. filter.count = [];
  1687. 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);
  1688. 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);
  1689. 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);
  1690. 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);
  1691. 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);
  1692. let codeRule = [];
  1693. let c_connector = '1';
  1694. let c_rule_first = 1;
  1695. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  1696. if (tender.c_code_rules) {
  1697. const c_code_rules = JSON.parse(tender.c_code_rules);
  1698. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  1699. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  1700. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  1701. }
  1702. for (const rule of codeRule) {
  1703. switch (rule.rule_type) {
  1704. case codeRuleConst.measure.ruleType.dealCode:
  1705. rule.preview = ctx.tender.info.deal_info.dealCode;
  1706. break;
  1707. case codeRuleConst.measure.ruleType.tenderName:
  1708. rule.preview = tender.name;
  1709. break;
  1710. case codeRuleConst.measure.ruleType.inDate:
  1711. rule.preview = moment().format('YYYY');
  1712. break;
  1713. case codeRuleConst.measure.ruleType.text:
  1714. rule.preview = rule.text;
  1715. break;
  1716. case codeRuleConst.measure.ruleType.addNo:
  1717. const s = '0000000000';
  1718. rule.preview = s.substr(s.length - rule.format);
  1719. break;
  1720. default: break;
  1721. }
  1722. }
  1723. const renderData = {
  1724. uid: ctx.session.sessionUser.accountId,
  1725. userPermission,
  1726. tender,
  1727. pageInfo,
  1728. changes,
  1729. status,
  1730. rule_type,
  1731. codeRule,
  1732. c_connector,
  1733. c_rule_first,
  1734. filter,
  1735. ruleType: codeRuleConst.ruleType[rule_type],
  1736. dealCode: ctx.tender.info.deal_info.dealCode,
  1737. auditConst: audit.changeProject,
  1738. ruleConst: codeRuleConst.measure,
  1739. changeConst,
  1740. auditType,
  1741. tenderMenu: this.menu.tenderMenu,
  1742. preUrl: '/tender/' + tender.id,
  1743. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  1744. };
  1745. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  1746. }
  1747. /**
  1748. * 变更立项列表 页面 (Get)
  1749. *
  1750. * @param {Object} ctx - egg全局变量
  1751. * @return {void}
  1752. */
  1753. async project(ctx) {
  1754. try {
  1755. await this._filterChangesProject(ctx);
  1756. } catch (err) {
  1757. this.log(err);
  1758. ctx.redirect('/dashboard');
  1759. }
  1760. }
  1761. /**
  1762. * 审批流程(Get)
  1763. * @param ctx
  1764. * @return {Promise<void>}
  1765. */
  1766. async changeProjectAuditors(ctx) {
  1767. try {
  1768. const id = JSON.parse(ctx.request.body.data).id;
  1769. const tenderId = ctx.params.id;
  1770. const changeInfo = await ctx.service.changeProject.getDataById(id);
  1771. await ctx.service.changeProject.loadChangeUser(changeInfo);
  1772. await ctx.service.changeProject.loadChangeAuditViewData(changeInfo);
  1773. ctx.body = { err: 0, msg: '', data: changeInfo };
  1774. } catch (error) {
  1775. this.log(error);
  1776. ctx.body = { err: 1, msg: error.toString(), data: null };
  1777. }
  1778. }
  1779. /**
  1780. * 新增变更立项 (Post)
  1781. *
  1782. * @param {Object} ctx - egg全局变量
  1783. * @return {void}
  1784. */
  1785. async projectAdd(ctx) {
  1786. try {
  1787. const tenderId = ctx.params.id;
  1788. if (!tenderId) {
  1789. throw '当前未打开标段';
  1790. }
  1791. const data = JSON.parse(ctx.request.body.data);
  1792. if (!data.code || data.code === '' || !data.name || data.name === '') {
  1793. throw '变更立项书编号不能为空';
  1794. }
  1795. // 在生成新变更立项后,需要copy前一个变更立项报表的签名信息
  1796. const lastChange = await ctx.service.changeProject.getLastChange(tenderId);
  1797. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  1798. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-302', change.id, lastChange ? lastChange.id : null);
  1799. ctx.body = { err: 0, msg: '', data: change };
  1800. } catch (err) {
  1801. this.log(err);
  1802. ctx.body = { err: 1, msg: err.toString() };
  1803. }
  1804. }
  1805. /**
  1806. * 删除变更立项
  1807. * @param {Object} ctx - egg全局变量
  1808. * @return {void}
  1809. */
  1810. async projectDelete(ctx) {
  1811. try {
  1812. const result = await ctx.service.changeProject.delete(ctx.request.body.cpid);
  1813. if (!result) {
  1814. throw '删除变更立项失败';
  1815. }
  1816. ctx.redirect(ctx.request.header.referer);
  1817. } catch (err) {
  1818. console.log(err);
  1819. ctx.redirect(ctx.request.header.referer);
  1820. }
  1821. }
  1822. /**
  1823. * 变更管理 状态筛选 页面 (Get)
  1824. * @param {Object} ctx - egg全局变量
  1825. * @return {void}
  1826. */
  1827. async projectStatus(ctx) {
  1828. try {
  1829. const status = parseInt(ctx.params.status);
  1830. await this._filterChangesProject(ctx, status);
  1831. } catch (err) {
  1832. this.logger.error(err);
  1833. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  1834. }
  1835. }
  1836. /**
  1837. * 获取审批界面所需的 原报、审批人数据等
  1838. * @param ctx
  1839. * @return {Promise<void>}
  1840. * @private
  1841. */
  1842. async _getChangeProjectAuditViewData(ctx) {
  1843. await ctx.service.changeProject.loadChangeAuditViewData(ctx.change);
  1844. }
  1845. // 变更类别获取及更新
  1846. async _getOrUpdateClass(ctx, serviceName) {
  1847. // 工程变更类别读取
  1848. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  1849. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  1850. if (ctx.change.status === audit[serviceName].status.uncheck ||
  1851. (serviceName === 'changeProject' && ctx.change.status === audit[serviceName].status.back) ||
  1852. (serviceName !== 'changeProject' && ctx.change.status === audit[serviceName].status.checkNo)) {
  1853. const classInfo = ctx.helper._.find(fun_set.change_class, function(item) {
  1854. return item.checked && (item.name === ctx.change.class || item.new_name === ctx.change.class);
  1855. });
  1856. if (!classInfo) {
  1857. const classInfo2 = ctx.helper._.find(fun_set.change_class, { checked: true });
  1858. ctx.change.class = classInfo2.new_name ? classInfo2.new_name : classInfo2.name;
  1859. await ctx.service[serviceName].defaultUpdate({
  1860. id: ctx.change.id,
  1861. class: ctx.change.class,
  1862. });
  1863. } else if (classInfo && classInfo.new_name && ctx.change.class !== classInfo.new_name) {
  1864. ctx.change.class = classInfo.new_name;
  1865. await ctx.service[serviceName].defaultUpdate({
  1866. id: ctx.change.id,
  1867. class: ctx.change.class,
  1868. });
  1869. }
  1870. }
  1871. return fun_set.change_class;
  1872. }
  1873. async projectInformation(ctx) {
  1874. try {
  1875. const whiteList = this.ctx.app.config.multipart.whitelist;
  1876. // const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  1877. // 获取附件列表
  1878. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  1879. await this._getChangeProjectAuditViewData(ctx);
  1880. const changeClass = await this._getOrUpdateClass(ctx, 'changeProject');
  1881. // 获取用户人验证手机号
  1882. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1883. const auth_mobile = pa.auth_mobile;
  1884. // 判断并更新
  1885. const renderData = {
  1886. tender: ctx.tender,
  1887. change: ctx.change,
  1888. changeConst,
  1889. changeClass,
  1890. auditConst: audit.changeProject,
  1891. fileList,
  1892. whiteList,
  1893. authMobile: auth_mobile,
  1894. auditType,
  1895. shenpiConst,
  1896. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/project') ? ctx.request.headers.referer : null,
  1897. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project_information),
  1898. preUrl: '/tender/' + ctx.tender.id + '/change/project/' + ctx.change.id + '/information',
  1899. };
  1900. // 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)) {
  1901. // data.accountGroup = accountGroup;
  1902. // 获取所有项目参与者
  1903. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  1904. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  1905. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  1906. });
  1907. renderData.accountList = accountList;
  1908. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  1909. renderData.accountGroup = unitList.map(item => {
  1910. const groupList = accountList.filter(item1 => item1.company === item.name);
  1911. return { groupName: item.name, groupList };
  1912. });
  1913. // 获取固定审批流列表
  1914. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  1915. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changeProject');
  1916. }
  1917. // }
  1918. await this.layout('change/project_information.ejs', renderData, 'change/project_information_modal.ejs');
  1919. } catch (err) {
  1920. this.log(err);
  1921. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  1922. }
  1923. }
  1924. async changeProjectSpGroup(ctx) {
  1925. try {
  1926. const data = JSON.parse(ctx.request.body.data);
  1927. const result = await ctx.service.changeProjectAudit.changeSpGroup(ctx.change, data.sp_group);
  1928. if (!result) {
  1929. throw '切换审批组失败';
  1930. }
  1931. const auditors = await ctx.service.changeProjectAudit.getUserGroup(ctx.change.id, ctx.change.times);
  1932. ctx.body = { err: 0, msg: '', data: auditors };
  1933. } catch (err) {
  1934. ctx.body = { err: 1, msg: err.toString(), data: null };
  1935. }
  1936. }
  1937. // 审批相关
  1938. /**
  1939. * 添加审批人
  1940. * @param ctx
  1941. * @return {Promise<void>}
  1942. */
  1943. async addProjectAudit(ctx) {
  1944. try {
  1945. const auditConst = audit.changeProject;
  1946. const data = JSON.parse(ctx.request.body.data);
  1947. const id = this.app._.toInteger(data.auditorId);
  1948. if (isNaN(id) || id <= 0) {
  1949. throw '参数错误';
  1950. }
  1951. // 检查权限等
  1952. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  1953. throw '您无权添加审核人';
  1954. }
  1955. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  1956. throw '当前不允许添加审核人';
  1957. }
  1958. // 判断是否是协审人,是则无法添加到审批人中
  1959. const xsAuditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  1960. const xsAidList = this.app._.map(xsAuditorList, 'aid');
  1961. if (this.app._.indexOf(xsAidList, id) !== -1) {
  1962. throw '该用户已添加到协审人列表中,请删除该协审人再添加';
  1963. }
  1964. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  1965. // 检查审核人是否已存在
  1966. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  1967. if (exist) {
  1968. throw '该审核人已存在,请勿重复添加';
  1969. }
  1970. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  1971. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  1972. const result = await ctx.service.changeProjectAudit.addAuditor(ctx.change.id, id, ctx.change.times, is_gdzs);
  1973. if (!result) {
  1974. throw '添加审核人失败';
  1975. }
  1976. const auditors = await ctx.service.changeProjectAudit.getUserGroup(ctx.change.id, ctx.change.times);
  1977. ctx.body = { err: 0, msg: '', data: auditors };
  1978. } catch (err) {
  1979. this.log(err);
  1980. ctx.body = { err: 1, msg: err.toString(), data: null };
  1981. }
  1982. }
  1983. /**
  1984. * 移除审批人
  1985. * @param ctx
  1986. * @return {Promise<void>}
  1987. */
  1988. async deleteProjectAudit(ctx) {
  1989. try {
  1990. const data = JSON.parse(ctx.request.body.data);
  1991. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  1992. if (isNaN(id) || id <= 0) {
  1993. throw '参数错误';
  1994. }
  1995. const result = await ctx.service.changeProjectAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  1996. if (!result) {
  1997. throw '移除审核人失败';
  1998. }
  1999. const auditors = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2000. ctx.body = { err: 0, msg: '', data: auditors };
  2001. } catch (err) {
  2002. ctx.body = { err: 1, msg: err.toString(), data: null };
  2003. }
  2004. }
  2005. /**
  2006. * 添加协审人
  2007. * @param ctx
  2008. * @return {Promise<void>}
  2009. */
  2010. async addProjectXsAudit(ctx) {
  2011. try {
  2012. const auditConst = audit.changeProject;
  2013. const data = JSON.parse(ctx.request.body.data);
  2014. const id = this.app._.toInteger(data.auditorId);
  2015. if (isNaN(id) || id <= 0) {
  2016. throw '参数错误';
  2017. }
  2018. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  2019. const spAuditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times);
  2020. const aidLists = this.app._.map(spAuditors, 'aid');
  2021. // 检查权限等
  2022. if (this.app._.indexOf(aidLists, ctx.session.sessionUser.accountId) === -1) {
  2023. throw '您无权添加协审人';
  2024. }
  2025. // 如果已经是审批人则无法添加此人为协审
  2026. if (this.app._.indexOf(aidLists, id) !== -1) {
  2027. throw '该用户为审批人或原报,无需添加至协审人';
  2028. }
  2029. const auditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2030. // 检查审核人是否已存在
  2031. const exist = this.app._.find(auditorList, { aid: id });
  2032. if (exist) {
  2033. throw '该协审人已存在,请勿重复添加';
  2034. }
  2035. const result = await ctx.service.changeProjectXsAudit.addAuditor(ctx.change.id, id);
  2036. if (!result) {
  2037. throw '添加协审人失败';
  2038. }
  2039. const auditors = await ctx.service.changeProjectXsAudit.getOneAudit(ctx.change.id, id);
  2040. ctx.body = { err: 0, msg: '', data: auditors };
  2041. } catch (err) {
  2042. this.log(err);
  2043. ctx.body = { err: 1, msg: err.toString(), data: null };
  2044. }
  2045. }
  2046. /**
  2047. * 移除协审人
  2048. * @param ctx
  2049. * @return {Promise<void>}
  2050. */
  2051. async deleteProjectXsAudit(ctx) {
  2052. try {
  2053. const data = JSON.parse(ctx.request.body.data);
  2054. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2055. if (isNaN(id) || id <= 0) {
  2056. throw '参数错误';
  2057. }
  2058. const result = await ctx.service.changeProjectXsAudit.deleteAuditor(ctx.change.id, id);
  2059. if (!result) {
  2060. throw '移除协审人失败';
  2061. }
  2062. const auditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2063. ctx.body = { err: 0, msg: '', data: auditors };
  2064. } catch (err) {
  2065. ctx.body = { err: 1, msg: err.toString(), data: null };
  2066. }
  2067. }
  2068. async saveProjectAudit(ctx) {
  2069. try {
  2070. // if (ctx.change.revising) {
  2071. // throw '台账修订中,请勿修改提交期数据';
  2072. // }
  2073. const data = JSON.parse(ctx.request.body.data);
  2074. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  2075. await ctx.service.changeProjectAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  2076. const auditors = await ctx.service.changeProjectAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  2077. ctx.body = { err: 0, msg: '', data: auditors };
  2078. } else {
  2079. throw '您无权进行该操作';
  2080. }
  2081. } catch (err) {
  2082. this.log(err);
  2083. // ctx.session.postError = err.toString();
  2084. // ctx.redirect(ctx.request.header.referer);
  2085. ctx.body = {
  2086. err: 1,
  2087. // url: ctx.request.header.referer,
  2088. msg: err,
  2089. };
  2090. }
  2091. }
  2092. /**
  2093. * 上传附件
  2094. * @param {*} ctx 上下文
  2095. */
  2096. async uploadProjectFile(ctx) {
  2097. let stream;
  2098. try {
  2099. const auditConst = audit.changeProject;
  2100. // this._checkAdvanceFileCanModify(ctx);
  2101. const parts = this.ctx.multipart({
  2102. autoFields: true,
  2103. });
  2104. const files = [];
  2105. const create_time = Date.parse(new Date()) / 1000;
  2106. let idx = 0;
  2107. const extra_upload = ctx.change.status === auditConst.status.checked;
  2108. while ((stream = await parts()) !== undefined) {
  2109. if (!stream.filename) {
  2110. // 如果没有传入直接返回
  2111. return;
  2112. }
  2113. const fileInfo = path.parse(stream.filename);
  2114. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_project/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2115. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2116. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2117. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2118. ++idx;
  2119. stream && (await sendToWormhole(stream));
  2120. }
  2121. const in_time = new Date();
  2122. const payload = files.map(file => {
  2123. let idx;
  2124. if (Array.isArray(parts.field.name)) {
  2125. idx = parts.field.name.findIndex(name => name === file.name);
  2126. } else {
  2127. idx = 'isString';
  2128. }
  2129. const newFile = {
  2130. tid: ctx.tender.id,
  2131. cpid: ctx.change.id,
  2132. uid: ctx.session.sessionUser.accountId,
  2133. filename: file.name,
  2134. fileext: file.ext,
  2135. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2136. filepath: file.filepath,
  2137. upload_time: in_time,
  2138. extra_upload,
  2139. };
  2140. return newFile;
  2141. });
  2142. // 执行文件信息写入数据库
  2143. await ctx.service.changeProjectAtt.saveFileMsgToDb(payload);
  2144. // 将最新的当前标段的所有文件信息返回
  2145. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2146. ctx.body = { err: 0, msg: '', data };
  2147. } catch (err) {
  2148. stream && (await sendToWormhole(stream));
  2149. this.log(err);
  2150. ctx.body = { err: 1, msg: err.toString(), data: null };
  2151. }
  2152. }
  2153. /**
  2154. * 删除附件
  2155. * @param {Ojbect} ctx 上下文
  2156. */
  2157. async deleteProjectFile(ctx) {
  2158. try {
  2159. const { id } = JSON.parse(ctx.request.body.data);
  2160. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2161. if (fileInfo || Object.keys(fileInfo).length) {
  2162. // 先删除文件
  2163. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2164. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2165. // 再删除数据库
  2166. await ctx.service.changeProjectAtt.delete(id);
  2167. } else {
  2168. throw '不存在该文件';
  2169. }
  2170. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2171. ctx.body = { err: 0, msg: '请求成功', data };
  2172. } catch (err) {
  2173. this.log(err);
  2174. ctx.body = { err: 1, msg: err.toString(), data: null };
  2175. }
  2176. }
  2177. /**
  2178. * 下载附件
  2179. * @param {Object} ctx - egg全局变量
  2180. * @return {void}
  2181. */
  2182. async downloadProjectFile(ctx) {
  2183. const id = ctx.params.fid;
  2184. if (id) {
  2185. try {
  2186. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2187. if (fileInfo !== undefined && fileInfo !== '') {
  2188. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2189. // 解决中文无法下载问题
  2190. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2191. let disposition = '';
  2192. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2193. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2194. } else if (userAgent.indexOf('firefox') >= 0) {
  2195. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2196. } else {
  2197. /* safari等其他非主流浏览器只能自求多福了 */
  2198. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2199. }
  2200. ctx.response.set({
  2201. 'Content-Type': 'application/octet-stream',
  2202. 'Content-Disposition': disposition,
  2203. 'Content-Length': fileInfo.filesize,
  2204. });
  2205. // ctx.body = await fs.createReadStream(fileName);
  2206. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2207. } else {
  2208. throw '不存在该文件';
  2209. }
  2210. } catch (err) {
  2211. this.log(err);
  2212. this.setMessage(err.toString(), this.messageType.ERROR);
  2213. }
  2214. }
  2215. }
  2216. async projectInformationSave(ctx) {
  2217. try {
  2218. const data = JSON.parse(ctx.request.body.data);
  2219. if (data.name === 'code') {
  2220. const info = await ctx.service.changeProject.isRepeat(ctx.change.id, data.val, ctx.tender.id, ctx.change.type);
  2221. if (info) {
  2222. throw '该编号已存在';
  2223. }
  2224. }
  2225. const result = await ctx.service.changeProject.saveInfo(ctx.change.id, data);
  2226. if (!result) {
  2227. throw '修改失败';
  2228. }
  2229. ctx.body = { err: 0, msg: '请求成功', data: null };
  2230. } catch (err) {
  2231. this.log(err);
  2232. ctx.body = { err: 1, msg: err.toString(), data: null };
  2233. }
  2234. }
  2235. /**
  2236. * 上报和重新上报
  2237. * @param ctx
  2238. * @return {Promise<void>}
  2239. */
  2240. async startProjectAudit(ctx) {
  2241. try {
  2242. const auditConst = audit.changeProject;
  2243. // 检查权限等
  2244. if (!ctx.change) {
  2245. throw '数据错误';
  2246. }
  2247. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2248. throw '您无权上报该期数据';
  2249. }
  2250. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2251. throw '该材料调差期数据当前无法上报';
  2252. }
  2253. await ctx.service.changeProjectAudit.start(ctx.change.id, ctx.change.times);
  2254. ctx.redirect(ctx.request.header.referer);
  2255. } catch (err) {
  2256. this.log(err);
  2257. ctx.session.postError = err.toString();
  2258. ctx.redirect(ctx.request.header.referer);
  2259. }
  2260. }
  2261. /**
  2262. * 审批
  2263. * @param ctx
  2264. * @return {Promise<void>}
  2265. */
  2266. async checkProjectAudit(ctx) {
  2267. try {
  2268. const auditConst = audit.changeProject;
  2269. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2270. throw '当前材料调差期数据有误';
  2271. }
  2272. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  2273. throw '您无权进行该操作';
  2274. }
  2275. const data = {
  2276. checkType: parseInt(ctx.request.body.checkType),
  2277. opinion: ctx.request.body.opinion,
  2278. };
  2279. if (!data.checkType || isNaN(data.checkType)) {
  2280. throw '提交数据错误';
  2281. }
  2282. // if (data.checkType === auditConst.status.checkNo) {
  2283. // if (!data.checkType || isNaN(data.checkType)) {
  2284. // throw '提交数据错误';
  2285. // }
  2286. // }
  2287. await ctx.service.changeProjectAudit.check(ctx.change.id, data, ctx.change.times);
  2288. ctx.redirect(ctx.request.header.referer);
  2289. } catch (err) {
  2290. this.log(err);
  2291. ctx.session.postError = err.toString();
  2292. ctx.redirect(ctx.request.header.referer);
  2293. }
  2294. }
  2295. /**
  2296. * 撤回审批
  2297. * @param ctx
  2298. * @return {Promise<void>}
  2299. */
  2300. async checkProjectAuditCancel(ctx) {
  2301. try {
  2302. if (!ctx.change.cancancel) throw '您无权进行该操作';
  2303. await ctx.service.changeProjectAudit.checkCancel(ctx.change);
  2304. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  2305. } catch (err) {
  2306. this.log(err);
  2307. ctx.body = { err: 1, msg: err };
  2308. }
  2309. }
  2310. /**
  2311. * 变更立项重新审批
  2312. * @param {Object} ctx - egg全局变量
  2313. * @return {void}
  2314. */
  2315. async checkProjectAgain(ctx) {
  2316. try {
  2317. // 获取终审
  2318. // const auditInfo = await this.ctx.service.changeProjectAudit.getAuditorByStatus(ctx.change.id, audit.changeProject.status.checked);
  2319. // if (ctx.change.status !== audit.changeProject.status.checked || ctx.session.sessionUser.accountId !== auditInfo.aid) {
  2320. if (ctx.change.status !== audit.changeProject.status.checked) {
  2321. throw '您无权进行该操作';
  2322. }
  2323. // 判断是否被变更申请调用了,是则无法发起修订
  2324. const projectInfo = await ctx.service.changeApply.getDataByCondition({ tid: ctx.tender.id, project_code: ctx.change.code });
  2325. if (projectInfo) {
  2326. throw '该变更立项已被变更申请调用,无法发起重新审批';
  2327. }
  2328. if (ctx.session.sessionUser.loginStatus === 0) {
  2329. const code = ctx.request.body.code;
  2330. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2331. if (!pa.auth_mobile) {
  2332. throw '未绑定手机号';
  2333. }
  2334. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  2335. const cacheCode = await app.redis.get(cacheKey);
  2336. // console.log(cacheCode);
  2337. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  2338. throw '验证码不正确!';
  2339. }
  2340. }
  2341. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changeProject.status.checked) {
  2342. // 重新审批
  2343. const result = await ctx.service.changeProjectAudit.checkAgain(ctx.change);
  2344. if (!result) {
  2345. throw '重新审批失败';
  2346. }
  2347. } else {
  2348. throw '您无权进行该操作';
  2349. }
  2350. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  2351. ctx.body = {
  2352. err: 0,
  2353. url: ctx.request.header.referer,
  2354. msg: '',
  2355. };
  2356. } catch (err) {
  2357. console.log(err);
  2358. // ctx.redirect(ctx.request.header.referer);
  2359. ctx.body = {
  2360. err: 1,
  2361. // url: ctx.request.header.referer,
  2362. msg: err,
  2363. };
  2364. }
  2365. }
  2366. /**
  2367. * 变更立项修订重新上报
  2368. * @param {Object} ctx - egg全局变量
  2369. * @return {void}
  2370. */
  2371. async checkProjectRevise(ctx) {
  2372. try {
  2373. if (ctx.change.status !== audit.changeProject.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  2374. throw '您无权进行该操作';
  2375. }
  2376. // 判断是否被变更申请调用了,是则无法发起修订
  2377. const projectInfo = await ctx.service.changeApply.getDataByCondition({ tid: ctx.tender.id, project_code: ctx.change.code });
  2378. if (projectInfo) {
  2379. throw '该变更立项已被变更申请调用,无法发起修订';
  2380. }
  2381. if (ctx.session.sessionUser.loginStatus === 0) {
  2382. const code = ctx.request.body.code;
  2383. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2384. if (!pa.auth_mobile) {
  2385. throw '未绑定手机号';
  2386. }
  2387. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  2388. const cacheCode = await app.redis.get(cacheKey);
  2389. // console.log(cacheCode);
  2390. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  2391. throw '验证码不正确!';
  2392. }
  2393. }
  2394. // 重新审批
  2395. const result = await ctx.service.changeProjectAudit.checkRevise(ctx.change);
  2396. if (!result) {
  2397. throw '修订发起失败';
  2398. }
  2399. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  2400. ctx.body = {
  2401. err: 0,
  2402. url: ctx.request.header.referer,
  2403. msg: '',
  2404. };
  2405. } catch (err) {
  2406. console.log(err);
  2407. // ctx.redirect(ctx.request.header.referer);
  2408. ctx.body = {
  2409. err: 1,
  2410. // url: ctx.request.header.referer,
  2411. msg: err,
  2412. };
  2413. }
  2414. }
  2415. /**
  2416. * 变更令撤销修订
  2417. * @param {Object} ctx - egg全局变量
  2418. * @return {void}
  2419. */
  2420. async cancelProjectRevise(ctx) {
  2421. try {
  2422. if (!(ctx.change.status === audit.changeProject.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  2423. throw '您无权进行该操作';
  2424. }
  2425. // 重新审批
  2426. const result = await ctx.service.changeProjectAudit.cancelRevise(ctx.change);
  2427. if (!result) {
  2428. throw '撤销修订失败';
  2429. }
  2430. ctx.body = {
  2431. err: 0,
  2432. url: ctx.request.header.referer,
  2433. msg: '',
  2434. };
  2435. } catch (err) {
  2436. console.log(err);
  2437. ctx.body = {
  2438. err: 1,
  2439. msg: err,
  2440. };
  2441. }
  2442. }
  2443. async _filterChangesApply(ctx, status = 0) {
  2444. const tenderId = ctx.params.id;
  2445. ctx.session.sessionUser.tenderId = tenderId;
  2446. const tender = await this.service.tender.getDataById(ctx.tender.id);
  2447. // const tender = ctx.tender;
  2448. // const tenderList = await this.service.tender.getList();
  2449. const page = ctx.page;
  2450. const pageSize = ctx.pageSize;
  2451. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  2452. const orders = ctx.query.order ? ctx.query.order : 0;
  2453. const changes = await ctx.service.changeApply.getListByStatus(tender.id, status, 1, sorts, orders);
  2454. const total = await ctx.service.changeApply.getCountByStatus(tender.id, status);
  2455. let page_total = 0;
  2456. const tp = await ctx.service.changeApply.getTp(tender.id, status);
  2457. for (const c of changes) {
  2458. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  2459. c.curAuditors = await ctx.service.changeApplyAudit.getAuditorsByStatus(c.id, c.status, c.times);
  2460. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  2461. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  2462. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  2463. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  2464. await ctx.service.changeApply.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  2465. }
  2466. }
  2467. page_total = ctx.helper.add(page_total, c.total_price);
  2468. }
  2469. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  2470. // 分页相关
  2471. const pageInfo = {
  2472. page,
  2473. pageSizeSelect: 1,
  2474. pageSize,
  2475. total_num: total,
  2476. total: Math.ceil(total / pageSize),
  2477. queryData: JSON.stringify(ctx.urlInfo.query),
  2478. };
  2479. const filter = JSON.parse(JSON.stringify(audit.changeApply.filter));
  2480. filter.count = [];
  2481. 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);
  2482. 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);
  2483. 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);
  2484. 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);
  2485. // 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);
  2486. let codeRule = [];
  2487. let c_connector = '1';
  2488. let c_rule_first = 1;
  2489. const rule_type = 'apply';
  2490. if (tender.c_code_rules) {
  2491. const c_code_rules = JSON.parse(tender.c_code_rules);
  2492. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  2493. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  2494. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  2495. }
  2496. for (const rule of codeRule) {
  2497. switch (rule.rule_type) {
  2498. case codeRuleConst.measure.ruleType.dealCode:
  2499. rule.preview = ctx.tender.info.deal_info.dealCode;
  2500. break;
  2501. case codeRuleConst.measure.ruleType.tenderName:
  2502. rule.preview = tender.name;
  2503. break;
  2504. case codeRuleConst.measure.ruleType.inDate:
  2505. rule.preview = moment().format('YYYY');
  2506. break;
  2507. case codeRuleConst.measure.ruleType.text:
  2508. rule.preview = rule.text;
  2509. break;
  2510. case codeRuleConst.measure.ruleType.addNo:
  2511. const s = '0000000000';
  2512. rule.preview = s.substr(s.length - rule.format);
  2513. break;
  2514. default: break;
  2515. }
  2516. }
  2517. const changeProjectList = await ctx.service.changeProject.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeProject.status.checked } });
  2518. const allProjectCodes = await ctx.service.changeApply.getAllDataByCondition({
  2519. columns: ['project_code'],
  2520. where: {
  2521. tid: tender.id,
  2522. },
  2523. });
  2524. const pcLists = allProjectCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allProjectCodes, 'project_code')) : [];
  2525. const renderData = {
  2526. uid: ctx.session.sessionUser.accountId,
  2527. tender,
  2528. pageInfo,
  2529. changes,
  2530. status,
  2531. rule_type,
  2532. codeRule,
  2533. c_connector,
  2534. c_rule_first,
  2535. filter,
  2536. apply_username: tender_userInfo ? tender_userInfo.name : null,
  2537. ruleType: codeRuleConst.ruleType[rule_type],
  2538. dealCode: ctx.tender.info.deal_info.dealCode,
  2539. auditConst: audit.changeApply,
  2540. ruleConst: codeRuleConst.measure,
  2541. changeConst,
  2542. auditType,
  2543. changeProjectList,
  2544. pcLists,
  2545. tp,
  2546. page_total,
  2547. tenderMenu: this.menu.tenderMenu,
  2548. preUrl: '/tender/' + tender.id,
  2549. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply),
  2550. };
  2551. await this.layout('change/apply.ejs', renderData, 'change/apply_modal.ejs');
  2552. }
  2553. /**
  2554. * 变更申请列表 页面 (Get)
  2555. *
  2556. * @param {Object} ctx - egg全局变量
  2557. * @return {void}
  2558. */
  2559. async apply(ctx) {
  2560. try {
  2561. await this._filterChangesApply(ctx);
  2562. } catch (err) {
  2563. this.log(err);
  2564. ctx.redirect('/dashboard');
  2565. }
  2566. }
  2567. /**
  2568. * 变更管理 状态筛选 页面 (Get)
  2569. * @param {Object} ctx - egg全局变量
  2570. * @return {void}
  2571. */
  2572. async applyStatus(ctx) {
  2573. try {
  2574. const status = parseInt(ctx.params.status);
  2575. await this._filterChangesApply(ctx, status);
  2576. } catch (err) {
  2577. this.logger.error(err);
  2578. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2579. }
  2580. }
  2581. /**
  2582. * 审批流程(Get)
  2583. * @param ctx
  2584. * @return {Promise<void>}
  2585. */
  2586. async changeApplyAuditors(ctx) {
  2587. try {
  2588. const id = JSON.parse(ctx.request.body.data).id;
  2589. const tenderId = ctx.params.id;
  2590. const changeInfo = await ctx.service.changeApply.getDataById(id);
  2591. await ctx.service.changeApply.loadChangeUser(changeInfo);
  2592. await ctx.service.changeApply.loadChangeAuditViewData(changeInfo);
  2593. ctx.body = { err: 0, msg: '', data: changeInfo };
  2594. } catch (error) {
  2595. this.log(error);
  2596. ctx.body = { err: 1, msg: error.toString(), data: null };
  2597. }
  2598. }
  2599. async changeApplySpGroup(ctx) {
  2600. try {
  2601. const data = JSON.parse(ctx.request.body.data);
  2602. const result = await ctx.service.changeApplyAudit.changeSpGroup(ctx.change, data.sp_group);
  2603. if (!result) {
  2604. throw '切换审批组失败';
  2605. }
  2606. const auditors = await ctx.service.changeApplyAudit.getUserGroup(ctx.change.id, ctx.change.times);
  2607. ctx.body = { err: 0, msg: '', data: auditors };
  2608. } catch (err) {
  2609. ctx.body = { err: 1, msg: err.toString(), data: null };
  2610. }
  2611. }
  2612. /**
  2613. * 撤回审批
  2614. * @param ctx
  2615. * @return {Promise<void>}
  2616. */
  2617. async checkApplyAuditCancel(ctx) {
  2618. try {
  2619. if (!ctx.change.cancancel) throw '您无权进行该操作';
  2620. await ctx.service.changeApplyAudit.checkCancel(ctx.change);
  2621. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  2622. } catch (err) {
  2623. this.log(err);
  2624. ctx.body = { err: 1, msg: err };
  2625. }
  2626. }
  2627. /**
  2628. * 新增变更申请 (Post)
  2629. *
  2630. * @param {Object} ctx - egg全局变量
  2631. * @return {void}
  2632. */
  2633. async applyAdd(ctx) {
  2634. try {
  2635. const tenderId = ctx.params.id;
  2636. if (!tenderId) {
  2637. throw '当前未打开标段';
  2638. }
  2639. const data = JSON.parse(ctx.request.body.data);
  2640. if (!data.code || data.code === '') {
  2641. throw '变更申请编号不能为空';
  2642. }
  2643. // 在生成新变更申请后,需要copy前一个变更申请报表的签名信息
  2644. const lastChange = await ctx.service.changeApply.getLastChange(tenderId);
  2645. const change = await ctx.service.changeApply.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.project_code, data.name);
  2646. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-303', change.id, lastChange ? lastChange.id : null);
  2647. ctx.body = { err: 0, msg: '', data: change };
  2648. } catch (err) {
  2649. this.log(err);
  2650. ctx.body = { err: 1, msg: err.toString() };
  2651. }
  2652. }
  2653. /**
  2654. * 删除变更立项
  2655. * @param {Object} ctx - egg全局变量
  2656. * @return {void}
  2657. */
  2658. async applyDelete(ctx) {
  2659. try {
  2660. const result = await ctx.service.changeApply.delete(ctx.request.body.caid);
  2661. if (!result) {
  2662. throw '删除变更立项失败';
  2663. }
  2664. ctx.redirect(ctx.request.header.referer);
  2665. } catch (err) {
  2666. console.log(err);
  2667. ctx.redirect(ctx.request.header.referer);
  2668. }
  2669. }
  2670. /**
  2671. * 获取审批界面所需的 原报、审批人数据等
  2672. * @param ctx
  2673. * @return {Promise<void>}
  2674. * @private
  2675. */
  2676. async _getChangeApplyAuditViewData(ctx) {
  2677. await ctx.service.changeApply.loadChangeAuditViewData(ctx.change);
  2678. }
  2679. async applyInformation(ctx) {
  2680. try {
  2681. const whiteList = this.ctx.app.config.multipart.whitelist;
  2682. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2683. await this._getChangeApplyAuditViewData(ctx);
  2684. // 获取清单列表
  2685. const changeList = await ctx.service.changeApplyList.getList(ctx.change.id);
  2686. // 获取附件列表
  2687. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2688. const changeClass = await this._getOrUpdateClass(ctx, 'changeApply');
  2689. // 获取用户人验证手机号
  2690. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2691. const auth_mobile = pa.auth_mobile;
  2692. const renderData = {
  2693. tender,
  2694. change: ctx.change,
  2695. listRule: tender.c_apply_list_rule ? JSON.parse(tender.c_apply_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  2696. changeList,
  2697. changeConst,
  2698. changeClass,
  2699. auditConst: audit.changeApply,
  2700. fileList,
  2701. whiteList,
  2702. authMobile: auth_mobile,
  2703. auditType,
  2704. shenpiConst,
  2705. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  2706. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  2707. changeUnits: changeConst.units,
  2708. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  2709. 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,
  2710. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information),
  2711. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information',
  2712. };
  2713. // 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)) {
  2714. // data.accountGroup = accountGroup;
  2715. // 获取所有项目参与者
  2716. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  2717. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  2718. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  2719. });
  2720. renderData.accountList = accountList;
  2721. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  2722. renderData.accountGroup = unitList.map(item => {
  2723. const groupList = accountList.filter(item1 => item1.company === item.name);
  2724. return { groupName: item.name, groupList };
  2725. });
  2726. // }
  2727. // 获取固定审批流列表
  2728. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  2729. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changeApply');
  2730. }
  2731. await this.layout('change/apply_information.ejs', renderData, 'change/apply_information_modal.ejs');
  2732. } catch (err) {
  2733. this.log(err);
  2734. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2735. }
  2736. }
  2737. async applyInformationNotice(ctx) {
  2738. try {
  2739. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2740. // 获取附件列表
  2741. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2742. await this._getChangeApplyAuditViewData(ctx);
  2743. const renderData = {
  2744. tender,
  2745. change: ctx.change,
  2746. changeConst,
  2747. auditConst: audit.changeApply,
  2748. fileList,
  2749. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') ? ctx.request.headers.referer : null,
  2750. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information_notice),
  2751. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information/notice',
  2752. };
  2753. await this.layout('change/apply_information_notice.ejs', renderData, 'change/apply_information_notice_modal.ejs');
  2754. } catch (err) {
  2755. this.log(err);
  2756. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2757. }
  2758. }
  2759. // 审批相关
  2760. /**
  2761. * 添加审批人
  2762. * @param ctx
  2763. * @return {Promise<void>}
  2764. */
  2765. async addApplyAudit(ctx) {
  2766. try {
  2767. const auditConst = audit.changeApply;
  2768. const data = JSON.parse(ctx.request.body.data);
  2769. const id = this.app._.toInteger(data.auditorId);
  2770. if (isNaN(id) || id <= 0) {
  2771. throw '参数错误';
  2772. }
  2773. // 检查权限等
  2774. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2775. throw '您无权添加审核人';
  2776. }
  2777. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2778. throw '当前不允许添加审核人';
  2779. }
  2780. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2781. // 检查审核人是否已存在
  2782. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2783. if (exist) {
  2784. throw '该审核人已存在,请勿重复添加';
  2785. }
  2786. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  2787. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  2788. const result = await ctx.service.changeApplyAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  2789. if (!result) {
  2790. throw '添加审核人失败';
  2791. }
  2792. const auditors = await ctx.service.changeApplyAudit.getUserGroup(ctx.change.id, ctx.change.times);
  2793. ctx.body = { err: 0, msg: '', data: auditors };
  2794. } catch (err) {
  2795. this.log(err);
  2796. ctx.body = { err: 1, msg: err.toString(), data: null };
  2797. }
  2798. }
  2799. /**
  2800. * 移除审批人
  2801. * @param ctx
  2802. * @return {Promise<void>}
  2803. */
  2804. async deleteApplyAudit(ctx) {
  2805. try {
  2806. const data = JSON.parse(ctx.request.body.data);
  2807. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2808. if (isNaN(id) || id <= 0) {
  2809. throw '参数错误';
  2810. }
  2811. const result = await ctx.service.changeApplyAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2812. if (!result) {
  2813. throw '移除审核人失败';
  2814. }
  2815. const auditors = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2816. ctx.body = { err: 0, msg: '', data: auditors };
  2817. } catch (err) {
  2818. ctx.body = { err: 1, msg: err.toString(), data: null };
  2819. }
  2820. }
  2821. async saveApplyAudit(ctx) {
  2822. try {
  2823. // if (ctx.change.revising) {
  2824. // throw '台账修订中,请勿修改提交期数据';
  2825. // }
  2826. const data = JSON.parse(ctx.request.body.data);
  2827. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  2828. await ctx.service.changeApplyAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  2829. const auditors = await ctx.service.changeApplyAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  2830. ctx.body = { err: 0, msg: '', data: auditors };
  2831. } else {
  2832. throw '您无权进行该操作';
  2833. }
  2834. } catch (err) {
  2835. this.log(err);
  2836. // ctx.session.postError = err.toString();
  2837. // ctx.redirect(ctx.request.header.referer);
  2838. ctx.body = {
  2839. err: 1,
  2840. // url: ctx.request.header.referer,
  2841. msg: err,
  2842. };
  2843. }
  2844. }
  2845. /**
  2846. * 上传附件
  2847. * @param {*} ctx 上下文
  2848. */
  2849. async uploadApplyFile(ctx) {
  2850. let stream;
  2851. try {
  2852. const auditConst = audit.changeApply;
  2853. // this._checkAdvanceFileCanModify(ctx);
  2854. const parts = this.ctx.multipart({
  2855. autoFields: true,
  2856. });
  2857. const files = [];
  2858. const create_time = Date.parse(new Date()) / 1000;
  2859. let idx = 0;
  2860. const extra_upload = ctx.change.status === auditConst.status.checked;
  2861. while ((stream = await parts()) !== undefined) {
  2862. if (!stream.filename) {
  2863. // 如果没有传入直接返回
  2864. return;
  2865. }
  2866. const fileInfo = path.parse(stream.filename);
  2867. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_apply/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2868. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2869. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2870. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2871. ++idx;
  2872. stream && (await sendToWormhole(stream));
  2873. }
  2874. const in_time = new Date();
  2875. const payload = files.map(file => {
  2876. let idx;
  2877. if (Array.isArray(parts.field.name)) {
  2878. idx = parts.field.name.findIndex(name => name === file.name);
  2879. } else {
  2880. idx = 'isString';
  2881. }
  2882. const newFile = {
  2883. tid: ctx.tender.id,
  2884. caid: ctx.change.id,
  2885. uid: ctx.session.sessionUser.accountId,
  2886. type: parts.field.type,
  2887. filename: file.name,
  2888. fileext: file.ext,
  2889. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2890. filepath: file.filepath,
  2891. upload_time: in_time,
  2892. extra_upload,
  2893. };
  2894. return newFile;
  2895. });
  2896. // 执行文件信息写入数据库
  2897. await ctx.service.changeApplyAtt.saveFileMsgToDb(payload);
  2898. // 将最新的当前标段的所有文件信息返回
  2899. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2900. ctx.body = { err: 0, msg: '', data };
  2901. } catch (err) {
  2902. stream && (await sendToWormhole(stream));
  2903. this.log(err);
  2904. ctx.body = { err: 1, msg: err.toString(), data: null };
  2905. }
  2906. }
  2907. /**
  2908. * 删除附件
  2909. * @param {Ojbect} ctx 上下文
  2910. */
  2911. async deleteApplyFile(ctx) {
  2912. try {
  2913. const { id } = JSON.parse(ctx.request.body.data);
  2914. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2915. if (fileInfo || Object.keys(fileInfo).length) {
  2916. // 先删除文件
  2917. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2918. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2919. // 再删除数据库
  2920. await ctx.service.changeApplyAtt.delete(id);
  2921. } else {
  2922. throw '不存在该文件';
  2923. }
  2924. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2925. ctx.body = { err: 0, msg: '请求成功', data };
  2926. } catch (err) {
  2927. this.log(err);
  2928. ctx.body = { err: 1, msg: err.toString(), data: null };
  2929. }
  2930. }
  2931. /**
  2932. * 下载附件
  2933. * @param {Object} ctx - egg全局变量
  2934. * @return {void}
  2935. */
  2936. async downloadApplyFile(ctx) {
  2937. const id = ctx.params.fid;
  2938. if (id) {
  2939. try {
  2940. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2941. if (fileInfo !== undefined && fileInfo !== '') {
  2942. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2943. // 解决中文无法下载问题
  2944. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2945. let disposition = '';
  2946. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2947. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2948. } else if (userAgent.indexOf('firefox') >= 0) {
  2949. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2950. } else {
  2951. /* safari等其他非主流浏览器只能自求多福了 */
  2952. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2953. }
  2954. ctx.response.set({
  2955. 'Content-Type': 'application/octet-stream',
  2956. 'Content-Disposition': disposition,
  2957. 'Content-Length': fileInfo.filesize,
  2958. });
  2959. // ctx.body = await fs.createReadStream(fileName);
  2960. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2961. } else {
  2962. throw '不存在该文件';
  2963. }
  2964. } catch (err) {
  2965. this.log(err);
  2966. this.setMessage(err.toString(), this.messageType.ERROR);
  2967. }
  2968. }
  2969. }
  2970. async applyInformationSave(ctx) {
  2971. try {
  2972. const data = JSON.parse(ctx.request.body.data);
  2973. if (data.name === 'code') {
  2974. const info = await ctx.service.changeApply.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  2975. if (info) {
  2976. throw '该编号已存在';
  2977. }
  2978. }
  2979. const result = await ctx.service.changeApply.saveInfo(ctx.change.id, data);
  2980. if (!result) {
  2981. throw '修改失败';
  2982. }
  2983. ctx.body = { err: 0, msg: '请求成功', data: null };
  2984. } catch (err) {
  2985. this.log(err);
  2986. ctx.body = { err: 1, msg: err.toString(), data: null };
  2987. }
  2988. }
  2989. /**
  2990. * 上报和重新上报
  2991. * @param ctx
  2992. * @return {Promise<void>}
  2993. */
  2994. async startApplyAudit(ctx) {
  2995. try {
  2996. const auditConst = audit.changeApply;
  2997. // 检查权限等
  2998. if (!ctx.change) {
  2999. throw '数据错误';
  3000. }
  3001. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3002. throw '您无权上报该期数据';
  3003. }
  3004. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3005. throw '该材料调差期数据当前无法上报';
  3006. }
  3007. await ctx.service.changeApplyAudit.start(ctx.change.id, ctx.change.times);
  3008. ctx.redirect(ctx.request.header.referer);
  3009. } catch (err) {
  3010. this.log(err);
  3011. ctx.session.postError = err.toString();
  3012. ctx.redirect(ctx.request.header.referer);
  3013. }
  3014. }
  3015. /**
  3016. * 审批
  3017. * @param ctx
  3018. * @return {Promise<void>}
  3019. */
  3020. async checkApplyAudit(ctx) {
  3021. try {
  3022. const auditConst = audit.changeApply;
  3023. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  3024. throw '当前材料调差期数据有误';
  3025. }
  3026. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  3027. throw '您无权进行该操作';
  3028. }
  3029. const data = {
  3030. checkType: parseInt(ctx.request.body.checkType),
  3031. opinion: ctx.request.body.opinion,
  3032. };
  3033. if (!data.checkType || isNaN(data.checkType)) {
  3034. throw '提交数据错误';
  3035. }
  3036. if (ctx.request.body.notice_uid) {
  3037. data.notice_code = ctx.request.body.notice_code;
  3038. data.notice_uid = ctx.request.body.notice_uid;
  3039. }
  3040. // if (data.checkType === auditConst.status.checkNo) {
  3041. // if (!data.checkType || isNaN(data.checkType)) {
  3042. // throw '提交数据错误';
  3043. // }
  3044. // }
  3045. await ctx.service.changeApplyAudit.check(ctx.change.id, data, ctx.change.times);
  3046. ctx.redirect(ctx.request.header.referer);
  3047. } catch (err) {
  3048. this.log(err);
  3049. ctx.session.postError = err.toString();
  3050. ctx.redirect(ctx.request.header.referer);
  3051. }
  3052. }
  3053. /**
  3054. * 变更清单 - 操作 (Ajax)
  3055. * @param ctx
  3056. * @return {Promise<void>}
  3057. */
  3058. async saveApplyListsData(ctx) {
  3059. try {
  3060. const data = JSON.parse(ctx.request.body.data);
  3061. const responseData = {
  3062. err: 0,
  3063. msg: '',
  3064. data: {},
  3065. };
  3066. switch (data.type) {
  3067. case 'add':
  3068. responseData.data = await ctx.service.changeApplyList.add(data.updateData);
  3069. break;
  3070. case 'batchadd':
  3071. responseData.data = await ctx.service.changeApplyList.batchAdd(data);
  3072. break;
  3073. case 'del':
  3074. await ctx.service.changeApplyList.del(data.ids);
  3075. // 取所有工料表
  3076. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3077. break;
  3078. case 'update':
  3079. // if (data.updateData.code === '' || data.updateData.code === null) {
  3080. // throw '请先输入编号';
  3081. // }
  3082. await ctx.service.changeApplyList.save(data.updateData);
  3083. break;
  3084. case 'paste':
  3085. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3086. // 取所有工料表
  3087. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3088. break;
  3089. case 'paste_amount_rows':
  3090. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3091. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3092. break;
  3093. case 'list_rule':
  3094. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_apply_list_rule: data.postData });
  3095. if (!result) {
  3096. throw '修改失败';
  3097. }
  3098. break;
  3099. // case 'update_tp':
  3100. // await ctx.service.changeApply.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  3101. // break;
  3102. default: throw '参数有误';
  3103. }
  3104. ctx.body = responseData;
  3105. } catch (err) {
  3106. this.log(err);
  3107. ctx.body = { err: 1, msg: err.toString(), data: null };
  3108. }
  3109. }
  3110. /**
  3111. * 变更申请重新审批
  3112. * @param {Object} ctx - egg全局变量
  3113. * @return {void}
  3114. */
  3115. async checkApplyAgain(ctx) {
  3116. try {
  3117. // 获取终审
  3118. // const auditInfo = await this.ctx.service.changeApplyAudit.getAuditorByStatus(ctx.change.id, audit.changeApply.status.checked);
  3119. if (ctx.change.status !== audit.changeApply.status.checked) {
  3120. throw '您无权进行该操作';
  3121. }
  3122. // 判断是否被变更申请调用了,是则无法发起修订
  3123. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3124. if (projectInfo) {
  3125. throw '该变更申请已被变更方案调用,无法发起重新审批';
  3126. }
  3127. if (ctx.session.sessionUser.loginStatus === 0) {
  3128. const code = ctx.request.body.code;
  3129. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3130. if (!pa.auth_mobile) {
  3131. throw '未绑定手机号';
  3132. }
  3133. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3134. const cacheCode = await app.redis.get(cacheKey);
  3135. // console.log(cacheCode);
  3136. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3137. throw '验证码不正确!';
  3138. }
  3139. }
  3140. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changeApply.status.checked) {
  3141. // 重新审批
  3142. const result = await ctx.service.changeApplyAudit.checkAgain(ctx.change);
  3143. if (!result) {
  3144. throw '重新审批失败';
  3145. }
  3146. } else {
  3147. throw '您无权进行该操作';
  3148. }
  3149. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3150. ctx.body = {
  3151. err: 0,
  3152. url: ctx.request.header.referer,
  3153. msg: '',
  3154. };
  3155. } catch (err) {
  3156. console.log(err);
  3157. // ctx.redirect(ctx.request.header.referer);
  3158. ctx.body = {
  3159. err: 1,
  3160. // url: ctx.request.header.referer,
  3161. msg: err,
  3162. };
  3163. }
  3164. }
  3165. /**
  3166. * 变更申请修订重新上报
  3167. * @param {Object} ctx - egg全局变量
  3168. * @return {void}
  3169. */
  3170. async checkApplyRevise(ctx) {
  3171. try {
  3172. if (ctx.change.status !== audit.changeApply.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  3173. throw '您无权进行该操作';
  3174. }
  3175. // 判断是否被变更申请调用了,是则无法发起修订
  3176. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3177. if (projectInfo) {
  3178. throw '该变更申请已被变更方案调用,无法发起修订';
  3179. }
  3180. if (ctx.session.sessionUser.loginStatus === 0) {
  3181. const code = ctx.request.body.code;
  3182. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3183. if (!pa.auth_mobile) {
  3184. throw '未绑定手机号';
  3185. }
  3186. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3187. const cacheCode = await app.redis.get(cacheKey);
  3188. // console.log(cacheCode);
  3189. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3190. throw '验证码不正确!';
  3191. }
  3192. }
  3193. // 重新审批
  3194. const result = await ctx.service.changeApplyAudit.checkRevise(ctx.change);
  3195. if (!result) {
  3196. throw '修订发起失败';
  3197. }
  3198. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3199. ctx.body = {
  3200. err: 0,
  3201. url: ctx.request.header.referer,
  3202. msg: '',
  3203. };
  3204. } catch (err) {
  3205. console.log(err);
  3206. // ctx.redirect(ctx.request.header.referer);
  3207. ctx.body = {
  3208. err: 1,
  3209. // url: ctx.request.header.referer,
  3210. msg: err,
  3211. };
  3212. }
  3213. }
  3214. /**
  3215. * 变更令撤销修订
  3216. * @param {Object} ctx - egg全局变量
  3217. * @return {void}
  3218. */
  3219. async cancelApplyRevise(ctx) {
  3220. try {
  3221. if (!(ctx.change.status === audit.changeApply.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  3222. throw '您无权进行该操作';
  3223. }
  3224. // 重新审批
  3225. const result = await ctx.service.changeApplyAudit.cancelRevise(ctx.change);
  3226. if (!result) {
  3227. throw '撤销修订失败';
  3228. }
  3229. ctx.body = {
  3230. err: 0,
  3231. url: ctx.request.header.referer,
  3232. msg: '',
  3233. };
  3234. } catch (err) {
  3235. console.log(err);
  3236. ctx.body = {
  3237. err: 1,
  3238. msg: err,
  3239. };
  3240. }
  3241. }
  3242. // 变更方案
  3243. async _filterChangesPlan(ctx, status = 0) {
  3244. const tenderId = ctx.params.id;
  3245. ctx.session.sessionUser.tenderId = tenderId;
  3246. const tender = await this.service.tender.getDataById(ctx.tender.id);
  3247. // const tender = ctx.tender;
  3248. // const tenderList = await this.service.tender.getList();
  3249. const page = ctx.page;
  3250. const pageSize = ctx.pageSize;
  3251. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  3252. const orders = ctx.query.order ? ctx.query.order : 0;
  3253. const changes = await ctx.service.changePlan.getListByStatus(tender.id, status, 1, sorts, orders);
  3254. const total = await ctx.service.changePlan.getCountByStatus(tender.id, status);
  3255. let page_total = 0;
  3256. const tp = await ctx.service.changePlan.getTp(tender.id, status);
  3257. for (const c of changes) {
  3258. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  3259. c.curAuditors = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, c.status, c.times);
  3260. // if (c.status === audit.changePlan.status.checkNoPre) {
  3261. // c.curAuditors2 = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, audit.changePlan.status.checking, c.times);
  3262. // }
  3263. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  3264. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  3265. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  3266. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  3267. await ctx.service.changePlan.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  3268. }
  3269. }
  3270. page_total = ctx.helper.add(page_total, c.total_price);
  3271. }
  3272. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  3273. // 分页相关
  3274. const pageInfo = {
  3275. page,
  3276. pageSizeSelect: 1,
  3277. pageSize,
  3278. total_num: total,
  3279. total: Math.ceil(total / pageSize),
  3280. queryData: JSON.stringify(ctx.urlInfo.query),
  3281. };
  3282. const filter = JSON.parse(JSON.stringify(audit.changePlan.filter));
  3283. filter.count = [];
  3284. 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);
  3285. 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);
  3286. 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);
  3287. 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);
  3288. // 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);
  3289. let codeRule = [];
  3290. let c_connector = '1';
  3291. let c_rule_first = 1;
  3292. const rule_type = 'plan';
  3293. if (tender.c_code_rules) {
  3294. const c_code_rules = JSON.parse(tender.c_code_rules);
  3295. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  3296. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  3297. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  3298. }
  3299. for (const rule of codeRule) {
  3300. switch (rule.rule_type) {
  3301. case codeRuleConst.measure.ruleType.dealCode:
  3302. rule.preview = ctx.tender.info.deal_info.dealCode;
  3303. break;
  3304. case codeRuleConst.measure.ruleType.tenderName:
  3305. rule.preview = tender.name;
  3306. break;
  3307. case codeRuleConst.measure.ruleType.inDate:
  3308. rule.preview = moment().format('YYYY');
  3309. break;
  3310. case codeRuleConst.measure.ruleType.text:
  3311. rule.preview = rule.text;
  3312. break;
  3313. case codeRuleConst.measure.ruleType.addNo:
  3314. const s = '0000000000';
  3315. rule.preview = s.substr(s.length - rule.format);
  3316. break;
  3317. default: break;
  3318. }
  3319. }
  3320. const changeApplyList = await ctx.service.changeApply.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeApply.status.checked } });
  3321. const allApplyCodes = await ctx.service.changePlan.getAllDataByCondition({
  3322. columns: ['apply_code'],
  3323. where: {
  3324. tid: tender.id,
  3325. },
  3326. });
  3327. const acLists = allApplyCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allApplyCodes, 'apply_code')) : [];
  3328. const renderData = {
  3329. uid: ctx.session.sessionUser.accountId,
  3330. tender,
  3331. pageInfo,
  3332. changes,
  3333. status,
  3334. rule_type,
  3335. codeRule,
  3336. c_connector,
  3337. c_rule_first,
  3338. filter,
  3339. plan_username: tender_userInfo ? tender_userInfo.name : null,
  3340. ruleType: codeRuleConst.ruleType[rule_type],
  3341. dealCode: ctx.tender.info.deal_info.dealCode,
  3342. auditConst: audit.changePlan,
  3343. ruleConst: codeRuleConst.measure,
  3344. changeConst,
  3345. auditType,
  3346. changeApplyList,
  3347. acLists,
  3348. page_total,
  3349. tp,
  3350. tenderMenu: this.menu.tenderMenu,
  3351. preUrl: '/tender/' + tender.id,
  3352. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan),
  3353. };
  3354. await this.layout('change/plan.ejs', renderData, 'change/plan_modal.ejs');
  3355. }
  3356. /**
  3357. * 变更申请列表 页面 (Get)
  3358. *
  3359. * @param {Object} ctx - egg全局变量
  3360. * @return {void}
  3361. */
  3362. async plan(ctx) {
  3363. try {
  3364. await this._filterChangesPlan(ctx);
  3365. } catch (err) {
  3366. this.log(err);
  3367. ctx.redirect('/dashboard');
  3368. }
  3369. }
  3370. /**
  3371. * 变更管理 状态筛选 页面 (Get)
  3372. * @param {Object} ctx - egg全局变量
  3373. * @return {void}
  3374. */
  3375. async planStatus(ctx) {
  3376. try {
  3377. const status = parseInt(ctx.params.status);
  3378. await this._filterChangesPlan(ctx, status);
  3379. } catch (err) {
  3380. this.logger.error(err);
  3381. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3382. }
  3383. }
  3384. /**
  3385. * 审批流程(Get)
  3386. * @param ctx
  3387. * @return {Promise<void>}
  3388. */
  3389. async changePlanAuditors(ctx) {
  3390. try {
  3391. const id = JSON.parse(ctx.request.body.data).id;
  3392. const tenderId = ctx.params.id;
  3393. const changeInfo = await ctx.service.changePlan.getDataById(id);
  3394. await ctx.service.changePlan.loadChangeUser(changeInfo);
  3395. await ctx.service.changePlan.loadChangeAuditViewData(changeInfo);
  3396. ctx.body = { err: 0, msg: '', data: changeInfo };
  3397. } catch (error) {
  3398. this.log(error);
  3399. ctx.body = { err: 1, msg: error.toString(), data: null };
  3400. }
  3401. }
  3402. /**
  3403. * 新增变更方案 (Post)
  3404. *
  3405. * @param {Object} ctx - egg全局变量
  3406. * @return {void}
  3407. */
  3408. async planAdd(ctx) {
  3409. try {
  3410. const tenderId = ctx.params.id;
  3411. if (!tenderId) {
  3412. throw '当前未打开标段';
  3413. }
  3414. const data = JSON.parse(ctx.request.body.data);
  3415. if (!data.code || data.code === '') {
  3416. throw '变更方案编号不能为空';
  3417. }
  3418. // 在生成新变更方案后,需要copy前一个变更方案报表的签名信息
  3419. const lastChange = await ctx.service.changePlan.getLastChange(tenderId);
  3420. const change = await ctx.service.changePlan.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.apply_code, data.name);
  3421. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-301', change.id, lastChange ? lastChange.id : null);
  3422. ctx.body = { err: 0, msg: '', data: change };
  3423. } catch (err) {
  3424. this.log(err);
  3425. ctx.body = { err: 1, msg: err.toString() };
  3426. }
  3427. }
  3428. /**
  3429. * 删除变更立项
  3430. * @param {Object} ctx - egg全局变量
  3431. * @return {void}
  3432. */
  3433. async planDelete(ctx) {
  3434. try {
  3435. const result = await ctx.service.changePlan.delete(ctx.request.body.cpid);
  3436. if (!result) {
  3437. throw '删除变更方案失败';
  3438. }
  3439. ctx.redirect(ctx.request.header.referer);
  3440. } catch (err) {
  3441. console.log(err);
  3442. ctx.redirect(ctx.request.header.referer);
  3443. }
  3444. }
  3445. /**
  3446. * 获取审批界面所需的 原报、审批人数据等
  3447. * @param ctx
  3448. * @return {Promise<void>}
  3449. * @private
  3450. */
  3451. async _getChangePlanAuditViewData(ctx) {
  3452. await ctx.service.changePlan.loadChangeAuditViewData(ctx.change);
  3453. }
  3454. async planInformation(ctx) {
  3455. try {
  3456. const whiteList = this.ctx.app.config.multipart.whitelist;
  3457. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  3458. await this._getChangePlanAuditViewData(ctx);
  3459. // 获取附件列表
  3460. const fileList = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3461. // 获取清单列表
  3462. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3463. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3464. // const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3465. // ctx.change.listAudits = listAudits;
  3466. for (const cl of changeList) {
  3467. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3468. // 清单表页赋值
  3469. for (const au in ctx.change.userGroups) {
  3470. if (ctx.change.userGroups[au][0].audit_order !== 0) {
  3471. cl['audit_amount_' + ctx.change.userGroups[au][0].audit_order] =
  3472. (ctx.change.userGroups[au][0].audit_type === auditType.key.and &&
  3473. ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId, status: audit.changePlan.status.checked }) !== -1) ||
  3474. (ctx.change.shenpiPower && ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId }) !== -1) ?
  3475. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  3476. }
  3477. }
  3478. }
  3479. }
  3480. // 获取用户人验证手机号
  3481. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3482. const auth_mobile = pa.auth_mobile;
  3483. const changeClass = await this._getOrUpdateClass(ctx, 'changePlan');
  3484. const renderData = {
  3485. tender,
  3486. change: ctx.change,
  3487. listRule: tender.c_plan_list_rule ? JSON.parse(tender.c_plan_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  3488. changeList,
  3489. changeClass,
  3490. changeConst,
  3491. auditConst: audit.changePlan,
  3492. fileList,
  3493. whiteList,
  3494. authMobile: auth_mobile,
  3495. auditType,
  3496. shenpiConst,
  3497. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  3498. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  3499. changeUnits: changeConst.units,
  3500. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  3501. 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,
  3502. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan_information),
  3503. preUrl: '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information',
  3504. };
  3505. // 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)) {
  3506. // data.accountGroup = accountGroup;
  3507. // 获取所有项目参与者
  3508. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  3509. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  3510. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  3511. });
  3512. renderData.accountList = accountList;
  3513. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  3514. renderData.accountGroup = unitList.map(item => {
  3515. const groupList = accountList.filter(item1 => item1.company === item.name);
  3516. return { groupName: item.name, groupList };
  3517. });
  3518. // 获取固定审批流列表
  3519. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  3520. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changePlan');
  3521. }
  3522. // }
  3523. await this.layout('change/plan_information.ejs', renderData, 'change/plan_information_modal.ejs');
  3524. } catch (err) {
  3525. this.log(err);
  3526. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3527. }
  3528. }
  3529. async changePlanSpGroup(ctx) {
  3530. try {
  3531. const data = JSON.parse(ctx.request.body.data);
  3532. const result = await ctx.service.changePlanAudit.changeSpGroup(ctx.change, data.sp_group);
  3533. if (!result) {
  3534. throw '切换审批组失败';
  3535. }
  3536. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3537. ctx.body = { err: 0, msg: '', data: auditors };
  3538. } catch (err) {
  3539. ctx.body = { err: 1, msg: err.toString(), data: null };
  3540. }
  3541. }
  3542. // 审批相关
  3543. /**
  3544. * 添加审批人
  3545. * @param ctx
  3546. * @return {Promise<void>}
  3547. */
  3548. async addPlanAudit(ctx) {
  3549. try {
  3550. const auditConst = audit.changePlan;
  3551. const data = JSON.parse(ctx.request.body.data);
  3552. const id = this.app._.toInteger(data.auditorId);
  3553. if (isNaN(id) || id <= 0) {
  3554. throw '参数错误';
  3555. }
  3556. // 检查权限等
  3557. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3558. throw '您无权添加审核人';
  3559. }
  3560. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3561. throw '当前不允许添加审核人';
  3562. }
  3563. ctx.change.auditorList = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3564. // 检查审核人是否已存在
  3565. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3566. if (exist) {
  3567. throw '该审核人已存在,请勿重复添加';
  3568. }
  3569. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3570. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3571. const result = await ctx.service.changePlanAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3572. if (!result) {
  3573. throw '添加审核人失败';
  3574. }
  3575. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3576. ctx.body = { err: 0, msg: '', data: auditors };
  3577. } catch (err) {
  3578. this.log(err);
  3579. ctx.body = { err: 1, msg: err.toString(), data: null };
  3580. }
  3581. }
  3582. /**
  3583. * 移除审批人
  3584. * @param ctx
  3585. * @return {Promise<void>}
  3586. */
  3587. async deletePlanAudit(ctx) {
  3588. try {
  3589. const data = JSON.parse(ctx.request.body.data);
  3590. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3591. if (isNaN(id) || id <= 0) {
  3592. throw '参数错误';
  3593. }
  3594. const result = await ctx.service.changePlanAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3595. if (!result) {
  3596. throw '移除审核人失败';
  3597. }
  3598. const auditors = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3599. ctx.body = { err: 0, msg: '', data: auditors };
  3600. } catch (err) {
  3601. ctx.body = { err: 1, msg: err.toString(), data: null };
  3602. }
  3603. }
  3604. async savePlanAudit(ctx) {
  3605. try {
  3606. // if (ctx.change.revising) {
  3607. // throw '台账修订中,请勿修改提交期数据';
  3608. // }
  3609. const data = JSON.parse(ctx.request.body.data);
  3610. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  3611. await ctx.service.changePlanAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  3612. const auditors = await ctx.service.changePlanAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  3613. ctx.body = { err: 0, msg: '', data: auditors };
  3614. } else {
  3615. throw '您无权进行该操作';
  3616. }
  3617. } catch (err) {
  3618. this.log(err);
  3619. // ctx.session.postError = err.toString();
  3620. // ctx.redirect(ctx.request.header.referer);
  3621. ctx.body = {
  3622. err: 1,
  3623. // url: ctx.request.header.referer,
  3624. msg: err,
  3625. };
  3626. }
  3627. }
  3628. /**
  3629. * 上传附件
  3630. * @param {*} ctx 上下文
  3631. */
  3632. async uploadPlanFile(ctx) {
  3633. let stream;
  3634. try {
  3635. const auditConst = audit.changePlan;
  3636. // this._checkAdvanceFileCanModify(ctx);
  3637. const parts = this.ctx.multipart({
  3638. autoFields: true,
  3639. });
  3640. const files = [];
  3641. const create_time = Date.parse(new Date()) / 1000;
  3642. let idx = 0;
  3643. const extra_upload = ctx.change.status === auditConst.status.checked;
  3644. while ((stream = await parts()) !== undefined) {
  3645. if (!stream.filename) {
  3646. // 如果没有传入直接返回
  3647. return;
  3648. }
  3649. const fileInfo = path.parse(stream.filename);
  3650. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_plan/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3651. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3652. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3653. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3654. ++idx;
  3655. stream && (await sendToWormhole(stream));
  3656. }
  3657. const in_time = new Date();
  3658. const payload = files.map(file => {
  3659. let idx;
  3660. if (Array.isArray(parts.field.name)) {
  3661. idx = parts.field.name.findIndex(name => name === file.name);
  3662. } else {
  3663. idx = 'isString';
  3664. }
  3665. const newFile = {
  3666. tid: ctx.tender.id,
  3667. cpid: ctx.change.id,
  3668. uid: ctx.session.sessionUser.accountId,
  3669. filename: file.name,
  3670. fileext: file.ext,
  3671. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3672. filepath: file.filepath,
  3673. upload_time: in_time,
  3674. extra_upload,
  3675. };
  3676. return newFile;
  3677. });
  3678. // 执行文件信息写入数据库
  3679. await ctx.service.changePlanAtt.saveFileMsgToDb(payload);
  3680. // 将最新的当前标段的所有文件信息返回
  3681. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3682. ctx.body = { err: 0, msg: '', data };
  3683. } catch (err) {
  3684. stream && (await sendToWormhole(stream));
  3685. this.log(err);
  3686. ctx.body = { err: 1, msg: err.toString(), data: null };
  3687. }
  3688. }
  3689. /**
  3690. * 删除附件
  3691. * @param {Ojbect} ctx 上下文
  3692. */
  3693. async deletePlanFile(ctx) {
  3694. try {
  3695. const { id } = JSON.parse(ctx.request.body.data);
  3696. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3697. if (fileInfo || Object.keys(fileInfo).length) {
  3698. // 先删除文件
  3699. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  3700. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  3701. // 再删除数据库
  3702. await ctx.service.changePlanAtt.delete(id);
  3703. } else {
  3704. throw '不存在该文件';
  3705. }
  3706. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3707. ctx.body = { err: 0, msg: '请求成功', data };
  3708. } catch (err) {
  3709. this.log(err);
  3710. ctx.body = { err: 1, msg: err.toString(), data: null };
  3711. }
  3712. }
  3713. /**
  3714. * 下载附件
  3715. * @param {Object} ctx - egg全局变量
  3716. * @return {void}
  3717. */
  3718. async downloadPlanFile(ctx) {
  3719. const id = ctx.params.fid;
  3720. if (id) {
  3721. try {
  3722. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3723. if (fileInfo !== undefined && fileInfo !== '') {
  3724. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  3725. // 解决中文无法下载问题
  3726. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  3727. let disposition = '';
  3728. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  3729. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  3730. } else if (userAgent.indexOf('firefox') >= 0) {
  3731. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  3732. } else {
  3733. /* safari等其他非主流浏览器只能自求多福了 */
  3734. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  3735. }
  3736. ctx.response.set({
  3737. 'Content-Type': 'application/octet-stream',
  3738. 'Content-Disposition': disposition,
  3739. 'Content-Length': fileInfo.filesize,
  3740. });
  3741. // ctx.body = await fs.createReadStream(fileName);
  3742. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  3743. } else {
  3744. throw '不存在该文件';
  3745. }
  3746. } catch (err) {
  3747. this.log(err);
  3748. this.setMessage(err.toString(), this.messageType.ERROR);
  3749. }
  3750. }
  3751. }
  3752. async planInformationSave(ctx) {
  3753. try {
  3754. const data = JSON.parse(ctx.request.body.data);
  3755. if (data.name === 'code') {
  3756. const info = await ctx.service.changePlan.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  3757. if (info) {
  3758. throw '该编号已存在';
  3759. }
  3760. }
  3761. const result = await ctx.service.changePlan.saveInfo(ctx.change.id, data);
  3762. if (!result) {
  3763. throw '修改失败';
  3764. }
  3765. ctx.body = { err: 0, msg: '请求成功', data: null };
  3766. } catch (err) {
  3767. this.log(err);
  3768. ctx.body = { err: 1, msg: err.toString(), data: null };
  3769. }
  3770. }
  3771. /**
  3772. * 上报和重新上报
  3773. * @param ctx
  3774. * @return {Promise<void>}
  3775. */
  3776. async startPlanAudit(ctx) {
  3777. try {
  3778. const auditConst = audit.changePlan;
  3779. // 检查权限等
  3780. if (!ctx.change) {
  3781. throw '数据错误';
  3782. }
  3783. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3784. throw '您无权上报该期数据';
  3785. }
  3786. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3787. throw '该材料调差期数据当前无法上报';
  3788. }
  3789. await ctx.service.changePlanAudit.start(ctx.change.id, ctx.change.times);
  3790. ctx.redirect(ctx.request.header.referer);
  3791. } catch (err) {
  3792. this.log(err);
  3793. ctx.session.postError = err.toString();
  3794. ctx.redirect(ctx.request.header.referer);
  3795. }
  3796. }
  3797. /**
  3798. * 审批
  3799. * @param ctx
  3800. * @return {Promise<void>}
  3801. */
  3802. async checkPlanAudit(ctx) {
  3803. try {
  3804. const auditConst = audit.changePlan;
  3805. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  3806. throw '当前变更方案数据有误';
  3807. }
  3808. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  3809. throw '您无权进行该操作';
  3810. }
  3811. const data = {
  3812. checkType: parseInt(ctx.request.body.checkType),
  3813. opinion: ctx.request.body.opinion,
  3814. };
  3815. if (!data.checkType || isNaN(data.checkType)) {
  3816. throw '提交数据错误';
  3817. }
  3818. // if (data.checkType === auditConst.status.checkNo) {
  3819. // if (!data.checkType || isNaN(data.checkType)) {
  3820. // throw '提交数据错误';
  3821. // }
  3822. // }
  3823. await ctx.service.changePlanAudit.check(ctx.change.id, data, ctx.change.times);
  3824. ctx.redirect(ctx.request.header.referer);
  3825. } catch (err) {
  3826. this.log(err);
  3827. console.log(err);
  3828. ctx.session.postError = err.toString();
  3829. ctx.redirect(ctx.request.header.referer);
  3830. }
  3831. }
  3832. /**
  3833. * 变更清单 - 操作 (Ajax)
  3834. * @param ctx
  3835. * @return {Promise<void>}
  3836. */
  3837. async savePlanListsData(ctx) {
  3838. try {
  3839. const data = JSON.parse(ctx.request.body.data);
  3840. const responseData = {
  3841. err: 0,
  3842. msg: '',
  3843. data: {},
  3844. };
  3845. switch (data.type) {
  3846. case 'add':
  3847. responseData.data = await ctx.service.changePlanList.add(data.updateData);
  3848. break;
  3849. case 'batchadd':
  3850. responseData.data = await ctx.service.changePlanList.batchAdd(data);
  3851. break;
  3852. case 'del':
  3853. await ctx.service.changePlanList.del(data.ids);
  3854. // 取所有工料表
  3855. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  3856. break;
  3857. case 'update':
  3858. // if (data.updateData.code === '' || data.updateData.code === null) {
  3859. // throw '请先输入编号';
  3860. // }
  3861. await ctx.service.changePlanList.save(data.updateData);
  3862. break;
  3863. case 'paste':
  3864. await ctx.service.changePlanList.saveDatas(data.updateData);
  3865. // 取所有工料表
  3866. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  3867. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3868. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3869. for (const cl of responseData.data) {
  3870. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3871. // 清单表页赋值
  3872. for (const [index, au] of listAudits.entries()) {
  3873. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  3874. }
  3875. }
  3876. }
  3877. break;
  3878. case 'list_rule':
  3879. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_plan_list_rule: data.postData });
  3880. if (!result) {
  3881. throw '修改失败';
  3882. }
  3883. break;
  3884. case 'paste_amount_rows':
  3885. await ctx.service.changePlanList.saveDatas(data.updateData);
  3886. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3887. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3888. for (const cl of changeList) {
  3889. // 清单表页赋值
  3890. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3891. // 清单表页赋值
  3892. for (const [index, au] of listAudits.entries()) {
  3893. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  3894. }
  3895. }
  3896. // 取所有工料表
  3897. responseData.data = changeList;
  3898. break;
  3899. // case 'update_tp':
  3900. // await ctx.service.changePlan.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  3901. // break;
  3902. default: throw '参数有误';
  3903. }
  3904. ctx.body = responseData;
  3905. } catch (err) {
  3906. this.log(err);
  3907. ctx.body = { err: 1, msg: err.toString(), data: null };
  3908. }
  3909. }
  3910. /**
  3911. * 撤回审批
  3912. * @param ctx
  3913. * @return {Promise<void>}
  3914. */
  3915. async checkPlanAuditCancel(ctx) {
  3916. try {
  3917. if (!ctx.change.cancancel) throw '您无权进行该操作';
  3918. await ctx.service.changePlanAudit.checkCancel(ctx.change);
  3919. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  3920. } catch (err) {
  3921. this.log(err);
  3922. ctx.body = { err: 1, msg: err };
  3923. }
  3924. }
  3925. /**
  3926. * 变更申请重新审批
  3927. * @param {Object} ctx - egg全局变量
  3928. * @return {void}
  3929. */
  3930. async checkPlanAgain(ctx) {
  3931. try {
  3932. // 获取终审
  3933. // const auditInfo = await this.ctx.service.changePlanAudit.getAuditorByStatus(ctx.change.id, audit.changePlan.status.checked);
  3934. if (ctx.change.status !== audit.changePlan.status.checked) {
  3935. throw '您无权进行该操作';
  3936. }
  3937. // 判断是否被变更申请调用了,是则无法发起修订
  3938. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  3939. if (projectInfo) {
  3940. throw '该变更方案已被变更令调用,无法发起重新审批';
  3941. }
  3942. if (ctx.session.sessionUser.loginStatus === 0) {
  3943. const code = ctx.request.body.code;
  3944. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3945. if (!pa.auth_mobile) {
  3946. throw '未绑定手机号';
  3947. }
  3948. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3949. const cacheCode = await app.redis.get(cacheKey);
  3950. // console.log(cacheCode);
  3951. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3952. throw '验证码不正确!';
  3953. }
  3954. }
  3955. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changePlan.status.checked) {
  3956. // 重新审批
  3957. const result = await ctx.service.changePlanAudit.checkAgain(ctx.change);
  3958. if (!result) {
  3959. throw '重新审批失败';
  3960. }
  3961. } else {
  3962. throw '您无权进行该操作';
  3963. }
  3964. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3965. ctx.body = {
  3966. err: 0,
  3967. url: ctx.request.header.referer,
  3968. msg: '',
  3969. };
  3970. } catch (err) {
  3971. console.log(err);
  3972. // ctx.redirect(ctx.request.header.referer);
  3973. ctx.body = {
  3974. err: 1,
  3975. // url: ctx.request.header.referer,
  3976. msg: err,
  3977. };
  3978. }
  3979. }
  3980. /**
  3981. * 变更申请修订重新上报
  3982. * @param {Object} ctx - egg全局变量
  3983. * @return {void}
  3984. */
  3985. async checkPlanRevise(ctx) {
  3986. try {
  3987. if (ctx.change.status !== audit.changePlan.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  3988. throw '您无权进行该操作';
  3989. }
  3990. // 判断是否被变更申请调用了,是则无法发起修订
  3991. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  3992. if (projectInfo) {
  3993. throw '该变更方案已被变更令调用,无法发起修订';
  3994. }
  3995. if (ctx.session.sessionUser.loginStatus === 0) {
  3996. const code = ctx.request.body.code;
  3997. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3998. if (!pa.auth_mobile) {
  3999. throw '未绑定手机号';
  4000. }
  4001. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  4002. const cacheCode = await app.redis.get(cacheKey);
  4003. // console.log(cacheCode);
  4004. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  4005. throw '验证码不正确!';
  4006. }
  4007. }
  4008. // 重新审批
  4009. const result = await ctx.service.changePlanAudit.checkRevise(ctx.change);
  4010. if (!result) {
  4011. throw '修订发起失败';
  4012. }
  4013. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  4014. ctx.body = {
  4015. err: 0,
  4016. url: ctx.request.header.referer,
  4017. msg: '',
  4018. };
  4019. } catch (err) {
  4020. console.log(err);
  4021. // ctx.redirect(ctx.request.header.referer);
  4022. ctx.body = {
  4023. err: 1,
  4024. // url: ctx.request.header.referer,
  4025. msg: err,
  4026. };
  4027. }
  4028. }
  4029. /**
  4030. * 变更令撤销修订
  4031. * @param {Object} ctx - egg全局变量
  4032. * @return {void}
  4033. */
  4034. async cancelPlanRevise(ctx) {
  4035. try {
  4036. if (!(ctx.change.status === audit.changePlan.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  4037. throw '您无权进行该操作';
  4038. }
  4039. // 重新审批
  4040. const result = await ctx.service.changePlanAudit.cancelRevise(ctx.change);
  4041. if (!result) {
  4042. throw '撤销修订失败';
  4043. }
  4044. ctx.body = {
  4045. err: 0,
  4046. url: ctx.request.header.referer,
  4047. msg: '',
  4048. };
  4049. } catch (err) {
  4050. console.log(err);
  4051. ctx.body = {
  4052. err: 1,
  4053. msg: err,
  4054. };
  4055. }
  4056. }
  4057. }
  4058. return ChangeController;
  4059. };