change_controller.js 220 KB

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