change_controller.js 189 KB

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