| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843 | '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);            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);            }            // 获取待审批的变更期            const auditChanges = await ctx.service.changeAudit.getAuditChangeByWap(ctx.session.sessionUser.accountId);            // 获取待审批的变更方案            let auditChangePlans = [];            if (ctx.session.sessionProject.page_show.openChangePlan) {                auditChangePlans = await ctx.service.changePlanAudit.getAuditChangePlanByWap(ctx.session.sessionUser.accountId);            }            // 获取待审批的台账修订            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,                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(this.ctx.session.sessionProject.id);                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 changes = await ctx.service.change.getListByStatus(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.stageAudit.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 changePlans = [];                if (ctx.session.sessionProject.page_show.openChangePlan) {                    changePlans = await ctx.service.changePlan.getListByStatus(tender.id, 0, 0);                    for (const c of changePlans) {                        c.curAuditor = await ctx.service.changePlanAudit.getAuditorByStatus(c.id, c.status, c.times);                    }                }                // 台账修订列表                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,                    changes,                    changePlans,                    revises,                    advanceList,                    auditConst: auditConst.stage,                    auditChangeConst: auditConst.change,                    auditChangePlanConst: auditConst.changePlan,                    auditReviseConst: auditConst.revise,                    changeConst,                    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 = lastStage;                const renderData = {                    tender,                    stage,                    auditConst: auditConst.stage,                };                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 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 changePlan(ctx) {            try {                const tender = ctx.tender.data;                if (!ctx.session.sessionProject.page_show.openChangePlan) {                    throw '该功能已关闭';                }                const change = await ctx.service.changePlan.getDataById(ctx.params.cpid);                const renderData = {                    tender,                    change,                    auditConst: auditConst.changePlan,                    changeConst,                    tpUnit: ctx.tender.info.decimal.tp,                };                const times = change.status !== auditConst.changePlan.status.checkNo ? change.times : change.times - 1;                renderData.change.user = await ctx.service.projectAccount.getAccountInfoById(change.uid);                renderData.change.auditors = await ctx.service.changePlanAudit.getAuditors(change.id, times);                // 获取审批流程中左边列表                renderData.change.auditors2 = await ctx.service.changePlanAudit.getAuditGroupByList(change.id, times);                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 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);                if (!msgInfo) {                    throw '项目通知不存在';                }                if (msgInfo && msgInfo.type === 1 && msgInfo.project_id !== ctx.session.sessionProject.id) {                    throw '非该项目通知无权查看';                }                const renderData = {                    msgInfo,                    moment,                };                await ctx.render('wap/msg.ejs', renderData);            } catch (error) {                console.log(error);                this.log(error);                ctx.redirect('/wap/dashboard');            }        }    }    return WapController;};
 |