change_controller.js 186 KB

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