change_controller.js 214 KB

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