change_controller.js 189 KB

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