change_controller.js 202 KB

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