change_controller.js 238 KB

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