change_controller.js 211 KB

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