change_controller.js 216 KB

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