change_controller.js 192 KB

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