cost_controller.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. 'use strict';
  2. /**
  3. *
  4. * 成本管理
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const audit = require('../const/audit');
  10. const shenpiConst = require('../const/shenpi');
  11. const moment = require('moment');
  12. const sendToWormhole = require('stream-wormhole');
  13. const fs = require('fs');
  14. const path = require('path');
  15. module.exports = app => {
  16. class CostController extends app.BaseController {
  17. constructor(ctx) {
  18. super(ctx);
  19. ctx.showProject = true;
  20. // ctx.showTitle = true;
  21. }
  22. loadMenu(ctx) {
  23. super.loadMenu(ctx);
  24. // 虚拟menu,以保证标题显示正确
  25. ctx.menu = {
  26. name: '成本管理',
  27. display: false,
  28. caption: '成本管理',
  29. controller: 'cost',
  30. };
  31. }
  32. async tender(ctx) {
  33. try {
  34. if (!ctx.subProject.page_show.cost) throw '该功能已关闭';
  35. const renderData = {
  36. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.cost.tender),
  37. };
  38. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  39. renderData.accountList = accountList;
  40. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  41. const accountGroupList = unitList.map(item => {
  42. const groupList = accountList.filter(item1 => item1.company === item.name);
  43. return { groupName: item.name, groupList };
  44. }).filter(x => { return x.groupList.length > 0; });
  45. renderData.accountGroup = accountGroupList;
  46. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  47. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'cost', ctx.session.sessionUser.is_admin ? 'all' : '');
  48. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  49. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  50. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('cost');
  51. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('cost');
  52. renderData.costLedgerTemplates = await ctx.app.mysql.select('zh_bills_template_list', { where: { sub_type: 1} });
  53. renderData.costAnalysisTemplates = await ctx.app.mysql.select('zh_bills_template_list', { where: { sub_type: 2} });
  54. renderData.costCalcTemplates = await ctx.service.calcTmpl.getAllTemplate(this.ctx.session.sessionProject.id, 'cost');
  55. await this.layout('cost/tender.ejs', renderData, 'cost/tender_modal.ejs');
  56. } catch (err) {
  57. ctx.log(err);
  58. ctx.postError(err, '无法查看成本管理数据');
  59. ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
  60. }
  61. }
  62. async member(ctx) {
  63. try {
  64. const data = JSON.parse(ctx.request.body.data);
  65. const result = await ctx.service.tenderPermission.getPartsPermission(data.tid, data.parts);
  66. ctx.body = { err: 0, msg: '', data: result };
  67. } catch (err) {
  68. ctx.log(err);
  69. ctx.ajaxErrorBody(err, '查询标段权限错误');
  70. }
  71. }
  72. async memberSave(ctx) {
  73. try {
  74. const data = JSON.parse(ctx.request.body.data);
  75. await ctx.service.tenderPermission.savePermission(data.tid, data.member, data.permissionBlock);
  76. ctx.body = { err: 0, msg: '', data: '' };
  77. } catch (err) {
  78. ctx.log(err);
  79. ctx.ajaxErrorBody(err, '保存标段权限错误');
  80. }
  81. }
  82. async ledger(ctx) {
  83. try {
  84. const stage_type = this.ctx.service.costStage.stageType.ledger.key;
  85. const stages = await this.ctx.service.costStage.getAllStages(ctx.tender.id, stage_type, 'DESC');
  86. for (const s of stages) {
  87. if (s.audit_status !== audit.common.status.checked) await this.ctx.service.costStage.loadUser(s);
  88. s.can_del = (s.create_user_id === ctx.session.sessionUser.accountId || ctx.session.sessionUser.is_admin)
  89. && (s.audit_status === audit.common.status.uncheck || s.audit_status === audit.common.status.checkNo);
  90. }
  91. const renderData = {
  92. stage_type,
  93. auditType: audit.auditType,
  94. stages,
  95. auditConst: audit.common,
  96. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.cost.cost_stage)
  97. };
  98. await this.layout('cost/ledger_list.ejs', renderData, 'cost/ledger_list_modal.ejs');
  99. } catch(err) {
  100. ctx.log(err);
  101. ctx.redirect(ctx.request.header.referer);
  102. }
  103. }
  104. async book(ctx) {
  105. try {
  106. const stage_type = this.ctx.service.costStage.stageType.book.key;
  107. const stages = await this.ctx.service.costStage.getAllStages(ctx.tender.id, stage_type, 'DESC');
  108. for (const s of stages) {
  109. if (s.audit_status !== audit.common.status.checked) await this.ctx.service.costStage.loadUser(s);
  110. s.can_del = (s.create_user_id === ctx.session.sessionUser.accountId || ctx.session.sessionUser.is_admin)
  111. && (s.audit_status === audit.common.status.uncheck || s.audit_status === audit.common.status.checkNo);
  112. }
  113. const renderData = {
  114. stage_type,
  115. auditType: audit.auditType,
  116. stages,
  117. auditConst: audit.common,
  118. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.cost.cost_stage)
  119. };
  120. await this.layout('cost/book_list.ejs', renderData, 'cost/book_list_modal.ejs');
  121. } catch(err) {
  122. ctx.log(err);
  123. ctx.redirect(ctx.request.header.referer);
  124. }
  125. }
  126. async analysis(ctx) {
  127. try {
  128. const stage_type = this.ctx.service.costStage.stageType.analysis.key;
  129. const stages = await this.ctx.service.costStage.getAllStages(ctx.tender.id, stage_type, 'DESC');
  130. for (const s of stages) {
  131. if (s.audit_status !== audit.common.status.checked) await this.ctx.service.costStage.loadUser(s);
  132. s.can_del = (s.create_user_id === ctx.session.sessionUser.accountId || ctx.session.sessionUser.is_admin)
  133. && (s.audit_status === audit.common.status.uncheck || s.audit_status === audit.common.status.checkNo);
  134. }
  135. const renderData = {
  136. stage_type,
  137. auditType: audit.auditType,
  138. stages,
  139. auditConst: audit.common,
  140. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.cost.cost_stage)
  141. };
  142. await this.layout('cost/ledger_list.ejs', renderData, 'cost/analysis_list_modal.ejs');
  143. } catch(err) {
  144. ctx.log(err);
  145. ctx.redirect(ctx.request.header.referer);
  146. }
  147. }
  148. async addStage(ctx) {
  149. const stage_type = ctx.request.body.stage_type;
  150. try {
  151. if (!ctx.permission.cost[stage_type + '_add']) throw '您无权创建期';
  152. const stage_date = ctx.request.body.date;
  153. if (!stage_date) throw '请选择年月';
  154. const stages = await ctx.service.costStage.getAllStages(ctx.tender.id, stage_type, 'DESC');
  155. const unCompleteCount = stages.filter(s => { return s.status !== auditConst.common.status.checked; }).length;
  156. if (unCompleteCount.length > 0) throw '最新一期未审批通过,请审批通过后再新增';
  157. const newStage = await ctx.service.costStage.add(ctx.tender.id, stage_type, stage_date);
  158. if (!newStage) throw '新增期失败';
  159. ctx.redirect(`/sp/${ctx.subProject.id}/cost/tender/${ctx.tender.id}/${stage_type}/${newStage.stage_order}`);
  160. } catch (err) {
  161. ctx.log(err);
  162. ctx.postError(err, '新增期失败');
  163. ctx.redirect(`/sp/${ctx.subProject.id}/cost/tender/${ctx.tender.id}/${stage_type}`);
  164. }
  165. }
  166. async delStage(ctx) {
  167. try {
  168. const stage_id = ctx.request.body.stage_id;
  169. const stage = await ctx.service.costStage.getDataById(stage_id);
  170. if (!stage) throw '删除的期不存在,请刷新页面';
  171. if (!ctx.session.sessionUser.is_admin && stage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权删除本期';
  172. // 获取最新的期数
  173. const stages = await ctx.service.costStage.getAllStages(ctx.tender.id, stage.stage_type, 'DESC');
  174. if (stage.id !== stages[0].id) throw '非最新一期,不可删除';
  175. await ctx.service.costStage.delete(stage_id);
  176. ctx.redirect(`/sp/${ctx.subProject.id}/cost/tender/${ctx.tender.id}/${stage.stage_type}`);
  177. } catch (err) {
  178. ctx.log(err);
  179. ctx.postError(err, '删除期失败');
  180. ctx.redirect(ctx.request.header.referer);
  181. }
  182. }
  183. /**
  184. * 期审批流程(POST)
  185. * @param ctx
  186. * @return {Promise<void>}
  187. */
  188. async loadAuditors(ctx) {
  189. try {
  190. const stageId = JSON.parse(ctx.request.body.data).id;
  191. const stage = await ctx.service.costStage.get(stageId);
  192. await ctx.service.costStage.loadUser(stage);
  193. await ctx.service.costStage.loadAuditViewData(stage);
  194. ctx.body = { err: 0, msg: '', data: stage };
  195. } catch (error) {
  196. ctx.log(error);
  197. ctx.body = { err: 1, msg: error.toString(), data: null };
  198. }
  199. }
  200. async _getStageAuditViewData(ctx) {
  201. await this.ctx.service.costStage.loadAuditViewData(ctx.costStage);
  202. }
  203. async stage(ctx) {
  204. const stageTypeInfo = ctx.service.costStage.stageType[ctx.costStage.stage_type];
  205. try {
  206. await this._getStageAuditViewData(ctx);
  207. // 流程审批人相关数据
  208. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  209. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  210. const accountGroup = unitList.map(item => {
  211. const groupList = accountList.filter(item1 => item1.company === item.name);
  212. return { groupName: item.name, groupList };
  213. }).filter(x => { return x.groupList.length > 0; });
  214. // 是否已验证手机短信
  215. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  216. const renderData = {
  217. auditConst: audit.common,
  218. auditType: audit.auditType,
  219. accountList,
  220. accountGroup,
  221. shenpiConst,
  222. authMobile: pa.auth_mobile,
  223. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.cost[`cost_stage_${stageTypeInfo.key}`]),
  224. shenpi_status: ctx.tender.info.shenpi[stageTypeInfo.shenpi_status] || 1,
  225. };
  226. await this.layout(`cost/${stageTypeInfo.key}.ejs`, renderData, `cost/${stageTypeInfo.key}_modal.ejs`);
  227. } catch (err) {
  228. ctx.log(err);
  229. ctx.postError(err, '读取成本报审错误');
  230. ctx.redirect(`/sp/${ctx.subProject.id}/cost/tender/${ctx.tender.id}/${stageTypeInfo.key}`);
  231. }
  232. }
  233. async _ledgerLoad(ctx) {
  234. try {
  235. const data = JSON.parse(ctx.request.body.data);
  236. const filter = data.filter.split(';');
  237. const responseData = { err: 0, msg: '', data: {}, hpack: [] };
  238. for (const f of filter) {
  239. switch (f) {
  240. case 'bills':
  241. responseData.data.bills = ctx.costStage.readOnly
  242. ? await ctx.service.costStageLedger.getReadData(ctx.costStage)
  243. : await ctx.service.costStageLedger.getEditData(ctx.costStage);
  244. break;
  245. case 'billsCompare':
  246. responseData.data[f] = await ctx.service.costStageLedger.getCompareData(ctx.costStage);
  247. break;
  248. case 'detail':
  249. responseData.data.detail = ctx.costStage.readOnly
  250. ? await ctx.service.costStageDetail.getReadData(ctx.costStage)
  251. : await ctx.service.costStageDetail.getEditData(ctx.costStage);
  252. break;
  253. case 'detailCompare':
  254. // todo
  255. responseData.data.detailCompare = await ctx.service.costStageDetail.getCompareData(ctx.costStage);
  256. break;
  257. case 'auditFlow':
  258. responseData.data[f] = await ctx.service.costStageAudit.getViewFlow(ctx.costStage);
  259. break;
  260. case 'att':
  261. responseData.data[f] = await ctx.service.costStageFile.getData(ctx.costStage.id, 'DESC');
  262. break;
  263. case 'tags':
  264. responseData.data[f] = await ctx.service.costStageTag.getDatas(ctx.costStage.id);
  265. break;
  266. default:
  267. responseData.data[f] = [];
  268. break;
  269. }
  270. }
  271. ctx.body = responseData;
  272. } catch (err) {
  273. this.log(err);
  274. ctx.body = { err: 1, msg: err.toString(), data: null };
  275. }
  276. }
  277. async _bookLoad(ctx) {
  278. }
  279. async _analysisLoad(ctx) {
  280. }
  281. async stageLoad(ctx) {
  282. const updateFun = `_${ctx.costStage.stage_type}Load`;
  283. if (this[updateFun]) {
  284. await this[updateFun](ctx);
  285. } else {
  286. ctx.ajaxErrorBody('未知期数据类型', '加载数据错误');
  287. }
  288. }
  289. async _billsBase(stage, type, data) {
  290. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  291. if (type !== 'add') {
  292. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  293. }
  294. switch (type) {
  295. case 'add':
  296. return await this.ctx.service.costStageLedger.addLedgerNode(stage, data.id, data.count);
  297. case 'delete':
  298. return await this.ctx.service.costStageLedger.delete(stage.id, data.id, data.count);
  299. case 'up-move':
  300. return await this.ctx.service.costStageLedger.upMoveNode(stage.id, data.id, data.count);
  301. case 'down-move':
  302. return await this.ctx.service.costStageLedger.downMoveNode(stage.id, data.id, data.count);
  303. case 'up-level':
  304. return await this.ctx.service.costStageLedger.upLevelNode(stage.id, data.id, data.count);
  305. case 'down-level':
  306. return await this.ctx.service.costStageLedger.downLevelNode(stage.id, data.id, data.count);
  307. }
  308. }
  309. async _ledgerUpdate(ctx) {
  310. try {
  311. const data = JSON.parse(ctx.request.body.data);
  312. if (!data.target) throw '数据错误';
  313. const responseData = { err: 0, msg: '', data: {} };
  314. if (data.target === 'ledger') {
  315. if (!data.postType || !data.postData) throw '数据错误';
  316. switch (data.postType) {
  317. case 'add':
  318. case 'delete':
  319. case 'up-move':
  320. case 'down-move':
  321. case 'up-level':
  322. case 'down-level':
  323. responseData.data = await this._billsBase(ctx.costStage, data.postType, data.postData);
  324. break;
  325. case 'update':
  326. responseData.data = await this.ctx.service.costStageLedger.updateCalc(ctx.costStage, data.postData);
  327. break;
  328. default:
  329. throw '未知操作';
  330. }
  331. } else if (data.target === 'detail') {
  332. responseData.data = await this.ctx.service.costStageDetail.updateDatas(data);
  333. }
  334. ctx.body = responseData;
  335. } catch (err) {
  336. this.log(err);
  337. ctx.body = this.ajaxErrorBody(err, '数据错误');
  338. }
  339. }
  340. async _bookUpdate(ctx) {
  341. try {
  342. const data = JSON.parse(ctx.request.body.data);
  343. if (!data.postType || !data.postData) throw '数据错误';
  344. const responseData = { err: 0, msg: '', data: {} };
  345. switch (data.postType) {
  346. case 'update':
  347. responseData.data = await this.ctx.service.costStageBook.updateCalc(ctx.costStage, data.postData);
  348. break;
  349. default:
  350. throw '未知操作';
  351. }
  352. ctx.body = responseData;
  353. } catch (err) {
  354. this.log(err);
  355. ctx.body = this.ajaxErrorBody(err, '数据错误');
  356. }
  357. }
  358. async _analysisBillsBase(stage, type, data) {
  359. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  360. if (type !== 'add') {
  361. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  362. }
  363. switch (type) {
  364. case 'add':
  365. return await this.ctx.service.costStageAnalysis.addSafeBillsNode(stage, data.id, data.count);
  366. case 'delete':
  367. return await this.ctx.service.costStageAnalysis.delete(stage.id, data.id, data.count);
  368. case 'up-move':
  369. return await this.ctx.service.costStageAnalysis.upMoveNode(stage.id, data.id, data.count);
  370. case 'down-move':
  371. return await this.ctx.service.costStageAnalysis.downMoveNode(stage.id, data.id, data.count);
  372. case 'up-level':
  373. return await this.ctx.service.costStageAnalysis.upLevelNode(stage.id, data.id, data.count);
  374. case 'down-level':
  375. return await this.ctx.service.costStageAnalysis.downLevelNode(stage.id, data.id, data.count);
  376. }
  377. }
  378. async _analysisUpdate(ctx) {
  379. try {
  380. const data = JSON.parse(ctx.request.body.data);
  381. if (!data.postType || !data.postData) throw '数据错误';
  382. const responseData = { err: 0, msg: '', data: {} };
  383. switch (data.postType) {
  384. case 'add':
  385. case 'delete':
  386. case 'up-move':
  387. case 'down-move':
  388. case 'up-level':
  389. case 'down-level':
  390. responseData.data = await this._analysisBillsBase(ctx.costStage, data.postType, data.postData);
  391. break;
  392. case 'update':
  393. responseData.data = await this.ctx.service.costStageAnalysis.updateCalc(ctx.costStage, data.postData);
  394. break;
  395. default:
  396. throw '未知操作';
  397. }
  398. ctx.body = responseData;
  399. } catch (err) {
  400. this.log(err);
  401. ctx.body = this.ajaxErrorBody(err, '数据错误');
  402. }
  403. }
  404. async stageUpdate(ctx) {
  405. const updateFun = `_${ctx.costStage.stage_type}Update`;
  406. if (this[updateFun]) {
  407. await this[updateFun](ctx);
  408. } else {
  409. ctx.ajaxErrorBody('未知期数据类型', '保存数据错误');
  410. }
  411. }
  412. async uploadStageFile(ctx) {
  413. let stream;
  414. try {
  415. const parts = ctx.multipart({ autoFields: true });
  416. let index = 0;
  417. const create_time = Date.parse(new Date()) / 1000;
  418. let stream = await parts();
  419. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  420. const rela_id = parts.field.rela_id;
  421. const rela_sub_id = parts.field.rela_sub_id;
  422. const uploadfiles = [];
  423. while (stream !== undefined) {
  424. if (!stream.filename) throw '未发现上传文件!';
  425. const fileInfo = path.parse(stream.filename);
  426. const filepath = `app/public/upload/${ctx.costStage.tid}/costStage/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  427. // 保存文件
  428. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  429. await sendToWormhole(stream);
  430. // 插入到stage_pay对应的附件列表中
  431. uploadfiles.push({
  432. rela_id, rela_sub_id,
  433. filename: fileInfo.name,
  434. fileext: fileInfo.ext,
  435. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  436. filepath,
  437. });
  438. ++index;
  439. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  440. stream = await parts();
  441. } else {
  442. stream = undefined;
  443. }
  444. }
  445. const result = await ctx.service.costStageFile.addFiles(ctx.costStage, uploadfiles, user);
  446. ctx.body = { err: 0, msg: '', data: result };
  447. } catch (error) {
  448. ctx.log(error);
  449. // 失败需要消耗掉stream 以防卡死
  450. if (stream) await sendToWormhole(stream);
  451. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  452. }
  453. }
  454. async deleteStageFile(ctx) {
  455. try {
  456. const data = JSON.parse(ctx.request.body.data);
  457. if (!data && !data.id) throw '缺少参数';
  458. const result = await ctx.service.costStageFile.delFiles(data.id);
  459. ctx.body = { err: 0, msg: '', data: result };
  460. } catch (error) {
  461. ctx.log(error);
  462. ctx.ajaxErrorBody(error, '删除附件失败');
  463. }
  464. }
  465. async tag(ctx) {
  466. try {
  467. const isRelaUser = ctx.costStage.userIds.indexOf(this.ctx.session.sessionUser.accountId) >= 0;
  468. const isValidTourist = ctx.permission.cost.view && ctx.tender.touristPermission.tag;
  469. if (!isRelaUser && !isValidTourist) throw '您无权进行该操作';
  470. const data = JSON.parse(ctx.request.body.data);
  471. const result = await ctx.service.costStageTag.update(data);
  472. ctx.body = { err: 0, msg: '', data: result };
  473. } catch (err) {
  474. console.log(err);
  475. this.log(err);
  476. ctx.body = this.ajaxErrorBody(err, '书签数据错误');
  477. }
  478. }
  479. }
  480. return CostController;
  481. };