change_controller.js 216 KB

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