change_controller.js 190 KB

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