| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 | 'use strict';/** * * * @author Mai * @date 2021/10/27 * @version */const auditConst = require('../const/audit');const sendToWormhole = require('stream-wormhole');const path = require('path');const advanceConst = require('../const/advance');module.exports = app => {    class BudgetController extends app.BaseController {        /**         * 概算投资         *         * @param ctx         * @returns {Promise<void>}         */        async index(ctx) {            try {                const renderData = {                    jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.index),                    auditConst,                };                renderData.projectList = await ctx.service.subProject.getFileProject(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin);                renderData.tenderList = await ctx.service.tender.getList4Select('stage');                renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.session.sessionProject.id);                await this.layout('file/index.ejs', renderData, 'file/modal.ejs');            } catch (err) {                ctx.log(err);            }        }        async file(ctx) {            try {                const renderData = {                    jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.file),                };                renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);                renderData.categoryData = await ctx.service.category.getAllCategory(ctx.session.sessionProject.id);                renderData.canFiling = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.filing.value) >= 0;                renderData.canUpload = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) >= 0;                renderData.filingTypes = ctx.service.filing.filingType;                await this.layout('file/file.ejs', renderData, 'file/file_modal.ejs');            } catch (err) {                ctx.log(err);            }        }        async getFilingTypePermission(ctx) {            try {                if (ctx.subProject.project_id !== this.ctx.session.sessionProject.id) throw '您无权操作该数据';                const filingType = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);                ctx.body = { err: 0, msg: '', data: filingType };            } catch(err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '获取授权用户数据错误');            }        }        async saveFilingTypePermission(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                await ctx.service.subProjPermission.saveFilingType(data);                ctx.body = { err: 0, msg: '', data: '' };            } catch(err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '保存授权用户信息错误');            }        }        async addFiling(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                const result = await ctx.service.filing.add(data);                ctx.body = { err: 0, msg: '', data: result };            } catch (err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '新增分类失败');            }        }        async delFiling(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                const result = await ctx.service.filing.del(data);                ctx.body = { err: 0, msg: '', data: result };            } catch (err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '删除分类失败');            }        }        async saveFiling(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                const result = await ctx.service.filing.save(data);                ctx.body = { err: 0, msg: '', data: result };            } catch (err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '保存分类数据失败');            }        }        async moveFiling(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (!data.id || !(data.tree_order >= 0)) throw '数据错误';                const result = await ctx.service.filing.move(data);                ctx.body = { err: 0, msg: '', data: result };            } catch (err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '移动分类失败');            }        }        async loadFile(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                const result = await ctx.service.file.getFiles({                    where: { filing_id: data.filing_id, is_deleted: 0 },                    limit: data.count,                    offset: (data.page-1)*data.count                });                ctx.body = { err: 0, msg: '', data: result };            } catch (err) {                ctx.log(err);                ctx.ajaxErrorBody(err, '加载文件失败');            }        }        async checkCanUpload(ctx) {            if (ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) < 0) {                throw '您无权上传、导入、删除文件';            }        }        async checkFiling(filing) {            const child = await this.ctx.service.filing.getDataByCondition({ tree_pid: filing.id, is_deleted: 0 });            if (child) throw '该分类下存在子分类,请在子分类下上传、导入文件';        }        async uploadFile(ctx){            let stream;            try {                await this.checkCanUpload(ctx);                const parts = ctx.multipart({ autoFields: true });                let index = 0;                const create_time = Date.parse(new Date()) / 1000;                let stream = await parts();                const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                const filing = await ctx.service.filing.getDataById(parts.field.filing_id);                if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';                await this.checkFiling(filing);                const uploadfiles = [];                while (stream !== undefined) {                    if (!stream.filename) throw '未发现上传文件!';                    const fileInfo = path.parse(stream.filename);                    const filepath = `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;                    // 保存文件                    await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);                    await sendToWormhole(stream);                    // 插入到stage_pay对应的附件列表中                    uploadfiles.push({                        filename: fileInfo.name,                        fileext: fileInfo.ext,                        filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,                        filepath,                    });                    ++index;                    if (Array.isArray(parts.field.size) && index < parts.field.size.length) {                        stream = await parts();                    } else {                        stream = undefined;                    }                }                const result = await ctx.service.file.addFiles(filing, uploadfiles, user);                ctx.body = {err: 0, msg: '', data: result };            } catch (error) {                ctx.helper.log(error);                // 失败需要消耗掉stream 以防卡死                if (stream) await sendToWormhole(stream);                ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');            }        }        async delFile(ctx) {            try{                const data = JSON.parse(ctx.request.body.data);                if (!data.del) throw '缺少参数';                const result = await ctx.service.file.delFiles(data.del);                ctx.body = { err: 0, msg: '', data: result };            } catch(error) {                this.log(error);                ctx.ajaxErrorBody(error, '删除附件失败');            }        }        async saveFile(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (!data.id) throw '缺少参数';                const result = await ctx.service.file.saveFile(data.id, data.filename);                ctx.body = { err: 0, msg: '', data: result };            } catch (error) {                this.log(error);                ctx.ajaxErrorBody(error, '编辑附件失败');            }        }        async uploadBigFile(ctx) {            try {                await this.checkCanUpload(ctx);                const data = JSON.parse(ctx.request.body.data);                if (!data.type || !data.filing_id || !data.fileInfo) throw '缺少参数';                const filing = await ctx.service.filing.getDataById(data.filing_id);                if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';                let result;                const fileInfo = path.parse(data.fileInfo.filename);                switch(data.type) {                    case 'begin':                        const create_time = Date.parse(new Date()) / 1000;                        result = {                            filename: `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + fileInfo.ext}`,                        };                        result.filepath = ctx.app.config.fujianOssFolder + result.filename;                        // todo 写入ossToken                        result.oss = await ctx.helper.getOssToken(ctx.app.fujianOss);                        break;                    case 'end':                        const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                        const uploadFiles = [{                            filepath: data.filepath,                            filename: fileInfo.name, fileext: fileInfo.ext, filesize: data.fileInfo.filesize,                        }];                        result = await ctx.service.file.addFiles(filing, uploadFiles, user);                        break;                }                ctx.body = {err: 0, msg: '', data: result };            } catch (error) {                ctx.log(error);                ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');            }        }        async loadValidRelaTender(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (data.type) throw '参数错误';                const accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                const userPermission = accountInfo !== undefined && accountInfo.permission !== ''                    ? JSON.parse(accountInfo.permission) : null;                const tenderList = await ctx.service.tender.getList('', userPermission, ctx.session.sessionUser.is_admin);                const rela_tender = await ctx.subProject.rela_tender.split(',');                const result = tenderList.filter(x => { return rela_tender.indexOf(x.id + '') >= 0});                for (const r of result) {                    r.advance = await ctx.service.advance.getAllDataByCondition({ columns: ['id', 'order', 'type'], where: { tid: r.id }});                    r.advance.forEach(a => {                        const type = advanceConst.typeCol.find(x => { return x.type === a.type });                        if (type) a.type_str = type.name;                    });                    r.stage = await ctx.service.stage.getAllDataByCondition({ columns: ['id', 'order'], where: { tid: r.id, status: auditConst.stage.status.checked } });                }                ctx.body = {err: 0, msg: '', data: result };            } catch (error) {                ctx.helper.log(error);                ctx.body = this.ajaxErrorBody(error, '加载标段信息失败');            }        }        async _loadLedgerAtt(data) {            if (!data.tender_id) throw '参数错误';            return await this.ctx.service.ledgerAtt.getAllDataByCondition({ where: { tid: data.tender_id }, order: [['id', 'desc']]});        }        async _loadStageAtt(data) {            if (!data.tender_id || !data.stage) throw '参数错误';            switch (data.sub_type) {                case 'att':                    const stage = await this.ctx.service.stage.getDataById(data.stage);                    return await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: data.tender_id, sid: stage.order }, order: [['id', 'desc']]});            }        }        async _loadAdvanceAtt(data) {            if (!data.stage) throw '参数错误';            const self = this;            const result = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { vid: data.stage }, order: [['id', 'desc']]});            result.forEach(x => {                const info = path.parse(x.filename);                x.filename = info.name;                x.filesize = self.ctx.helper.sizeToBytes(x.filesize);            });            return result;        }        async loadRelaFiles(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (!data.type) throw '参数错误';                let files;                switch(data.type) {                    case 'ledger':                        files = await this._loadLedgerAtt(data);                        break;                    case 'stage':                        files = await this._loadStageAtt(data);                        break;                    case 'advance':                        files = await this._loadAdvanceAtt(data);                        break;                    default: throw '未知文件类型';                }                ctx.body = {err: 0, msg: '', data: files };            } catch (error) {                ctx.helper.log(error);                ctx.body = this.ajaxErrorBody(error, '加载附件失败,请重试');            }        }        async relaFile(ctx) {            try {                const data = JSON.parse(ctx.request.body.data);                if (!data.filing_id || !data.files) throw '缺少参数';                const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);                const filing = await ctx.service.filing.getDataById(data.filing_id);                if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';                await this.checkFiling(filing);                const result = await ctx.service.file.relaFiles(filing, data.files, user);                ctx.body = {err: 0, msg: '', data: result };            } catch (error) {                ctx.helper.log(error);                ctx.body = this.ajaxErrorBody(error, '导入附件失败,请重试');            }        }    }    return BudgetController;};
 |