change_controller.js 205 KB

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