Selaa lähdekoodia

feat: 增加标段、期对应调差-附件的文件删除的逻辑

lanjianrong 5 vuotta sitten
vanhempi
commit
4b6aa99883

+ 2 - 42
app/controller/material_controller.js

@@ -631,7 +631,7 @@ module.exports = app => {
                         user_id: ctx.session.sessionUser.accountId,
                         mid: ctx.material.id,
                         upload_time,
-                        file_path: file.filepath,
+                        filepath: file.filepath,
                         file_size: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
                         file_name: file.name,
                     };
@@ -669,46 +669,6 @@ module.exports = app => {
         }
 
         /**
-         * 下载附件
-         * @param {Object} ctx - egg全局变量
-         * @return {void}
-         */
-        async downloadFile(ctx) {
-            const id = ctx.params.fid;
-            if (id) {
-                try {
-                    const fileInfo = await ctx.service.materialFile.getMaterialFileById(id);
-                    if (fileInfo) {
-                        const fileName = path.join(this.app.baseDir, './app', fileInfo.file_path);
-                        console.log(fileName);
-                        // 解决中文无法下载问题
-                        const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
-                        let disposition = '';
-                        if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
-                            disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.file_name);
-                        } else if (userAgent.indexOf('firefox') >= 0) {
-                            disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.file_name) + '"';
-                        } else {
-                            /* safari等其他非主流浏览器只能自求多福了 */
-                            disposition = 'attachment; filename=' + new Buffer(fileInfo.file_name).toString('binary');
-                        }
-                        ctx.response.set({
-                            'Content-Type': 'application/octet-stream',
-                            'Content-Disposition': disposition,
-                            'Content-Length': fileInfo.file_size,
-                        });
-                        ctx.body = await fs.createReadStream(fileName);
-                    } else {
-                        throw '不存在该文件';
-                    }
-                } catch (err) {
-                    this.log(err);
-                    this.setMessage(err.toString(), this.messageType.ERROR);
-                }
-            }
-        }
-
-        /**
          * 删除附件
          * @param {Ojbect} ctx 上下文
          */
