change_controller.js 183 KB

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