change_controller.js 212 KB

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