@@ -719,7 +679,7 @@ module.exports = app => {
                 const fileInfo = await ctx.service.materialFile.getMaterialFileById(id);
                 if (fileInfo) {
                     // 先删除文件
-                    await fs.unlinkSync(path.join(this.app.baseDir, './app', fileInfo.file_path));
+                    await fs.unlinkSync(path.join(this.app.baseDir, './app', fileInfo.filepath));
                     // 再删除数据库
                     await ctx.service.materialFile.delete(id);
                 } else {

+ 117 - 99
app/extend/helper.js

@@ -19,7 +19,7 @@ Decimal.set({ precision: 50, defaults: true });
 const SMS = require('../lib/sms');
 
 module.exports = {
-    _: _,
+    _,
 
     /**
      * 生成随机字符串
@@ -143,7 +143,7 @@ module.exports = {
             if (decimals < 1) {
                 val = (Math.round(val)).toString();
             } else {
-                let num = val.toString();
+                const num = val.toString();
                 if (num.lastIndexOf('.') === -1) {
                     // num += '.';
                     // num += this.makezero(decimals);
@@ -155,7 +155,7 @@ module.exports = {
                         val = num;
                     } else if (parseInt(valdecimals) > parseInt(decimals)) {
                         val = parseFloat(val) !== 0 ? Math.round(this.accMul(val, this.makemultiple(decimals))) / this.makemultiple(decimals) : this.makedecimalzero(decimals);
-                        let num = val.toString();
+                        const num = val.toString();
                         if (num.lastIndexOf('.') === -1) {
                             // num += '.';
                             // num += this.makezero(decimals);
@@ -320,7 +320,7 @@ module.exports = {
      * obj = {a: 1, b: 2}, sObj = {a: 0, c: 3}, 返回{a: 0, b: 2, c: 3}
      * @param obj
      * @param sObj
-     * @returns {any}
+     * @return {any}
      */
     updateObj(obj, sObj) {
         if (!obj) {
@@ -340,7 +340,7 @@ module.exports = {
      * @param {Array} arr
      * @param name -
      * @param value
-     * @returns {*}
+     * @return {*}
      */
     findData(arr, name, value) {
         if (!arr instanceof Array) {
@@ -368,14 +368,14 @@ module.exports = {
      * 检查数字是否相等
      * @param {Number} value1
      * @param {Number} value2
-     * @returns {boolean}
+     * @return {boolean}
      */
     checkNumberEqual(value1, value2) {
         if (value1 && value2) {
             return Math.abs(value2 - value1) > zeroRange;
-        } else {
-            return (!value1 && !value2)
         }
+        return (!value1 && !value2);
+
     },
 
     /**
@@ -383,7 +383,7 @@ module.exports = {
      * @param str1
      * @param str2
      * @param symbol
-     * @returns {number}
+     * @return {number}
      */
     compareCode(str1, str2, symbol = '-') {
         if (!str1) {
@@ -396,19 +396,20 @@ module.exports = {
             if (numReg.test(code1)) {
                 if (numReg.test(code2)) {
                     return parseInt(code1) - parseInt(code2);
-                } else {
-                    return -1
-                }
-            } else {
-                if (numReg.test(code2)) {
-                    return 1;
-                } else {
-                    return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); //code1.localeCompare(code2);
                 }
+                return -1;
+
+            }
+            if (numReg.test(code2)) {
+                return 1;
             }
+            return code1 === code2 ? 0 : (code1 < code2 ? -1 : 1); // code1.localeCompare(code2);
+
+
         }
         const numReg = /^[0-9]+$/;
-        const aCodes = str1.split(symbol), bCodes = str2.split(symbol);
+        const aCodes = str1.split(symbol),
+            bCodes = str2.split(symbol);
         for (let i = 0, iLength = Math.min(aCodes.length, bCodes.length); i < iLength; ++i) {
             const iCompare = compareSubCode(aCodes[i], bCodes[i]);
             if (iCompare !== 0) {
@@ -422,7 +423,7 @@ module.exports = {
      * 根据 清单编号 获取 章级编号
      * @param code
      * @param symbol
-     * @returns {string}
+     * @return {string}
      */
     getChapterCode(code, symbol = '-') {
         if (!code || code === '') return '';
@@ -433,9 +434,9 @@ module.exports = {
             const result = codePath[0].match(numReg);
             const num = parseInt(result[0]);
             return this.mul(this.div(num, 100, 0), 100) + '';
-        } else {
-            return '10000';
         }
+        return '10000';
+
     },
 
     /**
@@ -444,9 +445,9 @@ module.exports = {
      * @param idField
      * @param pidField
      */
-    sortTreeNodes (treeNodes, idField, pidField) {
+    sortTreeNodes(treeNodes, idField, pidField) {
         const result = [];
-        const getFirstLevel = function (nodes) {
+        const getFirstLevel = function(nodes) {
             let result;
             for (const node of nodes) {
                 if (!result || result > node.level) {
@@ -455,26 +456,26 @@ module.exports = {
             }
             return result;
         };
-        const getLevelNodes = function (nodes, level) {
-            const children = nodes.filter(function (a) {
+        const getLevelNodes = function(nodes, level) {
+            const children = nodes.filter(function(a) {
                 return a.level = level;
             });
-            children.sort(function (a, b) {
+            children.sort(function(a, b) {
                 return a.order - b.order;
             });
             return children;
         };
-        const getChildren = function (nodes, node) {
-            const children = nodes.filter(function (a) {
+        const getChildren = function(nodes, node) {
+            const children = nodes.filter(function(a) {
                 return a[pidField] = node[idField];
             });
-            children.sort(function (a, b) {
+            children.sort(function(a, b) {
                 return a.order - b.order;
             });
             return children;
         };
-        const addSortNodes = function (nodes) {
-            for (let i = 0; i< nodes.length; i++) {
+        const addSortNodes = function(nodes) {
+            for (let i = 0; i < nodes.length; i++) {
                 result.push(nodes[i]);
                 addSortNodes(getChildren(nodes[i]));
             }
@@ -524,7 +525,7 @@ module.exports = {
     /**
      * 递归创建文件夹(fs.mkdirSync需要上一层文件夹已存在)
      * @param pathName
-     * @returns {Promise<void>}
+     * @return {Promise<void>}
      */
     async recursiveMkdirSync(pathName) {
         if (!fs.existsSync(pathName)) {
@@ -540,7 +541,7 @@ module.exports = {
      * 字节 保存至 本地文件
      * @param buffer - 字节
      * @param fileName - 文件名
-     * @returns {Promise<void>}
+     * @return {Promise<void>}
      */
     async saveBufferFile(buffer, fileName) {
         // 检查文件夹是否存在,不存在则直接创建文件夹
@@ -555,7 +556,7 @@ module.exports = {
      * 将文件流的数据保存至本地文件
      * @param stream
      * @param fileName
-     * @returns {Promise<void>}
+     * @return {Promise<void>}
      */
     async saveStreamFile(stream, fileName) {
         // 读取字节流
@@ -569,7 +570,7 @@ module.exports = {
     /**
      * 检查code是否是指标模板数据
      * @param {String} code
-     * @returns {boolean}
+     * @return {boolean}
      */
     validBillsCode(code) {
         const reg1 = /(^[0-9]+)([a-z0-9\-]*)/i;
@@ -579,11 +580,11 @@ module.exports = {
 
     getNumberFormatter(decimal) {
         if (decimal <= 0) {
-            return "0";
+            return '0';
         }
-        let pre = "0.";
+        let pre = '0.';
         for (let i = 0; i < decimal; i++) {
-            pre += "#"
+            pre += '#';
         }
         return pre;
     },
@@ -592,7 +593,7 @@ module.exports = {
      * 根据单位查找对应的清单精度
      * @param {tenderInfo.precision} list - 清单精度列表
      * @param {String} unit - 单位
-     * @returns {number}
+     * @return {number}
      */
     findPrecision(list, unit) {
         if (unit) {
@@ -637,9 +638,9 @@ module.exports = {
                 }
             }
             return result;
-        } else {
-            return data;
         }
+        return data;
+
     },
 
     // 加减乘除方法,为方便调用,兼容num为空的情况
@@ -648,16 +649,16 @@ module.exports = {
      * 加法 num1 + num2
      * @param num1
      * @param num2
-     * @returns {number}
+     * @return {number}
      */
     add(num1, num2) {
-        return bc.add(num1 ? num1 : 0, num2 ? num2: 0);
+        return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
     },
     /**
      * 减法 num1 - num2
      * @param num1
      * @param num2
-     * @returns {number}
+     * @return {number}
      */
     sub(num1, num2) {
         return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
@@ -666,7 +667,7 @@ module.exports = {
      * 乘法 num1 * num2
      * @param num1
      * @param num2
-     * @returns {*}
+     * @return {*}
      */
     mul(num1, num2, digit = 6) {
         if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
@@ -678,29 +679,29 @@ module.exports = {
      * 除法 num1 / num2
      * @param num1 - 被除数
      * @param num2 - 除数
-     * @returns {*}
+     * @return {*}
      */
     div(num1, num2, digit = 6) {
         if (num2 && !this.checkZero(num2)) {
-            return Decimal.div(num1 ? num1: 0, num2).toDecimalPlaces(digit).toNumber();
-        } else {
-            return null;
+            return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
         }
+        return null;
+
     },
     /**
      * 四舍五入(统一,方便以后万一需要置换)
      * @param {Number} value - 舍入的数字
      * @param {Number} decimal - 要保留的小数位数
-     * @returns {*}
+     * @return {*}
      */
     round(value, decimal) {
-        //return value ? bc.round(value, decimal) : null;
+        // return value ? bc.round(value, decimal) : null;
         return value ? new Decimal(value).toDecimalPlaces(decimal).toNumber() : null;
     },
     /**
      * 汇总
      * @param array
-     * @returns {number}
+     * @return {number}
      */
     sum(array) {
         let result = 0;
@@ -715,7 +716,7 @@ module.exports = {
      * @param str
      * @param reg
      * @param subStr
-     * @returns {*}
+     * @return {*}
      */
     replaceStr(str, reg, subStr) {
         return str ? str.replace(reg, subStr) : str;
@@ -723,7 +724,7 @@ module.exports = {
     /**
      * 替换字符串中的 换行符回车符
      * @param str
-     * @returns {*}
+     * @return {*}
      */
     replaceReturn(str) {
         // return str
@@ -737,7 +738,7 @@ module.exports = {
     /**
      * 替换字符串中的 换行符回车符为换行符<br>
      * @param str
-     * @returns {*}
+     * @return {*}
      */
     replaceRntoBr(str) {
         // return str
@@ -752,13 +753,13 @@ module.exports = {
      * 获取 字符串 数组的 mysql 筛选条件
      *
      * @param arr
-     * @returns {*}
+     * @return {*}
      */
     getInArrStrSqlFilter(arr) {
         let result = '';
         for (const a of arr) {
             if (result !== '') {
-                result = result + ','
+                result = result + ',';
             }
             result = result + this.ctx.app.mysql.escape(a);
         }
@@ -771,8 +772,9 @@ module.exports = {
      * @param {Array[]}rela - 相关数据 {data, fields, prefix, relaId}
      */
     assignRelaData(main, rela) {
-        const index = {}, indexPre = 'id_';
-        const loadFields = function (datas, fields, prefix, relaId) {
+        const index = {},
+            indexPre = 'id_';
+        const loadFields = function(datas, fields, prefix, relaId) {
             for (const d of datas) {
                 const key = indexPre + d[relaId];
                 const m = index[key];
@@ -793,7 +795,7 @@ module.exports = {
         }
     },
 
-    whereSql (where, as) {
+    whereSql(where, as) {
         if (!where) {
             return '';
         }
@@ -817,31 +819,31 @@ module.exports = {
     },
     formatMoney(s, dot = ',') {
         if (!s) return '0.00';
-        s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
-        var l = s.split(".")[0].split("").reverse(),
-            r = s.split(".")[1];
-        let t = "";
-        for(let i = 0; i < l.length; i ++ )   {
-            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
+        s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(2) + '';
+        let l = s.split('.')[0].split('').reverse(),
+            r = s.split('.')[1];
+        let t = '';
+        for (let i = 0; i < l.length; i++) {
+            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : '');
         }
-        return t.split("").reverse().join("") + "." + r;
+        return t.split('').reverse().join('') + '.' + r;
     },
     transFormToChinese(num) {
         const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
-        const unit = ["", "十", "百", "千", "万"];
+        const unit = ['', '十', '百', '千', '万'];
         num = parseInt(num);
-        let getWan = (temp) => {
-            let strArr = temp.toString().split("").reverse();
-            let newNum = "";
-            for (var i = 0; i < strArr.length; i++) {
-                newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
+        const getWan = temp => {
+            const strArr = temp.toString().split('').reverse();
+            let newNum = '';
+            for (let i = 0; i < strArr.length; i++) {
+                newNum = (i == 0 && strArr[i] == 0 ? '' : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? '' : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
             }
-            return strArr.length === 2 && newNum.indexOf("一十") !== -1 ? newNum.replace('一十', '十') : newNum;
-        }
-        let overWan = Math.floor(num / 10000);
+            return strArr.length === 2 && newNum.indexOf('一十') !== -1 ? newNum.replace('一十', '十') : newNum;
+        };
+        const overWan = Math.floor(num / 10000);
         let noWan = num % 10000;
-        if (noWan.toString().length < 4) noWan = "0" + noWan;
-        return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
+        if (noWan.toString().length < 4) noWan = '0' + noWan;
+        return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num);
     },
 
     dateTran(time) {
@@ -926,20 +928,20 @@ module.exports = {
             alignment: { horizontal: 'center' },
         };
         const sHeader = setting.header
-            .map((v, i) => Object.assign({}, { v: v, s: headerStyle, position: String.fromCharCode(65+i) + 1 }))
-            .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
+            .map((v, i) => Object.assign({}, { v, s: headerStyle, position: String.fromCharCode(65 + i) + 1 }))
+            .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
         const sData = data
             .map((v, i) => v.map((k, j) => Object.assign({}, {
                 v: k ? k : '',
-                s: { font: { sz: 10 }, alignment: {horizontal: setting.hAlign[j]}},
-                position: String.fromCharCode(65+j) + (i+2) })))
+                s: { font: { sz: 10 }, alignment: { horizontal: setting.hAlign[j] } },
+                position: String.fromCharCode(65 + j) + (i + 2) })))
             .reduce((prev, next) => prev.concat(next))
-            .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v, s: next.s}}), {});
+            .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v, s: next.s } }), {});
         const output = Object.assign({}, sHeader, sData);
         const outputPos = Object.keys(output);
         const result = Object.assign({}, output,
-            {'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]},
-            {'!cols': setting.width.map((w) => Object.assign({}, {wpx: w}))});
+            { '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] },
+            { '!cols': setting.width.map(w => Object.assign({}, { wpx: w })) });
         return result;
     },
 
@@ -948,7 +950,7 @@ module.exports = {
             this.ctx.logger.error(error);
         } else {
             this.ctx.getLogger('fail').info(JSON.stringify({
-                error: error,
+                error,
                 project: this.ctx.session.sessionProject,
                 user: this.ctx.session.sessionUser,
                 body: this.ctx.session.body,
@@ -977,13 +979,13 @@ module.exports = {
     /**
      * 深拷贝
      * @param obj
-     * @returns {*}
+     * @return {*}
      */
-    clone: function (obj) {
+    clone(obj) {
         if (obj === null) return null;
-        var o = obj instanceof Array ? [] : {};
-        for (var i in obj) {
-            o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? this.clone(obj[i]) : obj[i]);
+        const o = obj instanceof Array ? [] : {};
+        for (const i in obj) {
+            o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === 'object' ? this.clone(obj[i]) : obj[i]);
         }
         return o;
     },
@@ -991,7 +993,7 @@ module.exports = {
     /**
      * 短链接生成
      * @param url
-     * @returns {*}
+     * @return {*}
      */
     async urlToShort(url) {
         const apiUrl = 'http://scn.ink/api/shorturl';
@@ -1005,7 +1007,7 @@ module.exports = {
     /**
      * 判断是否wap访问
      * @param request
-     * @returns {*}
+     * @return {*}
      */
     isWap(request) {
         return request.url.indexOf('/wap/') !== -1;
@@ -1017,11 +1019,12 @@ module.exports = {
             source: {
                 bills: [],
                 pos: [],
-            }
+            },
         };
         for (const b of bills) {
-            const pr = _.remove(pos, {lid: b.id});
-            const checkData = {}, calcData = {};
+            const pr = _.remove(pos, { lid: b.id });
+            const checkData = {},
+                calcData = {};
             if (pr && pr.length > 0) {
                 for (const field of fields) {
                     checkData[field] = b[field] ? b[field] : 0;
@@ -1036,7 +1039,7 @@ module.exports = {
                         ledger_id: b.ledger_id,
                         b_code: b.b_code,
                         name: b.name,
-                        error: {checkData: checkData, calcData: calcData}
+                        error: { checkData, calcData },
                     });
                     result.source.bills.push(b);
                     for (const p of pr) {
@@ -1058,9 +1061,24 @@ module.exports = {
     /**
      * 判断是否是移动端访问
      * @param request
-     * @returns {*}
+     * @return {*}
      */
     isMobile(agent) {
         return agent.match(/(iphone|ipod|android)/i);
     },
-}
+
+    /**
+     * 删除文件
+     * @param {Array} fileList 文件数组(格式为数据库查询出来的结果集,且文件字段必须为filepath)
+     * @return {void}
+     */
+    async delFiles(fileList) {
+        if (fileList.length !== 0) {
+            for (const att of fileList) {
+                if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
+                    await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
+                }
+            }
+        }
+    },
+};

+ 2 - 2
app/public/js/material_file.js

@@ -31,7 +31,7 @@ $(document).ready(function () {
                     result.forEach((fileInfo, idx) => {
                         html += `<tr>
                         <td>${idx + 1}</td>
-                        <td><a href="/${fileInfo.file_path}">${fileInfo.file_name}</a></td>
+                        <td><a href="/${fileInfo.filepath}">${fileInfo.file_name}</a></td>
                         <td>${fileInfo.file_size}</td>
                         <td>${fileInfo.upload_time}</td>`
                     if (user_id == fileInfo.user_id && !checked) {
@@ -61,7 +61,7 @@ $(document).ready(function () {
             result.forEach((fileInfo, idx) => {
                 html += `<tr>
                 <td>${idx + 1 }</td>
-                <td><a href="/${fileInfo.file_path}">${fileInfo.file_name}</a></td>
+                <td><a href="/${fileInfo.filepath}">${fileInfo.file_name}</a></td>
                 <td>${fileInfo.file_size}</td>
                 <td>${fileInfo.upload_time}</td>`
                 if (user_id == fileInfo.user_id && !checked) {

+ 0 - 1
app/router.js

@@ -290,7 +290,6 @@ module.exports = app => {
     app.get('/tender/:id/measure/material/:order/file', sessionAuth, tenderCheck, materialCheck, 'materialController.file');
     app.post('/tender/:id/measure/material/:order/file/upload', sessionAuth, tenderCheck, materialCheck, 'materialController.upload');
     app.post('/tender/:id/measure/material/:order/file/find', sessionAuth, tenderCheck, materialCheck, 'materialController.getCurMatericalFiles');
-    app.get('/tender/measure/material/file/download/:fid', sessionAuth, 'materialController.downloadFile');
     app.post('/tender/measure/material/file/delete', sessionAuth, 'materialController.deleteFile');
 
     // 个人账号相关

+ 12 - 8
app/service/material.js

@@ -27,7 +27,7 @@ module.exports = app => {
          * 获取 最新一期 材料调差期计量
          * @param tenderId
          * @param includeUnCheck
-         * @returns {Promise<*>}
+         * @return {Promise<*>}
          */
         async getLastestMaterial(tenderId, includeUnCheck = false) {
             this.initSqlBuilder();
@@ -50,7 +50,7 @@ module.exports = app => {
         /**
          * 获取 最新一期 审批完成的 材料调差期计量
          * @param tenderId
-         * @returns {Promise<*>}
+         * @return {Promise<*>}
          */
         async getLastestCompleteMaterial(tenderId) {
             this.initSqlBuilder();
@@ -71,7 +71,7 @@ module.exports = app => {
         /**
          * 获取标段下的全部计量期,按倒序
          * @param tenderId
-         * @returns {Promise<void>}
+         * @return {Promise<void>}
          */
         async getValidMaterials(tenderId) {
             const materials = await this.db.select(this.tableName, {
@@ -101,7 +101,7 @@ module.exports = app => {
          * 添加材料调差期
          * @param tenderId - 标段id
          * @param data - post的数据
-         * @returns {Promise<void>}
+         * @return {Promise<void>}
          */
         async addMaterial(tenderId, data) {
             const materials = await this.getAllDataByCondition({
@@ -169,7 +169,7 @@ module.exports = app => {
          * 删除材料调差期
          *
          * @param {Number} id - 期Id
-         * @returns {Promise<void>}
+         * @return {Promise<void>}
          */
         async deleteMaterial(id) {
             const transaction = await this.db.beginTransaction();
@@ -179,6 +179,7 @@ module.exports = app => {
                 await transaction.delete(this.ctx.service.materialList.tableName, { mid: id });
                 await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { mid: id });
                 await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { mid: id });
+                await transaction.delete(this.ctx.service.materialFile.tableName, { mid: id });
                 // 如果存在上一期,把上一期的quantity,pre_tp添加到bill中
                 const materialInfo = await this.getDataById(id);
                 if (materialInfo.order > 1) {
@@ -191,6 +192,9 @@ module.exports = app => {
                 }
                 await transaction.delete(this.tableName, { id });
                 await transaction.commit();
+                // 删除期第一个参数不用传,第二个为期数
+                const attList = await this.ctx.service.materialFile.getAllMaterialFiles('', id);
+                await this.ctx.helper.delFiles(attList);
                 return true;
             } catch (err) {
                 await transaction.rollback();
@@ -202,7 +206,7 @@ module.exports = app => {
          * 获取包含当前期之前的调差期id
          *
          * @param {Number} id - 期Id
-         * @returns {Promise<void>}
+         * @return {Promise<void>}
          */
         async getPreMidList(tid, order) {
             const midList = await this.getAllDataByCondition({
@@ -221,7 +225,7 @@ module.exports = app => {
         /**
          * 修改增税税率
          * @param {int} rate 税率
-         * @returns {Promise<*>}
+         * @return {Promise<*>}
          */
         async changeRate(rate) {
             const updateData = {
@@ -235,7 +239,7 @@ module.exports = app => {
          * 修改增税税率
          * @param {int} tid 标段id
          * @param {int} order 调差期数
-         * @returns {Promise<*>}
+         * @return {Promise<*>}
          */
         async getPreTpHs(tid, order) {
             const sql = 'SELECT SUM(ROUND(`m_tp`*(1+ `rate`/100),2)) AS `pre_tp_hs` FROM ?? WHERE `tid` = ? AND `order` < ?';

+ 5 - 3
app/service/material_file.js

@@ -24,12 +24,14 @@ module.exports = app => {
 
         /**
          * 获取当前标段所有上传的附件
-         * @param {Number} tenderId 标段id
-         * @param {Number} mid 期id
+         * @param {Number?} tenderId 标段id
+         * @param {Number?} mid 期id
          * @return {Promise<void>} 数据库查询实例
          */
         async getAllMaterialFiles(tenderId, mid) {
-            const where = mid ? { tid: tenderId, mid } : { tid: tenderId };
+            const where = {};
+            if (tenderId) where.tenderId = tenderId;
+            if (mid) where.mid = mid;
             return await this.db.select(this.tableName, {
                 where,
             });

+ 8 - 11
app/service/tender.js

@@ -147,7 +147,7 @@ module.exports = app => {
             return list;
         }
 
-        async getTender (id) {
+        async getTender(id) {
             this.initSqlBuilder();
             this.sqlBuilder.setAndWhere('id', {
                 value: id,
@@ -230,7 +230,7 @@ module.exports = app => {
             id = parseInt(id);
 
             const rowData = {
-                id: id,
+                id,
                 name: postData.name,
                 type: postData.type,
                 category: JSON.stringify(postData.category),
@@ -258,7 +258,7 @@ module.exports = app => {
         /**
          * 真删除
          * @param {Number} id - 删除的标段id
-         * @returns {Promise<boolean>} - 结果
+         * @return {Promise<boolean>} - 结果
          */
         async deleteTenderNoBackup(id) {
             const transaction = await this.db.beginTransaction();
@@ -293,18 +293,15 @@ module.exports = app => {
                 await transaction.delete(this.ctx.service.materialBillsHistory.tableName, { tid: id });
                 await transaction.delete(this.ctx.service.materialList.tableName, { tid: id });
                 await transaction.delete(this.ctx.service.materialListNotjoin.tableName, { tid: id });
+                await transaction.delete(this.ctx.service.materialFile.tableName, { tid: id });
 
                 await transaction.delete(this.ctx.service.signatureUsed.tableName, { tender_id: id });
                 await transaction.delete(this.ctx.service.signatureRole.tableName, { tender_id: id });
                 // 先删除附件文件
                 const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { tid: id } });
-                if (attList.length !== 0) {
-                    for (const att of attList) {
-                        if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
-                            await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
-                        }
-                    }
-                }
+                const newAttList = await this.ctx.service.materialFile.getAllMaterialFiles(id);
+                attList.concat(newAttList);
+                await this.ctx.helper.delFiles(attList);
                 await transaction.delete(this.ctx.service.changeAtt.tableName, { tid: id });
                 await transaction.commit();
                 return true;
@@ -371,7 +368,7 @@ module.exports = app => {
             const tenderNodeTemplateData = await this.ctx.service.tenderNodeTemplate.getData(templateId);
             const conn = await this.db.beginTransaction();
             try {
-                await conn.update(this.tableName, {id: tender.id, measure_type: type});
+                await conn.update(this.tableName, { id: tender.id, measure_type: type });
 
                 // 复制模板数据到标段数据表
                 const result = await this.ctx.service.ledger.innerAdd(tenderNodeTemplateData, tender.id, conn);

+ 1 - 4
app/view/material/file.ejs

@@ -11,9 +11,6 @@
             <span class="text-primary" style="margin-left: 5px;">所有期</span>
           </span>
         </div>
-      <div>
-        <a href="#sub-ap" data-toggle="modal" data-target="#sub-ap" class="btn btn-sm btn-primary pull-right">上报审批</a>
-      </div>
     </div>
   </div>
   <div class="content-wrap">
@@ -28,7 +25,7 @@
               <tr>
                 <td><%=idx + 1%></td>
                 <td>
-                  <a href="/<%- file.file_path %>" target="_blank"><%=file.file_name%></a>
+                  <a href="/<%- file.filepath %>" target="_blank"><%=file.file_name%></a>
                 </td><td><%=file.file_size%></td>
                 <td><%=file.upload_time%></td>
                 <td>