change_controller.js 227 KB

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