change_controller.js 176 KB

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