change_controller.js 220 KB

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