123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921 |
- '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 QualityController 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: 'quality',
- };
- }
- async tender(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const renderData = {
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.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, 'quality', 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('quality');
- renderData.permissionBlock = ctx.service.tenderPermission.partPermissionBlock('quality');
- await this.layout('quality/tender.ejs', renderData, 'quality/tender_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect('/dashboard');
- }
- }
- async member(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- const result = await ctx.service.tenderPermission.getPartsPermission(data.tid, data.parts);
- ctx.body = { err: 0, msg: '', data: result };
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '查询标段权限错误');
- }
- }
- async memberSave(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- await ctx.service.tenderPermission.savePermission(data.tid, data.member, data.permissionBlock);
- ctx.body = { err: 0, msg: '', data: '' };
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '保存标段权限错误');
- }
- }
- async auditSave(ctx) {
- try {
- if (ctx.session.sessionUser.is_admin === 0) throw '没有设置权限';
- const tid = parseInt(ctx.params.tid);
- const responseData = {
- err: 0, msg: '', data: null,
- };
- const tenderInfo = await ctx.service.tender.getDataById(tid);
- if (!tenderInfo) throw '标段不存在';
- const data = JSON.parse(ctx.request.body.data);
- if (!data.type) {
- throw '提交数据错误';
- }
- let uids;
- let auditList = [];
- switch (data.type) {
- case 'add-audit':
- // // 判断用户是单个还是数组
- uids = data.id instanceof Array ? data.id : [data.id];
- // // 判断该用户的组是否已加入到表中,已加入则提示无需添加
- auditList = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, ['quality']);
- const addAidList = ctx.helper._.difference(uids, ctx.helper._.map(auditList, 'uid'));
- if (addAidList.length === 0) {
- throw '用户已存在成员管理中,无需重复添加';
- }
- const accountList = await ctx.service.projectAccount.getAllDataByCondition({ where: { id: addAidList } });
- const insert_members = [];
- for (const account of accountList) {
- insert_members.push({
- uid: account.id,
- quality: ['1'],
- });
- }
- await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, ctx.helper._.map(accountList, 'id'), insert_members, ['quality']);
- responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, ['quality']);
- break;
- case 'del-audit':
- uids = data.id instanceof Array ? data.id : [data.id];
- if (uids.length === 0) throw '没有选择要移除的用户';
- auditList = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, ['quality']);
- // 判断uids和auditList中是否有相同的uid
- const commonUids = ctx.helper._.intersection(uids, ctx.helper._.map(auditList, 'uid'));
- if (commonUids.length === 0) {
- throw '该用户已不在成员管理中,移除失败';
- }
- const del_members = [];
- for (const uid of uids) {
- del_members.push({
- uid,
- quality: [],
- });
- }
- await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, uids, del_members, ['quality']);
- responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, ['quality']);
- break;
- case 'save-permission':
- uids = data.uid instanceof Array ? data.uid : [data.uid];
- await ctx.service.tenderPermission.saveOnePermission(tenderInfo.id, uids, data.members, ['quality']);
- break;
- case 'list':
- responseData.data = await ctx.service.tenderPermission.getPartsPermission(tenderInfo.id, ['quality']);
- break;
- default: throw '参数有误';
- }
- ctx.body = responseData;
- } catch (err) {
- this.log(err);
- ctx.body = { err: 1, msg: err.toString(), data: null };
- }
- }
- async info(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const renderData = {
- thirdParty: {
- gxby: ctx.session.sessionProject.gxby_status,
- dagl: ctx.session.sessionProject.dagl_status,
- },
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.info),
- };
- await this.layout('quality/info.ejs', renderData, 'quality/info_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
- }
- }
- async flaw(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const renderData = {
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.flaw),
- };
- await this.layout('quality/flaw.ejs', renderData, 'quality/flaw_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
- }
- }
- async lab(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const renderData = {
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.lab),
- };
- await this.layout('quality/lab.ejs', renderData, 'quality/lab_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
- }
- }
- async _loadXmjData(spec) {
- const xmj = await this.ctx.service.ledger.getAllDataByCondition({
- where: { tender_id: this.ctx.tender.id },
- columns: ['id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', 'code', 'b_code', 'name'],
- });
- // const quality = spec && spec.loadStatus ? await this.ctx.service.quality.getAllDataByCondition({
- // where: { tid: this.ctx.tender.id, rela_type: 'xmj' },
- // columns: ['rela_id', 'gxby_status', 'gxby_date', 'dagl_status'],
- // }) : [];
- // this.ctx.helper.assignRelaData(xmj, [
- // { data: quality, fields: ['gxby_status', 'gxby_date', 'dagl_status'], prefix: '', relaId: 'rela_id' },
- // ]);
- return xmj; // .filter(x => { return !x.b_code; });
- }
- async _loadPosData(condition, spec) {
- const pos = await this.ctx.service.pos.getAllDataByCondition({
- where: condition,
- columns: ['id', 'tid', 'lid', 'name'],
- orders: [['porder', 'ASC']],
- });
- // const quality = spec && spec.loadStatus ? await this.ctx.service.quality.getAllDataByCondition({
- // where: { tid: this.ctx.tender.id, rela_type: 'pos' },
- // columns: ['rela_id', 'gxby_status', 'gxby_date', 'dagl_status'],
- // }) : [];
- // this.ctx.helper.assignRelaData(pos, [
- // { data: quality, fields: ['gxby_status', 'gxby_date', 'dagl_status'], prefix: '', relaId: 'rela_id' },
- // ]);
- return pos;
- }
- async _loadDetailData(rela_type, rela_id, rela_name) {
- const result = await this.ctx.service.quality.getDataByCondition({ tid: this.ctx.tender.id, rela_type, rela_id, rela_name });
- if (!result) return result;
- await this.ctx.service.quality.loadQualityDetail(result);
- await this.ctx.service.quality.checkQualityStatusAndSave(result);
- return result;
- }
- async _loadData(type, data, result) {
- if (result[type]) return result[type];
- switch (type) {
- case 'xmj':
- return this._loadXmjData(data.spec);
- case 'pos':
- return this._loadPosData({ tid: this.ctx.tender.id }, data.spec);
- case 'detail':
- if (!data.rela_id && !data.rela_type) throw '缺少参数';
- return this._loadDetailData(data.rela_type, data.rela_id, data.rela_name);
- case 'quality':
- return await this.ctx.service.quality.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
- case 'lab':
- return await this.ctx.service.qualityLab.getAllDataByCondition({ where: { tid: this.ctx.tender.id } });
- default: throw '未知数据类型';
- }
- }
- async load(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- if (!data.filter) throw '参数错误';
- const filter = data.filter.split(';');
- const result = {};
- for (const f of filter) {
- result[f] = await this._loadData(f, data, result);
- }
- ctx.body = { err: 0, msg: '', data: result };
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '获取数据错误');
- }
- }
- async _saveKaigong(ctx, data) {
- if (data.add) {
- if (!ctx.permission.quality.add) throw '您无权新增开工';
- await ctx.service.quality.kaigong(data, data.add.name, data.add.date);
- } else if (data.update) {
- await ctx.service.quality.kaigong(data, data.update.name, data.update.date);
- } else if (data.del) {
- await ctx.service.quality.delKaigong(data);
- }
- }
- async _saveGongxu(ctx, data) {
- if (data.add) {
- if (!ctx.permission.quality.add) throw '您无权新增工序';
- await ctx.service.qualityGongxu.add(data, data.add.name);
- } else if (data.update) {
- await ctx.service.qualityGongxu.update(data.update.id, data.update.name);
- } else if (data.del) {
- await ctx.service.qualityGongxu.del(data.del);
- }
- }
- async _saveYinbi(ctx, data) {
- if (data.add) {
- if (!ctx.permission.quality.add) throw '您无权新增隐蔽工程';
- await ctx.service.qualityYinbi.add(data, data.add);
- } else if (data.update) {
- await ctx.service.qualityYinbi.update(data.update.id, data.update);
- } else if (data.del) {
- await ctx.service.qualityYinbi.del(data.del);
- }
- }
- async save(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- if (!data.quality_id && (!data.rela_type && !data.rela_id)) throw '参数错误';
- switch (ctx.params.type) {
- case 'kaigong':
- await this._saveKaigong(ctx, data);
- break;
- case 'gongxu':
- await this._saveGongxu(ctx, data);
- break;
- case 'yinbi':
- await this._saveYinbi(ctx, data);
- break;
- default: throw '请求错误';
- }
- const quality = await this._loadDetailData(data.rela_type, data.rela_id, data.rela_name);
- ctx.body = { err: 0, msg: '', data: quality };
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '保存数据错误');
- }
- }
- async checkCanUpload(ctx) {
- if (!ctx.permission.quality.upload) {
- throw '您无权上传、删除文件';
- }
- }
- async uploadFile(ctx) {
- let stream;
- try {
- await this.checkCanUpload(ctx);
- 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 quality = await ctx.service.quality.getDataById(parts.field.quality_id);
- if (!quality) throw '工程未开工';
- const blockType = parts.field.block_type;
- const blockId = parts.field.block_id || '';
- const specType = parts.field.spec_type || '';
- if (!blockType) throw '参数错误';
- const uploadfiles = [];
- while (stream !== undefined) {
- if (!stream.filename) throw '未发现上传文件!';
- const fileInfo = path.parse(stream.filename);
- const filepath = `${ctx.session.sessionProject.id}/${ctx.tender.id}/quality/${blockType}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
- // 保存文件
- await ctx.fujianOss.put(ctx.fujianOssPath + filepath, stream);
- await sendToWormhole(stream);
- // 插入到stage_pay对应的附件列表中
- uploadfiles.push({
- 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.qualityFile.addFiles(user, quality, uploadfiles, blockType, blockId, specType);
- ctx.body = { err: 0, msg: '', data: result };
- } catch (error) {
- ctx.log(error);
- // 失败需要消耗掉stream 以防卡死
- if (stream) await sendToWormhole(stream);
- ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
- }
- }
- async delFile(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- if (!data.del) throw '缺少参数';
- const result = await ctx.service.qualityFile.delFiles(data.del);
- ctx.body = { err: 0, msg: '', data: result };
- } catch (error) {
- this.log(error);
- ctx.ajaxErrorBody(error, '删除附件失败');
- }
- }
- async saveFile(ctx) {
- try {
- const data = JSON.parse(ctx.request.body.data);
- if (!data.id) throw '缺少参数';
- const result = await ctx.service.file.qualityFile(data.id, data.filename);
- ctx.body = { err: 0, msg: '', data: result };
- } catch (error) {
- this.log(error);
- ctx.ajaxErrorBody(error, '编辑附件失败');
- }
- }
- async rule(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const ruleGroups = await ctx.service.qualityRule.getRuleGroups(ctx.subProject.id);
- const tenderList = await ctx.service.tender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
- const renderData = {
- jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.quality.rule),
- ruleGroups,
- thirdParty: {
- gxby: ctx.session.sessionProject.gxby_status,
- dagl: ctx.session.sessionProject.dagl_status,
- },
- tenderList,
- };
- await this.layout('quality/rule.ejs', renderData, 'quality/rule_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/quality`);
- }
- }
- async ruleSave(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const data = JSON.parse(ctx.request.body.data);
- if (!data.group && !data.rule && !data.quality) throw '参数错误';
- if (data.group) {
- const result = await ctx.service.qualityRule.saveGroup(data.group);
- ctx.body = { err: 0, msg: '', data: result };
- } else if (data.rule) {
- const result = await ctx.service.qualityRule.saveRule(data.rule);
- ctx.body = { err: 0, msg: '', data: result };
- } else if (data.quality) {
- const result = await ctx.service.quality.saveQualityManage(this.ctx.tender.id, data.quality);
- ctx.body = { err: 0, msg: '', data: result };
- }
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '保存状态推送规则错误');
- }
- }
- async _pushIncStatus(select) {
- // todo 向其他系统推送
- return await this.ctx.service.quality.pushIncStatus(select);
- }
- async _pushAllStatus(select) {
- // todo 向其他系统推送
- return await this.ctx.service.quality.pushAllStatus(select);
- }
- async pushStatus(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) throw '该功能已关闭';
- const data = JSON.parse(ctx.request.body.data);
- if (!data.push_type) throw '参数错误';
- let count;
- switch (data.push_type) {
- case 'inc':
- count = await this._pushIncStatus(data.select);
- break;
- case 'all':
- count = await this._pushAllStatus();
- break;
- default: throw '参数错误';
- }
- ctx.body = { err: 0, msg: '', data: count };
- } catch (err) {
- ctx.log(err);
- ctx.ajaxErrorBody(err, '推送失败');
- }
- }
- /**
- * 变更管理 页面 (Get)
- *
- * @param {Object} ctx - egg全局变量
- * @return {void}
- */
- async inspection(ctx) {
- try {
- if (!ctx.subProject.page_show.quality) 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}/quality/tender`);
- }
- }
- // 质量巡检单功能
- 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.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.pending);
- filter.count[filter.status.uncheck] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.uncheck);
- filter.count[filter.status.checking] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checking);
- filter.count[filter.status.rectification] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.rectification);
- filter.count[filter.status.checked] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checked);
- filter.count[filter.status.checkStop] = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, filter.status.checkStop);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
- const inspectionList = await ctx.service.qualityInspection.getListByStatus(ctx.tender.id, status, 1, sorts, orders);
- const total = await ctx.service.qualityInspection.getCountByStatus(ctx.tender.id, status);
- const allAttList = inspectionList.length > 0 ? await ctx.service.qualityInspectionAtt.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 = '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.quality,
- 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.quality.inspection),
- pageInfo,
- };
- await this.layout('quality/inspection.ejs', renderData, 'quality/inspection_modal.ejs');
- } catch (err) {
- ctx.log(err);
- ctx.postError(err, '无法查看质量管理数据');
- ctx.redirect(`/sp/${ctx.subProject.id}/quality/tender`);
- }
- }
- /**
- * 新增变更申请 (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.qualityInspection.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.qualityInspection.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.qualityInspectionAtt.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.quality.inspection_information),
- preUrl: `/sp/${ctx.subProject.id}/quality/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('quality/inspection_information.ejs', renderData, 'quality/inspection_information_modal.ejs');
- } catch (err) {
- this.log(err);
- ctx.redirect(`/sp/${ctx.subProject.id}/quality/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.qualityInspection.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.qualityInspectionAudit.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.qualityInspectionAudit.addAuditor(ctx.inspection.id, id, ctx.inspection.times);
- if (!result) {
- throw '添加审核人失败';
- }
- reponseData.data = await ctx.service.qualityInspectionAudit.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.qualityInspectionAudit.deleteAuditor(ctx.inspection.id, id2, ctx.inspection.times);
- if (!result2) {
- throw '移除审核人失败';
- }
- reponseData.data = await ctx.service.qualityInspectionAudit.getAuditors(ctx.inspection.id, ctx.inspection.times);
- break;
- case 'start-inspection':
- if (ctx.inspection.readOnly) {
- throw '当前状态不可提交';
- }
- await ctx.service.qualityInspectionAudit.start(ctx.inspection.id, ctx.inspection.times);
- break;
- case 'del-inspection':
- if (ctx.inspection.readOnly) {
- throw '当前状态不可删除';
- }
- await ctx.service.qualityInspection.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.qualityInspectionAudit.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.qualityInspectionAudit.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()}/quality_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.qualityInspectionAtt.saveFileMsgToDb(payload);
- // 将最新的当前标段的所有文件信息返回
- const data = await ctx.service.qualityInspectionAtt.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.qualityInspectionAtt.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.qualityInspectionAtt.delete(id);
- } else {
- throw '不存在该文件';
- }
- const data = await ctx.service.qualityInspectionAtt.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.qualityInspectionAtt.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 QualityController;
- };
|