change_controller.js 218 KB

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