| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956 |
- '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 stage(ctx) {
- try {
- if (!ctx.subProject.page_show.safePayment) throw '该功能已关闭';
- const renderData = {
- auditType: auditConst.auditType,
- auditConst: auditConst.common,
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.stage),
- };
- renderData.stages = await this.ctx.service.safeStage.getAllStages(ctx.tender.id, 'DESC');
- for (const s of renderData.stages) {
- if (s.audit_status !== auditConst.common.status.checked) await this.ctx.service.safeStage.loadUser(s);
- s.can_del = (s.create_user_id === ctx.session.sessionUser.accountId || ctx.session.sessionUser.is_admin)
- && (s.audit_status === auditConst.common.status.uncheck || s.audit_status === auditConst.common.status.checkNo);
- }
- await this.layout('safe_calc/stage.ejs', renderData, 'safe_calc/stage_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '查看安全计量数据错误');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe`);
- }
- }
- async addStage(ctx) {
- try {
- if (!ctx.permission.safe_payment.add) throw '您无权创建计量期';
- const stage_date = ctx.request.body.stage_date;
- if (!stage_date) throw '请选择日期';
- const stage_code = ctx.request.body.stage_code;
- const stages = await ctx.service.safeStage.getAllStages(ctx.tender.id, 'DESC');
- const unCompleteCount = stages.filter(s => { return s.status !== auditConst.common.status.checked; }).length;
- if (unCompleteCount.length > 0) throw `最新一起未审批通过,请审批通过后再新增`;
- const newStage = await ctx.service.safeStage.add(ctx.tender.id, stage_code, stage_date);
- if (!newStage) throw '新增期失败';
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${newStage.stage_order}/bills`);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '新增期失败');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- }
- }
- async delStage(ctx) {
- try {
- // if (!ctx.session.sessionUser.is_admin && ctx.request.body.confirm !== '确认删除本期') throw '请输入文本确认删除本期';
- const stage_id = ctx.request.body.stage_id;
- const stage = await ctx.service.safeStage.getDataById(stage_id);
- if (!stage) throw '删除的期不存在,请刷新页面';
- if (!ctx.session.sessionUser.is_admin && stage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权删除本期';
- // 获取最新的期数
- const stageCount = await ctx.service.safeStage.count({ tid: ctx.tender.id });
- if (stage.stage_order !== stageCount) throw '非最新一期,不可删除';
- await ctx.service.safeStage.delete(stage_id);
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '删除期失败');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- }
- }
- async saveStage(ctx) {
- try {
- const stage_id = ctx.request.body.stage_id;
- const data = {
- stage_date: ctx.request.body.stage_date,
- stage_code: ctx.request.body.stage_code,
- };
- const stage = await ctx.service.safeStage.getStage(stage_id);
- if (!stage) throw '删除的期不存在,请刷新页面';
- if (!ctx.session.sessionUser.is_admin && stage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权修改该数据';
- await this.ctx.service.safeStage.save(stage, data);
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- } catch (err) {
- ctx.log(err);
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- }
- }
- async _getStageAuditViewData(ctx) {
- await this.ctx.service.safeStage.loadAuditViewData(ctx.safeStage);
- }
- async safeBills(ctx) {
- try {
- await this._getStageAuditViewData(ctx);
- // 获取附件列表
- const attList = await ctx.service.paymentDetailAtt.getPaymentDetailAttachment(ctx.safeStage.id, 'desc');
- const stdBills = await ctx.service.stdGclList.getSafeGcl();
- // 流程审批人相关数据
- const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
- const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
- const 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; });
- // 是否已验证手机短信
- const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
- const renderData = {
- auditConst: auditConst.common,
- accountList,
- accountGroup,
- shenpiConst,
- auditType: auditConst.auditType,
- authMobile: pa.auth_mobile,
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.bills),
- stdBills,
- attList,
- };
- await this.layout('safe_calc/index.ejs', renderData, 'safe_calc/modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '读取安全生产费错误');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- }
- }
- async safeCompare(ctx) {
- try {
- const renderData = {
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.safe.compare),
- auditConst,
- };
- await this.layout('safe_calc/compare.ejs', renderData);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '读取安全生产费错误');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage`);
- }
- }
- async safeLoad(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const filter = data.filter.split(';');
- const responseData = { err: 0, msg: '', data: {}, hpack: [] };
- for (const f of filter) {
- switch (f) {
- case 'bills':
- responseData.data.bills = ctx.safeStage.readOnly
- ? await ctx.service.safeStageBills.getReadData(ctx.safeStage)
- : await ctx.service.safeStageBills.getEditData(ctx.safeStage);
- break;
- case 'billsCompare':
- responseData.data[f] = await ctx.service.safeStageBills.getCompareData(ctx.safeStage);
- break;
- case 'auditFlow':
- responseData.data[f] = await ctx.service.safeStageAudit.getViewFlow(ctx.safeStage);
- break;
- case 'att':
- responseData.data[f] = await ctx.service.safeStageFile.getData(ctx.safeStage.id, 'bills', 'DESC');
- break;
- default:
- responseData.data[f] = [];
- break;
- }
- }
- ctx.body = responseData;
- } catch (err) {
- this.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- async _billsBase(stage, type, data) {
- if (isNaN(data.id) || data.id <= 0) throw '数据错误';
- if (type !== 'add') {
- if (isNaN(data.count) || data.count <= 0) data.count = 1;
- }
- switch (type) {
- case 'add':
- return await this.ctx.service.safeStageBills.addSafeBillsNode(stage, data.id, data.count);
- case 'delete':
- return await this.ctx.service.safeStageBills.delete(stage.id, data.id, data.count);
- case 'up-move':
- return await this.ctx.service.safeStageBills.upMoveNode(stage.id, data.id, data.count);
- case 'down-move':
- return await this.ctx.service.safeStageBills.downMoveNode(stage.id, data.id, data.count);
- case 'up-level':
- return await this.ctx.service.safeStageBills.upLevelNode(stage.id, data.id, data.count);
- case 'down-level':
- return await this.ctx.service.safeStageBills.downLevelNode(stage.id, data.id, data.count);
- }
- }
- async safeUpdate(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- if (!data.postType || !data.postData) throw '数据错误';
- const responseData = { err: 0, msg: '', data: {} };
- switch (data.postType) {
- case 'add':
- case 'delete':
- case 'up-move':
- case 'down-move':
- case 'up-level':
- case 'down-level':
- responseData.data = await this._billsBase(ctx.safeStage, data.postType, data.postData);
- break;
- case 'update':
- responseData.data = await this.ctx.service.safeStageBills.updateCalc(ctx.safeStage, data.postData);
- break;
- case 'add-std':
- responseData.data = await this.ctx.service.safeStageBills.addStdNodeWithParent(ctx.safeStage, data.postData.id, data.postData.stdData);
- break;
- default:
- throw '未知操作';
- }
- ctx.body = responseData;
- } catch (err) {
- this.log(err);
- ctx.body = this.ajaxErrorBody(err, '数据错误');
- }
- }
- async safeDecimal(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const result = await this.ctx.service.safeStageBills.setDecimal(data.decimal);
- ctx.body = { err: 0, msg: '', data: result };
- } catch (err) {
- this.log(err);
- ctx.body = this.ajaxErrorBody(err, '设置小数位数错误');
- }
- }
- async uploadStageFile(ctx) {
- let stream;
- try {
- const parts = ctx.multipart({autoFields: true});
- let index = 0;
- const create_time = Date.parse(new Date()) / 1000;
- let stream = await parts();
- const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
- const rela_type = parts.fields.type;
- const rela_id = parts.field.rela_id;
- const uploadfiles = [];
- while (stream !== undefined) {
- if (!stream.filename) throw '未发现上传文件!';
- const fileInfo = path.parse(stream.filename);
- const filepath = `app/public/upload/${ctx.safeStage.tid}/safeStage/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
- // 保存文件
- await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
- await sendToWormhole(stream);
- // 插入到stage_pay对应的附件列表中
- uploadfiles.push({
- rela_id,
- filename: fileInfo.name,
- fileext: fileInfo.ext,
- filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
- filepath,
- });
- ++index;
- if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
- stream = await parts();
- } else {
- stream = undefined;
- }
- }
- const result = await ctx.service.safeStageFile.addFiles(ctx.safeStage, 'bills', uploadfiles, user);
- ctx.body = {err: 0, msg: '', data: result};
- } catch (error) {
- ctx.log(error);
- // 失败需要消耗掉stream 以防卡死
- if (stream) await sendToWormhole(stream);
- ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
- }
- }
- async deleteStageFile(ctx) {
- try{
- const data = JSON.parse(ctx.request.body.data);
- if (!data && !data.id) throw '缺少参数';
- const result = await ctx.service.safeStageFile.delFiles(data.id);
- ctx.body = { err: 0, msg: '', data: result };
- } catch(error) {
- ctx.log(error);
- ctx.ajaxErrorBody(error, '删除附件失败');
- }
- }
- /**
- * 添加审批人
- * @param ctx
- * @return {Promise<void>}
- */
- async addStageAudit(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const id = this.app._.toInteger(data.auditorId);
- if (isNaN(id) || id <= 0) throw '参数错误';
- // 检查权限等
- if (ctx.safeStage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权添加审核人';
- if (ctx.safeStage.audit_status !== auditConst.common.status.uncheck && ctx.safeStage.audit_status !== auditConst.common.status.checkNo) {
- throw '当前不允许添加审核人';
- }
- // 检查审核人是否已存在
- const exist = await ctx.service.safeStageAudit.getDataByCondition({ stage_id: ctx.safeStage.id, audit_times: ctx.safeStage.audit_times, audit_id: id });
- if (exist) throw '该审核人已存在,请勿重复添加';
- const auditorInfo = await this.ctx.service.projectAccount.getDataById(id);
- if (!auditorInfo) throw '添加的审批人不存在';
- const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.safe_payment, sp_status: shenpiConst.sp_status.gdzs });
- const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.safe_payment === shenpiConst.sp_status.gdzs ? 1 : 0;
- const result = await ctx.service.safeStageAudit.addAuditor(ctx.safeStage.id, auditorInfo, ctx.safeStage.audit_times, is_gdzs);
- if (!result) throw '添加审核人失败';
- const auditors = await ctx.service.safeStageAudit.getAuditorGroup(ctx.safeStage.id, ctx.safeStage.audit_times);
- ctx.body = { err: 0, msg: '', data: auditors };
- } catch (err) {
- ctx.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- /**
- * 移除审批人
- * @param ctx
- * @return {Promise<void>}
- */
- async deleteStageAudit(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
- if (isNaN(id) || id <= 0) throw '参数错误';
- const result = await ctx.service.safeStageAudit.deleteAuditor(ctx.safeStage.id, id, ctx.safeStage.audit_times);
- if (!result) throw '移除审核人失败';
- const auditors = await ctx.service.safeStageAudit.getAuditors(ctx.safeStage.id, ctx.safeStage.audit_times);
- ctx.body = { err: 0, msg: '', data: auditors };
- } catch (err) {
- ctx.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- async stageAuditStart(ctx) {
- try {
- if (ctx.safeStage.create_user_id !== ctx.session.sessionUser.accountId) throw '您无权上报该期数据';
- if (ctx.safeStage.revising) throw '台账修订中,不可上报';
- if (ctx.safeStage.audit_status !== auditConst.common.status.uncheck && ctx.safeStage.audit_status !== auditConst.common.status.checkNo) throw '该期数据当前无法上报';
- await ctx.service.safeStageAudit.start(ctx.safeStage);
- ctx.redirect(ctx.request.header.referer);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '上报失败');
- ctx.redirect(`/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${ctx.safeStage.stage_order}/bills`);
- }
- }
- async stageAuditCheck(ctx) {
- try {
- if (!ctx.safeStage || (ctx.safeStage.audit_status !== auditConst.common.status.checking && ctx.safeStage.audit_status !== auditConst.common.status.checkNoPre)) {
- throw '当前期数据有误';
- }
- if (ctx.safeStage.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0) {
- throw '您无权进行该操作';
- }
- if (ctx.safeStage.revising) throw '台账修订中,不可审批';
- const checkType = parseInt(ctx.request.body.checkType);
- const opinion = ctx.request.body.opinion.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
- await ctx.service.safeStageAudit.check(ctx.safeStage, checkType, opinion);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '审批失败');
- }
- ctx.redirect(ctx.request.header.referer);
- }
- async stageAuditCheckAgain(ctx) {
- try {
- if (!ctx.safeStage.isLatest) throw '非最新一期,不可重新审批';
- if (ctx.safeStage.audit_status !== auditConst.common.status.checked) throw '未审批完成,不可重新审批';
- if (ctx.safeStage.revising) throw '台账修订中,不可重审';
- if (ctx.session.sessionUser.loginStatus === 0) {
- const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
- if (!user.auth_mobile) throw '未绑定手机号';
- const code = ctx.request.body.code;
- const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
- const cacheCode = await app.redis.get(cacheKey);
- if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
- throw '验证码不正确!';
- }
- }
- const adminCheckAgain = ctx.request.body.confirm === '确认设置终审审批' && ctx.session.sessionUser.is_admin;
- if (ctx.safeStage.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) < 0 && !adminCheckAgain) throw '您无权重新审批';
- await ctx.service.safeStageAudit.checkAgain(ctx.safeStage, adminCheckAgain);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '重新审批失败');
- }
- ctx.redirect(ctx.request.header.referer);
- }
- async stageAuditCheckCancel(ctx) {
- try {
- if (ctx.safeStage.revising) throw '台账修订中,不可撤回';
- if (!ctx.safeStage.cancancel) throw '您无权进行该操作';
- await ctx.service.safeStageAudit.checkCancel(ctx.safeStage);
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '撤回失败');
- }
- ctx.redirect(ctx.request.header.referer);
- }
- 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 c of inspectionList) {
- c.attList = ctx.helper._.filter(allAttList, { qiid: c.id });
- c.curAuditors = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, c.status, c.times);
- if (c.status === auditConst.inspection.status.checkNoPre) {
- c.curAuditors2 = await ctx.service.safeInspectionAudit.getAuditorsByStatus(c.id, auditConst.inspection.status.checking, c.times);
- }
- }
- // 分页相关
- 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;
- };
|