change_controller.js 186 KB

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