change_controller.js 182 KB

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