change_controller.js 189 KB

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