change_controller.js 177 KB

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