change_controller.js 227 KB

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