change_controller.js 213 KB

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