浏览代码

正负变更,旧数据兼容脚本

MaiXinRong 2 年之前
父节点
当前提交
db150d1a35
共有 3 个文件被更改,包括 247 次插入0 次删除
  1. 163 0
      db_script/baseUtils.js
  2. 74 0
      db_script/change.js
  3. 10 0
      sql/update.sql

+ 163 - 0
db_script/baseUtils.js

@@ -0,0 +1,163 @@
+'use strict';
+
+
+const fs = require('fs');
+const path = require('path');
+var util = require('util');
+var logPath = path.join(__dirname, 'change_rela.log');
+var logFile = fs.createWriteStream(logPath, { flags: 'a' });
+console.log = function() {
+    logFile.write(util.format.apply(null, arguments) + '\n');
+    process.stdout.write(util.format.apply(null, arguments) + '\n');
+};
+
+const mysql = require('mysql');
+const config = process.argv.splice(2)[0];
+if (['local', 'uat', 'default'].indexOf(config) < 0) throw `参数错误: ${config}`;
+const options = require(`../config/config.${config}`)({ baseDir: __dirname + '/app', root: __dirname, name: 'calc' });
+const pool = mysql.createPool(options.mysql.client);
+const querySql = async function(sql, sqlParam) {
+    return new Promise(function(resolve, reject) {
+        pool.getConnection(function(err, conn) {
+            if (err) {
+                if (err) console.log(err);
+                reject(err);
+            } else {
+                conn.query(sql, sqlParam, function(err, rows, fields) {
+                    if (err) console.log(err);
+                    // 释放连接
+                    conn.release();
+                    // 传递Promise回调对象
+                    resolve(rows);
+                });
+            }
+        });
+    });
+};
+
+const timesLen = 100;
+const filterLastestData = function (data, keyFields, timesField = 'times', orderField = 'order') {
+    const dataIndex = {};
+    for (const d of data) {
+        let key = 'd';
+        for (const kf of keyFields) {
+            key = key + '.' + (d[kf] || '');
+        }
+
+        const di = dataIndex[key];
+        if (di) {
+            if ((di[timesField] * timesLen + di[orderField]) < (d[timesField] * timesLen + d[orderField])) dataIndex[key] = d;
+        } else {
+            dataIndex[key] = d;
+        }
+    }
+    const result = [];
+    for (const prop in dataIndex) {
+        result.push(dataIndex[prop]);
+    }
+    return result;
+};
+
+const zeroRange = 0.0000000001;
+const bc = require('../app/lib/base_calc.js');
+const Decimal = require('decimal.js');
+Decimal.set({ precision: 50, defaults: true });
+
+const ZhCalc = {
+    // 加减乘除方法,为方便调用,兼容num为空的情况
+    // 加减法使用base_calc,乘除法使用Decimal(原因详见demo/calc_test)
+    /**
+     * 加法 num1 + num2
+     * @param num1
+     * @param num2
+     * @return {number}
+     */
+    add(num1, num2) {
+        return bc.add(num1 ? num1 : 0, num2 ? num2 : 0);
+    },
+    /**
+     * 减法 num1 - num2
+     * @param num1
+     * @param num2
+     * @return {number}
+     */
+    sub(num1, num2) {
+        return bc.sub(num1 ? num1 : 0, num2 ? num2 : 0);
+    },
+    /**
+     * 乘法 num1 * num2
+     * @param num1
+     * @param num2
+     * @return {*}
+     */
+    mul(num1, num2, digit = 6) {
+        if (num1 === '' || num1 === null || num2 === '' || num2 === null) {
+            return 0;
+        }
+        return Decimal.mul(num1 ? num1 : 0, num2 ? num2 : 0).toDecimalPlaces(digit).toNumber();
+    },
+    /**
+     * 除法 num1 / num2
+     * @param num1 - 被除数
+     * @param num2 - 除数
+     * @return {*}
+     */
+    div(num1, num2, digit = 6) {
+        if (num2 && !this.checkZero(num2)) {
+            return Decimal.div(num1 ? num1 : 0, num2).toDecimalPlaces(digit).toNumber();
+        }
+        return null;
+
+    },
+    /**
+     * 四舍五入(统一,方便以后万一需要置换)
+     * @param {Number} value - 舍入的数字
+     * @param {Number} decimal - 要保留的小数位数
+     * @return {*}
+     */
+    round(value, decimal) {
+        return value ? new Decimal(value.toString()).toDecimalPlaces(decimal).toNumber() : 0;
+    },
+    /**
+     * 汇总
+     * @param array
+     * @return {number}
+     */
+    sum(array) {
+        let result = 0;
+        for (const a of array) {
+            result = this.add(result, a);
+        }
+        return result;
+    },
+    /**
+     * 检查数字是否为0
+     * @param {Number} value
+     * @return {boolean}
+     */
+    checkZero(value) {
+        return value === undefined || value === null || (this._.isNumber(value) && Math.abs(value) < zeroRange);
+    },
+    /**
+     * 检查数字是否相等
+     * @param {Number} value1
+     * @param {Number} value2
+     * @return {boolean}
+     */
+    numEqual(value1, value2) {
+        if (value1 && value2) {
+            return Math.abs(value2 - value1) < zeroRange;
+        }
+        return (!value1 && !value2);
+
+    },
+};
+
+module.exports = {
+    querySql,
+    filterLastestData,
+    closePool: function () {
+        pool.end();
+    },
+    ZhCalc,
+};

+ 74 - 0
db_script/change.js

