safe_controller.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. 'use strict';
  2. /**
  3. * 标段管理控制器
  4. *
  5. * @author Mai
  6. * @date 2025/7/17
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  10. const auditType = require('../const/audit').auditType;
  11. const shenpiConst = require('../const/shenpi');
  12. const codeRuleConst = require('../const/code_rule');
  13. const contractConst = require('../const/contract');
  14. const moment = require('moment');
  15. const sendToWormhole = require('stream-wormhole');
  16. const fs = require('fs');
  17. const path = require('path');
  18. const PermissionCheck = require('../const/account_permission').PermissionCheck;
  19. module.exports = app => {
  20. class SafeController extends app.BaseController {
  21. constructor(ctx) {
  22. super(ctx);
  23. ctx.showProject = true;
  24. // ctx.showTitle = true;
  25. }
  26. loadMenu(ctx) {
  27. super.loadMenu(ctx);
  28. // 虚拟menu,以保证标题显示正确
  29. ctx.menu = {
  30. name: '安全管理',
  31. display: false,
  32. caption: '安全管理',
  33. controller: 'safe',
  34. };
  35. }
  36. async inspectionTender(ctx) {
  37. try {
  38. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  39. const renderData = {
  40. is_inspection: ctx.url.includes('inspection') ? 1 : 0,
  41. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
  42. };
  43. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  44. renderData.accountList = accountList;
  45. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  46. const accountGroupList = unitList.map(item => {
  47. const groupList = accountList.filter(item1 => item1.company === item.name);
  48. return { groupName: item.name, groupList };
  49. }).filter(x => { return x.groupList.length > 0; });
  50. // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  51. // renderData.accountGroup = unitList.map(item => {
  52. // const groupList = accountList.filter(item1 => item1.company === item.name);
  53. // return { groupName: item.name, groupList };
  54. // });
  55. renderData.accountGroup = accountGroupList;
  56. renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  57. renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_inspection', ctx.session.sessionUser.is_admin ? 'all' : '');
  58. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
  59. renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
  60. renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_inspection');
  61. renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_inspection');
  62. await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
  63. } catch (err) {
  64. ctx.log(err);
  65. ctx.postError(err, '无法查看安全巡检数据');
  66. ctx.redirect('/dashboard');
  67. }
  68. }
  69. /**
  70. * 变更管理 页面 (Get)
  71. *
  72. * @param {Object} ctx - egg全局变量
  73. * @return {void}
  74. */
  75. async inspection(ctx) {
  76. try {
  77. if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
  78. const status = parseInt(ctx.query.status) || 0;
  79. await this._filterInspection(ctx, status);
  80. } catch (err) {
  81. ctx.log(err);
  82. ctx.postError(err, '无法查看质量管理数据');
  83. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  84. }
  85. }
  86. // 质量巡检单功能
  87. async _filterInspection(ctx, status = 0) {
  88. try {
  89. ctx.session.sessionUser.tenderId = ctx.tender.id;
  90. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  91. const orders = ctx.query.order ? ctx.query.order : 0;
  92. const filter = JSON.parse(JSON.stringify(auditConst.inspection.filter));
  93. filter.count = [];
  94. filter.count[filter.status.pending] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
  95. filter.count[filter.status.uncheck] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
  96. filter.count[filter.status.checking] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
  97. filter.count[filter.status.rectification] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
  98. filter.count[filter.status.checked] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
  99. filter.count[filter.status.checkStop] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checkStop);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  100. const inspectionList = await ctx.service.safeInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
  101. const total = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status);
  102. const allAttList = inspectionList.length > 0 ? await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.helper._.map(inspectionList, 'id')) : [];
  103. for (const item of inspectionList) {
  104. item.attList = ctx.helper._.filter(allAttList, { qiid: item.id });
  105. }
  106. // 分页相关
  107. const page = ctx.page;
  108. const pageSize = ctx.pageSize;
  109. const pageInfo = {
  110. page,
  111. pageSizeSelect: 1,
  112. pageSize,
  113. total_num: total,
  114. total: Math.ceil(total / pageSize),
  115. queryData: JSON.stringify(ctx.urlInfo.query),
  116. };
  117. let codeRule = [];
  118. let c_connector = '1';
  119. let c_rule_first = 1;
  120. const rule_type = 'safe_inspection';
  121. const tender = await this.service.tender.getDataById(ctx.tender.id);
  122. if (tender.c_code_rules) {
  123. const c_code_rules = JSON.parse(tender.c_code_rules);
  124. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  125. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  126. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  127. }
  128. for (const rule of codeRule) {
  129. switch (rule.rule_type) {
  130. case codeRuleConst.measure.ruleType.dealCode:
  131. rule.preview = ctx.tender.info.deal_info.dealCode;
  132. break;
  133. case codeRuleConst.measure.ruleType.tenderName:
  134. rule.preview = tender.name;
  135. break;
  136. case codeRuleConst.measure.ruleType.inDate:
  137. rule.preview = moment().format('YYYY');
  138. break;
  139. case codeRuleConst.measure.ruleType.text:
  140. rule.preview = rule.text;
  141. break;
  142. case codeRuleConst.measure.ruleType.addNo:
  143. const s = '0000000000';
  144. rule.preview = s.substr(s.length - rule.format);
  145. break;
  146. default: break;
  147. }
  148. }
  149. const renderData = {
  150. moment,
  151. tender,
  152. permission: ctx.permission.safe_inspection,
  153. rule_type,
  154. codeRule,
  155. dealCode: ctx.tender.info.deal_info.dealCode,
  156. c_connector,
  157. c_rule_first,
  158. ruleType: codeRuleConst.ruleType[rule_type],
  159. ruleConst: codeRuleConst.measure,
  160. filter,
  161. inspectionList,
  162. auditType,
  163. auditConst: auditConst.inspection,
  164. status,
  165. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection),
  166. pageInfo,
  167. };
  168. await this.layout('safe/inspection.ejs', renderData, 'safe/inspection_modal.ejs');
  169. } catch (err) {
  170. ctx.log(err);
  171. ctx.postError(err, '无法查看安全巡检数据');
  172. ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
  173. }
  174. }
  175. /**
  176. * 新增变更申请 (Post)
  177. *
  178. * @param {Object} ctx - egg全局变量
  179. * @return {void}
  180. */
  181. async inspectionSave(ctx) {
  182. try {
  183. const data = JSON.parse(ctx.request.body.data);
  184. const reponseData = {
  185. err: 0, msg: '', data: {},
  186. };
  187. switch (data.type) {
  188. case 'add':
  189. if (!data.code || data.code === '') {
  190. throw '编号不能为空';
  191. }
  192. if (!data.check_item || !data.check_date) {
  193. throw '请填写检查项和日期';
  194. }
  195. reponseData.data = await ctx.service.safeInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
  196. break;
  197. default:throw '参数有误';
  198. }
  199. ctx.body = reponseData;
  200. } catch (err) {
  201. this.log(err);
  202. ctx.body = { err: 1, msg: err.toString() };
  203. }
  204. }
  205. /**
  206. * 获取审批界面所需的 原报、审批人数据等
  207. * @param ctx
  208. * @return {Promise<void>}
  209. * @private
  210. */
  211. async _getInspectionAuditViewData(ctx) {
  212. await ctx.service.safeInspection.loadAuditViewData(ctx.inspection);
  213. }
  214. async inspectionInformation(ctx) {
  215. try {
  216. const whiteList = this.ctx.app.config.multipart.whitelist;
  217. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  218. await this._getInspectionAuditViewData(ctx);
  219. // 获取附件列表
  220. const fileList = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  221. // 获取用户人验证手机号
  222. const renderData = {
  223. moment,
  224. tender,
  225. inspection: ctx.inspection,
  226. auditConst: auditConst.inspection,
  227. fileList,
  228. whiteList,
  229. auditType,
  230. shenpiConst,
  231. deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
  232. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_information),
  233. preUrl: `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
  234. };
  235. // data.accountGroup = accountGroup;
  236. // 获取所有项目参与者
  237. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  238. renderData.accountList = accountList;
  239. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  240. renderData.accountGroup = unitList.map(item => {
  241. const groupList = accountList.filter(item1 => item1.company === item.name);
  242. return { groupName: item.name, groupList };
  243. }).filter(x => { return x.groupList.length > 0; });
  244. await this.layout('safe/inspection_information.ejs', renderData, 'safe/inspection_information_modal.ejs');
  245. } catch (err) {
  246. this.log(err);
  247. ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
  248. }
  249. }
  250. async inspectionInformationSave(ctx) {
  251. try {
  252. const data = JSON.parse(ctx.request.body.data);
  253. const reponseData = {
  254. err: 0, msg: '', data: {},
  255. };
  256. switch (data.type) {
  257. case 'update-field':
  258. if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
  259. throw '当前状态不可修改';
  260. }
  261. if (data.update.check_item !== undefined && data.update.check_item === '') {
  262. throw '检查项不能为空';
  263. }
  264. if (data.update.check_date !== undefined && data.update.check_date === '') {
  265. throw '请填写检查日期';
  266. }
  267. if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
  268. throw '整改情况不能为空';
  269. }
  270. if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
  271. throw '请填写整改日期';
  272. }
  273. const fields = ['id', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
  274. if (!this.checkFieldExists(data.update, fields)) {
  275. throw '参数有误';
  276. }
  277. reponseData.data = await ctx.service.safeInspection.defaultUpdate(data.update);
  278. break;
  279. case 'add-audit':
  280. const id = this.app._.toInteger(data.auditorId);
  281. if (isNaN(id) || id <= 0) {
  282. throw '参数错误';
  283. }
  284. // 检查权限等
  285. if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
  286. throw '您无权添加审核人';
  287. }
  288. if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
  289. throw '当前不允许添加审核人';
  290. }
  291. ctx.inspection.auditorList = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  292. // 检查审核人是否已存在
  293. const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
  294. if (exist) {
  295. throw '该审核人已存在,请勿重复添加';
  296. }
  297. const result = await ctx.service.safeInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
  298. if (!result) {
  299. throw '添加审核人失败';
  300. }
  301. reponseData.data = await ctx.service.safeInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
  302. break;
  303. case 'del-audit':
  304. const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  305. if (isNaN(id2) || id2 <= 0) {
  306. throw '参数错误';
  307. }
  308. const result2 = await ctx.service.safeInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
  309. if (!result2) {
  310. throw '移除审核人失败';
  311. }
  312. reponseData.data = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
  313. break;
  314. case 'start-inspection':
  315. if (ctx.inspection.readOnly) {
  316. throw '当前状态不可提交';
  317. }
  318. await ctx.service.safeInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
  319. break;
  320. case 'del-inspection':
  321. if (ctx.inspection.readOnly) {
  322. throw '当前状态不可删除';
  323. }
  324. await ctx.service.safeInspection.delInspection(ctx.inspection.id);
  325. break;
  326. case 'check':
  327. if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
  328. throw '当前质量巡检数据有误';
  329. }
  330. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  331. throw '您无权进行该操作';
  332. }
  333. await ctx.service.safeInspectionAudit.check(ctx.inspection, data);
  334. break;
  335. case 'rectification':
  336. if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
  337. throw '当前质量巡检数据有误';
  338. }
  339. if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  340. throw '您无权进行该操作';
  341. }
  342. await ctx.service.safeInspectionAudit.rectification(ctx.inspection, data);
  343. break;
  344. default:throw '参数有误';
  345. }
  346. ctx.body = reponseData;
  347. } catch (err) {
  348. this.log(err);
  349. ctx.body = { err: 1, msg: err.toString() };
  350. }
  351. }
  352. checkFieldExists(update, fields) {
  353. for (const field of Object.keys(update)) {
  354. if (!fields.includes(field)) {
  355. return false;
  356. }
  357. }
  358. return true;
  359. }
  360. /**
  361. * 上传附件
  362. * @param {*} ctx 上下文
  363. */
  364. async uploadInspectionFile(ctx) {
  365. let stream;
  366. try {
  367. // this._checkAdvanceFileCanModify(ctx);
  368. const parts = this.ctx.multipart({
  369. autoFields: true,
  370. });
  371. const files = [];
  372. const create_time = Date.parse(new Date()) / 1000;
  373. let idx = 0;
  374. const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
  375. while ((stream = await parts()) !== undefined) {
  376. if (!stream.filename) {
  377. // 如果没有传入直接返回
  378. return;
  379. }
  380. const fileInfo = path.parse(stream.filename);
  381. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/safe_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  382. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  383. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  384. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  385. ++idx;
  386. stream && (await sendToWormhole(stream));
  387. }
  388. const in_time = new Date();
  389. const payload = files.map(file => {
  390. let idx;
  391. if (Array.isArray(parts.field.name)) {
  392. idx = parts.field.name.findIndex(name => name === file.name);
  393. } else {
  394. idx = 'isString';
  395. }
  396. const newFile = {
  397. tid: ctx.tender.id,
  398. qiid: ctx.inspection.id,
  399. uid: ctx.session.sessionUser.accountId,
  400. filename: file.name,
  401. fileext: file.ext,
  402. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  403. filepath: file.filepath,
  404. upload_time: in_time,
  405. extra_upload,
  406. };
  407. return newFile;
  408. });
  409. // 执行文件信息写入数据库
  410. await ctx.service.safeInspectionAtt.saveFileMsgToDb(payload);
  411. // 将最新的当前标段的所有文件信息返回
  412. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  413. ctx.body = { err: 0, msg: '', data };
  414. } catch (err) {
  415. stream && (await sendToWormhole(stream));
  416. this.log(err);
  417. ctx.body = { err: 1, msg: err.toString(), data: null };
  418. }
  419. }
  420. /**
  421. * 删除附件
  422. * @param {Ojbect} ctx 上下文
  423. */
  424. async deleteInspectionFile(ctx) {
  425. try {
  426. const { id } = JSON.parse(ctx.request.body.data);
  427. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  428. if (fileInfo || Object.keys(fileInfo).length) {
  429. // 先删除文件
  430. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  431. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  432. // 再删除数据库
  433. await ctx.service.safeInspectionAtt.delete(id);
  434. } else {
  435. throw '不存在该文件';
  436. }
  437. const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
  438. ctx.body = { err: 0, msg: '请求成功', data };
  439. } catch (err) {
  440. this.log(err);
  441. ctx.body = { err: 1, msg: err.toString(), data: null };
  442. }
  443. }
  444. /**
  445. * 下载附件
  446. * @param {Object} ctx - egg全局变量
  447. * @return {void}
  448. */
  449. async downloadInspectionFile(ctx) {
  450. const id = ctx.params.fid;
  451. if (id) {
  452. try {
  453. const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
  454. if (fileInfo !== undefined && fileInfo !== '') {
  455. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  456. // 解决中文无法下载问题
  457. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  458. let disposition = '';
  459. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  460. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  461. } else if (userAgent.indexOf('firefox') >= 0) {
  462. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  463. } else {
  464. /* safari等其他非主流浏览器只能自求多福了 */
  465. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  466. }
  467. ctx.response.set({
  468. 'Content-Type': 'application/octet-stream',
  469. 'Content-Disposition': disposition,
  470. 'Content-Length': fileInfo.filesize,
  471. });
  472. // ctx.body = await fs.createReadStream(fileName);
  473. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  474. } else {
  475. throw '不存在该文件';
  476. }
  477. } catch (err) {
  478. this.log(err);
  479. this.setMessage(err.toString(), this.messageType.ERROR);
  480. }
  481. }
  482. }
  483. }
  484. return SafeController;
  485. };