| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544 | 'use strict';const auditConst = require('../const/audit');const contractConst = require('../const/contract');const moment = require('moment');const sendToWormhole = require('stream-wormhole');const fs = require('fs');const path = require('path');module.exports = app => {    class ContractController extends app.BaseController {        /**         * 构造函数         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        constructor(ctx) {            super(ctx);            ctx.showProject = true;            // ctx.showTitle = true;        }        /**         * 项目合同列表页         *         * @param {Object} ctx - egg全局页面         * @return {void}         */        async index(ctx) {            try {                if (!ctx.subProject.page_show.openContract) {                    throw '该功能已关闭或无法查看';                }                const renderData = {                    jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.contract.index),                    auditConst,                    isTender: false,                };                // renderData.budgetStd = await ctx.service.budgetStd.getDataByProjectId(ctx.session.sessionProject.id);                renderData.projectList = await ctx.service.subProject.getSubProjectByContract(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin);                for (const t of renderData.projectList) {                    if (!t.is_folder) {                        const expensessList = await ctx.service.contract.getListByUsers({ spid: t.id, contract_type: contractConst.type.expenses }, ctx.session.sessionUser);                        t.expenses_count = expensessList.length;                        t.expenses_total_price = expensessList.reduce((total, item) => ctx.helper.add(total, item.total_price), 0);                        t.expenses_yf_price = expensessList.reduce((total, item) => ctx.helper.add(total, item.yf_price), 0);                        const incomeList = await ctx.service.contract.getListByUsers({ spid: t.id, contract_type: contractConst.type.income }, ctx.session.sessionUser);                        t.income_count = incomeList.length;                        t.income_total_price = incomeList.reduce((total, item) => ctx.helper.add(total, item.total_price), 0);                        t.income_yf_price = incomeList.reduce((total, item) => ctx.helper.add(total, item.yf_price), 0);                    }                }                const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);                renderData.accountList = accountList;                const unitList = await ctx.service.constructionUnit.getAllDataByCondition({where: {pid: ctx.session.sessionProject.id}});                renderData.accountGroup = unitList.map(item => {                    const groupList = accountList.filter(item1 => item1.company === item.name);                    return { groupName: item.name, groupList };                }).filter(x => { return x.groupList.length > 0; });                // renderData.permissionConst = ctx.service.subProjPermission.PermissionConst;                renderData.categoryData = await this.ctx.service.category.getAllCategory(ctx.subProject);                renderData.companys = await this.ctx.service.constructionUnit.getAllDataByCondition({where: {pid: ctx.session.sessionProject.id}});                // renderData.templates = await this.ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id);                await this.layout('contract/index.ejs', renderData, 'contract/modal.ejs');            } catch (err) {                ctx.log(err);                ctx.session.postError = err.toString();                ctx.redirect(this.menu.menu.dashboard.url);            }        }        /**         * 标段合同列表页         *         * @param {Object} ctx - egg全局页面         * @return {void}         */        async tender(ctx) {            try {                if (!ctx.subProject.page_show.openContract) {                    throw '该功能已关闭或无法查看';                }                // 获取用户新建标段权利                const accountInfo = await this.ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                const userPermission = accountInfo !== undefined && accountInfo.permission !== ''                    ? JSON.parse(accountInfo.permission) : null;                let tenderList = await ctx.service.tender.getContractList('', userPermission, ctx.session.sessionUser.is_admin);                const projectList = await ctx.service.subProject.getSubProjectByTender(ctx.session.sessionProject.id, tenderList);                const removeTidList = [];                for (const t of tenderList) {                    const spInfo = ctx.helper._.find(projectList, { id: t.spid });                    if (!spInfo) {                        removeTidList.push(t.id);                        continue;                    }                    spInfo.child_order = spInfo.child_order ? spInfo.child_order : 0;                    spInfo.is_folder = 1;                    t.tree_pid = spInfo.id;                    t.tree_level = spInfo.tree_level + 1;                    t.tree_order = spInfo.child_order + 1;                    spInfo.child_order++;                    const expensessList = await ctx.service.contract.getListByUsers({ tid: t.id, contract_type: contractConst.type.expenses }, ctx.session.sessionUser);                    t.expenses_count = expensessList.length;                    t.expenses_total_price = expensessList.reduce((total, item) => ctx.helper.add(total, item.total_price), 0);                    t.expenses_yf_price = expensessList.reduce((total, item) => ctx.helper.add(total, item.yf_price), 0);                    const incomeList = await ctx.service.contract.getListByUsers({ tid: t.id, contract_type: contractConst.type.income }, ctx.session.sessionUser);                    t.income_count = incomeList.length;                    t.income_total_price = incomeList.reduce((total, item) => ctx.helper.add(total, item.total_price), 0);                    t.income_yf_price = incomeList.reduce((total, item) => ctx.helper.add(total, item.yf_price), 0);                }                if (removeTidList.length > 0) {                    tenderList = tenderList.filter(item => !removeTidList.includes(item.id));                }                const categoryData = await ctx.service.category.getAllCategory(ctx.subProject);                const renderData = {                    jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.contract.tender),                    // jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.contract.index),                    auditConst,                    tenderList,                    projectList: projectList.concat(tenderList),                    categoryData,                    isTender: true,                    selfCategoryLevel: accountInfo ? accountInfo.self_category_level : '',                    // selfCategoryLevel: '',                    pid: ctx.session.sessionProject.id,                    uid: ctx.session.sessionUser.accountId,                };                if (ctx.session.sessionUser.is_admin) {                    const projectId = ctx.session.sessionProject.id;                    // 获取所有项目参与者                    const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);                    const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: projectId } });                    const accountGroupList = unitList.map(item => {                        const groupList = accountList.filter(item1 => item1.company === item.name);                        return { groupName: item.name, groupList };                    }).filter(x => { return x.groupList.length > 0; });                    renderData.accountList = accountList;                    renderData.accountGroup = accountGroupList;                }                await this.layout('contract/tender.ejs', renderData, 'contract/modal.ejs');                // await this.layout('contract/index.ejs', renderData, 'contract/modal.ejs');            } catch (err) {                ctx.log(err);                ctx.session.postError = err.toString();                ctx.redirect(this.menu.menu.dashboard.url);            }        }        async auditSave(ctx) {            try {                if (ctx.session.sessionUser.is_admin === 0) throw '没有设置权限';                const responseData = {                    err: 0, msg: '', data: null,                };                const data = JSON.parse(ctx.request.body.data);                if (!data.type) {                    throw '提交数据错误';                }                const info = ctx.contract;                const options = ctx.contractOptions;                let uids;                let result = false;                let auditList = [];                switch (data.type) {                    case 'check':                        await ctx.service.contractTree.insertTree(options, info);                        // 新建合同信息                        break;                    case 'add-audit':                        // 判断用户是单个还是数组                        uids = data.id instanceof Array ? data.id : [data.id];                        // 判断该用户的组是否已加入到表中,已加入则提示无需添加                        auditList = await ctx.service.contractAudit.getList(options);                        const addAidList = ctx.helper._.difference(uids, ctx.helper._.map(auditList, 'uid'));                        if (addAidList.length === 0) {                            throw '用户已存在成员管理中,无需重复添加';                        }                        const accountList = await ctx.service.projectAccount.getAllDataByCondition({ where: { id: addAidList } });                        await ctx.service.contractAudit.saveAudits(options, accountList);                        responseData.data = await ctx.service.contractAudit.getList(options);                        break;                    case 'del-audit':                        uids = data.id instanceof Array ? data.id : [data.id];                        const cloneOptions = ctx.helper._.cloneDeep(options);                        cloneOptions.uid = uids;                        auditList = options.spid ? await ctx.service.subProjPermission.getContractAuditList(options.spid, uids) : await ctx.service.contractAudit.getAllDataByCondition({ where: cloneOptions });                        if (auditList.length !== uids.length) {                            throw '该用户已不存在成员管理中,移除失败';                        }                        await ctx.service.contractAudit.delAudit(options, ctx.helper._.map(auditList, 'id'));                        responseData.data = await ctx.service.contractAudit.getList(options);                        break;                    case 'save-permission':                        result = await ctx.service.contractAudit.updatePermission(options, data.updateData);                        if (!result) {                            throw '修改权限失败';                        }                        break;                    case 'list':                        responseData.data = await ctx.service.contractAudit.getList(options);                        break;                    default: throw '参数有误';                }                ctx.body = responseData;            } catch (err) {                this.log(err);                ctx.body = { err: 1, msg: err.toString(), data: null };            }        }        async detail(ctx) {            try {                const whiteList = ctx.app.config.multipart.whitelist;                const contractOptions = ctx.helper._.cloneDeep(ctx.contractOptions);                contractOptions.contract_type = ctx.contract_type;                const contractTreeAudits = await ctx.service.contractTreeAudit.getAllDataByCondition({ where: contractOptions });                const renderData = {                    contractTreeAudits,                    audit_permission: ctx.contract_audit_permission,                    preUrl: `/sp/${ctx.subProject.id}` + (ctx.contractOptions.tid ? '/contract/tender' : '/contract'),                    jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.contract.detail),                    contract_type: ctx.contract_type,                    contractConst,                    whiteList,                    thisUrl: `/sp/${ctx.subProject.id}` + (ctx.contract_tender ? `/contract/tender/${ctx.contract.id}/detail` : '/contract/detail'),                };                if (ctx.session.sessionUser.is_admin) {                    const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);                    renderData.accountList = accountList;                    const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });                    renderData.accountGroup = unitList.map(item => {                        const groupList = accountList.filter(item1 => item1.company === item.name);                        return { groupName: item.name, groupList };                    }).filter(x => { return x.groupList.length > 0; });                }                await this.layout('contract/detail.ejs', renderData, 'contract/detail_modal.ejs');            } catch (err) {                ctx.log(err);                ctx.session.postError = err.toString();                ctx.redirect(`/sp/${ctx.subProject.id}` + (ctx.contractOptions.spid ? '/contract/detail' : '/contract/tender'));            }        }        async loadDetail(ctx) {            try {                const responseData = {                    err: 0, msg: '', data: {},                };                const contractOptions = ctx.helper._.cloneDeep(ctx.contractOptions);                contractOptions.contract_type = ctx.contract_type;                // const data = JSON.parse(ctx.request.body.data);                // ctx.contractOptions.contract_type = ctx.contract_type;                responseData.data.contractTree = await ctx.service.contractTree.getAllDataByCondition({ where: contractOptions });                // 获取权限并展示对应合同                responseData.data.contractList = await ctx.service.contract.getListByUsers(contractOptions, ctx.session.sessionUser);                // responseData.data.contractList = await ctx.service.contract.getAllDataByCondition({ where: contractOptions });                // const userOptions = ctx.helper._.cloneDeep(ctx.contractOptions);                // // userOptions.uid = ctx.session.sessionUser.id;                // const permissionEdit = ctx.session.sessionUser.is_admin ? true : await ctx.service.contractAudit.getUserPermissionEdit(userOptions);                // responseData.data.auditContractTreePermission = permissionEdit ? [] : await ctx.service.contractTreeAudit.getAllDataByCondition({ where: contractOptions });                // responseData.data.contractAttList = await ctx.service.contractAtt.getAllDataByCondition({ where: ctx.contractOptions });                if (ctx.session.sessionUser.is_admin) {                    const contractAudits = await ctx.service.contractAudit.getList(ctx.contractOptions);                    const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });                    const accountGroup = unitList.map(item => {                        const groupList = contractAudits.filter(item1 => item1.company === item.name);                        return { groupName: item.name, groupList };                    }).filter(x => { return x.groupList.length > 0; });                    responseData.data.contractAudits = contractAudits;                    responseData.data.accountGroup = ctx.helper._.filter(accountGroup, function (item) {                        return item.groupList.length > 0;                    });                }                ctx.body = responseData;            } catch (err) {                this.log(err);                ctx.body = { err: 1, msg: err.toString(), data: null };            }        }        async updateBills(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (!data.postType || !data.postData) throw '数据错误';                const responseData = { err: 0, msg: '', data: {} };                const options = ctx.helper._.cloneDeep(ctx.contractOptions);                options.contract_type = ctx.contract_type;                switch (data.postType) {                    case 'add':                    case 'add-child':                    case 'delete':                    case 'up-move':                    case 'down-move':                    case 'up-level':                    case 'down-level':                        responseData.data = await this._billsBase(ctx, data.postType, data.postData, options);                        break;                    case 'update':                        responseData.data = await ctx.service.contractTree.updateCalc(options, data.postData);                        break;                    case 'update-contract':                        responseData.data = await ctx.service.contract.updateCalc(options, data.postData);                        break;                    case 'paste-block':                        responseData.data = await this._pasteBlock(ctx, data.postData, options);                        break;                    case 'add-contract':                        responseData.data = await ctx.service.contract.add(options, data.postData.select, data.postData.contract);                        break;                    case 'add-tree-audit':                        responseData.data = await ctx.service.contractTreeAudit.add(options, data.postData.select, data.postData.auditId);                        break;                    case 'del-tree-audit':                        responseData.data = await ctx.service.contractTreeAudit.dels(options, data.postData.select, data.postData.auditIds);                        break;                    case 'get-contract':                        responseData.data.pays = await ctx.service.contractPay.getPays(options, data.postData);                        responseData.data.files = await ctx.service.contractAtt.getAtt(data.postData);                        break;                    case 'add-contract-pay':                        responseData.data = await ctx.service.contractPay.add(options, data.postData.select, data.postData.pay);                        break;                    case 'save-contract-pay':                        responseData.data = await ctx.service.contractPay.save(options, data.postData.select, data.postData.pay);                        break;                    case 'del-contract-pay':                        responseData.data = await ctx.service.contractPay.del(options, data.postData.select, data.postData.pay);                        break;                    default:                        throw '未知操作';                }                ctx.body = responseData;            } catch (err) {                console.log(err);                this.log(err);                ctx.body = this.ajaxErrorBody(err, '数据错误');            }        }        async _billsBase(ctx, type, data, options) {            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 ctx.service.contractTree.addNodeBatch(options, data.id, data.count);                case 'add-child':                    return await ctx.service.contractTree.addChildNode(options, data.id, data.count);                case 'delete':                    return await ctx.service.contractTree.delete(options, data.id, data.count);                case 'up-move':                    return await ctx.service.contractTree.upMoveNode(options, data.id, data.count);                case 'down-move':                    return await ctx.service.contractTree.downMoveNode(options, data.id, data.count);                case 'up-level':                    return await ctx.service.contractTree.upLevelNode(options, data.id, data.count);                case 'down-level':                    return await ctx.service.contractTree.downLevelNode(options, data.id, data.count);                default:                    throw '未知操作';            }        }        /**         * 复制粘贴整块         *         * @param ctx         * @return {Promise<void>}         */        async _pasteBlock(ctx, data, options) {            if ((isNaN(data.id) || data.id <= 0) ||                (!data.block || data.block.length <= 0)) throw '参数错误';            return await ctx.service.contractTree.pasteBlockData(options, data.id, data.block);        }        /**         * 上传附件         * @param {*} ctx 上下文         */        async uploadFile(ctx) {            let stream;            try {                const responseData = { err: 0, msg: '', data: {} };                const cid = ctx.params.cid;                if (!cid) throw '参数有误';                const cpid = parseInt(ctx.params.cpid);                const parts = this.ctx.multipart({                    autoFields: true,                });                const files = [];                const create_time = Date.parse(new Date()) / 1000;                let idx = 0;                while ((stream = await parts()) !== undefined) {                    if (!stream.filename) {                        // 如果没有传入直接返回                        return;                    }                    const fileInfo = path.parse(stream.filename);                    const headpath = ctx.contractOptions.spid ? `sp/contract/${ctx.contractOptions.spid}` : `app/public/upload/${ctx.contractOptions.tid}`;                    const filepath = `${headpath}/contract/${cid}${cpid ? '/pay/' + cpid : ''}/fujian_${create_time + idx.toString() + fileInfo.ext}`;                    // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));                    await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);                    files.push({ filepath, name: stream.filename, ext: fileInfo.ext });                    ++idx;                    stream && (await sendToWormhole(stream));                }                const in_time = new Date();                const payload = files.map(file => {                    let idx;                    if (Array.isArray(parts.field.name)) {                        idx = parts.field.name.findIndex(name => name === file.name);                    } else {                        idx = 'isString';                    }                    const newFile = {                        spid: ctx.contractOptions.spid || null,                        tid: ctx.contractOptions.tid || null,                        contract_type: ctx.contract_type,                        cid,                        uid: ctx.session.sessionUser.accountId,                        filename: file.name,                        fileext: file.ext,                        filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),                        filepath: file.filepath,                        upload_time: in_time,                    };                    if (cpid) {                        newFile.cpid = cpid;                    }                    return newFile;                });                if (cpid) {                    // 执行文件信息写入数据库                    await ctx.service.contractPayAtt.saveFileMsgToDb(payload);                    // 将最新的当前标段的所有文件信息返回                    responseData.data = await ctx.service.contractPayAtt.getAtt(cpid);                } else {                    // 执行文件信息写入数据库                    await ctx.service.contractAtt.saveFileMsgToDb(payload);                    // 将最新的当前标段的所有文件信息返回                    responseData.data = await ctx.service.contractAtt.getAtt(cid);                }                ctx.body = responseData;            } catch (err) {                stream && (await sendToWormhole(stream));                this.log(err);                ctx.body = { err: 1, msg: err.toString(), data: null };            }        }        /**         * 删除附件         * @param {Ojbect} ctx 上下文         */        async deleteFile(ctx) {            try {                const cpid = ctx.params.cpid;                const cid = ctx.params.cid;                const responseData = { err: 0, msg: '', data: {} };                const data = JSON.parse(ctx.request.body.data);                let fileInfo = null;                if (cpid) {                    fileInfo = await ctx.service.contractPayAtt.getDataById(data.id);                } else if (cid) {                    fileInfo = await ctx.service.contractAtt.getDataById(data.id);                } else {                    throw '参数错误';                }                if (fileInfo || Object.keys(fileInfo).length) {                    // 先删除文件                    // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));                    await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);                    // 再删除数据库                    if (cpid) {                        await ctx.service.contractPayAtt.delete(data.id);                    } else {                        await ctx.service.contractAtt.delete(data.id);                    }                } else {                    throw '不存在该文件';                }                if (cpid) {                    responseData.data = await ctx.service.contractPayAtt.getAtt(cpid);                } else {                    responseData.data = await ctx.service.contractAtt.getAtt(cid);                }                ctx.body = responseData;            } catch (err) {                this.log(err);                ctx.body = { err: 1, msg: err.toString(), data: null };            }        }        /**         * 下载附件         * @param {Object} ctx - egg全局变量         * @return {void}         */        async downloadFile(ctx) {            const id = ctx.params.fid;            if (id) {                try {                    const cpid = ctx.params.cpid;                    const cid = ctx.params.cid;                    let fileInfo = null;                    if (cpid) {                        fileInfo = await ctx.service.contractPayAtt.getDataById(id);                    } else if (cid) {                        fileInfo = await ctx.service.contractAtt.getDataById(id);                    } else {                        throw '参数错误';                    }                    if (fileInfo || Object.keys(fileInfo).length) {                        // const fileName = path.join(__dirname, '../', fileInfo.filepath);                        // 解决中文无法下载问题                        const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();                        let disposition = '';                        if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {                            disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);                        } else if (userAgent.indexOf('firefox') >= 0) {                            disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';                        } else {                            /* safari等其他非主流浏览器只能自求多福了 */                            disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');                        }                        ctx.response.set({                            'Content-Type': 'application/octet-stream',                            'Content-Disposition': disposition,                            'Content-Length': fileInfo.filesize,                        });                        // ctx.body = await fs.createReadStream(fileName);                        ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);                    } else {                        throw '不存在该文件';                    }                } catch (err) {                    this.log(err);                    this.setMessage(err.toString(), this.messageType.ERROR);                }            }        }    }    return ContractController;};
 |