change_controller.js 214 KB

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