change_controller.js 191 KB

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