change_controller.js 176 KB

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