change_controller.js 220 KB

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