@@ -0,0 +1,74 @@
+// 计算变更令,正负变更数
+
+const defaultInfo = require('../app/const/tender_info');
+const BaseUtil = require('./baseUtils');
+const querySql = BaseUtil.querySql;
+const ZhCalc = BaseUtil.ZhCalc;
+const audit = require('../app/const/audit');
+
+const checkChange = async function(change, decimal) {
+    const changeBills = await querySql('Select * From zh_change_audit_list where cid = ?', [change.cid]);
+    let p_tp = 0, n_tp = 0;
+    for (const cb of changeBills) {
+        cb.tp = ZhCalc.mul(cb.spamount, cb.unit_price, change.tp_decimal || decimal.tp);
+        if (cb.spamount > 0) {
+            p_tp = ZhCalc.add(p_tp, cb.tp);
+        } else if (cb.spamount < 0){
+            n_tp = ZhCalc.add(n_tp, cb.tp);
+        }
+    }
+    await querySql('Update zh_change Set positive_tp = ?, negative_tp = ? Where cid = ?', [p_tp, n_tp, change.cid]);
+    console.log(`Update Change ${change.cid}: p_tp(${p_tp}), n_tp(${n_tp})`);
+};
+
+const checkStage = async function(stage, decimal, preStage) {
+    let stageChange;
+    if (stage.status === 3) {
+        stageChange = await querySql('Select scf.*, cal.unit_price From zh_stage_change_final scf Left Join zh_change_audit_list cal ON scf.cbid = cal.id where sid = ?', [stage.id]);
+    } else {
+        const stageChangeAll = await querySql('SELECT sc.*, cal.unit_price FROM zh_stage_change sc Left Join zh_change_audit_list cal ON sc.cbid = cal.id WHERE sid = ?', [stage.id]);
+        stageChange = BaseUtil.filterLastestData(stageChangeAll, ['lid', 'pid', 'cbid', 'no_value'], 'stimes', 'sorder');
+    }
+    if (stageChange.length === 0) return;
+
+    stage.positive_qc_tp = 0;
+    stage.pre_positive_qc_tp = preStage ? ZhCalc.add(stage.positive_qc_tp, stage.pre_positive_qc_tp) : 0;
+    stage.negative_qc_tp = 0;
+    stage.pre_negative_qc_tp = preStage ? ZhCalc.add(stage.negative_qc_tp, stage.pre_negative_qc_tp) : 0;
+    for (const sc of stageChange) {
+        if (sc.no_value || !sc.qty) continue;
+        const tp = ZhCalc.mul(sc.unit_price, sc.qty, decimal.tp);
+        if (sc.minus) {
+            stage.negative_qc_tp = ZhCalc.add(tp, stage.negative_qc_tp);
+        } else {
+            stage.positive_qc_tp = ZhCalc.add(tp, stage.positive_qc_tp);
+        }
+    }
+
+    await querySql('Update zh_stage Set positive_qc_tp = ?, pre_positive_qc_tp = ?, negative_qc_tp = ?, pre_negative_qc_tp = ? Where id = ?', [stage.positive_qc_tp, stage.pre_positive_qc_tp, stage.negative_qc_tp, stage.pre_negative_qc_tp, stage.id]);
+    console.log(`Update Stage ${stage.order}: p_tp(${stage.positive_qc_tp}), pre_p_tp(${stage.pre_positive_qc_tp}), n_tp(${stage.negative_qc_tp}), pre_n_tp(${stage.pre_negative_qc_tp})`);
+};
+
+const doComplete = async function() {
+    try {
+        const tender = await querySql('Select * From zh_tender');
+        for (const t of tender) {
+            console.log(`Update Tender ${t.id}:`);
+            const info = await querySql('Select * From zh_tender_info where tid = ?', [t.id]);
+            const decimal = info[0].decimal ? JSON.parse(info[0].decimal) : defaultInfo.parseInfo.decimal;
+
+            const changes = await querySql('Select * From zh_change where tid = ?', [t.id]);
+            for (const c of changes) {
+                await checkChange(c, decimal);
+            }
+            const stage = await querySql('Select * From zh_stage where tid = ? order by `order` asc', [t.id]);
+            for (const [i, s] of stage.entries()) {
+                await checkStage(s, decimal, i > 1 ? stage[i-1] : null);
+            }
+        }
+    } catch (err) {
+        console.log(err);
+    }
+    BaseUtil.closePool();
+};
+doComplete();

+ 10 - 0
sql/update.sql

@@ -245,3 +245,13 @@ ALTER TABLE `zh_ledger_revise`
 ADD COLUMN `sum`   varchar(255) NOT NULL DEFAULT '' COMMENT 'sum统计数据' AFTER `pre_his_id`;
 
 ALTER TABLE `zh_project` ADD `fun_set` VARCHAR(1000) NULL DEFAULT NULL COMMENT '项目设置页内容json' AFTER `map_json`;
+
+ALTER TABLE `zh_change`
+ADD COLUMN `positive_tp`  decimal(24,8) NOT NULL DEFAULT 0 COMMENT '正变更金额' AFTER `order_by`,
+ADD COLUMN `negative_tp`  decimal(24,8) NOT NULL DEFAULT 0 COMMENT '负变更金额' AFTER `positive_tp`;
+
+ALTER TABLE `zh_stage`
+ADD COLUMN `positive_qc_tp`  decimal(24,8) NULL DEFAULT 0 COMMENT '本期-正-变更金额' AFTER `his_id`,
+ADD COLUMN `pre_positive_qc_tp`  decimal(24,8) NULL DEFAULT 0 COMMENT '截止上期-正-变更金额' AFTER `positive_qc_tp`,
+ADD COLUMN `negative_qc_tp`  decimal(24,8) NULL DEFAULT 0 COMMENT '本期-负-变更金额' AFTER `pre_positive_qc_tp`,
+ADD COLUMN `pre_negative_qc_tp`  decimal(24,8) NULL DEFAULT 0 COMMENT '截止上期-负-变更金额' AFTER `negative_qc_tp`;