change_controller.js 183 KB

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