change_controller.js 202 KB

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