| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540 |
- 'use strict';
- /**
- * 标段管理控制器
- *
- * @author Mai
- * @date 2025/7/17
- * @version
- */
- const auditConst = require('../const/audit');
- const auditType = require('../const/audit').auditType;
- const shenpiConst = require('../const/shenpi');
- const codeRuleConst = require('../const/code_rule');
- const contractConst = require('../const/contract');
- const moment = require('moment');
- const sendToWormhole = require('stream-wormhole');
- const fs = require('fs');
- const path = require('path');
- const PermissionCheck = require('../const/account_permission').PermissionCheck;
- module.exports = app => {
- class SafeController extends app.BaseController {
- constructor(ctx) {
- super(ctx);
- ctx.showProject = true;
- // ctx.showTitle = true;
- }
- loadMenu(ctx) {
- super.loadMenu(ctx);
- // 虚拟menu,以保证标题显示正确
- ctx.menu = {
- name: '安全管理',
- display: false,
- caption: '安全管理',
- controller: 'safe',
- };
- }
- async tender(ctx) {
- try {
- if (!ctx.subProject.page_show.safePayment) throw '该功能已关闭';
- const renderData = {
- is_inspection: ctx.url.includes('inspection') ? 1 : 0,
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
- };
- const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
- renderData.accountList = accountList;
- const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- const accountGroupList = unitList.map(item => {
- const groupList = accountList.filter(item1 => item1.company === item.name);
- return { groupName: item.name, groupList };
- }).filter(x => { return x.groupList.length > 0; });
- // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- // renderData.accountGroup = unitList.map(item => {
- // const groupList = accountList.filter(item1 => item1.company === item.name);
- // return { groupName: item.name, groupList };
- // });
- renderData.accountGroup = accountGroupList;
- renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
- renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_payment', ctx.session.sessionUser.is_admin ? 'all' : '');
- renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
- renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
- renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_payment');
- renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_payment');
- await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看安全计量数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
- }
- }
- async inspectionTender(ctx) {
- try {
- if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
- const renderData = {
- is_inspection: ctx.url.includes('inspection') ? 1 : 0,
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.tender),
- };
- const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
- renderData.accountList = accountList;
- const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- const accountGroupList = unitList.map(item => {
- const groupList = accountList.filter(item1 => item1.company === item.name);
- return { groupName: item.name, groupList };
- }).filter(x => { return x.groupList.length > 0; });
- // const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- // renderData.accountGroup = unitList.map(item => {
- // const groupList = accountList.filter(item1 => item1.company === item.name);
- // return { groupName: item.name, groupList };
- // });
- renderData.accountGroup = accountGroupList;
- renderData.accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
- renderData.tenderList = await ctx.service.tender.getSpecList(ctx.service.tenderPermission, 'safe_inspection', ctx.session.sessionUser.is_admin ? 'all' : '');
- renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.subProject);
- renderData.selfCategoryLevel = this.ctx.subProject.permission.self_category_level;
- renderData.permissionConst = ctx.service.tenderPermission.partPermissionConst('safe_inspection');
- renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('safe_inspection');
- await this.layout('safe/tender.ejs', renderData, 'safe/tender_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看安全巡检数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/dashboard`);
- }
- }
- /**
- * 变更管理 页面 (Get)
- *
- * @param {Object} ctx - egg全局变量
- * @return {void}
- */
- async inspection(ctx) {
- try {
- if (!ctx.subProject.page_show.safeInspection) throw '该功能已关闭';
- const status = parseInt(ctx.query.status) || 0;
- await this._filterInspection(ctx, status);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
- }
- }
- // 质量巡检单功能
- async _filterInspection(ctx, status = 0) {
- try {
- ctx.session.sessionUser.tenderId = ctx.tender.id;
- const sorts = ctx.query.sort ? ctx.query.sort : 0;
- const orders = ctx.query.order ? ctx.query.order : 0;
- const filter = JSON.parse(JSON.stringify(auditConst.inspection.filter));
- filter.count = [];
- filter.count[filter.status.pending] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
- filter.count[filter.status.uncheck] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
- filter.count[filter.status.checking] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
- filter.count[filter.status.rectification] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
- filter.count[filter.status.checked] = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
- 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);
- const inspectionList = await ctx.service.safeInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
- const total = await ctx.service.safeInspection.getCountByStatus(ctx.tender.id, status);
- const allAttList = inspectionList.length > 0 ? await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.helper._.map(inspectionList, 'id')) : [];
- for (const item of inspectionList) {
- item.attList = ctx.helper._.filter(allAttList, { qiid: item.id });
- }
- // 分页相关
- const page = ctx.page;
- const pageSize = ctx.pageSize;
- const pageInfo = {
- page,
- pageSizeSelect: 1,
- pageSize,
- total_num: total,
- total: Math.ceil(total / pageSize),
- queryData: JSON.stringify(ctx.urlInfo.query),
- };
- let codeRule = [];
- let c_connector = '1';
- let c_rule_first = 1;
- const rule_type = 'safe_inspection';
- const tender = await this.service.tender.getDataById(ctx.tender.id);
- if (tender.c_code_rules) {
- const c_code_rules = JSON.parse(tender.c_code_rules);
- codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
- c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
- c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
- }
- for (const rule of codeRule) {
- switch (rule.rule_type) {
- case codeRuleConst.measure.ruleType.dealCode:
- rule.preview = ctx.tender.info.deal_info.dealCode;
- break;
- case codeRuleConst.measure.ruleType.tenderName:
- rule.preview = tender.name;
- break;
- case codeRuleConst.measure.ruleType.inDate:
- rule.preview = moment().format('YYYY');
- break;
- case codeRuleConst.measure.ruleType.text:
- rule.preview = rule.text;
- break;
- case codeRuleConst.measure.ruleType.addNo:
- const s = '0000000000';
- rule.preview = s.substr(s.length - rule.format);
- break;
- default: break;
- }
- }
- const renderData = {
- moment,
- tender,
- permission: ctx.permission.safe_inspection,
- rule_type,
- codeRule,
- dealCode: ctx.tender.info.deal_info.dealCode,
- c_connector,
- c_rule_first,
- ruleType: codeRuleConst.ruleType[rule_type],
- ruleConst: codeRuleConst.measure,
- filter,
- inspectionList,
- auditType,
- auditConst: auditConst.inspection,
- status,
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection),
- pageInfo,
- };
- await this.layout('safe/inspection.ejs', renderData, 'safe/inspection_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看安全巡检数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/inspection`);
- }
- }
- /**
- * 新增变更申请 (Post)
- *
- * @param {Object} ctx - egg全局变量
- * @return {void}
- */
- async inspectionSave(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const reponseData = {
- err: 0, msg: '', data: {},
- };
- switch (data.type) {
- case 'add':
- if (!data.code || data.code === '') {
- throw '编号不能为空';
- }
- if (!data.check_item || !data.check_date) {
- throw '请填写检查项和日期';
- }
- reponseData.data = await ctx.service.safeInspection.add(ctx.tender.id, ctx.session.sessionUser.accountId, data.code, data.check_item, data.check_date);
- break;
- default:throw '参数有误';
- }
- ctx.body = reponseData;
- } catch (err) {
- this.log(err);
- ctx.body = { err: 1, msg: err.toString() };
- }
- }
- /**
- * 获取审批界面所需的 原报、审批人数据等
- * @param ctx
- * @return {Promise<void>}
- * @private
- */
- async _getInspectionAuditViewData(ctx) {
- await ctx.service.safeInspection.loadAuditViewData(ctx.inspection);
- }
- async inspectionInformation(ctx) {
- try {
- const whiteList = this.ctx.app.config.multipart.whitelist;
- const tender = await ctx.service.tender.getDataById(ctx.tender.id);
- await this._getInspectionAuditViewData(ctx);
- // 获取附件列表
- const fileList = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
- // 获取用户人验证手机号
- const renderData = {
- moment,
- tender,
- inspection: ctx.inspection,
- auditConst: auditConst.inspection,
- fileList,
- whiteList,
- auditType,
- shenpiConst,
- deleteFilePermission: PermissionCheck.delFile(this.ctx.session.sessionUser.permission),
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.inspection_information),
- preUrl: `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection/${ctx.inspection.id}/information`,
- };
- // data.accountGroup = accountGroup;
- // 获取所有项目参与者
- const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
- renderData.accountList = accountList;
- const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- renderData.accountGroup = unitList.map(item => {
- const groupList = accountList.filter(item1 => item1.company === item.name);
- return { groupName: item.name, groupList };
- }).filter(x => { return x.groupList.length > 0; });
- await this.layout('safe/inspection_information.ejs', renderData, 'safe/inspection_information_modal.ejs');
- } catch (err) {
- this.log(err);
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/inspection`);
- }
- }
- async inspectionInformationSave(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const reponseData = {
- err: 0, msg: '', data: {},
- };
- switch (data.type) {
- case 'update-field':
- if (!(!ctx.inspection.readOnly || ctx.inspection.rectificationPower)) {
- throw '当前状态不可修改';
- }
- if (data.update.check_item !== undefined && data.update.check_item === '') {
- throw '检查项不能为空';
- }
- if (data.update.check_date !== undefined && data.update.check_date === '') {
- throw '请填写检查日期';
- }
- if (data.update.rectification_item !== undefined && data.update.rectification_item === '') {
- throw '整改情况不能为空';
- }
- if (data.update.rectification_date !== undefined && data.update.rectification_date === '') {
- throw '请填写整改日期';
- }
- const fields = ['id', 'check_item', 'check_situation', 'action', 'check_date', 'inspector', 'rectification_item', 'rectification_date'];
- if (!this.checkFieldExists(data.update, fields)) {
- throw '参数有误';
- }
- reponseData.data = await ctx.service.safeInspection.defaultUpdate(data.update);
- break;
- case 'add-audit':
- const id = this.app._.toInteger(data.auditorId);
- if (isNaN(id) || id <= 0) {
- throw '参数错误';
- }
- // 检查权限等
- if (ctx.inspection.uid !== ctx.session.sessionUser.accountId) {
- throw '您无权添加审核人';
- }
- if (ctx.inspection.status !== auditConst.inspection.status.uncheck && ctx.inspection.status !== auditConst.inspection.status.checkNo) {
- throw '当前不允许添加审核人';
- }
- ctx.inspection.auditorList = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
- // 检查审核人是否已存在
- const exist = this.app._.find(ctx.inspection.auditorList, { aid: id });
- if (exist) {
- throw '该审核人已存在,请勿重复添加';
- }
- const result = await ctx.service.safeInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
- if (!result) {
- throw '添加审核人失败';
- }
- reponseData.data = await ctx.service.safeInspectionAudit.getUserGroup(ctx.inspection.id, ctx.inspection.times);
- break;
- case 'del-audit':
- const id2 = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
- if (isNaN(id2) || id2 <= 0) {
- throw '参数错误';
- }
- const result2 = await ctx.service.safeInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
- if (!result2) {
- throw '移除审核人失败';
- }
- reponseData.data = await ctx.service.safeInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
- break;
- case 'start-inspection':
- if (ctx.inspection.readOnly) {
- throw '当前状态不可提交';
- }
- await ctx.service.safeInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
- break;
- case 'del-inspection':
- if (ctx.inspection.readOnly) {
- throw '当前状态不可删除';
- }
- await ctx.service.safeInspection.delInspection(ctx.inspection.id);
- break;
- case 'check':
- if (!ctx.inspection || !(ctx.inspection.status === auditConst.inspection.status.checking || ctx.inspection.status === auditConst.inspection.status.checkNoPre)) {
- throw '当前质量巡检数据有误';
- }
- if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
- throw '您无权进行该操作';
- }
- await ctx.service.safeInspectionAudit.check(ctx.inspection, data);
- break;
- case 'rectification':
- if (!ctx.inspection || ctx.inspection.status !== auditConst.inspection.status.rectification) {
- throw '当前质量巡检数据有误';
- }
- if (ctx.inspection.curAuditorIds.length === 0 || ctx.inspection.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
- throw '您无权进行该操作';
- }
- await ctx.service.safeInspectionAudit.rectification(ctx.inspection, data);
- break;
- default:throw '参数有误';
- }
- ctx.body = reponseData;
- } catch (err) {
- this.log(err);
- ctx.body = { err: 1, msg: err.toString() };
- }
- }
- checkFieldExists(update, fields) {
- for (const field of Object.keys(update)) {
- if (!fields.includes(field)) {
- return false;
- }
- }
- return true;
- }
- /**
- * 上传附件
- * @param {*} ctx 上下文
- */
- async uploadInspectionFile(ctx) {
- let stream;
- try {
- // this._checkAdvanceFileCanModify(ctx);
- const parts = this.ctx.multipart({
- autoFields: true,
- });
- const files = [];
- const create_time = Date.parse(new Date()) / 1000;
- let idx = 0;
- const extra_upload = ctx.inspection.status === auditConst.inspection.status.checked;
- while ((stream = await parts()) !== undefined) {
- if (!stream.filename) {
- // 如果没有传入直接返回
- return;
- }
- const fileInfo = path.parse(stream.filename);
- const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/safe_inspection/fujian_${create_time + idx.toString() + fileInfo.ext}`;
- // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
- await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
- files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
- ++idx;
- stream && (await sendToWormhole(stream));
- }
- const in_time = new Date();
- const payload = files.map(file => {
- let idx;
- if (Array.isArray(parts.field.name)) {
- idx = parts.field.name.findIndex(name => name === file.name);
- } else {
- idx = 'isString';
- }
- const newFile = {
- tid: ctx.tender.id,
- qiid: ctx.inspection.id,
- uid: ctx.session.sessionUser.accountId,
- filename: file.name,
- fileext: file.ext,
- filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
- filepath: file.filepath,
- upload_time: in_time,
- extra_upload,
- };
- return newFile;
- });
- // 执行文件信息写入数据库
- await ctx.service.safeInspectionAtt.saveFileMsgToDb(payload);
- // 将最新的当前标段的所有文件信息返回
- const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
- ctx.body = { err: 0, msg: '', data };
- } catch (err) {
- stream && (await sendToWormhole(stream));
- this.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- /**
- * 删除附件
- * @param {Ojbect} ctx 上下文
- */
- async deleteInspectionFile(ctx) {
- try {
- const { id } = JSON.parse(ctx.request.body.data);
- const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
- if (fileInfo || Object.keys(fileInfo).length) {
- // 先删除文件
- // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
- await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
- // 再删除数据库
- await ctx.service.safeInspectionAtt.delete(id);
- } else {
- throw '不存在该文件';
- }
- const data = await ctx.service.safeInspectionAtt.getAllAtt(ctx.tender.id, ctx.inspection.id);
- ctx.body = { err: 0, msg: '请求成功', data };
- } catch (err) {
- this.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- /**
- * 下载附件
- * @param {Object} ctx - egg全局变量
- * @return {void}
- */
- async downloadInspectionFile(ctx) {
- const id = ctx.params.fid;
- if (id) {
- try {
- const fileInfo = await ctx.service.safeInspectionAtt.getDataById(id);
- if (fileInfo !== undefined && fileInfo !== '') {
- // const fileName = path.join(__dirname, '../', fileInfo.filepath);
- // 解决中文无法下载问题
- const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
- let disposition = '';
- if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
- disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
- } else if (userAgent.indexOf('firefox') >= 0) {
- disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
- } else {
- /* safari等其他非主流浏览器只能自求多福了 */
- disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
- }
- ctx.response.set({
- 'Content-Type': 'application/octet-stream',
- 'Content-Disposition': disposition,
- 'Content-Length': fileInfo.filesize,
- });
- // ctx.body = await fs.createReadStream(fileName);
- ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
- } else {
- throw '不存在该文件';
- }
- } catch (err) {
- this.log(err);
- this.setMessage(err.toString(), this.messageType.ERROR);
- }
- }
- }
- }
- return SafeController;
- };
|