change_controller.js 186 KB

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