change_controller.js 194 KB

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