| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297 | 'use strict';/** * * * @author Mai * @date * @version */const itemsPre = 'id_';class baseTree {    /**     * 构造函数     */    constructor (ctx, setting) {        this.ctx = ctx;        // 无索引        this.datas = [];        // 以key为索引        this.items = {};        // 以排序为索引        this.nodes = [];        // 根节点        this.children = [];        // 树设置        this.setting = setting;        if (!this.setting.isLeaf) this.setting.isLeaf = 'is_leaf';        if (!this.setting.fullPath) this.setting.fullPath = 'full_path';    }    clear() {        // 无索引        this.datas = [];        // 以key为索引        this.items = {};        // 以排序为索引        this.nodes = [];        // 根节点        this.children = [];    }    /**     * 根据id获取树结构节点数据     * @param {Number} id     * @returns {Object}     */    getItems (id) {        return this.items[itemsPre + id];    };    /**     * 查找node的parent     * @param {Object} node     * @returns {Object}     */    getParent (node) {        return this.getItems(node[this.setting.pid]);    };    getTopParent(node) {        const parents = this.getAllParents(node);        return parents[0];    };    getAllParents(node) {        const parents = [];        if (!node) return parents;        if (node[this.setting.fullPath] && node[this.setting.fullPath] !== '') {            const parentIds = node[this.setting.fullPath].split('-');            for (const id of parentIds) {                if (id !== node[this.setting.id]) {                    parents.push(this.getItems(id));                }            }        } else {            let vP = this.getParent(node);            while (vP) {                parents.unshift(vP);                vP = this.getParent(vP);            }        }        return parents;    }    /**     * 查询node的已下载子节点     * @param {Object} node     * @returns {Array}     */    getChildren (node) {        const setting = this.setting;        const pid = node ? node[setting.id] : setting.rootId;        const children = this.datas.filter(function (x) {            return x[setting.pid] === pid;        });        children.sort(function (a, b) {            return a[setting.order] - b[setting.order];        });        return children;    };    /**     * 获取节点的 index     * @param node     * @returns {number}     */    getNodeSerialNo(node) {        return this.nodes.indexOf(node);    }    /**     * 树结构根据显示排序     */    sortTreeNode (isResort) {        const self = this;        const setting = this.setting;        const addSortNodes = function (nodes) {            if (!nodes) { return }            for (let i = 0; i < nodes.length; i++) {                self.nodes.push(nodes[i]);                nodes[i].index = self.nodes.length - 1;                if (!isResort) {                    nodes[i].children = self.getChildren(nodes[i]);                } else {                    nodes[i].children.sort(function (a, b) {                        return a[setting.order] - b[setting.order];                    })                }                addSortNodes(nodes[i].children);            }        };        this.nodes = [];        if (!isResort) {            this.children = this.getChildren();        } else {            this.children.sort(function (a, b) {                return a[setting.order] - b[setting.order];            })        }        addSortNodes(this.children);    }    /**     * 加载数据(初始化), 并给数据添加部分树结构必须数据     * @param datas     */    loadDatas (datas) {        // 清空旧数据        this.items = {};        this.nodes = [];        this.datas = [];        this.children = [];        const setting = this.setting;        // 加载全部数据        datas.sort(function (a, b) {            return a[setting.level] - b[setting.level];        });        for (const data of datas) {            const keyName = itemsPre + data[this.setting.id];            if (!this.items[keyName]) {                const item = JSON.parse(JSON.stringify(data));                item.children = [];                item.expanded = true;                item.visible = true;                this.items[keyName] = item;                this.datas.push(item);                if (item[this.setting.pid] === this.setting.rootId) {                    this.children.push(item);                } else {                    const parent = this.getParent(item);                    if (parent) {                        parent.children.push(item);                    }                }            }        }        this.children.sort(function (a, b) {            return a[setting.order] - b[setting.order];        });        this.sortTreeNode(true);    }    /**     * 递归方式 查询node的已下载的全部后代 (兼容full_path不存在的情况)     * @param node     * @returns {*}     * @private     */    _recursiveGetPosterity (node) {        let posterity = node.children;        for (const c of node.children) {            posterity = posterity.concat(this._recursiveGetPosterity(c));        }        return posterity;    };    /**     * 查询node的已下载的全部后代     * @param {Object} node     * @returns {Array}     */    getPosterity (node) {        const self = this;        let posterity;        if (node.full_path !== '') {            const reg = new RegExp('^' + node.full_path + '-');            posterity = this.datas.filter(function (x) {                return reg.test(x.full_path);            });        } else {            posterity = this._recursiveGetPosterity(node);        }        posterity.sort(function (x, y) {            return self.getNodeSerialNo(x) - self.getNodeSerialNo(y);        });        return posterity;    };    /**     * 根据 字段名称 获取数据     * @param fields     * @returns {Array}     */    getDatas (fields) {        const datas = [];        for (const node of this.nodes) {            if (node.b_code && node.b_code !== '') node.chapter = this.ctx.helper.getChapterCode(node.b_code);            node.is_leaf = !node.children || node.children.length === 0;            const data = {};            for (const field of fields) {                data[field] = node[field];            }            datas.push(data);        }        return datas;    }    /**     * 排除 某些字段 获取数据     * @param fields     * @returns {Array}     */    getDatasWithout (fields, filter) {        const datas = [];        for (const node of this.nodes) {            if (filter && filter(node)) {                continue;            }            if (node.b_code && node.b_code !== '') node.chapter = this.ctx.helper.getChapterCode(node.b_code);            node.is_leaf = !node.children || node.children.length === 0;            const data = {};            for (const field in node) {                if (fields.indexOf(field) === -1) {                    data[field] = node[field];                }            }            datas.push(data);        }        return datas;    }    /**     * 获取默认数据 剔除一些树结构需要的缓存数据     * @returns {Array}     */    getDefaultDatas(filter) {        return this.getDatasWithout(['expanded', 'visible', 'children', 'index'], filter);    }    /**     * 获取默认数据 剔除一些树结构需要的缓存数据     * @returns {Array}     */    getDefaultDatasByLevel(level) {        const levelField = this.setting.level;        return this.getDatasWithout(['expanded', 'visible', 'children', 'index'], function(node) {            switch(level) {                case "2":                case "3":                case "4":                case "5":                    return node[levelField] > parseInt(level);                case "last":                    return false;            }        });    }    _mapTreeNode () {        let map = {}, maxLevel = 0;        const levelField = this.setting.level;        for (const node of this.nodes) {            let levelArr = map[node[levelField]];            if (!levelArr) {                levelArr = [];                map[node[levelField]] = levelArr;            }            if (node[levelField] > maxLevel) {                maxLevel = node[levelField];            }            levelArr.push(node);        }        return [maxLevel, map];    }    _calculateNode (node, fun) {        const self = this;        if (node.children && node.children.length > 0) {            const gather = node.children.reduce(function (rst, x) {                const result = {};                for (const cf of self.setting.calcFields) {                    result[cf] = self.ctx.helper.add(rst[cf], x[cf]);                }                return result;            });            // 汇总子项            for (const cf of this.setting.calcFields) {                if (gather[cf]) {                    node[cf] = gather[cf];                } else {                    node[cf] = null;                }            }        }        // 自身运算        if (fun) {            fun(node);        } else if (this.setting.calc) {            this.setting.calc(node, this.ctx.helper, this.ctx.tender.info.decimal);        }    }    calculateAll(fun) {        const [maxLevel, levelMap] = this._mapTreeNode();        for (let i = maxLevel; i >= 0; i--) {            const levelNodes = levelMap[i];            if (levelNodes && levelNodes.length > 0) {                for (const node of levelNodes) {                    this._calculateNode(node, fun);                }            }        }    }    initNodeData(field, defaultValue, calcFun) {        if (!field || !calcFun) return;        const initNode = function (node) {            if (node[field] === undefined) node[field] = defaultValue;            if (node.children && node.children.length > 0) {                const values = [];                for (const child of node.children) {                    initNode(child);                    if (values.indexOf(child[field]) < 0) values.push(child[field]);                }                node[field] = calcFun(values, defaultValue);            }        };        for (const node of this.children) {            initNode(node);        }    }}class billsTree extends baseTree {    /**     * 检查节点是否是最底层项目节     * @param node     * @returns {boolean}     */    isLeafXmj(node) {        if (node.b_code && node.b_code !== '') {            return false;        }        for (const child of node.children) {            if (!child.b_code || child.b_code === '') {                return false;            }        }        return true;    }    /**     * 查询最底层项目节(本身或父项)     * @param {Object} node - 查询节点     * @returns {Object}     */    getLeafXmjParent(node) {        let parent = node;        while (parent) {            if (this.isLeafXmj(parent)) {                return parent;            } else {                parent = this.getParent(parent);            }        }        return null;    }}class filterTree extends baseTree {    addData(data, fields) {        const item = {};        for (const prop in data) {            if (fields.indexOf(prop) >= 0) {                item[prop] = data[prop];            }        }        const keyName = itemsPre + item[this.setting.id];        if (!this.items[keyName]) {            item.children = [];            item.is_leaf = true;            item.expanded = true;            item.visible = true;            this.items[keyName] = item;            this.datas.push(item);            if (item[this.setting.pid] === this.setting.rootId) {                this.children.push(item);            } else {                const parent = this.getParent(item);                if (parent) {                    parent.is_leaf = false;                    parent.children.push(item);                }            }        } else {            return this.items[keyName];        }        return item;    }}class filterGatherTree extends baseTree {    clearDatas() {        this.items = {};        this.nodes = [];        this.datas = [];        this.children = [];    }    get newId() {        if (!this._maxId) {            this._maxId = 0;        }        this._maxId++;        return this._maxId;    }    addNode(data, parent) {        data[this.setting.pid] = parent ? parent[this.setting.id] : this.setting.rootId;        let item = this.ctx.helper._.find(this.items, data);        if (item) return item;        item = data;        item.drawing_code = [];        item.memo = [];        item.ex_memo1 = [];        item.ex_memo2 = [];        item.ex_memo3 = [];        item.postil = [];        item[this.setting.id] = this.newId;        const keyName = itemsPre + item[this.setting.id];        item.children = [];        item.is_leaf = true;        item.expanded = true;        item.visible = true;        this.items[keyName] = item;        this.datas.push(item);        if (parent) {            item[this.setting.fullPath] = parent[this.setting.fullPath] + '-' + item[this.setting.id];            item[this.setting.level] = parent[this.setting.level] + 1;            item[this.setting.order] = parent.children.length + 1;            parent.is_leaf = false;            parent.children.push(item);        } else {            item[this.setting.fullPath] = '' + item[this.setting.id];            item[this.setting.level] = 1;            item[this.setting.order] = this.children.length + 1;            this.children.push(item);        }        return item;    }    generateSortNodes() {        const self = this;        const addSortNode = function (node) {            self.nodes.push(node);            for (const c of node.children) {                addSortNode(c);            }        };        this.nodes = [];        for (const n of this.children) {            addSortNode(n);        }    }    sortTreeNodeCustom(fun) {        const sortNodes = function (nodes) {            nodes.sort(fun);            for (const [i, node] of nodes.entries()) {                node.order = i + 1;            }            for (const node of nodes) {                if (node.children && node.children.length > 1) {                    sortNodes(node.children);                }            }        };        this.nodes = [];        this.children = this.getChildren(null);        sortNodes(this.children);        this.generateSortNodes();    }}class gatherTree extends baseTree {    constructor(ctx, setting) {        super(ctx, setting);        this._newId = 1;    }    get newId() {        return this._newId++;    }    loadGatherNode(node, parent, loadFun, loadPosFun) {        const siblings = parent ? parent.children : this.children;        let cur = siblings.find(function (x) {            return node.b_code                ? x.b_code === node.b_code && x.name === node.name && x.unit === node.unit && x.unit_price === node.unit_price                : x.code === node.code && x.name === node.name;        });        if (!cur) {            const id = this.newId;            cur = {                id: id,                pid: parent ? parent.id : this.setting.rootId,                full_path: parent ? parent.full_path + '-' + id : '' + id,                level: parent ? parent.level + 1 : 1,                order: siblings.length + 1,                children: [],                code: node.code, b_code: node.b_code, name: node.name,                unit: node.unit, unit_price: node.unit_price, drawing_code: node.drawing_code,            };            siblings.push(cur);            this.datas.push(cur);        }        if (!cur.memo && !!node.memo) cur.memo = node.memo;        if (!cur.ex_memo1 && !!node.ex_memo1) cur.ex_memo1 = node.ex_memo1;        if (!cur.ex_memo2 && !!node.ex_memo2) cur.ex_memo2 = node.ex_memo2;        if (!cur.ex_memo3 && !!node.ex_memo3) cur.ex_memo3 = node.ex_memo3;        loadFun(cur, node);        if (node.children && node.children.length > 0) {            for (const c of node.children) {                this.loadGatherNode(c, cur, loadFun, loadPosFun);            }        } else if (loadPosFun) {            loadPosFun(cur, node);        }    }    generateSortNodes() {        const self = this;        const addSortNode = function (node) {            self.nodes.push(node);            for (const c of node.children) {                addSortNode(c);            }        };        this.nodes = [];        for (const n of this.children) {            addSortNode(n);        }    }    loadGatherTree(sourceTree, loadFun, loadPosFun) {        for (const c of sourceTree.children) {            this.loadGatherNode(c, null, loadFun, loadPosFun);        }    }    resortChildrenByCustom(fun) {        for (const n of this.datas) {            if (n.children && n.children.length > 1) {                n.children.sort(fun);                n.children.forEach((x, i) => { x.order = i + 1; });            }        }        this.generateSortNodes();    }    resortChildrenDefault() {        const helper = this.ctx.helper;        this.resortChildrenByCustom((x, y) => {            const iCode = (x.code || y.code) ? helper.compareCode(x.code, y.code) : helper.compareCode(x.b_code, y.b_code);            if (iCode) return iCode;            if (!x.name) return -1;            if (!y.name) return 1;            return x.name.localeCompare(y.name);        })    }    calculateSum() {        if (this.setting.calcSum) {            for (const d of this.datas) {                this.setting.calcSum(d, this.count);            }        }    }}class pos {    /**     * 构造函数     * @param {id|Number, masterId|Number} setting     */    constructor (setting) {        // 无索引        this.datas = [];        // 以key为索引        this.items = {};        // 以分类id为索引的有序        this.ledgerPos = {};        // pos设置        this.setting = setting;    }    /**     * 加载部位明细数据     * @param datas     */    loadDatas(datas) {        this.datas = datas;        this.items = {};        this.ledgerPos = {};        for (const data of this.datas) {            const key = itemsPre + data[this.setting.id];            this.items[key] = data;            const masterKey = itemsPre + data[this.setting.ledgerId];            if (!this.ledgerPos[masterKey]) {                this.ledgerPos[masterKey] = [];            }            this.ledgerPos[masterKey].push(data);        }        for (const prop in this.ledgerPos) {            this.resortLedgerPos(this.ledgerPos[prop]);        }    }    getPos(id) {        return this.items[itemsPre + id];    }    getLedgerPosKey() {        const result = [];        for (const prop in this.ledgerPos) {            result.push(prop);        }        return result;    }    getLedgerPos(mid) {        return this.ledgerPos[itemsPre + mid];    }    resortLedgerPos(ledgerPos) {        if (ledgerPos instanceof Array) {            ledgerPos.sort(function (a, b) {                return a.porder - b.porder;            })        }    }    /**     * 计算全部     */    calculateAll(fun) {        const calcFun = fun ? fun : this.setting.calc;        if (!calcFun) return;        for (const pos of this.datas) {            calcFun(pos);        }    }    getDatas () {        return this.datas;    }}class gatherPos extends pos {    loadGatherPos(ledgerId, sourcePosRange, loadFun) {        let posRange = this.getLedgerPos(itemsPre + ledgerId);        if (!posRange) {            posRange = [];            this.ledgerPos[itemsPre + ledgerId] = posRange;        }        for (const spr of sourcePosRange) {            let gp = posRange.find(x => { return x.name === spr.name; });            if (!gp) {                gp = { name: spr.name };                gp[this.setting.ledgerId] = ledgerId;                this.datas.push(gp);                posRange.push(gp);            }            if (!gp.ex_memo1 && !!spr.ex_memo1) gp.ex_memo1 = spr.ex_memo1;            if (!gp.ex_memo2 && !!spr.ex_memo2) gp.ex_memo2 = spr.ex_memo2;            if (!gp.ex_memo3 && !!spr.ex_memo3) gp.ex_memo3 = spr.ex_memo3;            loadFun(gp, spr);        }    }}class checkData {    constructor(ctx, measureType) {        this.ctx = ctx;        this.checkBills = new billsTree(ctx, { id: 'ledger_id', pid: 'ledger_pid', order: 'order', level: 'level', rootId: -1 });        this.checkPos = new pos({ id: 'id', ledgerId: 'lid' });        this.checkResult = {            error: [],            source: {                bills: [],                pos: [],            },        };        this.measureType = measureType;    }    _check3f(data, limit, ratio) {        if (limit === 0) {            if (data.contract_tp || data.pre_contract_tp) return 1; // 违规        }        if (limit === 1) {            if (ratio === 0) {                if (!data.contract_tp && !data.pre_contract_tp) return 2; // 漏计            } else {                const tp = this.ctx.helper.mul(data.final_1_tp, this.ctx.helper.div(ratio, 100, 4), this.ctx.tender.info.decimal.tp);                const checkTp = this.ctx.helper.add(data.contract_tp, data.pre_contract_tp);                if (tp > checkTp) return 1; // 违规                if (tp < checkTp) return 2; // 漏计            }        }        return 0; // 合法    }    _check3fQty(data, limit, ratio, unit) {        if (limit === 0) {            if (data.contract_qty || data.qc_qty || data.pre_contract_qty || data.pre_qc_qty) return 1; // 违规        }        if (limit === 1) {            if (!ratio || ratio === 0) {                if (!data.contract_qty && !data.qc_qty && !data.pre_contract_qty && !data.pre_qc_qty) return 2; // 漏计            } else {                const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, unit);                const checkQty = this.ctx.helper.mul(data.final_1_qty, this.ctx.helper.div(ratio, 100, 4), precision.value);                const qty = this.ctx.helper.add(data.contract_qty, data.pre_contract_qty);                if (qty > checkQty) return 1; // 违规                if (qty < checkQty) return 2; // 漏计            }        }        return 0; // 合法    }    _getRatio(type, status) {        const statusConst = type === 'gxby' ? this.ctx.session.sessionProject.gxby_status : this.ctx.session.sessionProject.dagl_status;        const sc = statusConst.find(x => { return x.value === status });        return sc ? sc.ratio : null;    }    _getValid = function (type, status, limit) {        if (limit) {            const statusConst = type === 'gxby' ? this.ctx.session.sessionProject.gxby_status : this.ctx.session.sessionProject.dagl_status;            const sc = statusConst.find(x => { return x.value === status; });            return sc ? (sc.limit ? 1 : 0) : 0;        } else {            return -1;        }    };    _checkLeafBills3fLimit(checkType, bills, checkInfo) {        const over = [], lost = [];        const posRange = this.checkPos.getLedgerPos(bills.id);        if (posRange && posRange.length > 0) {            for (const p of posRange) {                const posCheckInfo = this.ctx.helper._.assign({}, checkInfo);                for (const ct of checkType) {                    if (p[ct + '_limit'] > 0) {                        posCheckInfo[ct + '_limit'] = p[ct + '_limit'];                    }                }                for (const ct of checkType) {                    const checkResult = this._check3fQty(p, this._getValid(ct, p[ct + '_status'], posCheckInfo[ct + '_limit']), this._getRatio(ct, p[ct+'_status']), bills.unit);                    if (checkResult === 1) {                        if (over.indexOf(ct) === -1) over.push(ct);                    }                    if (checkResult === 2) {                        if (lost.indexOf(ct) === -1) lost.push(ct);                    }                }            }        } else {            for (const ct of checkType) {                const checkResult = bills.is_tp                    ? this._check3f(bills, this._getValid(ct, bills[ct + '_status'], checkInfo[ct + '_limit']), this._getRatio(ct, bills[ct+'_status']))                    : this._check3fQty(bills, this._getValid(ct, bills[ct + '_status'], checkInfo[ct + '_limit']), this._getRatio(ct, bills[ct+'_status']), bills.unit);                if (checkResult === 1) {                    if (over.indexOf(ct) === -1) over.push(ct);                }                if (checkResult === 2) {                    if (lost.indexOf(ct) === -1) lost.push(ct);                }            }        }        if (over.length + lost.length > 0) {            for (const o of over) {                this.checkResult.error.push({                    ledger_id: bills.ledger_id,                    b_code: bills.b_code,                    name: bills.name,                    errorType: 's2b_over_' + o,                });            }            for (const l of lost) {                this.checkResult.error.push({                    ledger_id: bills.ledger_id,                    b_code: bills.b_code,                    name: bills.name,                    errorType: 's2b_lost_' + l,                });            }            if (!this.checkResult.source.bills.find(x => {return x.ledger_id === bills.ledger_id})) {                this.checkResult.source.bills.push(bills);                if (posRange && posRange.length > 0) this.checkResult.source.pos.push(...posRange);            }        }    }    _recursiveCheckBills3fLimit(checkType, bills, parentCheckInfo) {        const checkInfo = this.ctx.helper._.assign({}, parentCheckInfo);        for (const ct of checkType) {            if (bills[ct + '_limit'] > 0) {                checkInfo[ct + '_limit'] = bills[ct + '_limit'];            }        }        if (bills.children && bills.children.length > 0) {            for (const c of bills.children) {                this._recursiveCheckBills3fLimit(checkType, c, checkInfo);            }        } else {            this._checkLeafBills3fLimit(checkType, bills, checkInfo);        }    }    loadData(bills, pos) {        this.checkBills.loadDatas(bills);        this.checkPos.loadDatas(pos);    }    checkSibling() {        for (const node of this.checkBills.nodes) {            if (!node.children || node.children.length === 0) continue;            let hasXmj, hasGcl;            for (const child of node.children) {                if (child.b_code) hasXmj = true;                if (!child.b_code) hasGcl = true;            }            if (hasXmj && hasGcl) this.checkResult.error.push({                ledger_id: node.ledger_id,                b_code: node.b_code,                name: node.name,                errorType: 'sibling',            });        }    }    checkSameCode() {        //let xmj = this.checkBills.nodes.filter(x => { return /^((GD*)|G)?[0-9]+/.test(x.code); });        let xmj = [];        const addXmjCheck = function (node) {            if (/^((GD*)|G)?[0-9]+/.test(node.code)) xmj.push(node);            for (const child of node.children) {                addXmjCheck(child);            }        };        for (const topLevel of this.checkBills.children) {            if ([1, 2, 3, 4].indexOf(topLevel.node_type) < 0) continue;            addXmjCheck(topLevel);        }        const xmjPart = {}, xmjIndex = [];        for (const x of xmj) {            if (!xmjPart[x.code]) {                xmjPart[x.code] = [];                xmjIndex.push(x.code);            }            xmjPart[x.code].push(x);        }        for (const x of xmjIndex) {            if (xmjPart[x].length <= 1) continue;            for (const xp of xmjPart[x]) {                this.checkResult.error.push({                    ledger_id: xp.ledger_id,                    b_code: xp.b_code,                    name: xp.name,                    errorType: 'same_code',                })            }        }        let check = null;        while (xmj.length > 0) {            [check, xmj] = this.ctx.helper._.partition(xmj, x => { return x.code === xmj[0].code; });            if (check.length > 1) {                for (const c of check) {                    this.checkResult.error.push({                        ledger_id: c.ledger_id,                        b_code: c.b_code,                        name: c.name,                        errorType: 'same_code',                    })                }            }        }    }    check3fLimit(tender) {        const check = [];        if (tender.s2b_gxby_limit) check.push('gxby');        if (tender.s2b_dagl_limit) check.push('dagl');        if (check.length === 0) return;        for (const b of this.checkBills.children) {            this._recursiveCheckBills3fLimit(check, b, {});        }    }    checkBillsQty(fields) {        for (const b of this.checkBills.nodes) {            if (b.children && b.children.length > 0) continue;            const pr = this.checkPos.getLedgerPos(b.id);            if (!pr || pr.length === 0) continue;            const checkData = {},                calcData = {};            for (const field of fields) {                checkData[field] = b[field] ? b[field] : 0;            }            for (const p of pr) {                for (const field of fields) {                    calcData[field] = this.ctx.helper.add(calcData[field], p[field]);                }            }            if (!this.ctx.helper._.isMatch(checkData, calcData)) {                this.checkResult.error.push({                    ledger_id: b.ledger_id,                    b_code: b.b_code,                    name: b.name,                    errorType: 'qty',                    error: { checkData, calcData },                });                if (!this.checkResult.source.bills.find(x => {return x.ledger_id === b.ledger_id})) {                    this.checkResult.source.bills.push(b);                    for (const p of pr) {                        this.checkResult.source.pos.push(p);                    }                }            }        }    }    checkBillsTp(field, decimal, filter) {        for (const b of this.checkBills.nodes) {            if ((b.children && b.children.length > 0)) continue;            if (filter && filter(b)) continue;            const checkData = {}, calcData = {};            for (const f of field) {                checkData[f.tp] = b[f.tp] || 0;                calcData[f.tp] = this.ctx.helper.mul(b.unit_price, b[f.qty], decimal.tp) || 0;            }            if (!this.ctx.helper._.isMatch(checkData, calcData)) {                this.checkResult.error.push({                    ledger_id: b.ledger_id,                    b_code: b.b_code,                    name: b.name,                    errorType: 'tp',                    error: { checkData, calcData },                });                if (!this.checkResult.source.bills.find(x => {return x.ledger_id === b.ledger_id})) {                    this.checkResult.source.bills.push(b);                }            }        }    }    _checkPosOverRangeTz(p, coe) {        const end_contract_qty = this.ctx.helper.add(p.pre_contract_qty, p.contract_qty);        const base_qty = p.quantity;        const compare_qty = this.ctx.helper.mul(p.final_1_qty, coe);        if (!base_qty) return !!end_contract_qty;        return base_qty > 0            ? end_contract_qty > compare_qty            : (compare_qty > 0 ? true : end_contract_qty < compare_qty || end_contract_qty > 0);    }    _checkPosOverRange(p, checkInfo) {        const checkTz = checkInfo.checkTz ? this._checkPosOverRangeTz(p, checkInfo.coe) : false;        const checkDeal = false;        return checkTz || checkDeal;    }    _checkBillsOverRangeTz(bills, coe) {        const end_contract_qty = this.ctx.helper.add(bills.contract_qty, bills.pre_contract_qty);        const end_contract_tp = this.ctx.helper.add(bills.contract_tp, bills.pre_contract_tp);        if (bills.is_tp) {            const base_tp = bills.total_price;            const compare_tp = this.ctx.helper.mul(base_tp, coe);            if (!base_tp) return !!end_contract_tp;            return base_tp >= 0 ? end_contract_tp > compare_tp : end_contract_tp < compare_tp || end_contract_tp > 0;        } else {            const base_qty = bills.quantity;            const compare_qty = this.ctx.helper.mul(bills.final_1_qty, coe);            if (!base_qty) return !!end_contract_qty;            return base_qty > 0                ? end_contract_qty > compare_qty                : (compare_qty > 0 ? true : end_contract_qty < compare_qty || end_contract_qty > 0);        }    }    _checkBillsOverRangeDeal(bills, coe) {        const end_contract_qty = this.ctx.helper.add(bills.contract_qty, bills.pre_contract_qty);        const end_contract_tp = this.ctx.helper.add(bills.contract_tp, bills.pre_contract_tp);        if (bills.is_tp) {            const base_tp = bills.deal_tp;            const compare_tp = this.ctx.helper.mul(base_tp, coe);            if (!base_tp) return !!end_contract_tp;            return base_tp >= 0 ? end_contract_tp > compare_tp : end_contract_tp < compare_tp || end_contract_tp > 0;        } else {            const base_qty = bills.deal_qty;            const compare_qty = this.ctx.helper.mul(bills.deal_final_1_qty, coe);            if (!base_qty) return !!end_contract_qty;            return base_qty > 0                ? end_contract_qty > compare_qty                : (compare_qty > 0 ? true : end_contract_qty < compare_qty || end_contract_qty > 0);        }    }    _checkBillsOverRange(bills, posRange, checkInfo) {        if (checkInfo.hasPosCheckPos && posRange.length > 0) {            for (const p of posRange) {                if (this._checkPosOverRange(p, checkInfo)) return true;            }        }        if (checkInfo.hasPosCheckBills || posRange.length === 0) {            const checkTz = checkInfo.checkTz ? this._checkBillsOverRangeTz(bills, checkInfo.coe) : false;            const checkDeal = checkInfo.checkDeal ? this._checkBillsOverRangeDeal(bills, checkInfo.coe) : false;            return checkTz || checkDeal;        }        return false;    }    checkOverRange(checkInfo) {        for (const b of this.checkBills.nodes) {            if (b.children && b.children.length > 0) continue;            const pr = this.checkPos.getLedgerPos(b.id) || [];            if (this._checkBillsOverRange(b, pr, checkInfo)) {                this.checkResult.error.push({                    ledger_id: b.ledger_id,                    b_code: b.b_code,                    name: b.name,                    errorType: 'over',                });                if (!this.checkResult.source.bills.find(x => {return x.ledger_id === b.ledger_id})) {                    this.checkResult.source.bills.push(b);                    if (pr.length > 0) this.checkResult.source.pos.push(...pr);                }            }        }    }    checkMinusChangeBills(change, changeBills, finalStageChange) {        const error = this.checkResult.error;        const helper = this.ctx.helper;        const changeIndex = {};        change.forEach(c => {            changeIndex[c.cid] = c;            c.bills = [];            c.billsIndex = {};            c.stageChange = [];        });        changeBills.forEach(cb => {            const c = changeIndex[cb.cid];            if (c) c.bills.push(cb);            c.billsIndex[cb.id] = cb;            cb.used_qty = 0;            cb.qty = parseFloat(cb.samount);        });        finalStageChange.forEach(sc => {            if (!sc.qty) return;            const c = changeIndex[sc.cid];            if (c) {                c.used = true;                const cb = c.billsIndex[sc.cbid];                if (cb) cb.used_qty = helper.add(cb.used_qty, sc.qty);            }        });        change.forEach(c => {            if (!c.used) return;            c.bills.forEach(b => {                if (b.qty >= 0) return;                if (!helper.numEqual(b.used_qty, b.qty)) error.push({ b_code: b.code, name: b.name, errorType: 'minus_cb', memo: c.code });            });        });    }    checkChangeBillsOver(change, changeBills, finalStageChange, curStageId) {        const error = this.checkResult.error;        const helper = this.ctx.helper;        const changeIndex = {};        change.forEach(c => {            changeIndex[c.cid] = c;            c.bills = [];            c.billsIndex = {};            c.stageChange = [];        });        changeBills.forEach(cb => {            const c = changeIndex[cb.cid];            if (c) c.bills.push(cb);            c.billsIndex[cb.id] = cb;            cb.used_qty = 0;            cb.qty = parseFloat(cb.samount);        });        finalStageChange.forEach(sc => {            if (!sc.qty) return;            const c = changeIndex[sc.cid];            if (c) {                c.used = true;                const cb = c.billsIndex[sc.cbid];                if (cb) {                    cb.used_qty = helper.add(cb.used_qty, sc.qty);                    if (sc.sid === curStageId) {                        cb.cur_used = true;                        cb.lid = sc.lid;                    }                }            }        });        change.forEach(c => {            if (!c.used) return;            c.bills.forEach(b => {                if (!b.cur_used) return;                const qtyDecimal = helper.findDecimal(b.unit);                const limitQty = helper.mul(b.qty, helper.div(b.delimit, 100, 2), qtyDecimal);                if (Math.abs(b.used_qty) > Math.abs(limitQty)) error.push({ b_code: b.code, name: b.name, errorType: 'change_over', memo: c.code, lid: b.lid, used_qty: b.used_qty, limit_qty: limitQty });            });        });    }    checkSettle() {        const settleStatus = this.ctx.service.settle.settleStatus;        for (const b of this.checkBills.nodes) {            if (b.children && b.children.length > 0) continue;            if (!b.settleStatus) continue;            const pr = this.checkPos.getLedgerPos(b.id);            if (!pr || pr.length === 0) {                if (b.settleStatus !== settleStatus.finish) continue;                if (b.contract_qty || b.contract_tp || b.qc_qty || b.qc_minus_qty || b.positive_qc_qty || b.negative_qc_qty) {                    this.checkResult.error.push({                        ledger_id: b.ledger_id,                        b_code: b.b_code,                        name: b.name,                        errorType: 'settle',                    });                    if (!this.checkResult.source.bills.find(x => {return x.ledger_id === b.ledger_id})) {                        this.checkResult.source.bills.push(b);                    }                }            } else {                for (const p of pr) {                    if (p.settle_status !== settleStatus.finish)  continue;                    if (p.contract_qty || p.qc_qty || p.qc_minus_qty || p.positive_qc_qty || p.negative_qc_qty) {                        this.checkResult.error.push({                            ledger_id: b.ledger_id,                            b_code: b.b_code,                            name: b.name,                            errorType: 'settle',                        });                        if (!this.checkResult.source.bills.find(x => {return x.ledger_id === b.ledger_id})) {                            this.checkResult.source.bills.push(b);                            for (const p of pr) {                                this.checkResult.source.pos.push(p);                            }                        }                    }                }            }        }    }}class reviseTree extends billsTree {    constructor (ctx, setting) {        super(ctx, setting);        this.price = [];    }    loadRevisePrice(price, decimal) {        this.decimal = decimal;        this.price = price || [];        this.rela_price = [];        this.common_price = [];        this.price.forEach(x => {            if (x.rela_lid) {                x.rela_lid = x.rela_lid.split(',');                this.rela_price.push(x);            } else {                this.common_price.push(x);            }        });    }    checkRevisePrice(d) {        if (d.settle_status) return false;        const helper = this.ctx.helper;        const setting = this.setting;        const pid = this.getAllParents(d).map(x => { return x[setting.id] + ''; });        const checkRela = function(rela_lid) {            if (!rela_lid || rela_lid.length === 0) return false;            for (const lid of rela_lid) {                if (pid.indexOf(lid) >= 0) return true;            }            return false;        };        let p = this.rela_price.find(x => {            return x.b_code === d.b_code &&                ((!x.name && !d.name) || x.name === d.name) &&                ((!x.unit && !d.unit) || x.unit === d.unit) &&                helper.checkZero(x.org_price - d.unit_price) &&                checkRela(x.rela_lid);        });        if (!p) p = this.common_price.find(x => {            return x.b_code === d.b_code &&                ((!x.name && !d.name) || x.name === d.name) &&                ((!x.unit && !d.unit) || x.unit === d.unit) &&                helper.checkZero(x.org_price - d.unit_price);        });        if (!p) return false;        d.org_price = p.org_price;        d.unit_price = p.new_price;        d.deal_tp = helper.mul(d.deal_qty, d.unit_price, this.decimal.tp);        d.sgfh_tp = helper.mul(d.sgfh_qty, d.unit_price, this.decimal.tp);        d.sjcl_tp = helper.mul(d.sjcl_qty, d.unit_price, this.decimal.tp);        d.qtcl_tp = helper.mul(d.qtcl_qty, d.unit_price, this.decimal.tp);        d.total_price = helper.mul(d.quantity, d.unit_price, this.decimal.tp);        return true;    }    loadDatas(datas) {        super.loadDatas(datas);        if (this.price.length > 0) {            for (const d of this.datas) {                if (d.children && d.children.length > 0) continue;                if (!d.b_code) continue;                this.checkRevisePrice(d);            }        }    }    getUpdateReviseData() {        return this.datas.map(x => {            if (x.children && x.children.length > 0) {                return {                    id: x.id, tender_id: x.tender_id, crid: x.crid,                    ledger_id: x.ledger_id, ledger_pid: x.ledger_pid, full_path: x.full_path, order: x.order, level: x.level, is_leaf: 0,                    node_type: x.node_type, check_calc: x.check_calc,                    code: x.code, b_code: x.b_code, name: x.name, unit: x.unit, position: x.position,                    drawing_code: x.drawing_code, memo: x.memo, add_user: x.add_user, in_time: x.in_time,                    unit_price: 0, dgn_qty1: x.dgn_qty1, dgn_qty2: x.dgn_qty2,                    quantity: 0, total_price: 0,                    sgfh_qty: 0, sgfh_tp: 0, sgfh_expr: '',                    sjcl_qty: 0, sjcl_tp: 0, sjcl_expr: '',                    qtcl_qty: 0, qtcl_tp: 0, qtcl_expr: '',                    deal_qty: 0, deal_tp: 0,                };            } else {                return {                    id: x.id, tender_id: x.tender_id, crid: x.crid,                    ledger_id: x.ledger_id, ledger_pid: x.ledger_pid, full_path: x.full_path, order: x.order, level: x.level, is_leaf: 1,                    node_type: x.node_type, check_calc: x.check_calc,                    code: x.code, b_code: x.b_code, name: x.name, unit: x.unit, position: x.position,                    drawing_code: x.drawing_code, memo: x.memo, add_user: x.add_user, in_time: x.in_time,                    unit_price: x.unit_price, dgn_qty1: x.dgn_qty1, dgn_qty2: x.dgn_qty2,                    quantity: x.quantity, total_price: x.total_price,                    sgfh_qty: x.sgfh_qty, sgfh_tp: x.sgfh_tp, sgfh_expr: x.sgfh_expr,                    sjcl_qty: x.sjcl_qty, sjcl_tp: x.sjcl_tp, sjcl_expr: x.sjcl_expr,                    qtcl_qty: x.qtcl_qty, qtcl_tp: x.qtcl_tp, qtcl_expr: x.qtcl_expr,                    deal_qty: x.deal_qty, deal_tp: x.deal_tp,                };            }        });    }    sum() {        const result = { total_price: 0 };        for (const d of this.datas) {            if (d.children && d.children.length > 0) continue;            result.total_price = this.ctx.helper.add(result.total_price, d.total_price);        }        return result;    }}module.exports = {    baseTree,    billsTree,    pos,    filterTree,    filterGatherTree,    gatherTree,    gatherPos,    checkData,    reviseTree,};
 |