change_controller.js 190 KB

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