change_controller.js 216 KB

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