change_controller.js 214 KB

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