| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 | 'use strict';/** * *  附件 * @author Ellisran * @date 2019/1/11 * @version */const archiver = require('archiver');const path = require('path');const fs = require('fs');module.exports = app => {    class StageAtt extends app.BaseService {        /**         * 构造函数         *         * @param {Object} ctx - egg全局变量         * @return {void}         */        constructor(ctx) {            super(ctx);            this.tableName = 'stage_attachment';        }        /**         * 添加附件         * @param {Object} postData - 表单信息         * @param {Object} fileData - 文件信息         * @param {int} uid - 上传者id         * @return {void}         */        async save(postData, fileData, uid) {            const data = {                lid: postData.lid,                uid,                remark: '',            };            Object.assign(data, fileData);            const result = await this.db.insert(this.tableName, data);            return result;        }        /**         * 添加附件         * @param {Object} postData - 表单信息         * @param {Object} fileData - 文件信息         * @param {int} uid - 上传者id         * @return {void}         */        async updateByID(postData, fileData) {            delete postData.size;            const data = {};            Object.assign(data, fileData);            Object.assign(data, postData);            const result = await this.db.update(this.tableName, data);            return result.affectedRows === 1;        }        /**         * 获取所有附件         * @param {int} tid - 标段id         * @param {int} sid - 当前期数         * @return {void}         */        async getDataByTenderIdAndStageId(tid, sid) {            const sql = 'SELECT att.id, att.lid, att.uid, att.filepath, att.filename, att.fileext, att.filesize, att.extra_upload, att.remark, att.in_time,' +                ' pa.name as `username`, leg.name as `lname`, leg.code as `code`, leg.ledger_id as `ledger_id`, leg.b_code as `b_code`' +                ' FROM ?? AS att,?? AS pa,?? AS leg' +                ' WHERE leg.id = att.lid AND pa.id = att.uid AND att.tid = ? AND att.sid = ? ORDER BY att.id DESC';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.ctx.service.ledger.departTableName(tid), tid, sid];            // return await this.db.query(sql, sqlParam);            const result = await this.db.query(sql, sqlParam);            return result.map(item => {                item.orginpath = this.ctx.app.config.fujianOssPath + item.filepath;                delete item.filepath;                // if (!this.ctx.helper.canPreview(item.fileext)) {                //     item.filepath = `/tender/${this.ctx.tender.id}/measure/stage/${this.ctx.params.order}/download/file/${item.id}`;                // } else {                //     item.filepath = this.ctx.app.config.fujianOssPath + item.filepath;                // }                return item;            });        }        /**         * 获取单个附件         * @param {int} tid - 标段id         * @param {int} sid - 当前期数         * @return {void}         */        async getDataByFid(id) {            const { ctx } = this;            const sql = 'SELECT att.id, att.lid, att.uid, att.filepath, att.filename, att.extra_upload, att.fileext, att.filesize, att.remark, att.in_time,' +                ' pa.name as `username`, leg.name as `lname`, leg.code as `code`, leg.ledger_id as `ledger_id`,leg.b_code as `b_code`' +                ' FROM ?? AS att,?? AS pa,?? AS leg' +                ' WHERE leg.id = att.lid AND pa.id = att.uid AND att.id = ? ORDER BY att.in_time DESC';            const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.ctx.service.ledger.tableName, id];            const result = await this.db.queryOne(sql, sqlParam);            result.orginpath = this.ctx.app.config.fujianOssPath + result.filepath;            if (!ctx.helper.canPreview(result.fileext)) {                result.filepath = `/tender/${ctx.tender.id}/measure/stage/${ctx.params.order}/download/file/${result.id}`;            } else {                // result.filepath = result.filepath.replace(/^app|\/app/, '');                result.filepath = this.ctx.app.config.fujianOssPath + result.filepath;            }            return result;        }        /**         * 将文件压缩成zip,并返回zip文件的路径         * @param {array} fileIds - 文件数组id         * @param {string} zipPath - 压缩文件存储路径         * @return {string} 压缩后的zip文件路径         */        async compressedFile(fileIds, zipPath) {            this.initSqlBuilder();            this.sqlBuilder.setAndWhere('id', {                value: fileIds,                operate: 'in',            });            const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);            const files = await this.db.query(sql, sqlParam);            // const paths = files.map(item => {            //     return { name: item.filename + item.fileext, path: item.filepath }            // })            return new Promise((resolve, reject) => {                // 每次开一个新的archiver                const ziparchiver = archiver('zip');                const outputPath = fs.createWriteStream(path.resolve(this.app.baseDir, zipPath));                outputPath.on('error', err => {                    return reject(err);                });                ziparchiver.pipe(outputPath);                files.forEach(item => {                    ziparchiver.file(item.filepath, { name: item.filename + item.fileext });                });                // 存档警告                ziparchiver.on('warning', function(err) {                    // if (err.code === 'ENOENT') {                    //     console.warn('stat故障和其他非阻塞错误');                    // }                    return reject(err);                });                // 存档出错                ziparchiver.on('error', function(err) {                    // console.log(err);                    return reject(err);                });                ziparchiver.finalize();                outputPath.on('close', () => {                    return resolve(ziparchiver.pointer());                });            });        }    }    return StageAtt;};
 |