change_controller.js 202 KB

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