change_controller.js 190 KB

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