change_controller.js 190 KB

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