change_controller.js 176 KB

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