change_controller.js 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  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 accountGroup = require('../const/account_group').group;
  22. const shenpiConst = require('../const/shenpi');
  23. const tenderMenu = require('../../config/menu').tenderMenu;
  24. const measureType = require('../const/tender').measureType;
  25. const spreadConst = require('../const/spread');
  26. // const tenderMenu = require('../../config/menu').tenderMenu;
  27. module.exports = app => {
  28. class ChangeController extends app.BaseController {
  29. /**
  30. * 构造函数
  31. *
  32. * @param {Object} ctx - egg全局变量
  33. * @return {void}
  34. */
  35. constructor(ctx) {
  36. super(ctx);
  37. ctx.showProject = true;
  38. ctx.showTender = true;
  39. ctx.showTitle = true;
  40. }
  41. async _filterChanges(ctx, status = 0) {
  42. const tenderId = ctx.params.id;
  43. ctx.session.sessionUser.tenderId = tenderId;
  44. const tender = await this.service.tender.getDataById(tenderId);
  45. // const tenderList = await this.service.tender.getList();
  46. const page = ctx.page;
  47. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  48. const orders = ctx.query.order ? ctx.query.order : 0;
  49. const changes = await ctx.service.change.getListByStatus(tender.id, status, 1, sorts, orders);
  50. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  51. let page_total = 0;
  52. const tp = await ctx.service.change.getTp(tender.id, status);
  53. if (changes !== null) {
  54. let i = 0;
  55. for (const c of changes) {
  56. page_total = ctx.helper.add(page_total, c.total_price);
  57. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  58. // 根据审批人对当前变更令的状态取不同的展示方式。
  59. let changeAudit = '';
  60. let auditStatus = 0;
  61. switch (c.status) {
  62. case 1:
  63. auditStatus = 1;
  64. break;
  65. case 2:
  66. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  67. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  68. break;
  69. case 3:
  70. case 4:
  71. auditStatus = 0;
  72. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  73. break;
  74. case 5:
  75. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  76. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  77. const back_changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  78. c.stageChangeNum = this.ctx.helper.sum(back_changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  79. break;
  80. case 6:
  81. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  82. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  83. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  84. break;
  85. case 9:
  86. auditStatus = 9;
  87. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  88. c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  89. break;
  90. default:
  91. break;
  92. }
  93. changes[i].changeAudit = changeAudit;
  94. changes[i].auditStatus = auditStatus;
  95. i++;
  96. }
  97. }
  98. // 分页相关
  99. const pageInfo = {
  100. page,
  101. total: Math.ceil(total / app.config.pageSize),
  102. queryData: JSON.stringify(ctx.urlInfo.query),
  103. };
  104. const filter = JSON.parse(JSON.stringify(audit.filter));
  105. filter.count = [];
  106. 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);
  107. 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);
  108. 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);
  109. 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);
  110. 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);
  111. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  112. for (const rule of codeRule) {
  113. switch (rule.rule_type) {
  114. case codeRuleConst.measure.ruleType.dealCode:
  115. rule.preview = ctx.tender.info.deal_info.dealCode;
  116. break;
  117. case codeRuleConst.measure.ruleType.tenderName:
  118. rule.preview = tender.name;
  119. break;
  120. case codeRuleConst.measure.ruleType.inDate:
  121. rule.preview = moment().format('YYYY');
  122. break;
  123. case codeRuleConst.measure.ruleType.text:
  124. rule.preview = rule.text;
  125. break;
  126. case codeRuleConst.measure.ruleType.addNo:
  127. const s = '0000000000';
  128. rule.preview = s.substr(s.length - rule.format);
  129. break;
  130. default: break;
  131. }
  132. }
  133. const renderData = {
  134. uid: ctx.session.sessionUser.accountId,
  135. moment,
  136. tender,
  137. // tenderList,
  138. pageInfo,
  139. changes,
  140. page_total,
  141. tp,
  142. filter,
  143. status,
  144. codeRule,
  145. dealCode: ctx.tender.info.deal_info.dealCode,
  146. auditConst: audit.flow,
  147. changeConst,
  148. ruleType: codeRuleConst.ruleType.change,
  149. ruleConst: codeRuleConst.measure,
  150. tenderMenu: this.menu.tenderMenu,
  151. preUrl: '/tender/' + tenderId,
  152. tpUnit: ctx.tender.info.decimal.tp,
  153. };
  154. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  155. }
  156. /**
  157. * 变更管理 页面 (Get)
  158. *
  159. * @param {Object} ctx - egg全局变量
  160. * @return {void}
  161. */
  162. async index(ctx) {
  163. try {
  164. await this._filterChanges(ctx);
  165. } catch (err) {
  166. this.log(err);
  167. ctx.redirect('/dashboard');
  168. }
  169. }
  170. /**
  171. *
  172. * @param {Object} ctx - egg全局变量
  173. * @return {void}
  174. */
  175. async newCode(ctx) {
  176. const responseData = {
  177. err: 0,
  178. msg: '',
  179. data: '',
  180. };
  181. try {
  182. const tenderId = ctx.params.id;
  183. if (!tenderId) {
  184. throw '当前未打开标段';
  185. }
  186. const tenderData = await ctx.service.tender.getDataById(tenderId);
  187. const data = JSON.parse(ctx.request.body.data);
  188. let cCodeRule;
  189. let cConnector;
  190. let changeCount = 0;
  191. if (data && data.type) {
  192. const c_code_rules = tenderData.c_code_rules !== null ? JSON.parse(tenderData.c_code_rules) : null;
  193. cCodeRule = c_code_rules && c_code_rules[data.type + '_rule'] ? c_code_rules[data.type + '_rule'] : [];
  194. cConnector = c_code_rules && c_code_rules[data.type + '_connector'] ? c_code_rules[data.type + '_connector'] : null;
  195. changeCount = await ctx.service.changeProject.count({ tid: tenderId, type: codeRuleConst.ruleType[data.type] });
  196. } else {
  197. cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  198. cConnector = tenderData.c_connector;
  199. changeCount = await ctx.service.change.count({ tid: tenderId });
  200. }
  201. const code = [];
  202. for (const rule of cCodeRule) {
  203. switch (rule.rule_type) {
  204. case codeRuleConst.measure.ruleType.dealCode:
  205. code.push(ctx.tender.info.deal_info.dealCode);
  206. break;
  207. case codeRuleConst.measure.ruleType.tenderName:
  208. code.push(tenderData.name);
  209. break;
  210. case codeRuleConst.measure.ruleType.text:
  211. code.push(rule.text);
  212. break;
  213. case codeRuleConst.measure.ruleType.inDate:
  214. code.push(moment().format('YYYY'));
  215. break;
  216. case codeRuleConst.measure.ruleType.addNo:
  217. let s = '0000000000';
  218. const count = rule.start + changeCount;
  219. s = s + count;
  220. code.push(s.substr(s.length - rule.format));
  221. break;
  222. default: break;
  223. }
  224. }
  225. responseData.data = code.join(cConnector !== null && cConnector !== 3 ? codeRuleConst.measure.connectorString[cConnector] : '');
  226. } catch (err) {
  227. responseData.err = 1;
  228. responseData.msg = err;
  229. }
  230. ctx.body = responseData;
  231. }
  232. /**
  233. * 新增变更 (Post)
  234. *
  235. * @param {Object} ctx - egg全局变量
  236. * @return {void}
  237. */
  238. async add(ctx) {
  239. try {
  240. const tenderId = ctx.params.id;
  241. if (!tenderId) {
  242. throw '当前未打开标段';
  243. }
  244. const data = JSON.parse(ctx.request.body.data);
  245. if (!data.code || data.code === '' || !data.name || data.name === '') {
  246. throw '变更令号不能为空';
  247. }
  248. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  249. ctx.body = { err: 0, msg: '', data: change };
  250. } catch (err) {
  251. this.log(err);
  252. ctx.body = { err: 1, msg: err.toString() };
  253. }
  254. }
  255. /**
  256. * 变更管理 状态筛选 页面 (Get)
  257. * @param {Object} ctx - egg全局变量
  258. * @return {void}
  259. */
  260. async status(ctx) {
  261. try {
  262. const status = parseInt(ctx.params.status);
  263. await this._filterChanges(ctx, status);
  264. } catch (err) {
  265. this.logger.error(err);
  266. ctx.redirect('/tender/' + ctx.params.id + '/change');
  267. }
  268. }
  269. /**
  270. * 变更信息 页面 (Get)
  271. *
  272. * @param {Object} ctx - egg全局变量
  273. * @return {void}
  274. */
  275. async info(ctx) {
  276. try {
  277. const whiteList = this.ctx.app.config.multipart.whitelist;
  278. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  279. ctx.session.sessionUser.tenderId = tenderid;
  280. const tender = await ctx.service.tender.getDataById(tenderid);
  281. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  282. // 后台判断当前人查看info状态
  283. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  284. // 获取附件列表
  285. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  286. // 获取其他变更令数据
  287. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  288. // 根据auditStatus获取审批人列表
  289. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  290. // 获取已选清单
  291. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  292. // 获取用户人验证手机号
  293. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  294. const auth_mobile = pa.auth_mobile;
  295. const renderData = {
  296. uid: ctx.session.sessionUser.accountId,
  297. tender,
  298. change,
  299. othersChange,
  300. changeConst,
  301. auditStatus,
  302. auditConst: audit.flow,
  303. ledgerConsts: audit.ledger.status,
  304. attList,
  305. whiteList,
  306. auditList,
  307. changeList,
  308. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  309. upUnit: ctx.tender.info.decimal.up,
  310. authMobile: auth_mobile,
  311. shenpiConst,
  312. };
  313. // 根据auditStatus状态获取的不同的数据
  314. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  315. renderData.changeUnits = changeConst.units;
  316. renderData.precision = ctx.tender.info.precision;
  317. // renderData.accountGroup = accountGroup;
  318. // 获取所有项目参与者
  319. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  320. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  321. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  322. });
  323. renderData.accountList = accountList;
  324. renderData.accountGroup = accountGroup.map((item, idx) => {
  325. const groupList = accountList.filter(item => item.account_group === idx);
  326. return { groupName: item, groupList };
  327. });
  328. // 重新上报获取审批流程
  329. if (auditStatus === 2 || auditStatus === 9) {
  330. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  331. // 展示页右侧审批流程列表
  332. const auditList3 = [];
  333. for (let time = 1; time <= change.times - 1; time++) {
  334. const auditTimeList = [];
  335. let max_sort = 1;
  336. for (const al of auditList2) {
  337. if (al.times === time) {
  338. auditTimeList.push(al);
  339. if (al.usite > max_sort) {
  340. max_sort = al.usite;
  341. }
  342. }
  343. }
  344. for (const i in auditTimeList) {
  345. auditTimeList[i].max_sort = max_sort;
  346. }
  347. auditList3.push(auditTimeList);
  348. }
  349. renderData.auditList3 = auditList3;
  350. }
  351. // 根据清单获取提交数据和计算总金额
  352. const changeListData = [];
  353. const changeWhiteListData = [];
  354. let ototalCost = 0;
  355. let ctotalCost = 0;
  356. for (const cl of changeList) {
  357. const cLArray = [
  358. cl.code,
  359. cl.name,
  360. cl.bwmx,
  361. cl.unit,
  362. cl.unit_price,
  363. cl.oamount,
  364. cl.camount,
  365. cl.detail,
  366. cl.lid,
  367. cl.xmj_code,
  368. cl.xmj_jldy,
  369. cl.gcl_id,
  370. ];
  371. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  372. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  373. if (cl.lid !== '0') {
  374. changeListData.push(cLArray.join('*;*'));
  375. } else {
  376. changeWhiteListData.push(cLArray.join('*;*'));
  377. }
  378. }
  379. renderData.changeListData = changeListData.join('^_^');
  380. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  381. renderData.ototalCost = ototalCost;
  382. renderData.ctotalCost = ctotalCost;
  383. // 获取公司列表
  384. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  385. renderData.companyList = companyList;
  386. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  387. // 展示页左侧审批流程列表和清单审批列表数据
  388. const times = change.status === audit.flow.status.back ?
  389. change.times - 1 : change.times;
  390. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  391. // 展示页右侧审批流程列表
  392. const auditList3 = [];
  393. for (let time = 1; time <= times; time++) {
  394. const auditTimeList = [];
  395. let max_sort = 1;
  396. for (const al of auditList) {
  397. if (al.times === time) {
  398. auditTimeList.push(al);
  399. if (al.usite > max_sort) {
  400. max_sort = al.usite;
  401. }
  402. }
  403. }
  404. for (const i in auditTimeList) {
  405. auditTimeList[i].max_sort = max_sort;
  406. }
  407. auditList3.push(auditTimeList);
  408. }
  409. renderData.auditList3 = auditList3;
  410. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  411. renderData.changeList = changeList;
  412. let ototalCost = 0;
  413. let ctotalCost = 0;
  414. let stotalCost = 0;
  415. const auditTotalCost = [];
  416. for (const cl of changeList) {
  417. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  418. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  419. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  420. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  421. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  422. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  423. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  424. auditTotalCost.push(audit_amount);
  425. }
  426. renderData.ototalCost = ototalCost;
  427. renderData.ctotalCost = ctotalCost;
  428. renderData.stotalCost = stotalCost;
  429. // 清单表页赋值
  430. for (const [index, au] of auditList2.entries()) {
  431. if (au.usite !== 0) {
  432. au.list_amount = [];
  433. au.totalCost = 0;
  434. for (const [auindex, at] of auditTotalCost.entries()) {
  435. au.list_amount.push(at[index - 1]);
  436. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  437. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  438. }
  439. }
  440. }
  441. renderData.auditList2 = auditList2;
  442. } else if (auditStatus === 6) {
  443. // 展示页左侧审批流程列表和清单审批列表数据
  444. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  445. renderData.auditList2 = auditList2;
  446. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  447. for (const i in auditList3) {
  448. auditList3[i].max_sort = auditList2.length - 1;
  449. }
  450. renderData.auditList3 = auditList3;
  451. // 展示页右侧审批流程列表
  452. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  453. const auditList4 = [];
  454. for (let time = 1; time <= change.times; time++) {
  455. const auditTimeList = [];
  456. let max_sort = 1;
  457. for (const al of auditList5) {
  458. if (al.times === time) {
  459. auditTimeList.push(al);
  460. if (al.usite > max_sort) {
  461. max_sort = al.usite;
  462. }
  463. }
  464. }
  465. for (const i in auditTimeList) {
  466. auditTimeList[i].max_sort = max_sort;
  467. }
  468. if (auditTimeList.length > 0) {
  469. auditList4.push(auditTimeList);
  470. }
  471. }
  472. renderData.auditList4 = auditList4;
  473. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  474. renderData.changeList = changeList;
  475. let ototalCost = 0;
  476. let ctotalCost = 0;
  477. const auditTotalCost = [];
  478. const auditUnit = [];
  479. for (const cl of changeList) {
  480. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  481. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  482. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  483. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  484. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  485. auditTotalCost.push(audit_amount);
  486. }
  487. renderData.ototalCost = ototalCost;
  488. renderData.ctotalCost = ctotalCost;
  489. // 清单表页赋值
  490. for (const [index, au] of auditList.entries()) {
  491. if (au.usite !== 0) {
  492. au.list_amount = [];
  493. au.totalCost = 0;
  494. if (au.uid === renderData.uid) {
  495. for (const [auindex, at] of auditTotalCost.entries()) {
  496. // if (at[index - 2] !== undefined) {
  497. // au.list_amount.push(at[index - 2]);
  498. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  499. // } else if (at[index - 2] === undefined) {
  500. // au.list_amount.push(changeList[auindex].camount);
  501. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  502. // }
  503. au.list_amount.push(changeList[auindex].spamount);
  504. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  505. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  506. }
  507. } else {
  508. for (const [auindex, at] of auditTotalCost.entries()) {
  509. au.list_amount.push(at[index - 1]);
  510. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  511. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  512. }
  513. }
  514. }
  515. }
  516. }
  517. renderData.auditList = auditList;
  518. // 获取是否已存在调用变更令
  519. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  520. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  521. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  522. } catch (err) {
  523. this.log(err);
  524. ctx.redirect('/tender/' + ctx.params.id + '/change');
  525. }
  526. }
  527. /**
  528. * 变更信息 新版本页面 (Get)
  529. *
  530. * @param {Object} ctx - egg全局变量
  531. * @return {void}
  532. */
  533. async information(ctx) {
  534. try {
  535. const whiteList = this.ctx.app.config.multipart.whitelist;
  536. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  537. const change = ctx.change;
  538. // 后台判断当前人查看info状态
  539. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  540. // 获取附件列表
  541. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  542. // 获取其他变更令数据
  543. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  544. // 根据auditStatus获取审批人列表
  545. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  546. // 获取用户人验证手机号
  547. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  548. const auth_mobile = pa.auth_mobile;
  549. const renderData = {
  550. tender,
  551. change,
  552. othersChange,
  553. changeConst,
  554. auditStatus,
  555. auditConst: audit.flow,
  556. ledgerConsts: audit.ledger.status,
  557. attList,
  558. whiteList,
  559. auditList,
  560. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  561. upUnit: ctx.tender.info.decimal.up,
  562. authMobile: auth_mobile,
  563. shenpiConst,
  564. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  565. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  566. precision: ctx.tender.info.precision,
  567. };
  568. // 根据auditStatus状态获取的不同的数据
  569. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  570. renderData.changeUnits = changeConst.units;
  571. // renderData.accountGroup = accountGroup;
  572. // 获取所有项目参与者
  573. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  574. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  575. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  576. });
  577. renderData.accountList = accountList;
  578. renderData.accountGroup = accountGroup.map((item, idx) => {
  579. const groupList = accountList.filter(item => item.account_group === idx);
  580. return { groupName: item, groupList };
  581. });
  582. // 重新上报获取审批流程
  583. if (auditStatus === 2 || auditStatus === 9) {
  584. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  585. // 展示页右侧审批流程列表
  586. const auditList3 = [];
  587. for (let time = 1; time <= change.times - 1; time++) {
  588. const auditTimeList = [];
  589. let max_sort = 1;
  590. for (const al of auditList2) {
  591. if (al.times === time) {
  592. auditTimeList.push(al);
  593. if (al.usite > max_sort) {
  594. max_sort = al.usite;
  595. }
  596. }
  597. }
  598. for (const i in auditTimeList) {
  599. auditTimeList[i].max_sort = max_sort;
  600. }
  601. auditList3.push(auditTimeList);
  602. }
  603. renderData.auditList3 = auditList3;
  604. }
  605. // 获取公司列表
  606. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  607. renderData.companyList = companyList;
  608. // 获取已选清单
  609. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  610. renderData.changeList = changeList;
  611. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  612. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  613. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7 || auditStatus === 8) {
  614. // 展示页左侧审批流程列表和清单审批列表数据
  615. const times = change.status === audit.flow.status.back ?
  616. change.times - 1 : change.times;
  617. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  618. // 展示页右侧审批流程列表
  619. const auditList3 = [];
  620. for (let time = 1; time <= times; time++) {
  621. const auditTimeList = [];
  622. let max_sort = 1;
  623. for (const al of auditList) {
  624. if (al.times === time) {
  625. auditTimeList.push(al);
  626. if (al.usite > max_sort) {
  627. max_sort = al.usite;
  628. }
  629. }
  630. }
  631. for (const i in auditTimeList) {
  632. auditTimeList[i].max_sort = max_sort;
  633. }
  634. auditList3.push(auditTimeList);
  635. }
  636. renderData.auditList3 = auditList3;
  637. // 获取已选清单
  638. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  639. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  640. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  641. for (const cl of changeList) {
  642. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  643. // 清单表页赋值
  644. for (const [index, au] of auditList2.entries()) {
  645. if (au.usite !== 0) {
  646. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  647. }
  648. }
  649. }
  650. renderData.changeList = changeList;
  651. renderData.auditList2 = auditList2;
  652. } else if (auditStatus === 6) {
  653. // 展示页左侧审批流程列表和清单审批列表数据
  654. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  655. renderData.auditList2 = auditList2;
  656. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  657. for (const i in auditList3) {
  658. auditList3[i].max_sort = auditList2.length - 1;
  659. }
  660. renderData.auditList3 = auditList3;
  661. // 展示页右侧审批流程列表
  662. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  663. const auditList4 = [];
  664. for (let time = 1; time <= change.times; time++) {
  665. const auditTimeList = [];
  666. let max_sort = 1;
  667. for (const al of auditList5) {
  668. if (al.times === time) {
  669. auditTimeList.push(al);
  670. if (al.usite > max_sort) {
  671. max_sort = al.usite;
  672. }
  673. }
  674. }
  675. for (const i in auditTimeList) {
  676. auditTimeList[i].max_sort = max_sort;
  677. }
  678. if (auditTimeList.length > 0) {
  679. auditList4.push(auditTimeList);
  680. }
  681. }
  682. renderData.auditList4 = auditList4;
  683. // 获取已选清单
  684. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  685. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  686. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  687. for (const cl of changeList) {
  688. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  689. // 清单表页赋值
  690. for (const [index, au] of auditList2.entries()) {
  691. if (au.usite !== 0) {
  692. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  693. }
  694. }
  695. }
  696. renderData.changeList = changeList;
  697. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  698. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  699. }
  700. renderData.auditList = auditList;
  701. // 获取是否已存在调用变更令
  702. let changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  703. changeUsedData = ctx.helper._.filter(changeUsedData, function(item) {
  704. return item.used_qty !== null;
  705. })
  706. renderData.changeUsedData = changeUsedData;
  707. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  708. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  709. } catch (err) {
  710. this.log(err);
  711. ctx.redirect('/tender/' + ctx.params.id + '/change');
  712. }
  713. }
  714. /**
  715. * 变更清单 - 操作 (Ajax)
  716. * @param ctx
  717. * @return {Promise<void>}
  718. */
  719. async saveListsData(ctx) {
  720. try {
  721. const data = JSON.parse(ctx.request.body.data);
  722. const responseData = {
  723. err: 0,
  724. msg: '',
  725. data: {},
  726. };
  727. switch (data.type) {
  728. case 'add':
  729. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  730. break;
  731. case 'batchadd':
  732. responseData.data = await ctx.service.changeAuditList.batchAdd(data);
  733. break;
  734. case 'del':
  735. await ctx.service.changeAuditList.del(data.id);
  736. break;
  737. case 'update':
  738. await ctx.service.changeAuditList.save(data.updateData);
  739. break;
  740. case 'paste':
  741. await ctx.service.changeAuditList.saveDatas(data.updateData);
  742. // 取所有工料表
  743. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  744. break;
  745. case 'ledger_list':
  746. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  747. // 取所有工料表
  748. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  749. usedList: await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, ctx.change.cid) };
  750. break;
  751. case 'remove_list':
  752. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  753. // 取所有工料表
  754. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  755. break;
  756. case 'update_list':
  757. await ctx.service.changeAuditList.saveDatas(data.updateData);
  758. // 取所有工料表
  759. // responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  760. break;
  761. case 'info':
  762. await ctx.service.change.saveInfo(data.updateData);
  763. // 取所有工料表
  764. responseData.data = '保存成功';
  765. break;
  766. case 'paste_amount_rows':
  767. await ctx.service.changeAuditList.saveDatas(data.updateData);
  768. let changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  769. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  770. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  771. for (const cl of changeList) {
  772. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  773. // 清单表页赋值
  774. for (const [index, au] of auditList2.entries()) {
  775. if (au.usite !== 0) {
  776. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  777. }
  778. }
  779. }
  780. // 取所有工料表
  781. responseData.data = changeList;
  782. break;
  783. default: throw '参数有误';
  784. }
  785. ctx.body = responseData;
  786. } catch (err) {
  787. this.log(err);
  788. ctx.body = { err: 1, msg: err.toString(), data: null };
  789. }
  790. }
  791. /**
  792. * 上报和重新上报
  793. * @param ctx
  794. * @return {Promise<void>}
  795. */
  796. async startAudit(ctx) {
  797. try {
  798. // 检查权限等
  799. if (!ctx.change) {
  800. throw '数据错误';
  801. }
  802. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  803. throw '您无权上报该变更令数据';
  804. }
  805. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back || ctx.change.status === audit.flow.status.revise)) {
  806. throw '该变更令当前无法上报';
  807. }
  808. // 判断是否是修订,判断有无审批人员作弊
  809. if ((ctx.change.status === audit.flow.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  810. // 获取上一次的审批人流程
  811. const lastUserList = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times - 1);
  812. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  813. // 判断上一次审批是否为非原报为审批人
  814. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  815. // 判断条件修订可上报条件
  816. // 1.有原报,有其他人 可以添加原报作为审核人,但是不能只原报上报
  817. // 2.有原报,无其他人 可以添加原报作为审核人,可以只原报上报
  818. // 3.无原报,有其他人 不可以添加原报
  819. const noYBUidList = ctx.change.status === audit.flow.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  820. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  821. throw '该变更令不能指定原报人为单独审批人';
  822. }
  823. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  824. throw '该变更令不能指定原报为审批人,请移除';
  825. }
  826. }
  827. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  828. ctx.redirect(ctx.request.header.referer);
  829. } catch (err) {
  830. this.log(err);
  831. ctx.session.postError = err.toString();
  832. ctx.redirect(ctx.request.header.referer);
  833. }
  834. }
  835. // 审批相关
  836. /**
  837. * 添加审批人
  838. * @param ctx
  839. * @return {Promise<void>}
  840. */
  841. async addAudit(ctx) {
  842. try {
  843. const data = JSON.parse(ctx.request.body.data);
  844. const id = this.app._.toInteger(data.auditorId);
  845. if (isNaN(id) || id <= 0) {
  846. throw '参数错误';
  847. }
  848. // 检查权限等
  849. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  850. throw '您无权添加审核人';
  851. }
  852. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  853. throw '当前不允许添加审核人';
  854. }
  855. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  856. // 检查审核人是否已存在
  857. const exist = this.app._.find(auditorList, { uid: id });
  858. if (exist) {
  859. throw '该审核人已存在,请勿重复添加';
  860. }
  861. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  862. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  863. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  864. if (!result) {
  865. throw '添加审核人失败';
  866. }
  867. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  868. const auditors = null;
  869. ctx.body = { err: 0, msg: '', data: auditors };
  870. } catch (err) {
  871. this.log(err);
  872. ctx.body = { err: 1, msg: err.toString(), data: null };
  873. }
  874. }
  875. /**
  876. * 移除审批人
  877. * @param ctx
  878. * @return {Promise<void>}
  879. */
  880. async deleteAudit(ctx) {
  881. try {
  882. const data = JSON.parse(ctx.request.body.data);
  883. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  884. if (isNaN(id) || id <= 0) {
  885. throw '参数错误';
  886. }
  887. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  888. if (!result) {
  889. throw '移除审核人失败';
  890. }
  891. const auditors = null;
  892. ctx.body = { err: 0, msg: '', data: auditors };
  893. } catch (err) {
  894. ctx.body = { err: 1, msg: err.toString(), data: null };
  895. }
  896. }
  897. async defaultBills(ctx) {
  898. try {
  899. // 判断是否台账修订中,修订中则不获取changeLedger及changePos值
  900. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  901. const data = JSON.parse(ctx.request.body.data);
  902. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  903. 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));
  904. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  905. 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 }));
  906. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  907. // 标记ledger,搜索需求
  908. if (changePosData.length > 0) {
  909. const cplIdList = ctx.helper._.uniq(ctx.helper._.map(changePosData, 'lid'));
  910. const cLIdList = ctx.helper._.map(changeLedgerData, 'id');
  911. const ledgerIdList = [];
  912. for (const cp of cplIdList) {
  913. if (ctx.helper._.indexOf(cLIdList, cp) === -1) {
  914. ledgerIdList.push(cp);
  915. }
  916. }
  917. if (ledgerIdList.length > 0) {
  918. for (const lid of ledgerIdList) {
  919. const data = ctx.helper._.find(ledgerData, { id: lid });
  920. data.cid = 1;
  921. }
  922. }
  923. }
  924. ctx.body = { err: 0, msg: '', data: { bills: ctx.helper._.concat(ledgerData, changeLedgerData), pos: ctx.helper._.concat(posData, changePosData), dealBills } };
  925. } catch (err) {
  926. this.log(err);
  927. ctx.body = { err: 1, msg: err.toString(), data: [] };
  928. }
  929. }
  930. /**
  931. * 变更令上报和保存
  932. * @param {Object} ctx - egg全局变量
  933. * @return {void}
  934. */
  935. async save(ctx) {
  936. // 变更令信息
  937. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  938. try {
  939. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  940. if (!result) {
  941. throw '上报失败';
  942. }
  943. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  944. ctx.body = { err: 0, msg: '保存成功' };
  945. } else {
  946. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  947. }
  948. } catch (err) {
  949. this.log(err);
  950. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  951. ctx.body = { err: 1, msg: err.toString() };
  952. } else {
  953. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  954. }
  955. }
  956. }
  957. /**
  958. * 变更令审批
  959. * @param {Object} ctx - egg全局变量
  960. * @return {void}
  961. */
  962. async approval(ctx) {
  963. try {
  964. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  965. if (!changeData) {
  966. throw '变更令数据错误';
  967. }
  968. const status = parseInt(ctx.request.body.status);
  969. let result = false;
  970. const pid = this.ctx.session.sessionProject.id;
  971. switch (status) {
  972. case 3:// 审批通过
  973. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  974. break;
  975. case 4:// 审批终止
  976. result = await ctx.service.change.approvalStop(ctx.request.body);
  977. break;
  978. case 5:// 审批退回到原报人
  979. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  980. break;
  981. case 6:// 审批退回到上一个审批人
  982. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  983. break;
  984. default:break;
  985. }
  986. if (!result) {
  987. throw '审批失败';
  988. }
  989. ctx.redirect(ctx.request.header.referer);
  990. } catch (err) {
  991. console.log(err);
  992. ctx.redirect(ctx.request.header.referer);
  993. }
  994. }
  995. /**
  996. * 变更公司管理
  997. * @param {Object} ctx - egg全局变量
  998. * @return {void}
  999. */
  1000. async updateCompany(ctx) {
  1001. const responseData = {
  1002. err: 0,
  1003. msg: '',
  1004. data: '',
  1005. };
  1006. try {
  1007. const data = JSON.parse(ctx.request.body.data);
  1008. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1009. throw '参数有误';
  1010. }
  1011. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1012. responseData.data = { add: addCompany, select: selectCompany };
  1013. } catch (err) {
  1014. responseData.err = 1;
  1015. responseData.msg = err;
  1016. }
  1017. ctx.body = responseData;
  1018. }
  1019. /**
  1020. * 上传附件
  1021. * @param {Object} ctx - egg全局变量
  1022. * @return {void}
  1023. */
  1024. async uploadFile(ctx) {
  1025. const responseData = {
  1026. err: 0,
  1027. msg: '',
  1028. data: [],
  1029. };
  1030. let stream;
  1031. try {
  1032. const parts = ctx.multipart({ autoFields: true });
  1033. const files = [];
  1034. let index = 0;
  1035. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1036. const extra_upload = change.status === audit.flow.status.checked;
  1037. while ((stream = await parts()) !== undefined) {
  1038. // 判断用户是否选择上传文件
  1039. if (!stream.filename) {
  1040. throw '请选择上传的文件!';
  1041. }
  1042. // const create_time = Date.parse(new Date()) / 1000;
  1043. // const fileInfo = path.parse(stream.filename);
  1044. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  1045. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  1046. // // 判断文件夹是否存在,不存在则直接创建文件夹
  1047. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  1048. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  1049. // }
  1050. // // 保存文件
  1051. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1052. const fileInfo = path.parse(stream.filename);
  1053. const create_time = Date.parse(new Date()) / 1000;
  1054. // const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1055. const filepath = `app/public/upload/${parts.field.tid}/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1056. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1057. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  1058. await sendToWormhole(stream);
  1059. // 保存数据到att表
  1060. const fileData = {
  1061. in_time: create_time,
  1062. filename: fileInfo.name,
  1063. fileext: fileInfo.ext,
  1064. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1065. filepath,
  1066. extra_upload,
  1067. };
  1068. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1069. if (!result) {
  1070. throw '导入数据库保存失败';
  1071. }
  1072. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1073. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1074. fileData.uid = ctx.session.sessionUser.accountId;
  1075. fileData.id = result.insertId;
  1076. fileData.orginpath = ctx.app.config.fujianOssPath + filepath;
  1077. delete fileData.filepath;
  1078. files.push(fileData);
  1079. ++index;
  1080. }
  1081. responseData.data = files;
  1082. } catch (err) {
  1083. this.log(err);
  1084. // 失败需要消耗掉stream 以防卡死
  1085. if (stream) {
  1086. await sendToWormhole(stream);
  1087. }
  1088. this.setMessage(err.toString(), this.messageType.ERROR);
  1089. }
  1090. ctx.body = responseData;
  1091. }
  1092. /**
  1093. * 下载附件
  1094. * @param {Object} ctx - egg全局变量
  1095. * @return {void}
  1096. */
  1097. async downloadFile(ctx) {
  1098. const id = ctx.params.id;
  1099. if (id) {
  1100. try {
  1101. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1102. if (fileInfo !== undefined && fileInfo !== '') {
  1103. // const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1104. // 解决中文无法下载问题
  1105. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1106. let disposition = '';
  1107. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1108. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1109. } else if (userAgent.indexOf('firefox') >= 0) {
  1110. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1111. } else {
  1112. /* safari等其他非主流浏览器只能自求多福了 */
  1113. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1114. }
  1115. ctx.response.set({
  1116. 'Content-Type': 'application/octet-stream',
  1117. 'Content-Disposition': disposition,
  1118. 'Content-Length': fileInfo.filesize,
  1119. });
  1120. // ctx.body = await fs.createReadStream(fileName);
  1121. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1122. } else {
  1123. throw '不存在该文件';
  1124. }
  1125. } catch (err) {
  1126. this.log(err);
  1127. this.setMessage(err.toString(), this.messageType.ERROR);
  1128. }
  1129. }
  1130. }
  1131. /**
  1132. * 批量下载 - 压缩成zip文件返回
  1133. * @param {Oject} ctx - 全局上下文
  1134. */
  1135. async downloadZip(ctx) {
  1136. const time = Date.now();
  1137. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1138. const responseData = {
  1139. err: 0,
  1140. msg: '',
  1141. };
  1142. try {
  1143. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1144. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1145. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1146. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1147. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1148. // 解决中文无法下载问题
  1149. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1150. let disposition = '';
  1151. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1152. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1153. } else if (userAgent.indexOf('firefox') >= 0) {
  1154. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1155. } else {
  1156. /* safari等其他非主流浏览器只能自求多福了 */
  1157. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1158. }
  1159. ctx.response.set({
  1160. 'Content-Type': 'application/octet-stream',
  1161. 'Content-Disposition': disposition,
  1162. 'Content-Length': size,
  1163. });
  1164. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1165. ctx.body = readStream;
  1166. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1167. readStream.on('close', () => {
  1168. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1169. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1170. }
  1171. });
  1172. // fs的错误不能被try catch捕捉
  1173. readStream.on('error', err => {
  1174. this.log(err);
  1175. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1176. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1177. }
  1178. responseData.err = 1;
  1179. responseData.msg = err.toString();
  1180. ctx.body = responseData;
  1181. });
  1182. } catch (err) {
  1183. this.log(err);
  1184. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1185. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1186. }
  1187. this.setMessage(err.toString(), this.messageType.ERROR);
  1188. responseData.err = 1;
  1189. responseData.msg = err.toString();
  1190. ctx.body = responseData;
  1191. }
  1192. }
  1193. /**
  1194. * 删除附件
  1195. * @param {Object} ctx - egg全局变量
  1196. * @return {void}
  1197. */
  1198. async deleteFile(ctx) {
  1199. const responseData = {
  1200. err: 0,
  1201. msg: '',
  1202. data: '',
  1203. };
  1204. try {
  1205. const data = JSON.parse(ctx.request.body.data);
  1206. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1207. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1208. if (!fileInfo || !Object.keys(fileInfo).length) {
  1209. throw '该文件不存在';
  1210. }
  1211. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1212. throw '无权限删除';
  1213. }
  1214. if (fileInfo !== undefined && fileInfo !== '') {
  1215. // 先删除文件
  1216. // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1217. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  1218. // 再删除数据库
  1219. await ctx.service.changeAtt.deleteById(data.id);
  1220. responseData.data = '';
  1221. } else {
  1222. throw '不存在该文件';
  1223. }
  1224. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1225. // throw '参数有误';
  1226. // }
  1227. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1228. // responseData.data = { add: addCompany, select: selectCompany };
  1229. } catch (err) {
  1230. responseData.err = 1;
  1231. responseData.msg = err;
  1232. }
  1233. ctx.body = responseData;
  1234. }
  1235. /**
  1236. * 查看附件
  1237. * @param {Object} ctx - egg全局变量
  1238. * @return {void}
  1239. */
  1240. async checkFile(ctx) {
  1241. const responseData = { err: 0, msg: '' };
  1242. const id = parseInt(ctx.params.id);
  1243. if (id) {
  1244. try {
  1245. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1246. if (fileInfo && Object.keys(fileInfo).length) {
  1247. let filepath = fileInfo.filepath;
  1248. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1249. filepath = `/change/download/file/${fileInfo.id}`;
  1250. } else {
  1251. filepath = filepath.replace(/^app|\/app/, '');
  1252. }
  1253. fileInfo.filepath && (responseData.data = { filepath });
  1254. }
  1255. } catch (error) {
  1256. this.log(error);
  1257. this.setMessage(error.toString(), this.messageType.ERROR);
  1258. responseData.err = 1;
  1259. responseData.msg = error.toString();
  1260. }
  1261. }
  1262. ctx.body = responseData;
  1263. }
  1264. /**
  1265. * 删除变更令
  1266. * @param {Object} ctx - egg全局变量
  1267. * @return {void}
  1268. */
  1269. async delete(ctx) {
  1270. try {
  1271. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1272. if (!result) {
  1273. throw '删除变更令失败';
  1274. }
  1275. ctx.redirect(ctx.request.header.referer);
  1276. } catch (err) {
  1277. console.log(err);
  1278. ctx.redirect(ctx.request.header.referer);
  1279. }
  1280. }
  1281. /**
  1282. * 变更令重新审批
  1283. * @param {Object} ctx - egg全局变量
  1284. * @return {void}
  1285. */
  1286. async checkAgain(ctx) {
  1287. try {
  1288. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1289. if (!changeData) {
  1290. throw '变更令数据错误';
  1291. }
  1292. // 获取终审
  1293. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1294. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1295. throw '您无权进行该操作';
  1296. }
  1297. if (ctx.session.sessionUser.loginStatus === 0) {
  1298. const code = ctx.request.body.code;
  1299. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1300. if (!pa.auth_mobile) {
  1301. throw '未绑定手机号';
  1302. }
  1303. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1304. const cacheCode = await app.redis.get(cacheKey);
  1305. // console.log(cacheCode);
  1306. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1307. throw '验证码不正确!';
  1308. }
  1309. }
  1310. // 获取是否已存在调用变更令
  1311. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1312. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1313. if (stageChangeNum !== 0) {
  1314. throw '该变更令已被调用,无法重新审批';
  1315. }
  1316. // 重新审批
  1317. const result = await ctx.service.change.checkAgain(changeData.cid);
  1318. if (!result) {
  1319. throw '重新审批失败';
  1320. }
  1321. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1322. ctx.body = {
  1323. err: 0,
  1324. url: ctx.request.header.referer,
  1325. msg: '',
  1326. };
  1327. } catch (err) {
  1328. console.log(err);
  1329. // ctx.redirect(ctx.request.header.referer);
  1330. ctx.body = {
  1331. err: 1,
  1332. // url: ctx.request.header.referer,
  1333. msg: err,
  1334. };
  1335. }
  1336. }
  1337. /**
  1338. * 变更令修订重新上报
  1339. * @param {Object} ctx - egg全局变量
  1340. * @return {void}
  1341. */
  1342. async checkRevise(ctx) {
  1343. try {
  1344. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1345. if (!changeData) {
  1346. throw '变更令数据错误';
  1347. }
  1348. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== changeData.uid) {
  1349. throw '您无权进行该操作';
  1350. }
  1351. if (ctx.session.sessionUser.loginStatus === 0) {
  1352. const code = ctx.request.body.code;
  1353. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1354. if (!pa.auth_mobile) {
  1355. throw '未绑定手机号';
  1356. }
  1357. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1358. const cacheCode = await app.redis.get(cacheKey);
  1359. // console.log(cacheCode);
  1360. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1361. throw '验证码不正确!';
  1362. }
  1363. }
  1364. // 获取是否已存在调用变更令
  1365. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1366. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1367. // if (stageChangeNum !== 0) {
  1368. // throw '该变更令已被调用,无法重新审批';
  1369. // }
  1370. // 重新审批
  1371. const result = await ctx.service.change.checkRevise(changeData.cid);
  1372. if (!result) {
  1373. throw '修订发起失败';
  1374. }
  1375. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1376. ctx.body = {
  1377. err: 0,
  1378. url: ctx.request.header.referer,
  1379. msg: '',
  1380. };
  1381. } catch (err) {
  1382. console.log(err);
  1383. // ctx.redirect(ctx.request.header.referer);
  1384. ctx.body = {
  1385. err: 1,
  1386. // url: ctx.request.header.referer,
  1387. msg: err,
  1388. };
  1389. }
  1390. }
  1391. /**
  1392. * 获取变更清单
  1393. * @param ctx
  1394. * @return {Promise<void>}
  1395. */
  1396. async bills(ctx) {
  1397. try {
  1398. const data = JSON.parse(ctx.request.body.data);
  1399. const responseData = { err: 0, msg: '', data: [] };
  1400. switch (data.type) {
  1401. case 'gather':
  1402. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1403. break;
  1404. default:
  1405. throw '查询的数据不存在';
  1406. }
  1407. ctx.body = responseData;
  1408. } catch (err) {
  1409. this.log(err);
  1410. this.ajaxErrorBody(err, '获取变更清单失败');
  1411. }
  1412. }
  1413. /**
  1414. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1415. * @param ctx
  1416. * @return {Promise<void>}
  1417. */
  1418. async checkCodeRepeat(ctx) {
  1419. const responseData = {
  1420. err: 0,
  1421. msg: '',
  1422. data: '',
  1423. };
  1424. try {
  1425. const tenderId = ctx.params.id;
  1426. const cid = ctx.params.cid;
  1427. const data = JSON.parse(ctx.request.body.data);
  1428. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1429. if (result) {
  1430. throw '该变更令号(批复编号)已使用';
  1431. }
  1432. } catch (err) {
  1433. responseData.err = 1;
  1434. responseData.msg = err;
  1435. }
  1436. ctx.body = responseData;
  1437. }
  1438. /**
  1439. * 拷贝其他变更令
  1440. * @param {object} ctx - 全局上下文
  1441. */
  1442. async copyChange(ctx) {
  1443. const responseData = {
  1444. err: 0,
  1445. msg: '',
  1446. data: '',
  1447. };
  1448. try {
  1449. const cid = ctx.params.cid;
  1450. const copy_cid = JSON.parse(ctx.request.body.data);
  1451. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1452. if (!result) {
  1453. responseData.err = 1;
  1454. responseData.msg = '拷贝失败!';
  1455. }
  1456. } catch (error) {
  1457. responseData.err = 1;
  1458. responseData.msg = error;
  1459. }
  1460. ctx.body = responseData;
  1461. }
  1462. /**
  1463. * 修订 详细页面(Get)
  1464. * @param ctx
  1465. * @return {Promise<void>}
  1466. */
  1467. async reviseInfo(ctx) {
  1468. try {
  1469. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1470. throw '该功能已关闭';
  1471. }
  1472. const change = ctx.change;
  1473. let edit = true;
  1474. let changing = false;
  1475. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1476. // throw '本条变更审批中或已完成,无法操作台账数据';
  1477. edit = false;
  1478. changing = true;
  1479. }
  1480. let revising = false;
  1481. // 判断是否在修订中,是则无法操作本页
  1482. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1483. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1484. // throw '台账修订中,无法操作台账数据';
  1485. edit = false;
  1486. revising = true;
  1487. }
  1488. const renderData = await this._getDefaultReviseInfoData(ctx, change, edit);
  1489. // 台账只读、使用数据
  1490. renderData.readOnly = !edit;
  1491. renderData.changing = changing;
  1492. renderData.revising = revising;
  1493. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1494. } catch (err) {
  1495. this.log(err);
  1496. ctx.redirect(ctx.request.header.referer);
  1497. }
  1498. }
  1499. async _getDefaultReviseInfoData(ctx, change, edit) {
  1500. const [ledgerSpread, posSpread] = this._getSpreadSetting(change, edit);
  1501. const sjsRela = await this.ctx.service.project.getSjsRela(ctx.session.sessionProject.id);
  1502. this.ctx.helper.refreshSpreadShow(sjsRela.ledgerCol, [ledgerSpread, posSpread]);
  1503. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1504. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1505. return {
  1506. change,
  1507. tender: ctx.tender.data,
  1508. ledgerSpread, posSpread, tenderMenu, measureType,
  1509. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1510. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1511. stdBills,
  1512. auditConst: audit.flow,
  1513. audit: audit.flow,
  1514. stdChapters,
  1515. };
  1516. }
  1517. /**
  1518. * 获取SpreadSetting
  1519. * @private
  1520. */
  1521. _getSpreadSetting(change, edit) {
  1522. const _ = this.app._;
  1523. function removeFieldCols(setting, cols) {
  1524. _.remove(setting.cols, function(c) {
  1525. return cols.indexOf(c.field) > -1;
  1526. });
  1527. }
  1528. const tender = this.ctx.tender;
  1529. const setting = tender.data.measure_type === measureType.tz.value
  1530. ? (tender.info.display.ledger.clQty ? spreadConst.withCl : spreadConst.withoutCl)
  1531. : (tender.info.display.ledger.clQty ? spreadConst.withClGcl : spreadConst.withoutClGcl);
  1532. const ledger = JSON.parse(JSON.stringify(setting.ledger));
  1533. const pos = setting.pos ? JSON.parse(JSON.stringify(setting.pos)) : spreadConst.blank;
  1534. // if (change.status === audit.flow.status.checking || change.status === audit.flow.status.checked) {
  1535. // ledger.readOnly = true;
  1536. // pos.readOnly = true;
  1537. // }
  1538. if (!edit) {
  1539. ledger.readOnly = true;
  1540. pos.readOnly = true;
  1541. }
  1542. if (tender.data.measure_type === measureType.tz.value) {
  1543. removeFieldCols(ledger, spreadConst.filterCols.tzWithoutCols);
  1544. }
  1545. if (!tender.info.display.ledger.dgnQty) {
  1546. removeFieldCols(ledger, spreadConst.filterCols.dgnCols);
  1547. }
  1548. return [ledger, pos];
  1549. }
  1550. async updateRevise(ctx) {
  1551. try {
  1552. if (!ctx.tender.data) throw '标段数据错误';
  1553. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1554. throw '该功能已关闭';
  1555. }
  1556. const data = JSON.parse(ctx.request.body.data);
  1557. if (!data.postType || !data.postData) throw '数据错误';
  1558. const responseData = { err: 0, msg: '', data: {} };
  1559. const change = ctx.change;
  1560. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1561. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1562. }
  1563. // 判断是否在修订中,是则无法操作本页
  1564. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1565. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1566. throw '台账修订中,无法操作新增部位数据';
  1567. }
  1568. // const revise = await this.checkRevise(ctx);
  1569. //
  1570. switch (data.postType) {
  1571. case 'add':
  1572. case 'delete':
  1573. case 'up-move':
  1574. case 'down-move':
  1575. case 'up-level':
  1576. case 'down-level':
  1577. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1578. break;
  1579. case 'update':
  1580. ctx.helper.checkDgnQtyPrecision(data.postData);
  1581. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1582. break;
  1583. case 'paste-block':
  1584. responseData.data = await this._pasteBlock(ctx, data.postData);
  1585. break;
  1586. case 'add-std':
  1587. responseData.data = await this._addStd(ctx, data.postData);
  1588. break;
  1589. case 'add-deal':
  1590. responseData.data = await this._addDeal(ctx, data.postData);
  1591. break;
  1592. // case 'batch-insert':
  1593. // responseData.data = await this._batchInsert(ctx, data.postData);
  1594. // break;
  1595. case 'pos':
  1596. responseData.data = await this._updatePos(ctx, data);
  1597. break;
  1598. default:
  1599. throw '未知操作';
  1600. }
  1601. ctx.body = responseData;
  1602. } catch (err) {
  1603. this.log(err);
  1604. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1605. }
  1606. }
  1607. async _billsBase(ctx, type, data) {
  1608. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1609. if (type !== 'add') {
  1610. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1611. }
  1612. switch (type) {
  1613. case 'add':
  1614. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1615. case 'delete':
  1616. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1617. case 'up-move':
  1618. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1619. case 'down-move':
  1620. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1621. case 'up-level':
  1622. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1623. case 'down-level':
  1624. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1625. default:
  1626. throw '未知操作';
  1627. }
  1628. }
  1629. /**
  1630. * 复制粘贴整块
  1631. *
  1632. * @param ctx
  1633. * @return {Promise<void>}
  1634. */
  1635. async _pasteBlock(ctx, data) {
  1636. if ((isNaN(data.id) || data.id <= 0) ||
  1637. (!data.tid && data.tid <= 0) ||
  1638. (!data.block || data.block.length <= 0)) throw '参数错误';
  1639. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1640. }
  1641. /**
  1642. * 从标准项目表添加数据
  1643. * @param ctx
  1644. * @return {Promise<void>}
  1645. */
  1646. async _addStd(ctx, data) {
  1647. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1648. // todo 校验项目是否使用该库的权限
  1649. let stdLib,
  1650. addType;
  1651. switch (data.stdType) {
  1652. case 'xmj':
  1653. stdLib = ctx.service.stdXmj;
  1654. addType = stdDataAddType.withParent;
  1655. break;
  1656. case 'gcl':
  1657. stdLib = ctx.service.stdGcl;
  1658. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1659. if (selectNode.b_code) {
  1660. addType = stdDataAddType.next;
  1661. } else {
  1662. addType = stdDataAddType.child;
  1663. }
  1664. break;
  1665. default:
  1666. throw '未知标准库';
  1667. }
  1668. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1669. switch (addType) {
  1670. case stdDataAddType.child:
  1671. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1672. case stdDataAddType.next:
  1673. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1674. case stdDataAddType.withParent:
  1675. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1676. default:
  1677. throw '未知添加方式';
  1678. }
  1679. }
  1680. /**
  1681. * 从签约清单添加节点
  1682. * @param ctx
  1683. * @return {Promise<void>}
  1684. */
  1685. async _addDeal(ctx, data) {
  1686. if (!data.type || !data.dealBills) throw '数据错误';
  1687. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1688. if (data.type === 'child') {
  1689. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1690. } else if (data.type === 'next') {
  1691. data.dealBills.ccid = ctx.change.cid;
  1692. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1693. }
  1694. throw '数据错误';
  1695. }
  1696. /**
  1697. * 批量插入数据
  1698. *
  1699. * data = {id, batchData, batchType}
  1700. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1701. * data.batchData = [{name, children}] -- 项目节列表
  1702. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1703. *
  1704. * @param ctx
  1705. * @return {Promise<void>}
  1706. */
  1707. async _batchInsert(ctx, data) {
  1708. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1709. switch (data.batchType) {
  1710. case 'child':
  1711. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1712. case 'next':
  1713. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1714. default:
  1715. throw '参数错误';
  1716. }
  1717. }
  1718. async _updatePos(ctx, data) {
  1719. await this.checkMeasureType(measureType.tz.value);
  1720. if (!data.posPostType) throw '数据错误';
  1721. switch (data.posPostType) {
  1722. case 'add':
  1723. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1724. case 'update':
  1725. if (data.postData instanceof Array) {
  1726. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1727. }
  1728. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1729. case 'delete':
  1730. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1731. case 'paste':
  1732. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1733. default:
  1734. throw '未知操作';
  1735. }
  1736. }
  1737. async _filterChangesProject(ctx, status = 0) {
  1738. const tenderId = ctx.params.id;
  1739. ctx.session.sessionUser.tenderId = tenderId;
  1740. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1741. // const tender = ctx.tender;
  1742. // const tenderList = await this.service.tender.getList();
  1743. const page = ctx.page;
  1744. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1745. const orders = ctx.query.order ? ctx.query.order : 0;
  1746. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1747. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1748. for (const c of changes) {
  1749. c.curAuditor = await ctx.service.changeProjectAudit.getAuditorByStatus(c.id, c.status, c.times);
  1750. }
  1751. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1752. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1753. ? JSON.parse(accountInfo.permission) : null;
  1754. // let page_total = 0;
  1755. // if (changes !== null) {
  1756. // let i = 0;
  1757. // for (const c of changes) {
  1758. // page_total = ctx.helper.add(page_total, c.total_price);
  1759. // const status = c.status === audit.uncheck ? 0 : 1;
  1760. // // 根据审批人对当前变更令的状态取不同的展示方式。
  1761. // let changeAudit = '';
  1762. // let auditStatus = 0;
  1763. // switch (c.status) {
  1764. // case 1:
  1765. // auditStatus = 1;
  1766. // break;
  1767. // case 2:
  1768. // changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  1769. // auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  1770. // break;
  1771. // case 3:
  1772. // case 4:
  1773. // auditStatus = 0;
  1774. // changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  1775. // break;
  1776. // case 5:
  1777. // changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  1778. // auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  1779. // const back_changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  1780. // c.stageChangeNum = this.ctx.helper.sum(back_changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1781. // break;
  1782. // case 6:
  1783. // changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  1784. // const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  1785. // auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  1786. // break;
  1787. // case 9:
  1788. // auditStatus = 9;
  1789. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  1790. // c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1791. // break;
  1792. // default:
  1793. // break;
  1794. // }
  1795. // changes[i].changeAudit = changeAudit;
  1796. // changes[i].auditStatus = auditStatus;
  1797. // i++;
  1798. // }
  1799. // }
  1800. // 分页相关
  1801. const pageInfo = {
  1802. page,
  1803. total: Math.ceil(total / app.config.pageSize),
  1804. queryData: JSON.stringify(ctx.urlInfo.query),
  1805. };
  1806. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  1807. filter.count = [];
  1808. 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);
  1809. 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);
  1810. 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);
  1811. 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);
  1812. 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);
  1813. let codeRule = [];
  1814. let c_connector = '1';
  1815. let c_rule_first = 1;
  1816. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  1817. if (tender.c_code_rules) {
  1818. const c_code_rules = JSON.parse(tender.c_code_rules);
  1819. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  1820. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  1821. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  1822. }
  1823. for (const rule of codeRule) {
  1824. switch (rule.rule_type) {
  1825. case codeRuleConst.measure.ruleType.dealCode:
  1826. rule.preview = ctx.tender.info.deal_info.dealCode;
  1827. break;
  1828. case codeRuleConst.measure.ruleType.tenderName:
  1829. rule.preview = tender.name;
  1830. break;
  1831. case codeRuleConst.measure.ruleType.inDate:
  1832. rule.preview = moment().format('YYYY');
  1833. break;
  1834. case codeRuleConst.measure.ruleType.text:
  1835. rule.preview = rule.text;
  1836. break;
  1837. case codeRuleConst.measure.ruleType.addNo:
  1838. const s = '0000000000';
  1839. rule.preview = s.substr(s.length - rule.format);
  1840. break;
  1841. default: break;
  1842. }
  1843. }
  1844. const renderData = {
  1845. uid: ctx.session.sessionUser.accountId,
  1846. userPermission,
  1847. tender,
  1848. pageInfo,
  1849. changes,
  1850. status,
  1851. rule_type,
  1852. codeRule,
  1853. c_connector,
  1854. c_rule_first,
  1855. filter,
  1856. ruleType: codeRuleConst.ruleType[rule_type],
  1857. dealCode: ctx.tender.info.deal_info.dealCode,
  1858. auditConst: audit.changeProject,
  1859. ruleConst: codeRuleConst.measure,
  1860. changeConst,
  1861. tenderMenu: this.menu.tenderMenu,
  1862. preUrl: '/tender/' + tender.id,
  1863. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  1864. };
  1865. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  1866. }
  1867. /**
  1868. * 变更立项列表 页面 (Get)
  1869. *
  1870. * @param {Object} ctx - egg全局变量
  1871. * @return {void}
  1872. */
  1873. async project(ctx) {
  1874. try {
  1875. await this._filterChangesProject(ctx);
  1876. } catch (err) {
  1877. this.log(err);
  1878. ctx.redirect('/dashboard');
  1879. }
  1880. }
  1881. /**
  1882. * 新增变更立项 (Post)
  1883. *
  1884. * @param {Object} ctx - egg全局变量
  1885. * @return {void}
  1886. */
  1887. async projectAdd(ctx) {
  1888. try {
  1889. const tenderId = ctx.params.id;
  1890. if (!tenderId) {
  1891. throw '当前未打开标段';
  1892. }
  1893. const data = JSON.parse(ctx.request.body.data);
  1894. if (!data.code || data.code === '' || !data.name || data.name === '') {
  1895. throw '变更立项书编号不能为空';
  1896. }
  1897. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  1898. ctx.body = { err: 0, msg: '', data: change };
  1899. } catch (err) {
  1900. this.log(err);
  1901. ctx.body = { err: 1, msg: err.toString() };
  1902. }
  1903. }
  1904. /**
  1905. * 变更管理 状态筛选 页面 (Get)
  1906. * @param {Object} ctx - egg全局变量
  1907. * @return {void}
  1908. */
  1909. async projectStatus(ctx) {
  1910. try {
  1911. const status = parseInt(ctx.params.status);
  1912. await this._filterChangesProject(ctx, status);
  1913. } catch (err) {
  1914. this.logger.error(err);
  1915. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  1916. }
  1917. }
  1918. /**
  1919. * 获取审批界面所需的 原报、审批人数据等
  1920. * @param ctx
  1921. * @return {Promise<void>}
  1922. * @private
  1923. */
  1924. async _getChangeProjectAuditViewData(ctx) {
  1925. const auditConst = audit.changeProject;
  1926. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  1927. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  1928. ctx.change.auditHistory = [];
  1929. if (times >= 1) {
  1930. for (let i = 1; i <= times; i++) {
  1931. ctx.change.auditHistory.push(await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, i));
  1932. }
  1933. }
  1934. // 获取审批流程中左边列表
  1935. ctx.change.auditors2 = ctx.change.status === auditConst.status.back && ctx.change.user_id !== ctx.session.sessionUser.accountId ?
  1936. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times) :
  1937. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  1938. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.back) {
  1939. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  1940. }
  1941. }
  1942. async projectInformation(ctx) {
  1943. try {
  1944. const whiteList = this.ctx.app.config.multipart.whitelist;
  1945. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  1946. // 获取附件列表
  1947. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  1948. await this._getChangeProjectAuditViewData(ctx);
  1949. const renderData = {
  1950. tender,
  1951. change: ctx.change,
  1952. changeConst,
  1953. auditConst: audit.changeProject,
  1954. fileList,
  1955. whiteList,
  1956. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project_information),
  1957. preUrl: '/tender/' + ctx.tender.id + '/change/project/' + ctx.change.id + '/information',
  1958. };
  1959. 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)) {
  1960. // data.accountGroup = accountGroup;
  1961. // 获取所有项目参与者
  1962. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  1963. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  1964. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  1965. });
  1966. renderData.accountList = accountList;
  1967. renderData.accountGroup = accountGroup.map((item, idx) => {
  1968. const groupList = accountList.filter(item => item.account_group === idx);
  1969. return { groupName: item, groupList };
  1970. });
  1971. }
  1972. await this.layout('change/project_information.ejs', renderData, 'change/project_information_modal.ejs');
  1973. } catch (err) {
  1974. this.log(err);
  1975. ctx.redirect('/tender/' + ctx.params.id + '/change');
  1976. }
  1977. }
  1978. // 审批相关
  1979. /**
  1980. * 添加审批人
  1981. * @param ctx
  1982. * @return {Promise<void>}
  1983. */
  1984. async addProjectAudit(ctx) {
  1985. try {
  1986. const auditConst = audit.changeProject;
  1987. const data = JSON.parse(ctx.request.body.data);
  1988. const id = this.app._.toInteger(data.auditorId);
  1989. if (isNaN(id) || id <= 0) {
  1990. throw '参数错误';
  1991. }
  1992. // 检查权限等
  1993. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  1994. throw '您无权添加审核人';
  1995. }
  1996. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  1997. throw '当前不允许添加审核人';
  1998. }
  1999. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2000. // 检查审核人是否已存在
  2001. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2002. if (exist) {
  2003. throw '该审核人已存在,请勿重复添加';
  2004. }
  2005. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  2006. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  2007. const result = await ctx.service.changeProjectAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  2008. if (!result) {
  2009. throw '添加审核人失败';
  2010. }
  2011. const auditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2012. ctx.body = { err: 0, msg: '', data: auditors };
  2013. } catch (err) {
  2014. this.log(err);
  2015. ctx.body = { err: 1, msg: err.toString(), data: null };
  2016. }
  2017. }
  2018. /**
  2019. * 移除审批人
  2020. * @param ctx
  2021. * @return {Promise<void>}
  2022. */
  2023. async deleteProjectAudit(ctx) {
  2024. try {
  2025. const data = JSON.parse(ctx.request.body.data);
  2026. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2027. if (isNaN(id) || id <= 0) {
  2028. throw '参数错误';
  2029. }
  2030. const result = await ctx.service.changeProjectAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2031. if (!result) {
  2032. throw '移除审核人失败';
  2033. }
  2034. const auditors = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2035. ctx.body = { err: 0, msg: '', data: auditors };
  2036. } catch (err) {
  2037. ctx.body = { err: 1, msg: err.toString(), data: null };
  2038. }
  2039. }
  2040. /**
  2041. * 上传附件
  2042. * @param {*} ctx 上下文
  2043. */
  2044. async uploadProjectFile(ctx) {
  2045. let stream;
  2046. try {
  2047. const auditConst = audit.changeProject;
  2048. // this._checkAdvanceFileCanModify(ctx);
  2049. const parts = this.ctx.multipart({
  2050. autoFields: true,
  2051. });
  2052. const files = [];
  2053. const create_time = Date.parse(new Date()) / 1000;
  2054. let idx = 0;
  2055. const extra_upload = ctx.change.status === auditConst.status.checked;
  2056. while ((stream = await parts()) !== undefined) {
  2057. if (!stream.filename) {
  2058. // 如果没有传入直接返回
  2059. return;
  2060. }
  2061. const fileInfo = path.parse(stream.filename);
  2062. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_project/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2063. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2064. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2065. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2066. ++idx;
  2067. stream && (await sendToWormhole(stream));
  2068. }
  2069. const in_time = new Date();
  2070. const payload = files.map(file => {
  2071. let idx;
  2072. if (Array.isArray(parts.field.name)) {
  2073. idx = parts.field.name.findIndex(name => name === file.name);
  2074. } else {
  2075. idx = 'isString';
  2076. }
  2077. const newFile = {
  2078. tid: ctx.tender.id,
  2079. cpid: ctx.change.id,
  2080. uid: ctx.session.sessionUser.accountId,
  2081. filename: file.name,
  2082. fileext: file.ext,
  2083. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2084. filepath: file.filepath,
  2085. upload_time: in_time,
  2086. extra_upload,
  2087. };
  2088. return newFile;
  2089. });
  2090. // 执行文件信息写入数据库
  2091. await ctx.service.changeProjectAtt.saveFileMsgToDb(payload);
  2092. // 将最新的当前标段的所有文件信息返回
  2093. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2094. ctx.body = { err: 0, msg: '', data };
  2095. } catch (err) {
  2096. stream && (await sendToWormhole(stream));
  2097. this.log(err);
  2098. ctx.body = { err: 1, msg: err.toString(), data: null };
  2099. }
  2100. }
  2101. /**
  2102. * 删除附件
  2103. * @param {Ojbect} ctx 上下文
  2104. */
  2105. async deleteProjectFile(ctx) {
  2106. try {
  2107. const { id } = JSON.parse(ctx.request.body.data);
  2108. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2109. if (fileInfo || Object.keys(fileInfo).length) {
  2110. // 先删除文件
  2111. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2112. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2113. // 再删除数据库
  2114. await ctx.service.changeProjectAtt.delete(id);
  2115. } else {
  2116. throw '不存在该文件';
  2117. }
  2118. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2119. ctx.body = { err: 0, msg: '请求成功', data };
  2120. } catch (err) {
  2121. this.log(err);
  2122. ctx.body = { err: 1, msg: err.toString(), data: null };
  2123. }
  2124. }
  2125. /**
  2126. * 下载附件
  2127. * @param {Object} ctx - egg全局变量
  2128. * @return {void}
  2129. */
  2130. async downloadProjectFile(ctx) {
  2131. const id = ctx.params.fid;
  2132. if (id) {
  2133. try {
  2134. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2135. if (fileInfo !== undefined && fileInfo !== '') {
  2136. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2137. // 解决中文无法下载问题
  2138. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2139. let disposition = '';
  2140. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2141. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.file_name);
  2142. } else if (userAgent.indexOf('firefox') >= 0) {
  2143. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.file_name) + '"';
  2144. } else {
  2145. /* safari等其他非主流浏览器只能自求多福了 */
  2146. disposition = 'attachment; filename=' + new Buffer(fileInfo.file_name).toString('binary');
  2147. }
  2148. ctx.response.set({
  2149. 'Content-Type': 'application/octet-stream',
  2150. 'Content-Disposition': disposition,
  2151. 'Content-Length': fileInfo.file_size,
  2152. });
  2153. // ctx.body = await fs.createReadStream(fileName);
  2154. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2155. } else {
  2156. throw '不存在该文件';
  2157. }
  2158. } catch (err) {
  2159. this.log(err);
  2160. this.setMessage(err.toString(), this.messageType.ERROR);
  2161. }
  2162. }
  2163. }
  2164. async projectInformationSave(ctx) {
  2165. try {
  2166. const data = JSON.parse(ctx.request.body.data);
  2167. if (data.name === 'code') {
  2168. const info = await ctx.service.changeProject.isRepeat(ctx.change.id, data.val, ctx.tender.id, ctx.change.type);
  2169. if (info) {
  2170. throw '该编号已存在';
  2171. }
  2172. }
  2173. const result = await ctx.service.changeProject.saveInfo(ctx.change.id, data);
  2174. if (!result) {
  2175. throw '修改失败';
  2176. }
  2177. ctx.body = { err: 0, msg: '请求成功', data: null };
  2178. } catch (err) {
  2179. this.log(err);
  2180. ctx.body = { err: 1, msg: err.toString(), data: null };
  2181. }
  2182. }
  2183. /**
  2184. * 上报和重新上报
  2185. * @param ctx
  2186. * @return {Promise<void>}
  2187. */
  2188. async startProjectAudit(ctx) {
  2189. try {
  2190. const auditConst = audit.changeProject;
  2191. // 检查权限等
  2192. if (!ctx.change) {
  2193. throw '数据错误';
  2194. }
  2195. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2196. throw '您无权上报该期数据';
  2197. }
  2198. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2199. throw '该材料调差期数据当前无法上报';
  2200. }
  2201. await ctx.service.changeProjectAudit.start(ctx.change.id, ctx.change.times);
  2202. ctx.redirect(ctx.request.header.referer);
  2203. } catch (err) {
  2204. this.log(err);
  2205. ctx.session.postError = err.toString();
  2206. ctx.redirect(ctx.request.header.referer);
  2207. }
  2208. }
  2209. /**
  2210. * 审批
  2211. * @param ctx
  2212. * @return {Promise<void>}
  2213. */
  2214. async checkProjectAudit(ctx) {
  2215. try {
  2216. const auditConst = audit.changeProject;
  2217. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2218. throw '当前材料调差期数据有误';
  2219. }
  2220. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  2221. throw '您无权进行该操作';
  2222. }
  2223. const data = {
  2224. checkType: parseInt(ctx.request.body.checkType),
  2225. opinion: ctx.request.body.opinion,
  2226. };
  2227. if (!data.checkType || isNaN(data.checkType)) {
  2228. throw '提交数据错误';
  2229. }
  2230. // if (data.checkType === auditConst.status.checkNo) {
  2231. // if (!data.checkType || isNaN(data.checkType)) {
  2232. // throw '提交数据错误';
  2233. // }
  2234. // }
  2235. await ctx.service.changeProjectAudit.check(ctx.change.id, data, ctx.change.times);
  2236. ctx.redirect(ctx.request.header.referer);
  2237. } catch (err) {
  2238. this.log(err);
  2239. ctx.session.postError = err.toString();
  2240. ctx.redirect(ctx.request.header.referer);
  2241. }
  2242. }
  2243. }
  2244. return ChangeController;
  2245. };