| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 | 'use strict';/** * * * @author Mai * @date * @version */const TreeService = require('./base_tree_service');const billsUtils = require('../lib/bills_utils');const readOnlyFields = ['id', 'bid', 'tree_id', 'tree_pid', 'order', 'level', 'full_path', 'is_leaf'];const calcFields = ['unit_price', 'quantity', 'total_price'];class BaseBudget extends TreeService {    /**     * 构造函数     *     * @param {Object} ctx - egg全局变量     * @param {String} tableName - 表名     * @return {void}     */    constructor(ctx, setting, tablename) {        super(ctx, {            mid: 'bid',            kid: 'tree_id',            pid: 'tree_pid',            order: 'order',            level: 'level',            isLeaf: 'is_leaf',            fullPath: 'full_path',            keyPre: setting.keyPre,            uuid: true,        });        this.tableName = tablename;    }    async initByTemplate(conn, budgetId, templateId){        if (!conn) throw '内部错误';        if (budgetId <= 0) throw '概算项目id错误';        const data = await this.ctx.service.tenderNodeTemplate.getData(templateId);        if (!data.length) throw '模板数据有误';        // 整理数据        const insertData = [];        for (const tmp of data) {            insertData.push({                id: this.uuid.v4(),                bid: budgetId,                tree_id: tmp.template_id,                tree_pid: tmp.pid,                level: tmp.level,                order: tmp.order,                full_path: tmp.full_path,                is_leaf: tmp.is_leaf,                code: tmp.code,                name: tmp.name,                unit: tmp.unit,                node_type: tmp.node_type,            });        }        const operate = await conn.insert(this.tableName, insertData);        return operate.affectedRows === data.length;    }    async addChild(budgetId, selectId, data) {        if ((budgetId <= 0) || (selectId <= 0)) return [];        const selectData = await this.getDataByKid(budgetId, selectId);        if (!selectData) {            throw '新增节点数据错误';        }        const children = await this.getChildrenByParentId(budgetId, selectId);        const maxId = await this._getMaxLid(budgetId);        data.id = this.uuid.v4();        data.bid = budgetId;        data.tree_id = maxId + 1;        data.tree_pid = selectData.tree_id;        data.level = selectData.level + 1;        data.order = children.length + 1;        data.full_path = selectData.full_path + '-' + data.tree_id;        data.is_leaf = true;        this.transaction = await this.db.beginTransaction();        try {            const result = await this.transaction.insert(this.tableName, data);            if (children.length === 0) {                await this.transaction.update(this.tableName,                    { is_leaf: false, quantity: 0, unit_price: 0, total_price: 0 },                    { where: { bid: budgetId, tree_id: selectData.tree_id } });            }            await this.transaction.commit();        } catch(err) {            this.transaction.rollback();            throw err;        }        this._cacheMaxLid(budgetId, maxId + 1);        // 查询应返回的结果        const resultData = {};        resultData.create = await this.getDataByKid(budgetId, data.tree_id);        if (children.length === 0) resultData.update = await this.getDataByKid(budgetId, selectId);        return resultData;    }    _filterStdData(stdData) {        const result = {            name: stdData.name,            unit: stdData.unit,            node_type: stdData.node_type,        };        result.code = stdData.code ? stdData.code : '';        result.b_code = stdData.b_code ? stdData.b_code : '';        return result;    }    async _addChildNodeData(budgetId, parentData, data) {        if (budgetId <= 0) return undefined;        if (!data) data = {};        const pid = parentData ? parentData.tree_id : this.rootId;        const maxId = await this._getMaxLid(budgetId);        data.id = this.uuid.v4();        data.bid = budgetId;        data.tree_id = maxId + 1;        data.tree_pid = pid;        if (data.order === undefined) data.order = 1;        data.level = parentData ? parentData.level + 1 : 1;        data.full_path = parentData ? parentData.full_path + '-' + data.tree_id : '' + data.tree_id;        if (data.is_leaf === undefined) data.is_leaf = true;        const result = await this.transaction.insert(this.tableName, data);        this._cacheMaxLid(budgetId, maxId + 1);        return [result, data];    }    async _addChildAutoOrder(budgetId, parentData, data) {        const findPreData = function(list, a) {            if (!list || list.length === 0) { return null; }            for (let i = 0, iLen = list.length; i < iLen; i++) {                if (billsUtils.compareCode(list[i].code, a.code) > 0) {                    return i > 0 ? list[i - 1] : null;                }            }            return list[list.length - 1];        };        const pid = parentData ? parentData.tree_id : this.rootId;        const children = await this.getChildrenByParentId(budgetId, pid);        const preData = findPreData(children, data);        if (!preData || children.indexOf(preData) < children.length - 1) {            await this._updateChildrenOrder(budgetId, pid, preData ? preData.order + 1 : 1);        }        data.order = preData ? preData.order + 1 : 1;        const [addResult, node] = await this._addChildNodeData(budgetId, parentData, data);        return [addResult, node];    }    async addStdNodeWithParent(budgetId, stdData, stdLib) {        // 查询完整标准清单,并按层次排序        const fullLevel = await stdLib.getFullLevelDataByFullPath(stdData.list_id, stdData.full_path);        fullLevel.sort(function(x, y) {            return x.level - y.level;        });        let isNew = false,            node,            firstNew,            updateParent,            addResult;        const expandIds = [];        this.transaction = await this.db.beginTransaction();        try {            // 从最顶层节点依次查询是否存在,否则添加            for (let i = 0, len = fullLevel.length; i < len; i++) {                const stdNode = fullLevel[i];                if (isNew) {                    const newData = this._filterStdData(stdNode);                    newData.is_leaf = (i === len - 1);                    [addResult, node] = await this._addChildNodeData(budgetId, node, newData);                } else {                    const parent = node;                    node = await this.getDataByCondition({                        bid: budgetId,                        tree_pid: parent ? parent.tree_id : this.rootId,                        code: stdNode.code,                        name: stdNode.name,                    });                    if (!node) {                        isNew = true;                        const newData = this._filterStdData(stdNode);                        newData.is_leaf = (i === len - 1);                        [addResult, node] = await this._addChildAutoOrder(budgetId, parent, newData);                        if (parent && parent.is_leaf) {                            await this.transaction.update(this.tableName, { id: parent.id, is_leaf: false,                                unit_price: 0, quantity: 0, total_price: 0});                            updateParent = parent;                        }                        firstNew = node;                    } else {                        expandIds.push(node.tree_id);                    }                }            }            await this.transaction.commit();        } catch (err) {            await this.transaction.rollback();            throw err;        }        // 查询应返回的结果        let createData = [],            updateData = [];        if (firstNew) {            createData = await this.getDataByFullPath(budgetId, firstNew.full_path + '%');            updateData = await this.getNextsData(budgetId, firstNew.tree_pid, firstNew.order);            if (updateParent) {                updateData.push(await this.getDataByCondition({ id: updateParent.id }));            }        }        return { create: createData, update: updateData };    }    async addBillsNode(budgetId, selectId, data) {        return await this.addNode(budgetId, selectId, data ? data : {});    }    async addStdNode(budgetId, selectId, stdData) {        const newData = this._filterStdData(stdData);        const result = await this.addBillsNode(budgetId, selectId, newData);        return result;    }    async addStdNodeAsChild(budgetId, selectId, stdData) {        const newData = this._filterStdData(stdData);        const result = await this.addChild(budgetId, selectId, newData);        return result;    }    _filterUpdateInvalidField(id, data) {        const result = { id };        for (const prop in data) {            if (readOnlyFields.indexOf(prop) === -1) result[prop] = data[prop];        }        return result;    }    _checkCalcField(data) {        for (const prop in data) {            if (calcFields.indexOf(prop) >= 0) {                return true;            }        }        return false;    }    async updateCalc(budgetId, data) {        const helper = this.ctx.helper;        // 简单验证数据        if (budgetId <= 0 || !this.ctx.budget) throw '标段不存在';        if (!data) throw '提交数据错误';        const datas = data instanceof Array ? data : [data];        const ids = [];        for (const row of datas) {            if (budgetId !== row.bid) throw '提交数据错误';            ids.push(row.id);        }        const conn = await this.db.beginTransaction();        try {            for (const row of datas) {                const updateNode = await this.getDataById(row.id);                if (!updateNode || budgetId !== updateNode.bid || row.tree_id !== updateNode.tree_id) throw '提交数据错误';                let updateData;                // 项目节、工程量清单相关                if (row.b_code) {                    row.dgn_qty1 = 0;                    row.dgn_qty2 = 0;                    row.code = '';                }                if (row.code) row.b_code = '';                if (this._checkCalcField(row)) {                    let calcData = JSON.parse(JSON.stringify(row));                    if (row.quantity !== undefined || row.unit_price !== undefined) {                        calcData.quantity = row.quantity === undefined ? updateNode.quantity : helper.round(row.quantity, this.ctx.budget.decimal.qty);                        calcData.unit_price = row.unit_price === undefined ? updateNode.unit_price : helper.round(row.unit_price, this.ctx.budget.decimal.up);                        calcData.total_price = helper.mul(calcData.quantity, calcData.unit_price, this.ctx.budget.decimal.tp);                    } else if (row.total_price !== undefined ) {                        calcData.quantity = 0;                        calcData.unit_price = 0;                        calcData.total_price = helper.round(row.total_price, this.ctx.budget.decimal.tp);                    }                    updateData = this._filterUpdateInvalidField(updateNode.id, this._.defaults(calcData, row));                } else {                    updateData = this._filterUpdateInvalidField(updateNode.id, row);                }                await conn.update(this.tableName, updateData);            }            await conn.commit();        } catch (err) {            await conn.rollback();            throw err;        }        return { update: await this.getDataById(ids) };    }    async pasteBlockData (bid, sid, pasteData, defaultData) {        if ((bid <= 0) || (sid <= 0)) return [];        if (!pasteData || pasteData.length <= 0) throw '复制数据错误';        for (const pd of pasteData) {            if (!pd || pd.length <= 0) throw '复制数据错误';            pd.sort(function (x, y) {                return x.level - y.level            });            if (pd[0].tree_pid !== pasteData[0][0].tree_pid) throw '复制数据错误:仅可操作同层节点';        }        this.newBills = false;        const selectData = await this.getDataByKid(bid, sid);        if (!selectData) throw '粘贴数据错误';        const newParentPath = selectData.full_path.replace(selectData.tree_id, '');        const pasteBillsData = [];        let maxId = await this._getMaxLid(bid);        for (const [i, pd] of pasteData.entries()) {            for (const d of pd) {                d.children = pd.filter(function (x) {                    return x.tree_pid === d.tree_id;                });            }            const pbd = [];            for (const [j, d] of pd.entries()) {                const newBills = {                    id: this.uuid.v4(),                    bid: bid,                    tree_id: maxId + j + 1,                    tree_pid: j === 0 ? selectData.tree_pid : d.tree_pid,                    level: d.level + selectData.level - pd[0].level,                    order: j === 0 ? selectData.order + i + 1 : d.order,                    is_leaf: d.is_leaf,                    code: d.code,                    b_code: d.b_code,                    name: d.name,                    unit: d.unit,                    source: d.source,                    remark: d.remark,                    drawing_code: d.drawing_code,                    memo: d.memo,                    node_type: d.node_type,                };                for (const c of d.children) {                    c.tree_pid = newBills.tree_id;                }                if (d.b_code && d.is_leaf) {                    newBills.dgn_qty1 = 0;                    newBills.dgn_qty2 = 0;                    newBills.unit_price = this.ctx.helper.round(d.unit_price, this.ctx.budget.decimal.up);                    newBills.quantity = this.ctx.helper.round(d.quantity, this.ctx.budget.decimal.qty);                    newBills.total_price = this.ctx.helper.mul(newBills.quantity, newBills.unit_price, this.ctx.budget.decimal.tp);                } else {                    newBills.dgn_qty1 = this.ctx.helper.round(d.dgn_qty1, this.ctx.budget.decimal.qty);                    newBills.dgn_qty2 = this.ctx.helper.round(d.dgn_qty2, this.ctx.budget.decimal.qty);                    newBills.unit_price = 0;                    newBills.quantity = 0;                    newBills.total_price = d.is_leaf ? this.ctx.helper.round(d.total_price, this.ctx.budget.decimal.tp) : 0;                }                if (defaultData) this.ctx.helper._.assignIn(newBills, defaultData);                pbd.push(newBills);            }            for (const d of pbd) {                const parent = pbd.find(function (x) {                    return x.tree_id === d.tree_pid;                });                d.full_path = parent                    ? parent.full_path + '-' + d.tree_id                    : newParentPath + d.tree_id;                if (defaultData) this.ctx.helper._.assignIn(pbd, defaultData);                pasteBillsData.push(d);            }            maxId = maxId + pbd.length;        }        this.transaction = await this.db.beginTransaction();        try {            // 选中节点的所有后兄弟节点,order+粘贴节点个数            await this._updateChildrenOrder(bid, selectData.tree_pid, selectData.order + 1, pasteData.length);            // 数据库创建新增节点数据            if (pasteBillsData.length > 0) await this.transaction.insert(this.tableName, pasteBillsData);            this._cacheMaxLid(bid, maxId);            await this.transaction.commit();        } catch (err) {            await this.transaction.rollback();            throw err;        }        // 查询应返回的结果        const updateData = await this.getNextsData(selectData.bid, selectData.tree_pid, selectData.order + pasteData.length);        return { create: pasteBillsData, update: updateData };    }    async importExcel(templateId, excelData, needGcl, filter) {        const AnalysisExcel = require('../lib/analysis_excel').AnalysisExcelTree;        const analysisExcel = new AnalysisExcel(this.ctx, this.setting, needGcl ? ['code', 'b_code'] : ['code']);        const tempData = await this.ctx.service.tenderNodeTemplate.getData(templateId, true);        const cacheTree = analysisExcel.analysisData(excelData, tempData, {            filterZeroGcl: filter, filterPos: true, filterGcl: !needGcl, filterCalc: true,        });        const orgMaxId = await this._getMaxLid(this.ctx.budget.id);        const conn = await this.db.beginTransaction();        try {            await conn.delete(this.tableName, { bid: this.ctx.budget.id });            const datas = [];            for (const node of cacheTree.items) {                const data = {                    id: node.id,                    bid: this.ctx.budget.id,                    tree_id: node.tree_id,                    tree_pid: node.tree_pid,                    level: node.level,                    order: node.order,                    is_leaf: !node.children || node.children.length === 0,                    full_path: node.full_path,                    code: node.code || '',                    b_code: node.b_code || '',                    name: node.name || '',                    unit: node.unit || '',                    unit_price: !node.children || node.children.length === 0 ? node.unit_price || 0 : 0,                    dgn_qty1: node.dgn_qty1 || 0,                    dgn_qty2: node.dgn_qty2 || 0,                    memo: node.memo,                    drawing_code: node.drawing_code,                    node_type: node.node_type,                    quantity: !node.children || node.children.length === 0 ? node.quantity || 0 : 0,                    total_price: !node.children || node.children.length === 0 ? node.total_price || 0 : 0,                };                datas.push(data);            }            await conn.insert(this.tableName, datas);            await conn.commit();            if (orgMaxId) this._cacheMaxLid(this.ctx.budget.id, cacheTree.keyNodeId);            return datas;        } catch (err) {            await conn.rollback();            throw err;        }    }    async getSumTp(bid) {        const sql = 'SELECT Sum(total_price) As total_price FROM ' + this.tableName + ' Where bid = ? and is_leaf = true';        const result = await this.db.queryOne(sql, [bid]);        return result.total_price;    }}module.exports = BaseBudget;
 |