change_controller.js 228 KB

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