change_controller.js 189 KB

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