change_controller.js 202 KB

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