change_controller.js 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468
  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 && pa.permission ? JSON.parse(pa.permission) : null;
  410. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  411. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  412. const settleBills = ctx.change.readySettle ? await ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: ctx.change.readySettle.id } }) : [];
  413. const settlePos = ctx.change.readySettle ? await ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: ctx.change.readySettle.id } }) : [];
  414. // 判断并是否更新结算清单数据
  415. await ctx.service.change.checkSettleUpdate(ctx.tender.id, ctx.change.readySettle);
  416. // 处理清单数据
  417. const removeSettleNum = change.status !== audit.change.status.checked ? await ctx.service.changeSettleList.updateChangeList(change.cid, settleBills, settlePos, changeList) : 0;
  418. const renderData = {
  419. tender,
  420. change,
  421. othersChange,
  422. changeConst,
  423. changeClass: fun_set.change_class,
  424. changeState: fun_set.change_state,
  425. auditConst: audit.change,
  426. ledgerConsts: audit.ledger.status,
  427. auditType,
  428. auditorGroups: change.userGroups,
  429. attList,
  430. whiteList,
  431. showPlanBtn,
  432. planList,
  433. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  434. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  435. authMobile: auth_mobile,
  436. shenpiConst,
  437. settleStatus: ctx.service.settle.settleStatus,
  438. unitList,
  439. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  440. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  441. precision: ctx.tender.info.precision,
  442. settleBills,
  443. settlePos,
  444. removeSettleNum,
  445. deleteFilePermission,
  446. };
  447. // 获取是否已存在调用变更令
  448. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  449. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  450. return item.qty !== null;
  451. }), ['sorder'], ['desc']);
  452. const useChangeUsedData = [];
  453. if (changeUsedData.length > 0) { // 防止未创建期时调用
  454. for (const cu of changeUsedData) {
  455. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  456. if (index !== -1) {
  457. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  458. } else {
  459. useChangeUsedData.push(cu);
  460. }
  461. }
  462. }
  463. renderData.changeUsedData = useChangeUsedData;
  464. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  465. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  466. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  467. if (!change.readOnly || ctx.session.sessionUser.is_admin) {
  468. // 获取所有项目参与者
  469. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  470. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  471. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  472. });
  473. renderData.accountList = accountList;
  474. renderData.accountGroup = unitList.map(item => {
  475. const groupList = accountList.filter(item1 => item1.company === item.name);
  476. return { groupName: item.name, groupList };
  477. });
  478. renderData.changeUnits = changeConst.units;
  479. // 获取公司列表
  480. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  481. renderData.companyList = companyList;
  482. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: ctx.change.state });
  483. renderData.deLimit = stateInfo.value;
  484. if (stateInfo.value !== ctx.change.delimit) {
  485. // 需要更新所有的计量上限值,除了已调用的值
  486. const updateList = [];
  487. for (const cl of changeList) {
  488. const one = {
  489. id: cl.id,
  490. };
  491. if (useChangeUsedData.length > 0 && ctx.helper._.findIndex(useChangeUsedData, { cbid: cl.id }) !== -1) {
  492. // 获取比例值
  493. const uc = ctx.helper._.find(useChangeUsedData, { cbid: cl.id });
  494. const minLimit = Math.ceil(ctx.helper.mul(ctx.helper.div(uc.qty, cl.camount), 100));
  495. if (minLimit <= renderData.deLimit) {
  496. one.delimit = renderData.deLimit;
  497. cl.delimit = renderData.deLimit;
  498. }
  499. } else if (cl.delimit !== renderData.deLimit) {
  500. one.delimit = renderData.deLimit;
  501. cl.delimit = renderData.deLimit;
  502. }
  503. if (!ctx.helper._.isEqual(one, { id: cl.id })) updateList.push(one);
  504. }
  505. console.log(updateList);
  506. if (updateList.length > 0) await ctx.service.changeAuditList.defaultUpdateRows(updateList);
  507. await ctx.service.change.defaultUpdate({ delimit: stateInfo.value }, { where: { cid: change.cid } });
  508. }
  509. // 判断是否更新变更类别
  510. if (ctx.helper._.findIndex(fun_set.change_class, { value: change.class, checked: true }) === -1) {
  511. renderData.change.class = ctx.helper._.find(fun_set.change_class, { checked: true }).value;
  512. await ctx.service.change.saveInfo({ class: ctx.helper._.find(fun_set.change_class, { checked: true }).value });
  513. }
  514. // 获取固定审批流列表
  515. if (tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  516. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(tender.id, shenpiConst.sp_type.change, 'change');
  517. }
  518. }
  519. renderData.changeList = changeList;
  520. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  521. } catch (err) {
  522. this.log(err);
  523. ctx.session.postError = err.toString();
  524. ctx.redirect('/tender/' + ctx.params.id + '/change');
  525. }
  526. }
  527. /**
  528. * 变更关联数据 - 操作 (Ajax)
  529. * @param ctx
  530. * @return {Promise<void>}
  531. */
  532. async relation(ctx) {
  533. try {
  534. if (!ctx.session.sessionProject.page_show.openChangePlan) {
  535. throw '该功能已关闭';
  536. }
  537. // await this._getChangeAuditViewData(ctx);
  538. const tender = ctx.tender;
  539. const change = ctx.change;
  540. const renderData = {
  541. tender,
  542. change,
  543. };
  544. renderData.changePlanInfo = null;
  545. renderData.changeApplyInfo = null;
  546. renderData.changeProjectInfo = null;
  547. if (change.plan_code) {
  548. renderData.changePlanInfo = await ctx.service.changePlan.getDataByCondition({ tid: tender.id, code: change.plan_code });
  549. if (renderData.changePlanInfo && renderData.changePlanInfo.apply_code) {
  550. renderData.changeApplyInfo = await ctx.service.changeApply.getDataByCondition({ tid: tender.id, code: renderData.changePlanInfo.apply_code });
  551. if (renderData.changeApplyInfo && renderData.changeApplyInfo.project_code) {
  552. renderData.changeProjectInfo = await ctx.service.changeProject.getDataByCondition({ tid: tender.id, code: renderData.changeApplyInfo.project_code });
  553. }
  554. }
  555. }
  556. await this.layout('change/relation.ejs', renderData);
  557. } catch (err) {
  558. this.log(err);
  559. ctx.session.postError = err.toString();
  560. ctx.redirect('/tender/' + ctx.params.id + '/change');
  561. }
  562. }
  563. /**
  564. * 变更清单 - 操作 (Ajax)
  565. * @param ctx
  566. * @return {Promise<void>}
  567. */
  568. async saveListsData(ctx) {
  569. try {
  570. const data = JSON.parse(ctx.request.body.data);
  571. const responseData = {
  572. err: 0,
  573. msg: '',
  574. data: {},
  575. };
  576. switch (data.type) {
  577. case 'add':
  578. case 'batchadd':
  579. if (!ctx.session.sessionProject.page_show.openChangeWhiteList) {
  580. throw '空白清单添加功能未开启。';
  581. }
  582. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  583. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  584. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: ctx.change.state });
  585. if (data.type === 'add') {
  586. responseData.data = await ctx.service.changeAuditList.add(data.postData, stateInfo.value);
  587. } else {
  588. responseData.data = await ctx.service.changeAuditList.batchAdd(data, stateInfo.value);
  589. }
  590. break;
  591. case 'del':
  592. await ctx.service.changeAuditList.del(data);
  593. break;
  594. case 'update':
  595. await ctx.service.changeAuditList.save(data.updateData);
  596. break;
  597. case 'paste':
  598. await ctx.service.changeAuditList.saveDatas(data.updateData);
  599. // 取所有工料表
  600. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  601. break;
  602. case 'ledger_list':
  603. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData, data.postData);
  604. // 取所有工料表
  605. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  606. usedList: await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, ctx.change.cid) };
  607. break;
  608. case 'remove_list':
  609. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  610. // 取所有工料表
  611. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  612. break;
  613. case 'update_list':
  614. await ctx.service.changeAuditList.saveDatas(data.updateData);
  615. // 取所有工料表
  616. // responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  617. break;
  618. case 'info':
  619. let value = 100;
  620. if (data.updateData.state && parseInt(data.updateData.state) !== ctx.change.state) {
  621. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  622. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  623. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: parseInt(data.updateData.state) });
  624. value = stateInfo.value;
  625. }
  626. responseData.data = await ctx.service.change.saveInfo(data.updateData, value);
  627. // 取所有工料表
  628. // responseData.data = '保存成功';
  629. break;
  630. case 'paste_amount_rows':
  631. await ctx.service.changeAuditList.saveDatas(data.updateData);
  632. const changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  633. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  634. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  635. for (const cl of changeList) {
  636. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  637. // 清单表页赋值
  638. for (const [index, au] of auditList2.entries()) {
  639. if (au.usite !== 0) {
  640. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  641. }
  642. }
  643. }
  644. // 取所有工料表
  645. responseData.data = changeList;
  646. break;
  647. case 'update_tp':
  648. await ctx.service.change.saveInfo(data.updateData);
  649. break;
  650. case 'order_by':
  651. const result = await ctx.service.change.saveOrderBy(data.updateData, data.newLedgerList);
  652. responseData.data = result;
  653. break;
  654. case 'order_site':
  655. await ctx.service.change.defaultUpdate({ order_site: data.listid }, { where: { cid: ctx.change.cid } });
  656. break;
  657. case 'changeOrder':
  658. await ctx.service.changeAuditList.changeOrder(data.postData);
  659. break;
  660. case 'set_all_valuation':
  661. await ctx.service.changeAuditList.setAllValuation(ctx.change.cid, data.ids, data.is_valuation);
  662. // 取所有工料表
  663. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  664. break;
  665. // 从新增部位页新增清单
  666. case 'add-change-list':
  667. if (ctx.change.status !== audit.change.status.uncheck && ctx.change.status !== audit.change.status.checkNo && ctx.change.status !== audit.change.status.revise) {
  668. throw '该变更令正在审批中或已完成,无法操作清单数据';
  669. }
  670. await ctx.service.changeAuditList.adds(data.postData);
  671. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid) };
  672. break;
  673. // 从新增部位页删除清单
  674. case 'del-change-list':
  675. if (ctx.change.status !== audit.change.status.uncheck && ctx.change.status !== audit.change.status.checkNo && ctx.change.status !== audit.change.status.revise) {
  676. throw '该变更令正在审批中或已完成,无法操作清单数据';
  677. }
  678. await ctx.service.changeAuditList.dels(data);
  679. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid) };
  680. break;
  681. case 'get-revise-list':
  682. responseData.data.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  683. responseData.data.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  684. break;
  685. default: throw '参数有误';
  686. }
  687. ctx.body = responseData;
  688. } catch (err) {
  689. this.log(err);
  690. ctx.body = { err: 1, msg: err.toString(), data: null };
  691. }
  692. }
  693. /**
  694. * 上报和重新上报
  695. * @param ctx
  696. * @return {Promise<void>}
  697. */
  698. async startAudit(ctx) {
  699. const responseData = {
  700. err: 0,
  701. msg: '',
  702. data: {},
  703. };
  704. try {
  705. // 检查权限等
  706. if (!ctx.change) {
  707. throw '数据错误';
  708. }
  709. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  710. throw '您无权上报该变更令数据';
  711. }
  712. if (!(ctx.change.status === audit.change.status.uncheck || ctx.change.status === audit.change.status.checkNo || ctx.change.status === audit.change.status.revise)) {
  713. throw '该变更令当前无法上报';
  714. }
  715. // 判断是否是修订,判断有无审批人员作弊
  716. if ((ctx.change.status === audit.change.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  717. // 获取上一次的审批人流程
  718. const lastUserList = await ctx.service.changeAudit.getUniqAuditor(ctx.change.cid, ctx.change.times - 1);
  719. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  720. // 判断上一次审批是否为非原报为审批人
  721. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  722. // 判断条件修订可上报条件
  723. // 1.有原报,不管有无其他人 可以添加原报作为审核人,但是不能只原报上报
  724. // 2.无原报,有其他人 不可以添加原报
  725. // const noYBUidList = ctx.change.status === audit.change.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  726. const noYBUidList = ctx.helper._.tail(lastUidList);
  727. // if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  728. if (nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  729. throw '该变更令不能指定原报人为单独审批人';
  730. }
  731. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  732. throw '该变更令不能指定原报为审批人,请移除';
  733. }
  734. }
  735. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  736. // ctx.redirect(ctx.request.header.referer);
  737. ctx.body = responseData;
  738. } catch (err) {
  739. this.log(err);
  740. // ctx.session.postError = err.toString();
  741. // ctx.redirect(ctx.request.header.referer);
  742. ctx.body = { err: 1, msg: err.toString(), data: null };
  743. }
  744. }
  745. // 审批相关
  746. /**
  747. * 添加审批人
  748. * @param ctx
  749. * @return {Promise<void>}
  750. */
  751. async addAudit(ctx) {
  752. try {
  753. const data = JSON.parse(ctx.request.body.data);
  754. const id = this.app._.toInteger(data.auditorId);
  755. if (isNaN(id) || id <= 0) {
  756. throw '参数错误';
  757. }
  758. // 检查权限等
  759. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  760. throw '您无权添加审核人';
  761. }
  762. if (ctx.change.status === audit.change.status.checking || ctx.change.status === audit.change.status.checked) {
  763. throw '当前不允许添加审核人';
  764. }
  765. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  766. // 检查审核人是否已存在
  767. const exist = this.app._.find(auditorList, { uid: id });
  768. if (exist) {
  769. throw '该审核人已存在,请勿重复添加';
  770. }
  771. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  772. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  773. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  774. if (!result) {
  775. throw '添加审核人失败';
  776. }
  777. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  778. ctx.body = { err: 0, msg: '', data: auditors };
  779. } catch (err) {
  780. this.log(err);
  781. ctx.body = { err: 1, msg: err.toString(), data: null };
  782. }
  783. }
  784. /**
  785. * 移除审批人
  786. * @param ctx
  787. * @return {Promise<void>}
  788. */
  789. async deleteAudit(ctx) {
  790. try {
  791. const data = JSON.parse(ctx.request.body.data);
  792. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  793. if (isNaN(id) || id <= 0) {
  794. throw '参数错误';
  795. }
  796. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  797. if (!result) {
  798. throw '移除审核人失败';
  799. }
  800. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  801. ctx.body = { err: 0, msg: '', data: auditors };
  802. } catch (err) {
  803. ctx.body = { err: 1, msg: err.toString(), data: null };
  804. }
  805. }
  806. async changeSpGroup(ctx) {
  807. try {
  808. const data = JSON.parse(ctx.request.body.data);
  809. const result = await ctx.service.changeAudit.changeSpGroup(ctx.change, data.sp_group);
  810. if (!result) {
  811. throw '切换审批组失败';
  812. }
  813. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  814. ctx.body = { err: 0, msg: '', data: auditors };
  815. } catch (err) {
  816. ctx.body = { err: 1, msg: err.toString(), data: null };
  817. }
  818. }
  819. async defaultBills(ctx) {
  820. try {
  821. // 判断是否台账修订中,修订中则不获取changeLedger及changePos值
  822. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  823. const data = JSON.parse(ctx.request.body.data);
  824. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  825. if (data.from === 'revise') await ctx.service.change.checkSettleUpdate(ctx.tender.id, readySettle);
  826. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  827. 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));
  828. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  829. 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 }));
  830. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  831. // const settleStatus = ctx.service.settle.settleStatus;
  832. const settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  833. const stages = data.from === 'revise' ? await ctx.service.stage.getAllDataByCondition({
  834. where: { tid: ctx.tender.id },
  835. orders: [['order', 'desc']],
  836. }) : [];
  837. if (stages.length > 0) {
  838. const usedBills = [], usedPos = [];
  839. for (const s of stages) {
  840. if (s.status === audit.stage.status.checked) {
  841. const usedPreBills = await ctx.service.stageBillsFinal.getUsedBills(ctx.tender.id, s.order);
  842. usedBills.push(...usedPreBills);
  843. const usedPrePos = await ctx.service.stagePosFinal.getUsedPos(ctx.tender.id, s.order);
  844. usedPos.push(...usedPrePos);
  845. break;
  846. } else {
  847. const usedCurBills = await ctx.service.stageBills.getStageUsedBills(ctx.tender.id, s.id);
  848. usedBills.push(...usedCurBills);
  849. const usedCurPos = await ctx.service.stagePos.getStageUsedPos(ctx.tender.id, s.id);
  850. usedPos.push(...usedCurPos);
  851. }
  852. }
  853. for (const b of ledgerData) {
  854. b.used = usedBills.indexOf(b.id) >= 0;
  855. }
  856. for (const p of posData) {
  857. p.used = usedPos.indexOf(p.id) >= 0;
  858. }
  859. }
  860. ctx.helper.assignRelaData(ledgerData, [
  861. { data: settleBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  862. ]);
  863. const settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  864. this.ctx.helper.assignRelaData(posData, [
  865. { data: settlePos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  866. { data: settlePos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  867. ]);
  868. // 标记ledger,搜索需求
  869. if (changePosData.length > 0) {
  870. const cplIdList = ctx.helper._.uniq(ctx.helper._.map(changePosData, 'lid'));
  871. const cLIdList = ctx.helper._.map(changeLedgerData, 'id');
  872. const ledgerIdList = [];
  873. for (const cp of cplIdList) {
  874. if (ctx.helper._.indexOf(cLIdList, cp) === -1) {
  875. ledgerIdList.push(cp);
  876. }
  877. }
  878. if (ledgerIdList.length > 0) {
  879. for (const lid of ledgerIdList) {
  880. const data = ctx.helper._.find(ledgerData, { id: lid });
  881. if (data) data.cid = 1;
  882. }
  883. }
  884. }
  885. const bodyData = { bills: ctx.helper._.concat(ledgerData, changeLedgerData), pos: ctx.helper._.concat(posData, changePosData), dealBills };
  886. if (data.from === 'batch') {
  887. bodyData.changeLedgerList = changeLedgerData;
  888. bodyData.changePosList = changePosData;
  889. }
  890. ctx.body = { err: 0, msg: '', data: bodyData };
  891. } catch (err) {
  892. console.log(err);
  893. this.log(err);
  894. ctx.body = { err: 1, msg: err.toString(), data: [] };
  895. }
  896. }
  897. /**
  898. * 变更令上报和保存
  899. * @param {Object} ctx - egg全局变量
  900. * @return {void}
  901. */
  902. async save(ctx) {
  903. // 变更令信息
  904. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  905. try {
  906. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  907. if (!result) {
  908. throw '上报失败';
  909. }
  910. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  911. ctx.body = { err: 0, msg: '保存成功' };
  912. } else {
  913. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  914. }
  915. } catch (err) {
  916. this.log(err);
  917. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  918. ctx.body = { err: 1, msg: err.toString() };
  919. } else {
  920. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  921. }
  922. }
  923. }
  924. /**
  925. * 变更令审批
  926. * @param {Object} ctx - egg全局变量
  927. * @return {void}
  928. */
  929. async approval(ctx) {
  930. const data = JSON.parse(ctx.request.body.data);
  931. const responseData = {
  932. err: 0,
  933. msg: '',
  934. data: {},
  935. };
  936. try {
  937. const changeData = await ctx.service.change.getDataByCondition({ cid: data.change_id });
  938. if (!changeData) {
  939. throw '变更令数据错误';
  940. }
  941. const status = parseInt(data.status);
  942. // 判断是否到你审批,如果不是则无法审批
  943. const curAuditor = await ctx.service.changeAudit.getCurAuditors(changeData.cid, changeData.times);
  944. if (!curAuditor || (curAuditor && ctx.helper._.findIndex(curAuditor, { uid: ctx.session.sessionUser.accountId }) === -1)) {
  945. throw '该变更令当前您无权操作';
  946. }
  947. const readySettle = await ctx.service.settle.getReadySettle(changeData.tid);
  948. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  949. throw '结算数据发生变化,请刷新页面再提交';
  950. }
  951. let result = false;
  952. const pid = this.ctx.session.sessionProject.id;
  953. switch (status) {
  954. case 3:// 审批通过
  955. result = await ctx.service.change.approvalSuccess(pid, data, changeData);
  956. break;
  957. // case 4:// 审批终止
  958. // result = await ctx.service.change.approvalStop(ctx.request.body);
  959. // break;
  960. case 5:// 审批退回到原报人
  961. result = await ctx.service.change.approvalCheckNo(pid, data, changeData);
  962. break;
  963. case 6:// 审批退回到上一个审批人
  964. result = await ctx.service.change.approvalCheckNoPre(pid, data, changeData);
  965. break;
  966. default:break;
  967. }
  968. if (!result) {
  969. throw '审批失败';
  970. }
  971. ctx.body = responseData;
  972. } catch (err) {
  973. console.log(err);
  974. // ctx.session.postError = err.toString();
  975. // ctx.redirect(ctx.request.header.referer);
  976. ctx.body = { err: 1, msg: err.toString(), data: null };
  977. }
  978. }
  979. /**
  980. * 撤回审批
  981. * @param ctx
  982. * @return {Promise<void>}
  983. */
  984. async checkAuditCancel(ctx) {
  985. try {
  986. if (!ctx.change.cancancel) throw '您无权进行该操作';
  987. if (ctx.change.readySettle && ctx.change.readySettle.settle_order !== ctx.tender.data.settle_order) {
  988. throw '结算数据发生变化,请刷新页面再提交';
  989. }
  990. await ctx.service.changeAudit.checkCancel(ctx.change);
  991. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  992. } catch (err) {
  993. this.log(err);
  994. ctx.body = { err: 1, msg: err };
  995. }
  996. }
  997. /**
  998. * 变更公司管理
  999. * @param {Object} ctx - egg全局变量
  1000. * @return {void}
  1001. */
  1002. async updateCompany(ctx) {
  1003. const responseData = {
  1004. err: 0,
  1005. msg: '',
  1006. data: '',
  1007. };
  1008. try {
  1009. const data = JSON.parse(ctx.request.body.data);
  1010. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1011. throw '参数有误';
  1012. }
  1013. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1014. responseData.data = { add: addCompany, select: selectCompany };
  1015. } catch (err) {
  1016. responseData.err = 1;
  1017. responseData.msg = err;
  1018. }
  1019. ctx.body = responseData;
  1020. }
  1021. /**
  1022. * 上传附件
  1023. * @param {Object} ctx - egg全局变量
  1024. * @return {void}
  1025. */
  1026. async uploadFile(ctx) {
  1027. const responseData = {
  1028. err: 0,
  1029. msg: '',
  1030. data: [],
  1031. };
  1032. let stream;
  1033. try {
  1034. const parts = ctx.multipart({ autoFields: true });
  1035. const files = [];
  1036. let index = 0;
  1037. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1038. const extra_upload = change.status === audit.change.status.checked;
  1039. while ((stream = await parts()) !== undefined) {
  1040. // 判断用户是否选择上传文件
  1041. if (!stream.filename) {
  1042. throw '请选择上传的文件!';
  1043. }
  1044. // const create_time = Date.parse(new Date()) / 1000;
  1045. // const fileInfo = path.parse(stream.filename);
  1046. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  1047. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  1048. // // 判断文件夹是否存在,不存在则直接创建文件夹
  1049. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  1050. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  1051. // }
  1052. // // 保存文件
  1053. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1054. const fileInfo = path.parse(stream.filename);
  1055. const create_time = Date.parse(new Date()) / 1000;
  1056. // const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1057. const filepath = `app/public/upload/${parts.field.tid}/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1058. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1059. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  1060. await sendToWormhole(stream);
  1061. // 保存数据到att表
  1062. const fileData = {
  1063. in_time: create_time,
  1064. filename: fileInfo.name,
  1065. fileext: fileInfo.ext,
  1066. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1067. filepath,
  1068. extra_upload,
  1069. };
  1070. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1071. if (!result) {
  1072. throw '导入数据库保存失败';
  1073. }
  1074. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1075. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1076. fileData.uid = ctx.session.sessionUser.accountId;
  1077. fileData.id = result.insertId;
  1078. fileData.orginpath = ctx.app.config.fujianOssPath + filepath;
  1079. delete fileData.filepath;
  1080. if (!ctx.helper.canPreview(fileData.fileext)) {
  1081. fileData.filepath = `/change/download/file/${fileData.id}`;
  1082. } else {
  1083. fileData.filepath = ctx.app.config.fujianOssPath + filepath;
  1084. }
  1085. files.push(fileData);
  1086. ++index;
  1087. }
  1088. responseData.data = files;
  1089. } catch (err) {
  1090. this.log(err);
  1091. // 失败需要消耗掉stream 以防卡死
  1092. if (stream) {
  1093. await sendToWormhole(stream);
  1094. }
  1095. this.setMessage(err.toString(), this.messageType.ERROR);
  1096. }
  1097. ctx.body = responseData;
  1098. }
  1099. /**
  1100. * 下载附件
  1101. * @param {Object} ctx - egg全局变量
  1102. * @return {void}
  1103. */
  1104. async downloadFile(ctx) {
  1105. const id = ctx.params.id;
  1106. if (id) {
  1107. try {
  1108. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1109. if (fileInfo !== undefined && fileInfo !== '') {
  1110. // const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1111. // 解决中文无法下载问题
  1112. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1113. let disposition = '';
  1114. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1115. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1116. } else if (userAgent.indexOf('firefox') >= 0) {
  1117. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1118. } else {
  1119. /* safari等其他非主流浏览器只能自求多福了 */
  1120. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1121. }
  1122. ctx.response.set({
  1123. 'Content-Type': 'application/octet-stream',
  1124. 'Content-Disposition': disposition,
  1125. 'Content-Length': fileInfo.filesize,
  1126. });
  1127. // ctx.body = await fs.createReadStream(fileName);
  1128. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1129. } else {
  1130. throw '不存在该文件';
  1131. }
  1132. } catch (err) {
  1133. this.log(err);
  1134. this.setMessage(err.toString(), this.messageType.ERROR);
  1135. }
  1136. }
  1137. }
  1138. /**
  1139. * 批量下载 - 压缩成zip文件返回
  1140. * @param {Oject} ctx - 全局上下文
  1141. */
  1142. async downloadZip(ctx) {
  1143. const time = Date.now();
  1144. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1145. const responseData = {
  1146. err: 0,
  1147. msg: '',
  1148. };
  1149. try {
  1150. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1151. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1152. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1153. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1154. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1155. // 解决中文无法下载问题
  1156. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1157. let disposition = '';
  1158. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1159. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1160. } else if (userAgent.indexOf('firefox') >= 0) {
  1161. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1162. } else {
  1163. /* safari等其他非主流浏览器只能自求多福了 */
  1164. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1165. }
  1166. ctx.response.set({
  1167. 'Content-Type': 'application/octet-stream',
  1168. 'Content-Disposition': disposition,
  1169. 'Content-Length': size,
  1170. });
  1171. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1172. ctx.body = readStream;
  1173. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1174. readStream.on('close', () => {
  1175. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1176. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1177. }
  1178. });
  1179. // fs的错误不能被try catch捕捉
  1180. readStream.on('error', err => {
  1181. this.log(err);
  1182. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1183. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1184. }
  1185. responseData.err = 1;
  1186. responseData.msg = err.toString();
  1187. ctx.body = responseData;
  1188. });
  1189. } catch (err) {
  1190. this.log(err);
  1191. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1192. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1193. }
  1194. this.setMessage(err.toString(), this.messageType.ERROR);
  1195. responseData.err = 1;
  1196. responseData.msg = err.toString();
  1197. ctx.body = responseData;
  1198. }
  1199. }
  1200. /**
  1201. * 删除附件
  1202. * @param {Object} ctx - egg全局变量
  1203. * @return {void}
  1204. */
  1205. async deleteFile(ctx) {
  1206. const responseData = {
  1207. err: 0,
  1208. msg: '',
  1209. data: '',
  1210. };
  1211. try {
  1212. const data = JSON.parse(ctx.request.body.data);
  1213. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1214. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1215. if (!fileInfo || !Object.keys(fileInfo).length) {
  1216. throw '该文件不存在';
  1217. }
  1218. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1219. const userPermission = accountInfo && accountInfo.permission ? JSON.parse(accountInfo.permission) : null;
  1220. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  1221. if (!fileInfo.extra_upload && change.status === audit.change.status.checked && !deleteFilePermission) {
  1222. throw '无权限删除';
  1223. }
  1224. if (fileInfo !== undefined && fileInfo !== '') {
  1225. // 先删除文件
  1226. // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1227. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  1228. // 再删除数据库
  1229. await ctx.service.changeAtt.deleteById(data.id);
  1230. responseData.data = '';
  1231. } else {
  1232. throw '不存在该文件';
  1233. }
  1234. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1235. // throw '参数有误';
  1236. // }
  1237. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1238. // responseData.data = { add: addCompany, select: selectCompany };
  1239. } catch (err) {
  1240. responseData.err = 1;
  1241. responseData.msg = err;
  1242. }
  1243. ctx.body = responseData;
  1244. }
  1245. /**
  1246. * 查看附件
  1247. * @param {Object} ctx - egg全局变量
  1248. * @return {void}
  1249. */
  1250. async checkFile(ctx) {
  1251. const responseData = { err: 0, msg: '' };
  1252. const id = parseInt(ctx.params.id);
  1253. if (id) {
  1254. try {
  1255. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1256. if (fileInfo && Object.keys(fileInfo).length) {
  1257. let filepath = fileInfo.filepath;
  1258. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1259. filepath = `/change/download/file/${fileInfo.id}`;
  1260. } else {
  1261. filepath = filepath.replace(/^app|\/app/, '');
  1262. }
  1263. fileInfo.filepath && (responseData.data = { filepath });
  1264. }
  1265. } catch (error) {
  1266. this.log(error);
  1267. this.setMessage(error.toString(), this.messageType.ERROR);
  1268. responseData.err = 1;
  1269. responseData.msg = error.toString();
  1270. }
  1271. }
  1272. ctx.body = responseData;
  1273. }
  1274. /**
  1275. * 删除变更令
  1276. * @param {Object} ctx - egg全局变量
  1277. * @return {void}
  1278. */
  1279. async delete(ctx) {
  1280. try {
  1281. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1282. if (!result) {
  1283. throw '删除变更令失败';
  1284. }
  1285. ctx.redirect(ctx.request.header.referer);
  1286. } catch (err) {
  1287. console.log(err);
  1288. ctx.redirect(ctx.request.header.referer);
  1289. }
  1290. }
  1291. /**
  1292. * 变更令重新审批
  1293. * @param {Object} ctx - egg全局变量
  1294. * @return {void}
  1295. */
  1296. async checkAgain(ctx) {
  1297. try {
  1298. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1299. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1300. throw '结算数据发生变化,请刷新页面再提交';
  1301. }
  1302. if (ctx.session.sessionUser.loginStatus === 0) {
  1303. const code = ctx.request.body.code;
  1304. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1305. if (!pa.auth_mobile) {
  1306. throw '未绑定手机号';
  1307. }
  1308. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1309. const cacheCode = await app.redis.get(cacheKey);
  1310. // console.log(cacheCode);
  1311. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1312. throw '验证码不正确!';
  1313. }
  1314. }
  1315. // 重新审批
  1316. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.change.status.checked) {
  1317. const result = await ctx.service.change.checkAgain(ctx.change);
  1318. if (!result) {
  1319. throw '重新审批失败';
  1320. }
  1321. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1322. ctx.body = {
  1323. err: 0,
  1324. url: ctx.request.header.referer,
  1325. msg: '',
  1326. };
  1327. } else {
  1328. throw '您无权进行该操作';
  1329. }
  1330. } catch (err) {
  1331. console.log(err);
  1332. // ctx.redirect(ctx.request.header.referer);
  1333. ctx.body = {
  1334. err: 1,
  1335. // url: ctx.request.header.referer,
  1336. msg: err,
  1337. };
  1338. }
  1339. }
  1340. /**
  1341. * 变更令修订重新上报
  1342. * @param {Object} ctx - egg全局变量
  1343. * @return {void}
  1344. */
  1345. async checkRevise(ctx) {
  1346. try {
  1347. if (ctx.change.status !== audit.change.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  1348. throw '您无权进行该操作';
  1349. }
  1350. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1351. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1352. throw '结算数据发生变化,请刷新页面再提交';
  1353. }
  1354. if (ctx.session.sessionUser.loginStatus === 0) {
  1355. const code = ctx.request.body.code;
  1356. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1357. if (!pa.auth_mobile) {
  1358. throw '未绑定手机号';
  1359. }
  1360. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1361. const cacheCode = await app.redis.get(cacheKey);
  1362. // console.log(cacheCode);
  1363. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1364. throw '验证码不正确!';
  1365. }
  1366. }
  1367. // 获取是否已存在调用变更令
  1368. // const changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, changeData.cid);
  1369. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  1370. // if (stageChangeNum !== 0) {
  1371. // throw '该变更令已被调用,无法重新审批';
  1372. // }
  1373. // 重新审批
  1374. const result = await ctx.service.change.checkRevise(ctx.change);
  1375. if (!result) {
  1376. throw '修订发起失败';
  1377. }
  1378. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1379. ctx.body = {
  1380. err: 0,
  1381. url: ctx.request.header.referer,
  1382. msg: '',
  1383. };
  1384. } catch (err) {
  1385. console.log(err);
  1386. // ctx.redirect(ctx.request.header.referer);
  1387. ctx.body = {
  1388. err: 1,
  1389. // url: ctx.request.header.referer,
  1390. msg: err,
  1391. };
  1392. }
  1393. }
  1394. /**
  1395. * 变更令撤销修订
  1396. * @param {Object} ctx - egg全局变量
  1397. * @return {void}
  1398. */
  1399. async cancelRevise(ctx) {
  1400. try {
  1401. if (!(ctx.change.status === audit.change.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  1402. throw '您无权进行该操作';
  1403. }
  1404. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1405. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1406. throw '结算数据发生变化,请刷新页面再提交';
  1407. }
  1408. // 重新审批
  1409. const result = await ctx.service.change.cancelRevise(ctx.change.cid, ctx.change.times);
  1410. if (!result) {
  1411. throw '撤销修订失败';
  1412. }
  1413. ctx.body = {
  1414. err: 0,
  1415. url: ctx.request.header.referer,
  1416. msg: '',
  1417. };
  1418. } catch (err) {
  1419. console.log(err);
  1420. ctx.body = {
  1421. err: 1,
  1422. msg: err,
  1423. };
  1424. }
  1425. }
  1426. async saveAudit(ctx) {
  1427. try {
  1428. // if (ctx.change.revising) {
  1429. // throw '台账修订中,请勿修改提交期数据';
  1430. // }
  1431. const data = JSON.parse(ctx.request.body.data);
  1432. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  1433. await ctx.service.changeAudit.saveAudit(ctx.change.cid, ctx.change.times, ctx.change.sp_group, data);
  1434. const auditors = await ctx.service.changeAudit.getUniqUserGroup(ctx.change.cid, ctx.change.times);
  1435. ctx.body = { err: 0, msg: '', data: auditors };
  1436. } else {
  1437. throw '您无权进行该操作';
  1438. }
  1439. } catch (err) {
  1440. this.log(err);
  1441. // ctx.session.postError = err.toString();
  1442. // ctx.redirect(ctx.request.header.referer);
  1443. ctx.body = {
  1444. err: 1,
  1445. // url: ctx.request.header.referer,
  1446. msg: err,
  1447. };
  1448. }
  1449. }
  1450. /**
  1451. * 获取变更清单
  1452. * @param ctx
  1453. * @return {Promise<void>}
  1454. */
  1455. async bills(ctx) {
  1456. try {
  1457. const data = JSON.parse(ctx.request.body.data);
  1458. const responseData = { err: 0, msg: '', data: [] };
  1459. switch (data.type) {
  1460. case 'gather':
  1461. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1462. break;
  1463. default:
  1464. throw '查询的数据不存在';
  1465. }
  1466. ctx.body = responseData;
  1467. } catch (err) {
  1468. this.log(err);
  1469. this.ajaxErrorBody(err, '获取变更清单失败');
  1470. }
  1471. }
  1472. /**
  1473. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1474. * @param ctx
  1475. * @return {Promise<void>}
  1476. */
  1477. async checkCodeRepeat(ctx) {
  1478. const responseData = {
  1479. err: 0,
  1480. msg: '',
  1481. data: '',
  1482. };
  1483. try {
  1484. const tenderId = ctx.params.id;
  1485. const cid = ctx.params.cid;
  1486. const data = JSON.parse(ctx.request.body.data);
  1487. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1488. if (result) {
  1489. throw '该变更令号(批复编号)已使用';
  1490. }
  1491. } catch (err) {
  1492. responseData.err = 1;
  1493. responseData.msg = err;
  1494. }
  1495. ctx.body = responseData;
  1496. }
  1497. /**
  1498. * 拷贝其他变更令
  1499. * @param {object} ctx - 全局上下文
  1500. */
  1501. async copyChange(ctx) {
  1502. const responseData = {
  1503. err: 0,
  1504. msg: '',
  1505. data: '',
  1506. };
  1507. try {
  1508. const cid = ctx.params.cid;
  1509. const copy_cid = JSON.parse(ctx.request.body.data);
  1510. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1511. if (!result) {
  1512. responseData.err = 1;
  1513. responseData.msg = '拷贝失败!';
  1514. }
  1515. } catch (error) {
  1516. responseData.err = 1;
  1517. responseData.msg = error;
  1518. }
  1519. ctx.body = responseData;
  1520. }
  1521. /**
  1522. * 修订 详细页面(添加台账清单-台账模式)(Get)
  1523. * @param ctx
  1524. * @return {Promise<void>}
  1525. */
  1526. async reviseInfo(ctx) {
  1527. try {
  1528. // if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1529. // throw '该功能已关闭';
  1530. // }
  1531. const change = ctx.change;
  1532. let edit = true;
  1533. let changing = false;
  1534. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1535. // throw '本条变更审批中或已完成,无法操作台账数据';
  1536. edit = false;
  1537. changing = true;
  1538. }
  1539. let revising = false;
  1540. // 判断是否在修订中,是则无法操作本页
  1541. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1542. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1543. // throw '台账修订中,无法操作台账数据';
  1544. edit = false;
  1545. revising = true;
  1546. }
  1547. change.order_site_msg = change.order_site ? await ctx.service.changeAuditList.getDataById(change.order_site) : null;
  1548. const renderData = await this._getDefaultReviseInfoData(ctx, change, !edit);
  1549. // 获取原报dsk数据
  1550. const accountInfo = await ctx.service.projectAccount.getDataById(change.uid);
  1551. renderData.changeList = await ctx.service.changeAuditList.getList(change.cid);
  1552. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  1553. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  1554. return item.qty !== null;
  1555. }), ['sorder'], ['desc']);
  1556. const useChangeUsedData = [];
  1557. if (changeUsedData.length > 0) { // 防止未创建期时调用
  1558. for (const cu of changeUsedData) {
  1559. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  1560. if (index !== -1) {
  1561. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  1562. } else {
  1563. useChangeUsedData.push(cu);
  1564. }
  1565. }
  1566. }
  1567. renderData.changeUsedData = useChangeUsedData;
  1568. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  1569. renderData.settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1570. renderData.settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1571. renderData.dskAccountData = accountInfo && accountInfo.dsk_account ? JSON.parse(accountInfo.dsk_account) : {};
  1572. renderData.dskProjects = accountInfo && accountInfo.dsk_account && accountInfo.dsk_projects ? JSON.parse(accountInfo.dsk_projects) : [];
  1573. // 台账只读、使用数据
  1574. renderData.readOnly = !edit;
  1575. renderData.changing = changing;
  1576. renderData.revising = revising;
  1577. renderData.isYb = change.uid === ctx.session.sessionUser.accountId;
  1578. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1579. } catch (err) {
  1580. this.log(err);
  1581. ctx.redirect(ctx.request.header.referer);
  1582. }
  1583. }
  1584. /**
  1585. * 修订 详细页面(添加台账清单-清单模式)(Get)
  1586. * @param ctx
  1587. * @return {Promise<void>}
  1588. */
  1589. async addListInfo(ctx) {
  1590. try {
  1591. const change = ctx.change;
  1592. let edit = true;
  1593. let changing = false;
  1594. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1595. // throw '本条变更审批中或已完成,无法操作台账数据';
  1596. edit = false;
  1597. changing = true;
  1598. }
  1599. change.order_site_msg = change.order_site ? await ctx.service.changeAuditList.getDataById(change.order_site) : null;
  1600. const renderData = {
  1601. change,
  1602. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  1603. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  1604. precision: ctx.tender.info.precision,
  1605. tender: ctx.tender.data,
  1606. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1607. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.addList),
  1608. auditConst: audit.change,
  1609. settleStatus: ctx.service.settle.settleStatus,
  1610. };
  1611. // 获取原报dsk数据
  1612. const accountInfo = await ctx.service.projectAccount.getDataById(change.uid);
  1613. renderData.changeList = await ctx.service.changeAuditList.getList(change.cid);
  1614. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  1615. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  1616. return item.qty !== null;
  1617. }), ['sorder'], ['desc']);
  1618. const useChangeUsedData = [];
  1619. if (changeUsedData.length > 0) { // 防止未创建期时调用
  1620. for (const cu of changeUsedData) {
  1621. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  1622. if (index !== -1) {
  1623. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  1624. } else {
  1625. useChangeUsedData.push(cu);
  1626. }
  1627. }
  1628. }
  1629. renderData.changeUsedData = useChangeUsedData;
  1630. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  1631. renderData.settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1632. renderData.settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1633. // 台账只读、使用数据
  1634. renderData.readOnly = !edit;
  1635. renderData.changing = changing;
  1636. renderData.isYb = change.uid === ctx.session.sessionUser.accountId;
  1637. await this.layout('change/addlist.ejs', renderData, 'change/addlist_modal.ejs');
  1638. } catch (err) {
  1639. this.log(err);
  1640. ctx.redirect(ctx.request.header.referer);
  1641. }
  1642. }
  1643. async _getDefaultReviseInfoData(ctx, change, edit) {
  1644. const [ledgerSpread, posSpread] = await spreadSetting.getLedgerSpreadSetting(ctx, change.tid, edit);
  1645. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1646. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1647. return {
  1648. change,
  1649. tender: ctx.tender.data,
  1650. ledgerSpread, posSpread, tenderMenu, measureType,
  1651. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1652. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1653. stdBills,
  1654. auditConst: audit.flow,
  1655. audit: audit.flow,
  1656. stdChapters,
  1657. nodeType: stdConst.nodeType,
  1658. settleStatus: ctx.service.settle.settleStatus,
  1659. };
  1660. }
  1661. async updateRevise(ctx) {
  1662. try {
  1663. if (!ctx.tender.data) throw '标段数据错误';
  1664. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1665. throw '该功能已关闭';
  1666. }
  1667. const data = JSON.parse(ctx.request.body.data);
  1668. if (!data.postType || !data.postData) throw '数据错误';
  1669. const responseData = { err: 0, msg: '', data: {} };
  1670. const change = ctx.change;
  1671. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1672. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1673. }
  1674. // 判断是否在修订中,是则无法操作本页
  1675. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1676. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1677. throw '台账修订中,无法操作新增部位数据';
  1678. }
  1679. // const revise = await this.checkRevise(ctx);
  1680. //
  1681. switch (data.postType) {
  1682. case 'add':
  1683. case 'delete':
  1684. case 'up-move':
  1685. case 'down-move':
  1686. case 'up-level':
  1687. case 'down-level':
  1688. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1689. break;
  1690. case 'update':
  1691. ctx.helper.checkDgnQtyPrecision(data.postData);
  1692. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1693. break;
  1694. case 'paste-block':
  1695. responseData.data = await this._pasteBlock(ctx, data.postData);
  1696. break;
  1697. case 'add-std':
  1698. responseData.data = await this._addStd(ctx, data.postData);
  1699. break;
  1700. case 'add-deal':
  1701. responseData.data = await this._addDeal(ctx, data.postData);
  1702. break;
  1703. // case 'batch-insert':
  1704. // responseData.data = await this._batchInsert(ctx, data.postData);
  1705. // break;
  1706. case 'pos':
  1707. responseData.data = await this._updatePos(ctx, data);
  1708. break;
  1709. default:
  1710. throw '未知操作';
  1711. }
  1712. responseData.data.changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  1713. ctx.body = responseData;
  1714. } catch (err) {
  1715. console.log(err);
  1716. this.log(err);
  1717. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1718. }
  1719. }
  1720. async _billsBase(ctx, type, data) {
  1721. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1722. if (type !== 'add') {
  1723. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1724. }
  1725. switch (type) {
  1726. case 'add':
  1727. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1728. case 'delete':
  1729. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1730. case 'up-move':
  1731. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1732. case 'down-move':
  1733. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1734. case 'up-level':
  1735. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1736. case 'down-level':
  1737. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1738. default:
  1739. throw '未知操作';
  1740. }
  1741. }
  1742. /**
  1743. * 复制粘贴整块
  1744. *
  1745. * @param ctx
  1746. * @return {Promise<void>}
  1747. */
  1748. async _pasteBlock(ctx, data) {
  1749. if ((isNaN(data.id) || data.id <= 0) ||
  1750. (!data.tid && data.tid <= 0) ||
  1751. (!data.block || data.block.length <= 0)) throw '参数错误';
  1752. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1753. }
  1754. /**
  1755. * 从标准项目表添加数据
  1756. * @param ctx
  1757. * @return {Promise<void>}
  1758. */
  1759. async _addStd(ctx, data) {
  1760. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1761. // todo 校验项目是否使用该库的权限
  1762. let stdLib,
  1763. addType;
  1764. switch (data.stdType) {
  1765. case 'xmj':
  1766. stdLib = ctx.service.stdXmj;
  1767. addType = stdDataAddType.withParent;
  1768. break;
  1769. case 'gcl':
  1770. stdLib = ctx.service.stdGcl;
  1771. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1772. if (selectNode.b_code) {
  1773. addType = stdDataAddType.next;
  1774. } else {
  1775. addType = stdDataAddType.child;
  1776. }
  1777. break;
  1778. default:
  1779. throw '未知标准库';
  1780. }
  1781. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1782. switch (addType) {
  1783. case stdDataAddType.child:
  1784. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1785. case stdDataAddType.next:
  1786. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1787. case stdDataAddType.withParent:
  1788. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1789. default:
  1790. throw '未知添加方式';
  1791. }
  1792. }
  1793. /**
  1794. * 从签约清单添加节点
  1795. * @param ctx
  1796. * @return {Promise<void>}
  1797. */
  1798. async _addDeal(ctx, data) {
  1799. if (!data.type || !data.dealBills) throw '数据错误';
  1800. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1801. if (data.dealBills.quantity && data.dealBills.unit) {
  1802. const precision = ctx.helper.findPrecision(ctx.tender.info.precision, data.dealBills.unit);
  1803. data.dealBills.quantity = ctx.helper.round(data.dealBills.quantity, precision.value);
  1804. data.dealBills.sgfh_qty = data.dealBills.quantity;
  1805. data.dealBills.total_price = ctx.helper.mul(data.dealBills.quantity, data.dealBills.unit_price, ctx.tender.info.decimal.tp);
  1806. data.dealBills.sgfh_tp = data.dealBills.total_price;
  1807. }
  1808. if (data.type === 'child') {
  1809. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1810. } else if (data.type === 'next') {
  1811. data.dealBills.ccid = ctx.change.cid;
  1812. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1813. }
  1814. throw '数据错误';
  1815. }
  1816. /**
  1817. * 批量插入数据
  1818. *
  1819. * data = {id, batchData, batchType}
  1820. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1821. * data.batchData = [{name, children}] -- 项目节列表
  1822. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1823. *
  1824. * @param ctx
  1825. * @return {Promise<void>}
  1826. */
  1827. async _batchInsert(ctx, data) {
  1828. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1829. switch (data.batchType) {
  1830. case 'child':
  1831. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1832. case 'next':
  1833. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1834. default:
  1835. throw '参数错误';
  1836. }
  1837. }
  1838. async _updatePos(ctx, data) {
  1839. await this.checkMeasureType(measureType.tz.value);
  1840. if (!data.posPostType) throw '数据错误';
  1841. switch (data.posPostType) {
  1842. case 'add':
  1843. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1844. case 'update':
  1845. if (data.postData instanceof Array) {
  1846. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1847. }
  1848. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1849. case 'delete':
  1850. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1851. case 'paste':
  1852. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1853. default:
  1854. throw '未知操作';
  1855. }
  1856. }
  1857. async _filterChangesProject(ctx, status = 0) {
  1858. const tenderId = ctx.params.id;
  1859. ctx.session.sessionUser.tenderId = tenderId;
  1860. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1861. // const tender = ctx.tender;
  1862. // const tenderList = await this.service.tender.getList();
  1863. const page = ctx.page;
  1864. const pageSize = ctx.pageSize;
  1865. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1866. const orders = ctx.query.order ? ctx.query.order : 0;
  1867. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1868. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1869. for (const c of changes) {
  1870. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  1871. c.curAuditors = await ctx.service.changeProjectAudit.getAuditorsByStatus(c.id, c.status, c.times);
  1872. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  1873. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  1874. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  1875. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  1876. await ctx.service.changeProject.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  1877. }
  1878. }
  1879. }
  1880. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1881. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1882. ? JSON.parse(accountInfo.permission) : null;
  1883. // 分页相关
  1884. const pageInfo = {
  1885. page,
  1886. pageSizeSelect: 1,
  1887. pageSize,
  1888. total_num: total,
  1889. total: Math.ceil(total / pageSize),
  1890. queryData: JSON.stringify(ctx.urlInfo.query),
  1891. };
  1892. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  1893. filter.count = [];
  1894. 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);
  1895. 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);
  1896. 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);
  1897. 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);
  1898. 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);
  1899. let codeRule = [];
  1900. let c_connector = '1';
  1901. let c_rule_first = 1;
  1902. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  1903. if (tender.c_code_rules) {
  1904. const c_code_rules = JSON.parse(tender.c_code_rules);
  1905. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  1906. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  1907. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  1908. }
  1909. for (const rule of codeRule) {
  1910. switch (rule.rule_type) {
  1911. case codeRuleConst.measure.ruleType.dealCode:
  1912. rule.preview = ctx.tender.info.deal_info.dealCode;
  1913. break;
  1914. case codeRuleConst.measure.ruleType.tenderName:
  1915. rule.preview = tender.name;
  1916. break;
  1917. case codeRuleConst.measure.ruleType.inDate:
  1918. rule.preview = moment().format('YYYY');
  1919. break;
  1920. case codeRuleConst.measure.ruleType.text:
  1921. rule.preview = rule.text;
  1922. break;
  1923. case codeRuleConst.measure.ruleType.addNo:
  1924. const s = '0000000000';
  1925. rule.preview = s.substr(s.length - rule.format);
  1926. break;
  1927. default: break;
  1928. }
  1929. }
  1930. const renderData = {
  1931. uid: ctx.session.sessionUser.accountId,
  1932. userPermission,
  1933. tender,
  1934. pageInfo,
  1935. changes,
  1936. status,
  1937. rule_type,
  1938. codeRule,
  1939. c_connector,
  1940. c_rule_first,
  1941. filter,
  1942. ruleType: codeRuleConst.ruleType[rule_type],
  1943. dealCode: ctx.tender.info.deal_info.dealCode,
  1944. auditConst: audit.changeProject,
  1945. ruleConst: codeRuleConst.measure,
  1946. changeConst,
  1947. auditType,
  1948. tenderMenu: this.menu.tenderMenu,
  1949. preUrl: '/tender/' + tender.id,
  1950. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  1951. };
  1952. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  1953. }
  1954. /**
  1955. * 变更立项列表 页面 (Get)
  1956. *
  1957. * @param {Object} ctx - egg全局变量
  1958. * @return {void}
  1959. */
  1960. async project(ctx) {
  1961. try {
  1962. await this._filterChangesProject(ctx);
  1963. } catch (err) {
  1964. this.log(err);
  1965. ctx.redirect('/dashboard');
  1966. }
  1967. }
  1968. /**
  1969. * 审批流程(Get)
  1970. * @param ctx
  1971. * @return {Promise<void>}
  1972. */
  1973. async changeProjectAuditors(ctx) {
  1974. try {
  1975. const id = JSON.parse(ctx.request.body.data).id;
  1976. const tenderId = ctx.params.id;
  1977. const changeInfo = await ctx.service.changeProject.getDataById(id);
  1978. await ctx.service.changeProject.loadChangeUser(changeInfo);
  1979. await ctx.service.changeProject.loadChangeAuditViewData(changeInfo);
  1980. ctx.body = { err: 0, msg: '', data: changeInfo };
  1981. } catch (error) {
  1982. this.log(error);
  1983. ctx.body = { err: 1, msg: error.toString(), data: null };
  1984. }
  1985. }
  1986. /**
  1987. * 新增变更立项 (Post)
  1988. *
  1989. * @param {Object} ctx - egg全局变量
  1990. * @return {void}
  1991. */
  1992. async projectAdd(ctx) {
  1993. try {
  1994. const tenderId = ctx.params.id;
  1995. if (!tenderId) {
  1996. throw '当前未打开标段';
  1997. }
  1998. const data = JSON.parse(ctx.request.body.data);
  1999. if (!data.code || data.code === '' || !data.name || data.name === '') {
  2000. throw '变更立项书编号不能为空';
  2001. }
  2002. // 在生成新变更立项后,需要copy前一个变更立项报表的签名信息
  2003. const lastChange = await ctx.service.changeProject.getLastChange(tenderId);
  2004. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  2005. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-302', change.id, lastChange ? lastChange.id : null);
  2006. ctx.body = { err: 0, msg: '', data: change };
  2007. } catch (err) {
  2008. this.log(err);
  2009. ctx.body = { err: 1, msg: err.toString() };
  2010. }
  2011. }
  2012. /**
  2013. * 删除变更立项
  2014. * @param {Object} ctx - egg全局变量
  2015. * @return {void}
  2016. */
  2017. async projectDelete(ctx) {
  2018. try {
  2019. const result = await ctx.service.changeProject.delete(ctx.request.body.cpid);
  2020. if (!result) {
  2021. throw '删除变更立项失败';
  2022. }
  2023. ctx.redirect(ctx.request.header.referer);
  2024. } catch (err) {
  2025. console.log(err);
  2026. ctx.redirect(ctx.request.header.referer);
  2027. }
  2028. }
  2029. /**
  2030. * 变更管理 状态筛选 页面 (Get)
  2031. * @param {Object} ctx - egg全局变量
  2032. * @return {void}
  2033. */
  2034. async projectStatus(ctx) {
  2035. try {
  2036. const status = parseInt(ctx.params.status);
  2037. await this._filterChangesProject(ctx, status);
  2038. } catch (err) {
  2039. this.logger.error(err);
  2040. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  2041. }
  2042. }
  2043. /**
  2044. * 获取审批界面所需的 原报、审批人数据等
  2045. * @param ctx
  2046. * @return {Promise<void>}
  2047. * @private
  2048. */
  2049. async _getChangeProjectAuditViewData(ctx) {
  2050. await ctx.service.changeProject.loadChangeAuditViewData(ctx.change);
  2051. }
  2052. // 变更类别获取及更新
  2053. async _getOrUpdateClass(ctx, serviceName) {
  2054. // 工程变更类别读取
  2055. const projectData = await ctx.service.project.getDataById(ctx.session.sessionProject.id);
  2056. const fun_set = await ctx.service.project.getFunSet(projectData.fun_set);
  2057. if (ctx.change.status === audit[serviceName].status.uncheck ||
  2058. (serviceName === 'changeProject' && ctx.change.status === audit[serviceName].status.back) ||
  2059. (serviceName !== 'changeProject' && ctx.change.status === audit[serviceName].status.checkNo)) {
  2060. const classInfo = ctx.helper._.find(fun_set.change_class, function(item) {
  2061. return item.checked && (item.name === ctx.change.class || item.new_name === ctx.change.class);
  2062. });
  2063. if (!classInfo) {
  2064. const classInfo2 = ctx.helper._.find(fun_set.change_class, { checked: true });
  2065. ctx.change.class = classInfo2.new_name ? classInfo2.new_name : classInfo2.name;
  2066. await ctx.service[serviceName].defaultUpdate({
  2067. id: ctx.change.id,
  2068. class: ctx.change.class,
  2069. });
  2070. } else if (classInfo && classInfo.new_name && ctx.change.class !== classInfo.new_name) {
  2071. ctx.change.class = classInfo.new_name;
  2072. await ctx.service[serviceName].defaultUpdate({
  2073. id: ctx.change.id,
  2074. class: ctx.change.class,
  2075. });
  2076. }
  2077. }
  2078. return fun_set.change_class;
  2079. }
  2080. async projectInformation(ctx) {
  2081. try {
  2082. const whiteList = this.ctx.app.config.multipart.whitelist;
  2083. // const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2084. // 获取附件列表
  2085. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2086. await this._getChangeProjectAuditViewData(ctx);
  2087. const changeClass = await this._getOrUpdateClass(ctx, 'changeProject');
  2088. // 获取用户人验证手机号
  2089. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2090. const auth_mobile = pa.auth_mobile;
  2091. const userPermission = pa && pa.permission ? 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 && pa.permission ? JSON.parse(pa.permission) : null;
  2903. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  2904. const renderData = {
  2905. tender,
  2906. change: ctx.change,
  2907. listRule: tender.c_apply_list_rule ? JSON.parse(tender.c_apply_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  2908. changeList,
  2909. changeConst,
  2910. changeClass,
  2911. auditConst: audit.changeApply,
  2912. fileList,
  2913. whiteList,
  2914. authMobile: auth_mobile,
  2915. deleteFilePermission,
  2916. auditType,
  2917. shenpiConst,
  2918. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  2919. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  2920. changeUnits: changeConst.units,
  2921. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  2922. 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,
  2923. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information),
  2924. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information',
  2925. };
  2926. // 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)) {
  2927. // data.accountGroup = accountGroup;
  2928. // 获取所有项目参与者
  2929. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  2930. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  2931. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  2932. });
  2933. renderData.accountList = accountList;
  2934. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  2935. renderData.accountGroup = unitList.map(item => {
  2936. const groupList = accountList.filter(item1 => item1.company === item.name);
  2937. return { groupName: item.name, groupList };
  2938. });
  2939. // }
  2940. // 获取固定审批流列表
  2941. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  2942. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changeApply');
  2943. }
  2944. await this.layout('change/apply_information.ejs', renderData, 'change/apply_information_modal.ejs');
  2945. } catch (err) {
  2946. this.log(err);
  2947. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2948. }
  2949. }
  2950. async applyInformationNotice(ctx) {
  2951. try {
  2952. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2953. // 获取附件列表
  2954. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2955. await this._getChangeApplyAuditViewData(ctx);
  2956. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2957. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  2958. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  2959. const renderData = {
  2960. tender,
  2961. change: ctx.change,
  2962. changeConst,
  2963. auditConst: audit.changeApply,
  2964. fileList,
  2965. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') ? ctx.request.headers.referer : null,
  2966. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information_notice),
  2967. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information/notice',
  2968. deleteFilePermission,
  2969. };
  2970. await this.layout('change/apply_information_notice.ejs', renderData, 'change/apply_information_notice_modal.ejs');
  2971. } catch (err) {
  2972. this.log(err);
  2973. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2974. }
  2975. }
  2976. // 审批相关
  2977. /**
  2978. * 添加审批人
  2979. * @param ctx
  2980. * @return {Promise<void>}
  2981. */
  2982. async addApplyAudit(ctx) {
  2983. try {
  2984. const auditConst = audit.changeApply;
  2985. const data = JSON.parse(ctx.request.body.data);
  2986. const id = this.app._.toInteger(data.auditorId);
  2987. if (isNaN(id) || id <= 0) {
  2988. throw '参数错误';
  2989. }
  2990. // 检查权限等
  2991. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2992. throw '您无权添加审核人';
  2993. }
  2994. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2995. throw '当前不允许添加审核人';
  2996. }
  2997. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2998. // 检查审核人是否已存在
  2999. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3000. if (exist) {
  3001. throw '该审核人已存在,请勿重复添加';
  3002. }
  3003. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3004. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3005. const result = await ctx.service.changeApplyAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3006. if (!result) {
  3007. throw '添加审核人失败';
  3008. }
  3009. const auditors = await ctx.service.changeApplyAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3010. ctx.body = { err: 0, msg: '', data: auditors };
  3011. } catch (err) {
  3012. this.log(err);
  3013. ctx.body = { err: 1, msg: err.toString(), data: null };
  3014. }
  3015. }
  3016. /**
  3017. * 移除审批人
  3018. * @param ctx
  3019. * @return {Promise<void>}
  3020. */
  3021. async deleteApplyAudit(ctx) {
  3022. try {
  3023. const data = JSON.parse(ctx.request.body.data);
  3024. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3025. if (isNaN(id) || id <= 0) {
  3026. throw '参数错误';
  3027. }
  3028. const result = await ctx.service.changeApplyAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3029. if (!result) {
  3030. throw '移除审核人失败';
  3031. }
  3032. const auditors = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  3033. ctx.body = { err: 0, msg: '', data: auditors };
  3034. } catch (err) {
  3035. ctx.body = { err: 1, msg: err.toString(), data: null };
  3036. }
  3037. }
  3038. async saveApplyAudit(ctx) {
  3039. try {
  3040. // if (ctx.change.revising) {
  3041. // throw '台账修订中,请勿修改提交期数据';
  3042. // }
  3043. const data = JSON.parse(ctx.request.body.data);
  3044. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  3045. await ctx.service.changeApplyAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  3046. const auditors = await ctx.service.changeApplyAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  3047. ctx.body = { err: 0, msg: '', data: auditors };
  3048. } else {
  3049. throw '您无权进行该操作';
  3050. }
  3051. } catch (err) {
  3052. this.log(err);
  3053. // ctx.session.postError = err.toString();
  3054. // ctx.redirect(ctx.request.header.referer);
  3055. ctx.body = {
  3056. err: 1,
  3057. // url: ctx.request.header.referer,
  3058. msg: err,
  3059. };
  3060. }
  3061. }
  3062. /**
  3063. * 上传附件
  3064. * @param {*} ctx 上下文
  3065. */
  3066. async uploadApplyFile(ctx) {
  3067. let stream;
  3068. try {
  3069. const auditConst = audit.changeApply;
  3070. // this._checkAdvanceFileCanModify(ctx);
  3071. const parts = this.ctx.multipart({
  3072. autoFields: true,
  3073. });
  3074. const files = [];
  3075. const create_time = Date.parse(new Date()) / 1000;
  3076. let idx = 0;
  3077. const extra_upload = ctx.change.status === auditConst.status.checked;
  3078. while ((stream = await parts()) !== undefined) {
  3079. if (!stream.filename) {
  3080. // 如果没有传入直接返回
  3081. return;
  3082. }
  3083. const fileInfo = path.parse(stream.filename);
  3084. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_apply/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3085. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3086. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3087. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3088. ++idx;
  3089. stream && (await sendToWormhole(stream));
  3090. }
  3091. const in_time = new Date();
  3092. const payload = files.map(file => {
  3093. let idx;
  3094. if (Array.isArray(parts.field.name)) {
  3095. idx = parts.field.name.findIndex(name => name === file.name);
  3096. } else {
  3097. idx = 'isString';
  3098. }
  3099. const newFile = {
  3100. tid: ctx.tender.id,
  3101. caid: ctx.change.id,
  3102. uid: ctx.session.sessionUser.accountId,
  3103. type: parts.field.type,
  3104. filename: file.name,
  3105. fileext: file.ext,
  3106. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3107. filepath: file.filepath,
  3108. upload_time: in_time,
  3109. extra_upload,
  3110. };
  3111. return newFile;
  3112. });
  3113. // 执行文件信息写入数据库
  3114. await ctx.service.changeApplyAtt.saveFileMsgToDb(payload);
  3115. // 将最新的当前标段的所有文件信息返回
  3116. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3117. ctx.body = { err: 0, msg: '', data };
  3118. } catch (err) {
  3119. stream && (await sendToWormhole(stream));
  3120. this.log(err);
  3121. ctx.body = { err: 1, msg: err.toString(), data: null };
  3122. }
  3123. }
  3124. /**
  3125. * 删除附件
  3126. * @param {Ojbect} ctx 上下文
  3127. */
  3128. async deleteApplyFile(ctx) {
  3129. try {
  3130. const { id } = JSON.parse(ctx.request.body.data);
  3131. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  3132. if (fileInfo || Object.keys(fileInfo).length) {
  3133. // 先删除文件
  3134. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  3135. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  3136. // 再删除数据库
  3137. await ctx.service.changeApplyAtt.delete(id);
  3138. } else {
  3139. throw '不存在该文件';
  3140. }
  3141. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3142. ctx.body = { err: 0, msg: '请求成功', data };
  3143. } catch (err) {
  3144. this.log(err);
  3145. ctx.body = { err: 1, msg: err.toString(), data: null };
  3146. }
  3147. }
  3148. /**
  3149. * 下载附件
  3150. * @param {Object} ctx - egg全局变量
  3151. * @return {void}
  3152. */
  3153. async downloadApplyFile(ctx) {
  3154. const id = ctx.params.fid;
  3155. if (id) {
  3156. try {
  3157. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  3158. if (fileInfo !== undefined && fileInfo !== '') {
  3159. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  3160. // 解决中文无法下载问题
  3161. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  3162. let disposition = '';
  3163. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  3164. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  3165. } else if (userAgent.indexOf('firefox') >= 0) {
  3166. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  3167. } else {
  3168. /* safari等其他非主流浏览器只能自求多福了 */
  3169. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  3170. }
  3171. ctx.response.set({
  3172. 'Content-Type': 'application/octet-stream',
  3173. 'Content-Disposition': disposition,
  3174. 'Content-Length': fileInfo.filesize,
  3175. });
  3176. // ctx.body = await fs.createReadStream(fileName);
  3177. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  3178. } else {
  3179. throw '不存在该文件';
  3180. }
  3181. } catch (err) {
  3182. this.log(err);
  3183. this.setMessage(err.toString(), this.messageType.ERROR);
  3184. }
  3185. }
  3186. }
  3187. async applyInformationSave(ctx) {
  3188. try {
  3189. const data = JSON.parse(ctx.request.body.data);
  3190. if (data.name === 'code') {
  3191. const info = await ctx.service.changeApply.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  3192. if (info) {
  3193. throw '该编号已存在';
  3194. }
  3195. }
  3196. const result = await ctx.service.changeApply.saveInfo(ctx.change.id, data);
  3197. if (!result) {
  3198. throw '修改失败';
  3199. }
  3200. ctx.body = { err: 0, msg: '请求成功', data: null };
  3201. } catch (err) {
  3202. this.log(err);
  3203. ctx.body = { err: 1, msg: err.toString(), data: null };
  3204. }
  3205. }
  3206. /**
  3207. * 上报和重新上报
  3208. * @param ctx
  3209. * @return {Promise<void>}
  3210. */
  3211. async startApplyAudit(ctx) {
  3212. try {
  3213. const auditConst = audit.changeApply;
  3214. // 检查权限等
  3215. if (!ctx.change) {
  3216. throw '数据错误';
  3217. }
  3218. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3219. throw '您无权上报该变更申请数据';
  3220. }
  3221. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3222. throw '该变更申请数据当前无法上报';
  3223. }
  3224. await ctx.service.changeApplyAudit.start(ctx.change.id, ctx.change.times);
  3225. ctx.redirect(ctx.request.header.referer);
  3226. } catch (err) {
  3227. this.log(err);
  3228. ctx.session.postError = err.toString();
  3229. ctx.redirect(ctx.request.header.referer);
  3230. }
  3231. }
  3232. /**
  3233. * 审批
  3234. * @param ctx
  3235. * @return {Promise<void>}
  3236. */
  3237. async checkApplyAudit(ctx) {
  3238. try {
  3239. const auditConst = audit.changeApply;
  3240. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  3241. throw '当前变更申请数据有误';
  3242. }
  3243. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  3244. throw '您无权进行该操作';
  3245. }
  3246. const data = {
  3247. checkType: parseInt(ctx.request.body.checkType),
  3248. opinion: ctx.request.body.opinion,
  3249. };
  3250. if (!data.checkType || isNaN(data.checkType)) {
  3251. throw '提交数据错误';
  3252. }
  3253. if (ctx.request.body.notice_uid) {
  3254. data.notice_code = ctx.request.body.notice_code;
  3255. data.notice_uid = ctx.request.body.notice_uid;
  3256. }
  3257. // if (data.checkType === auditConst.status.checkNo) {
  3258. // if (!data.checkType || isNaN(data.checkType)) {
  3259. // throw '提交数据错误';
  3260. // }
  3261. // }
  3262. await ctx.service.changeApplyAudit.check(ctx.change.id, data, ctx.change.times);
  3263. ctx.redirect(ctx.request.header.referer);
  3264. } catch (err) {
  3265. this.log(err);
  3266. ctx.session.postError = err.toString();
  3267. ctx.redirect(ctx.request.header.referer);
  3268. }
  3269. }
  3270. /**
  3271. * 变更清单 - 操作 (Ajax)
  3272. * @param ctx
  3273. * @return {Promise<void>}
  3274. */
  3275. async saveApplyListsData(ctx) {
  3276. try {
  3277. const data = JSON.parse(ctx.request.body.data);
  3278. const responseData = {
  3279. err: 0,
  3280. msg: '',
  3281. data: {},
  3282. };
  3283. switch (data.type) {
  3284. case 'add':
  3285. responseData.data = await ctx.service.changeApplyList.add(data.updateData);
  3286. break;
  3287. case 'batchadd':
  3288. responseData.data = await ctx.service.changeApplyList.batchAdd(data);
  3289. break;
  3290. case 'del':
  3291. await ctx.service.changeApplyList.del(data.ids);
  3292. // 取所有工料表
  3293. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3294. break;
  3295. case 'update':
  3296. // if (data.updateData.code === '' || data.updateData.code === null) {
  3297. // throw '请先输入编号';
  3298. // }
  3299. await ctx.service.changeApplyList.save(data.updateData);
  3300. break;
  3301. case 'paste':
  3302. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3303. // 取所有工料表
  3304. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3305. break;
  3306. case 'paste_amount_rows':
  3307. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3308. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3309. break;
  3310. case 'list_rule':
  3311. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_apply_list_rule: data.postData });
  3312. if (!result) {
  3313. throw '修改失败';
  3314. }
  3315. break;
  3316. // case 'update_tp':
  3317. // await ctx.service.changeApply.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  3318. // break;
  3319. default: throw '参数有误';
  3320. }
  3321. ctx.body = responseData;
  3322. } catch (err) {
  3323. this.log(err);
  3324. ctx.body = { err: 1, msg: err.toString(), data: null };
  3325. }
  3326. }
  3327. /**
  3328. * 变更申请重新审批
  3329. * @param {Object} ctx - egg全局变量
  3330. * @return {void}
  3331. */
  3332. async checkApplyAgain(ctx) {
  3333. try {
  3334. // 获取终审
  3335. // const auditInfo = await this.ctx.service.changeApplyAudit.getAuditorByStatus(ctx.change.id, audit.changeApply.status.checked);
  3336. if (ctx.change.status !== audit.changeApply.status.checked) {
  3337. throw '您无权进行该操作';
  3338. }
  3339. // 判断是否被变更申请调用了,是则无法发起修订
  3340. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3341. if (projectInfo) {
  3342. throw '该变更申请已被变更方案调用,无法发起重新审批';
  3343. }
  3344. if (ctx.session.sessionUser.loginStatus === 0) {
  3345. const code = ctx.request.body.code;
  3346. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3347. if (!pa.auth_mobile) {
  3348. throw '未绑定手机号';
  3349. }
  3350. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3351. const cacheCode = await app.redis.get(cacheKey);
  3352. // console.log(cacheCode);
  3353. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3354. throw '验证码不正确!';
  3355. }
  3356. }
  3357. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changeApply.status.checked) {
  3358. // 重新审批
  3359. const result = await ctx.service.changeApplyAudit.checkAgain(ctx.change);
  3360. if (!result) {
  3361. throw '重新审批失败';
  3362. }
  3363. } else {
  3364. throw '您无权进行该操作';
  3365. }
  3366. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3367. ctx.body = {
  3368. err: 0,
  3369. url: ctx.request.header.referer,
  3370. msg: '',
  3371. };
  3372. } catch (err) {
  3373. console.log(err);
  3374. // ctx.redirect(ctx.request.header.referer);
  3375. ctx.body = {
  3376. err: 1,
  3377. // url: ctx.request.header.referer,
  3378. msg: err,
  3379. };
  3380. }
  3381. }
  3382. /**
  3383. * 变更申请修订重新上报
  3384. * @param {Object} ctx - egg全局变量
  3385. * @return {void}
  3386. */
  3387. async checkApplyRevise(ctx) {
  3388. try {
  3389. if (ctx.change.status !== audit.changeApply.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  3390. throw '您无权进行该操作';
  3391. }
  3392. // 判断是否被变更申请调用了,是则无法发起修订
  3393. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3394. if (projectInfo) {
  3395. throw '该变更申请已被变更方案调用,无法发起修订';
  3396. }
  3397. if (ctx.session.sessionUser.loginStatus === 0) {
  3398. const code = ctx.request.body.code;
  3399. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3400. if (!pa.auth_mobile) {
  3401. throw '未绑定手机号';
  3402. }
  3403. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3404. const cacheCode = await app.redis.get(cacheKey);
  3405. // console.log(cacheCode);
  3406. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3407. throw '验证码不正确!';
  3408. }
  3409. }
  3410. // 重新审批
  3411. const result = await ctx.service.changeApplyAudit.checkRevise(ctx.change);
  3412. if (!result) {
  3413. throw '修订发起失败';
  3414. }
  3415. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3416. ctx.body = {
  3417. err: 0,
  3418. url: ctx.request.header.referer,
  3419. msg: '',
  3420. };
  3421. } catch (err) {
  3422. console.log(err);
  3423. // ctx.redirect(ctx.request.header.referer);
  3424. ctx.body = {
  3425. err: 1,
  3426. // url: ctx.request.header.referer,
  3427. msg: err,
  3428. };
  3429. }
  3430. }
  3431. /**
  3432. * 变更令撤销修订
  3433. * @param {Object} ctx - egg全局变量
  3434. * @return {void}
  3435. */
  3436. async cancelApplyRevise(ctx) {
  3437. try {
  3438. if (!(ctx.change.status === audit.changeApply.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  3439. throw '您无权进行该操作';
  3440. }
  3441. // 重新审批
  3442. const result = await ctx.service.changeApplyAudit.cancelRevise(ctx.change);
  3443. if (!result) {
  3444. throw '撤销修订失败';
  3445. }
  3446. ctx.body = {
  3447. err: 0,
  3448. url: ctx.request.header.referer,
  3449. msg: '',
  3450. };
  3451. } catch (err) {
  3452. console.log(err);
  3453. ctx.body = {
  3454. err: 1,
  3455. msg: err,
  3456. };
  3457. }
  3458. }
  3459. // 变更方案
  3460. async _filterChangesPlan(ctx, status = 0) {
  3461. const tenderId = ctx.params.id;
  3462. ctx.session.sessionUser.tenderId = tenderId;
  3463. const tender = await this.service.tender.getDataById(ctx.tender.id);
  3464. // const tender = ctx.tender;
  3465. // const tenderList = await this.service.tender.getList();
  3466. const page = ctx.page;
  3467. const pageSize = ctx.pageSize;
  3468. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  3469. const orders = ctx.query.order ? ctx.query.order : 0;
  3470. const changes = await ctx.service.changePlan.getListByStatus(tender.id, status, 1, sorts, orders);
  3471. const total = await ctx.service.changePlan.getCountByStatus(tender.id, status);
  3472. let page_total = 0;
  3473. const tp = await ctx.service.changePlan.getTp(tender.id, status);
  3474. for (const c of changes) {
  3475. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  3476. c.curAuditors = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, c.status, c.times);
  3477. // if (c.status === audit.changePlan.status.checkNoPre) {
  3478. // c.curAuditors2 = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, audit.changePlan.status.checking, c.times);
  3479. // }
  3480. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  3481. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  3482. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  3483. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  3484. await ctx.service.changePlan.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  3485. }
  3486. }
  3487. page_total = ctx.helper.add(page_total, c.total_price);
  3488. }
  3489. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  3490. // 分页相关
  3491. const pageInfo = {
  3492. page,
  3493. pageSizeSelect: 1,
  3494. pageSize,
  3495. total_num: total,
  3496. total: Math.ceil(total / pageSize),
  3497. queryData: JSON.stringify(ctx.urlInfo.query),
  3498. };
  3499. const filter = JSON.parse(JSON.stringify(audit.changePlan.filter));
  3500. filter.count = [];
  3501. 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);
  3502. 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);
  3503. 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);
  3504. 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);
  3505. // 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);
  3506. let codeRule = [];
  3507. let c_connector = '1';
  3508. let c_rule_first = 1;
  3509. const rule_type = 'plan';
  3510. if (tender.c_code_rules) {
  3511. const c_code_rules = JSON.parse(tender.c_code_rules);
  3512. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  3513. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  3514. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  3515. }
  3516. for (const rule of codeRule) {
  3517. switch (rule.rule_type) {
  3518. case codeRuleConst.measure.ruleType.dealCode:
  3519. rule.preview = ctx.tender.info.deal_info.dealCode;
  3520. break;
  3521. case codeRuleConst.measure.ruleType.tenderName:
  3522. rule.preview = tender.name;
  3523. break;
  3524. case codeRuleConst.measure.ruleType.inDate:
  3525. rule.preview = moment().format('YYYY');
  3526. break;
  3527. case codeRuleConst.measure.ruleType.text:
  3528. rule.preview = rule.text;
  3529. break;
  3530. case codeRuleConst.measure.ruleType.addNo:
  3531. const s = '0000000000';
  3532. rule.preview = s.substr(s.length - rule.format);
  3533. break;
  3534. default: break;
  3535. }
  3536. }
  3537. const changeApplyList = await ctx.service.changeApply.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeApply.status.checked } });
  3538. const allApplyCodes = await ctx.service.changePlan.getAllDataByCondition({
  3539. columns: ['apply_code'],
  3540. where: {
  3541. tid: tender.id,
  3542. },
  3543. });
  3544. const acLists = allApplyCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allApplyCodes, 'apply_code')) : [];
  3545. const renderData = {
  3546. uid: ctx.session.sessionUser.accountId,
  3547. tender,
  3548. pageInfo,
  3549. changes,
  3550. status,
  3551. rule_type,
  3552. codeRule,
  3553. c_connector,
  3554. c_rule_first,
  3555. filter,
  3556. plan_username: tender_userInfo ? tender_userInfo.name : null,
  3557. ruleType: codeRuleConst.ruleType[rule_type],
  3558. dealCode: ctx.tender.info.deal_info.dealCode,
  3559. auditConst: audit.changePlan,
  3560. ruleConst: codeRuleConst.measure,
  3561. changeConst,
  3562. auditType,
  3563. changeApplyList,
  3564. acLists,
  3565. page_total,
  3566. tp,
  3567. tenderMenu: this.menu.tenderMenu,
  3568. preUrl: '/tender/' + tender.id,
  3569. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan),
  3570. };
  3571. await this.layout('change/plan.ejs', renderData, 'change/plan_modal.ejs');
  3572. }
  3573. /**
  3574. * 变更申请列表 页面 (Get)
  3575. *
  3576. * @param {Object} ctx - egg全局变量
  3577. * @return {void}
  3578. */
  3579. async plan(ctx) {
  3580. try {
  3581. await this._filterChangesPlan(ctx);
  3582. } catch (err) {
  3583. this.log(err);
  3584. ctx.redirect('/dashboard');
  3585. }
  3586. }
  3587. /**
  3588. * 变更管理 状态筛选 页面 (Get)
  3589. * @param {Object} ctx - egg全局变量
  3590. * @return {void}
  3591. */
  3592. async planStatus(ctx) {
  3593. try {
  3594. const status = parseInt(ctx.params.status);
  3595. await this._filterChangesPlan(ctx, status);
  3596. } catch (err) {
  3597. this.logger.error(err);
  3598. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3599. }
  3600. }
  3601. /**
  3602. * 审批流程(Get)
  3603. * @param ctx
  3604. * @return {Promise<void>}
  3605. */
  3606. async changePlanAuditors(ctx) {
  3607. try {
  3608. const id = JSON.parse(ctx.request.body.data).id;
  3609. const tenderId = ctx.params.id;
  3610. const changeInfo = await ctx.service.changePlan.getDataById(id);
  3611. await ctx.service.changePlan.loadChangeUser(changeInfo);
  3612. await ctx.service.changePlan.loadChangeAuditViewData(changeInfo);
  3613. ctx.body = { err: 0, msg: '', data: changeInfo };
  3614. } catch (error) {
  3615. this.log(error);
  3616. ctx.body = { err: 1, msg: error.toString(), data: null };
  3617. }
  3618. }
  3619. /**
  3620. * 新增变更方案 (Post)
  3621. *
  3622. * @param {Object} ctx - egg全局变量
  3623. * @return {void}
  3624. */
  3625. async planAdd(ctx) {
  3626. try {
  3627. const tenderId = ctx.params.id;
  3628. if (!tenderId) {
  3629. throw '当前未打开标段';
  3630. }
  3631. const data = JSON.parse(ctx.request.body.data);
  3632. if (!data.code || data.code === '') {
  3633. throw '变更方案编号不能为空';
  3634. }
  3635. // 在生成新变更方案后,需要copy前一个变更方案报表的签名信息
  3636. const lastChange = await ctx.service.changePlan.getLastChange(tenderId);
  3637. const change = await ctx.service.changePlan.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.apply_code, data.name);
  3638. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-301', change.id, lastChange ? lastChange.id : null);
  3639. ctx.body = { err: 0, msg: '', data: change };
  3640. } catch (err) {
  3641. this.log(err);
  3642. ctx.body = { err: 1, msg: err.toString() };
  3643. }
  3644. }
  3645. /**
  3646. * 删除变更立项
  3647. * @param {Object} ctx - egg全局变量
  3648. * @return {void}
  3649. */
  3650. async planDelete(ctx) {
  3651. try {
  3652. const result = await ctx.service.changePlan.delete(ctx.request.body.cpid);
  3653. if (!result) {
  3654. throw '删除变更方案失败';
  3655. }
  3656. ctx.redirect(ctx.request.header.referer);
  3657. } catch (err) {
  3658. console.log(err);
  3659. ctx.redirect(ctx.request.header.referer);
  3660. }
  3661. }
  3662. /**
  3663. * 获取审批界面所需的 原报、审批人数据等
  3664. * @param ctx
  3665. * @return {Promise<void>}
  3666. * @private
  3667. */
  3668. async _getChangePlanAuditViewData(ctx) {
  3669. await ctx.service.changePlan.loadChangeAuditViewData(ctx.change);
  3670. }
  3671. async planInformation(ctx) {
  3672. try {
  3673. const whiteList = this.ctx.app.config.multipart.whitelist;
  3674. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  3675. await this._getChangePlanAuditViewData(ctx);
  3676. // 获取附件列表
  3677. const fileList = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3678. // 获取清单列表
  3679. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3680. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3681. // const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3682. // ctx.change.listAudits = listAudits;
  3683. for (const cl of changeList) {
  3684. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3685. // 清单表页赋值
  3686. for (const au in ctx.change.userGroups) {
  3687. if (ctx.change.userGroups[au][0].audit_order !== 0) {
  3688. cl['audit_amount_' + ctx.change.userGroups[au][0].audit_order] =
  3689. (ctx.change.userGroups[au][0].audit_type === auditType.key.and &&
  3690. ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId, status: audit.changePlan.status.checked }) !== -1) ||
  3691. (ctx.change.shenpiPower && ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId }) !== -1) ?
  3692. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  3693. }
  3694. }
  3695. }
  3696. }
  3697. // 获取用户人验证手机号
  3698. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3699. const auth_mobile = pa.auth_mobile;
  3700. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  3701. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  3702. const changeClass = await this._getOrUpdateClass(ctx, 'changePlan');
  3703. const renderData = {
  3704. tender,
  3705. change: ctx.change,
  3706. listRule: tender.c_plan_list_rule ? JSON.parse(tender.c_plan_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  3707. changeList,
  3708. changeClass,
  3709. changeConst,
  3710. auditConst: audit.changePlan,
  3711. fileList,
  3712. whiteList,
  3713. authMobile: auth_mobile,
  3714. deleteFilePermission,
  3715. auditType,
  3716. shenpiConst,
  3717. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  3718. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  3719. changeUnits: changeConst.units,
  3720. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  3721. 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,
  3722. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan_information),
  3723. preUrl: '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information',
  3724. };
  3725. // 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)) {
  3726. // data.accountGroup = accountGroup;
  3727. // 获取所有项目参与者
  3728. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  3729. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  3730. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  3731. });
  3732. renderData.accountList = accountList;
  3733. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  3734. renderData.accountGroup = unitList.map(item => {
  3735. const groupList = accountList.filter(item1 => item1.company === item.name);
  3736. return { groupName: item.name, groupList };
  3737. });
  3738. // 获取固定审批流列表
  3739. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  3740. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changePlan');
  3741. }
  3742. // }
  3743. await this.layout('change/plan_information.ejs', renderData, 'change/plan_information_modal.ejs');
  3744. } catch (err) {
  3745. this.log(err);
  3746. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3747. }
  3748. }
  3749. async changePlanSpGroup(ctx) {
  3750. try {
  3751. const data = JSON.parse(ctx.request.body.data);
  3752. const result = await ctx.service.changePlanAudit.changeSpGroup(ctx.change, data.sp_group);
  3753. if (!result) {
  3754. throw '切换审批组失败';
  3755. }
  3756. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3757. ctx.body = { err: 0, msg: '', data: auditors };
  3758. } catch (err) {
  3759. ctx.body = { err: 1, msg: err.toString(), data: null };
  3760. }
  3761. }
  3762. // 审批相关
  3763. /**
  3764. * 添加审批人
  3765. * @param ctx
  3766. * @return {Promise<void>}
  3767. */
  3768. async addPlanAudit(ctx) {
  3769. try {
  3770. const auditConst = audit.changePlan;
  3771. const data = JSON.parse(ctx.request.body.data);
  3772. const id = this.app._.toInteger(data.auditorId);
  3773. if (isNaN(id) || id <= 0) {
  3774. throw '参数错误';
  3775. }
  3776. // 检查权限等
  3777. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3778. throw '您无权添加审核人';
  3779. }
  3780. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3781. throw '当前不允许添加审核人';
  3782. }
  3783. ctx.change.auditorList = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3784. // 检查审核人是否已存在
  3785. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3786. if (exist) {
  3787. throw '该审核人已存在,请勿重复添加';
  3788. }
  3789. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3790. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3791. const result = await ctx.service.changePlanAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3792. if (!result) {
  3793. throw '添加审核人失败';
  3794. }
  3795. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3796. ctx.body = { err: 0, msg: '', data: auditors };
  3797. } catch (err) {
  3798. this.log(err);
  3799. ctx.body = { err: 1, msg: err.toString(), data: null };
  3800. }
  3801. }
  3802. /**
  3803. * 移除审批人
  3804. * @param ctx
  3805. * @return {Promise<void>}
  3806. */
  3807. async deletePlanAudit(ctx) {
  3808. try {
  3809. const data = JSON.parse(ctx.request.body.data);
  3810. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3811. if (isNaN(id) || id <= 0) {
  3812. throw '参数错误';
  3813. }
  3814. const result = await ctx.service.changePlanAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3815. if (!result) {
  3816. throw '移除审核人失败';
  3817. }
  3818. const auditors = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3819. ctx.body = { err: 0, msg: '', data: auditors };
  3820. } catch (err) {
  3821. ctx.body = { err: 1, msg: err.toString(), data: null };
  3822. }
  3823. }
  3824. async savePlanAudit(ctx) {
  3825. try {
  3826. // if (ctx.change.revising) {
  3827. // throw '台账修订中,请勿修改提交期数据';
  3828. // }
  3829. const data = JSON.parse(ctx.request.body.data);
  3830. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  3831. await ctx.service.changePlanAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  3832. const auditors = await ctx.service.changePlanAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  3833. ctx.body = { err: 0, msg: '', data: auditors };
  3834. } else {
  3835. throw '您无权进行该操作';
  3836. }
  3837. } catch (err) {
  3838. this.log(err);
  3839. // ctx.session.postError = err.toString();
  3840. // ctx.redirect(ctx.request.header.referer);
  3841. ctx.body = {
  3842. err: 1,
  3843. // url: ctx.request.header.referer,
  3844. msg: err,
  3845. };
  3846. }
  3847. }
  3848. /**
  3849. * 上传附件
  3850. * @param {*} ctx 上下文
  3851. */
  3852. async uploadPlanFile(ctx) {
  3853. let stream;
  3854. try {
  3855. const auditConst = audit.changePlan;
  3856. // this._checkAdvanceFileCanModify(ctx);
  3857. const parts = this.ctx.multipart({
  3858. autoFields: true,
  3859. });
  3860. const files = [];
  3861. const create_time = Date.parse(new Date()) / 1000;
  3862. let idx = 0;
  3863. const extra_upload = ctx.change.status === auditConst.status.checked;
  3864. while ((stream = await parts()) !== undefined) {
  3865. if (!stream.filename) {
  3866. // 如果没有传入直接返回
  3867. return;
  3868. }
  3869. const fileInfo = path.parse(stream.filename);
  3870. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_plan/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3871. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3872. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3873. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3874. ++idx;
  3875. stream && (await sendToWormhole(stream));
  3876. }
  3877. const in_time = new Date();
  3878. const payload = files.map(file => {
  3879. let idx;
  3880. if (Array.isArray(parts.field.name)) {
  3881. idx = parts.field.name.findIndex(name => name === file.name);
  3882. } else {
  3883. idx = 'isString';
  3884. }
  3885. const newFile = {
  3886. tid: ctx.tender.id,
  3887. cpid: ctx.change.id,
  3888. uid: ctx.session.sessionUser.accountId,
  3889. filename: file.name,
  3890. fileext: file.ext,
  3891. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3892. filepath: file.filepath,
  3893. upload_time: in_time,
  3894. extra_upload,
  3895. };
  3896. return newFile;
  3897. });
  3898. // 执行文件信息写入数据库
  3899. await ctx.service.changePlanAtt.saveFileMsgToDb(payload);
  3900. // 将最新的当前标段的所有文件信息返回
  3901. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3902. ctx.body = { err: 0, msg: '', data };
  3903. } catch (err) {
  3904. stream && (await sendToWormhole(stream));
  3905. this.log(err);
  3906. ctx.body = { err: 1, msg: err.toString(), data: null };
  3907. }
  3908. }
  3909. /**
  3910. * 删除附件
  3911. * @param {Ojbect} ctx 上下文
  3912. */
  3913. async deletePlanFile(ctx) {
  3914. try {
  3915. const { id } = JSON.parse(ctx.request.body.data);
  3916. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3917. if (fileInfo || Object.keys(fileInfo).length) {
  3918. // 先删除文件
  3919. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  3920. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  3921. // 再删除数据库
  3922. await ctx.service.changePlanAtt.delete(id);
  3923. } else {
  3924. throw '不存在该文件';
  3925. }
  3926. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3927. ctx.body = { err: 0, msg: '请求成功', data };
  3928. } catch (err) {
  3929. this.log(err);
  3930. ctx.body = { err: 1, msg: err.toString(), data: null };
  3931. }
  3932. }
  3933. /**
  3934. * 下载附件
  3935. * @param {Object} ctx - egg全局变量
  3936. * @return {void}
  3937. */
  3938. async downloadPlanFile(ctx) {
  3939. const id = ctx.params.fid;
  3940. if (id) {
  3941. try {
  3942. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  3943. if (fileInfo !== undefined && fileInfo !== '') {
  3944. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  3945. // 解决中文无法下载问题
  3946. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  3947. let disposition = '';
  3948. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  3949. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  3950. } else if (userAgent.indexOf('firefox') >= 0) {
  3951. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  3952. } else {
  3953. /* safari等其他非主流浏览器只能自求多福了 */
  3954. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  3955. }
  3956. ctx.response.set({
  3957. 'Content-Type': 'application/octet-stream',
  3958. 'Content-Disposition': disposition,
  3959. 'Content-Length': fileInfo.filesize,
  3960. });
  3961. // ctx.body = await fs.createReadStream(fileName);
  3962. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  3963. } else {
  3964. throw '不存在该文件';
  3965. }
  3966. } catch (err) {
  3967. this.log(err);
  3968. this.setMessage(err.toString(), this.messageType.ERROR);
  3969. }
  3970. }
  3971. }
  3972. async planInformationSave(ctx) {
  3973. try {
  3974. const data = JSON.parse(ctx.request.body.data);
  3975. if (data.name === 'code') {
  3976. const info = await ctx.service.changePlan.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  3977. if (info) {
  3978. throw '该编号已存在';
  3979. }
  3980. }
  3981. const result = await ctx.service.changePlan.saveInfo(ctx.change.id, data);
  3982. if (!result) {
  3983. throw '修改失败';
  3984. }
  3985. ctx.body = { err: 0, msg: '请求成功', data: null };
  3986. } catch (err) {
  3987. this.log(err);
  3988. ctx.body = { err: 1, msg: err.toString(), data: null };
  3989. }
  3990. }
  3991. /**
  3992. * 上报和重新上报
  3993. * @param ctx
  3994. * @return {Promise<void>}
  3995. */
  3996. async startPlanAudit(ctx) {
  3997. try {
  3998. const auditConst = audit.changePlan;
  3999. // 检查权限等
  4000. if (!ctx.change) {
  4001. throw '数据错误';
  4002. }
  4003. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  4004. throw '您无权上报该变更方案数据';
  4005. }
  4006. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  4007. throw '该变更方案数据当前无法上报';
  4008. }
  4009. await ctx.service.changePlanAudit.start(ctx.change.id, ctx.change.times);
  4010. ctx.redirect(ctx.request.header.referer);
  4011. } catch (err) {
  4012. this.log(err);
  4013. ctx.session.postError = err.toString();
  4014. ctx.redirect(ctx.request.header.referer);
  4015. }
  4016. }
  4017. /**
  4018. * 审批
  4019. * @param ctx
  4020. * @return {Promise<void>}
  4021. */
  4022. async checkPlanAudit(ctx) {
  4023. try {
  4024. const auditConst = audit.changePlan;
  4025. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  4026. throw '当前变更方案数据有误';
  4027. }
  4028. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  4029. throw '您无权进行该操作';
  4030. }
  4031. const data = {
  4032. checkType: parseInt(ctx.request.body.checkType),
  4033. opinion: ctx.request.body.opinion,
  4034. };
  4035. if (!data.checkType || isNaN(data.checkType)) {
  4036. throw '提交数据错误';
  4037. }
  4038. // if (data.checkType === auditConst.status.checkNo) {
  4039. // if (!data.checkType || isNaN(data.checkType)) {
  4040. // throw '提交数据错误';
  4041. // }
  4042. // }
  4043. await ctx.service.changePlanAudit.check(ctx.change.id, data, ctx.change.times);
  4044. ctx.redirect(ctx.request.header.referer);
  4045. } catch (err) {
  4046. this.log(err);
  4047. console.log(err);
  4048. ctx.session.postError = err.toString();
  4049. ctx.redirect(ctx.request.header.referer);
  4050. }
  4051. }
  4052. /**
  4053. * 变更清单 - 操作 (Ajax)
  4054. * @param ctx
  4055. * @return {Promise<void>}
  4056. */
  4057. async savePlanListsData(ctx) {
  4058. try {
  4059. const data = JSON.parse(ctx.request.body.data);
  4060. const responseData = {
  4061. err: 0,
  4062. msg: '',
  4063. data: {},
  4064. };
  4065. switch (data.type) {
  4066. case 'add':
  4067. responseData.data = await ctx.service.changePlanList.add(data.updateData);
  4068. break;
  4069. case 'batchadd':
  4070. responseData.data = await ctx.service.changePlanList.batchAdd(data);
  4071. break;
  4072. case 'del':
  4073. await ctx.service.changePlanList.del(data.ids);
  4074. // 取所有工料表
  4075. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  4076. break;
  4077. case 'update':
  4078. // if (data.updateData.code === '' || data.updateData.code === null) {
  4079. // throw '请先输入编号';
  4080. // }
  4081. await ctx.service.changePlanList.save(data.updateData);
  4082. break;
  4083. case 'paste':
  4084. await ctx.service.changePlanList.saveDatas(data.updateData);
  4085. // 取所有工料表
  4086. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  4087. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  4088. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  4089. for (const cl of responseData.data) {
  4090. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  4091. // 清单表页赋值
  4092. for (const [index, au] of listAudits.entries()) {
  4093. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  4094. }
  4095. }
  4096. }
  4097. break;
  4098. case 'list_rule':
  4099. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_plan_list_rule: data.postData });
  4100. if (!result) {
  4101. throw '修改失败';
  4102. }
  4103. break;
  4104. case 'paste_amount_rows':
  4105. await ctx.service.changePlanList.saveDatas(data.updateData);
  4106. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  4107. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  4108. for (const cl of changeList) {
  4109. // 清单表页赋值
  4110. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  4111. // 清单表页赋值
  4112. for (const [index, au] of listAudits.entries()) {
  4113. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  4114. }
  4115. }
  4116. // 取所有工料表
  4117. responseData.data = changeList;
  4118. break;
  4119. // case 'update_tp':
  4120. // await ctx.service.changePlan.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  4121. // break;
  4122. default: throw '参数有误';
  4123. }
  4124. ctx.body = responseData;
  4125. } catch (err) {
  4126. this.log(err);
  4127. ctx.body = { err: 1, msg: err.toString(), data: null };
  4128. }
  4129. }
  4130. /**
  4131. * 撤回审批
  4132. * @param ctx
  4133. * @return {Promise<void>}
  4134. */
  4135. async checkPlanAuditCancel(ctx) {
  4136. try {
  4137. if (!ctx.change.cancancel) throw '您无权进行该操作';
  4138. await ctx.service.changePlanAudit.checkCancel(ctx.change);
  4139. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  4140. } catch (err) {
  4141. this.log(err);
  4142. ctx.body = { err: 1, msg: err };
  4143. }
  4144. }
  4145. /**
  4146. * 变更申请重新审批
  4147. * @param {Object} ctx - egg全局变量
  4148. * @return {void}
  4149. */
  4150. async checkPlanAgain(ctx) {
  4151. try {
  4152. // 获取终审
  4153. // const auditInfo = await this.ctx.service.changePlanAudit.getAuditorByStatus(ctx.change.id, audit.changePlan.status.checked);
  4154. if (ctx.change.status !== audit.changePlan.status.checked) {
  4155. throw '您无权进行该操作';
  4156. }
  4157. // 判断是否被变更申请调用了,是则无法发起修订
  4158. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  4159. if (projectInfo) {
  4160. throw '该变更方案已被变更令调用,无法发起重新审批';
  4161. }
  4162. if (ctx.session.sessionUser.loginStatus === 0) {
  4163. const code = ctx.request.body.code;
  4164. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  4165. if (!pa.auth_mobile) {
  4166. throw '未绑定手机号';
  4167. }
  4168. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  4169. const cacheCode = await app.redis.get(cacheKey);
  4170. // console.log(cacheCode);
  4171. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  4172. throw '验证码不正确!';
  4173. }
  4174. }
  4175. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changePlan.status.checked) {
  4176. // 重新审批
  4177. const result = await ctx.service.changePlanAudit.checkAgain(ctx.change);
  4178. if (!result) {
  4179. throw '重新审批失败';
  4180. }
  4181. } else {
  4182. throw '您无权进行该操作';
  4183. }
  4184. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  4185. ctx.body = {
  4186. err: 0,
  4187. url: ctx.request.header.referer,
  4188. msg: '',
  4189. };
  4190. } catch (err) {
  4191. console.log(err);
  4192. // ctx.redirect(ctx.request.header.referer);
  4193. ctx.body = {
  4194. err: 1,
  4195. // url: ctx.request.header.referer,
  4196. msg: err,
  4197. };
  4198. }
  4199. }
  4200. /**
  4201. * 变更申请修订重新上报
  4202. * @param {Object} ctx - egg全局变量
  4203. * @return {void}
  4204. */
  4205. async checkPlanRevise(ctx) {
  4206. try {
  4207. if (ctx.change.status !== audit.changePlan.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  4208. throw '您无权进行该操作';
  4209. }
  4210. // 判断是否被变更申请调用了,是则无法发起修订
  4211. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  4212. if (projectInfo) {
  4213. throw '该变更方案已被变更令调用,无法发起修订';
  4214. }
  4215. if (ctx.session.sessionUser.loginStatus === 0) {
  4216. const code = ctx.request.body.code;
  4217. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  4218. if (!pa.auth_mobile) {
  4219. throw '未绑定手机号';
  4220. }
  4221. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  4222. const cacheCode = await app.redis.get(cacheKey);
  4223. // console.log(cacheCode);
  4224. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  4225. throw '验证码不正确!';
  4226. }
  4227. }
  4228. // 重新审批
  4229. const result = await ctx.service.changePlanAudit.checkRevise(ctx.change);
  4230. if (!result) {
  4231. throw '修订发起失败';
  4232. }
  4233. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  4234. ctx.body = {
  4235. err: 0,
  4236. url: ctx.request.header.referer,
  4237. msg: '',
  4238. };
  4239. } catch (err) {
  4240. console.log(err);
  4241. // ctx.redirect(ctx.request.header.referer);
  4242. ctx.body = {
  4243. err: 1,
  4244. // url: ctx.request.header.referer,
  4245. msg: err,
  4246. };
  4247. }
  4248. }
  4249. /**
  4250. * 变更令撤销修订
  4251. * @param {Object} ctx - egg全局变量
  4252. * @return {void}
  4253. */
  4254. async cancelPlanRevise(ctx) {
  4255. try {
  4256. if (!(ctx.change.status === audit.changePlan.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  4257. throw '您无权进行该操作';
  4258. }
  4259. // 重新审批
  4260. const result = await ctx.service.changePlanAudit.cancelRevise(ctx.change);
  4261. if (!result) {
  4262. throw '撤销修订失败';
  4263. }
  4264. ctx.body = {
  4265. err: 0,
  4266. url: ctx.request.header.referer,
  4267. msg: '',
  4268. };
  4269. } catch (err) {
  4270. console.log(err);
  4271. ctx.body = {
  4272. err: 1,
  4273. msg: err,
  4274. };
  4275. }
  4276. }
  4277. }
  4278. return ChangeController;
  4279. };