change_controller.js 179 KB

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