change_controller.js 212 KB

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