change_controller.js 218 KB

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