change_controller.js 187 KB

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