| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087 | 'use strict';/** * 登录页面控制器 * * @author CaiAoLin * @date 2017/11/15 * @version */const URL = require('url');const maintainConst = require('../const/maintain');const auditConst = require('../const/audit');const changeConst = require('../const/change');const advanceConst = require('../const/advance');const fs = require('fs');const path = require('path');const sendToWormhole = require('stream-wormhole');const moment = require('moment');const auditType = require('../const/audit').auditType;module.exports = app => {    class WapController extends app.BaseController {        /**         * 登录页面         *         * @param {Object} ctx - egg全局页面         * @return {void}         */        async index(ctx) {            if (!ctx.helper.isMobile(ctx.request.header['user-agent'])) {                ctx.redirect('/');                return;            }            const errorMessage = ctx.session.loginError;            // 显示完删除            ctx.session.loginError = null;            // 获取系统维护信息            const maintainData = await ctx.service.maintain.getDataById(1);            if (!ctx.app.config.is_debug) {                await ctx.service.maintain.syncMaintainData();            }            let projectData = '';            if (ctx.session.wapTenderID) {                const tenderData = await ctx.service.tender.getDataById(ctx.session.wapTenderID);                if (tenderData) projectData = await ctx.service.project.getDataById(tenderData.project_id);            }            const renderData = {                maintainData,                maintainConst,                errorMessage,                projectData,            };            await ctx.render('wap/login.ejs', renderData);        }        /**         * 登录操作         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async login(ctx) {            let loginType = ctx.request.body.type;            try {                loginType = parseInt(loginType);                const result = await ctx.service.projectAccount.accountLogin(ctx.request.body, loginType);                if (!result) {                    throw '用户名或密码错误';                }                if (result === 2) {                    // 判断是否有设置停用提示,有则展示                    const msg = await ctx.service.projectStopmsg.getMsg(ctx.session.sessionProject.id);                    throw msg;                }                // 调用 rotateCsrfSecret 刷新用户的 CSRF token                ctx.rotateCsrfSecret();                // 判断是否已经有对应用户信息,没有则跳转初始化页面                const needBoot = await ctx.service.customer.isNeedBoot(ctx.request.body);                const url = needBoot ? '/boot' : '/wap/dashboard';                const query = URL.parse(ctx.request.header.referer, true).query;                let referer = '';                if (ctx.session.wapTenderID) {                    referer = query.referer ? query.referer + '#shenpi' : url;                    ctx.session.wapTenderID = null;                }                ctx.redirect(referer ? referer : url);            } catch (error) {                this.log(error);                ctx.session.loginError = error;                ctx.redirect('/wap');            }        }        /**         * 退出登录         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async logout(ctx) {            // 删除session并跳转            ctx.session = null;            ctx.redirect('/wap');        }        /**         * 待办页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async dashboard(ctx) {            // 获取待审批的期            const auditStages = await ctx.service.stageAudit.getAuditStageByWap(ctx.session.sessionUser.accountId);            const subProjects = [];            for (const audit of auditStages) {                if (audit.status !== auditConst.stage.status.uncheck) {                    const isLastage = await ctx.service.stage.isLastStage(audit.tid, audit.id);                    if (isLastage) await this.ctx.service.stage.checkStageGatherData(audit);                }                audit.gather_tp = ctx.helper.sum([audit.contract_tp, audit.qc_tp, audit.pc_tp]);                audit.end_contract_tp = ctx.helper.sum([audit.contract_tp, audit.pre_contract_tp, audit.contract_pc_tp]);                audit.end_qc_tp = ctx.helper.sum([audit.qc_tp, audit.pre_qc_tp, audit.qc_pc_tp]);                audit.pre_gather_tp = ctx.helper.add(audit.pre_contract_tp, audit.pre_qc_tp);                audit.end_gather_tp = ctx.helper.add(audit.gather_tp, audit.pre_gather_tp);                let sp = null;                if (audit.spid) {                    if (ctx.helper._.findIndex(subProjects, { id: audit.spid }) !== -1) {                        sp = ctx.helper._.find(subProjects, { id: audit.spid });                    } else {                        sp = await ctx.service.subProject.getDataById(audit.spid);                        subProjects.push(sp);                    }                }                if (sp) {                    const pageShow = JSON.parse(sp.page_show);                    audit.closeWapYfSf = pageShow.closeWapYfSf || 0;                } else {                    audit.closeWapYfSf = 0;                }            }            // 获取待审批的变更期            const auditChanges = await ctx.service.changeAudit.getAuditChangeByWap(ctx.session.sessionUser.accountId);            // 获取待审批的变更立项            const auditChangeProjects = [];            const changeProjects = await ctx.service.changeProjectAudit.getAuditChangeProjectByWap(ctx.session.sessionUser.accountId);            for (const cp of changeProjects) {                let sp = null;                if (cp.spid) {                    if (ctx.helper._.findIndex(subProjects, { id: cp.spid }) !== -1) {                        sp = ctx.helper._.find(subProjects, { id: cp.spid });                    } else {                        sp = await ctx.service.subProject.getDataById(cp.spid);                        subProjects.push(sp);                    }                }                if (sp) {                    const pageShow = JSON.parse(sp.page_show);                    if (pageShow.openChangeProject) {                        auditChangeProjects.push(cp);                    }                } else {                    auditChangeProjects.push(cp);                }            }            // 获取待审批的变更申请            const auditChangeApplys = [];            const changeApplys = await ctx.service.changeApplyAudit.getAuditChangeApplyByWap(ctx.session.sessionUser.accountId);            for (const ca of changeApplys) {                let sp = null;                if (ca.spid) {                    if (ctx.helper._.findIndex(subProjects, { id: ca.spid }) !== -1) {                        sp = ctx.helper._.find(subProjects, { id: ca.spid });                    } else {                        sp = await ctx.service.subProject.getDataById(ca.spid);                        subProjects.push(sp);                    }                }                if (sp) {                    const pageShow = JSON.parse(sp.page_show);                    if (pageShow.openChangeApply) {                        auditChangeApplys.push(ca);                    }                } else {                    auditChangeApplys.push(ca);                }            }            // 获取待审批的变更方案            const auditChangePlans = [];            const changePlans = await ctx.service.changePlanAudit.getAuditChangePlanByWap(ctx.session.sessionUser.accountId);            for (const cp of changePlans) {                let sp = null;                if (cp.spid) {                    if (ctx.helper._.findIndex(subProjects, { id: cp.spid }) !== -1) {                        sp = ctx.helper._.find(subProjects, { id: cp.spid });                    } else {                        sp = await ctx.service.subProject.getDataById(cp.spid);                        subProjects.push(sp);                    }                }                if (sp) {                    const pageShow = JSON.parse(sp.page_show);                    if (pageShow.openChangePlan) {                        auditChangePlans.push(cp);                    }                } else {                    auditChangePlans.push(cp);                }            }            // 获取待审批的台账修订            const auditRevise = await ctx.service.reviseAudit.getAuditReviseByWap(ctx.session.sessionUser.accountId);            for (const revise of auditRevise) {                const yb_audit = await ctx.service.projectAccount.getAccountInfoById(revise.audit_id);                revise.yb_name = yb_audit.name;            }            // 获取待审批的预付款            const auditAdvance = await ctx.service.advanceAudit.getAuditAdvanceByWap(ctx.session.sessionUser.accountId);            const renderData = {                auditStages,                auditChanges,                auditChangeProjects,                auditChangeApplys,                auditChangePlans,                auditRevise,                auditAdvance,                changeConst,                advanceConst,                tpUnit: 2,            };            await ctx.render('wap/dashboard.ejs', renderData);        }        /**         * 标段列表页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async list(ctx) {            try {                // 获取用户新建标段权利                const accountInfo = await this.ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                const userPermission = accountInfo !== undefined && accountInfo.permission !== '' ? JSON.parse(accountInfo.permission) : null;                const tenderList = await this.ctx.service.tender.getBuildList('', userPermission);                for (const t of tenderList) {                    await this.ctx.service.tenderCache.loadTenderCache(t, this.ctx.session.sessionUser.accountId);                }                const categoryData = await this.ctx.service.category.getAllCategory(ctx.subProject);                const valuations = await this.ctx.service.valuation.getProjectValidValuation(this.ctx.session.sessionProject.id);                const renderData = {                    tenderList,                    categoryData,                    auditConst,                    userPermission,                    valuations,                    uid: this.ctx.session.sessionUser.accountId,                    pid: this.ctx.session.sessionProject.id,                };                await ctx.render('wap/list.ejs', renderData);            } catch (err) {                this.log(err);                this.ctx.redirect('/wap/dashboard');            }        }        /**         * 标段详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async tender(ctx) {            try {                const tender = ctx.tender.data;                if (tender.user_id === this.ctx.session.sessionUser.accountId && (                    tender.ledger_status === auditConst.ledger.status.checkNo || tender.ledger_status === auditConst.ledger.status.uncheck)) {                    const sum = await this.ctx.service.ledger.addUp({tender_id: tender.id/*, is_leaf: true*/});                    tender.total_price = sum.total_price;                    tender.deal_tp = sum.deal_tp;                }                const [change_tp, change_p_tp, change_n_tp, change_valuation_tp, change_unvaluation_tp] = await ctx.service.change.getChangeTp(ctx.tender.id);                tender.change_tp = change_tp;                tender.change_p_tp = change_p_tp;                tender.change_n_tp = change_n_tp;                tender.change_valuation_tp = change_valuation_tp;                tender.change_unvaluation_tp = change_unvaluation_tp;                const stages = await ctx.service.stage.getValidStages(ctx.tender.id);                const lastStage = stages.length > 0 ? stages[0] : null; //await ctx.service.stage.getLastestStage(ctx.tender.id);                if (lastStage) {                    await this.ctx.service.stage.checkStageGatherData(lastStage);                    tender.gather_tp = ctx.helper.sum([lastStage.contract_tp, lastStage.qc_tp, lastStage.pc_tp]);                    tender.end_contract_tp = ctx.helper.sum([lastStage.contract_tp, lastStage.pre_contract_tp, lastStage.contract_pc_tp]);                    tender.end_qc_tp = ctx.helper.sum([lastStage.qc_tp, lastStage.pre_qc_tp, lastStage.qc_pc_tp]);                    tender.pre_gather_tp = ctx.helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);                    tender.end_gather_tp = ctx.helper.add(tender.gather_tp, tender.pre_gather_tp);                    tender.yf_tp = lastStage.yf_tp;                    tender.qc_ratio = ctx.helper.mul(ctx.helper.div(tender.end_qc_tp, ctx.tender.info.deal_param.contractPrice, 2), 100);                    tender.sum = ctx.helper.add(tender.total_price, tender.change_tp);                    tender.pre_ratio = ctx.helper.mul(ctx.helper.div(tender.pre_gather_tp, tender.sum, 2), 100);                    tender.cur_ratio = ctx.helper.mul(ctx.helper.div(tender.gather_tp, tender.sum, 2), 100);                    tender.other_tp = ctx.helper.sub(ctx.helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);                    tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);                }                const monthProgress = [];                for (const s of stages) {                    if (s.s_time) {                        let progress = monthProgress.find(function(x) {                            return x.month === s.s_time;                        });                        if (!progress) {                            progress = { month: s.s_time };                            monthProgress.push(progress);                        }                        progress.tp = ctx.helper.add(ctx.helper.add(progress.tp, s.contract_tp), s.qc_tp);                    }                }                monthProgress.sort(function(x, y) {                    return Date.parse(x.month) - Date.parse(y.month);                });                let sum = 0;                for (const p of monthProgress) {                    p.ratio = ctx.helper.mul(ctx.helper.div(p.tp, tender.sum, 4), 100);                    sum = ctx.helper.add(sum, p.tp);                    p.end_tp = sum;                    p.end_ratio = ctx.helper.mul(ctx.helper.div(p.end_tp, tender.sum, 4), 100);                }                // 台账修订列表                const revises = await ctx.service.ledgerRevise.getReviseList(ctx.tender.id);                for (const lr of revises) {                    if (lr.valid) {                        lr.curAuditor = await ctx.service.reviseAudit.getAuditorByStatus(lr.id, lr.status, lr.times);                    }                }                // 预付款期数获取                const advanceList = [];                for (const t of advanceConst.typeCol) {                    const advance = await ctx.service.advance.getLastestAdvance(ctx.tender.id, t.type, true);                    advanceList.push(advance);                }                const renderData = {                    tender,                    stages,                    revises,                    advanceList,                    auditConst: auditConst.stage,                    auditReviseConst: auditConst.revise,                    advanceConst,                    tpUnit: ctx.tender.info.decimal.tp,                    monthProgress,                    stagesEcharts: JSON.parse(JSON.stringify(stages)).reverse(),                    auditType: auditConst.auditType,                };                if (stages.length > 0) {                    for (const s of stages) {                        // s.curAuditor = null;                        // 根据期状态返回展示用户                        s.curAuditors = await ctx.service.stageAudit.getAuditorsByStatus(s.id, s.status, s.times);                        if (s.status === auditConst.stage.status.checkNoPre) {                            s.curAuditors2 = await ctx.service.stageAudit.getAuditorsByStatus(s.id, auditConst.stage.status.checking);                        }                    }                    renderData.stage = stages[0];                    const times = renderData.stage.status === auditConst.stage.status.checkNo ? renderData.stage.times - 1 : renderData.stage.times;                    renderData.stage.user = await ctx.service.projectAccount.getAccountInfoById(renderData.stage.user_id);                    renderData.stage.auditors = await ctx.service.stageAudit.getAuditors(renderData.stage.id, times);                    // 获取审批流程中左边列表                    renderData.stage.auditors2 = await ctx.service.stageAudit.getAuditGroupByList(renderData.stage.id, times);                }                await ctx.render('wap/tender.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 期审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async stage(ctx) {            try {                const tender = ctx.tender.data;                // const stages = await ctx.service.stage.getValidStages(ctx.tender.id);                // const lastStage = stages.length > 0 ? stages[0] : null;                // if (lastStage) {                //     await this.ctx.service.stage.checkStageGatherData(lastStage);                // }                const stage = ctx.stage;                if (stage) {                    if (stage.status !== auditConst.stage.status.checked) await this.ctx.service.stage.checkStageGatherData(stage);                    stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);                    stage.pre_tp = this.ctx.helper.add(stage.pre_contract_tp, stage.pre_qc_tp);                    stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);                }                await ctx.service.stage.loadStageAuditViewData(stage);                const renderData = {                    moment,                    tender,                    stage,                    auditConst: auditConst.stage,                    auditType,                };                // const times = renderData.stage.status === auditConst.stage.status.checkNo ? renderData.stage.times - 1 : renderData.stage.times;                // renderData.stage.user = await ctx.service.projectAccount.getAccountInfoById(renderData.stage.user_id);                // renderData.stage.auditors = await ctx.service.stageAudit.getAuditors(renderData.stage.id, times);                // // 获取审批流程中左边列表                // renderData.stage.auditors2 = await ctx.service.stageAudit.getAuditGroupByList(renderData.stage.id, times);                renderData.stage.lastAuditors = await ctx.service.stageAudit.getAuditorsByStatus(stage.id, stage.status, stage.times);                await ctx.render('wap/shenpi_stage.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 工程变更列表页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async changeIndex(ctx) {            try {                // 变更令列表                const changes = await ctx.service.change.getListByStatus(ctx.tender.id, 0, 0);                for (const c of changes) {                    c.showApprovalBtn = false;                    c.curAuditors = await ctx.service.changeAudit.getAuditorsByStatus(c.cid, c.status, c.times);                    if (c.status === auditConst.change.status.checkNoPre) {                        c.curAuditors2 = await ctx.service.changeAudit.getAuditorsByStatus(c.cid, auditConst.change.status.checking, c.times);                        const curAudit = c.curAuditors2.find(function(x) {                            return x.uid === ctx.session.sessionUser.accountId;                        });                        if (curAudit && curAudit.status === auditConst.change.status.checking) {                            c.showApprovalBtn = true;                        }                    } else {                        const curAudit = c.curAuditors.find(function(x) {                            return x.uid === ctx.session.sessionUser.accountId;                        });                        if (curAudit && curAudit.status === auditConst.change.status.checking) {                            c.showApprovalBtn = true;                        }                    }                }                // 变更立项列表                let changeProjects = [];                if (ctx.subProject.page_show.openChangeProject) {                    changeProjects = await ctx.service.changeProject.getListByStatus(ctx.tender.id, 0, 0);                    for (const c of changeProjects) {                        c.showApprovalBtn = false;                        c.curAuditors = await ctx.service.changeProjectAudit.getAuditorsByStatus(c.id, c.status, c.times);                        const curAudit = c.curAuditors.find(function(x) {                            return x.uid === ctx.session.sessionUser.accountId;                        });                        if (curAudit && curAudit.status === auditConst.changeProject.status.checking) {                            c.showApprovalBtn = true;                        }                    }                }                // 变更申请列表                let changeApplys = [];                if (ctx.subProject.page_show.openChangeApply) {                    changeApplys = await ctx.service.changeApply.getListByStatus(ctx.tender.id, 0, 0);                    for (const c of changeApplys) {                        c.showApprovalBtn = false;                        c.curAuditors = await ctx.service.changeApplyAudit.getAuditorsByStatus(c.id, c.status, c.times);                        const curAudit = c.curAuditors.find(function(x) {                            return x.uid === ctx.session.sessionUser.accountId;                        });                        if (curAudit && curAudit.status === auditConst.changeApply.status.checking) {                            c.showApprovalBtn = true;                        }                    }                }                // 变更方案列表                let changePlans = [];                if (ctx.subProject.page_show.openChangePlan) {                    changePlans = await ctx.service.changePlan.getListByStatus(ctx.tender.id, 0, 0);                    for (const c of changePlans) {                        c.showApprovalBtn = false;                        c.curAuditors = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, c.status, c.times);                        const curAudit = c.curAuditors.find(function(x) {                            return x.uid === ctx.session.sessionUser.accountId;                        });                        if (curAudit && curAudit.status === auditConst.changePlan.status.checking) {                            c.showApprovalBtn = true;                        }                    }                }                const renderData = {                    tender: ctx.tender,                    changes,                    changeProjects,                    changeApplys,                    changePlans,                    auditChangeConst: auditConst.change,                    auditChangeProjectConst: auditConst.changeProject,                    auditChangeApplyConst: auditConst.changeApply,                    auditChangePlanConst: auditConst.changePlan,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                    auditType: auditConst.auditType,                };                await ctx.render('wap/shenpi_change_index.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 变更审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async change(ctx) {            try {                const tender = ctx.tender.data;                const change = ctx.change;                const times = change.status !== auditConst.change.status.checkNo && change.status !== auditConst.change.status.revise ? change.times : change.times - 1;                const auditList = await ctx.service.changeAudit.getListOrderByTimes(change.cid, times);                const auditGroupList = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);                await ctx.service.change.loadChangeAuditViewData(ctx.change);                const renderData = {                    moment,                    tender,                    change,                    auditList,                    auditGroupList,                    auditConst: auditConst.change,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                    auditType,                };                await ctx.render('wap/shenpi_change.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 变更立项审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async changeProject(ctx) {            try {                const tender = ctx.tender.data;                const change = ctx.change;                await ctx.service.changeProject.loadChangeAuditViewData(ctx.change);                const renderData = {                    moment,                    tender,                    change,                    auditConst: auditConst.changeProject,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                    auditType,                };                await ctx.render('wap/shenpi_change_project.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 变更申请审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async changeApply(ctx) {            try {                const tender = ctx.tender.data;                const change = ctx.change;                await ctx.service.changeApply.loadChangeAuditViewData(ctx.change);                const renderData = {                    moment,                    tender,                    change,                    auditConst: auditConst.changeApply,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                    auditType,                };                await ctx.render('wap/shenpi_change_apply.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 变更方案审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async changePlan(ctx) {            try {                const tender = ctx.tender.data;                const change = ctx.change;                await ctx.service.changePlan.loadChangeAuditViewData(ctx.change);                const renderData = {                    moment,                    tender,                    change,                    auditConst: auditConst.changeApply,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                    auditType,                };                await ctx.render('wap/shenpi_change_plan.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 修订审批详细页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async revise(ctx) {            try {                const tender = ctx.tender.data;                const revise = await ctx.service.ledgerRevise.getDataByCondition({ id: ctx.params.rid });                revise.user = await ctx.service.projectAccount.getAccountInfoById(revise.uid);                const times = revise.status === auditConst.revise.status.checkNo ? revise.times - 1 : revise.times;                revise.curAuditor = await ctx.service.reviseAudit.getAuditorByStatus(revise.id, revise.status, times);                revise.auditors = await ctx.service.reviseAudit.getAuditors(revise.id, times);                console.log(times, revise.auditors);                const renderData = {                    tender,                    revise,                    auditConst: auditConst.revise,                };                await ctx.render('wap/shenpi_revise.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 预付款列表页         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        async advance(ctx) {            try {                const tender = ctx.tender.data;                const { decimal } = ctx.tender.info;                this.decimal = decimal.pay ? decimal.payTp : decimal.tp;                const advancePayTotalList = [];                const advanceList = [];                for (const t of advanceConst.typeCol) {                    const advancePayTotal = ctx.tender.info.deal_param[t.key + 'Advance'];                    advancePayTotalList.push(advancePayTotal);                    const advances = await ctx.service.advance.getAdvanceList(ctx.tender.id, t.type, this.decimal, advancePayTotal);                    advanceList.push(advances);                }                const renderData = {                    tender,                    advancePayTotalList,                    advanceList,                    auditConst: auditConst.advance,                    advanceConst,                };                await ctx.render('wap/shenpi_advance.ejs', renderData);            } catch (err) {                this.log(err);                ctx.redirect('/wap/list');            }        }        /**         * 预付款详情页 GET         * @param {Object} ctx 全局上下文         */        async advanceDetail(ctx) {            try {                const tender = ctx.tender.data;                ctx.advance.advancePayTotal = ctx.tender.info.deal_param[ advanceConst.typeCol[ctx.advance.type].key + 'Advance'];                const times = ctx.advance.status === auditConst.advance.status.checkNo ? ctx.advance.times - 1 : ctx.advance.times;                if (ctx.advance.status === auditConst.advance.status.checkNo) {                    ctx.advance.curAuditor = await ctx.service.advanceAudit.getAuditorByStatus(ctx.advance.id, ctx.advance.status, times);                    ctx.advance.auditors = await ctx.service.advanceAudit.getAuditors(ctx.advance.id, times);                }                // 获取审批流程中左边列表                ctx.advance.auditors2 = await ctx.service.advanceAudit.getAuditGroupByList(ctx.advance.id, times);                const renderData = {                    tender,                    advance: ctx.advance,                    auditConst: auditConst.advance,                    advanceConst,                };                await ctx.render('wap/shenpi_advance_detail.ejs', renderData);            } catch (error) {                this.log(error);                ctx.redirect('/wap/tender/' + ctx.tender.id + '/advance');            }        }        /**         * 变更令审批         * @param {Object} ctx - egg全局变量         * @return {void}         */        async changeApproval(ctx) {            try {                const cid = ctx.request.body.change_id;                const changeData = await ctx.service.change.getDataByCondition({ cid });                if (!changeData) {                    throw '变更令数据错误';                }                // 判断是否到你审批,如果不是则无法审批                const curAuditor = await ctx.service.changeAudit.getCurAuditors(changeData.cid, changeData.times);                if (!curAuditor || (curAuditor && ctx.helper._.findIndex(curAuditor, { uid: ctx.session.sessionUser.accountId }) === -1)) {                    throw '该变更令当前您无权操作';                }                const readySettle = await ctx.service.settle.getReadySettle(changeData.tid);                if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {                    throw '结算数据发生变化,请刷新页面再提交';                }                const status = parseInt(ctx.request.body.status);                const pid = this.ctx.session.sessionProject.id;                let result = false;                switch (status) {                    case 3:// 审批通过                        result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);                        break;                    // case 4:// 审批终止                    //     result = await ctx.service.change.approvalStop(ctx.request.body);                    //     break;                    case 5:// 审批退回到原报人                        result = await ctx.service.change.approvalCheckNo(pid, ctx.request.body, changeData);                        break;                    case 6:// 审批退回到上一个审批人                        result = await ctx.service.change.approvalCheckNoPre(pid, ctx.request.body, changeData);                        break;                    default:break;                }                if (!result) {                    throw '审批失败';                }                ctx.redirect(ctx.request.header.referer);            } catch (err) {                console.log(err);                ctx.redirect(ctx.request.header.referer);            }        }        /**         * 收方单附件上传页         * @param {Object} ctx - egg全局变量         * @return {void}         */        async shoufangUpload(ctx) {            try {                const tid = parseInt(ctx.query.tid) || 0;                const order = parseInt(ctx.query.order) || 0;                const sfid = parseInt(ctx.query.sfid) || 0;                if (!tid || !order || !sfid) {                    throw '参数有误';                }                const tender = await ctx.service.tender.getDataById(tid);                if (!tender) {                    throw '该标段不存在';                }                const sfInfo = await ctx.service.stageShoufang.getDataByCondition({ id: sfid, tid, order });                if (!sfInfo) {                    throw '该收方单不存在';                }                // 查找对应的台账或计量单元名称                const ledger = await ctx.service.ledger.getData(tid);                const ledgerInfo = ctx.helper._.find(ledger, { id: sfInfo.lid });                let name = ledgerInfo.b_code;                if (sfInfo.pid) {                    const pos = await ctx.service.pos.getPosData({ tid });                    const posInfo = ctx.helper._.find(pos, { lid: sfInfo.lid, id: sfInfo.pid });                    name += ' / ' + posInfo.name;                }                const renderData = {                    tender,                    order,                    name,                    sfid,                    whiteList: this.ctx.app.config.multipart.whitelist,                };                await ctx.render('wap/shoufangupload.ejs', renderData);            } catch (error) {                this.log(error);                ctx.redirect('/wap/login');            }        }        /**         * 上传附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async shoufangUpFile(ctx) {            const responseData = {                err: 0,                msg: '',                data: [],            };            let stream;            try {                const parts = ctx.multipart({ autoFields: true });                const files = [];                let index = 0;                while ((stream = await parts()) !== undefined) {                    // 判断是否存在                    const sfInfo = await ctx.service.stageShoufang.getDataById(parts.field.sfid);                    if (!sfInfo) {                        throw '该清单 / 计量单元下不存在收方单';                    }                    // 判断用户是否选择上传文件                    if (!stream.filename) {                        throw '请选择上传的文件!';                    }                    // const dirName = 'app/public/upload/stage/' + moment().format('YYYYMMDD');                    // 判断文件夹是否存在,不存在则直接创建文件夹                    // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {                    //     await fs.mkdirSync(path.join(this.app.baseDir, dirName));                    // }                    const fileInfo = path.parse(stream.filename);                    const now_time = new Date();                    const create_time = Date.parse(now_time) / 1000;                    const filepath = `app/public/upload/${sfInfo.tid}/stage/shoufang/fujian_${create_time + index.toString() + fileInfo.ext}`;                    // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));                    await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);                    // console.log(await fs.existsSync(path.resolve(this.app.baseDir, 'app', filepath)));                    // const fileInfo = path.parse(stream.filename);                    // const fileName = 'stage' + create_time + '_' + index + fileInfo.ext;                    // 保存文件                    // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, dirName, fileName));                    if (stream) {                        await sendToWormhole(stream);                    }                    // 保存数据到att表                    const fileData = {                        tid: sfInfo.tid,                        sid: sfInfo.sid,                        sfid: sfInfo.id,                        in_time: now_time,                        filename: fileInfo.name,                        fileext: fileInfo.ext,                        filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,                        filepath,                    };                    // if (ctx.reUploadPermission) {                    //     fileData.re_upload = 1;                    // }                    const result = await ctx.service.stageShoufangAtt.save(fileData);                    if (!result) {                        throw '导入数据库保存失败';                    }                    const attData = await ctx.service.stageShoufangAtt.getDataByFid(result.insertId);                    attData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');                    files.length !== 0 ? files.unshift(attData) : files.push(attData);                    ++index;                }                responseData.data = files;            } catch (err) {                this.log(err);                // 失败需要消耗掉stream 以防卡死                if (stream) {                    await sendToWormhole(stream);                }                this.setMessage(err.toString(), this.messageType.ERROR);                responseData.err = 1;                responseData.msg = err.toString();            }            ctx.body = responseData;        }        /**         * 删除附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async shoufangDeleteFile(ctx) {            const responseData = {                err: 0,                msg: '',                data: '',            };            try {                const data = JSON.parse(ctx.request.body.data);                const fileInfo = await ctx.service.stageShoufangAtt.getDataById(data.id);                if (!fileInfo || !Object.keys(fileInfo).length) {                    throw '该文件不存在';                }                if (fileInfo !== undefined && fileInfo !== '') {                    // 先删除文件                    // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));                    await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);                    // 再删除数据库                    await ctx.service.stageShoufangAtt.deleteById(data.id);                    responseData.data = '';                } else {                    throw '不存在该文件';                }            } catch (err) {                responseData.err = 1;                responseData.msg = err;            }            ctx.body = responseData;        }        /**         * 编辑附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async shoufangEditFile(ctx) {            const responseData = {                err: 0,                msg: '',                data: '',            };            try {                const data = JSON.parse(ctx.request.body.data);                const fileInfo = await ctx.service.stageShoufangAtt.getDataById(data.id);                if (!fileInfo || !Object.keys(fileInfo).length) {                    throw '该文件不存在';                }                await ctx.service.stageShoufangAtt.edit(data);            } catch (err) {                responseData.err = 1;                responseData.msg = err;            }            ctx.body = responseData;        }        /**         * 下载附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async messageDownloadFile(ctx) {            const id = ctx.params.fid;            if (id) {                try {                    const fileInfo = await ctx.service.messageAtt.getDataById(id);                    if (fileInfo !== undefined && fileInfo !== '') {                        // const fileName = path.join(this.app.baseDir, fileInfo.filepath);                        // 解决中文无法下载问题                        const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();                        let disposition = '';                        if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {                            disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);                        } else if (userAgent.indexOf('firefox') >= 0) {                            disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';                        } else {                            /* safari等其他非主流浏览器只能自求多福了 */                            disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');                        }                        ctx.response.set({                            'Content-Type': 'application/octet-stream',                            'Content-Disposition': disposition,                            'Content-Length': fileInfo.filesize,                        });                        // ctx.body = await fs.createReadStream(fileName);                        ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);                    } else {                        throw '不存在该文件';                    }                } catch (err) {                    this.log(err);                    this.setMessage(err.toString(), this.messageType.ERROR);                }            }        }        /**         * 下载附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async shoufangDownloadFile(ctx) {            const id = ctx.params.fid;            if (id) {                try {                    const fileInfo = await ctx.service.stageShoufangAtt.getDataById(id);                    if (fileInfo !== undefined && fileInfo !== '') {                        // const fileName = path.join(this.app.baseDir, fileInfo.filepath);                        // 解决中文无法下载问题                        const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();                        let disposition = '';                        if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {                            disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);                        } else if (userAgent.indexOf('firefox') >= 0) {                            disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';                        } else {                            /* safari等其他非主流浏览器只能自求多福了 */                            disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');                        }                        ctx.response.set({                            'Content-Type': 'application/octet-stream',                            'Content-Disposition': disposition,                            'Content-Length': fileInfo.filesize,                        });                        // ctx.body = await fs.createReadStream(fileName);                        ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);                    } else {                        throw '不存在该文件';                    }                } catch (err) {                    this.log(err);                    this.setMessage(err.toString(), this.messageType.ERROR);                }            }        }        async msg(ctx) {            try {                const msgId = parseInt(ctx.params.id) || 0;                if (!msgId) {                    throw '参数有误';                }                const msgInfo = await ctx.service.message.getDataById(msgId);                const files = await ctx.service.messageAtt.getAtt(msgId);                if (!msgInfo) {                    throw '项目通知不存在';                }                if (msgInfo && msgInfo.type === 1 && msgInfo.project_id !== ctx.session.sessionProject.id) {                    throw '非该项目通知无权查看';                }                if (msgInfo) {                    msgInfo.content = JSON.parse(JSON.stringify(msgInfo.content).replace(/\\r\\n/g, '<br>').replace(/\\"/g, '"').replace(/'/g, ''').replace(/\\t/g, '	'));                }                const renderData = {                    msgInfo,                    moment,                    files,                };                await ctx.render('wap/msg.ejs', renderData);            } catch (error) {                console.log(error);                this.log(error);                ctx.redirect('/wap/dashboard');            }        }    }    return WapController;};
 |