change_controller.js 178 KB

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