| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094 |
- /**
- * Created by zhang on 2018/1/26.
- */
- module.exports = {
- setChildren,
- sortChildren,
- markUpdateProject: markUpdateProject,
- removeProjectMark: removeProjectMark,
- updateNodes: updateNodes,
- saveProperty: saveProperty,
- getDefaultColSetting: getDefaultColSetting,
- markProjectsToChange: markProjectsToChange,
- getBudgetSummayDatas: getBudgetSummayDatas,
- getGLJSummayDatas: getGLJSummayDatas,
- };
- let mongoose = require("mongoose");
- let logger = require("../../../logs/log_helper").logger;
- let projectsModel = mongoose.model("projects");
- let async_n = require("async");
- let _ = require("lodash");
- let ration_model = require("../models/ration");
- let optionModel = mongoose.model("options");
- let bill_model = require("../models/bills");
- let consts = require("../models/project_consts");
- let projectConsts = consts.projectConst;
- let ration_glj_model = mongoose.model("ration_glj");
- let rationTemplateModel = mongoose.model("ration_template");
- let project_glj_model = mongoose.model("glj_list");
- let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
- const uuidV1 = require("uuid/v1");
- const gljUtil = require("../../../public/gljUtil");
- let stdColSettingModel = mongoose.model("std_main_col_lib");
- let decimal_facade = require("../../main/facade/decimal_facade");
- const scMathUtil = require("../../../public/scMathUtil").getUtil();
- const calcUtil = require("../../../public/calculate_util");
- const { fixedFlag } = require("../../../public/common_constants");
- const GLJListModel = require("../../glj/models/glj_list_model");
- const projectDao = require("../../pm/models/project_model").project;
- const UnitPriceFileModel = require("../../glj/models/unit_price_file_model");
- async function createRationGLJData(glj) {
- glj.ID = uuidV1();
- let [info, projectGLJ] = await ration_glj_facade.getInfoFromProjectGLJ(glj);
- let newRecode = ration_glj_facade.createNewRecord(info);
- return [newRecode, projectGLJ];
- }
- function generateTasks(data, userID) {
- let tasks = [];
- let deleteInfo = {
- deleted: true,
- deleteDateTime: new Date(),
- deleteBy: userID,
- };
- if (data.delete && data.delete.length > 0) {
- for (let bd of data.delete) {
- //原先是假删除,现在改成真删除
- let task = {
- deleteOne: {
- filter: {
- ID: bd.ID,
- projectID: bd.projectID,
- },
- },
- };
- /* let task={
- updateOne:{
- filter:{
- ID:bd.ID,
- projectID:bd.projectID
- },
- update :{
- deleteInfo:deleteInfo
- }
- }
- };*/
- tasks.push(task);
- }
- }
- if (data.add && data.add.length > 0) {
- for (let n_data of data.add) {
- let task = {
- insertOne: {
- document: n_data,
- },
- };
- tasks.push(task);
- }
- }
- return tasks;
- }
- async function updateNodes(datas) {
- let nodeGroups = _.groupBy(datas, "type");
- let asyncTasks = [];
- let deleteRationIDs = [];
- let taskMap = {};
- taskMap[projectConsts.BILLS] = {
- tasks: [],
- model: bill_model.model,
- };
- taskMap[projectConsts.RATION] = {
- tasks: [],
- model: ration_model.model,
- };
- taskMap[projectConsts.RATION_GLJ] = {
- tasks: [],
- model: ration_glj_model,
- };
- taskMap[projectConsts.PROJECTGLJ] = {
- tasks: [],
- model: project_glj_model,
- };
- taskMap[projectConsts.PROJECT] = {
- tasks: [],
- model: projectsModel,
- };
- taskMap[projectConsts.RATION_TEMPLATE] = {
- tasks: [],
- model: rationTemplateModel,
- };
- for (let type in nodeGroups) {
- for (let node of nodeGroups[type]) {
- if (taskMap[type]) {
- if (type == projectConsts.RATION) {
- if (node.action == "delete") deleteRationIDs.push(node.data.ID);
- }
- if (type == projectConsts.RATION_GLJ) {
- if (node.action == "add") {
- //添加定額工料机的時候,要先走项目工料机的逻辑
- let [newRecode, projectGLJ] = await createRationGLJData(node.data);
- node.data = newRecode;
- node.projectGLJ = projectGLJ;
- }
- }
- taskMap[type].tasks.push(getTask(node));
- }
- }
- }
- for (let key in taskMap) {
- if (taskMap[key].tasks.length > 0)
- asyncTasks.push(taskMap[key].model.bulkWrite(taskMap[key].tasks));
- }
- if (asyncTasks.length > 0) await Promise.all(asyncTasks);
- if (deleteRationIDs.length > 0)
- await ration_glj_model.deleteMany({
- rationID: {
- $in: deleteRationIDs,
- },
- });
- return datas;
- function getTask(node, idFiled = "ID") {
- let task = {};
- if (node.action == "add") {
- task.insertOne = {
- document: node.data,
- };
- } else if (node.action == "delete") {
- task.deleteOne = {
- filter: {},
- };
- task.deleteOne.filter[idFiled] = node.data[idFiled];
- } else {
- task.updateOne = {
- filter: {},
- update: {}, //_.cloneDeep(node.data)
- };
- for (let key in node.data) {
- if (key.indexOf("function(") !== -1) {
- //有时候会出现field里包含一串 function(e){if(e.length>0)... 这些东西,本地测试又不出现,所以这里先把这些field删除看看
- delete node.data[key];
- } else {
- task.updateOne.update[key] = node.data[key];
- }
- }
- task.updateOne.filter[idFiled] = node.data[idFiled]; //现在复制项目也重新生成一个新的ID了,所以ID是唯一的
- delete task.updateOne.update[idFiled]; //防止误操作
- }
- return task;
- }
- }
- //data = {feeRateID:111111,projectID:1245}; type = feeRate
- async function markUpdateProject(data, type) {
- let query = {
- deleteInfo: null,
- };
- if (type == "feeRate") {
- //更改了费率
- query["property.feeFile.id"] = data.feeRateID;
- }
- if (type == "unitFile") {
- //更改了单价文件
- query["property.unitPriceFile.id"] = data.unitFileID; //unitPriceFile
- }
- let projects = await projectsModel.find(query);
- return await markProjectsToChange(
- projects,
- type,
- data.projectID,
- data.isInclude
- );
- }
- async function markProjectsToChange(projects, type, extProjectID, isInclude) {
- let tasks = [];
- for (let p of projects) {
- if (isInclude != true) {
- if (extProjectID && p.ID === extProjectID) continue; //排除当前项目
- }
- tasks.push(generateMarkTask(type, p.ID));
- }
- return tasks.length > 0 ? await projectsModel.bulkWrite(tasks) : null;
- }
- async function removeProjectMark(projectID) {
- return await projectsModel.findOneAndUpdate(
- {
- ID: projectID,
- },
- {
- $unset: {
- changeMark: 1,
- },
- }
- );
- }
- function generateMarkTask(value, projectID) {
- let task = {
- updateOne: {
- filter: {
- ID: projectID,
- },
- update: {
- changeMark: value,
- },
- },
- };
- return task;
- }
- // {projectID: 5, propertyName: 'aaa', propertyValue: 1}
- function saveProperty(data, callback) {
- let obj = {};
- let pn = "property." + data.propertyName;
- obj[pn] = data.propertyValue;
- projectsModel.update(
- {
- ID: data.projectID,
- },
- obj,
- function (err) {
- if (err) {
- logger.err(pn + " save error: " + err);
- callback(err, null);
- } else {
- logger.info(pn + " saved.");
- callback("", null);
- }
- }
- );
- }
- async function getDefaultColSetting(libID) {
- return await stdColSettingModel.findOne(
- {
- ID: libID,
- deleted: false,
- },
- "-_id main_tree_col"
- );
- }
- async function getBudgetSummayDatas(
- projectIDs,
- userID,
- compilationID,
- overWriteUrl
- ) {
- try {
- let projects = [];
- let names = [];
- let prjTypeNames = [];
- let compilationScopes = [];
- let decimal = null;
- let isProgressiveType = true;
- for (let ID of projectIDs) {
- projects.push(await getBillsByProjectID(ID));
- }
- if (projects.length == 0) {
- return [];
- }
- let mp = projects[0];
- names.push(mp.name);
- prjTypeNames.push(mp.prjTypeName);
- compilationScopes.push(mp.compilationScope);
- if (projects.length == 1)
- decimal = await decimal_facade.getProjectDecimal(projectIDs[0]); //如果只有一个项目,则没走合并的那一步,decimal会为空,从面报错
- for (let i = 1; i < projects.length; i++) {
- names.push(projects[i].name);
- prjTypeNames.push(projects[i].prjTypeName);
- compilationScopes.push(projects[i].compilationScope);
- decimal = await mergeProject(mp.roots, projects[i].roots);
- }
- let options_setting = await optionModel
- .findOne({
- user_id: userID,
- compilation_id: compilationID,
- })
- .lean();
- if (
- options_setting &&
- options_setting.options &&
- options_setting.options.GENERALOPTS
- )
- isProgressiveType =
- options_setting.options.GENERALOPTS.progressiveType == 1 ? false : true;
- let SummaryAuditDetail = getReportData(
- names,
- mp.roots,
- prjTypeNames,
- compilationScopes,
- decimal,
- isProgressiveType,
- mp.progressiveInterval,
- overWriteUrl
- );
- let parentProject = await projectsModel.findOne({
- ID: mp.ParentID,
- });
- let result = {
- prj: {},
- SummaryAudit: {
- name: parentProject ? parentProject.name : "",
- 编制: mp.author,
- 复核: mp.auditor,
- 编制范围: mp.compilationScope,
- },
- SummaryAuditDetail: SummaryAuditDetail,
- };
- return result;
- } catch (e) {
- // console.log(e.message)
- console.log(e);
- }
- }
- function getReportData(
- nameList,
- items,
- prjTypeNames,
- compilationScopes,
- decimal,
- isProgressiveType,
- progressiveInterval,
- overWriteUrl
- ) {
- let datas = [],
- totalItem = null,
- one_to_four_Item = null;
- let overWrite = null;
- if (overWriteUrl && overWriteUrl != "") {
- overWrite = require("../../.." + overWriteUrl);
- }
- setChildrenDatas(items, datas);
- if (one_to_four_Item)
- recalcTotalItem(
- one_to_four_Item,
- datas,
- isProgressiveType,
- progressiveInterval
- );
- if (totalItem)
- recalcTotalItem(totalItem, datas, isProgressiveType, progressiveInterval);
- for (let d of datas) {
- if (d.billsTtlPrice && totalItem.billsTtlPrice) {
- d["各项费用比例"] = scMathUtil.roundForObj(
- (d.billsTtlPrice / totalItem.billsTtlPrice) * 100,
- 2
- );
- }
- d["prjNames"] = nameList;
- d["prjTypeNames"] = prjTypeNames;
- d["编制范围明细"] = compilationScopes;
- }
- return datas;
- function recalcTotalItem(
- item,
- datas,
- isProgressiveType,
- progressiveInterval
- ) {
- let totalExp = item.calcBase;
- if (totalExp.indexOf("@") == -1) return;
- if (isProgressiveType && progressiveInterval) {
- //有累进的要重新计算总金额和技术经济综合指标
- let hasReplace = false;
- for (let t of datas) {
- if (totalExp.includes(t.ID)) hasReplace = true; // 强壮性处理:控制提前计算问题(ID在datas中找不到)
- totalExp = totalExp.replace(t.ID, t.billsTtlPrice + "");
- }
- if (hasReplace) {
- totalExp = totalExp.replace(/@/g, "");
- //还有其他符号(如%)
- totalExp = totalExp.replace(/%/g, " / 100 ");
- let nTotal = eval(totalExp);
- item.billsTtlPrice = scMathUtil.roundForObj(
- nTotal,
- decimal.bills.totalPrice
- );
- item["技术经济综合指标"] =
- item.billsTtlAmt && parseFloat(item.billsTtlAmt) !== 0
- ? scMathUtil.roundForObj(item.billsTtlPrice / item.billsTtlAmt, 2)
- : scMathUtil.roundForObj(item.billsTtlPrice, 2);
- }
- }
- }
- function setChildrenDatas(children, arr, level = 0, rootFlag) {
- let temTotalPrice = 0;
- for (let c of children) {
- if (level == 0) rootFlag = c.flag; //取最顶层节点的固定清单类别
- let tbill = getBillDatas(c, level, rootFlag);
- arr.push(tbill);
- let sumChildren = setChildrenDatas(c.children, arr, level + 1, rootFlag);
- if (isProgressiveType && progressiveInterval) {
- //如果要累进的,父节点要重新汇总
- if (c.children.length > 0) {
- tbill.billsTtlPrice = sumChildren;
- tbill["技术经济综合指标"] =
- tbill.billsTtlAmt && parseFloat(tbill.billsTtlAmt) !== 0
- ? scMathUtil.roundForObj(
- tbill.billsTtlPrice / tbill.billsTtlAmt,
- 2
- )
- : scMathUtil.roundForObj(tbill.billsTtlPrice, 2);
- } else if (
- tbill.calcBase &&
- tbill.calcBase.indexOf("@") >= 0 &&
- tbill.calcBase.indexOf("{") < 0
- ) {
- // 说明:在实际中,发现清单‘第一、二、三部分费用合计’没有再计算,这样会造成问题(实际情况比较复杂,需要多方测试)
- recalcTotalItem(tbill, arr, isProgressiveType, progressiveInterval);
- }
- if (level > 0)
- temTotalPrice = scMathUtil.roundForObj(
- tbill.billsTtlPrice + temTotalPrice,
- decimal.bills.totalPrice
- );
- }
- }
- return temTotalPrice;
- }
- function getBillDatas(bills, level, rootFlag) {
- let tem = {
- ID: bills.ID,
- billsName: bills.name,
- billsCode: bills.code,
- billsUnit: bills.unit,
- billsTtlAmt: bills.quantity,
- billsPrices: [],
- billsUnitPrices: [],
- rationCommons: [],
- billsAmounts: [],
- 技术经济指标: [],
- billsLevel: level,
- calcBase: bills.calcBase,
- billsMemos: bills.remark,
- };
- let total = 0;
- let rationTotal = 0;
- let baseTotal = 0;
- for (let n of nameList) {
- let p = 0; //金额
- let up = 0; //单价
- let ra = 0; //定额建安费
- let bt = 0; //累计相关
- if (bills.unitPrices[n])
- up = scMathUtil.roundForObj(
- bills.unitPrices[n],
- decimal.bills.unitPrice
- );
- tem.billsUnitPrices.push(up);
- if (bills.prices[n]) {
- p = scMathUtil.roundForObj(bills.prices[n], decimal.bills.totalPrice);
- total = scMathUtil.roundForObj(p + total, decimal.process);
- }
- tem.billsPrices.push(p);
- if (bills.rationCommons[n]) {
- ra = scMathUtil.roundForObj(
- bills.rationCommons[n],
- decimal.bills.totalPrice
- );
- rationTotal = scMathUtil.roundForObj(ra + rationTotal, decimal.process);
- }
- tem.rationCommons.push(ra);
- if (bills.quantityMap[n] && parseFloat(bills.quantityMap[n]) !== 0) {
- tem.billsAmounts.push(bills.quantityMap[n]);
- tem["技术经济指标"].push(
- scMathUtil.roundForObj(p / bills.quantityMap[n], 2)
- );
- } else {
- tem.billsAmounts.push(0);
- tem["技术经济指标"].push(scMathUtil.roundForObj(p, 2));
- }
- //如果是第三部分下的子清单,才要计算累计的相关信息
- // 10-26 需求变更,所有清单都算累计
- /* if (rootFlag == fixedFlag.MAINTENANCE_EXPENSES) {
- if (bills.baseProgressiveFees[n]) {
- bt = scMathUtil.roundForObj(bills.baseProgressiveFees[n], decimal.bills.totalPrice);
- baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
- }
- } */
- if (bills.baseProgressiveFees[n]) {
- bt = scMathUtil.roundForObj(
- bills.baseProgressiveFees[n],
- decimal.bills.totalPrice
- );
- baseTotal = scMathUtil.roundForObj(bt + baseTotal, decimal.process);
- }
- }
- tem.billsTtlPrice = scMathUtil.roundForObj(total, decimal.bills.totalPrice);
- // 10-26 需求变更,所有清单都算累计 && rootFlag == fixedFlag.MAINTENANCE_EXPENSES
- if (progressiveInterval && isProgressiveType) {
- let baseArr = calcUtil.getProgressive(
- bills.calcBase,
- overWrite ? overWrite.progression : undefined
- );
- if (baseArr.length > 0) {
- let deficiency = (overWrite && overWrite.deficiency) || null;
- let beyond = (overWrite && overWrite.beyond) || null;
- let calcTotal = calcUtil.getProgressiveFee(
- baseTotal,
- baseArr[0],
- progressiveInterval,
- decimal.bills.totalPrice,
- deficiency,
- beyond
- );
- tem.billsTtlPrice = calcTotal;
- let rate = scMathUtil.roundForObj(
- (calcTotal * 100) / baseTotal,
- decimal.feeRate
- );
- tem.billsMemos = "费率:" + rate + "%";
- //“费率:n%”,n为汇总后重算的金额/汇总后的基数
- }
- }
- tem.rationTotal = scMathUtil.roundForObj(
- rationTotal,
- decimal.bills.totalPrice
- ); //定额总建安费
- tem["技术经济综合指标"] =
- tem.billsTtlAmt && parseFloat(tem.billsTtlAmt) !== 0
- ? scMathUtil.roundForObj(tem.billsTtlPrice / tem.billsTtlAmt, 2)
- : scMathUtil.roundForObj(tem.billsTtlPrice, 2);
- if (bills.flag == fixedFlag.TOTAL_COST) totalItem = tem;
- if (bills.flag == fixedFlag.ONE_TO_FOUR_TOTAL) one_to_four_Item = tem;
- return tem;
- }
- }
- async function mergeProject(main, sub) {
- //合并两个项目
- let decimal = await decimal_facade.getProjectDecimal(main[0].projectID);
- let project = await projectsModel.findOne({
- ID: main[0].projectID,
- });
- let notMatchList = [];
- for (let s of sub) {
- //先找有没有相同的大项费用
- let same = findTheSameItem(main, s);
- same
- ? await mergeItem(same, s, decimal, project._doc)
- : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
- }
- for (let n of notMatchList) {
- main.push(n);
- }
- return decimal;
- }
- async function mergeItem(a, b, decimal, project) {
- let bqDecimal = await decimal_facade.getBillsQuantityDecimal(
- a.projectID,
- a.unit,
- project
- );
- a.quantity = a.quantity ? scMathUtil.roundForObj(a.quantity, bqDecimal) : 0;
- b.quantity = b.quantity ? scMathUtil.roundForObj(b.quantity, bqDecimal) : 0;
- a.quantity = scMathUtil.roundForObj(a.quantity + b.quantity, decimal.process);
- for (let name in b.prices) {
- a.prices[name] = b.prices[name];
- a.rationCommons[name] = b.rationCommons[name];
- a.quantityMap[name] = b.quantityMap[name];
- a.unitPrices[name] = b.unitPrices[name];
- a.baseProgressiveFees[name] = b.baseProgressiveFees[name];
- }
- for (let name in a.quantityMap) {
- a.quantityMap[name] = a.quantityMap[name]
- ? scMathUtil.roundForObj(a.quantityMap[name], bqDecimal)
- : 0;
- }
- await mergeChildren(a, b, decimal, project);
- }
- async function mergeChildren(a, b, decimal, project) {
- let notMatchList = [];
- if (a.children.length > 0 && b.children.length == 0) {
- return;
- } else if (a.children.length == 0 && b.children.length > 0) {
- a.children = b.children;
- return;
- }
- //=============剩下的是两者都有的情况
- for (let s of b.children) {
- let same = findTheSameItem(a.children, s);
- same ? await mergeItem(same, s, decimal, project) : notMatchList.push(s); //如果找到,则合并,找不到就放在未匹配表
- }
- for (let n of notMatchList) {
- let match = false; //符合插入标记
- //对于未匹配的子项,如果是固定清单:第100章至700章清单的子项,要匹配名字中的数字来做排充
- if (a.flag == fixedFlag.ONE_SEVEN_BILLS) {
- for (let i = 0; i < a.children.length; i++) {
- let m_name = a.children[i].name.replace(/[^0-9]/gi, "");
- let s_name = n.name.replace(/[^0-9]/gi, "");
- m_name = parseFloat(m_name);
- s_name = parseFloat(s_name);
- if (m_name && s_name) {
- if (m_name == s_name) {
- await mergeItem(a.children[i], n, project);
- match = true;
- break;
- }
- if (m_name > s_name) {
- //主节点名字中的数字大于被插节点,则被插节点放在主节点前面
- a.children.splice(i, 0, n);
- match = true;
- break;
- }
- }
- }
- } else {
- //其它的子项按编号进行排序
- for (let i = 0; i < a.children.length; i++) {
- let m_code = a.children[i].code;
- let s_code = n.code;
- if (m_code && s_code && m_code != "" && s_code != "") {
- if (m_code > s_code) {
- a.children.splice(i, 0, n);
- match = true;
- break;
- }
- }
- }
- }
- if (match == false) a.children.push(n); //没有插入成功,直接放到最后面
- }
- }
- function findTheSameItem(main, item) {
- //编号名称单位三个相同,认为是同一条清单
- return _.find(main, function (tem) {
- return (
- isEqual(tem.code, item.code) &&
- isEqual(tem.name, item.name) &&
- isEqual(tem.unit, item.unit)
- );
- });
- }
- function isEqual(a, b) {
- //粗略匹配,null undefind "" 认为相等
- return getValue(a) == getValue(b);
- function getValue(t) {
- if (t == null || t == undefined || t == "") return null;
- return t;
- }
- }
- async function getBillsByProjectID(projectID) {
- let roots = [],
- parentMap = {};
- let bills = await bill_model.model.find(
- {
- projectID: projectID,
- },
- "-_id"
- ); //取出所有清单
- let project = await projectsModel.findOne({
- ID: projectID,
- });
- if (!project) throw new Error(`找不到项目:${projectID}`);
- let projectName = project.name;
- let author = ""; //编制人
- let auditor = ""; //审核人
- let compilationScope = ""; //编制范围
- let engineering = ""; //养护类别
- let progressiveType = 0; //累进计算类型
- let progressiveInterval = null;
- if (project.property && project.property.projectFeature) {
- for (let f of project.property.projectFeature) {
- if (f.key == "author") author = f.value;
- if (f.key == "auditor") auditor = f.value;
- if (f.key == "compilationScope") compilationScope = f.value;
- if (f.key == "engineering") engineering = f.value;
- }
- if (project.property.progressiveType)
- progressiveType = project.property.progressiveType;
- progressiveInterval = project.property.progressiveInterval;
- }
- for (let b of bills) {
- let commonFee = _.find(b._doc.fees, {
- fieldName: "common",
- });
- let prices = {};
- let quantityMap = {};
- let unitPrices = {};
- let rationCommons = {};
- let baseProgressiveFees = {};
- let rationFee = _.find(b._doc.fees, {
- fieldName: "rationCommon",
- });
- if (commonFee && commonFee.tenderTotalFee)
- prices[projectName] = commonFee.tenderTotalFee;
- if (commonFee && commonFee.tenderUnitFee)
- unitPrices[projectName] = commonFee.tenderUnitFee;
- if (rationFee && rationFee.tenderTotalFee)
- rationCommons[projectName] = rationFee.tenderTotalFee;
- baseProgressiveFees[projectName] = b.baseProgressiveFee;
- quantityMap[projectName] = b.quantity;
- let flagIndex = _.find(b._doc.flags, {
- fieldName: "fixed",
- });
- let doc = {
- ID: b.ID,
- name: b.name,
- code: b.code,
- unit: b.unit,
- projectID: b.projectID,
- ParentID: b.ParentID,
- NextSiblingID: b.NextSiblingID,
- unitPrices: unitPrices,
- quantity: b.quantity,
- prices: prices,
- rationCommons: rationCommons,
- quantityMap: quantityMap,
- flag: flagIndex ? flagIndex.flag : -99,
- remark: b.remark,
- calcBase: b.calcBase,
- baseProgressiveFees: baseProgressiveFees,
- }; //选取有用字段
- if (b.ParentID == -1) roots.push(doc);
- parentMap[b.ParentID]
- ? parentMap[b.ParentID].push(doc)
- : (parentMap[b.ParentID] = [doc]);
- } //设置子节点
- for (let r of roots) {
- setChildren(r, parentMap);
- }
- roots = sortChildren(roots);
- return {
- name: projectName,
- roots: roots,
- author: author,
- auditor: auditor,
- compilationScope: compilationScope,
- ParentID: project.ParentID,
- prjTypeName: engineering,
- progressiveType: progressiveType,
- progressiveInterval: progressiveInterval,
- };
- }
- function setChildren(bill, parentMap) {
- let children = parentMap[bill.ID];
- if (children) {
- for (let c of children) {
- setChildren(c, parentMap);
- }
- bill.children = children;
- } else {
- bill.children = [];
- }
- }
- function sortChildren(lists) {
- let IDMap = {},
- nextMap = {},
- firstNode = null,
- newList = [];
- for (let l of lists) {
- if (l.children && l.children.length > 0)
- l.children = sortChildren(l.children); //递规排序
- IDMap[l.ID] = l;
- if (l.NextSiblingID != -1) nextMap[l.NextSiblingID] = l;
- }
- for (let t of lists) {
- if (!nextMap[t.ID]) {
- //如果在下一节点映射没找到,则是第一个节点
- firstNode = t;
- break;
- }
- }
- if (firstNode) {
- newList.push(firstNode);
- delete IDMap[firstNode.ID];
- setNext(firstNode, newList);
- }
- //容错处理,如果链断了的情况,直接添加到后面
- for (let key in IDMap) {
- if (IDMap[key]) newList.push(IDMap[key]);
- }
- return newList;
- function setNext(node, array) {
- if (node.NextSiblingID != -1) {
- let next = IDMap[node.NextSiblingID];
- if (next) {
- array.push(next);
- delete IDMap[next.ID];
- setNext(next, array);
- }
- }
- }
- }
- async function getGLJSummayDatas(projectIDs, compilationName = "") {
- let projects = [];
- let names = [];
- let prjTypeNames = [];
- let compilationScopes = [];
- try {
- for (let ID of projectIDs) {
- projects.push(await getProjectData(ID));
- }
- if (projects.length == 0) {
- return [];
- }
- let mp = projects[0];
- for (let p of projects) {
- names.push(p.name);
- prjTypeNames.push(p.prjTypeName);
- p.gljList = await getProjectGLJData(p.ID, p.unitPriceFileId, mp.property);
- compilationScopes.push(p.compilationScope);
- }
- let mList = mergeGLJ(mp, projects, names, prjTypeNames, compilationName);
- mList = gljUtil.sortProjectGLJ(mList, _);
- let summaryGLJDatas = getSummaryGLJDatas(
- mList,
- mp.property.decimal,
- names,
- prjTypeNames,
- compilationScopes
- );
- let parentProject = await projectsModel.findOne({
- ID: mp.ParentID,
- });
- let result = {
- prj: {},
- SummaryGljAudit: {
- name: parentProject ? parentProject.name : "",
- 编制: mp.author,
- 复核: mp.auditor,
- 编制范围: mp.compilationScope,
- },
- SummaryGljAuditDetail: summaryGLJDatas,
- };
- return result;
- } catch (e) {
- console.log(e.toString());
- }
- }
- function getSummaryGLJDatas(
- gljList,
- decimal,
- nameList,
- prjTypeNames,
- compilationScopes
- ) {
- let datas = [],
- qdecimal = decimal.glj.quantity,
- upDecimal = decimal.glj.unitPrice,
- process = decimal.process;
- for (let tem of gljList) {
- let d = {
- code: tem.code,
- name: tem.name,
- type: tem.type,
- unit: tem.unit,
- specs: tem.specs,
- marketPrice: tem.marketPrice,
- marketPriceList: [],
- prjNames: nameList,
- prjTypeNames: prjTypeNames,
- quantityList: [],
- 编制范围明细: compilationScopes,
- };
- let totalQuantity = 0;
- let totalPrice = 0;
- for (let n of nameList) {
- let q = tem.quantityMap[n]
- ? scMathUtil.roundForObj(tem.quantityMap[n], qdecimal)
- : 0;
- totalQuantity = scMathUtil.roundForObj(q + totalQuantity, process);
- d.quantityList.push(q);
- let up = tem.unitPriceMap[n]
- ? scMathUtil.roundForObj(tem.unitPriceMap[n], upDecimal)
- : 0;
- d.marketPriceList.push(up);
- totalPrice = scMathUtil.roundForObj(q * up + totalPrice, process);
- }
- d.totalQuantity = scMathUtil.roundForObj(totalQuantity, qdecimal);
- d.totalPrice = scMathUtil.roundForObj(totalPrice, upDecimal);
- datas.push(d);
- }
- return datas;
- }
- function mergeGLJ(mp, projects, names, prjTypeNames, compilationName = "") {
- let gljMap = {},
- gljList = [];
- const noPriceChkList = [
- "甘肃养护(2021)",
- "重庆养护(2018)",
- "浙江养护(2005)",
- "安徽养护(2018)",
- "山东养护(2016/2024)",
- "湖南养护(2014)",
- "广西日常养护年度预算(2020)",
- ];
- const noPriceCheck = noPriceChkList.indexOf(compilationName) >= 0;
- for (let g of mp.gljList) {
- g.quantityMap = {};
- g.quantityMap[mp.name] = g.tenderQuantity;
- g.unitPriceMap = {};
- g.unitPriceMap[mp.name] = g.marketPrice;
- gljMap[gljUtil.getIndex(g)] = g;
- gljList.push(g);
- }
- for (let i = 1; i < projects.length; i++) {
- let temList = projects[i].gljList;
- for (let t of temList) {
- t.quantityMap = {};
- t.quantityMap[projects[i].name] = t.tenderQuantity;
- t.unitPriceMap = {};
- t.unitPriceMap[projects[i].name] = t.marketPrice;
- //这里除了5个属性相同判断为同一个之外,还要判断市场价相同,才认为是同一个工料机
- //但有些省份不需要检测,体现在noPriceCheck标记
- let connect_key = gljUtil.getIndex(t);
- let g = gljMap[connect_key];
- if (g && (noPriceCheck || g.marketPrice == t.marketPrice)) {
- g.quantityMap[projects[i].name] = t.tenderQuantity;
- g.unitPriceMap[projects[i].name] = t.marketPrice;
- } else {
- gljMap[connect_key] = t;
- gljList.push(t);
- }
- }
- }
- return gljList;
- }
- async function getProjectGLJData(projectID, unitPriceFileId, property) {
- //取项目工料机数据
- let projectGLJDatas = await getProjectGLJPrice(
- projectID,
- unitPriceFileId,
- property
- );
- await calcProjectGLJQuantity(projectID, projectGLJDatas, property);
- _.remove(projectGLJDatas.gljList, {
- quantity: 0,
- });
- return projectGLJDatas.gljList;
- }
- async function getProjectData(projectID) {
- let project = await projectsModel.findOne({
- ID: projectID,
- });
- if (!project) throw new Error(`找不到项目:${projectID}`);
- let projectName = project.name;
- let author = ""; //编制人
- let auditor = ""; //审核人
- let compilationScope = ""; //编制范围
- let engineering = ""; //养护类别
- if (project.property && project.property.projectFeature) {
- for (let f of project.property.projectFeature) {
- if (f.key == "author") author = f.value;
- if (f.key == "auditor") auditor = f.value;
- if (f.key == "compilationScope") compilationScope = f.value;
- if (f.key == "engineering") engineering = f.value;
- }
- }
- if (!(project.property && project.property.unitPriceFile))
- throw new Error(`找不到单价文件:${projectID}`);
- let unitPriceFileId = project.property.unitPriceFile.id;
- return {
- ID: projectID,
- name: projectName,
- author: author,
- auditor: auditor,
- compilationScope: compilationScope,
- ParentID: project.ParentID,
- prjTypeName: engineering,
- property: project.property,
- unitPriceFileId: unitPriceFileId,
- };
- }
- async function getProjectGLJPrice(projectID, unitPriceFileId, property) {
- //取项目工料机数据
- let calcOptions = property.calcOptions;
- let decimalObj = property.decimal;
- let labourCoeDatas = []; //取调整价才需要用到
- let gljListModel = new GLJListModel();
- let [gljList, mixRatioConnectData, mixRatioMap, unitPriceMap] =
- await gljListModel.getListByProjectId(projectID, unitPriceFileId);
- let unitPriceFileModel = new UnitPriceFileModel();
- let unitFileInfo = await unitPriceFileModel.findDataByCondition({
- id: unitPriceFileId,
- });
- let machineConstCoe = unitFileInfo.machineConstCoe
- ? unitFileInfo.machineConstCoe
- : 1;
- gljList = JSON.parse(JSON.stringify(gljList));
- for (let glj of gljList) {
- let tenderCoe = gljUtil.getTenderPriceCoe(glj, property);
- let result = gljUtil.getGLJPrice(
- glj,
- {
- gljList: gljList,
- constData: { machineConstCoe: machineConstCoe },
- },
- calcOptions,
- labourCoeDatas,
- decimalObj,
- false,
- tenderCoe,
- true
- );
- glj.marketPrice = result.marketPrice;
- glj.basePrice = result.basePrice;
- }
- return {
- gljList: gljList,
- mixRatioMap: mixRatioMap,
- };
- }
- async function calcProjectGLJQuantity(projectID, projectGLJDatas, property) {
- let q_decimal = property.decimal.glj.quantity;
- let rationGLJDatas = await ration_glj_model.find({
- projectID: projectID,
- });
- let rationDatas = await ration_model.model.find({
- projectID: projectID,
- });
- let billDatas = await bill_model.model.find({
- projectID: projectID,
- });
- gljUtil.calcProjectGLJQuantity(
- projectGLJDatas,
- rationGLJDatas,
- rationDatas,
- billDatas,
- q_decimal
- );
- }
|