Przeglądaj źródła

安全计量相关

MaiXinRong 8 godzin temu
rodzic
commit
51c81a0bc0

+ 1 - 0
app/const/audit.js

@@ -1542,6 +1542,7 @@ module.exports = {
     ledger,
     stage,
     phasePay,
+    safeStage: phasePay,
     settle,
     revise,
     material,

+ 12 - 5
app/const/spread.js

@@ -139,6 +139,7 @@ const BaseSetCol = {
         { key: 'ex_memo2', name: '备注2', fixed: [], bills: 1, pos: 1, },
         { key: 'ex_memo3', name: '备注3', fixed: [], bills: 1, pos: 1, },
         { key: 'ex_calc1', name: '计算1', fixed: [], bills: 1, pos: 1, },
+        { key: 'from', name: '来源', fixed: ['alias'], bills: 1, pos: 1, },
     ],
     tz_stage_set: [
         { key: 'code', name: '项目节编号', fixed: ['move', 'valid', 'alias'], bills: 1, pos: 0 },
@@ -191,6 +192,7 @@ const BaseSetCol = {
         { key: 'ex_memo2', name: '备注2', fixed: [], bills: 1, pos: 1, },
         { key: 'ex_memo3', name: '备注3', fixed: [], bills: 1, pos: 1, },
         { key: 'ex_calc1', name: '计算1', fixed: [], bills: 1, pos: 1, },
+        { key: 'from', name: '来源', fixed: ['alias'], bills: 1, pos: 1, },
     ],
     gcl_stage_set: [
         { key: 'code', name: '项目节编号', fixed: ['move', 'valid', 'alias'], bills: 1, pos: 0 },
@@ -247,6 +249,7 @@ const glSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     tz_stage_set: [
         { key: 'code', valid: 1 },
@@ -299,6 +302,7 @@ const glSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     gcl_stage_set: [
         { key: 'code', valid: 1 },
@@ -354,6 +358,7 @@ const szSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     tz_stage_set: [
         { key: 'code', valid: 1 },
@@ -406,6 +411,7 @@ const szSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     gcl_stage_set: [
         { key: 'code', valid: 1 },
@@ -461,6 +467,7 @@ const fjSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     tz_stage_set: [
         { key: 'code', valid: 1 },
@@ -513,6 +520,7 @@ const fjSpreadTemplate = {
         { key: 'ex_memo2', valid: 0 },
         { key: 'ex_memo3', valid: 0 },
         { key: 'ex_calc1', valid: 0 },
+        { key: 'from', valid: 0 },
     ],
     gcl_stage_set: [
         { key: 'code', valid: 1 },
@@ -593,6 +601,7 @@ const BaseSpreadColSetting = {
                 {title: '计算1|数量', colSpan: '2|1', rowSpan: '1|1', field: 'ex_qty1', hAlign: 2, width: 60, type: 'Number', aliasFormat: '{%s}|数量'},
                 {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'ex_tp1', hAlign: 2, width: 60, type: 'Number', readOnly: true},
             ],
+            from: [{title: '来源', colSpan: '1', rowSpan: '2', field: 'from', hAlign: 1, width: 50, formatter: '@'}],
         },
         pos: {
             name: [{title: '计量单元', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 230, formatter: '@'}],
@@ -609,6 +618,7 @@ const BaseSpreadColSetting = {
             ex_memo2: [{title: 'ex_memo2', colSpan: '1', rowSpan: '2', field: 'ex_memo2', hAlign: 0, width: 100, formatter: '@', cellType: 'ellipsisAutoTip'}],
             ex_memo3: [{title: 'ex_memo3', colSpan: '1', rowSpan: '2', field: 'ex_memo3', hAlign: 0, width: 100, formatter: '@', cellType: 'ellipsisAutoTip'}],
             ex_calc1: [{title: '计算1数量', colSpan: '1', rowSpan: '2', field: 'ex_qty1', hAlign: 2, width: 100, type: 'Number', aliasFormat: '{%s}数量'}],
+            from: [{title: '来源', colSpan: '1', rowSpan: '2', field: 'from', hAlign: 1, width: 50, formatter: '@'}],
         }
     },
     tz_stage_set: {
@@ -759,6 +769,7 @@ const BaseSpreadColSetting = {
                 {title: '计算1|数量', colSpan: '2|1', rowSpan: '1|1', field: 'ex_qty1', hAlign: 2, width: 60, type: 'Number', aliasFormat: '{%s}|数量'},
                 {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'ex_tp1', hAlign: 2, width: 60, type: 'Number', readOnly: true},
             ],
+            from: [{title: '来源', colSpan: '1', rowSpan: '2', field: 'from', hAlign: 1, width: 50, formatter: '@'}],
         },
         pos: {
             name: [{title: '计量单元', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 230, formatter: '@'}],
@@ -775,6 +786,7 @@ const BaseSpreadColSetting = {
             ex_memo2: [{title: 'ex_memo2', colSpan: '1', rowSpan: '2', field: 'ex_memo2', hAlign: 0, width: 100, formatter: '@', cellType: 'ellipsisAutoTip'}],
             ex_memo3: [{title: 'ex_memo3', colSpan: '1', rowSpan: '2', field: 'ex_memo3', hAlign: 0, width: 100, formatter: '@', cellType: 'ellipsisAutoTip'}],
             ex_calc1: [{title: '计算1数量', colSpan: '1', rowSpan: '2', field: 'ex_qty1', hAlign: 2, width: 100, type: 'Number', aliasFormat: '{%s}数量'}],
+            from: [{title: '来源', colSpan: '1', rowSpan: '2', field: 'from', hAlign: 1, width: 50, formatter: '@'}],
         }
     },
     gcl_stage_set: {
@@ -1116,11 +1128,6 @@ const stageTz = {
             {title: '|项目节数量2',  colSpan: '|1', rowSpan: '|1', field: 'deal_dgn_qty2', hAlign: 2, width: 60, type: 'Number'},
             {title: '变更|项目节数量1',  colSpan: '2|1', rowSpan: '1|1', field: 'c_dgn_qty1', hAlign: 2, width: 60, type: 'Number'},
             {title: '|项目节数量2',  colSpan: '|1', rowSpan: '|1', field: 'c_dgn_qty2', hAlign: 2, width: 60, type: 'Number'},
-            // {title: '预估变更|数量', colSpan: '3|1', rowSpan: '1|1', field: 'due_qc_qty', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
-            // {title: '|不计价', colSpan: '|1', rowSpan: '|1', field: 'due_qc_minus_qty', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
-            // {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'due_qc_tp', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
-            // {title: '预估决算|数量', colSpan: '2|1', rowSpan: '1|1', field: 'due_final_qty', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
-            // {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'due_final_tp', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
             {title: '经济指标',  colSpan: '1', rowSpan: '2', field: 'final_dgn_price', hAlign: 2, width: 60, readOnly: true, type: 'Number'},
             {title: '本期批注', colSpan: '1', rowSpan: '2', field: 'postil', hAlign: 0, width: 100, formatter: '@', cellType: 'autoTip'},
             {title: '图(册)号', colSpan: '1', rowSpan: '2', field: 'drawing_code', hAlign: 0, width: 80, formatter: '@', readOnly: true},

+ 4 - 2
app/controller/ledger_controller.js

@@ -73,11 +73,13 @@ module.exports = app => {
             const ledgerColumn = [
                 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
                 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price',
-                'sgfh_qty', 'sgfh_expr', 'sgfh_tp', 'memo', 'features', 'drawing_code', 'node_type', 'ex_qty1', 'ex_tp1'];
+                'sgfh_qty', 'sgfh_expr', 'sgfh_tp', 'memo', 'features', 'drawing_code', 'node_type', 'ex_qty1', 'ex_tp1',
+                'crid', 'ccid'
+            ];
             if (tender.info.display.ledger.deal) ledgerColumn.push('deal_qty', 'deal_tp');
             if (tender.info.display.ledger.dgnQty) ledgerColumn.push('dgn_qty1', 'dgn_qty2');
             if (tender.info.display.ledger.clQty) ledgerColumn.push('sjcl_qty', 'qtcl_qty', 'sjcl_expr', 'qtcl_expr', 'sjcl_tp', 'qtcl_tp');
-            const posColumn = ['id', 'tid', 'lid', 'name', 'position', 'porder', 'sgfh_qty', 'sgfh_expr', 'add_stage_order', 'drawing_code', 'quantity', 'ex_qty1'];
+            const posColumn = ['id', 'tid', 'lid', 'name', 'position', 'porder', 'sgfh_qty', 'sgfh_expr', 'add_stage_order', 'drawing_code', 'quantity', 'ex_qty1', 'crid', 'ccid'];
             if (tender.info.display.ledger.clQty) posColumn.push('sjcl_qty', 'qtcl_qty', 'sjcl_expr', 'qtcl_expr');
 
             const extraFields = await spreadSetting.getExtraFields(this.ctx, tender.id);

+ 0 - 1
app/controller/pay_controller.js

@@ -314,7 +314,6 @@ module.exports = app => {
                 ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
             }
         }
-
         async deleteFile(ctx) {
             try{
                 const data = JSON.parse(ctx.request.body.data);

+ 412 - 0
app/controller/safe_controller.js

@@ -74,6 +74,418 @@ module.exports = app => {
             }
         }
 
+        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 '该功能已关闭';

+ 0 - 2
app/controller/stage_controller.js

@@ -271,7 +271,6 @@ module.exports = app => {
                     await ctx.service.stageBills.deleteById(surplus);
                 }
             }
-            const changeData = await ctx.service.changeAuditList.getBillsSum(ctx.tender.id);
             // 结算状态
             const settleStatus = ctx.stage.readySettle ? await ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: ctx.stage.readySettle.id }}) : [];
             // 查询截止上期数据
@@ -285,7 +284,6 @@ module.exports = app => {
                 { data: curStageData, fields: ['contract_qty', 'contract_expr', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty', 'postil', 'ex_stage_qty1', 'ex_stage_tp1'], prefix: '', relaId: 'lid' },
                 { data: preStageData, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty', 'used', 'ex_stage_qty1', 'ex_stage_tp1', 'used_time', 'update_time'], prefix: 'pre_', relaId: 'lid' },
                 { data: pcData, fields: ['contract_pc_tp', 'qc_pc_tp', 'pc_tp', 'org_price'], prefix: '', relaId: 'lid' },
-                { data: changeData, fields: ['qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'due_', relaId: 'gcl_id' },
                 { data: settleStatus, fields: ['settle_status'], prefix: '', relaId: 'lid' },
                 { data: exprData, fields: ['expr'], prefix: 'calc_', relaId: 'calc_id' },
             ]);

+ 34 - 34
app/lib/ledger.js

@@ -1448,49 +1448,49 @@ const treeUtils = {
                 if (helper._.isMatch(cb, b)) return node;
             }
             return null;
-        };
-        for (const change of changes) {
-            for (const changeBills of change.bills) {
-                const node = changeBills.gcl_id
-                    ? tree.nodes.find(x => {return x.id === changeBills.gcl_id})
-                    : findEmptyBills(tree, change, changeBills);
+            for (const change of changes) {
+                for (const changeBills of change.bills) {
+                    const node = changeBills.gcl_id
+                        ? tree.nodes.find(x => {return x.id === changeBills.gcl_id})
+                        : findEmptyBills(tree, change, changeBills);
 
-                if (!node) continue;
-                if (!node.changeBills) node.changeBills = [];
-                node.tz_qc_qty = helper.add(node.tz_qc_qty, changeBills.checked_amount);
-                if (tenderInfo.calc_type === 'up') {
-                    node.tz_qc_tp = helper.add(node.tz_qc_tp, changeBills.checked_price);
-                } else {
-                    node.tz_qc_tp = helper.add(node.tz_qc_tp, changeBills.tp);
-                }
+                    if (!node) continue;
+                    if (!node.changeBills) node.changeBills = [];
+                    node.tz_qc_qty = helper.add(node.tz_qc_qty, changeBills.checked_amount);
+                    if (tenderInfo.calc_type === 'up') {
+                        node.tz_qc_tp = helper.add(node.tz_qc_tp, changeBills.checked_price);
+                    } else {
+                        node.tz_qc_tp = helper.add(node.tz_qc_tp, changeBills.tp);
+                    }
 
-                const posData = pos ? pos.getLedgerPos(node.id) : undefined;
-                if (posData && posData.length > 0) {
-                    for (const p of changeBills.pos) {
-                        const changePos = p.bwmx ? posData.find(x => { return x.name === p.bwmx; }) : posData[0];
-                        if (changePos) {
-                            changePos.tz_qc_qty = helper.add(changePos.tz_qc_qty, p.checked_amount);
-                            if (!changePos.changeBills) changePos.changeBills = [];
-                            changePos.changeBills.push({
-                                code: change.code || '', name: change.name || '', is_valuation:  p.is_valuation,
-                                qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: changePos.name,
-                            });
+                    const posData = pos ? pos.getLedgerPos(node.id) : undefined;
+                    if (posData && posData.length > 0) {
+                        for (const p of changeBills.pos) {
+                            const changePos = p.bwmx ? posData.find(x => { return x.name === p.bwmx; }) : posData[0];
+                            if (changePos) {
+                                changePos.tz_qc_qty = helper.add(changePos.tz_qc_qty, p.checked_amount);
+                                if (!changePos.changeBills) changePos.changeBills = [];
+                                changePos.changeBills.push({
+                                    code: change.code || '', name: change.name || '', is_valuation:  p.is_valuation,
+                                    qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: changePos.name,
+                                });
+                                node.changeBills.push({
+                                    code: change.code || '', name: change.name || '', is_valuation: p.is_valuation,
+                                    qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: changePos.name,
+                                });
+                            }
+                        }
+                    } else {
+                        for (const p of changeBills.pos) {
                             node.changeBills.push({
                                 code: change.code || '', name: change.name || '', is_valuation: p.is_valuation,
-                                qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: changePos.name,
+                                qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: '',
                             });
                         }
                     }
-                } else {
-                    for (const p of changeBills.pos) {
-                        node.changeBills.push({
-                            code: change.code || '', name: change.name || '', is_valuation: p.is_valuation,
-                            qty: p.checked_amount || 0, tp: p.checked_price || 0, pos: '',
-                        });
-                    }
                 }
             }
-        }
+        };
     }
 };
 

+ 2 - 2
app/lib/ybp_tree.js

@@ -198,7 +198,7 @@ class YbpImportTree {
             cur.dgn_qty1 = isXmj ? node.quantity || 0 : 0;
             cur.dgn_qty2 = isXmj ? node.quantity2 || 0 : 0;
             cur.quantity = isXmj ? 0 : node.quantity || 0;
-            cur.total_fee = node.fees ? node.fees.marketCommon.totalFee : 0;
+            cur.total_fee = node.fees && node.fees.marketCommon ? node.fees.marketCommon.totalFee : 0;
             cur.labour_fee = node.fees && node.fees.marketLabour ? node.fees.marketLabour.totalFee : 0;
             cur.remark = node.remark;
             cur.features = node.itemCharacterText || '';
@@ -209,7 +209,7 @@ class YbpImportTree {
             } else {
                 cur.quantity = this.helper.add(cur.quantity, node.quantity || 0);
             }
-            cur.total_fee = this.helper.add(cur.total_fee, node.fees ? node.fees.marketCommon.totalFee : 0);
+            cur.total_fee = this.helper.add(cur.total_fee, node.fees && node.fees.marketCommon ? node.fees.marketCommon.totalFee : 0);
             cur.labour_fee = this.helper.add(cur.labour_fee, node.fees && node.fees.marketLabour ? node.fees.marketLabour.totalFee : 0);
         }
         if (loadRelaFun) loadRelaFun(cur, node);

+ 58 - 0
app/middleware/safe_stage_check.js

@@ -0,0 +1,58 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Mai
+ * @date
+ * @version
+ */
+
+module.exports = options => {
+    /**
+     * 期校验 中间件
+     * 1. 读取期数据
+     * 2. 检验用户是否参与期(不校验具体权限)
+     *
+     * 写入ctx.safeStage数据
+     * 其中:
+     * safeStage.user: 创建人
+     * safeStage.auditors: 审批人列表(退回原报时,加载上一流程)
+     * safeStage.curAuditors: 当前审批人(未上报为空,审批通过 or 退回原报时,为空)
+     *
+     * safeStage.readOnly: 登录人,是否可操作
+     * safeStage.curTimes: 当前登录人,操作、查阅数据times
+     * safeStage.curOrder: 当前登录人,操作、查阅数据order
+     *
+     * 该方法为通用方法,如需safeStage其他数据,请在controller中查询
+     *
+     * @param {function} next - 中间件继续执行的方法
+     * @return {void}
+     */
+    return function* safeStageCheck(next) {
+        try {
+            // 读取标段数据
+            const stageOrder = parseInt(this.params.sorder);
+            if (stageOrder <= 0) throw '您访问的合同支付不存在';
+
+            const safeStage = yield this.service.safeStage.getStageByOrder(this.tender.id, stageOrder);
+            if (!safeStage) throw '合同支付数据错误';
+
+            // 读取原报、审核人数据
+            yield this.service.safeStage.doCheckStage(safeStage);
+            safeStage.latestOrder = yield this.service.safeStage.count({ tid: this.tender.id });
+            safeStage.isLatest = safeStage.latestOrder === safeStage.stage_order;
+            yield this.service.safeStage.checkShenpi(safeStage);
+            this.safeStage = safeStage;
+            yield next;
+        } catch (err) {
+            this.log(err);
+            if (this.helper.isAjax(this.request)) {
+                this.ajaxErrorBody(err, '读取安全计量数据错误');
+            } else {
+                this.postError(err, '读取安全计量数据错误');
+                this.redirect(this.request.headers.referer);
+            }
+        }
+    };
+};

+ 2 - 0
app/public/js/ledger.js

@@ -1166,6 +1166,8 @@ $(document).ready(function() {
     //     {title: 'node_type', colSpan: '1', rowSpan: '2', field: 'node_type', hAlign: 2, width: 60, type: 'Number', readOnly: true}
     // );
     sjsSettingObj.setNodeTypeCol(ledgerSpreadSetting.cols, [{ field: 'node_type' }]);
+    sjsSettingObj.setFromCol(posSpreadSetting.cols, [{field: 'from'}]);
+    sjsSettingObj.setFromCol(ledgerSpreadSetting.cols, [{ field: 'from'}]);
     SpreadJsObj.initSheet(ledgerSpread.getActiveSheet(), ledgerSpreadSetting);
     SpreadJsObj.selChangedRefreshBackColor(ledgerSpread.getActiveSheet());
     // 绑定事件

+ 795 - 0
app/public/js/safe_bills.js

@@ -0,0 +1,795 @@
+function getTenderId() {
+    return window.location.pathname.split('/')[2];
+}
+const invalidFields = {
+    parent: ['cur_qty', 'cur_tp', 'unit_price'],
+};
+function transExpr(expr) {
+    return $.trim(expr).replace('\t', '').replace('=', '').replace('%', '/100');
+}
+
+$(document).ready(function() {
+    let stdGcl;
+    autoFlashHeight();
+    class BillsObj {
+        constructor() {
+            this.spread = SpreadJsObj.createNewSpread($('#bills-spread')[0]);
+            this.sheet = this.spread.getActiveSheet();
+            this.treeSetting = {
+                id: 'tree_id',
+                pid: 'tree_pid',
+                order: 'tree_order',
+                level: 'tree_level',
+                isLeaf: 'tree_is_leaf',
+                fullPath: 'tree_full_path',
+                rootId: -1,
+                calcFields: ['cur_tp', 'pre_tp', 'end_tp'],
+                keys: ['id', 'stage_id', 'tree_id'],
+            };
+            this.tree = createNewPathTree('ledger', this.treeSetting);
+            this.spreadSetting = {
+                cols: [
+                    {title: '编号', colSpan: '1', rowSpan: '2', field: 'b_code', hAlign: 0, width: 230, formatter: '@', cellType: 'tree'},
+                    {title: '名称', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 185, formatter: '@', cellType: 'autoTip'},
+                    {title: '规格', colSpan: '1', rowSpan: '2', field: 'spec', hAlign: 0, width: 150, formatter: '@'},
+                    {title: '单位', colSpan: '1', rowSpan: '2', field: 'unit', hAlign: 1, width: 50, formatter: '@', cellType: 'unit'},
+                    {title: '单价', colSpan: '1', rowSpan: '2', field: 'unit_price', hAlign: 2, width: 80, type: 'Number'},
+                    {title: '本期|数量', colSpan: '2|1', rowSpan: '1|1', field: 'cur_qty', hAlign: 2, width: 80, type: 'Number'},
+                    {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'cur_tp', hAlign: 2, width: 80, type: 'Number'},
+                    {title: '截止本期|数量', colSpan: '2|1', rowSpan: '1|1', field: 'end_qty', hAlign: 2, width: 80, type: 'Number'},
+                    {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'end_tp', hAlign: 2, width: 80, type: 'Number', readOnly: true},
+                    {title: '发票号', colSpan: '1', rowSpan: '2', field: 'invoice_code', hAlign: 0, width: 100, formatter: '@'},
+                    {title: '备注', colSpan: '1', rowSpan: '2', field: 'memo', hAlign: 0, width: 120, formatter: '@', cellType: 'ellipsisAutoTip'},
+                ],
+                emptyRows: 3,
+                headRows: 2,
+                headRowHeight: [25, 25],
+                defaultRowHeight: 21,
+                headerFont: '12px 微软雅黑',
+                font: '12px 微软雅黑',
+                readOnly: readOnly,
+                localCache: {
+                    key: 'payment-safe-bills',
+                    colWidth: true,
+                },
+            };
+            this.ckBillsSpread = window.location.pathname + '-billsSelect';
+
+            this.initSpread();
+            this.initOtherEvent();
+        }
+        initSpread() {
+            SpreadJsObj.initSheet(this.sheet, this.spreadSetting);
+            this.spread.bind(spreadNS.Events.SelectionChanged, this.selectionChanged);
+            this.spread.bind(spreadNS.Events.topRowChanged, this.topRowChanged);
+            this.spread.bind(spreadNS.Events.ClipboardChanging, function (e, info) {
+                const copyText = SpreadJsObj.getFilterCopyText(info.sheet);
+                SpreadJsObj.Clipboard.setCopyData(copyText);
+            });
+            if (readOnly) return;
+
+            this.spread.bind(spreadNS.Events.EditEnded, this.editEnded);
+            this.spread.bind(spreadNS.Events.EditStarting, this.editStarting);
+            this.spread.bind(spreadNS.Events.ClipboardPasting, this.clipboardPasting);
+            SpreadJsObj.addDeleteBind(this.spread, this.deletePress);
+        }
+        initOtherEvent() {
+            const self = this;
+            // 增删上下移升降级
+            $('a[name="base-opr"]').click(function () {
+                self.baseOpr(this.getAttribute('type'));
+            });
+        }
+        refreshOperationValid() {
+            const setObjEnable = function (obj, enable) {
+                if (enable) {
+                    obj.removeClass('disabled');
+                } else {
+                    obj.addClass('disabled');
+                }
+            };
+            const invalidAll = function () {
+                setObjEnable($('a[name=base-opr][type=add]'), false);
+                setObjEnable($('a[name=base-opr][type=delete]'), false);
+                setObjEnable($('a[name=base-opr][type=up-move]'), false);
+                setObjEnable($('a[name=base-opr][type=down-move]'), false);
+                setObjEnable($('a[name=base-opr][type=up-level]'), false);
+                setObjEnable($('a[name=base-opr][type=down-level]'), false);
+            };
+            const sel = this.sheet.getSelections()[0];
+            const row = sel ? sel.row : -1;
+            const tree = this.sheet.zh_tree;
+            if (!tree) {
+                invalidAll();
+                return;
+            }
+            const first = tree.nodes[row];
+            if (!first) {
+                invalidAll();
+                return;
+            }
+            let last = first, sameParent = true, nodeUsed = this.checkNodeUsed(tree, first);
+            if (sel.rowCount > 1 && first) {
+                for (let r = 1; r < sel.rowCount; r++) {
+                    const rNode = tree.nodes[sel.row + r];
+                    if (!rNode) {
+                        sameParent = false;
+                        break;
+                    }
+                    nodeUsed = nodeUsed || this.checkNodeUsed(tree, rNode);
+                    if (rNode.tree_level > first.tree_level) continue;
+                    if ((rNode.tree_level < first.tree_level) || (rNode.tree_level === first.tree_level && rNode.tree_pid !== first.tree_pid)) {
+                        sameParent = false;
+                        break;
+                    }
+                    last = rNode;
+                }
+            }
+            const preNode = tree.getPreSiblingNode(first);
+            const valid = !this.sheet.zh_setting.readOnly;
+
+            setObjEnable($('a[name=base-opr][type=add]'), valid && first && first.tree_level > 1);
+            setObjEnable($('a[name=base-opr][type=delete]'), valid && first && sameParent && first.tree_level > 1 && !nodeUsed);
+            setObjEnable($('a[name=base-opr][type=up-move]'), valid && first && sameParent && first.tree_level > 1 && preNode);
+            setObjEnable($('a[name=base-opr][type=down-move]'), valid && first && sameParent && first.tree_level > 1 && !tree.isLastSibling(last));
+            setObjEnable($('a[name=base-opr][type=up-level]'), valid && first && sameParent && tree.getParent(first) && !nodeUsed && first.tree_level > 2);
+            setObjEnable($('a[name=base-opr][type=down-level]'), valid && first && sameParent && first.tree_level > 1 && preNode && !this.checkNodeUsed(tree, preNode));
+        }
+        loadRelaData() {
+            this.refreshOperationValid();
+            SpreadJsObj.saveTopAndSelect(this.sheet, this.ckBillsSpread);
+            safeBillsFile.getCurAttHtml(SpreadJsObj.getSelectObject(this.sheet));
+        }
+        refreshTree(data) {
+            const sheet = this.sheet;
+            SpreadJsObj.massOperationSheet(sheet, function () {
+                const tree = sheet.zh_tree;
+                // 处理删除
+                if (data.delete) {
+                    data.delete.sort(function (a, b) {
+                        return b.deleteIndex - a.deleteIndex;
+                    });
+                    for (const d of data.delete) {
+                        sheet.deleteRows(d.deleteIndex, 1);
+                    }
+                }
+                // 处理新增
+                if (data.create) {
+                    const newNodes = data.create;
+                    if (newNodes) {
+                        newNodes.sort(function (a, b) {
+                            return a.index - b.index;
+                        });
+
+                        for (const node of newNodes) {
+                            sheet.addRows(node.index, 1);
+                            SpreadJsObj.reLoadRowData(sheet, tree.nodes.indexOf(node), 1);
+                        }
+                    }
+                }
+                // 处理更新
+                if (data.update) {
+                    const rows = [];
+                    for (const u of data.update) {
+                        rows.push(tree.nodes.indexOf(u));
+                    }
+                    SpreadJsObj.reLoadRowsData(sheet, rows);
+                }
+                // 处理展开
+                if (data.expand) {
+                    const expanded = [];
+                    for (const e of data.expand) {
+                        if (expanded.indexOf(e) === -1) {
+                            const posterity = tree.getPosterity(e);
+                            for (const p of posterity) {
+                                sheet.setRowVisible(tree.nodes.indexOf(p), p.visible);
+                                expanded.push(p);
+                            }
+                        }
+                    }
+                }
+            });
+        }
+        loadData(datas) {
+            this.tree.loadDatas(datas);
+            treeCalc.calculateAll(this.tree);
+            SpreadJsObj.loadSheetData(this.sheet, SpreadJsObj.DataType.Tree, this.tree);
+            SpreadJsObj.loadTopAndSelect(this.sheet, this.ckBillsSpread);
+            this.refreshOperationValid();
+        }
+        getDefaultSelectInfo() {
+            if (!this.tree) return;
+            const sel = this.sheet.getSelections()[0];
+            const node = this.sheet.zh_tree.nodes[sel.row];
+            if (!node) return;
+            let count = 1;
+            if (sel.rowCount > 1) {
+                for (let r = 1; r < sel.rowCount; r++) {
+                    const rNode = this.sheet.zh_tree.nodes[sel.row + r];
+                    if (rNode.tree_level > node.tree_level) continue;
+                    if ((rNode.tree_level < node.tree_level) || (rNode.tree_level === node.tree_level && rNode.tree_pid !== node.tree_pid)) {
+                        toastr.warning('请选择同一节点下的节点,进行该操作');
+                        return;
+                    }
+                    count += 1;
+                }
+            }
+            return [this.tree, node, count];
+        }
+        checkNodeUsed(tree, node) {
+            if (node.pre_qty || node.pre_tp) return true;
+            const posterity = tree.getPosterity(node);
+            for (const p of posterity) {
+                if (p.pre_qty || p.pre_tp) return true;
+            }
+            return false;
+        }
+        baseOpr(type, addCount = 1) {
+            const self = this;
+            const sheet = self.sheet;
+            const sel = sheet.getSelections()[0];
+            const [tree, node, count] = this.getDefaultSelectInfo();
+            if (!tree || !node || !count) return;
+
+            if (type === 'delete') {
+                const parent = tree.getParent(node);
+                const children = parent ? parent.children : tree.children;
+                const index = children.indexOf(node);
+                for (let i = 0; i < count; i++) {
+                    const child = children[i+index];
+                    if (this.checkNodeUsed(tree, child)) {
+                        toastr.warning('选中的节点已计量,不可删除');
+                        return;
+                    }
+                }
+            } else if (type === 'up-level') {
+                const parent = tree.getParent(node);
+                const children = parent ? parent.children : tree.children;
+                const index = children.indexOf(node);
+                for (let i = index; i < children.length; i++) {
+                    const child = children[index];
+                    if (this.checkNodeUsed(tree, child)) {
+                        if (i >= index + count) {
+                            toastr.warning('其后节点已计量,选中的节点不可升级');
+                        } else {
+                            toastr.warning('选中的节点已计量,不可升级');
+                        }
+                        return;
+                    }
+                }
+            } else if (type === 'down-level') {
+                const parent = tree.getParent(node);
+                const children = parent ? parent.children : tree.children;
+                const index = children.indexOf(node);
+                if (index > 0 && this.checkNodeUsed(tree, children[index-1])) {
+                    toastr.warning('其前节点已计量,选中的节点不可降级');
+                    return;
+                }
+                for (let i = index; i < count; i++) {
+                    const child = children[i+index];
+                    if (this.checkNodeUsed(tree, child)) {
+                        toastr.warning('选中的节点已计量,不可降级');
+                        return;
+                    }
+                }
+            }
+
+            const updateData = {
+                postType: type,
+                postData: {
+                    id: node.tree_id,
+                    count: type === 'add' ? addCount : count,
+                }
+            };
+            if (type === 'delete') {
+                deleteAfterHint(function () {
+                    postData('update', updateData, function (result) {
+                        const refreshData = tree.loadPostData(result);
+                        self.refreshTree(refreshData);
+                        if (sel) {
+                            sheet.setSelection(sel.row, sel.col, 1, sel.colCount);
+                        }
+                        self.refreshOperationValid();
+                    });
+                });
+            } else {
+                postData('update', updateData, function (result) {
+                    const refreshData = tree.loadPostData(result);
+                    self.refreshTree(refreshData);
+                    if (['up-move', 'down-move'].indexOf(type) > -1) {
+                        if (sel) {
+                            sheet.setSelection(tree.nodes.indexOf(node), sel.col, sel.rowCount, sel.colCount);
+                            // SpreadJsObj.reloadRowsBackColor(sheet, [sel.row, tree.nodes.indexOf(node)]);
+                        }
+                    } else if (type === 'add') {
+                        const sel = sheet.getSelections()[0];
+                        if (sel) {
+                            sheet.setSelection(tree.nodes.indexOf(refreshData.create[0]), sel.col, sel.rowCount, sel.colCount);
+                            // SpreadJsObj.reloadRowsBackColor(sheet, [sel.row, tree.nodes.indexOf(refreshData.create[0])]);
+                        }
+                    }
+                    self.refreshOperationValid();
+                });
+            }
+        }
+        // 事件
+        selectionChanged(e, info) {
+            if (info.newSelections) {
+                if (!info.oldSelections || info.newSelections[0].row !== info.oldSelections[0].row) {
+                    billsObj.loadRelaData();
+                }
+            }
+        }
+        topRowChanged(e, info) {
+            SpreadJsObj.saveTopAndSelect(info.sheet, billsObj.ckBillsSpread);
+        }
+        editEnded(e, info) {
+            if (!info.sheet.zh_setting) return;
+
+            const tree = info.sheet.zh_tree;
+            const node = SpreadJsObj.getSelectObject(info.sheet);
+            const data = { id: node.id, stage_id: node.stage_id, tree_id: node.tree_id };
+            // 未改变值则不提交
+            const col = info.sheet.zh_setting.cols[info.col];
+            const orgValue = node[col.field];
+            const newValue = trimInvalidChar(info.editingText);
+            if (orgValue == info.editingText || ((!orgValue || orgValue === '') && (newValue === ''))) return;
+
+            if (info.editingText) {
+                const text = newValue;
+                if (billsObj.checkNodeUsed(tree, node) && col.field ==='b_code' && orgValue !== '' && text === '') {
+                    toastr.error('节点已计量,请勿删除编号');
+                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
+                    return;
+                }
+                if (col.type === 'Number') {
+                    const num = _.toNumber(text);
+                    if (_.isFinite(num)) {
+                        data[col.field] = num;
+                    } else {
+                        try {
+                            data[col.field] = ZhCalc.mathCalcExpr(transExpr(text));
+                        } catch(err) {
+                            toastr.error('输入的表达式非法');
+                            SpreadJsObj.reLoadRowData(info.sheet, info.row);
+                            return;
+                        }
+                    }
+                } else {
+                    data[col.field] = text;
+                }
+            } else {
+                if (billsObj.checkNodeUsed(tree, node) && (col.field ==='b_code') && orgValue !== '') {
+                    toastr.error('节点已计量,请勿删除编号');
+                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
+                    return;
+                }
+                data[col.field] = col.type === 'Number' ? 0 : '';
+            }
+            // 更新至服务器
+            postData('update', {postType: 'update', postData: data}, function (result) {
+                const refreshNode = billsObj.tree.loadPostData(result);
+                billsObj.refreshTree(refreshNode);
+            }, function () {
+                SpreadJsObj.reLoadRowData(info.sheet, info.row, 1);
+            });
+        }
+        editStarting(e, info) {
+            if (!info.sheet.zh_setting || !info.sheet.zh_tree) return;
+
+            const tree = info.sheet.zh_tree;
+            const col = info.sheet.zh_setting.cols[info.col];
+            const node = info.sheet.zh_tree.nodes[info.row];
+            if (!node) {
+                info.cancel = true;
+                return;
+            }
+
+            switch (col.field) {
+                case 'b_code':
+                    info.cancel = readOnly || billsObj.checkNodeUsed(tree, node);
+                    break;
+                case 'unit_price':
+                    info.cancel = readOnly || (node.children && node.children.length > 0);
+                    break;
+                case 'cur_qty':
+                case 'cur_tp':
+                    info.cancel = (node.children && node.children.length > 0);
+                    break;
+            }
+        }
+        deletePress (sheet) {
+            if (!sheet.zh_setting) return;
+            const sel = sheet.getSelections()[0], datas = [];
+            for (let iRow = sel.row; iRow < sel.row + sel.rowCount; iRow++) {
+                let bDel = false;
+                const node = sheet.zh_tree.nodes[iRow];
+                const data = sheet.zh_tree.getNodeKeyData(node);
+                for (let iCol = sel.col; iCol < sel.col + sel.colCount; iCol++) {
+                    const col = sheet.zh_setting.cols[iCol];
+                    const style = sheet.getStyle(iRow, iCol);
+                    if (style.locked) continue;
+
+                    if (col.field === 'b_code' &&  sheet.zh_tree.checkNodeUsed(node, pos)) {
+                        toastr.warning(`"${node.b_code || ''} ${node.name}"已计量,请勿修改`);
+                        return;
+                    }
+
+                    data[col.field] = col.type === 'Number' ? 0 : '';
+                    bDel = true;
+                }
+                if (bDel) datas.push(data);
+            }
+            if (datas.length > 0) {
+                postData('update', {postType: 'update', postData: datas}, function (result) {
+                    const refreshNode = sheet.zh_tree.loadPostData(result);
+                    billsObj.refreshTree(refreshNode);
+                }, function () {
+                    SpreadJsObj.reLoadRowData(info.sheet, sel.row, sel.rowCount);
+                });
+            }
+        }
+        clipboardPasting(e, info) {
+            info.cancel = true;
+            const tree = info.sheet.zh_tree, setting = info.sheet.zh_setting;
+            if (!setting || !tree) return;
+
+            const pasteData = info.pasteData.html
+                ? SpreadJsObj.analysisPasteHtml(info.pasteData.html)
+                : (info.pasteData.text === ''
+                    ? SpreadJsObj.Clipboard.getAnalysisPasteText()
+                    : SpreadJsObj.analysisPasteText(info.pasteData.text));
+            const hint = {
+                usedUp: {type: 'warning', msg: '节点已计量,不可修改单价'},
+                usedCode: {type: 'warning', msg: '节点已计量,编号不可修改'},
+                invalidExpr: {type: 'warning', msg: '粘贴的表达式非法'},
+                parent: {type: 'warning', msg: '含有子项的清单,不可粘贴数量、单价、金额'},
+            };
+            const datas = [], filterNodes = [];
+
+            let level, filterRow = 0;
+            for (let iRow = 0; iRow < info.cellRange.rowCount; iRow ++) {
+                const curRow = info.cellRange.row + iRow;
+                const node = tree.nodes[curRow];
+                if (!node) continue;
+
+                if (!level) level = node.level;
+                if (node.level < level) break;
+
+                let bPaste = false;
+                const data = info.sheet.zh_tree.getNodeKeyData(node);
+                for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
+                    const curCol = info.cellRange.col + iCol;
+                    const colSetting = info.sheet.zh_setting.cols[curCol];
+                    const value = trimInvalidChar(pasteData[iRow-filterRow][iCol]);
+                    if (node.children && node.children.length > 0 && invalidFields.parent.indexOf(colSetting.field) >= 0) {
+                        toastMessageUniq(hint.parent);
+                        continue;
+                    }
+
+                    if (billsObj.checkNodeUsed(tree, node) && colSetting.field === 'unit_price') {
+                        toastMessageUniq (hint.usedUp);
+                        continue;
+                    }
+                    if (colSetting.type === 'Number') {
+                        const num = _.toNumber(value);
+                        if (num) {
+                            data[colSetting.field] = num;
+                        } else {
+                            try {
+                                data[colSetting.field] = ZhCalc.mathCalcExpr(transExpr(value));
+                                bPaste = true;
+                            } catch (err) {
+                                toastMessageUniq(hint.invalidExpr);
+                                continue;
+                            }
+                        }
+                    } else {
+                        if (node.used && (colSetting.field ==='b_code') && data[colSetting.field] !== '' && value === '') {
+                            toastMessageUniq(hint.usedCode);
+                            continue;
+                        }
+                        data[colSetting.field] = value;
+                    }
+                    bPaste = true;
+                }
+                if (bPaste) {
+                    datas.push(data);
+                } else {
+                    filterNodes.push(node);
+                }
+            }
+            if (datas.length > 0) {
+                postData('update', {postType: 'update', postData: datas}, function (result) {
+                    const refreshNode = tree.loadPostData(result);
+                    if (refreshNode.update) refreshNode.update = refreshNode.update.concat(filterNodes);
+                    billsObj.refreshTree(refreshNode);
+                }, function () {
+                    SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
+                });
+            } else {
+                SpreadJsObj.reLoadRowData(info.sheet, info.cellRange.row, info.cellRange.rowCount);
+            }
+        }
+    }
+    const billsObj = new BillsObj();
+
+    // 清单右键菜单
+    const billsContextMenuOptions = {
+        selector: '#bills-spread',
+        build: function ($trigger, e) {
+            const target = SpreadJsObj.safeRightClickSelection($trigger, e, billsSpread);
+            billsObj.loadRelaData();
+            return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
+        },
+        items: {}
+    };
+    if (!readOnly) {
+        billsContextMenuOptions.items.create = {
+            name: '新增',
+            icon: 'fa-sign-in',
+            callback: function (key, opt) {
+                billsObj.baseOpr('add');
+            },
+            disabled: function (key, opt) {
+                const sheet = billsObj.sheet;
+                const selection = sheet.getSelections();
+                const sel = selection ? selection[0] : sheet.getSelections()[0];
+                const row = sel ? sel.row : -1;
+                const tree = sheet.zh_tree;
+                if (!tree) return true;
+                const first = sheet.zh_tree.nodes[row];
+                const valid = !sheet.zh_setting.readOnly;
+                return !(valid && first && first.tree_level > 1);
+            }
+        };
+        billsContextMenuOptions.items.delete = {
+            name: '删除',
+            icon: 'fa-remove',
+            callback: function (key, opt) {
+                billsObj.baseOpr('delete');
+            },
+            disabled: function (key, opt) {
+                const sheet = billsObj.sheet;
+                const selection = sheet.getSelections();
+                const sel = selection ? selection[0] : sheet.getSelections()[0];
+                const row = sel ? sel.row : -1;
+                const tree = sheet.zh_tree;
+                if (!tree) return true;
+                const first = sheet.zh_tree.nodes[row];
+                let last = first, sameParent = true, nodeUsed = billsObj.checkNodeUsed(tree, first);
+                if (sel.rowCount > 1 && first) {
+                    for (let r = 1; r < sel.rowCount; r++) {
+                        const rNode = tree.nodes[sel.row + r];
+                        if (!rNode) {
+                            sameParent = false;
+                            break;
+                        }
+                        nodeUsed = nodeUsed || billsObj.checkNodeUsed(tree, rNode);
+                        if (rNode.tree_level > first.tree_level) continue;
+                        if ((rNode.tree_level < first.tree_level) || (rNode.tree_level === first.tree_level && rNode.tree_pid !== first.tree_pid)) {
+                            sameParent = false;
+                            break;
+                        }
+                        last = rNode;
+                    }
+                }
+                const valid = !sheet.zh_setting.readOnly;
+                return !(valid && first && sameParent && !(first.tree_level === 1) && !nodeUsed);
+            }
+        };
+        $('#psb-decimal').on('show.bs.modal', () => {
+            const decimalObjs = [$('#psb-qty'), $('#psb-up'), $('#psb-tp')];
+            for (const obj of decimalObjs) {
+                obj.val(obj.attr('org'));
+            }
+        });
+        $('#psb-decimal-ok').click(() => {
+            const decimal = { qty: parseInt($('#psb-qty').val()), up: parseInt($('#psb-up').val()), tp: parseInt($('#psb-tp').val()) };
+            postData('decimal', { decimal }, function(result) {
+                if (result.calc) {
+                    const refreshNode = billsObj.tree.loadPostData(result);
+                    billsObj.refreshTree(refreshNode);
+                }
+                $('#psb-qty').attr('org', decimal.qty);
+                $('#psb-up').attr('org', decimal.up);
+                $('#psb-tp').attr('org', decimal.tp);
+                $('#psb-decimal').modal('hide');
+            });
+        });
+    }
+
+    const safeBillsFile = $.ledger_att({
+        selector: '#fujian',
+        key: 'id',
+        masterKey: 'rela_id',
+        uploadUrl: 'file/upload',
+        deleteUrl: 'file/delete',
+        checked: false,
+        zipName: `附件.zip`,
+        readOnly: false,
+        fileIdType: 'string',
+        fileInfo: {
+            user_name: 'user_name',
+            user_id: 'user_id',
+            create_time: 'create_time',
+        },
+        getCurHint: function(node) {
+            return`${node.name || ''}`;
+        },
+        locate: function (att) {
+            if (!att) return;
+            SpreadJsObj.locateTreeNode(billsObj.sheet, att.node.tree_id, true);
+            safeBillsFile.getCurAttHtml(att.node);
+        }
+    });
+    // 加载安全生产费数据
+    postData('load', { filter: 'bills;att' }, function(result) {
+        billsObj.loadData(result.bills);
+
+        for (const f of result.att) {
+            f.node = billsObj.tree.datas.find(x => { return x.id === f.rela_id; });
+        }
+        safeBillsFile.loadDatas(result.att);
+        safeBillsFile.getCurAttHtml(SpreadJsObj.getSelectObject(billsObj.sheet));
+    });
+
+    const stdGclSetting = {
+        selector: '#std-gcl',
+        stdType: 'gcl',
+        libs: stdBills,
+        treeSetting: {
+            id: 'bill_id',
+            pid: 'pid',
+            order: 'order',
+            level: 'level',
+            isLeaf: 'is_leaf',
+            fullPath: 'full_path',
+            rootId: -1,
+            keys: ['id', 'list_id', 'bill_id']
+        },
+        spreadSetting: {
+            cols: [
+                {title: '清单编号', field: 'b_code', hAlign: 0, width: 170, formatter: '@', cellType: 'tree'},
+                {title: '名称', field: 'name', hAlign: 0, width: 150, formatter: '@'},
+                {title: '单位', field: 'unit', hAlign: 1, width: 50, formatter: '@'}
+            ],
+            treeCol: 0,
+            emptyRows: 0,
+            headRows: 1,
+            headRowHeight: [32],
+            defaultRowHeight: 21,
+            headerFont: '12px 微软雅黑',
+            font: '12px 微软雅黑',
+            headColWidth: [30],
+            selectedBackColor: '#fffacd',
+            readOnly: true,
+        },
+        page: 'paymentSafe',
+        tid: getTenderId(),
+        cellDoubleClick: function (updateData, stdNode, stdTree) {
+            if (!stdTree || !stdNode || !stdNode.b_code) return;
+
+            const mainSheet = billsObj.sheet;
+            if ( !mainSheet.zh_tree) return;
+            const mainTree = mainSheet.zh_tree;
+            const sel = mainSheet.getSelections()[0];
+
+            const nodes = [stdNode, ...stdTree.getAllParents(stdNode)];
+            nodes.sort((a, b) => { return a.level - b.level; });
+            const stdData = [];
+            let mainChildren = mainTree.children, mainCur, checkNode;
+            for (const sd of nodes) {
+                const field = sd.b_code ? 'b_code' : 'name';
+                checkNode = mainChildren.find(x => { return x[field] === sd[field]; });
+                if (!checkNode) {
+                    stdData.push({ b_code: sd.b_code, name: sd.name, unit: sd.unit });
+                } else {
+                    mainCur = checkNode;
+                    mainChildren = mainCur ? mainCur.children : [];
+                }
+            }
+
+            if (stdData.length > 0) {
+                postData('update', { postType: 'add-std',
+                    postData: {
+                        id: mainCur ? mainCur.tree_id : mainTree.setting.rootId,
+                        stdData
+                    }
+                }, function (result) {
+                    const refreshNode = mainTree.loadPostData(result);
+                    billsObj.refreshTree(refreshNode);
+                    const node = _.find(billsObj.tree.nodes, { b_code: stdNode.b_code, name: stdNode.name });
+                    if (node) {
+                        mainSheet.setSelection(billsObj.tree.nodes.indexOf(node), sel.col, 1, sel.colCount);
+                        SpreadJsObj.reloadRowsBackColor(mainSheet, [sel.row, billsObj.tree.nodes.indexOf(node)]);
+                    }
+                    billsObj.refreshOperationValid();
+                    billsObj.spread.focus();
+                });
+            } else {
+                const node = _.find(billsObj.tree.nodes, { b_code: stdNode.b_code, name: stdNode.name });
+                mainSheet.setSelection(billsObj.tree.nodes.indexOf(node), sel.col, 1, sel.colCount);
+                billsObj.spread.focus();
+            }
+        },
+    };
+
+    // 展开收起标准清单
+    $('a', '#side-menu').bind('click', function (e) {
+        e.preventDefault();
+        const tab = $(this), tabPanel = $(tab.attr('content'));
+        // 展开工具栏、切换标签
+        if (!tab.hasClass('active')) {
+            // const close = $('.active', '#side-menu').length === 0;
+            $('a', '#side-menu').removeClass('active');
+            $('.tab-content .tab-select-show.tab-pane.active').removeClass('active');
+            tab.addClass('active');
+            tabPanel.addClass('active');
+            // $('.tab-content .tab-pane').removeClass('active');
+            showSideTools(tab.hasClass('active'));
+            if (tab.attr('content') === '#std-gcl') {
+                if (!stdGcl) stdGcl = $.stdLib(stdGclSetting);
+                stdGcl.spread.refresh();
+            }
+        } else { // 收起工具栏
+            tab.removeClass('active');
+            tabPanel.removeClass('active');
+            showSideTools(tab.hasClass('active'));
+        }
+        billsObj.spread.refresh();
+    });
+
+    // 工具栏spr
+    $.divResizer({
+        select: '#right-spr',
+        callback: function () {
+            billsObj.spread.refresh();
+            if (stdGcl) stdGcl.spread.refresh();
+        }
+    });
+    // 导航Menu
+    $.subMenu({
+        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',
+        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',
+        key: 'menu.1.0.0',
+        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',
+        callback: function (info) {
+            if (info.mini) {
+                $('.panel-title').addClass('fluid');
+                $('#sub-menu').removeClass('panel-sidebar');
+            } else {
+                $('.panel-title').removeClass('fluid');
+                $('#sub-menu').addClass('panel-sidebar');
+            }
+            autoFlashHeight();
+            billsObj.spread.refresh();
+            if (stdGcl) stdGcl.spread.refresh();
+        }
+    });
+    // 显示层次
+    (function (select, sheet) {
+        $(select).click(function () {
+            if (!sheet.zh_tree) return;
+            const tag = $(this).attr('tag');
+            const tree = sheet.zh_tree;
+            setTimeout(() => {
+                showWaitingView();
+                switch (tag) {
+                    case "1":
+                    case "2":
+                    case "3":
+                    case "4":
+                        tree.expandByLevel(parseInt(tag));
+                        SpreadJsObj.refreshTreeRowVisible(sheet);
+                        break;
+                    case "last":
+                        tree.expandByCustom(() => { return true; });
+                        SpreadJsObj.refreshTreeRowVisible(sheet);
+                        break;
+                }
+                closeWaitingView();
+            }, 100);
+        });
+    })('a[name=showLevel]', billsObj.sheet);
+});

+ 162 - 0
app/public/js/safe_bills_compare.js

@@ -0,0 +1,162 @@
+$(document).ready(function() {
+    autoFlashHeight();
+    class BillsObj {
+        constructor() {
+            this.spread = SpreadJsObj.createNewSpread($('#bills-spread')[0]);
+            this.sheet = this.spread.getActiveSheet();
+            this.treeSetting = {
+                id: 'tree_id',
+                pid: 'tree_pid',
+                order: 'tree_order',
+                level: 'tree_level',
+                isLeaf: 'tree_is_leaf',
+                fullPath: 'tree_full_path',
+                rootId: -1,
+            };
+            this.spreadSetting = {
+                baseCols: [
+                    {title: '编号', colSpan: '1', rowSpan: '2', field: 'b_code', hAlign: 0, width: 230, formatter: '@', cellType: 'tree'},
+                    {title: '名称', colSpan: '1', rowSpan: '2', field: 'name', hAlign: 0, width: 185, formatter: '@'},
+                    {title: '规格', colSpan: '1', rowSpan: '2', field: 'spec', hAlign: 0, width: 150, formatter: '@'},
+                    {title: '单位', colSpan: '1', rowSpan: '2', field: 'unit', hAlign: 1, width: 50, formatter: '@', cellType: 'unit'},
+                    {title: '单价', colSpan: '1', rowSpan: '2', field: 'unit_price', hAlign: 2, width: 80, type: 'Number'},
+                ],
+                extraCols: [
+                    {title: '%s|数量', colSpan: '2|1', rowSpan: '1|1', field: 'qty_{%d}', hAlign: 2, width: 80, type: 'Number', },
+                    {title: '|金额', colSpan: '|1', rowSpan: '|1', field: 'tp_{%d}', hAlign: 2, width: 80, type: 'Number', },
+                ],
+                emptyRows: 3,
+                headRows: 2,
+                headRowHeight: [25, 25],
+                defaultRowHeight: 21,
+                headerFont: '12px 微软雅黑',
+                font: '12px 微软雅黑',
+                readOnly: true,
+            };
+            this.spreadSetting.getColor = function (sheet, data, row, col, defaultColor) {
+                function checkDiffer(data) {
+                    const fieldSufs = sheet.zh_setting.fieldSufs;
+                    if (fieldSufs.length <= 1) return false;
+                    const base = data['qty_' + fieldSufs[0]];
+                    for (let i = 1; i< fieldSufs.length; i++) {
+                        const compare = data['qty_' + fieldSufs[i]];
+                        if ((base || compare) && (compare!== base)) return true;
+                    }
+                }
+                return checkDiffer(data) ? spreadColor.safe.differ : defaultColor;
+            };
+            this.tree = createNewPathTree('ledger', this.treeSetting);
+            this.ckBillsSpread = window.location.pathname + '-billsSelect';
+
+            this.initSpread();
+        }
+        refreshSpreadSetting(roles) {
+            this.spreadSetting.cols = [];
+            this.spreadSetting.fieldSufs = [];
+            for (const col of this.spreadSetting.baseCols) {
+                this.spreadSetting.cols.push(col);
+            }
+            for (const role of roles) {
+                this.spreadSetting.fieldSufs.push(role.order);
+                for (const ec of this.spreadSetting.extraCols) {
+                    const col = JSON.parse(JSON.stringify(ec));
+                    col.title = _.replace(col.title, '%s', role.name);
+                    col.field = _.replace(col.field, '{%d}', role.order);
+                    this.spreadSetting.cols.push(col);
+                }
+            }
+        }
+        initSpread(roles = []) {
+            this.refreshSpreadSetting(roles);
+            SpreadJsObj.initSheet(this.sheet, this.spreadSetting);
+        }
+        analysisCompareData(datas, roles){
+            const findHis = function (role, history) {
+                let his = null;
+                for (const h of history) {
+                    if (h.times < role.times || (h.times === role.times && h.order <= role.order)) {
+                        his = h;
+                    } else {
+                        break;
+                    }
+                }
+                return his;
+            };
+            for (const d of datas) {
+                if (!d.tree_is_leaf) continue;
+                d.cur_his.sort((x, y) => { return x.times === y.times ? x.order - y.order : x.times - y.times; });
+                for (const r of roles) {
+                    if (r.latest) {
+                        d[`qty_${r.order}`] = d.cur_qty;
+                        d[`tp_${r.order}`] = d.cur_tp;
+                    } else {
+                        const rHis = findHis(r, d.cur_his);
+                        if (rHis) {
+                            d[`qty_${r.order}`] = rHis.qty;
+                            d[`tp_${r.order}`] = rHis.tp;
+                        }
+                    }
+                }
+            }
+        }
+        loadData(datas, roles) {
+            this.initSpread(roles);
+            this.analysisCompareData(datas, roles);
+            this.tree.loadDatas(datas);
+            this.tree.setting.calcFields = roles.map(x => { return `tp_${x.order}`});
+            treeCalc.calculateAll(this.tree);
+            SpreadJsObj.loadSheetData(this.sheet, SpreadJsObj.DataType.Tree, this.tree);
+            SpreadJsObj.loadTopAndSelect(this.sheet, this.ckBillsSpread);
+        }
+    }
+    const billsObj = new BillsObj();
+
+    // 加载安全生产费数据
+    postData('load', { filter: 'billsCompare;auditFlow' }, function(result) {
+        billsObj.loadData(result.billsCompare, result.auditFlow);
+    });
+
+    // 导航Menu
+    $.subMenu({
+        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',
+        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',
+        key: 'menu.1.0.0',
+        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',
+        callback: function (info) {
+            if (info.mini) {
+                $('.panel-title').addClass('fluid');
+                $('#sub-menu').removeClass('panel-sidebar');
+            } else {
+                $('.panel-title').removeClass('fluid');
+                $('#sub-menu').addClass('panel-sidebar');
+            }
+            autoFlashHeight();
+            billsObj.spread.refresh();
+        }
+    });
+    // 显示层次
+    (function (select, sheet) {
+        $(select).click(function () {
+            if (!sheet.zh_tree) return;
+            const tag = $(this).attr('tag');
+            const tree = sheet.zh_tree;
+            setTimeout(() => {
+                showWaitingView();
+                switch (tag) {
+                    case "1":
+                    case "2":
+                    case "3":
+                    case "4":
+                        tree.expandByLevel(parseInt(tag));
+                        SpreadJsObj.refreshTreeRowVisible(sheet);
+                        break;
+                    case "last":
+                        tree.expandByCustom(() => { return true; });
+                        SpreadJsObj.refreshTreeRowVisible(sheet);
+                        break;
+                }
+                closeWaitingView();
+            }, 100);
+        });
+    })('a[name=showLevel]', billsObj.sheet);
+});

+ 169 - 0
app/public/js/safe_stage.js

@@ -0,0 +1,169 @@
+'use strict';
+
+$(document).ready(() => {
+    $('#audit-list').on('click', 'a', function() {
+        const type = $(this).data('target')
+        const auditCard = $(this).parent().parent()
+        if (type === 'show') {
+            $(this).data('target', 'hide')
+            auditCard.find('.fold-card').slideDown('swing', () => {
+                auditCard.find('#end-target').text($(this).data('idx') + '#')
+                auditCard.find('#fold-btn').text('收起历史审核记录')
+            })
+        } else {
+            $(this).data('target', 'show')
+            auditCard.find('.fold-card').slideUp('swing', () => {
+                auditCard.find('#end-target').text('1#')
+                auditCard.find('#fold-btn').text('展开历史审核记录')
+            })
+        }
+    });
+
+    const getGroupAuditHtml = function (group) {
+        return group.map(u => { return `<small class="d-inline-block text-dark mx-1" title="${u.role}" data-auditorId="${u.aid}">${u.name}</small>`; }).join('');
+    };
+    const getAuditTypeHtml = function (type) {
+        if (type === auditType.key.common) return '';
+        return `<div class="li-subscript"><span class="badge badge-pill badge-${auditType.info[type].class} p-1 badge-bg-small"><small>${auditType.info[type].short}</small></span></div>`;
+    };
+    const getAuditTypeText = function (type) {
+        if (type === auditType.key.common) return '';
+        return `<span class="text-${auditType.info[type].class}">${auditType.info[type].long}</span>`;
+    };
+    const getAuditorsHtml = function (auditors) {
+        const auditorsHTML = [];
+        auditors.forEach((group, idx) => {
+            if (idx === 0) {
+                auditorsHTML.push(`<li class="list-group-item d-flex justify-content-between align-items-center">
+                    <span class="mr-1"><i class="fa fa fa-play-circle fa-rotate-90"></i></span>
+                <span class="text-muted">${getGroupAuditHtml(group)}</span>
+                <span class="badge badge-light badge-pill ml-auto"><small>原报</small></span>
+                </li>`);
+            } else if(idx === auditors.length -1 && idx !== 0) {
+                auditorsHTML.push(`<li class="list-group-item d-flex justify-content-between align-items-center">
+                    <span class="mr-1"><i class="fa fa fa-stop-circle fa-rotate-90"></i></span>
+                <span class="text-muted">${getGroupAuditHtml(group)}</span>
+                <div class="d-flex ml-auto">
+                ${getAuditTypeHtml(group[0].audit_type)}
+                <span class="badge badge-light badge-pill ml-auto"><small>终审</small></span>
+                </div>
+                </li>`);
+            } else {
+                auditorsHTML.push(`<li class="list-group-item d-flex justify-content-between align-items-center">
+                    <span class="mr-1"><i class="fa fa fa-chevron-circle-down"></i></span>
+                <span class="text-muted">${getGroupAuditHtml(group)}</span>
+                <div class="d-flex ml-auto">
+                ${getAuditTypeHtml(group[0].audit_type)}
+                <span class="badge badge-light badge-pill"><small>${transFormToChinese(idx)}审</small></span>
+                </div>
+                </li>`);
+            }
+        });
+        return auditorsHTML;
+    }
+    const getAuditHistroyHtml = function (auditHistory) {
+        const historyHTML = [];
+        auditHistory.forEach((his, idx) => {
+            if (idx === auditHistory.length - 1 && auditHistory.length !== 1) {
+                historyHTML.push(`<div class="text-right"><a href="javascript: void(0);" id="fold-btn" data-target="show">展开历史审批流程</a></div>`);
+            }
+            historyHTML.push(`<div class="${idx < auditHistory.length - 1 ? 'fold-card' : ''}">`);
+            historyHTML.push(`<div class="text-center text-muted">${idx+1}#</div>`);
+            historyHTML.push(`<ul class="timeline-list list-unstyled mt-2 ${ idx === auditHistory.length - 1 && auditHistory.length !== 1 ? 'last-auditor-list' : '' }">`);
+            his.forEach((group) => {
+                historyHTML.push(`<li class="timeline-list-item pb-2 ${ group.audit_status === auditConst.status.uncheck && idx === auditHistory.length - 1 && auditHistory.length !== 1 ? 'is_uncheck' : ''}">`);
+                if (group.auditYear) {
+                    historyHTML.push(`<div class="timeline-item-date">${group.auditYear}<span>${group.auditDate}</span><span>${group.auditTime}</span></div>`);
+                }
+                if (group.audit_order < his.length - 1) {
+                    historyHTML.push('<div class="timeline-item-tail"></div>');
+                }
+                if (group.audit_status === auditConst.status.checked) {
+                    historyHTML.push('<div class="timeline-item-icon bg-success text-light"><i class="fa fa-check"></i></div>');
+                } else if (group.audit_status === auditConst.status.checkNo || group.audit_status === auditConst.status.checkNoPre || group.status === auditConst.status.checkCancel) {
+                    historyHTML.push('<div class="timeline-item-icon bg-warning text-light"><i class="fa fa-level-up"></i></div>');
+                } else if (group.audit_status === auditConst.status.checking) {
+                    historyHTML.push('<div class="timeline-item-icon bg-warning text-light"><i class="fa fa-ellipsis-h"></i></div>');
+                } else {
+                    historyHTML.push('<div class="timeline-item-icon bg-secondary text-light"></div>');
+                }
+
+                historyHTML.push('<div class="timeline-item-content">');
+                if (group.audit_order > 0) {
+                    const statuStr = group.audit_status !== auditConst.status.uncheck ?
+                        `<span class="pull-right ${auditConst.info[group.audit_status].class}">${auditConst.info[group.audit_status].title}</span>` : '';
+                    historyHTML.push(`<div class="py-1">
+                        <span class="text-black-50">
+                        ${ !group.is_final ? group.audit_order + '' : '终' }审 ${getAuditTypeText(group.audit_type)}
+                        </span>
+                        ${statuStr}
+                    </div>`);
+                } else {
+                    historyHTML.push(` <div class="py-1">
+                        <span class="text-black-50">原报</span>
+                        <span class="pull-right text-success">${idx !== 0 ? '重新' : '' }上报审批</span>
+                    </div>`);
+                }
+                historyHTML.push('<div class="card"><div class="card-body px-3 py-0">');
+                for (const [i, auditor] of group.auditors.entries()) {
+                    historyHTML.push(`<div class="card-text p-2 py-3 row ${ ( i > 0 ? 'border-top' : '') }">`);
+                    let companyRolePart = '';
+                    if (group.audit_order !== 0) {
+                        const rolePart = auditor.role ? ' - ' + auditor.role : '';
+                        companyRolePart = `<span class="text-muted ml-1">${auditor.company}${rolePart}</span>`;
+                    }
+
+                    historyHTML.push(`<div class="col-10"><span class="h6">${auditor.name}</span>${companyRolePart}</div>`);
+                    historyHTML.push('<div class="col">');
+                    if (auditor.audit_status === auditConst.status.checked) {
+                        historyHTML.push('<span class="pull-right text-success"><i class="fa fa-check-circle"></i></span>');
+                    } if (auditor.audit_status === auditConst.status.checkNo || auditor.audit_status === auditConst.status.checkNoPre || auditor.audit_status === auditConst.status.checkCancel) {
+                        historyHTML.push('<span class="pull-right text-warning"><i class="fa fa-share-square fa-rotate-270"></i></span>');
+                    }
+                    historyHTML.push('</div>');
+                    if (group.audit_order > 0 && auditor.opinion) {
+                        historyHTML.push(`<div class="col-12 py-1 bg-light"><i class="fa fa-commenting-o mr-1"></i>${auditor.opinion}</div>`);
+                    }
+                    historyHTML.push('</div>');
+                }
+                historyHTML.push('</div></div>');
+                historyHTML.push('</div>');
+                historyHTML.push('</li>');
+            });
+            historyHTML.push('</div>');
+            historyHTML.push('</ul>');
+        });
+        return historyHTML.join('');
+    }
+    // 获取审批流程
+    $('a[data-target="#sp-list" ]').on('click', function () {
+        postData('stage/auditors', { order: $(this).attr('stage-order') }, function (result) {
+            $('#auditor-list').html(getAuditorsHtml(result.hisUserGroup));
+            $('#audit-list').html(getAuditHistroyHtml(result.auditHistory));
+        });
+    });
+
+    $.subMenu({
+        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',
+        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',
+        key: 'menu.1.0.0',
+        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',
+        callback: function (info) {
+            if (info.mini) {
+                $('.panel-title').addClass('fluid');
+                $('#sub-menu').removeClass('panel-sidebar');
+            } else {
+                $('.panel-title').removeClass('fluid');
+                $('#sub-menu').addClass('panel-sidebar');
+            }
+            autoFlashHeight();
+        }
+    });
+
+    $('select[name=stage]').select2({
+        language: 'zh-CN',
+        width: '100%',
+        multiple: true,
+        maximumSelectionlength: 6,
+    });
+});

+ 1 - 1
app/public/js/safe_tender.js

@@ -13,7 +13,7 @@ const tenderListSpec = (function(){
             html.push(arr.indexOf(node) === arr.length - 1 ? '└' : '├');
             html.push('</span>');
             //html.push('<a href="/tender/' + node.id + '">', node[c.field], '</a>');
-            html.push(`<a href="/sp/${spid}/safe/tender/${node.id}/${isInspection ? 'inspection' : 'info'}" name="name" style="min-width: 200px;word-break:break-all;" id="${node.id}">${node.name}</a>`);
+            html.push(`<a href="/sp/${spid}/safe/tender/${node.id}/${isInspection ? 'inspection' : 'stage'}" name="name" style="min-width: 200px;word-break:break-all;" id="${node.id}">${node.name}</a>`);
         }
         html.push('</td>');
 

+ 452 - 0
app/public/js/shares/common_audit.js

@@ -0,0 +1,452 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Mai
+ * @date 2019/2/27
+ * @version
+ */
+
+// 检查上报情况
+function checkAuditorFrom () {
+    if ($('#auditors li').length === 0) {
+        if(shenpi_status === shenpiConst.sp_status.gdspl) {
+            toastr.error('请联系管理员添加审批人');
+        } else {
+            toastr.error('请先选择审批人,再上报数据');
+        }
+        return false;
+    }
+    $('#hide-all').show();
+    return true;
+}
+// 点击验证码
+function codeSuccess(btn) {
+    let counter = 60;
+    btn.addClass('disabled').text('重新获取 ' + counter + 'S');
+    btn.parent().siblings('input').removeAttr('readonly').attr('placeholder', '输入短信中的6位验证码');
+    const bindBtn = $("#bind-btn");
+    bindBtn.removeClass('btn-secondary disabled').addClass('btn-primary');
+
+    const countDown = setInterval(function() {
+        const countString = counter - 1 <= 0 ? '' : ' ' + (counter - 1) + 'S';
+        // 倒数结束后
+        if (countString === '') {
+            clearInterval(countDown);
+            btn.removeClass('disabled');
+        }
+        const text = '重新获取' + countString;
+        btn.text(text);
+        counter -= 1;
+    }, 1000);
+}
+
+$(document).ready(function () {
+    let timer = null;
+    let oldSearchVal = null;
+
+    // 搜索审批人
+    $('#gr-search').bind('input propertychange', function(e) {
+        oldSearchVal = e.target.value;
+        timer && clearTimeout(timer);
+        timer = setTimeout(() => {
+            const newVal = $('#gr-search').val();
+            let html = '';
+            if (newVal && newVal === oldSearchVal) {
+                accountList.filter(item => item && createUserId !== item.id && (item.name.indexOf(newVal) !== -1 || (item.mobile && item.mobile.indexOf(newVal) !== -1))).forEach(item => {
+                    html += `<dd class="border-bottom p-2 mb-0" data-id="${item.id}">
+                        <p class="mb-0 d-flex"><span class="text-primary">${item.name}</span><spanclass="ml-auto">${item.mobile || ''}</span></p>
+                        <span class="text-muted">${item.role || ''}</span>
+                    </dd>`;
+                });
+                $('.book-list').empty();
+                $('.book-list').append(html);
+            } else {
+                if (!$('.acc-btn').length) {
+                    accountGroup.forEach((group, idx) => {
+                        if (!group) return;
+                        html += `<dt><a href="javascript: void(0);" class="acc-btn" data-groupid="${idx}" data-type="hide"><i class="fa fa-plus-square"></i></a> ${group.groupName}</dt><div class="dd-content" data-toggleid="${idx}">`;
+                        group.groupList.forEach(item => {
+                            if (item.id !== createUserId) {
+                                html += `<dd class="border-bottom p-2 mb-0" data-id="${item.id}">
+                                    <p class="mb-0 d-flex"><span class="text-primary">${item.name}</span><span class="ml-auto">${item.mobile || ''}</span></p>
+                                    <span class="text-muted">${item.role || ''}</span>
+                                </dd>`;
+                            }
+                        });
+                        html += '</div>';
+                    });
+                    $('.book-list').empty();
+                    $('.book-list').append(html);
+                }
+            }
+        }, 400);
+    });
+
+    // 添加审批流程按钮逻辑
+    $('body').on('click', '.book-list dt', function () {
+        const idx = $(this).find('.acc-btn').attr('data-groupid');
+        const type = $(this).find('.acc-btn').attr('data-type');
+        if (type === 'hide') {
+            $(this).parent().find(`div[data-toggleid="${idx}"]`).show(() => {
+                $(this).children().find('i').removeClass('fa-plus-square').addClass('fa-minus-square-o');
+                $(this).find('.acc-btn').attr('data-type', 'show');
+
+            })
+        } else {
+            $(this).parent().find(`div[data-toggleid="${idx}"]`).hide(() => {
+                $(this).children().find('i').removeClass('fa-minus-square-o').addClass('fa-plus-square');
+                $(this).find('.acc-btn').attr('data-type', 'hide');
+            })
+        }
+        return false
+    });
+
+    // 添加到审批流程
+    $('#book-list').on('click', 'dd', function () {
+        const id = parseInt($(this).data('id'));
+        if (!id) return;
+
+        postData('audit/add', { auditorId: id }, (datas) => {
+            const html = [];
+            // 如果是重新上报,添加到重新上报列表中
+            const auditorshtml = [];
+            for (const [index, data] of datas.entries()) {
+                if (index !== 0) {
+                    html.push('<li class="list-group-item d-flex" auditorId="'+ data[0].audit_id +'">');
+                    html.push(`<div class="col-auto">${index}</div>`);
+                    html.push('<div class="col">');
+                    for (const auditor of data) {
+                        html.push(`<div class="d-inline-block mx-1"><i class="fa fa-user text-muted"></i> ${auditor.name} <small class="text-muted">${auditor.role}</small></div>`);
+                    }
+                    html.push('</div>');
+                    html.push('<div class="col-auto">');
+                    if (data[0].audit_type !== auditType.key.common)
+                        html.push(`<span class="badge badge-pill badge-${auditType.info[data[0].audit_type].class} p-1"><small>${auditType.info[data[0].audit_type].long}</small></span>`);
+                    if (shenpi_status === shenpiConst.sp_status.sqspr || (shenpi_status === shenpiConst.sp_status.gdzs && index+1 !== datas.length)) {
+                        html.push('<a href="javascript: void(0)" class="text-danger pull-right">移除</a>');
+                    }
+                    html.push('</div>');
+                    html.push('</li>');
+                }
+                auditorshtml.push('<li class="list-group-item" data-auditorid="' + data.audit_id + '">');
+                auditorshtml.push('<i class="fa ' + (index+1 === datas.length ? 'fa-stop-circle' : 'fa-chevron-circle-down') + '"></i> ');
+                auditorshtml.push(data.name + ' <small class="text-muted">' + data.role + '</small>');
+                if (index === 0) {
+                    auditorshtml.push('<span class="pull-right">原报</span>');
+                } else if (index+1 === datas.length) {
+                    auditorshtml.push('<span class="pull-right">终审</span>');
+                } else {
+                    auditorshtml.push('<span class="pull-right">'+ transFormToChinese(index) +'审</span>');
+                }
+                auditorshtml.push('</li>');
+            }
+            $('#auditors').html(html.join(''));
+            $('#auditors-list').html(auditorshtml.join(''));
+        });
+    });
+    // 删除审批人
+    $('body').on('click', '#auditors li a', function () {
+        const li = $(this).parents('li');
+        const data = {
+            auditorId: parseInt(li.attr('auditorId')),
+        };
+        postData('audit/delete', data, (result) => {
+            li.remove();
+            for (const rst of result) {
+                const aLi = $('li[auditorId=' + rst.audit_id + ']');
+                $('div:first', aLi).text(rst.order);
+            }
+
+            // 如果是重新上报
+            // 令最后一个图标转换
+            $('#auditors-list li[data-auditorid="' + data.auditorId + '"]').remove();
+            if ($('#auditors-list li').length !== 0 && !$('#auditors-list li i').hasClass('fa-stop-circle')) {
+                $('#auditors-list li').eq($('#auditors-list li').length-1).children('i')
+                    .removeClass('fa-chevron-circle-down').addClass('fa-stop-circle');
+            }
+            for (let i = 0; i < $('#auditors-list li').length; i++) {
+                $('#auditors-list li').eq(i).find('.pull-right').text(i === 0 ? '原报' : (i+1 === $('#auditors-list li').length ? '终' : transFormToChinese(i)) + '审');
+                // $('#auditors-list2 li').eq(i).find('.pull-right').text((i+1 === $('#auditors-list2 li').length ? '终' : transFormToChinese(i+1)) + '审');
+            }
+        });
+    });
+    // 退回选择修改审批人流程
+    $('#hideSp').click(function () {
+        $('#sp-list').modal('hide');
+    });
+    $('a[f-target]').click(function () {
+        $($(this).attr('f-target')).modal('show');
+    });
+
+    // 多层modal关闭后的滚动bug修复
+    $('#sp-list').on('hidden.bs.modal', function (e) {
+        $(document.body).addClass('modal-open');
+    });
+
+    // 重新审批获取手机验证码
+    // 获取验证码
+    let isPosting = false;
+    $("#get-code").click(function() {
+        if (isPosting) return false;
+
+        const btn = $(this);
+        $.ajax({
+            url: '/profile/code',
+            type: 'post',
+            data: { mobile: authMobile, type: 'shenpi' },
+            dataTye: 'json',
+            error: function() {
+                isPosting = false;
+                let csrfToken = Cookies.get('csrfToken_j');
+                xhr.setRequestHeader('x-csrf-token', csrfToken);
+            },
+            beforeSend: function() {
+                isPosting = true;
+            },
+            success: function(response) {
+                isPosting = false;
+                if (response.err === 0) {
+                    codeSuccess(btn);
+                    $("input[name='code']").removeAttr('readonly');
+                    $("#re-shenpi-btn").removeAttr('disabled');
+                } else {
+                    toast(response.msg, 'error');
+                }
+            }
+        });
+    });
+
+    // 管理员更改审批流程js部分
+    let timer2 = null;
+    let oldSearchVal2 = null;
+    $('body').on('input propertychange', '.gr-search', function(e) {
+        oldSearchVal2 = e.target.value;
+        timer2 && clearTimeout(timer2);
+        timer2 = setTimeout(() => {
+            const newVal = $(this).val();
+            const code = $(this).attr('data-code');
+            let html = '';
+            if (newVal && newVal === oldSearchVal2) {
+                accountList.filter(item => item && item.id !== createUserId && (item.name.indexOf(newVal) !== -1 || (item.mobile && item.mobile.indexOf(newVal) !== -1))).forEach(item => {
+                    html += `<dd class="border-bottom p-2 mb-0 " data-id="${item.id}" >
+                        <p class="mb-0 d-flex"><span class="text-primary">${item.name}</span><span
+                                class="ml-auto">${item.mobile || ''}</span></p>
+                        <span class="text-muted">${item.role || ''}</span>
+                    </dd>`
+                });
+                $('#' + code + '_dropdownMenu .book-list').empty();
+                $('#' + code + '_dropdownMenu .book-list').append(html);
+            } else {
+                if (!$('#' + code + '_dropdownMenu .acc-btn').length) {
+                    accountGroup.forEach((group, idx) => {
+                        if (!group) return;
+                        html += `<dt><a href="javascript: void(0);" class="acc-btn" data-groupid="${idx}" data-type="hide"><i class="fa fa-plus-square"></i>
+                        </a> ${group.groupName}</dt>
+                        <div class="dd-content" data-toggleid="${idx}">`;
+                        group.groupList.forEach(item => {
+                            if (item.id !== createUserId) {
+                                html += `<dd class="border-bottom p-2 mb-0 " data-id="${item.id}" >
+                                    <p class="mb-0 d-flex"><span class="text-primary">${item.name}</span><span
+                                            class="ml-auto">${item.mobile || ''}</span></p>
+                                    <span class="text-muted">${item.role || ''}</span>
+                                </dd>`;
+                            }
+                        });
+                        html += '</div>';
+                    });
+                    $('#' + code + '_dropdownMenu .book-list').empty();
+                    $('#' + code + '_dropdownMenu .book-list').append(html);
+                }
+            }
+        }, 400);
+    });
+
+    const getAdminEditShenpiListHtml = function(auditGroup) {
+        const html = [];
+        for (const [i, group] of auditGroup.entries()) {
+            if (i === 0) continue;
+            for (const [j, auditor] of group.entries()) {
+                html.push('<tr>');
+                if (j === 0) {
+                    const auditTypeHtml = auditor.type === auditType.key.common ? '' : `<span class="ml-2 badge badge-pill badge-${auditType.info[auditor.audit_type].class} p-1"><small>${auditType.info[auditor.audit_type].short}</small></span>`;
+                    html.push(`<td class="text-left d-flex">${i + '审'}${auditTypeHtml}</td>`);
+                } else {
+                    html.push(`<td class="text-left d-flex"></td>`);
+                }
+                html.push(`<td></span> ${auditor.name} <small class="text-muted">${auditor.role}</small></td>`);
+                html.push(`<td style="text-align: center"><span class="${auditConst.auditStringClass[auditor.audit_status]}">${ auditor.audit_status !== auditConst.status.uncheck ? auditConst.auditString[auditor.audit_status] : '待审批' }</span></td>`);
+                html.push('<td style="text-align: center">');
+                if (auditor.audit_status === auditConst.status.checking && j === group.length - 1) {
+                    html.push('<span class="dropdown mr-2">',
+                        `<a href="javascript: void(0)" class="add-audit" id="${auditor.audit_id}_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">增加</a>`,
+                        makeSelectAudit(auditor.audit_id+'_add', auditor.audit_id, 'add'),'</div>', '</span>');
+                }
+                if (auditor.audit_status === auditConst.status.uncheck) {
+                    if (j === group.length - 1) {
+                        html.push('<span class="dropdown mr-2">',
+                            `<a href="javascript: void(0)" class="add-audit" id="${auditor.audit_id}_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">增加</a>`,
+                            makeSelectAudit(auditor.audit_id+'_add', auditor.audit_id, 'add'),'</div>', '</span>');
+                        if (auditor.audit_type !== auditType.key.common) {
+                            html.push('<span class="dropdown mr-2">',
+                                `<a href="javascript: void(0)" class="add-audit" id="${auditor.audit_id}_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">平级</a>`,
+                                makeSelectAudit(auditor.audit_id+'_add-sibling', auditor.audit_id, 'add-sibling'),'</div>', '</span>');
+                        }
+                    }
+                    html.push('<span class="dropdown mr-2">',
+                        `<a href="javascript: void(0)" class="add-audit" id="${auditor.audit_id}_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">更换</a>`,
+                        makeSelectAudit(auditor.audit_id+'_change', auditor.audit_id, 'change'),'</div>', '</span>');
+                    html.push(`<span class="dropdown">
+                                    <a href="javascript: void(0)" class="text-danger" title="移除" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">移除</a>
+                                    <div class="dropdown-menu">
+                                        <span class="dropdown-item" href="javascript:void(0);">确认移除审批人?</span>
+                                        <div class="dropdown-divider"></div>
+                                        <div class="px-2 py-1 text-center">
+                                            <button class="remove-audit btn btn-sm btn-danger" data-id="${auditor.audit_id}">移除</button>
+                                            <button class="btn btn-sm btn-secondary">取消</button>
+                                        </div>
+                                    </div>
+                                    </span>`);
+                }
+                html.push('</td>');
+                html.push('</tr>');
+            }
+        }
+        return html.join('');
+    };
+
+    $('body').on('click', '#admin-edit-shenpi dl dd', function () {
+        const id = parseInt($(this).attr('data-id'));
+        if (!id) return;
+
+        let this_aid = parseInt($(this).parents('.book-list').attr('data-aid'));
+        let this_operate = $(this).parents('.book-list').attr('data-operate');
+        const user = _.find(accountList, function (item) {
+            return item.id === id;
+        });
+        const auditorIndex = _.findIndex(auditorList, { audit_id: id });
+        if (auditorIndex !== -1) {
+            toastr.warning('该审核人已存在,请勿重复添加');
+            return;
+        }
+        const prop = {
+            operate: this_operate,
+            old_aid: this_aid,
+            new_aid: user.id,
+        };
+        postData('audit/save', prop, (datas) => {
+            $('#admin-edit-shenpi-list').html(getAdminEditShenpiListHtml(datas));
+            changeLiucheng(datas);
+        });
+    });
+
+    // 管理员移除审批人
+    $('body').on('click', '.remove-audit', function () {
+        const id = parseInt($(this).attr('data-id'));
+        const prop = {
+            operate: 'del',
+            old_aid: id,
+        };
+        postData('audit/save', prop, (datas) => {
+            $('#admin-edit-shenpi-list').html(getAdminEditShenpiListHtml(datas));
+            changeLiucheng(datas);
+        });
+    });
+
+    const getAuditTypeText = function (type) {
+        if (type === auditType.key.common) return '';
+        return `<span class="text-${auditType.info[type].class}">${auditType.info[type].long}</span>`;
+    };
+
+    function changeLiucheng(datas) {
+        const auditorshtml = [];
+        let lastAuditorHtml = [];
+        for (const [index,data] of datas.entries()) {
+            auditorshtml.push('<li class="list-group-item d-flex justify-content-between align-items-center">');
+            if (index === 0) {
+                auditorshtml.push('<span class="mr-1"><i class="fa fa fa-play-circle fa-rotate-90"></i></span>');
+            } else if (index+1 === datas.length) {
+                auditorshtml.push('<span class="mr-1"><i class="fa fa fa-stop-circle"></i></span>');
+            } else {
+                auditorshtml.push('<span class="mr-1"><i class="fa fa-chevron-circle-down"></i></span>');
+            }
+            auditorshtml.push('<span class="text-muted">');
+            for (const u of data) {
+                auditorshtml.push(`<small class="d-inline-block text-dark mx-1" title="${u.role}" data-auditorId="${u.audit_id}">${u.name}</small>`);
+            }
+            auditorshtml.push('</span>');
+            auditorshtml.push('<div class="d-flex ml-auto">');
+            if (data[0].audit_type !== auditType.key.common) auditorshtml.push(`<span class="badge badge-pill badge-${auditType.info[data[0].audit_type].class} p-1"><small>${auditType.info[data[0].audit_type].short}</small></span>`);
+            if (index === 0) {
+                auditorshtml.push('<span class="badge badge-light badge-pill ml-auto"><small>原报</small></span>');
+            } else if (index+1 === datas.length) {
+                auditorshtml.push('<span class="badge badge-light badge-pill"><small>终审</small></span>');
+            } else {
+                auditorshtml.push('<span class="badge badge-light badge-pill"><small>'+ transFormToChinese(index) +'审</small></span>');
+            }
+            auditorshtml.push('</div>');
+            auditorshtml.push('</li>');
+            if (data[0].audit_status === sam_auditConst.status.uncheck) {
+                lastAuditorHtml.push('<li class="timeline-list-item pb-2 is_uncheck">');
+                if (index < datas.length - 1) {
+                    lastAuditorHtml.push('<div class="timeline-item-tail"></div>');
+                }
+                lastAuditorHtml.push('<div class="timeline-item-icon bg-secondary text-light"></div>');
+
+                lastAuditorHtml.push('<div class="timeline-item-content">');
+                lastAuditorHtml.push(`<div class="py-1">
+                        <span class="text-black-50">
+                        ${ !index === datas.length - 1 ? data[0].audit_order + '' : '终' }审 ${getAuditTypeText(data[0].audit_type)}
+                        </span>
+                    </div>`);
+                lastAuditorHtml.push('<div class="card"><div class="card-body px-3 py-0">');
+                for (const [i, auditor] of data.entries()) {
+                    lastAuditorHtml.push(`<div class="card-text p-2 py-3 row ${ ( i > 0 ? 'border-top' : '') }">`);
+                    lastAuditorHtml.push(`<div class="col"><span class="h6">${auditor.name}</span><span class="text-muted ml-1">${auditor.role}</span></div>`);
+                    lastAuditorHtml.push('<div class="col">');
+                    lastAuditorHtml.push('</div>');
+                    lastAuditorHtml.push('</div>');
+                }
+                lastAuditorHtml.push('</div></div>');
+                lastAuditorHtml.push('</div>');
+                lastAuditorHtml.push('</li>');
+            }
+        }
+        $('.last-auditor-list .is_uncheck').remove();
+        $('.last-auditor-list').append(lastAuditorHtml.join(''));
+        $('.auditors-list').html(auditorshtml.join(''));
+
+    }
+
+    // 审批流程-选择审批人html 生成
+    function makeSelectAudit(code, aid, status) {
+        let divhtml = '';
+        accountGroup.forEach((group, idx) => {
+            let didivhtml = '';
+            if(group) {
+                group.groupList.forEach(item => {
+                    didivhtml += item.id !== createUserId ? '<dd class="border-bottom p-2 mb-0 " data-id="' + item.id + '" >\n' +
+                        '<p class="mb-0 d-flex"><span class="text-primary">' + item.name + '</span><span\n' +
+                        '                                                                                class="ml-auto">' + item.mobile + '</span></p>\n' +
+                        '                                                                    <span class="text-muted">' + item.role + '</span>\n' +
+                        '                                                                    </dd>\n' : '';
+                });
+                divhtml += '<dt><a href="javascript: void(0);" class="acc-btn" data-groupid="' + idx + '" data-type="hide"><i class="fa fa-plus-square"></i></a> ' + group.groupName + '</dt>\n' +
+                    '                                                                <div class="dd-content" data-toggleid="' + idx + '">\n' + didivhtml +
+                    '                                                                </div>\n';
+            }
+        });
+        let html = '<div class="dropdown-menu dropdown-menu-right" id="' + code + '_dropdownMenu" aria-labelledby="' + code + '_dropdownMenuButton" style="width:220px">\n' +
+            '                                                        <div class="mb-2 p-2"><input class="form-control form-control-sm gr-search"\n' +
+            '                                                                                     placeholder="姓名/手机 检索" autocomplete="off" data-code="' + code + '"></div>\n' +
+            '                                                        <dl class="list-unstyled book-list" data-aid="'+ aid +'" data-operate="'+ status +'">\n' + divhtml +
+            '                                                        </dl>\n' +
+            '                                                    </div>\n' +
+            '                                                </div>\n' +
+            '                                            </span>\n' +
+            '                                        </span>\n' +
+            '                                        </li>';
+        return html;
+    }
+});

+ 10 - 1
app/public/js/shares/sjs_setting.js

@@ -173,9 +173,18 @@ const sjsSettingObj = (function () {
             col.getHeaderTip = function() { return '可用单位:总额、元、台、个、处、月 、棵、套、组、辆、项、座、根、块、系统'; };
         });
     };
+    const setFromCol = function(cols, rela) {
+        setRelaCols(cols, rela, function(col, r) {
+            col.getValue = function(data) {
+                if (data.crid) return '修订';
+                if (data.ccid) return '变更';
+                return '';
+            }
+        });
+    };
     return {
         setFxTreeStyle, FxTreeStyle, setGridSelectStyle,
         setTpThousandthFormat, setThousandthFormat, setTpColsThousandthFormat,
-        setPropValue, set3FCols, setQcCols, setOrgPriceCol, setNodeTypeCol, setIsTpCol,
+        setPropValue, set3FCols, setQcCols, setOrgPriceCol, setNodeTypeCol, setIsTpCol, setFromCol,
     };
 })();

+ 1 - 4
app/public/js/stage.js

@@ -310,7 +310,7 @@ $(document).ready(() => {
     stageTreeSetting.updateFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty', 'postil', 'used', 'contract_expr', 'ex_stage_qty1', 'ex_stage_tp1'];
     stageTreeSetting.calcFields = ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp', 'contract_pc_tp', 'qc_pc_tp', 'pc_tp',
         'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp', 'end_contract_tp', 'end_qc_tp', 'end_gather_tp', 'end_correct_tp',
-        'final_1_tp', 'end_final_1_tp', 'due_qc_tp', 'due_final_tp', 'ex_tp1', 'ex_stage_tp1', 'end_ex_stage_tp1', 'tz2_tp', 'tz_qc_tp', 'tz_qc_minus_tp'];
+        'final_1_tp', 'end_final_1_tp', 'ex_tp1', 'ex_stage_tp1', 'end_ex_stage_tp1', 'tz2_tp', 'tz_qc_tp', 'tz_qc_minus_tp'];
     stageTreeSetting.calcFun = function (node) {
         if (!node.children || node.children.length === 0) {
             node.pre_gather_qty = ZhCalc.add(node.pre_contract_qty, node.pre_qc_qty);
@@ -323,7 +323,6 @@ $(document).ready(() => {
             node.final_1_tp = ZhCalc.mul(node.final_1_qty, node.unit_price, tenderInfo.decimal.tp);
             node.deal_final_1_qty = ZhCalc.add(node.end_qc_minus_qty, node.deal_qty);
             node.end_final_1_qty = ZhCalc.add(node.end_qc_qty, node.final_1_qty);
-            node.due_final_qty = ZhCalc.add(node.quantity, node.due_qc_qty);
             node.end_ex_stage_qty1 = ZhCalc.add(node.ex_stage_qty1, node.pre_ex_stage_qty1);
             node.tz2_qty = ZhCalc.sum([node.quantity, node.tz_qc_qty, node.tz_qc_minus_qty]);
         }
@@ -334,7 +333,6 @@ $(document).ready(() => {
         node.end_gather_tp = ZhCalc.add(node.pre_gather_tp, node.gather_tp);
         node.end_final_tp = ZhCalc.add(node.end_qc_tp, node.total_price);
         node.end_final_1_tp = ZhCalc.add(node.end_qc_tp, node.final_1_tp);
-        node.due_final_tp = ZhCalc.add(node.total_price, node.due_qc_tp);
         node.end_ex_stage_tp1 = ZhCalc.add(node.ex_stage_tp1, node.pre_ex_stage_tp1);
         if (!node.children || node.children.length === 0) {
             if (node.end_contract_qty) {
@@ -382,7 +380,6 @@ $(document).ready(() => {
         pos.deal_final_1_qty = ZhCalc.add(pos.end_qc_minus_qty, pos.deal_qty);
         pos.end_final_1_qty = ZhCalc.add(pos.end_qc_qty, pos.final_1_qty);
         pos.end_ex_stage_qty1 = ZhCalc.add(pos.pre_ex_stage_qty1, pos.ex_stage_qty1);
-        pos.due_final_qty = ZhCalc.add(pos.quantity, pos.due_qc_qty);
         pos.tz2_qty = ZhCalc.sum([pos.quantity, pos.tz_qc_qty, pos.tz_qc_minus_qty]);
     };
     const stagePos = new StagePosData(stagePosSetting);

+ 19 - 0
app/router.js

@@ -63,6 +63,7 @@ module.exports = app => {
     const qualityInspectionCheck = app.middlewares.qualityInspectionCheck();
     // 安全巡检中间件
     const safeInspectionCheck = app.middlewares.safeInspectionCheck();
+    const safeStageCheck = app.middlewares.safeStageCheck();
     // 登入登出相关
     app.get('/login', 'loginController.index');
     app.get('/login/:code', 'loginController.index');
@@ -506,6 +507,24 @@ module.exports = app => {
     // 安全管理
     // 安全计量
     app.get('/sp/:id/safe', sessionAuth, subProjectCheck, 'safeController.tender');
+    app.get('/sp/:id/safe/tender/:tid/stage', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'safeController.stage');
+    app.post('/sp/:id/safe/tender/:tid/stage/add', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'safeController.addStage');
+    app.post('/sp/:id/safe/tender/:tid/stage/delete', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'safeController.delStage');
+    app.post('/sp/:id/safe/tender/:tid/stage/save', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'safeController.saveStage');
+    app.post('/sp/:id/safe/tender/:tid/stage/auditors', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'payController.loadAuditors');
+    app.get('/sp/:id/safe/tender/:tid/stage/:sorder/bills', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.safeBills');
+    app.get('/sp/:id/safe/tender/:tid/stage/:sorder/compare', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.safeCompare');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/load', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.safeLoad');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/update', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.safeUpdate');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/decimal', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.safeDecimal');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/file/upload', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.uploadStageFile');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/file/delete', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.deleteStageFile');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/add', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.addStageAudit');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/delete', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.deleteStageAudit');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/start', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.stageAuditStart');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/check', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.stageAuditCheck');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/checkAgain', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.stageAuditCheckAgain');
+    app.post('/sp/:id/safe/tender/:tid/stage/:sorder/audit/checkCancel', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, safeStageCheck, 'safeController.stageAuditCheckCancel');
     // 安全巡检
     app.get('/sp/:id/safe/inspection', sessionAuth, subProjectCheck, 'safeController.inspectionTender');
     app.get('/sp/:id/safe/tender/:tid/inspection', sessionAuth, subProjectCheck, tenderCheck, tenderPermissionCheck, 'safeController.inspection');

+ 6 - 6
app/service/rpt_gather_memory.js

@@ -611,10 +611,10 @@ module.exports = app => {
             });
             const billsData = await this.ctx.service.ledger.getData(tender.id);
             const dgnData = await this.ctx.service.stageBillsDgn.getDgnData(tender.id);
-            const changeBillsData = await this.ctx.service.changeAuditList.getBillsSum(tender.id);
+            // const changeBillsData = await this.ctx.service.changeAuditList.getBillsSum(tender.id);
             this.ctx.helper.assignRelaData(billsData, [
                 { data: dgnData, fields: ['deal_dgn_qty1', 'deal_dgn_qty2', 'c_dgn_qty1', 'c_dgn_qty2'], prefix: '', relaId: 'id' },
-                { data: changeBillsData, fields: ['qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'due_', relaId: 'gcl_id' },
+                // { data: changeBillsData, fields: ['qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'due_', relaId: 'gcl_id' },
             ]);
             const pos = new Ledger.pos({
                 id: 'id', ledgerId: 'lid',
@@ -628,10 +628,10 @@ module.exports = app => {
                 },
             });
             const posData = await this.ctx.service.pos.getPosData({ tid: tender.id });
-            const changePosData = await this.ctx.service.changeAuditList.getPosSum(tender.id);
-            this.ctx.helper.assignRelaData(posData, [
-                { data: changePosData, fields: ['qc_qty', 'qc_minus_qty'], prefix: 'due_', relaId: 'mx_id' },
-            ]);
+            // const changePosData = await this.ctx.service.changeAuditList.getPosSum(tender.id);
+            // this.ctx.helper.assignRelaData(posData, [
+            //     { data: changePosData, fields: ['qc_qty', 'qc_minus_qty'], prefix: 'due_', relaId: 'mx_id' },
+            // ]);
             if (stage) {
                 await this.ctx.service.stage.doCheckStage(stage);
                 const curStage = stage.readOnly

+ 290 - 0
app/service/safe_stage.js

@@ -0,0 +1,290 @@
+'use strict';
+
+/**
+ *
+ *
+ * @author Mai
+ * @date
+ * @version
+ */
+
+const audit = require('../const/audit').common;
+const shenpiConst = require('../const/shenpi');
+
+module.exports = app => {
+    class SafeStage extends app.BaseService {
+
+        /**
+         * 构造函数
+         *
+         * @param {Object} ctx - egg全局变量
+         * @return {void}
+         */
+        constructor(ctx) {
+            super(ctx);
+            this.tableName = 'safe_stage';
+        }
+
+        calculateStage(data) {
+            const helper = this.ctx.helper;
+            const datas = data instanceof Array ? data : [data];
+            const formatNum = this.ctx.tender.info.display.thousandth ? this.ctx.helper.formatNum : function(num) { return num ? num + '' : ''; };
+            datas.forEach(x => {
+                x.end_tp = helper.add(x.tp, x.pre_tp);
+                for (const prop in x) {
+                    if (prop.indexOf('_tp') > 0) {
+                        x['display_' + prop] = formatNum(x[prop]);
+                    }
+                }
+            });
+        }
+
+        /**
+         * 获取全部修订
+         * @param tid
+         * @returns {Promise<*>}
+         */
+        async getAllStages (tid, sort = 'ASC') {
+            const result = await this.getAllDataByCondition({
+                where: { tid: tid },
+                orders: [['stage_order', sort]],
+            });
+            return result;
+        }
+        async getStage(id) {
+            const result = await this.getDataById(id);
+            result.decimal = result.bills_decimal ? JSON.parse(result.bills_decimal) : { qty: 3, tp: 2, up: 2};
+            return result;
+        }
+        async getStageByOrder(tid, stage_order) {
+            const result = await this.getDataByCondition({ tid, stage_order });
+            result.decimal = result.bills_decimal ? JSON.parse(result.bills_decimal) : { qty: 3, tp: 2, up: 2};
+            return result;
+        }
+
+        async getMaxOrder(tid) {
+            const sql = 'SELECT Max(`stage_order`) As max_order FROM ' + this.tableName + ' Where `tid` = ?';
+            const sqlParam = [tid];
+            const result = await this.db.queryOne(sql, sqlParam);
+            return result.max_order || 0;
+        }
+
+        async add(tid, stage_code, stage_date) {
+            if (!tid) throw '数据错误';
+            const user_id = this.ctx.session.sessionUser.accountId;
+
+            const maxOrder = await this.getMaxOrder(tid);
+            const data = {
+                id: this.uuid.v4(), tid: tid, create_user_id: user_id, update_user_id: user_id,
+                stage_order: maxOrder + 1, stage_code, stage_date,
+                audit_times: 1, audit_status: audit.status.uncheck,
+                bills_decimal: JSON.stringify({ up: 2, tp: 2, qty: 3 }),
+            };
+
+            const preStage = maxOrder > 0 ? await this.getStageByOrder(tid, maxOrder) : null;
+            if (preStage) {
+                data.pre_tp = this.ctx.helper.add(preStage.tp, preStage.pre_tp);
+            }
+            const transaction = await this.db.beginTransaction();
+            try {
+                const result = await transaction.insert(this.tableName, data);
+                if (result.affectedRows !== 1) throw '新增安全计量期失败';
+
+                await this.ctx.service.safeStageBills.initStageBills(transaction, data, preStage);
+                await this.ctx.service.safeStageAudit.copyPreAuditors(transaction, preStage, data);
+                await transaction.commit();
+                return data;
+            } catch(err) {
+                await transaction.rollback();
+                throw err;
+            }
+        }
+        async delete(id) {
+            // const info = await this.getDataById(id);
+            const conn = await this.db.beginTransaction();
+            try {
+                await conn.delete(this.tableName, { id });
+                await conn.delete(this.ctx.service.safeStageBills.tableName, { stage_id: id });
+                const files = await this.ctx.service.safeStageFile.getFiles({ where: { stage_id: id} });
+                for (const f of files) {
+                    this.ctx.app.fujianOss.delete(f.filepath);
+                }
+                await conn.delete(this.ctx.service.safeStageFile.tableName, { stage_id: id });
+                await conn.delete(this.ctx.service.safeStageAudit.tableName, { stage_id: id });
+                // 记录删除日志
+                // await this.ctx.service.projectLog.addProjectLog(conn, projectLogConst.type.safeStage, projectLogConst.status.delete, `第${info.phase_order}期`);
+                await conn.commit();
+            } catch (err) {
+                await conn.rollback();
+                throw err;
+            }
+        }
+        async save(stage, data) {
+            await this.defaultUpdate({ id: stage.id, stage_date: data.stage_date, stage_code: data.stage_code });
+        }
+
+        async loadUser(safeStage) {
+            safeStage.user = await this.ctx.service.projectAccount.getAccountInfoById(safeStage.create_user_id);
+            safeStage.auditors = await this.ctx.service.safeStageAudit.getAuditors(safeStage.id, safeStage.curTimes || safeStage.audit_times);
+            safeStage.auditorIds = this._.map(safeStage.auditors, 'audit_id');
+            safeStage.curAuditors = safeStage.auditors.filter(x => { return x.audit_status === audit.status.checking; });
+            safeStage.curAuditorIds = safeStage.curAuditors.map(x => { return x.audit_id; });
+            safeStage.flowAuditors = safeStage.curAuditors.length === 0 ? [] : safeStage.auditors.filter(x => { return x.active_order === safeStage.curAuditors[0].active_order; });
+            safeStage.flowAuditorIds = safeStage.flowAuditors.map(x => { return x.audit_id; });
+            safeStage.nextAuditors = safeStage.curAuditors.length > 0 ? safeStage.auditors.filter(x => { return x.active_order === safeStage.curAuditors[0].active_order + 1; }) : [];
+            safeStage.nextAuditorIds = this._.map(safeStage.nextAuditors, 'audit_id');
+            safeStage.auditorGroups = this.ctx.helper.groupAuditors(safeStage.auditors, 'active_order');
+            safeStage.userGroups = this.ctx.helper.groupAuditorsUniq(safeStage.auditorGroups);
+            safeStage.finalAuditorIds = safeStage.userGroups.length > 1 ? safeStage.userGroups[safeStage.userGroups.length - 1].map(x => { return x.audit_id; }) : [];
+            safeStage.userIds = safeStage.audit_status === audit.status.uncheck // 当前流程下全部参与人id
+                ? [safeStage.user_id]
+                : safeStage.auditorIds;
+        }
+        async loadAuditViewData(safeStage) {
+            if (!safeStage.user) safeStage.user = await this.ctx.service.projectAccount.getAccountInfoById(safeStage.user_id);
+            const auditTimes = safeStage.audit_status === audit.status.checkNo ? safeStage.audit_times - 1 : safeStage.audit_times;
+            safeStage.auditHistory = await this.ctx.service.safeStageAudit.getAuditorHistory(safeStage.id, auditTimes);
+            // 获取审批流程中左边列表
+            if (safeStage.audit_status === audit.status.checkNo && safeStage.create_user_id !== this.ctx.session.sessionUser.accountId) {
+                const auditors = await this.ctx.service.safeStageAudit.getAuditors(safeStage.id, safeStage.audit_times - 1); // 全部参与的审批人
+                const auditorGroups = this.ctx.helper.groupAuditors(auditors);
+                safeStage.hisUserGroup = this.ctx.helper.groupAuditorsUniq(auditorGroups);
+            } else {
+                safeStage.hisUserGroup = safeStage.userGroups;
+            }
+        }
+        /**
+         * cancancel = 0 不可撤回
+         * cancancel = 1 原报撤回
+         * cancancel = 2 审批人撤回 审批通过
+         * cancancel = 3 审批人撤回 审批退回上一人
+         * cancancel = 4 审批人撤回 退回原报
+         * cancancel = 5 会签未全部审批通过时,审批人撤回 审批通过
+         *
+         * @param safeStage
+         * @returns {Promise<void>}
+         */
+        async doCheckCanCancel(safeStage) {
+            // 默认不可撤回
+            safeStage.cancancel = 0;
+            // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回)
+            const status = audit.status;
+            if (safeStage.audit_status === status.checked || safeStage.audit_status === status.uncheck) return;
+
+            const accountId = this.ctx.session.sessionUser.accountId;
+            if (safeStage.audit_status !== status.checkNo) {
+                // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报
+                if (safeStage.flowAuditors.find(x => { return x.audit_status !== status.checking}) && safeStage.flowAuditorIds.indexOf(accountId) < 0) return; // 当前流程存在审批人审批通过时,不可撤回
+                if (safeStage.curAuditorIds.indexOf(accountId) < 0 && safeStage.flowAuditorIds.indexOf(accountId) >= 0) {
+                    safeStage.cancancel = 5; // 会签未全部审批通过时,审批人撤回审批通过
+                    return;
+                }
+
+                const preAuditors = safeStage.curAuditors[0] && safeStage.curAuditors[0].active_order !== 1 ? safeStage.auditors.filter(x => { return x.active_order === safeStage.curAuditors[0].active_order - 1; }) : [];
+                const preAuditorCheckAgain = preAuditors.find(pa => { return pa.audit_status === status.checkAgain; });
+                const preAuditorCheckCancel = preAuditors.find(pa => { return pa.audit_status === status.checkCancel; });
+                const preAuditorHasOld = preAuditors.find(pa => { return pa.is_old === 1; });
+                const preAuditorIds = (preAuditorCheckAgain ? [] : preAuditors.map(x => { return x.audit_id })); // 重审不可撤回
+                if ((this._.isEqual(safeStage.flowAuditorIds, preAuditorIds) && preAuditorCheckCancel) || preAuditorHasOld) {
+                    return; // 不可以多次撤回
+                }
+
+                const preAuditChecked = preAuditors.find(pa => { return pa.audit_status === status.checked && pa.audit_id === accountId; });
+                const preAuditCheckNoPre = preAuditors.find(pa => { return pa.audit_status === status.checkNoPre && pa.audit_id === accountId; });
+                if (preAuditorIds.indexOf(accountId) >= 0) {
+                    if (preAuditChecked) {
+                        safeStage.cancancel = 2;// 审批人撤回审批通过
+                    } else if (preAuditCheckNoPre) {
+                        safeStage.cancancel = 3;// 审批人撤回审批退回上一人
+                    }
+                    safeStage.preAuditors = preAuditors;
+                } else if (preAuditors.length === 0 && accountId === safeStage.create_user_id) {
+                    safeStage.cancancel = 1;// 原报撤回
+                }
+            } else {
+                const lastAuditors = await this.ctx.service.safeStageAudit.getAuditors(safeStage.id, safeStage.audit_times - 1);
+                const onAuditor = this._.findLast(lastAuditors, { audit_status: status.checkNo });
+                if (onAuditor.audit_id === accountId) {
+                    safeStage.cancancel = 4;// 审批人撤回退回原报
+                    safeStage.preAuditors = lastAuditors.filter(x => { return x.active_order === onAuditor.active_order });
+                }
+            }
+        }
+        async doCheckStage(safeStage) {
+            const accountId = this.ctx.session.sessionUser.accountId;
+            // 审批退回时,原报读取本轮流程,其他人读取上一轮流程
+            if (safeStage.audit_status === audit.status.checkNo) {
+                safeStage.curTimes = safeStage.create_user_id === accountId ? safeStage.audit_times : safeStage.audit_times - 1;
+            } else {
+                safeStage.curTimes = safeStage.audit_times;
+            }
+            // 加载参与人
+            await this.loadUser(safeStage);
+
+            if (safeStage.audit_status === audit.status.uncheck) {
+                safeStage.readOnly = accountId !== safeStage.create_user_id;
+                safeStage.curSort = 0;
+            } else if (safeStage.audit_status === audit.status.checkNo) {
+                safeStage.readOnly = accountId !== safeStage.create_user_id;
+                if (!safeStage.readOnly) {
+                    safeStage.curSort = 0;
+                } else {
+                    const checkNoAudit = await this.service.safeStageAudit.getDataByCondition({
+                        phase_id: safeStage.id, audit_times: safeStage.audit_times - 1, audit_status: audit.status.checkNo,
+                    });
+                    safeStage.curSort = checkNoAudit.active_order;
+                }
+            } else if (safeStage.audit_status === audit.status.checked) {
+                safeStage.readOnly = true;
+                safeStage.curSort = safeStage.audit_max_sort;
+            } else {
+                // 会签,会签人部分审批通过时,只读,但是curSort需按原来的取值
+                safeStage.curSort = safeStage.flowAuditorIds.indexOf(accountId) >= 0 ? safeStage.curAuditors[0].active_order : safeStage.curAuditors[0].active_order - 1;
+                safeStage.readOnly = safeStage.curAuditorIds.indexOf(accountId) < 0;
+                safeStage.canCheck = safeStage.readOnly && safeStage.curAuditorIds.indexOf(accountId) > 0;
+            }
+            await this.doCheckCanCancel(safeStage);
+        }
+        async checkShenpi(safeStage) {
+            const status = audit.status;
+            const info = this.ctx.tender.info;
+            const shenpi_status = info.shenpi.safe_stage;
+            if ((safeStage.audit_status === status.uncheck || safeStage.audit_status === status.checkNo) && shenpi_status !== shenpiConst.sp_status.sqspr) {
+                // 进一步比较审批流是否与审批流程设置的相同,不同则替换为固定审批流或固定的终审
+                const auditList = await this.ctx.service.safeStageAudit.getAllDataByCondition({ where: { phase_id: safeStage.id, audit_times: safeStage.audit_times }, orders: [['audit_order', 'asc']] });
+                auditList.shift();
+                if (shenpi_status === shenpiConst.sp_status.gdspl) {
+                    const shenpiList = await this.ctx.service.shenpiAudit.getAllDataByCondition({ where: { tid: safeStage.tid, sp_type: shenpiConst.sp_type.safe_payment, sp_status: shenpi_status } });
+                    // 判断2个id数组是否相同,不同则删除原审批流,切换成固定的审批流
+                    let sameAudit = auditList.length === shenpiList.length;
+                    if (sameAudit) {
+                        for (const audit of auditList) {
+                            const shenpi = shenpiList.find(x => { return x.audit_id === audit.audit_id; });
+                            if (!shenpi || shenpi.audit_order !== audit.audit_order || shenpi.audit_type !== audit.audit_type) {
+                                sameAudit = false;
+                                break;
+                            }
+                        }
+                    }
+                    if (!sameAudit) {
+                        await this.ctx.service.safeStageAudit.updateNewAuditList(safeStage, shenpiList);
+                        await this.loadUser(safeStage);
+                    }
+                } else if (shenpi_status === shenpiConst.sp_status.gdzs) {
+                    const shenpiInfo = await this.ctx.service.shenpiAudit.getDataByCondition({ tid: safeStage.tid, sp_type: shenpiConst.sp_type.safe_payment, sp_status: shenpi_status });
+                    // 判断最后一个id是否与固定终审id相同,不同则删除原审批流中如果存在的id和添加终审
+                    const lastAuditors = auditList.filter(x => { x.active_order === auditList.active_order; });
+                    if (shenpiInfo && (lastAuditors.length === 0 || (lastAuditors.length > 1 || shenpiInfo.audit_id !== lastAuditors[0].audit_id))) {
+                        await this.ctx.service.safeStageAudit.updateLastAudit(safeStage, auditList, shenpiInfo.audit_id);
+                        await this.loadUser(safeStage);
+                    } else if (!shenpiInfo) {
+                        // 不存在终审人的状态下这里恢复为授权审批人
+                        this.ctx.tender.info.shenpi.safe_stage = shenpiConst.sp_status.sqspr;
+                    }
+                }
+            }
+        }
+    }
+
+    return SafeStage;
+};

Plik diff jest za duży
+ 1060 - 0
app/service/safe_stage_audit.js


+ 571 - 0
app/service/safe_stage_bills.js

@@ -0,0 +1,571 @@
+'use strict';
+
+/**
+ *
+ * 支付审批-安全生产
+ * @author Mai
+ * @date
+ * @version
+ */
+
+const defaultBills = require('../const/payment').defaultSafeBills;
+const billsUtils = require('../lib/bills_utils');
+const SafeBillsFields = {
+    textFields: ['b_code', 'name', 'unit', 'spec', 'invoice_code', 'memo'],
+    calcFields: ['unit_price', 'cur_qty', 'cur_tp', 'end_qty', 'end_tp'],
+    fixedFields: ['safe_id', 'tender_id', 'pre_qty', 'pre_tp', 'cur_read_qty', 'cur_read_tp', 'cur_his', 'add_user_id', 'add_time'],
+    treeFields: ['id', 'stage_id', 'safe_id', 'tree_id', 'tree_pid', 'tree_level', 'tree_order', 'tree_full_path', 'tree_is_leaf'],
+};
+SafeBillsFields.editQueryFields = [...SafeBillsFields.treeFields, ...SafeBillsFields.textFields, ...SafeBillsFields.calcFields, 'pre_qty', 'pre_tp'];
+SafeBillsFields.readQueryFields = [...SafeBillsFields.treeFields, ...SafeBillsFields.textFields, 'unit_price', 'pre_qty', 'pre_tp', 'cur_read_qty', 'cur_read_tp'];
+SafeBillsFields.compareQueryFields = [...SafeBillsFields.treeFields, ...SafeBillsFields.textFields, 'unit_price', 'cur_his', 'cur_qty', 'cur_tp'];
+SafeBillsFields.preQueryFields = [...SafeBillsFields.treeFields, ...SafeBillsFields.textFields, 'tender_id', 'unit_price', 'end_qty', 'end_tp', 'add_user_id', 'add_time', 'update_user_id', 'update_time'];
+
+const auditConst = require('../const/audit').safeStage;
+
+module.exports = app => {
+
+    class SafeStageBills extends app.BaseTreeService {
+
+        /**
+         * 构造函数
+         *
+         * @param {Object} ctx - egg全局变量
+         * @return {void}
+         */
+        constructor(ctx) {
+            super(ctx, {
+                mid: 'stage_id',
+                kid: 'tree_id',
+                pid: 'tree_pid',
+                order: 'tree_order',
+                level: 'tree_level',
+                isLeaf: 'tree_is_leaf',
+                fullPath: 'tree_full_path',
+                keyPre: 'safe_stage_bills_maxLid:',
+                uuid: true,
+            });
+            // this.depart = ctx.app.config.table_depart.light;
+            this.tableName = 'safe_stage_bills';
+            this.decimal = { tp: 2, up: 2, qty: 3 };
+        }
+
+        // 继承方法
+        clearParentingData(data) {
+            for (const f of SafeBillsFields.calcFields) {
+                data[f] = 0;
+            }
+        }
+
+        _getDefaultData(data, stage) {
+            data.id = this.uuid.v4();
+            data.safe_id = data.id;
+            data.tender_id = stage.tid;
+            data.stage_id = stage.id;
+            data.add_user_id = this.ctx.session.sessionUser.accountId;
+        }
+
+        async getEditData(stage) {
+            return await this.getAllDataByCondition({
+                where: { stage_id: stage.id },
+                columns: SafeBillsFields.editQueryFields
+            });
+        }
+
+        async getReadData(stage) {
+            const helper = this.ctx.helper;
+            const result = await this.getAllDataByCondition({
+                where: { stage_id: stage.id },
+                columns: SafeBillsFields.readQueryFields
+            });
+            result.forEach(x => {
+                x.cur_qty = x.cur_read_qty;
+                x.cur_tp = x.cur_read_tp;
+                x.end_qty = helper.add(x.pre_qty, x.cur_qty);
+                x.end_tp = helper.add(x.pre_tp, x.cur_tp);
+            });
+            return result;
+        }
+
+        async getCompareData(stage) {
+            const result = await this.getAllDataByCondition({
+                where: { stage_id: stage.id },
+                columns: SafeBillsFields.compareQueryFields
+            });
+            result.forEach(x => {
+                x.cur_his = x.cur_his ? JSON.parse(x.cur_his) : [];
+            });
+            return result;
+        }
+
+        async init(stage, transaction) {
+            console.log(1);
+            if (!stage || !transaction) throw '安全生产费数据错误';
+
+            const insertData = [];
+            for (const b of defaultBills) {
+                const bills = JSON.parse(JSON.stringify(b));
+                this._getDefaultData(bills, stage);
+                insertData.push(bills);
+            }
+
+            const operate = await transaction.insert(this.tableName, insertData);
+            return operate.affectedRows === insertData.length;
+        }
+        async initByPre(stage, preStage, transaction) {
+            if (!stage || !preStage || !transaction) throw '安全生产费数据错误';
+
+            const preBills = await this.getAllDataByCondition({
+                where: { stage_id: preStage.id },
+                columns: SafeBillsFields.preQueryFields
+            });
+            const insertData = [];
+            for (const bills of preBills) {
+                //const bills = JSON.parse(JSON.stringify(b));
+                bills.id = this.uuid.v4();
+                bills.stage_id = stage.id;
+                delete bills.invoice_code;
+                bills.pre_qty = bills.end_qty;
+                bills.pre_tp = bills.end_tp;
+                insertData.push(bills);
+            }
+            const operate = await transaction.insert(this.tableName, insertData);
+            return operate.affectedRows === insertData.length;
+        }
+        async initStageBills(transaction, stage, preStage) {
+            if (preStage) {
+                this.initByPre(stage, preStage, transaction);
+            } else {
+                this.init(stage, transaction);
+            }
+        }
+
+        /**
+         * 新增数据(供内部或其他service类调用, controller不可直接使用)
+         * @param {Array|Object} data - 新增数据
+         * @param {Number} stageId - 期id
+         * @param {Object} transaction - 新增事务
+         * @return {Promise<boolean>} - {Promise<是否正确新增成功>}
+         */
+        async innerAdd(data, stageId, transaction) {
+            const datas = data instanceof Array ? data : [data];
+            if (stageId <= 0) {
+                throw '期id错误';
+            }
+            if (datas.length <= 0) {
+                throw '插入数据为空';
+            }
+            if (!transaction) {
+                throw '内部错误';
+            }
+            // 整理数据
+            const insertData = [];
+            for (const tmp of datas) {
+                tmp[this.setting.id] = tmp.template_id;
+                tmp[this.setting.pid] = tmp.pid;
+                tmp[this.setting.mid] = stageId;
+                delete tmp.template_id;
+                delete tmp.pid;
+                tmp.id = this.uuid.v4();
+                insertData.push(tmp);
+            }
+            const operate = await transaction.insert(this.tableName, insertData);
+            return operate.affectedRows === datas.length;
+        }
+        /**
+         * 新增数据
+         *
+         * @param {Object} data - 新增的数据(可批量)
+         * @param {Number} stageId - 安全计量期id
+         * @return {Boolean} - 返回新增的结果
+         */
+        async add(data, stageId) {
+            this.transaction = await this.db.beginTransaction();
+            let result = false;
+            try {
+                result = await this.innerAdd(data, stageId, this.transaction);
+                if (!result) {
+                    throw '新增数据错误';
+                }
+                await this.transaction.commit();
+            } catch (error) {
+                await this.transaction.rollback();
+                result = false;
+            }
+
+            return result;
+        }
+
+        /**
+         * 根据节点Id获取数据
+         *
+         * @param {Number} stageId - 安全计量期id
+         * @param {Number} nodeId - 项目节/工程量清单节点id
+         * @return {Object} - 返回查询到的节点数据
+         */
+        async getDataByNodeId(stageId, nodeId) {
+            if ((nodeId <= 0) || (stageId <= 0)) {
+                return undefined;
+            }
+            const where = {};
+            where[this.setting.mid] = stageId;
+            where[this.setting.id] = nodeId;
+            const data = await this.db.getDataByCondition(where);
+
+            return data;
+        }
+        /**
+         * 根据节点Id获取数据
+         * @param {Number} stageId - 期Id
+         * @param {Array} nodesIds - 节点Id
+         * @return {Array}
+         */
+        async getDataByNodeIds(stageId, nodesIds) {
+            if (stageId <= 0) {
+                return [];
+            }
+
+            const where = {};
+            where[this.setting.mid] = stageId;
+            where[this.setting.id] = nodesIds;
+            const data = await this.db.getAllDataByCondition({ where });
+
+            return this._.sortBy(data, function(d) {
+                return nodesIds.indexOf(d.ledger_id);
+            });
+        }
+        /**
+         * 根据主键id获取数据
+         * @param {Array|Number} id - 主键id
+         * @return {Promise<*>}
+         */
+        async getDataByIds(id) {
+            if (!id) {
+                return [];
+            }
+            const ids = id instanceof Array ? id : [id];
+            if (ids.length === 0) {
+                return [];
+            }
+
+            const data = await this.db.getAllDataByCondition({ where: { id: ids } });
+
+            return data;
+        }
+
+        /**
+         * 根据 父节点id 获取子节点
+         * @param stageId
+         * @param nodeId
+         * @return {Promise<*>}
+         */
+        async getChildrenByParentId(stageId, nodeId) {
+            if (stageId <= 0 || !nodeId) {
+                return undefined;
+            }
+            const nodeIds = nodeId instanceof Array ? nodeId : [nodeId];
+            if (nodeIds.length === 0) {
+                return [];
+            }
+
+            const where = {};
+            where[this.setting.mid] = stageId;
+            where[this.setting.pid] = nodeIds;
+            const data = await this.getAllDataByCondition({ where, orders: [[this.setting.order, 'ASC']] });
+
+            return data;
+        }
+
+        async pasteBlockData(stageId, targetId, pasteData, defaultData) {
+            const setting = this.setting;
+            if ((stageId <= 0) || (sid <= 0)) return [];
+
+            if (!pasteData || pasteData.length <= 0) throw '复制数据错误';
+            for (const pd of pasteData) {
+                if (!pd || pd.length <= 0) throw '复制数据错误';
+                pd.sort(function (x, y) {
+                    return x[setting.level] - y[setting.level]
+                });
+                if (pd[0][this.setting.pid] !== pasteData[0][0][this.setting.pid]) throw '复制数据错误:仅可操作同层节点';
+            }
+            this.newBills = false;
+            const targetData = await this.getDataByKid(stageId, targetId);
+            if (!targetData) throw '粘贴数据错误';
+
+            const newParentPath = targetData.full_path.replace(targetData.ledger_id, '');
+            const tpDecimal = this.ctx.safeStage && this.ctx.safeStage.decimal ? this.ctx.safeStage.decimal : this.decimal;
+
+            const pasteBillsData = [], leafBillsId = [];
+            let maxId = await this._getMaxLid(this.ctx.tender.id);
+            for (const [i, pd] of pasteData.entries()) {
+                for (const d of pd) {
+                    d.children = pd.filter(function (x) {
+                        return x[setting.pid] === d[setting.id];
+                    });
+                }
+                const pbd = [];
+                for (const [j, d] of pd.entries()) {
+                    const newBills = {
+                        id: this.uuid.v4(),
+                        safe_id: this.uuid.v4(),
+                        b_code: d.b_code,
+                        name: d.name,
+                        unit: d.unit,
+                        unit_price: this.ctx.helper.round(d.unit_price, tpDecimal.up),
+                        memo: d.memo,
+                    };
+                    newBills[setting.mid] = stageId;
+                    newBills[setting.id] = maxId + j + 1;
+                    newBills[setting.pid] = j === 0 ? targetData[setting.pid] : d[setting.pid];
+                    newBills[setting.level] = d[setting.level] + targetData[setting.level] - pd[0][setting.level];
+                    newBills[setting.order] = j === 0 ? targetData[setting.order] + i + 1 : d[setting.order];
+                    newBills[setting.isLeaf] = d[setting.isLeaf];
+
+                    for (const c of d.children) {
+                        c[setting.pid] = newBills[setting.id];
+                    }
+                    newBills.quantity = this.ctx.helper.round(d.quantity, tpDecimal.qty);
+                    newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, tpDecimal.tp);
+                    if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);
+                    pbd.push(newBills);
+                }
+                for (const d of pbd) {
+                    const parent = pbd.find(function (x) {
+                        return x[setting.id] === d[setting.pid];
+                    });
+                    d[setting.fullPath] = parent
+                        ? parent[setting.fullPath] + '-' + d[setting.id]
+                        : newParentPath + d[setting.id];
+                    if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);
+                    pasteBillsData.push(d);
+                }
+                maxId = maxId + pbd.length;
+            }
+
+            this.transaction = await this.db.beginTransaction();
+            try {
+                // 选中节点的所有后兄弟节点,order+粘贴节点个数
+                await this._updateChildrenOrder(tid, targetData[setting.pid], targetData[setting.order] + 1, pasteData.length);
+                // 数据库创建新增节点数据
+                if (pasteBillsData.length > 0) {
+                    const newData = await this.transaction.insert(this.tableName, pasteBillsData);
+                }
+                this._cacheMaxLid(tid, maxId);
+                await this.transaction.commit();
+            } catch (err) {
+                await this.transaction.rollback();
+                throw err;
+            }
+
+            // 查询应返回的结果
+            const updateData = await this.getNextsData(targetData[setting.mid], targetData[setting.pid], targetData[setting.order] + pasteData.length);
+            return { create: pasteBillsData, update: updateData };
+        }
+
+        async addSafeBillsNode(stage, targetId, count) {
+            if (!stage) return null;
+
+            const select = targetId ? await this.getDataByKid(stage.id, targetId) : null;
+            if (targetId && !select) throw '新增节点数据错误';
+
+            this.transaction = await this.db.beginTransaction();
+            try {
+                if (select) await this._updateChildrenOrder(stage.id, select[this.setting.pid], select[this.setting.order] + 1, count);
+                const newDatas = [];
+                const maxId = await this._getMaxLid(stage.id);
+                for (let i = 1; i < count + 1; i++) {
+                    const newData = {};
+                    newData[this.setting.kid] = maxId + i;
+                    newData[this.setting.pid] = select ? select[this.setting.pid] : this.rootId;
+                    newData[this.setting.mid] = stage.id;
+                    newData[this.setting.level] = select ? select[this.setting.level] : 1;
+                    newData[this.setting.order] = select ? select[this.setting.order] + i : i;
+                    newData[this.setting.fullPath] = newData[this.setting.level] > 1
+                        ? select[this.setting.fullPath].replace('-' + select[this.setting.kid], '-' + newData[this.setting.kid])
+                        : newData[this.setting.kid] + '';
+                    newData[this.setting.isLeaf] = true;
+                    this._getDefaultData(newData, stage);
+                    newDatas.push(newData);
+                }
+                const insertResult = await this.transaction.insert(this.tableName, newDatas);
+                this._cacheMaxLid(stage.id, maxId + count);
+
+                if (insertResult.affectedRows !== count) throw '新增节点数据错误';
+                await this.transaction.commit();
+                this.transaction = null;
+            } catch (err) {
+                await this.transaction.rollback();
+                this.transaction = null;
+                throw err;
+            }
+
+            if (select) {
+                const createData = await this.getChildBetween(stage.id, select[this.setting.pid], select[this.setting.order], select[this.setting.order] + count + 1);
+                const updateData = await this.getNextsData(stage.id, select[this.setting.pid], select[this.setting.order] + count);
+                return {create: createData, update: updateData};
+            } else {
+                const createData = await this.getChildBetween(stage.id, -1, 0, count + 1);
+                return {create: createData};
+            }
+        }
+
+        async addStdNodeWithParent(stage, targetId, stdData) {
+            const findPreData = function(list, a) {
+                if (!list || list.length === 0) { return null; }
+                for (let i = 0, iLen = list.length; i < iLen; i++) {
+                    if (billsUtils.compareCode(list[i].b_code, a.b_code) > 0) {
+                        return i > 0 ? list[i - 1] : null;
+                    }
+                }
+                return list[list.length - 1];
+            };
+            let parent = await this.getDataByKid(stage.id, targetId);
+            if (targetId && !parent) throw '新增节点数据错误,请刷新页面重试';
+            const orgParentId = parent.id;
+            let children = await this.getChildrenByParentId(stage.id, targetId);
+            const updateParent = children.length === 0;
+
+            const insertData = [];
+            const maxId = await this._getMaxLid(stage.id);
+            this.transaction = await this.db.beginTransaction();
+            try {
+                if (updateParent) {
+                    const updateData = { id: parent.id };
+                    updateData[this.setting.isLeaf] = false;
+                    this.clearParentingData(updateData);
+                    await this.transaction.update(this.tableName, updateData);
+                }
+                // 从最顶层节点依次查询是否存在,否则添加
+                for (let i = 0, len = stdData.length; i < len; i++) {
+                    const newData = { b_code: stdData[i].b_code, name: stdData[i].name, unit: stdData[i].unit };
+                    newData[this.setting.kid] = maxId + i + 1;
+                    newData[this.setting.pid] = parent ? parent[this.setting.kid] : this.rootId;
+                    newData[this.setting.level] = parent ? parent[this.setting.level] + 1 : 1;
+                    newData[this.setting.fullPath] = parent ? `${parent[this.setting.fullPath]}-${newData[this.setting.kid]}` : `${newData[this.setting.kid]}`;
+                    const pre = findPreData(children, newData);
+                    newData[this.setting.order] = pre ? pre[this.setting.order] + 1 : 1;
+                    if (!pre || children.indexOf(pre) < children.length - 1) {
+                        await this._updateChildrenOrder(stage.id, parent ? parent[this.setting.kid] : this.rootId, pre ? pre[this.setting.order] + 1 : 1);
+                    }
+                    newData[this.setting.isLeaf] = (i === len - 1);
+                    this._getDefaultData(newData, stage);
+                    insertData.push(newData);
+                    parent = newData;
+                    children = [];
+                }
+                await this.transaction.insert(this.tableName, insertData);
+                await this.transaction.commit();
+            } catch (err) {
+                await this.transaction.rollback();
+                throw err;
+            }
+            this._cacheMaxLid(stage.id, maxId + stdData.length);
+
+            // 查询应返回的结果
+            const createData = await this.getDataByFullPath(stage.id, insertData[0][this.setting.fullPath] + '%');
+            const updateData = await this.getNextsData(stage.id, targetId, insertData[0][this.setting.order]);
+            if (updateParent) {
+                updateData.push(await this.getDataByKid(stage.id, targetId));
+            }
+            return { create: createData, update: updateData };
+        }
+
+        async updateCalc(stage, data) {
+            const helper = this.ctx.helper;
+            // 简单验证数据
+            if (!stage) throw '安全生产费不存在';
+            const decimal = stage.decimal;
+            if (!data) throw '提交数据错误';
+            const datas = data instanceof Array ? data : [data];
+            const ids = datas.map(x => { return x.id; });
+            const orgData = await this.getAllDataByCondition({ where: { id: ids }});
+            const updateData = [];
+            for (const row of datas) {
+                const oData = orgData.find(x => { return x.id === row.id });
+                if (!oData || oData.stage_id !== stage.id || oData.tree_id !== row.tree_id) throw '提交数据错误';
+
+                let nData = { id: oData.id, tree_id: oData.tree_id, update_user_id: this.ctx.session.sessionUser.accountId };
+
+                // 计算相关
+                if (row.cur_qty !== undefined || row.unit_price !== undefined || row.cur_tp !== undefined) {
+                    nData.unit_price = row.unit_price !== undefined ? helper.round(row.unit_price, decimal.up) : oData.unit_price;
+                    nData.cur_qty = row.cur_qty !== undefined ? helper.round(row.cur_qty, decimal.qty) : oData.cur_qty;
+                    if (row.cur_tp !== undefined && row.unit_price === undefined) {
+                        nData.unit_price = nData.cur_qty ? helper.div(row.cur_tp, nData.cur_qty, decimal.up) : 0;
+                    }
+                    nData.cur_tp = helper.mul(nData.unit_price, nData.cur_qty, decimal.tp);
+                    nData.end_qty = helper.add(nData.cur_qty, oData.pre_qty);
+                    nData.end_tp = helper.add(nData.cur_tp, oData.pre_tp);
+                }
+                for (const field of SafeBillsFields.textFields) {
+                    if (row[field] !== undefined) nData[field] = row[field];
+                }
+                updateData.push(nData);
+            }
+
+            await this.db.updateRows(this.tableName, updateData);
+            return { update: updateData };
+        }
+
+        async auditCache(transaction, stageId, auditInfo) {
+            const leaf = await this.getAllDataByCondition({ where: { stage_id: stageId, tree_is_leaf: true} });
+            const updateData = [];
+            for (const l of leaf) {
+                if (l.cur_read_qty !== l.cur_qty || l.cur_read_tp !== l.cur_tp) {
+                    const data = { id: l.id, cur_read_qty: l.cur_qty, cur_read_tp: l.cur_tp };
+                    const his = l.cur_his ? JSON.parse(l.cur_his) : [];
+                    his.push({ ...auditInfo, qty: l.cur_qty, tp: l.cur_tp, up: l.unit_price });
+                    data.cur_his = JSON.stringify(his);
+                    data.cur_read_qty = l.cur_qty;
+                    data.cur_read_tp = l.cur_tp;
+                    updateData.push(data);
+                }
+            }
+            if (updateData.length > 0) await transaction.updateRows(this.tableName, updateData);
+        }
+
+        async setDecimal(decimal) {
+            if (!this.ctx.safeStage) throw '读取数据错误';
+            if (this.ctx.safeStage.stage_order !== this.ctx.safeStage.latestOrder) throw '往期不可修改小数位数';
+            if (this.ctx.safeStage.audit_status !== auditConst.status.uncheck && this.ctx.safeStage.audit_status !== auditConst.status.checkNo) throw '仅原报可修改小数位数';
+            const orgDecimal = this.ctx.safeStage.decimal ? this.ctx.safeStage.decimal : this.decimal;
+
+            const calcQty = decimal.qty < orgDecimal.qty;
+            const calcUp = decimal.up < orgDecimal.up;
+            const calcTp = decimal.tp < orgDecimal.tp;
+            this.ctx.safeStage.decimal = { up: decimal.up, tp: decimal.tp, qty: decimal.qty };
+
+            const updateData = [];
+            if (calcQty || calcUp || calcTp) {
+                const calcData = await this.getAllDataByCondition({ where: {stage_id: this.ctx.safeStage.id, tree_is_leaf: 1 } });
+                for (const cd of calcData) {
+                    const nd = { id: cd.id, tree_id: cd.tree_id };
+                    nd.unit_price = calcUp ? this.ctx.helper.round(cd.unit_price, decimal.up) : cd.unit_price;
+                    nd.cur_qty = calcQty ? this.ctx.helper.round(cd.cur_qty, decimal.qty) : cd.cur_qty;
+                    nd.cur_tp = this.ctx.helper.mul(nd.unit_price, nd.cur_qty, decimal.tp);
+                    nd.end_qty = this.ctx.helper.add(cd.pre_qty, nd.cur_qty);
+                    nd.end_tp = this.ctx.helper.add(cd.pre_tp, nd.cur_tp);
+                    updateData.push(nd);
+                }
+            }
+            const conn = await this.db.beginTransaction();
+            try {
+                await conn.update(this.ctx.service.safeStage.tableName, { id: this.ctx.safeStage.id, bills_decimal: JSON.stringify(this.ctx.safeStage.decimal)});
+                if (updateData.length > 0) await conn.updateRows(this.tableName, updateData);
+                await conn.commit();
+                return { calc: calcQty || calcUp || calcTp, update: updateData };
+            } catch(err) {
+                await conn.rollback();
+                return { calc: false, update: [] };
+            }
+
+        }
+
+        async getSum(stage) {
+            const result = await this.db.queryOne(`SELECT Sum(cur_tp) as cur_tp FROM ${this.tableName} where stage_id = ?`, [stage.id]);
+            return { bills_tp: result ? result.cur_tp || 0 : 0 };
+        }
+    }
+
+    return SafeStageBills;
+};

+ 92 - 0
app/service/safe_stage_file.js

@@ -0,0 +1,92 @@
+'use strict';
+
+/**
+ *
+ *  附件
+ * @author Ellisran
+ * @date 2019/1/11
+ * @version
+ */
+
+module.exports = app => {
+    class SafeStageFile extends app.BaseService {
+        /**
+         * 构造函数
+         *
+         * @param {Object} ctx - egg全局变量
+         * @return {void}
+         */
+        constructor(ctx) {
+            super(ctx);
+            this.tableName = 'safe_stage_file';
+        }
+
+        _analysisData(files) {
+            const helper = this.ctx.helper;
+            const userId = this.ctx.session.sessionUser.accountId;
+            const ossPath = this.ctx.app.config.fujianOssPath;
+            files.forEach(x => {
+                x.viewpath = helper.canPreview(x.fileext) ? ossPath + x.filepath : '';
+                x.filepath = ossPath + x.filepath;
+                x.fileext_str = helper.fileExtStr(x.fileext);
+                x.canEdit = x.user_id === userId;
+            });
+        }
+
+        async getData(stage_id, type) {
+            const data = await this.getAllDataByCondition({
+                where: { type, stage_id, is_deleted: 0 },
+                orders: [['create_time', 'desc']],
+            });
+            this._analysisData(data);
+            return data;
+        }
+
+        async getFiles(condition) {
+            condition.orders = [['create_time', 'desc']];
+            const result = await this.getAllDataByCondition(condition);
+            this._analysisData(result);
+            return result;
+        }
+
+        async addFiles(safeStage, type, fileInfo, user) {
+            const conn = await this.db.beginTransaction();
+            const result = {};
+            try {
+                const insertData = fileInfo.map(x => {
+                    return {
+                        id: this.uuid.v4(), tid: safeStage.tid, stage_id: safeStage.id, type, rela_id: x.rela_id,
+                        user_id: user.id, user_name: user.name, user_company: user.company, user_role: user.role,
+                        filename: x.filename, fileext: x.fileext, filesize: x.filesize, filepath: x.filepath,
+                    };
+                });
+                await conn.insert(this.tableName, insertData);
+                await conn.commit();
+                result.files = { id: insertData.map(x => { return x.id; })};
+            } catch (err) {
+                await conn.rollback();
+                throw err;
+            }
+            return await this.getFiles({ where: result.files });
+        }
+
+        async delFiles(files) {
+            const fileDatas = await this.getAllDataByCondition({ where: { id: files } });
+            const result = {};
+
+            const conn = await this.db.beginTransaction();
+            try {
+                const updateData = fileDatas.map(x => { return { id: x.id, is_deleted: 1 }; });
+                if (updateData.length > 0) await conn.updateRows(this.tableName, updateData);
+                await conn.commit();
+                result.del = files;
+            } catch (err) {
+                await conn.rollback();
+                throw err;
+            }
+            return result;
+        }
+    }
+
+    return SafeStageFile;
+};

+ 41 - 0
app/view/safe_calc/audit_btn.ejs

@@ -0,0 +1,41 @@
+<div class="contarl-box">
+    <% if (ctx.safeStage.audit_status === auditConst.status.uncheck) { %>
+        <% if (ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+            <a id="sub-sp-btn" href="javascript: void(0);" data-toggle="modal" data-target="#sub-sp" class="btn btn-primary btn-sm btn-block">上报审批</a>
+        <% } else { %>
+            <a id="sub-sp-btn" href="javascript: void(0);" data-toggle="modal" data-target="#sub-sp" class="btn btn-outline-secondary btn-sm btn-block">上报中</a>
+        <% } %>
+    <% } %>
+
+    <% if (ctx.safeStage.audit_status === auditConst.status.checking) { %>
+        <% if (ctx.safeStage.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) { %>
+            <a id="sp-done-btn" href="javascript: void(0);" data-toggle="modal" data-target="#sp-done" class="btn btn-success btn-sm btn-block">审批通过</a>
+            <a href="#sp-back" data-toggle="modal" data-target="#sp-back" class="btn btn-warning btn-sm btn-block">审批退回</a>
+        <% } else { %>
+            <a href="#sp-list" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-secondary btn-sm btn-block">审批中</a>
+        <% } %>
+    <% } %>
+
+    <% if (ctx.safeStage.audit_status === auditConst.status.checked) { %>
+        <a href="#sp-list" data-type="hide" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-secondary btn-sm btn-block sp-list-btn">审批完成</a>
+    <% } %>
+
+    <% if (ctx.safeStage.audit_status === auditConst.status.checkNo) { %>
+        <a href="#sp-list"  data-type="hide" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-warning btn-sm btn-block text-muted sp-list-btn">审批退回</a>
+        <% if (ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+            <a href="#sp-list" data-type="show" data-toggle="modal" data-target="#sp-list"  class="btn btn-primary btn-sm btn-block sp-list-btn">重新上报</a>
+        <% } %>
+    <% } %>
+
+    <% if (ctx.safeStage.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0 && ctx.safeStage.audit_status === auditConst.status.checked && ctx.safeStage.isLatest) { %>
+        <a href="javascript: void(0);" data-toggle="modal" data-target="#sp-down-back" class="btn btn-warning btn-sm btn-block">重新审批</a>
+    <% } %>
+
+    <% if (ctx.safeStage.cancancel) { %>
+        <a href="javascript: void(0);" data-toggle="modal" data-target="#sp-down-cancel" class="btn btn-danger btn-sm btn-block">撤回</a>
+    <% } %>
+
+    <% if (ctx.safeStage.create_user_id === ctx.session.sessionUser.accountId && ctx.safeStage.isLatest && (ctx.safeStage.audit_status === auditConst.status.checkNo || ctx.safeStage.audit_status === auditConst.status.uncheck)) { %>
+        <a href="#del-qi" data-toggle="modal" data-target="#del-qi" class="btn btn-outline-danger btn-sm btn-block mt-5">删除本期</a>
+    <% } %>
+</div>

+ 898 - 0
app/view/safe_calc/audit_modal.ejs

@@ -0,0 +1,898 @@
+<% if (ctx.safeStage && (ctx.safeStage.audit_status === auditConst.status.uncheck || ctx.safeStage.audit_status === auditConst.status.checkNo) && ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+<!--上报审批-->
+<div class="modal fade" id="sub-sp" data-backdrop="static">
+    <div class="modal-dialog" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">上报审批</h5>
+            </div>
+            <div class="modal-body">
+                <div class="dropdown text-right">
+                    <% if (ctx.tender.info.shenpi.safeStage !== shenpiConst.sp_status.gdspl && ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+                    <button class="btn btn-outline-primary btn-sm dropdown-toggle" type="button" id="dropdownMenuButton"
+                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+                        添加审批流程
+                    </button>
+                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton" style="width:220px">
+                        <div class="mb-2 p-2"><input class="form-control form-control-sm" placeholder="姓名/手机 检索"
+                                                     id="gr-search" autocomplete="off"></div>
+                        <dl class="list-unstyled book-list" id="book-list">
+                            <% accountGroup.forEach((group, idx) => { %>
+                            <dt><a href="javascript: void(0);" class="acc-btn" data-groupid="<%- idx %>"
+                                   data-type="hide"><i class="fa fa-plus-square"></i></a> <%- group.groupName %></dt>
+                            <div class="dd-content" data-toggleid="<%- idx %>">
+                                <% group.groupList.forEach(item => { %>
+                                <% if (item.id !== ctx.session.sessionUser.accountId) { %>
+                                <dd class="border-bottom p-2 mb-0 " data-id="<%- item.id %>">
+                                    <p class="mb-0 d-flex"><span class="text-primary"><%- item.name %></span><span
+                                                class="ml-auto"><%- item.mobile %></span></p>
+                                    <span class="text-muted"><%- item.role %></span>
+                                </dd>
+                                <% } %>
+                                <% });%>
+                            </div>
+                            <% }) %>
+                        </dl>
+                    </div>
+                    <% } %>
+                </div>
+                <div class="card mt-3">
+                    <div class="card-header">
+                        审批流程
+                    </div>
+                    <div class="modal-height-500" style="overflow: auto">
+                        <ul class="list-group list-group-flush" id="auditors">
+                            <% for (let i = 0, iLen = ctx.safeStage.auditorGroups.length; i < iLen; i++) { %>
+                            <% if (ctx.safeStage.auditorGroups[i][0].audit_order === 0) continue; %>
+                            <li class="list-group-item d-flex" auditorId="<%- ctx.safeStage.auditorGroups[i][0].audit_id %>">
+                                <div class="col-auto"><%- ctx.safeStage.auditorGroups[i][0].audit_order %></div>
+                                <div class="col">
+                                    <% for (const auditor of ctx.safeStage.auditorGroups[i]) { %>
+                                    <div class="d-inline-block mx-1" auditorId="<%- auditor.audit_id %>">
+                                        <i class="fa fa-user text-muted"></i> <%- auditor.name %> <small class="text-muted"><%- auditor.role %></small>
+                                    </div>
+                                    <% } %>
+                                </div>
+                                <div class="col-auto">
+                                    <% if (ctx.safeStage.auditorGroups[i][0].audit_type !== auditType.key.common) { %>
+                                    <span class="badge badge-pill badge-<%- auditType.info[ctx.safeStage.auditorGroups[i][0].audit_type].class %> badge-bg-small"><small><%- auditType.info[ctx.safeStage.auditorGroups[i][0].audit_type].long%></small></span>
+                                    <% } %>
+                                    <% if ((ctx.tender.info.shenpi.safeStage === shenpiConst.sp_status.sqspr ||
+                                                    (ctx.tender.info.shenpi.safeStage === shenpiConst.sp_status.gdzs && i+1 !== iLen)) && ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id && !ctx.tender.isTourist) { %>
+                                    <a href="javascript: void(0)" class="text-danger pull-right">移除</a>
+                                    <% } %>
+                                </div>
+                            </li>
+                            <% } %>
+                        </ul>
+                    </div>
+                </div>
+            </div>
+            <form class="modal-footer" method="post" action="audit/start" name="stage-start">
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>">
+                <% if (ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+                <button class="btn btn-primary btn-sm" type="submit">确认上报</button>
+                <% } %>
+            </form>
+        </div>
+    </div>
+</div>
+<% } %>
+<% if(ctx.safeStage && (ctx.safeStage.audit_status !== auditConst.status.uncheck)) { %>
+<!--审批流程/结果-->
+<div class="modal fade" id="sp-list" data-backdrop="static">
+    <div class="modal-dialog modal-lg" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">审批流程</h5>
+            </div>
+            <div class="modal-body">
+                <div class="row">
+                    <div class="col-4">
+                        <% if(ctx.safeStage.audit_status === auditConst.status.checkNo && ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+                        <a class="sp-list-item" href="#sub-sp" data-toggle="modal" data-target="#sub-sp"
+                           id="hideSp">修改审批流程</a>
+                        <% } else if(ctx.safeStage.audit_status !== auditConst.status.checked && ctx.session.sessionUser.is_admin) { %>
+                        <a class="sp-list-item" href="#sub-sp2" data-toggle="modal" data-target="#sub-sp2"
+                           id="hideSp" style="display: none;">修改审批流程</a>
+                        <% } %>
+                        <div class="card modal-height-500 mt-3" style="overflow: auto">
+                            <ul class="list-group list-group-flush auditors-list" id="auditors-list">
+                                <% ctx.safeStage.userGroups.forEach((item, idx) => { %>
+                                <% if (idx === 0) { %>
+                                <li class="list-group-item d-flex justify-content-between align-items-center">
+                                    <span class="mr-1"><i class="fa fa fa-play-circle fa-rotate-90"></i></span>
+                                    <span class="text-muted">
+                                        <% for (const u of item) { %>
+                                        <small class="d-inline-block text-dark mx-1" title="<%- u.company %>" data-auditorId="<%- u.audit_id %>"><%- u.name %></small>
+                                        <% } %>
+                                    </span>
+                                    <span class="badge badge-light badge-pill ml-auto"><small>原报</small></span>
+                                </li>
+                                <% } else if(idx === ctx.safeStage.userGroups.length -1 && idx !== 0) { %>
+                                <li class="list-group-item d-flex justify-content-between align-items-center">
+                                    <span class="mr-1"><i class="fa fa fa-stop-circle"></i></span>
+                                    <span class="text-muted">
+                                        <% for (const u of item) { %>
+                                        <small class="d-inline-block text-dark mx-1" title="<%- u.company %>" data-auditorId="<%- u.audit_id %>"><%- u.name %></small>
+                                        <% } %>
+                                    </span>
+                                    <div class="d-flex ml-auto">
+                                        <% if (item[0].audit_type !== auditType.key.common) { %>
+                                        <span class="badge badge-pill badge-<%-  auditType.info[item[0].audit_type].class %> p-1"><small><%- auditType.info[item[0].audit_type].short %></small></span>
+                                        <% } %>
+                                        <span class="badge badge-light badge-pill"><small>终审</small></span>
+                                    </div>
+                                </li>
+                                <% } else {%>
+                                <li class="list-group-item d-flex justify-content-between align-items-center">
+                                    <span class="mr-1"><i class="fa fa-chevron-circle-down"></i></span>
+                                    <span class="text-muted">
+                                        <% for (const u of item) { %>
+                                        <small class="d-inline-block text-dark mx-1" title="<%- u.company %>" data-auditorId="<%- u.audit_id %>"><%- u.name %></small>
+                                        <% } %>
+                                    </span>
+                                    <div class="d-flex ml-auto">
+                                        <% if (item[0].audit_type !== auditType.key.common) { %>
+                                        <span class="badge badge-pill badge-<%- auditType.info[item[0].audit_type].class %> p-1"><small><%- auditType.info[item[0].audit_type].short %></small></span>
+                                        <% } %>
+                                        <span class="badge badge-light badge-pill"><small><%= ctx.helper.transFormToChinese(idx) %>审</small></span>
+                                    </div>
+                                </li>
+                                <% } %>
+                                <% }) %>
+                            </ul>
+                        </div>
+                    </div>
+                    <div class="col-8 modal-height-500" style="overflow: auto">
+                        <% ctx.safeStage.auditHistory.forEach((his, idx) => { %>
+                        <!-- 展开/收起历史流程 -->
+                        <% if(idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>
+                        <div class="text-right">
+                            <a href="javascript: void(0);" id="fold-btn" data-target="show" >展开历史审批流程</a>
+                        </div>
+                        <% } %>
+                        <div class="<%- idx < ctx.safeStage.auditHistory.length - 1 ? 'fold-card' : '' %>">
+                            <div class="text-center text-muted"><%- idx+1 %>#</div>
+                            <ul class="timeline-list list-unstyled mt-2 <% if (idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>last-auditor-list<% } %>">
+                                <% his.forEach((group, index) => { %>
+                                <li class="timeline-list-item pb-2 <% if (group.audit_status === auditConst.status.uncheck && idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>is_uncheck<% } %>">
+                                    <% if (group.auditYear) { %>
+                                    <div class="timeline-item-date">
+                                        <%- group.auditYear %>
+                                        <span><%- group.auditDate %></span>
+                                        <span><%- group.auditTime %></span>
+                                    </div>
+                                    <% } %>
+                                    <% if (index < his.length - 1) { %>
+                                    <div class="timeline-item-tail"></div>
+                                    <% } %>
+                                    <% if (group.audit_order === 0) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-caret-down"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checked) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-check"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checkNo || group.audit_status === auditConst.status.checkNoPre || group.audit_status === auditConst.status.checkCancel) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-level-up"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checking) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-ellipsis-h"></i></div>
+                                    <% } else { %>
+                                    <div class="timeline-item-icon bg-secondary text-light"></div>
+                                    <% } %>
+                                    <div class="timeline-item-content">
+                                        <div class="py-1">
+                                            <span class="text-black-50">
+                                                <%- group.auditName %>
+                                                <% if (group.audit_type !== auditType.key.common) { %><span class="text-<%- auditType.info[group.audit_type].class %> "><%- auditType.info[group.audit_type].long %></span><% } %>
+                                            </span>
+                                            <% if (group.audit_order === 0) { %>
+                                            <span class="pull-right text-success"><%- idx !== 0 ? '重新' : '' %>上报审批</span>
+                                            <% } else if (group.audit_status !== auditConst.status.uncheck) { %>
+                                            <span class="pull-right <%- auditConst.info[group.audit_status].class %>"><%- auditConst.info[group.audit_status].title %></span>
+                                            <% } %>
+                                        </div>
+                                        <div class="card">
+                                            <div class="card-body px-3 py-0">
+                                                <% for (const [i, auditor] of group.auditors.entries()) { %>
+                                                <div class="card-text p-2 py-3 row <%- ( i > 0 ? 'border-top' : '') %>">
+                                                    <div class="col-10">
+                                                        <span class="h6"><%- auditor.name %></span>
+                                                        <% if (group.audit_order === 0) { %>
+                                                            <% if (auditor.role && auditor.role.trim()) { %>
+                                                                <span class="text-muted ml-1"><%- auditor.role %></span>
+                                                            <% } %>
+                                                        <% } else { %>
+                                                            <span class="text-muted ml-1">
+                                                                <%- auditor.company %>
+                                                                <% if (auditor.role) { %>
+                                                                    - <%- auditor.role %>
+                                                                <% } %>
+                                                            </span>
+                                                        <% } %>
+                                                    </div>
+                                                    <div class="col">
+                                                        <% if (auditor.audit_status === auditConst.status.checked) { %>
+                                                        <span class="pull-right text-success"><i class="fa fa-check-circle"></i></span>
+                                                        <% } if (auditor.audit_status === auditConst.status.checkNo || auditor.audit_status === auditConst.status.checkNoPre || auditor.audit_status === auditConst.status.checkCancel) { %>
+                                                        <span class="pull-right text-warning"><i class="fa fa-share-square fa-rotate-270"></i></span>
+                                                        <% } %>
+                                                    </div>
+                                                    <% if (auditor.opinion) { %>
+                                                    <div class="col-12 py-1 bg-light"><i class="fa fa-commenting-o mr-1"></i><%- auditor.opinion%></div>
+                                                    <% } %>
+                                                </div>
+                                                <% } %>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </li>
+                                <% }) %>
+                            </ul>
+                        </div>
+                        <% }) %>
+                    </div>
+                </div>
+            </div>
+            <form class="modal-footer" method="post" action="audit/start" name="stage-start">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>">
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+                <% if(ctx.safeStage.audit_status === auditConst.status.checkNo && ctx.session.sessionUser.accountId === ctx.safeStage.create_user_id) { %>
+                <button class="btn btn-primary btn-sm sp-list-item" type="submit">确认上报</button>
+                <% } %>
+            </form>
+        </div>
+    </div>
+</div>
+<% } %>
+<% if (ctx.safeStage && (ctx.safeStage.audit_status === auditConst.status.checking || ctx.safeStage.audit_status === auditConst.status.checkNoPre) && ctx.safeStage.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) { %>
+<!--审批通过-->
+<div class="modal fade sp-location-list" id="sp-done" data-backdrop="static">
+    <div class="modal-dialog modal-lg" role="document">
+        <form class="modal-content" action="audit/check" method="post" id="audit-check">
+            <div class="modal-header">
+                <h5 class="modal-title">审批通过</h5>
+            </div>
+            <div class="modal-body">
+                <div class="row">
+                    <div class="col-4">
+                        <% if(ctx.safeStage.audit_status !== auditConst.status.checked && ctx.session.sessionUser.is_admin) { %>
+                        <a class="sp-list-item" href="#sub-sp2" data-toggle="modal" data-target="#sub-sp2" id="hideSp">修改审批流程</a>
+                        <% } %>
+                        <div class="card modal-height-500 mt-3" style="overflow: auto">
+                            <ul class="list-group list-group-flush auditors-list">
+                                <% ctx.safeStage.userGroups.forEach((item, idx) => { %>
+                                <li class="list-group-item d-flex justify-content-between align-items-center">
+                                    <% if (idx === 0) { %>
+                                    <span class="mr-1"><i class="fa fa fa-play-circle fa-rotate-90"></i></span>
+                                    <% } else if (idx === ctx.safeStage.userGroups.length -1 && idx !== 0) { %>
+                                    <span class="mr-1"><i class="fa fa fa-stop-circle"></i></span>
+                                    <% } else { %>
+                                    <span class="mr-1"><i class="fa fa-chevron-circle-down"></i></span>
+                                    <% } %>
+                                    <span class="text-muted">
+                                        <% for (const u of item) { %>
+                                        <small class="d-inline-block text-dark mx-1" title="<%- u.company %>" data-auditorId="<%- u.audit_id %>"><%- u.name %></small>
+                                        <% } %>
+                                    </span>
+                                    <div class="d-flex ml-auto">
+                                        <% if (item[0].audit_type !== auditType.key.common) { %>
+                                        <span class="badge badge-pill badge-<%-  auditType.info[item[0].audit_type].class %> p-1"><small><%- auditType.info[item[0].audit_type].short %></small></span>
+                                        <% } %>
+                                        <span class="badge badge-light badge-pill"><small><%- item.auditName %></small></span>
+                                    </div>
+                                </li>
+                                <% }) %>
+                            </ul>
+                        </div>
+                    </div>
+                    <div class="col-8 modal-height-500" style="overflow: auto">
+                        <% ctx.safeStage.auditHistory.forEach((his, idx) => { %>
+                        <!-- 展开/收起历史流程 -->
+                        <% if(idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>
+                        <div class="text-right"><a href="javascript: void(0);" id="fold-btn" data-target="show">展开历史审批流程</a></div>
+                        <% } %>
+                        <div class="<%- idx < ctx.safeStage.auditHistory.length - 1 ? 'fold-card' : '' %>">
+                            <div class="text-center text-muted"><%- idx+1 %>#</div>
+                            <ul class="timeline-list list-unstyled mt-2 <% if (idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>last-auditor-list<% } %>">
+                                <% his.forEach((group, index) => { %>
+                                <li class="timeline-list-item pb-2 <% if (group.audit_status === auditConst.status.uncheck && idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>is_uncheck<% } %>">
+                                    <% if (group.auditYear) { %>
+                                    <div class="timeline-item-date">
+                                        <%- group.auditYear %>
+                                        <span><%- group.auditDate %></span>
+                                        <span><%- group.auditTime %></span>
+                                    </div>
+                                    <% } %>
+                                    <% if (index < his.length - 1) { %>
+                                    <div class="timeline-item-tail"></div>
+                                    <% } %>
+                                    <% if (group.audit_order === 0) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-caret-down"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checked) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-check"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checkNo || group.audit_status === auditConst.status.checkNoPre || group.audit_status === auditConst.status.checkCancel) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-level-up"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checking) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-ellipsis-h"></i></div>
+                                    <% } else { %>
+                                    <div class="timeline-item-icon bg-secondary text-light"></div>
+                                    <% } %>
+                                    <div class="timeline-item-content">
+                                        <div class="py-1">
+                                            <span class="text-black-50">
+                                                <%- group.auditName %>
+                                                <% if (group.audit_type !== auditType.key.common) { %><span class="text-<%- auditType.info[group.audit_type].class %> "><%- auditType.info[group.audit_type].long %></span><% } %>
+                                            </span>
+                                            <% if (group.audit_order === 0) { %>
+                                            <span class="pull-right text-success"><%- idx !== 0 ? '重新' : '' %>上报审批</span>
+                                            <% } else if (group.audit_status !== auditConst.status.uncheck) { %>
+                                            <span class="pull-right <%- auditConst.info[group.audit_status].class %>"><%- auditConst.info[group.audit_status].title %></span>
+                                            <% } %>
+                                        </div>
+                                        <div class="card">
+                                            <div class="card-body px-3 py-0">
+                                                <% for (const [i, auditor] of group.auditors.entries()) { %>
+                                                <div class="card-text p-2 py-3 row <%- ( i > 0 ? 'border-top' : '') %>">
+                                                    <div class="col-10">
+                                                        <span class="h6"><%- auditor.name %></span>
+                                                        <% if (group.audit_order === 0) { %>
+                                                            <% if (auditor.role && auditor.role.trim()) { %>
+                                                                <span class="text-muted ml-1"><%- auditor.role %></span>
+                                                            <% } %>
+                                                        <% } else { %>
+                                                            <span class="text-muted ml-1">
+                                                                <%- auditor.company %>
+                                                                <% if (auditor.role && auditor.role.trim()) { %>
+                                                                    - <%- auditor.role %>
+                                                                <% } %>
+                                                            </span>
+                                                        <% } %>
+                                                    </div>
+                                                    <div class="col">
+                                                        <% if (auditor.audit_status === auditConst.status.checked) { %>
+                                                        <span class="pull-right text-success"><i class="fa fa-check-circle"></i></span>
+                                                        <% } if (auditor.audit_status === auditConst.status.checkNo || auditor.audit_status === auditConst.status.checkNoPre || auditor.audit_status === auditConst.status.checkCancel) { %>
+                                                        <span class="pull-right text-warning"><i class="fa fa-share-square fa-rotate-270"></i></span>
+                                                        <% } else if (auditor.audit_status === auditConst.status.checking) { %>
+                                                        <span class="pull-right text-warning"><i class="fa fa-commenting"></i></span>
+                                                        <% } %>
+                                                    </div>
+                                                    <% if (auditor.audit_status !== auditConst.status.uncheck && auditor.opinion) { %>
+                                                    <div class="col-12 py-1 bg-light"><i class="fa fa-commenting-o mr-1"></i><%- auditor.opinion%></div>
+                                                    <% } %>
+                                                    <% if (auditor.audit_status === auditConst.status.checking && auditor.audit_id === ctx.session.sessionUser.accountId) { %>
+                                                    <div class="col-12 py-1 bg-light">
+                                                        <textarea class="form-control form-control-sm" name="opinion">同意</textarea>
+                                                    </div>
+                                                    <% } %>
+                                                </div>
+                                                <% } %>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </li>
+                                <% }) %>
+                            </ul>
+                        </div>
+                        <% }) %>
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <input type="hidden" name="checkType" value="<%= auditConst.status.checked %>" />
+                <button type="submit" class="btn btn-success btn-sm">确认通过</button>
+            </div>
+        </form>
+    </div>
+</div>
+<!--审批退回-->
+<div class="modal fade sp-location-list" id="sp-back" data-backdrop="static">
+    <div class="modal-dialog modal-lg" role="document">
+        <form class="modal-content modal-lg" action="audit/check" method="post" id="audit-check-no">
+            <div class="modal-header">
+                <h5 class="modal-title">审批退回</h5>
+            </div>
+            <div class="modal-body">
+                <div class="row">
+                    <div class="col-4">
+                        <% if(ctx.safeStage.audit_status !== auditConst.status.checked && ctx.session.sessionUser.is_admin) { %>
+                        <a class="sp-list-item" href="#sub-sp2" data-toggle="modal" data-target="#sub-sp2" id="hideSp">修改审批流程</a>
+                        <% } %>
+                        <div class="card modal-height-500 mt-3" style="overflow: auto">
+                            <ul class="list-group list-group-flush auditors-list">
+                                <% ctx.safeStage.userGroups.forEach((item, idx) => { %>
+                                <li class="list-group-item d-flex justify-content-between align-items-center">
+                                    <% if (idx === 0) { %>
+                                    <span class="mr-1"><i class="fa fa fa-play-circle fa-rotate-90"></i></span>
+                                    <% } else if (idx === ctx.safeStage.userGroups.length -1 && idx !== 0) { %>
+                                    <span class="mr-1"><i class="fa fa fa-stop-circle"></i></span>
+                                    <% } else { %>
+                                    <span class="mr-1"><i class="fa fa-chevron-circle-down"></i></span>
+                                    <% } %>
+                                    <span class="text-muted">
+                                        <% for (const u of item) { %>
+                                        <small class="d-inline-block text-dark mx-1" title="<%- u.company %>" data-auditorId="<%- u.audit_id %>"><%- u.name %></small>
+                                        <% } %>
+                                    </span>
+                                    <div class="d-flex ml-auto">
+                                        <% if (item[0].audit_type !== auditType.key.common) { %>
+                                        <span class="badge badge-pill badge-<%-  auditType.info[item[0].audit_type].class %> p-1"><small><%- auditType.info[item[0].audit_type].short %></small></span>
+                                        <% } %>
+                                        <span class="badge badge-light badge-pill"><small><%- item.auditName %></small></span>
+                                    </div>
+                                </li>
+                                <% }) %>
+                            </ul>
+                        </div>
+                    </div>
+                    <div class="col-8 modal-height-500" style="overflow: auto">
+                        <% ctx.safeStage.auditHistory.forEach((his, idx) => { %>
+                        <!-- 展开/收起历史流程 -->
+                        <% if(idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>
+                        <div class="text-right"><a href="javascript: void(0);" id="fold-btn" data-target="show" data-idx="<%- idx + 1 %>">展开历史审批流程</a></div>
+                        <% } %>
+                        <div class="<%- idx < ctx.safeStage.auditHistory.length - 1 ? 'fold-card' : '' %>">
+                            <div class="text-center text-muted"><%- idx+1 %>#</div>
+                            <ul class="timeline-list list-unstyled mt-2 <% if (idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>last-auditor-list<% } %>">
+                                <% his.forEach((group, index) => { %>
+                                <li class="timeline-list-item pb-2 <% if (group.audit_status === auditConst.status.uncheck && idx === ctx.safeStage.auditHistory.length - 1 && ctx.safeStage.auditHistory.length !== 1) { %>is_uncheck<% } %>">
+                                    <% if (group.auditYear) { %>
+                                    <div class="timeline-item-date">
+                                        <%- group.auditYear %>
+                                        <span><%- group.auditDate %></span>
+                                        <span><%- group.auditTime %></span>
+                                    </div>
+                                    <% } %>
+                                    <% if (index < his.length - 1) { %>
+                                    <div class="timeline-item-tail"></div>
+                                    <% } %>
+                                    <% if (group.audit_order === 0) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-caret-down"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checked) { %>
+                                    <div class="timeline-item-icon bg-success text-light"><i class="fa fa-check"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checkNo || group.audit_status === auditConst.status.checkNoPre || group.audit_status === auditConst.status.checkCancel) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-level-up"></i></div>
+                                    <% } else if (group.audit_status === auditConst.status.checking) { %>
+                                    <div class="timeline-item-icon bg-warning text-light"><i class="fa fa-ellipsis-h"></i></div>
+                                    <% } else { %>
+                                    <div class="timeline-item-icon bg-secondary text-light"></div>
+                                    <% } %>
+                                    <div class="timeline-item-content">
+                                        <div class="py-1">
+                                            <span class="text-black-50">
+                                                <%- group.auditName %>
+                                                <% if (group.audit_type !== auditType.key.common) { %><span class="text-<%- auditType.info[group.audit_type].class %> "><%- auditType.info[group.audit_type].long %></span><% } %>
+                                            </span>
+                                            <% if (group.audit_order === 0) { %>
+                                            <span class="pull-right text-success"><%- idx !== 0 ? '重新' : '' %>上报审批</span>
+                                            <% } else if (group.audit_status !== auditConst.status.uncheck) { %>
+                                            <span class="pull-right <%- auditConst.info[group.audit_status].class %>"><%- auditConst.info[group.audit_status].title %></span>
+                                            <% } %>
+                                        </div>
+                                        <div class="card">
+                                            <div class="card-body px-3 py-0">
+                                                <% for (const [i, auditor] of group.auditors.entries()) { %>
+                                                <div class="card-text p-2 py-3 row <%- ( i > 0 ? 'border-top' : '') %>">
+                                                    <div class="col-10">
+                                                        <span class="h6"><%- auditor.name %></span>
+                                                        <% if (group.audit_order === 0) { %>
+                                                            <% if (auditor.role && auditor.role.trim()) { %>
+                                                                <span class="text-muted ml-1"><%- auditor.role %></span>
+                                                            <% } %>
+                                                        <% } else { %>
+                                                            <span class="text-muted ml-1">
+                                                                <%- auditor.company %>
+                                                                <% if (auditor.role && auditor.role.trim()) { %>
+                                                                    - <%- auditor.role %>
+                                                                <% } %>
+                                                            </span>
+                                                        <% } %>
+                                                    </div>
+                                                    <div class="col">
+                                                        <% if (auditor.audit_status === auditConst.status.checked) { %>
+                                                        <span class="pull-right text-success"><i class="fa fa-check-circle"></i></span>
+                                                        <% } if (auditor.audit_status === auditConst.status.checkNo || auditor.audit_status === auditConst.status.checkNoPre || auditor.audit_status === auditConst.status.checkCancel) { %>
+                                                        <span class="pull-right text-warning"><i class="fa fa-share-square fa-rotate-270"></i></span>
+                                                        <% } else if (auditor.audit_status === auditConst.status.checking) { %>
+                                                        <span class="pull-right text-warning"><i class="fa fa-commenting"></i></span>
+                                                        <% } %>
+                                                    </div>
+                                                    <% if (auditor.audit_status !== auditConst.status.uncheck && auditor.opinion) { %>
+                                                    <div class="col-12 py-1 bg-light"><i class="fa fa-commenting-o mr-1"></i><%- auditor.opinion%></div>
+                                                    <% } %>
+                                                    <% if (auditor.audit_status === auditConst.status.checking && auditor.audit_id === ctx.session.sessionUser.accountId) { %>
+                                                    <div class="col-12 py-1 bg-light">
+                                                        <textarea class="form-control form-control-sm" name="opinion">不同意</textarea>
+                                                        <div id="reject-process" class="alert alert-warning mt-1 mb-0 p-2">
+                                                            <div class="form-check form-check-inline">
+                                                                <input class="form-check-input" type="radio" name="checkType" id="inlineRadio1" value="<%- auditConst.status.checkNo %>">
+                                                                <label class="form-check-label" for="inlineRadio1">退回原报 <%- ctx.safeStage.user.name %></label>
+                                                            </div>
+                                                            <% if (auditor.audit_order > 1) { %>
+                                                            <div class="form-check form-check-inline">
+                                                                <input class="form-check-input" type="radio" name="checkType" id="inlineRadio2" value="<%- auditConst.status.checkNoPre %>">
+                                                                <label class="form-check-label" for="inlineRadio2">退回上一审批人
+                                                                    <% const pre = his.find(x => { return x.audit_order === auditor.audit_order - 1}); %>
+                                                                    <%- ( pre ? pre.name : '') %>
+                                                                </label>
+                                                            </div>
+                                                            <% } %>
+                                                        </div>
+                                                    </div>
+                                                    <% } %>
+                                                </div>
+                                                <% } %>
+                                            </div>
+                                        </div>
+                                    </div>
+                                </li>
+                                <% }) %>
+                            </ul>
+                        </div>
+                        <% }) %>
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="submit" class="btn btn-warning btn-sm">确认退回</button>
+            </div>
+        </form>
+    </div>
+</div>
+<% } %>
+<% if (ctx.safeStage && ctx.safeStage.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0 && ctx.safeStage.audit_status === auditConst.status.checked && ctx.safeStage.isLatest) { %>
+<% if (!authMobile && ctx.session.sessionUser.loginStatus === 0) { %>
+<!--终审重新审批-->
+<div class="modal fade" id="sp-down-back" data-backdrop="static">
+    <div class="modal-dialog" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">重新审批</h5>
+            </div>
+            <div class="modal-body">
+                <h5>重新审批需要您的手机短信验证</h5>
+                <h5>您目前还没设置认证手机,请先设置。</h5>
+            </div>
+            <div class="modal-footer">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">取消</button>
+                <a href="/profile/sms" class="btn btn-sm btn-primary">去设置</a>
+            </div>
+        </div>
+    </div>
+</div>
+<% } else { %>
+<div class="modal fade" id="sp-down-back" data-backdrop="static">
+    <div class="modal-dialog" role="document">
+        <form class="modal-content" method="post" action="audit/checkAgain" name="stage-checkAgain">
+            <div class="modal-header">
+                <h5 class="modal-title">重新审批</h5>
+            </div>
+            <div class="modal-body">
+                <h5>确认由「终审-<%= ctx.session.sessionUser.name %>」重新审批「第<%= ctx.safeStage.stage_order %>期」?
+                </h5>
+                <% if (ctx.session.sessionUser.loginStatus === 0) { %>
+                <div class="form-group">
+                    <label>重审需要验证码确认,验证码将发送至尾号<%- authMobile.slice(-4) %>的手机</label>
+                    <div class="input-group input-group-sm mb-3">
+                        <input class="form-control" type="text" readonly="readonly" name="code"
+                               placeholder="输入短信中的6位验证码" />
+                        <div class="input-group-append">
+                            <button class="btn btn-outline-secondary" type="button" id="get-code">获取验证码</button>
+                        </div>
+                    </div>
+                </div>
+                <% } %>
+            </div>
+            <div class="modal-footer">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+                <button <% if (ctx.session.sessionUser.loginStatus === 0) { %>disabled<% } %> id="re-shenpi-btn" class="btn btn-warning btn-sm" type="submit">确定重审</button>
+            </div>
+        </form>
+    </div>
+</div>
+<% } %>
+<% } %>
+<% if (ctx.safeStage && ctx.safeStage.create_user_id === ctx.session.sessionUser.accountId && ctx.safeStage.isLatest && (ctx.safeStage.audit_status === auditConst.status.checkNo || ctx.safeStage.audit_status === auditConst.status.uncheck)) { %>
+<div class="modal fade" id="del-qi" data-backdrop="static">
+    <div class="modal-dialog" role="document">
+        <form class="modal-content" action='/sp/<%- ctx.subProject.id %>/safe/tender/<%= ctx.tender.id %>/stage/delete' method="post">
+            <div class="modal-header">
+                <h5 class="modal-title">删除期</h5>
+            </div>
+            <div class="modal-body">
+                <h5>确认删除「第<%= ctx.safeStage.stage_order %>期」?</h5>
+                <h5>删除后,数据无法恢复,请谨慎操作。</h5>
+            </div>
+            <div class="modal-footer">
+                <input type="hidden" name="stage_id" value="<%= ctx.safeStage.id %>">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">取消</button>
+                <button type="submit" class="btn btn-danger btn-sm">确定删除</button>
+            </div>
+        </form>
+    </div>
+</div>
+<% } %>
+<% if (ctx.safeStage && ctx.safeStage.cancancel) { %>
+<div class="modal fade" id="sp-down-cancel" data-backdrop="static">
+    <div class="modal-dialog" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">撤回</h5>
+            </div>
+            <div class="modal-body">
+                <h5>确定撤回?</h5>
+            </div>
+            <form class="modal-footer" action="audit/checkCancel" method="post">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">取消</button>
+                <button type="submit" class="btn btn-danger btn-sm" type="submit">确定撤回</button>
+            </form>
+        </div>
+    </div>
+</div>
+<% } %>
+<% if (ctx.safeStage && ctx.safeStage.audit_status !== auditConst.status.checked && ctx.session.sessionUser.is_admin) { %>
+<!--上报审批-->
+<div class="modal fade" id="sub-sp2" data-backdrop="static">
+    <div class="modal-dialog" style="max-width: 650px" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">修改审批流程</h5>
+            </div>
+            <div class="modal-body">
+                <div class="card mt-1">
+                    <div class="modal-height-500" style="overflow: auto">
+                        <style>
+                            #admin-edit-shenpi thead th {
+                                border-bottom: 0;
+                            }
+                            #admin-edit-shenpi td, #admin-edit-shenpi th {
+                                padding: 0.75rem;
+                            }
+                            #admin-edit-shenpi th {
+                                background: none;
+                                color: #212529;
+                                border-top: 0;
+                            }
+                        </style>
+                        <table class="table table-hover" id="admin-edit-shenpi">
+                            <thead>
+                            <tr class="card-header text-center">
+                                <th width="100px">审批流程</th>
+                                <th>审批人员</th>
+                                <th width="80" style="text-align: center">审批状态</th>
+                                <th width="200" style="text-align: center">操作</th>
+                            </tr>
+                            </thead>
+                            <tbody id="admin-edit-shenpi-list">
+                            <% for (const [i, group] of ctx.safeStage.userGroups.entries()) { %>
+                            <% if (i === 0) continue; %>
+                            <% for (const [j, auditor] of group.entries()) { %>
+                            <tr>
+                                <td class="text-left d-flex">
+                                    <% if (j === 0) { %>
+                                    <%- i + '审' %>
+                                    <% if (auditor.audit_type !== auditType.key.common) { %>
+                                    <span class="ml-2 badge badge-pill badge-<%-  auditType.info[auditor.audit_type].class %> p-1"><small><%- auditType.info[auditor.audit_type].short %></small></span>
+                                    <% } %>
+                                    <% } %>
+                                </td>
+                                <td></span> <%- auditor.name %> <small class="text-muted"><%- auditor.role %></small></td>
+                                <td style="text-align: center"><span class="<%- auditConst.info[auditor.audit_status].class %>"><%- auditor.audit_status !== auditConst.status.uncheck ? auditConst.info[auditor.audit_status].title : '待审批'  %></span></td>
+                                <td style="text-align: center">
+                                    <% if (auditor.audit_status === auditConst.status.checking && j === group.length - 1) { %>
+                                    <span class="dropdown mr-2">
+                                    <a href="javascript: void(0)" class="add-audit" id="<%- auditor.audit_id %>_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">增加</a>
+                                    <div class="dropdown-menu dropdown-menu-right" id="<%- auditor.audit_id %>_add_dropdownMenu" aria-labelledby="<%- auditor.audit_id %>_add_dropdownMenuButton" style="width:220px">
+                                        <div class="mb-2 p-2"><input class="form-control form-control-sm gr-search"
+                                                                     placeholder="姓名/手机 检索" autocomplete="off" data-code="<%- auditor.audit_id %>_add"></div>
+                                        <dl class="list-unstyled book-list" data-aid="<%- auditor.audit_id %>" data-operate="add">
+                                            <% accountGroup.forEach((group, idx) => { %>
+                                            <dt><a href="javascript: void(0);" class="acc-btn" data-groupid="<%- idx %>"
+                                                   data-type="hide"><i class="fa fa-plus-square"></i></a> <%- group.groupName %></dt>
+                                                <div class="dd-content" data-toggleid="<%- idx %>">
+                                                    <% group.groupList.forEach(item => { %>
+                                                    <% if (item.id !== ctx.safeStage.create_user_id) { %>
+                                                    <dd class="border-bottom p-2 mb-0 " data-id="<%- item.id %>">
+                                                                <p class="mb-0 d-flex"><span class="text-primary"><%- item.name %></span><span
+                                                                            class="ml-auto"><%- item.mobile %></span></p>
+                                                                <span class="text-muted"><%- item.role %></span>
+                                                            </dd>
+                                                    <% } %>
+                                                    <% });%>
+                                                </div>
+                                            <% }) %>
+                                        </dl>
+                                    </div>
+                                    </span>
+                                    <% } %>
+                                    <% if (auditor.audit_status === auditConst.status.uncheck) { %>
+                                    <% if (j === group.length - 1) { %>
+                                    <span class="dropdown mr-2">
+                                    <a href="javascript: void(0)" class="add-audit" id="<%- auditor.audit_id %>_add_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">增加</a>
+                                        <div class="dropdown-menu dropdown-menu-right" id="<%- auditor.audit_id %>_add_dropdownMenu" aria-labelledby="<%- auditor.audit_id %>_add_dropdownMenuButton" style="width:220px">
+                                            <div class="mb-2 p-2"><input class="form-control form-control-sm gr-search"
+                                                                         placeholder="姓名/手机 检索" autocomplete="off" data-code="<%- auditor.audit_id %>_add"></div>
+                                            <dl class="list-unstyled book-list" data-aid="<%- auditor.audit_id %>" data-operate="add">
+                                                <% accountGroup.forEach((group, idx) => { %>
+                                                <dt><a href="javascript: void(0);" class="acc-btn" data-groupid="<%- idx %>"
+                                                       data-type="hide"><i class="fa fa-plus-square"></i></a> <%- group.groupName %></dt>
+                                                    <div class="dd-content" data-toggleid="<%- idx %>">
+                                                        <% group.groupList.forEach(item => { %>
+                                                        <% if (item.id !== ctx.safeStage.create_user_id) { %>
+                                                        <dd class="border-bottom p-2 mb-0 " data-id="<%- item.id %>">
+                                                                    <p class="mb-0 d-flex"><span class="text-primary"><%- item.name %></span><span
+                                                                                class="ml-auto"><%- item.mobile %></span></p>
+                                                                    <span class="text-muted"><%- item.role %></span>
+                                                                </dd>
+                                                        <% } %>
+                                                        <% });%>
+                                                    </div>
+                                                <% }) %>
+                                            </dl>
+                                        </div>
+                                    </span>
+                                    <% if (auditor.audit_type !== auditType.key.common) { %>
+                                    <span class="dropdown mr-2">
+                                    <a href="javascript: void(0)" class="add-audit" id="<%- auditor.audit_id %>_add-sibling_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">平级</a>
+                                        <div class="dropdown-menu dropdown-menu-right" id="<%- auditor.audit_id %>_add-sibling_dropdownMenu" aria-labelledby="<%- auditor.audit_id %>_add-sibling_dropdownMenuButton" style="width:220px">
+                                            <div class="mb-2 p-2"><input class="form-control form-control-sm gr-search"
+                                                                         placeholder="姓名/手机 检索" autocomplete="off" data-code="<%- auditor.audit_id %>_add-sibling"></div>
+                                            <dl class="list-unstyled book-list" data-aid="<%- auditor.audit_id %>" data-operate="add-sibling">
+                                                <% accountGroup.forEach((group, idx) => { %>
+                                                <dt><a href="javascript: void(0);" class="acc-btn" data-groupid="<%- idx %>"
+                                                       data-type="hide"><i class="fa fa-plus-square"></i></a> <%- group.groupName %></dt>
+                                                    <div class="dd-content" data-toggleid="<%- idx %>">
+                                                        <% group.groupList.forEach(item => { %>
+                                                        <% if (item.id !== ctx.safeStage.create_user_id) { %>
+                                                        <dd class="border-bottom p-2 mb-0 " data-id="<%- item.id %>">
+                                                                    <p class="mb-0 d-flex"><span class="text-primary"><%- item.name %></span><span
+                                                                                class="ml-auto"><%- item.mobile %></span></p>
+                                                                    <span class="text-muted"><%- item.role %></span>
+                                                                </dd>
+                                                        <% } %>
+                                                        <% });%>
+                                                    </div>
+                                                <% }) %>
+                                            </dl>
+                                        </div>
+                                    </span>
+                                    <% } %>
+                                    <% } %>
+                                    <span class="dropdown mr-2">
+                                        <a href="javascript: void(0)" class="change-audit" id="<%- auditor.audit_id %>_change_dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">更换</a>
+                                        <div class="dropdown-menu dropdown-menu-right" id="<%- auditor.audit_id %>_change_dropdownMenu" aria-labelledby="<%- auditor.audit_id %>_change_dropdownMenuButton" style="width:220px">
+                                            <div class="mb-2 p-2"><input class="form-control form-control-sm gr-search"
+                                                                         placeholder="姓名/手机 检索" autocomplete="off" data-code="<%- auditor.audit_id %>_change"></div>
+                                            <dl class="list-unstyled book-list" data-aid="<%- auditor.audit_id %>" data-operate="change">
+                                                <% accountGroup.forEach((group, idx) => { %>
+                                                <dt><a href="javascript: void(0);" class="acc-btn" data-groupid="<%- idx %>"
+                                                       data-type="hide"><i class="fa fa-plus-square"></i></a> <%- group.groupName %></dt>
+                                                    <div class="dd-content" data-toggleid="<%- idx %>">
+                                                        <% group.groupList.forEach(item => { %>
+                                                        <% if (item.id !== ctx.safeStage.create_user_id) { %>
+                                                        <dd class="border-bottom p-2 mb-0 " data-id="<%- item.id %>">
+                                                                    <p class="mb-0 d-flex"><span class="text-primary"><%- item.name %></span><span
+                                                                                class="ml-auto"><%- item.mobile %></span></p>
+                                                                    <span class="text-muted"><%- item.role %></span>
+                                                                </dd>
+                                                        <% } %>
+                                                        <% });%>
+                                                    </div>
+                                                <% }) %>
+                                            </dl>
+                                        </div>
+                                    </span>
+                                    <span class="dropdown">
+                                    <a href="javascript: void(0)" class="text-danger" title="移除" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">移除</a>
+                                    <div class="dropdown-menu">
+                                        <span class="dropdown-item" href="javascript:void(0);">确认移除审批人?</span>
+                                        <div class="dropdown-divider"></div>
+                                        <div class="px-2 py-1 text-center">
+                                            <button class="remove-audit btn btn-sm btn-danger" data-id="<%- auditor.audit_id %>">移除</button>
+                                            <button class="btn btn-sm btn-secondary">取消</button>
+                                        </div>
+                                    </div>
+                                    </span>
+                                    <% } %>
+                                </td>
+                            </tr>
+                            <% } %>
+                            <% } %>
+                            </tbody>
+                        </table>
+                    </div>
+                </div>
+            </div>
+            <form class="modal-footer">
+                <div class="mr-auto text-warning">
+                    <span class="mr-3">增加:后级审核人</span>
+                    <span class="">平级:会签/或签增加平级审核人</span>
+                </div>
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+            </form>
+        </div>
+    </div>
+</div>
+<% } %>
+<script>
+    const accountGroup = JSON.parse(unescape('<%- escape(JSON.stringify(accountGroup)) %>'));
+    const accountList = JSON.parse(unescape('<%- escape(JSON.stringify(accountList)) %>'));
+    const shenpi_status = <%- ctx.tender.info.shenpi.safe_payment %>;
+    const shenpiConst =  JSON.parse('<%- JSON.stringify(shenpiConst) %>');
+    const createUserId = parseInt('<%= ctx.safeStage.create_user_id %>');
+    const auditType = JSON.parse(unescape('<%- escape(JSON.stringify(auditType)) %>'));
+</script>
+<script>
+    $('[name=stage-start]').submit(function (e) {
+        if (checkAuditorFrom()) {
+            $(this).parent().parent().parent().modal('hide');
+            $('#hide-all').hide();
+        } else {
+            return false;
+        }
+    });
+    $('#audit-check-no').submit(function (e) {
+        const checkType = parseInt($('[name=checkType]:checked').val());
+        if ($('#warning-text').length) $('#warning-text').remove();
+        if (!checkType && !$('#warning-text').length) {
+            $('#reject-process').prepend('<p id="warning-text" style="color: red; margin: 0;">请选择退回流程</p>');
+            return false;
+        }
+        $('#hide-all').hide();
+    });
+
+    $('.sp-location-list').on('shown.bs.modal', function () {
+        const scrollBox = $(this).find('div[class="col-8 modal-height-500"]');
+        const bdiv = (scrollBox.offset() && scrollBox.offset().top) || 0;
+        scrollBox.scrollTop(0);
+        const hdiv = divSearch($(this).find('textarea')) ? $(this).find('textarea') : null;
+        const hdheight = hdiv ? hdiv.parents('.timeline-item-content').offset().top : null;
+        if (hdiv && scrollBox.length && scrollBox[0].scrollHeight > 200 && hdheight - bdiv > 200) {
+            scrollBox.scrollTop(hdheight - bdiv);
+        }
+    });
+    function divSearch(div) {
+        if (div.length > 0) {
+            return true;
+        }
+        return false;
+    }
+
+    // 展开历史审核记录
+    $('.modal-body #fold-btn').click(function () {
+        const type = $(this).data('target')
+        const auditCard = $(this).parent().parent()
+        if (type === 'show') {
+            $(this).data('target', 'hide')
+            auditCard.find('.fold-card').slideDown('swing', () => {
+                auditCard.find('#fold-btn').text('收起历史审核记录')
+            })
+        } else {
+            $(this).data('target', 'show')
+            auditCard.find('.fold-card').slideUp('swing', () => {
+                auditCard.find('#fold-btn').text('展开历史审核记录')
+            })
+        }
+    });
+
+    // 重新审批
+    $('[name=stage-checkAgain]').submit(function (e) {
+        <% if (ctx.session.sessionUser.loginStatus === 0) { %>
+        const code = $("#sp-down-back input[name='code']").val();
+        if ($(this).hasClass('disabled')) return false;
+        if (code.length < 6) {
+            toast('请填写正确的验证码', 'error');
+            return false;
+        }
+        <% } %>
+        $('#hide-all').hide();
+    });
+</script>

+ 113 - 0
app/view/safe_calc/index.ejs

@@ -0,0 +1,113 @@
+<% include ./sub_menu.ejs %>
+<div class="panel-content">
+    <div class="panel-title">
+        <div class="title-main d-flex">
+            <% include ./sub_mini_menu.ejs %>
+            <div>
+                <div class="d-inline-block">
+                    <div class="dropdown">
+                        <button class="btn btn-sm btn-light dropdown-toggle text-primary" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+                            <i class="fa fa-list-ol"></i> 显示层级
+                        </button>
+                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
+                            <a class="dropdown-item" name="showLevel" tag="1" href="javascript: void(0);">第一层</a>
+                            <a class="dropdown-item" name="showLevel" tag="2" href="javascript: void(0);">第二层</a>
+                            <a class="dropdown-item" name="showLevel" tag="3" href="javascript: void(0);">第三层</a>
+                            <a class="dropdown-item" name="showLevel" tag="4" href="javascript: void(0);">第四层</a>
+                            <a class="dropdown-item" name="showLevel" tag="last" href="javascript: void(0);">最底层</a>
+                        </div>
+                    </div>
+                </div>
+                <% if (ctx.safeStage.create_user_id === ctx.session.sessionUser.accountId) { %>
+                <div class="d-inline-block">
+                    <a href="javascript: void(0);" name="base-opr" type="add" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="新增"><i class="fa fa-plus" aria-hidden="true"></i></a>
+                    <a href="javascript: void(0);" name="base-opr" type="delete" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="删除"><i class="fa fa-remove" aria-hidden="true"></i></a>
+                    <a href="javascript: void(0);" name="base-opr" type="up-level" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="升级"><i class="fa fa-arrow-left" aria-hidden="true"></i></a>
+                    <a href="javascript: void(0);" name="base-opr" type="down-level" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="降级"><i class="fa fa-arrow-right" aria-hidden="true"></i></a>
+                    <a href="javascript: void(0);" name="base-opr" type="down-move" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="下移"><i class="fa fa-arrow-down" aria-hidden="true"></i></a>
+                    <a href="javascript: void(0);" name="base-opr" type="up-move" class="btn btn-sm btn-light text-primary" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="上移"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
+                </div>
+                <div class="d-inline-block">
+                    <a href="" class="btn btn-sm btn-light text-primary" data-toggle="modal" data-placement="bottom" title="设置" data-target="#psb-decimal"><i class="fa fa-cog" aria-hidden="true"></i></a>
+                </div>
+                <% } %>
+            </div>
+            <div class="ml-auto">
+            </div>
+        </div>
+    </div>
+    <div class="content-wrap row pr-46">
+        <div class="c-header p-0 col-12">
+        </div>
+        <!--核心内容(两栏)-->
+        <div class="row w-100 sub-content">
+            <!--左栏-->
+            <div class="c-body" id="left-view" style="width: 100%">
+                <div id="bills-spread" class="sjs-height-1"></div>
+            </div>
+            <div class="c-body" id="right-view" style="display: none; width: 33%;">
+                <div class="resize-x" id="right-spr" r-Type="width" div1="#left-view" div2="#right-view" title="调整大小" a-type="percent"><!--调整左右高度条--></div>
+                <div class="tab-content">
+                    <div id="std-gcl" class="tab-pane tab-select-show">
+                    </div>
+                    <div id="fujian" class="tab-pane tab-select-show">
+                        <div class="sjs-bar">
+                            <ul class="nav nav-tabs">
+                                <li class="nav-item">
+                                    <a class="nav-link active" data-toggle="tab" href="#cur-att" role="tab" fujian-content="cur-att">当前节点</a>
+                                </li>
+                                <li class="nav-item">
+                                    <a class="nav-link" data-toggle="tab" href="#all-att" role="tab" fujian-content="all-att">所有附件</a>
+                                </li>
+                                <li class="nav-item ml-auto pt-1">
+                                    <button  id="batch-download-att" class="btn btn-sm btn-primary" type="curr">批量下载</button>
+                                    <!--所有附件 翻页-->
+                                    <span id="showPage" style="display: none"><a href="javascript:void(0);" class="page-select ml-3" content="pre"><i class="fa fa-chevron-left"></i></a> <span id="currentPage">1</span>/<span id="totalPage">10</span> <a href="javascript:void(0);" class="page-select mr-3" content="next"><i class="fa fa-chevron-right"></i></a></span>
+                                    <a href="#upload" data-toggle="modal" data-target="#upload" class="btn btn-sm btn-outline-primary ml-3">上传</a>
+                                </li>
+                            </ul>
+                        </div>
+                        <div class="tab-content">
+                            <div class="tab-pane active" id="cur-att">
+                                <div class="sjs-sh-3" style="overflow:auto; overflow-x:hidden;">
+                                    <table class="table table-sm table-bordered table-hover" style="word-break:break-all; table-layout: fixed">
+                                        <tr><th width="25"><input type="checkbox" class="check-all-file"><th>文件名</th><th width="80">上传</th></tr>
+                                        <tbody id="cur-att-list" class="list-table">
+                                        </tbody>
+                                    </table>
+                                </div>
+                            </div>
+                            <div class="tab-pane" id="all-att">
+                                <div class="sjs-sh-3" style="overflow:auto; overflow-x:hidden;">
+                                    <table class="table table-sm table-bordered table-hover" style="word-break:break-all; table-layout: fixed">
+                                        <tr><th width="25"><input type="checkbox" class="check-all-file"></th><th>文件名</th><th width="80">上传</th></tr>
+                                        <tbody id="all-att-list" class="list-table">
+                                        </tbody>
+                                    </table>
+                                </div>
+                            </div>
+                        </div>
+                    </div>
+                </div>
+            </div>
+        </div>
+        <!--右侧菜单-->
+        <div class="side-menu">
+            <ul class="nav flex-column right-nav" id="side-menu">
+                <li class="nav-item">
+                    <a class="nav-link" content="#std-gcl" href="javascript: void(0);">工程量清单</a>
+                </li>
+                <li class="nav-item">
+                    <a class="nav-link" content="#fujian" href="javascript: void(0);">附件</a>
+                </li>
+            </ul>
+        </div>
+    </div>
+</div>
+<script>
+    const readOnly = <%- ctx.safeStage.readOnly %>;
+    const stdBills = JSON.parse(unescape('<%- escape(JSON.stringify(stdBills)) %>'));
+    const tenderId = parseInt('<%- ctx.tender.id %>');
+    const stageId = parseInt('<%- ctx.safeStage.id %>');
+    const whiteList = JSON.parse('<%- JSON.stringify(ctx.app.config.multipart.whitelist) %>');
+</script>

+ 6 - 24
app/view/safe_calc/modal.ejs

@@ -1,24 +1,6 @@
 <% include ../shares/delete_hint_modal.ejs %>
-<% include ../payment/audit_modal.ejs %>
-<div class="modal fade" id="upload" data-backdrop="static">
-    <div class="modal-dialog" role="document">
-        <div class="modal-content">
-            <div class="modal-header">
-                <h5 class="modal-title">上传附件</h5>
-            </div>
-            <div class="modal-body">
-                <div class="form-group">
-                    <label for="formGroupExampleInput">单个文件大小限制:50MB,支持<span data-toggle="tooltip" data-placement="bottom" title="" data-original-title="doc,docx,xls,xlsx,ppt,pptx,pdf">office等文档格式</span>、<span data-toggle="tooltip" data-placement="bottom" title="" data-original-title="jpg,png,bmp">图片格式</span>、<span data-toggle="tooltip" data-placement="bottom" title="" data-original-title="rar,zip">压缩包格式</span></label>
-                    <input type="file" class="" id="upload-file" multiple>
-                </div>
-            </div>
-            <div class="modal-footer">
-                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
-                <button type="button" class="btn btn-primary btn-sm" id="upload-ok">确认</button>
-            </div>
-        </div>
-    </div>
-</div>
+<% include ./audit_modal.ejs %>
+<% include ../shares/upload_att.ejs %>
 <div class="modal fade show" id="psb-decimal" data-backdrop="static">
     <div class="modal-dialog" role="document">
         <div class="modal-content">
@@ -34,7 +16,7 @@
                                 <div class="input-group-prepend">
                                     <span class="input-group-text">单价</span>
                                 </div>
-                                <input type="number" id="psb-up" class="form-control" value="<%- ctx.detail.decimal.up %>" org="<%- ctx.detail.decimal.up %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.detail.readOnly) { %>disabled<% } %>>
+                                <input type="number" id="psb-up" class="form-control" value="<%- ctx.safeStage.decimal.up %>" org="<%- ctx.safeStage.decimal.up %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.safeStage.readOnly) { %>disabled<% } %>>
                             </div>
                         </div>
                         <div class="col-4">
@@ -42,7 +24,7 @@
                                 <div class="input-group-prepend">
                                     <span class="input-group-text">数量</span>
                                 </div>
-                                <input type="number" id="psb-qty" class="form-control" value="<%- ctx.detail.decimal.qty %>" org="<%- ctx.detail.decimal.qty %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.detail.readOnly) { %>disabled<% } %>>
+                                <input type="number" id="psb-qty" class="form-control" value="<%- ctx.safeStage.decimal.qty %>" org="<%- ctx.safeStage.decimal.qty %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.safeStage.readOnly) { %>disabled<% } %>>
                             </div>
                         </div>
                         <div class="col-4">
@@ -50,7 +32,7 @@
                                 <div class="input-group-prepend">
                                     <span class="input-group-text">金额</span>
                                 </div>
-                                <input type="number" id="psb-tp" class="form-control" value="<%- ctx.detail.decimal.tp %>" org="<%- ctx.detail.decimal.tp %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.detail.readOnly) { %>disabled<% } %>>
+                                <input type="number" id="psb-tp" class="form-control" value="<%- ctx.safeStage.decimal.tp %>" org="<%- ctx.safeStage.decimal.tp %>" min="0" max="6" maxlength="1" oninput="limitDecimal(this)" <% if (ctx.safeStage.readOnly) { %>disabled<% } %>>
                             </div>
                         </div>
                     </div>
@@ -58,7 +40,7 @@
             </div>
             <div class="modal-footer">
                 <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">取消</button>
-                <% if (!ctx.detail.readOnly) { %>
+                <% if (!ctx.safeStage.readOnly) { %>
                 <button type="button" class="btn btn-sm btn-primary" id="psb-decimal-ok">确认</button>
                 <% } %>
             </div>

+ 114 - 0
app/view/safe_calc/stage.ejs

@@ -0,0 +1,114 @@
+<div class="panel-sidebar" id="sub-menu">
+    <div class="sidebar-title" data-toggle="tooltip" data-placement="right" data-original-title="<%- ctx.tender.data.name %>">
+        <%- (ctx.tender.data.name.length > 15 ? ctx.tender.data.name.substring(0,15) + '...' : ctx.tender.data.name) %>
+    </div>
+    <div class="scrollbar-auto">
+        <div class="nav-box">
+            <ul class="nav-list list-unstyled">
+                <li class="active text-center"><a href="/sp/<%- ctx.subProject.id %>/safe/<%- ctx.tender.id %>/stage" class="h3 p-0"><span>各期计量</span></a></li>
+            </ul>
+        </div>
+    </div>
+    <div class="side-show"></div>
+    <div class="side-fold" data-toggle="tooltip" data-placement="top" data-original-title="折叠侧栏" id="to-mini-menu">
+        <i class="fa fa-angle-left"></i>
+    </div>
+</div>
+<div class="panel-content">
+    <div class="panel-title">
+        <div class="title-main d-flex">
+            <!--折起的菜单-->
+            <div class="min-side" id="sub-mini-menu" style="display: none;">
+                <!--<div id="sub-mini-hint" class="side-switch" data-container="body" data-toggle="popover" data-placement="bottom" data-content="这里打开收起的菜单栏"></div>-->
+                <div class="side-switch" data-toggle="tooltip" data-placement="left" data-original-title="点击这里打开收起的菜单栏">
+                    <i class="fa fa-bars mt-2"></i>
+                    <i class="fa fa-indent mt-2 text-primary" style="display: none;cursor: pointer;" id="to-menu"></i>
+                </div>
+                <div class="side-menu" id="mini-menu-list" style="display: none">
+                    <div class="nav-box">
+                        <ul class="nav-list list-unstyled">
+                            <li class="active"><a href="/sp/<%- ctx.subProject.id %>/safe/<%- ctx.tender.id %>/stage" class="h3"><i class="fa fa-pie-chart fa-fw"></i> <span>各期计量</span></a></li>
+                        </ul>
+                    </div>
+                </div>
+            </div>
+            <div>
+            </div>
+            <div class="ml-auto">
+                <% if (stages.length === 0 && ctx.session.sessionUser.is_admin) { %>
+                <a href="#add-qi" data-toggle="modal" data-target="#add-qi" class="btn btn-primary btn-sm">迁移旧数据</a>
+                <% } %>
+                <% if ((stages.length === 0 || stages[0].audit_status === auditConst.status.checked) && ctx.permission.safe_payment.add) { %>
+                <a href="#add-qi" data-toggle="modal" data-target="#add-qi" class="btn btn-primary btn-sm">开始新一期</a>
+                <% } %>
+            </div>
+        </div>
+    </div>
+    <div class="content-wrap">
+        <div class="c-body">
+            <div class="sjs-height-0">
+                <table class="table table-bordered table-hover">
+                    <thead>
+                    <tr>
+                        <th class="text-center" width="80px">期数</th>
+                        <th class="text-center" width="70px">编号</th>
+                        <th class="text-center" width="70px">上报人</th>
+                        <th class="text-center" width="100px">创建时间</th>
+                        <th class="text-center" width="100px">本期</th>
+                        <th class="text-center" width="100px">截止上期</th>
+                        <th class="text-center" width="100px">截止本期</th>
+                        <th class="text-center" width="100px">审批进度</th>
+                        <th class="text-center" width="90px">操作</th>
+                    </tr>
+                    </thead>
+                    <tbody>
+                    <% for (const [i,s] of stages.entries()) { %>
+                    <tr>
+                        <td class="text-center">
+                            <a href="<%- `/sp/${ctx.subProject.id}/safe/tender/${s.tid}/stage/${s.stage_order}/bills` %>" target="_blank">第 <%- s.stage_order %> 期</a>
+                        </td>
+                        <td class="text-center"><%- s.stage_code %></td>
+                        <td class="text-center"><%- s.user_name %></td>
+                        <td class="text-center"><%- s.stage_date %></td>
+                        <td class="text-right"><%- s.bills_tp %></td>
+                        <td class="text-right"><%- s.pre_bills_tp %></td>
+                        <td class="text-right"><%- ctx.helper.add(s.bills_tp, s.end_bills_tp) %></td>
+                        <td class="<%- auditConst.info[s.audit_status].class %>">
+                            <% if (s.audit_status === auditConst.status.checked && s.final_auditor_str) { %>
+                                <a href="#sp-list" data-toggle="modal" data-target="#sp-list" stage-order="<%- s.stage_order %>"><%- s.final_auditor_str %></a>
+                            <% } else { %>
+                                <% if (s.curAuditors.length > 0) { %>
+                                    <% if (s.curAuditors[0].audit_type === auditType.key.common) { %>
+                                        <a href="#sp-list" data-toggle="modal" data-target="#sp-list" stage-order="<%- s.stage_order %>"><%- s.curAuditors[0].name %><%if (s.curAuditors[0].role !== '' && s.curAuditors[0].role !== null) { %>-<%- s.curAuditors[0].role %><% } %></a>
+                                    <% } else { %>
+                                        <a href="#sp-list" data-toggle="modal" data-target="#sp-list" stage-order="<%- s.stage_order %>"><%- ctx.helper.transFormToChinese(s.curAuditors[0].audit_order) + '审' %></a>
+                                    <% } %>
+                                <% } %>
+                            <% } %>
+                            <%- auditConst.info[s.audit_status].title %>
+                        </td>
+                        <td class="text-center">
+                            <% if (s.audit_status === auditConst.status.uncheck && s.create_user_id === ctx.session.sessionUser.accountId) { %>
+                            <a href="<%- `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${s.stage_order}/bills` %>" target="_blank" class="btn <%- auditConst.info[s.audit_status].btnClass %> btn-sm"><%- auditConst.info[s.audit_status].btnTitle %></a>
+                            <% } else if (s.status === auditConst.status.checkNo && s.user_id === ctx.session.sessionUser.accountId) { %>
+                            <a href="<%- `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${s.stage_order}/bills` %>" target="_blank" class="btn <%- auditConst.info[s.audit_status].btnClass %> btn-sm"><%- auditConst.info[s.audit_status].btnTitle %></a>
+                            <% } else if ((s.status === auditConst.status.checking || s.status === auditConst.status.checkNoPre) && s.curAuditors && s.curAuditors.findIndex(x => { return x.aid === ctx.session.sessionUser.accountId; }) >= 0) { %>
+                            <a href="<%- `/sp/${ctx.subProject.id}/safe/tender/${ctx.tender.id}/stage/${s.stage_order}/bills` %>" target="_blank" class="btn <%- auditConst.info[s.audit_status].btnClass %> btn-sm"><%- auditConst.info[s.audit_status].btnTitle %></a>
+                            <% } else { %>
+                            <span class="<%- auditConst.info[s.audit_status].class %>"><%- auditConst.info[s.audit_status].title %></span>
+                            <% } %>
+                            <% if (s.can_del) { %><a href="#del-qi" class="btn btn-outline-danger btn-sm ml-1" data-toggle="modal" data-target="#del-qi">删除</a><% } %>
+                        </td>
+                    </tr>
+                    <% } %>
+                    </tbody>
+                </table>
+            </div>
+        </div>
+    </div>
+</div>
+<script>
+    const stages = JSON.parse('<%- JSON.stringify(stages) %>');
+    const auditType = JSON.parse('<%- JSON.stringify(auditType) %>');
+    const auditConst = JSON.parse('<%- JSON.stringify(auditConst) %>');
+</script>

+ 118 - 0
app/view/safe_calc/stage_modal.ejs

@@ -0,0 +1,118 @@
+<div class="modal" id="add-qi" data-backdrop="static" aria-modal="true" role="dialog">
+    <div class="modal-dialog" role="document">
+        <form class="modal-content" action="stage/add" method="POST" onsubmit="return checkAddValid();">
+            <div class="modal-header">
+                <h5 class="modal-title">添加新一期</h5>
+            </div>
+            <div class="modal-body">
+                <div class="form-group form-group-sm">
+                    <label>期数</label>
+                    <input class="form-control form-control-sm" value="第 <%- (stages.length + 1) %> 期" type="text" readonly="">
+                    <input type="hidden" value="<%- (stages.length + 1) %>" name="stage_order">
+                </div>
+                <div class="form-group form-group-sm">
+                    <label>日期</label>
+                    <input class="datepicker-here form-control form-control-sm" autocomplete="off" name="stage_date" placeholder="点击选择日期" data-view="days" data-min-view="days" data-date-format="yyyy-MM-dd" data-language="zh" type="text">
+                </div>
+                <div class="form-group form-group-sm">
+                    <label>编号</label>
+                    <input type="text" class="form-control form-control-sm" name="stage_code" placeholder="请输入编号" value="">
+                </div>
+            </div>
+            <div class="modal-footer">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">关闭</button>
+                <button type="submit" class="btn btn-sm btn-primary">确定</button>
+            </div>
+        </form>
+    </div>
+</div>
+<div class="modal" id="edit-qi" data-backdrop="static" aria-modal="true" role="dialog">
+    <div class="modal-dialog" role="document">
+        <form class="modal-content" action="pay/save" method="POST" onsubmit="return checkEditValid();">
+            <div class="modal-header">
+                <h5 class="modal-title">编辑</h5>
+            </div>
+            <div class="modal-body">
+                <div class="form-group form-group-sm">
+                    <label>支付期</label>
+                    <input class="form-control form-control-sm" id="edit-name" value="第 <%- (stages.length + 1) %> 期" type="text" readonly="">
+                </div>
+                <div class="form-group form-group-sm">
+                    <label>支付年月</label>
+                    <input class="datepicker-here form-control form-control-sm" id="edit-date" name="date" placeholder="点击选择年月" data-view="months" data-min-view="months" data-date-format="yyyy-MM" data-language="zh" type="text">
+                </div>
+                <div class="form-group form-group-sm">
+                    <label>支付期备注</label>
+                    <textarea class="form-control form-control-sm" rows="3" name="memo"></textarea>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <input type="hidden" value="" name="stage_id">
+                <input type="hidden" name="_csrf_j" value="<%= ctx.csrf %>" />
+                <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">关闭</button>
+                <button type="submit" class="btn btn-sm btn-primary">确定</button>
+            </div>
+        </form>
+    </div>
+</div>
+<!--审批流程/结果-->
+<div class="modal fade" id="sp-list" data-backdrop="static">
+    <div class="modal-dialog modal-lg" role="document">
+        <div class="modal-content">
+            <div class="modal-header">
+                <h5 class="modal-title">审批流程</h5>
+            </div>
+            <div class="modal-body">
+                <div class="row">
+                    <div class="col-4 modal-height-500" style="overflow: auto">
+                        <div class="card mt-3">
+                            <ul class="list-group list-group-flush" id="auditor-list">
+                            </ul>
+                        </div>
+                    </div>
+                    <div class="col-8 modal-height-500" style="overflow: auto" id="audit-list">
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">关闭</button>
+            </div>
+        </div>
+    </div>
+</div>
+<script>
+    $('.datepicker-here').datepicker({
+        autoClose: true,
+    });
+    const checkAddValid = function() {
+        if ($('[name=stage_date]', '#add-qi').val() == '') {
+            toastr.error('请选择日期');
+            return false;
+        }
+        if ($('[name=stage_code]', '#add-qi').val() == '') {
+            toastr.error('请输入编号');
+            return false;
+        }
+    }
+    const checkEditValid = function() {
+        if ($('[name=date]', '#edit-qi').val() == '') {
+            toastr.error('请选择计量年月');
+            return false;
+        }
+    }
+    $('.edit-pay').on('click', function () {
+        const id = $(this).data('id');
+        const stage = stages.find(x => { return x.id === id; });
+        if (!stage) return;
+
+        const editDate = $('#edit-date').datepicker().data('datepicker');
+        $('#edit-name').val('第 ' + stage.stage_order + ' 期');
+        if (stage.stage_date) {
+            editDate.selectDate(new Date(stage.stage_date));
+        }
+        $('[name=memo]', '#edit-qi').html(stage.memo);
+        $('[name=stage_id]', '#edit-qi').val(stage.id);
+        $('#edit-qi').modal('show');
+    })
+</script>

+ 15 - 0
app/view/safe_calc/sub_menu.ejs

@@ -0,0 +1,15 @@
+<div class="panel-sidebar" id="sub-menu">
+    <div class="sidebar-title" data-toggle="tooltip" data-placement="right" data-original-title="<%- ctx.tender.data.name %>">
+        <%- `第${ctx.safeStage.stage_order}期` %> -
+        <%- (ctx.tender.data.name.length > 11 ? ctx.tender.data.name.substring(0,11) + '...' : ctx.tender.data.name) %>
+    </div>
+    <div class="scrollbar-auto">
+        <% include ./sub_menu_list.ejs %>
+        <div class="side-fold"><a href="javascript: void(0)" data-toggle="tooltip" data-placement="top" data-original-title="折叠侧栏" id="to-mini-menu"><i class="fa fa-upload fa-rotate-270"></i></a></div>
+    </div>
+    <script>
+        new Vue({
+            el: '.scrollbar-auto',
+        });
+    </script>
+</div>

+ 5 - 0
app/view/safe_calc/sub_menu_list.ejs

@@ -0,0 +1,5 @@
+<nav-menu title="返回" url="/sp/<%- ctx.subProject.id %>/safe/tender/<%- ctx.tender.id  %>/stage" tclass="text-primary" ml="1" icon="fa-chevron-left"></nav-menu>
+<nav-menu title="安全生产费" url="/sp/<%- ctx.subProject.id %>/safe/tender/<%- ctx.tender.id %>/safe/<%= ctx.safeStage.stage_order %>/bills" ml="3" active="<%= ctx.url.indexOf('bills') %>"></nav-menu>
+<nav-menu title="审核比较" url="/sp/<%- ctx.subProject.id %>/safe/tender/<%- ctx.tender.id %>/safe/<%= ctx.safeStage.stage_order %>/compare" ml="3" active="<%= ctx.url.indexOf('compare') %>"></nav-menu>
+<nav-menu title="输出报表" url="/sp/<%- ctx.subProject.id %>/safe/tender/<%- ctx.tender.id %>/safe/<%= ctx.safeStage.stage_order %>/report" ml="3" active="<%= ctx.url.indexOf('report') %>"></nav-menu>
+<% include ./audit_btn.ejs %>

+ 16 - 0
app/view/safe_calc/sub_mini_menu.ejs

@@ -0,0 +1,16 @@
+<!--折起的菜单-->
+<div class="min-side" id="sub-mini-menu" style="display: none;">
+    <div id="sub-mini-hint" class="side-switch" data-container="body" data-toggle="popover" data-placement="bottom" data-content="这里打开收起的菜单栏"></div>
+    <div class="side-switch">
+        <i class="fa fa-bars"></i>
+    </div>
+    <div class="side-menu" id="mini-menu-list" style="display: none">
+        <% include ./sub_menu_list.ejs %>
+        <div class="side-fold"><a href="javascript: void(0);" data-toggle="tooltip" data-placement="top" data-original-title="展开侧栏" id="to-menu"><i class="fa fa-upload fa-rotate-90"></i></a></div>
+    </div>
+</div>
+<script>
+    new Vue({
+        el: '.side-menu',
+    });
+</script>

+ 60 - 0
config/web.js

@@ -2346,6 +2346,66 @@ const JsFiles = {
                 ],
                 mergeFile: 'safe_tender',
             },
+            stage: {
+                files: [
+                    '/public/js/datepicker/datepicker.min.js',
+                    '/public/js/datepicker/datepicker.zh.js',
+                ],
+                mergeFiles: [
+                    '/public/js/component/menu.js',
+                    '/public/js/sub_menu.js',
+                    '/public/js/safe_stage.js',
+                ],
+                mergeFile: 'safe_stage',
+            },
+            bills: {
+                files: [
+                    '/public/js/js-xlsx/xlsx.full.min.js',
+                    '/public/js/js-xlsx/xlsx.utils.js',
+                    '/public/js/spreadjs/sheets/v11/gc.spread.sheets.all.11.2.2.min.js',
+                    '/public/js/spreadjs/sheets/v11/interop/gc.spread.excelio.11.2.2.min.js',
+                    '/public/js/decimal.min.js',
+                    '/public/js/math.min.js',
+                    '/public/js/axios/axios.min.js', '/public/js/js-xlsx/jszip.min.js',
+                    '/public/js/file-saver/FileSaver.js',
+                    '/public/js/component/menu.js',
+                ],
+                mergeFiles: [
+                    '/public/js/sub_menu.js',
+                    '/public/js/div_resizer.js',
+                    '/public/js/spreadjs_rela/spreadjs_zh.js',
+                    '/public/js/shares/sjs_setting.js',
+                    '/public/js/shares/cs_tools.js',
+                    '/public/js/zh_calc.js',
+                    '/public/js/shares/ali_oss.js',
+                    '/public/js/path_tree.js',
+                    '/public/js/std_lib.js',
+                    '/public/js/shares/tools_att.js',
+                    '/public/js/shares/common_audit.js',
+                    '/public/js/safe_bills.js',
+                ],
+                mergeFile: 'safe_bills',
+            },
+            compare: {
+                files: [
+                    '/public/js/spreadjs/sheets/v11/gc.spread.sheets.all.11.2.2.min.js',
+                    '/public/js/spreadjs/sheets/v11/interop/gc.spread.excelio.11.2.2.min.js',
+                    '/public/js/decimal.min.js',
+                    '/public/js/math.min.js',
+                    '/public/js/component/menu.js',
+                ],
+                mergeFiles: [
+                    '/public/js/sub_menu.js',
+                    '/public/js/spreadjs_rela/spreadjs_zh.js',
+                    '/public/js/shares/sjs_setting.js',
+                    '/public/js/shares/cs_tools.js',
+                    '/public/js/zh_calc.js',
+                    '/public/js/path_tree.js',
+                    '/public/js/shares/common_audit.js',
+                    '/public/js/safe_bills_compare.js',
+                ],
+                mergeFile: 'safe_bills_compare',
+            },
             inspection: {
                 files: [
                     '/public/js/decimal.min.js',

+ 99 - 0
sql/update.sql

@@ -157,6 +157,105 @@ ALTER TABLE `zh_contract`
 ADD COLUMN `remark2` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '' COMMENT '备注2' AFTER `remark`,
 ADD COLUMN `calc` decimal(30, 6) NULL DEFAULT NULL COMMENT '计算1' AFTER `remark2`,
 ADD COLUMN `calc2` decimal(30, 6) NULL DEFAULT NULL COMMENT '计算2' AFTER `calc`;
+
+CREATE TABLE `zh_safe_stage`  (
+  `id` varchar(36) NOT NULL COMMENT 'uuid',
+  `tid` int(11) UNSIGNED NOT NULL COMMENT '标段id',
+  `stage_order` int(11) NOT NULL COMMENT '期序号',
+  `create_user_id` int(11) NOT NULL COMMENT '创建人id',
+  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `update_user_id` int(11) NOT NULL COMMENT '最后修改人id',
+  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间',
+  `stage_date` varchar(20) NOT NULL DEFAULT '' COMMENT '日期',
+  `stage_code` varchar(50) NOT NULL DEFAULT '' COMMENT '编号',
+  `bills_decimal` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '{\"tp\":2, \"up\": 2, \"qty\": 3}' COMMENT '小数位数',
+  `audit_times` tinyint(4) UNSIGNED NOT NULL DEFAULT 1 COMMENT '审批轮次',
+  `audit_status` tinyint(4) UNSIGNED NOT NULL DEFAULT 0 COMMENT '审批状态',
+  `audit_max_sort` tinyint(4) UNSIGNED NOT NULL DEFAULT 0 COMMENT '最大审批排序',
+  `audit_begin_time` timestamp(0) NULL DEFAULT NULL COMMENT '审批开始时间',
+  `audit_end_time` timestamp(0) NULL DEFAULT NULL COMMENT '审批结束时间',
+  `final_auditor_str` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '终审缓存信息',
+  `bills_tp` decimal(24, 8) NOT NULL DEFAULT 0.00000000 COMMENT '本期金额',
+  `pre_bills_tp` decimal(24, 8) NOT NULL DEFAULT 0.00000000 COMMENT '截止上期金额',
+  `memo` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '备注',
+  PRIMARY KEY (`id`)
+);
+
+CREATE TABLE `zh_safe_stage_bills` (
+  `id` varchar(36) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'uuid',
+  `safe_id` varchar(36) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT 'uuid(不同期保持统一)',
+  `tender_id` int(11) unsigned NOT NULL COMMENT '标段id',
+  `stage_id` varchar(36) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '期id',
+  `tree_id` int(11) NOT NULL COMMENT '节点id',
+  `tree_pid` int(11) NOT NULL COMMENT '父节点id',
+  `tree_level` tinyint(4) NOT NULL COMMENT '层级',
+  `tree_order` mediumint(4) NOT NULL COMMENT '同级排序',
+  `tree_full_path` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '层级定位辅助字段parent.full_path.ledger_id',
+  `tree_is_leaf` tinyint(4) unsigned NOT NULL DEFAULT '1' COMMENT '是否叶子节点,界面显示辅助字段',
+  `b_code` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '编号',
+  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '名称',
+  `unit` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '单位',
+  `spec` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '规格',
+  `unit_price` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '单价',
+  `pre_qty` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '截止上期数量',
+  `pre_tp` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '截止上期金额',
+  `cur_qty` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '本期数量',
+  `cur_tp` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '本期金额',
+  `end_qty` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '截止本期数量',
+  `end_tp` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '截止本期金额',
+  `invoice_code` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '发票号',
+  `memo` varchar(1000) COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '备注',
+  `add_user_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建人',
+  `add_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `update_user_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '最后编辑人',
+  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后编辑时间',
+  `cur_read_qty` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '本期数量-只读',
+  `cur_read_tp` decimal(24,8) NOT NULL DEFAULT '0.00000000' COMMENT '本期金额-只读',
+  `cur_his` json DEFAULT NULL COMMENT '本期历史',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
+
+CREATE TABLE `zh_safe_stage_audit`  (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `tid` int(11) UNSIGNED NOT NULL COMMENT '标段id',
+  `stage_id` varchar(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '期id',
+  `audit_id` int(11) UNSIGNED NOT NULL COMMENT '流程参与人id(含原报)',
+  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '参与人-姓名',
+  `company` varchar(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '参与人-单位',
+  `role` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '参与人-角色',
+  `mobile` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '参与人-电话',
+  `audit_times` int(11) UNSIGNED NOT NULL DEFAULT 1 COMMENT '审批次数',
+  `audit_order` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '预定流程顺序',
+  `audit_type` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '流程类型',
+  `active_order` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '实际流程顺序',
+  `audit_status` int(11) UNSIGNED NOT NULL DEFAULT 0 COMMENT '流程状态',
+  `audit_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '流程结束时间',
+  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
+  `opinion` varchar(1000) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '意见',
+  PRIMARY KEY (`id`) USING BTREE
+) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
+
+CREATE TABLE `zh_safe_stage_file`  (
+  `id` varchar(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'uuid',
+  `tid` int(11) UNSIGNED NOT NULL COMMENT '标段id',
+  `stage_id` varchar(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '期stage_id(zh_safe_stage.id)',
+  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '类型(bills/...)',
+  `rela_id` varchar(36) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'uuid(zh_safe_stage_bills.id/...)',
+  `filename` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '文件名',
+  `fileext` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '文件后缀',
+  `filesize` int(11) NOT NULL COMMENT '文件大小',
+  `filepath` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '文件存储路径',
+  `user_id` int(11) UNSIGNED NOT NULL COMMENT '用户id(zh_project_account.id)',
+  `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '' COMMENT '用户名(缓存)',
+  `user_company` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '公司(缓存)',
+  `user_role` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT '角色(缓存)',
+  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间',
+  `is_deleted` tinyint(4) UNSIGNED NOT NULL DEFAULT 0 COMMENT '是否删除',
+  PRIMARY KEY (`id`) USING BTREE
+) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
+
 ------------------------------------
 -- 表数据
 ------------------------------------