change_controller.js 216 KB

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