change_controller.js 216 KB

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