bill_facade.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /**
  2. * Created by zhang on 2018/1/22.
  3. */
  4. let mongoose = require('mongoose');
  5. let projectConst = require('../models/project_consts');
  6. const rationType = projectConst.rationType;
  7. const rationKeyArray = projectConst.rationKeyArray;
  8. const gljKeyArray = projectConst.gljKeyArray;
  9. let quantity_detail = require("./quantity_detail_facade");
  10. let quantity_detail_model = mongoose.model('quantity_detail');
  11. let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
  12. let Bills_Lib = mongoose.model('std_bills_lib_bills');
  13. let ration_Model = mongoose.model('ration');
  14. let ration_glj_Model = mongoose.model('ration_glj');
  15. let ration_coe_Model = mongoose.model('ration_coe');
  16. const projectModel = mongoose.model('projects');
  17. let ration_installation_Model = mongoose.model('ration_installation');
  18. let ration_template_Model = mongoose.model('ration_template');
  19. let bill_Model = require('../models/bills').model;
  20. let billsLibDao = require("../../bills_lib/models/bills_lib_interfaces");
  21. const pmFacade = require('../../pm/facade/pm_facade');
  22. const { getSortedTreeData, getSortedSeqTreeData, getEngineeringFeeType } = require('../../../public/common_util');
  23. const { billType, constructionFeeNodeID, constructionEquipmentFeeNodeID, BudgetArea, fixedFlag, BudgetType } = require('../../../public/common_constants');
  24. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  25. const uuidV1 = require('uuid/v1');
  26. const equipmentFacade = require('../../equipment_purchase/facade/equipment_purchase_facade');
  27. const gatherModel = mongoose.model('gather_calc_programs');
  28. const GLJController = require("../../glj/controllers/glj_controller");
  29. const GLJListModel = require('../../glj/models/glj_list_model');
  30. let _ = require("lodash");
  31. module.exports={
  32. getSectionInfo : async function (data) {
  33. let conditions=[];
  34. let fxList=[];
  35. let sectionInfo ={};
  36. for(let libID in data){
  37. let codes=[];
  38. let temp={};
  39. codes= _.keys(data[libID]);
  40. temp['billsLibId']=libID;
  41. temp['code'] = {"$in": codes};
  42. conditions.push(temp);
  43. }
  44. if(conditions.length>0){
  45. fxList = await Bills_Lib.find({"$or":conditions});
  46. }
  47. if(fxList.length>0){
  48. let sectionIDs = {};
  49. for(let f of fxList){
  50. if(f._doc.sectionInfo){
  51. f._doc.sectionInfo.first?sectionIDs[f._doc.sectionInfo.first]=true:"";
  52. f._doc.sectionInfo.second?sectionIDs[f._doc.sectionInfo.second]=true:"";
  53. f._doc.sectionInfo.third?sectionIDs[f._doc.sectionInfo.third]=true:"";
  54. }
  55. }
  56. let IDList = _.keys(sectionIDs);
  57. let sectionList = await Bills_Lib.find({'ID':{'$in':IDList}});
  58. let sectionMap = _.mapKeys(sectionList,'ID');
  59. let fxMap = _.mapKeys(fxList,'code');
  60. sectionInfo={
  61. fxMap:fxMap,
  62. sectionMap :sectionMap
  63. }
  64. return sectionInfo;
  65. }
  66. return null;
  67. },
  68. reorganizeFBFX:async function(data){
  69. let result = {};
  70. let tasks = generateBillTasks(data);
  71. if(data.delete && data.delete.length > 0){
  72. let qd_query={projectID: data.projectID, billID: {"$in": data.delete}};
  73. await quantity_detail.deleteByQuery(qd_query) ;
  74. }
  75. if(tasks.length > 0){
  76. result =await bill_Model.bulkWrite(tasks);
  77. }
  78. return result;
  79. },
  80. pasteBlock : async function(data,compilation){
  81. let pasteTasks = [
  82. pasteRationsAndRationGLJ(data.rations,data.ration_gljs,compilation),//这一步会花费比较多时间
  83. pasteOtherData(data)
  84. ];
  85. let [rationsAndRationGLJ,resultMap] = await Promise.all(pasteTasks);
  86. let gljController = new GLJController();
  87. // let projectGLJ = await gljController.getProjectGLJsByProjectID(data.projectID);
  88. resultMap.rations = rationsAndRationGLJ.rations;
  89. resultMap.ration_gljs = rationsAndRationGLJ.new_ration_gljs;
  90. resultMap.projectGLJList = rationsAndRationGLJ.projectGLJList;
  91. // resultMap.gljData = projectGLJ.data;
  92. return resultMap;
  93. },
  94. createNewBills:async function(newDatas){
  95. // billsLibDao.getStdBillsByCode 从这里取数据
  96. let results = [];
  97. for(let bills of newDatas){
  98. let stdB = await billsLibDao.getStdBillsByCode({billsLibId:bills.billsLibId,code:bills.billsLocation});
  99. if(stdB){
  100. stdB = JSON.parse(JSON.stringify(stdB));
  101. if(!bills.unit && /\//.test(stdB.unit)){
  102. bills.unit = stdB.unit.split(/\//)[0];
  103. }
  104. //处理项目特征和工作内容,现在默认都添加到项目特征列中
  105. stdB.itemCharacterText = "[项目特征]\n[工作内容]\n"+stdB.jobContentText;
  106. stdB.jobContentText="";
  107. bills = _.merge(stdB,bills);
  108. }
  109. delete bills.billsLocation;
  110. results.push(bills);
  111. }
  112. if(results.length > 0){
  113. await bill_Model.create(results);
  114. }
  115. return results;
  116. },
  117. insertBills: async function(datas) {
  118. let bulks = [];
  119. for (let data of datas) {
  120. if (data.updateType === 'update') {
  121. bulks.push({updateOne: {filter: {ID: data.updateData.ID}, update: {NextSiblingID: data.updateData.NextSiblingID}}});
  122. } else {
  123. bulks.push({insertOne: {document: data.updateData}});
  124. }
  125. }
  126. if (bulks.length > 0) {
  127. await bill_Model.bulkWrite(bulks);
  128. }
  129. },
  130. // 获取单位工程ID 工程费用(费用汇总里的totalFee) 映射表
  131. getUnitsBudgetMap: async function (unitIDs) {
  132. const rst = {};
  133. const gatherData = await gatherModel.find({ projectID: { $in: unitIDs } }, '-_id projectID totalFee').lean();
  134. const gatherMap = {};
  135. gatherData.forEach(item => gatherMap[item.projectID] = item.totalFee || 0);
  136. unitIDs.forEach(unitID => {
  137. rst[unitID] = gatherMap[unitID] || 0;
  138. });
  139. return rst;
  140. },
  141. // 获取设备购置费
  142. getUnitsEquipmentMap: async function (unitIDs) {
  143. return await equipmentFacade.getEquipmentTotalCost(unitIDs);
  144. },
  145. // 获取概算汇总初始化数据
  146. initialBudgetSummary: async function (constructionID) {
  147. const treeData = await this.getBudgetSummary(constructionID);
  148. const construction = await projectModel.findOne({ ID: constructionID }, { 'property.costGrowthRate': 1, 'property.growthPeriod': 1, 'property.budgetType': 1 }).lean();
  149. const costGrowthRate = construction && construction.property && construction.property.costGrowthRate || 0;
  150. const growthPeriod = construction && construction.property && construction.property.growthPeriod || 0;
  151. const budgetType = construction && construction.property && construction.property.budgetType || BudgetType.BUILDING;
  152. return {
  153. budgetType,
  154. treeData,
  155. costGrowthRate,
  156. growthPeriod,
  157. }
  158. },
  159. // 项目管理等需要获取概算汇总项目数据映射
  160. getBudgetSummaryInfo: async function (constructionIDs) {
  161. const map = {};
  162. const task = [];
  163. for (const constructionID of constructionIDs) {
  164. task.push(this.getBudgetSummary(constructionID, true));
  165. }
  166. const summaryResult = await Promise.all(task);
  167. summaryResult.forEach(items => {
  168. const constructionBudget = items.find(item => item.flags && item.flags[0] && item.flags[0].flag === fixedFlag.CONSTRUCTION_BUDGET);
  169. items.forEach(item => {
  170. if (item.orgProjectID) {
  171. map[item.orgProjectID] = item;
  172. if (item.projType === 'Project' && constructionBudget) {
  173. // 建设项目的总价需要取建设项目总概算
  174. map[item.orgProjectID].totalFee = constructionBudget.totalFee;
  175. map[item.orgProjectID].fees = constructionBudget.fees;
  176. }
  177. }
  178. });
  179. });
  180. return map;
  181. },
  182. // 获取单位工程分部数据(按树结构排好序的)
  183. getFBData: async function (unitID) {
  184. const bills = await bill_Model.find({ projectID: unitID }).lean();
  185. const sortedData = getSortedTreeData('-1', bills);
  186. return sortedData.filter(item => item.type === billType.FB);
  187. },
  188. // 获取概算汇总单项工程级别数据(排好序的,报表接口用)
  189. getSinglesBudgetSummary: async function (constructionID) {
  190. const items = await this.getBudgetSummary(constructionID, true);
  191. // 去除建设项目层级
  192. items.shift();
  193. const [budgetTotalItem] = items.splice(items.length - 1, 1);
  194. const budgetTotalFeeItem = budgetTotalItem.fees && budgetTotalItem.fees.find(f => f.fieldName === 'common');
  195. const budgetTotalFee = budgetTotalFeeItem ? +budgetTotalFeeItem.totalFee : 0;
  196. const rst = [];
  197. for (const project of items) {
  198. rst.push(project);
  199. // 方便报表取值处理
  200. if (project.projType === 'Engineering') {
  201. project.engineeringName = project.name || '';
  202. } else if (project.projType === 'Tender') {
  203. project.tenderName = project.name || '';
  204. // 追加分部和设备购置数据
  205. const feeType = getEngineeringFeeType(project.property && project.property.engineeringName || '');
  206. const fbs = await this.getFBData(project.orgProjectID);
  207. const equipments = await equipmentFacade.getSortedEquipmentData(project.orgProjectID);
  208. const detailData = [...fbs, ...equipments].map(item => {
  209. let totalFee = 0;
  210. if (item.feeType === 'equipment') {
  211. totalFee = item.totalPrice || 0;
  212. } else {
  213. const totalFeeItem = item.fees && item.fees.find(f => f.fieldName === 'common');
  214. totalFee = totalFeeItem ? +totalFeeItem.totalFee : 0;
  215. }
  216. // 计算占总投资比例
  217. const rate = (budgetTotalFee ? scMathUtil.roundForObj(totalFee / budgetTotalFee, 4) : 0) * 100;
  218. return {
  219. code: item.code || '',
  220. name: item.name || '',
  221. buildingFee: item.feeType !== 'equipment' && feeType === 'building' ? totalFee : 0,
  222. installationFee: item.feeType !== 'equipment' && feeType === 'installation' ? totalFee : 0,
  223. equipmentFee: item.feeType === 'equipment' ? totalFee : 0,
  224. otherFee: 0,
  225. totalFee,
  226. rate,
  227. }
  228. });
  229. rst.push(...detailData);
  230. }
  231. }
  232. return rst;
  233. },
  234. // 获取概算汇总数据(拍好序的)
  235. // 如果isSimple为true,只进行工程费用部分汇总,只返回工程费用部分数据
  236. getBudgetSummary: async function (constructionID, isSimple = false) {
  237. // 获取建设项目清单数据(工程建设其他费用 - 建设项目总概算)部分
  238. let sortedOtherFeeBills = [];
  239. if (!isSimple) {
  240. const constructionOtherFeeBills = await bill_Model.find({ projectID: constructionID }).lean();
  241. sortedOtherFeeBills = getSortedTreeData('-1', constructionOtherFeeBills);
  242. sortedOtherFeeBills.forEach(item => item.area = BudgetArea.CONSTRUCTION_OTHER_FEE);
  243. } else {
  244. sortedOtherFeeBills = await bill_Model.find({ projectID: constructionID, 'flags.flag': fixedFlag.CONSTRUCTION_BUDGET }).lean();
  245. }
  246. // 获取工程费用数据
  247. const constructionFeeBills = await this.getConstructionFeeData(constructionID, (sortedOtherFeeBills[0] && sortedOtherFeeBills[0].ID) || '-1');
  248. // 汇算工程费用
  249. await this.summarizeData(constructionFeeBills);
  250. const rst = [...constructionFeeBills, ...sortedOtherFeeBills];
  251. const totalItem = rst.find(item => item.flags && item.flags[0] && item.flags[0].flag === fixedFlag.CONSTRUCTION_BUDGET);
  252. let totalFee = 0;
  253. if (totalItem) {
  254. const totalFeeItem = totalItem.fees && totalItem.fees.find(f => f.fieldName === 'common');
  255. totalFee = totalFeeItem ? +totalFeeItem.totalFee : 0;
  256. }
  257. // 方便报表取数据,规范数据
  258. rst.forEach(item => {
  259. item.code = item.code || '';
  260. item.name = item.name || '';
  261. item.unit = item.unit || '';
  262. item.quantity = item.quantity || '';
  263. const buildingFeeItem = item.fees && item.fees.find(f => f.fieldName === 'building');
  264. const installFeeItem = item.fees && item.fees.find(f => f.fieldName === 'installation');
  265. const equipmentFeeItem = item.fees && item.fees.find(f => f.fieldName === 'equipment');
  266. const otherFeeItem = item.fees && item.fees.find(f => f.fieldName === 'other');
  267. const totalFeeItem = item.fees && item.fees.find(f => f.fieldName === 'common');
  268. const estimateFeeItem = item.fees && item.fees.find(f => f.fieldName === 'estimation');
  269. item.buildingFee = buildingFeeItem ? buildingFeeItem.totalFee : 0;
  270. item.installationFee = installFeeItem ? installFeeItem.totalFee : 0;
  271. item.equipmentFee = equipmentFeeItem ? equipmentFeeItem.totalFee : 0;
  272. item.otherFee = otherFeeItem ? otherFeeItem.totalFee : 0;
  273. item.totalFee = totalFeeItem ? totalFeeItem.totalFee : 0;
  274. item.estimateTotalFee = estimateFeeItem ? estimateFeeItem.totalFee : 0;
  275. item.estimateUnitFee = estimateFeeItem ? estimateFeeItem.unitFee : 0;
  276. item.unitFee = totalFeeItem ? totalFeeItem.unitFee : 0;
  277. item.diffFee = item.estimateTotalFee - item.totalFee; // 增减金额 估算合价-概算合价
  278. item.diffRate = item.estimateTotalFee ? scMathUtil.roundForObj((item.diffFee / item.estimateTotalFee) * 100, 4) : 0; // 增减金额/估算合价*100
  279. // 计算占总投资比例
  280. item.rate = totalFee ? scMathUtil.roundForObj((item.totalFee / totalFee) * 100, 4) : 0;
  281. });
  282. return rst;
  283. },
  284. // 获取工程费用数据,作为概算汇总数据的拼接树数据
  285. getConstructionFeeData: async function (constructionID, nextID) {
  286. const projects = await pmFacade.getPosterityProjects([constructionID], true, { _id: 0, ID: 1, ParentID: 1, NextSiblingID: 1, name: 1, projType: 1, chapterCode: 1, sectionCode: 1, quantity: 1, unit: 1, fees: 1, 'property.engineeringName': 1, 'property.basicInformation': 1 });
  287. const construction = projects.find(p => p.ID === constructionID);
  288. const items = getSortedTreeData(construction.ParentID, projects);
  289. // 转换为uuid
  290. const IDMap = {};
  291. items.forEach((item, index) => {
  292. //保留项目ID
  293. item.orgProjectID = item.ID;
  294. if (index == 0) {
  295. IDMap[item.ID] = constructionFeeNodeID;
  296. } else {
  297. IDMap[item.ID] = uuidV1()
  298. }
  299. });
  300. // 将项目调整为工程费用数据
  301. let curConstructionID;
  302. let curSingleNo = 0;
  303. let curSingleID;
  304. let curUnitNo = 0;
  305. // let latestSingleNode;
  306. items.forEach((item, index) => {
  307. item.area = BudgetArea.CONSTRUCTION_FEE;
  308. item.ID = IDMap[item.ID];
  309. item.ParentID = IDMap[item.ParentID] || '-1';
  310. item.NextSiblingID = IDMap[item.NextSiblingID] || '-1';
  311. if (index === 0) {
  312. curConstructionID = item.ID;
  313. item.type = billType.DXFY;
  314. item.flags = [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_FEE }];
  315. item.code = '1';
  316. item.name = '工程费用';
  317. item.NextSiblingID = nextID;
  318. } else {
  319. item.type = billType.BILL;
  320. if (item.ParentID === curConstructionID) {
  321. // latestSingleNode = item;
  322. curSingleNo += 1;
  323. curUnitNo = 0;
  324. curSingleID = item.ID;
  325. item.code = `1.${curSingleNo}`
  326. } else if (item.ParentID === curSingleID) {
  327. curUnitNo += 1;
  328. item.code = `1.${curSingleNo}.${curUnitNo}`
  329. }
  330. }
  331. });
  332. /* const constructionFeeNode = items[0];
  333. // 设备及工器具购置费
  334. const constructionEquipmentNode = {
  335. type: billType.BILL,
  336. area: BudgetArea.CONSTRUCTION_FEE,
  337. flags: [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_EQUIPMENT_FEE }],
  338. ID: constructionEquipmentFeeNodeID,
  339. ParentID: constructionFeeNode.ID,
  340. NextSiblingID: '-1',
  341. code: `1.${curSingleNo + 1}`,
  342. name: '设备及工器具购置费',
  343. };
  344. latestSingleNode.NextSiblingID = constructionEquipmentNode.ID;
  345. items.push(constructionEquipmentNode); */
  346. return items;
  347. },
  348. // 汇算数据
  349. summarizeData: async function (items) {
  350. const processDecimal = 6;
  351. const construction = items.find(item => item.projType === pmFacade.projectType.project);
  352. if (!construction) {
  353. return;
  354. }
  355. const singles = items.filter(item => item.projType === pmFacade.projectType.engineering);
  356. const units = items.filter(item => item.projType === pmFacade.projectType.tender);
  357. if (!singles.length || !units.length) {
  358. return;
  359. }
  360. const unitProjectIDs = units.map(unit => unit.orgProjectID);
  361. // 工程总量
  362. let projectQuantity = 0;
  363. // 估算总量
  364. let estimateQuantity = 0;
  365. for (const item of construction.property.basicInformation) {
  366. if (item.key === 'basicInfo' && item.items && item.items.length) {
  367. for (const sub of item.items) {
  368. if (sub.key === 'projectQuantity') {
  369. projectQuantity = +sub.value || 0;
  370. } else if (sub.key === 'estimateQuantity') {
  371. estimateQuantity = +sub.value || 0;
  372. }
  373. }
  374. }
  375. }
  376. // 获取第一个单位工程的小数位数(清单合价)
  377. const theUnit = await projectModel.findOne({ ID: unitProjectIDs[0] }, { _id: 0, 'property.decimal': 1 }).lean();
  378. const decimal = theUnit && theUnit.property && theUnit.property.decimal && theUnit.property.decimal.bills && theUnit.property.decimal.bills.totalPrice || 2;
  379. // 获取单位工程 -工程费用映射表
  380. const unitBudgetMap = await this.getUnitsBudgetMap(unitProjectIDs);
  381. // 获取单位工程 - 设备购置费映射表
  382. const unitEquipmentMap = await this.getUnitsEquipmentMap(unitProjectIDs);
  383. // 汇算
  384. const constructionFeeObj = { total: 0, building: 0, installation: 0, equipment: 0 };
  385. for (const single of singles) {
  386. const singleFeeObj = { total: 0, building: 0, installation: 0, equipment: 0 };
  387. const refUnits = units.filter(unit => unit.ParentID === single.ID);
  388. for (const unit of refUnits) {
  389. const unitFee = +unitBudgetMap[unit.orgProjectID]; // 费用汇总算出来的值
  390. const unitEquipmentFee = +unitEquipmentMap[unit.orgProjectID]; // 设备购置窗口的值
  391. const unitTotalFee = scMathUtil.roundForObj(unitFee + unitEquipmentFee, decimal); // 费用汇总算出来的值 + 设备购置值
  392. // 汇算到单项工程
  393. singleFeeObj.total = scMathUtil.roundForObj(singleFeeObj.total + unitTotalFee, processDecimal);
  394. singleFeeObj.equipment = scMathUtil.roundForObj(singleFeeObj.equipment + unitEquipmentFee, processDecimal);
  395. const unitFeeObj = { total: unitTotalFee || 0, building: 0, installation: 0, equipment: unitEquipmentFee || 0 };
  396. // 建筑工程费、安装工程费
  397. const feeType = getEngineeringFeeType(unit.property && unit.property.engineeringName || '');
  398. if (feeType) {
  399. unitFeeObj[feeType] = unitFee;
  400. singleFeeObj[feeType] = scMathUtil.roundForObj(singleFeeObj[feeType] + unitFee, processDecimal);
  401. }
  402. unit.fees = feeObj2Fees(unitFeeObj, unit.fees, projectQuantity, estimateQuantity);
  403. }
  404. single.fees = feeObj2Fees(singleFeeObj, single.fees, projectQuantity, estimateQuantity);
  405. // 汇算到建设项目
  406. constructionFeeObj.total = scMathUtil.roundForObj(constructionFeeObj.total + singleFeeObj.total, processDecimal);
  407. constructionFeeObj.building = scMathUtil.roundForObj(constructionFeeObj.building + singleFeeObj.building, processDecimal);
  408. constructionFeeObj.installation = scMathUtil.roundForObj(constructionFeeObj.installation + singleFeeObj.installation, processDecimal);
  409. constructionFeeObj.equipment = scMathUtil.roundForObj(constructionFeeObj.equipment + singleFeeObj.equipment, processDecimal);
  410. }
  411. construction.fees = feeObj2Fees(constructionFeeObj, construction.fees, projectQuantity, estimateQuantity);
  412. // 更新fees字段
  413. const bulks = [];
  414. items.forEach(item => {
  415. if (item.orgProjectID && item.fees) {
  416. bulks.push({
  417. updateOne: {
  418. filter: { ID: item.orgProjectID },
  419. update: { $set: { fees: item.fees } }
  420. }
  421. })
  422. }
  423. });
  424. if (bulks.length) {
  425. await projectModel.bulkWrite(bulks);
  426. }
  427. // 获取设备购置费(旧)
  428. /* const equipmentFee = await this.getEquipmentFee(unitProjectIDs);
  429. const equipmentItem = items.find(item => item.flags && item.flags[0] && item.flags[0].flag === fixedFlag.CONSTRUCTION_EQUIPMENT_FEE);
  430. const equipmentFeeObj = { fieldName: 'equipment', totalFee: equipmentFee };
  431. if (equipmentItem) {
  432. equipmentItem.fees = [equipmentFeeObj];
  433. }
  434. construction.fees.push(equipmentFeeObj); */
  435. function feeObj2Fees(feeObj, orgFees, quantity, estQuantity) {
  436. const totalFee = scMathUtil.roundForObj(feeObj.total, decimal)
  437. let unitFee = 0;
  438. if (+quantity && totalFee) {
  439. unitFee = scMathUtil.roundForObj(totalFee / (+quantity), 2);
  440. }
  441. const estimateItem = orgFees && orgFees.find(item => item.fieldName === 'estimation') || null;
  442. const estimateFee = estimateItem ? estimateItem.totalFee : 0;
  443. let estimateUnitFee = 0;
  444. if (+estQuantity && estimateFee) {
  445. estimateUnitFee = scMathUtil.roundForObj(estimateFee / (+estQuantity), 2);
  446. }
  447. return [
  448. { fieldName: 'common', totalFee: scMathUtil.roundForObj(feeObj.total, decimal), unitFee },
  449. { fieldName: 'building', totalFee: scMathUtil.roundForObj(feeObj.building, decimal) },
  450. { fieldName: 'installation', totalFee: scMathUtil.roundForObj(feeObj.installation, decimal) },
  451. { fieldName: 'equipment', totalFee: scMathUtil.roundForObj(feeObj.equipment, decimal) },
  452. { fieldName: 'estimation', totalFee: estimateFee, unitFee: estimateUnitFee },
  453. ];
  454. }
  455. },
  456. bulkOperation: async function (bulkData) {
  457. const bulks = [];
  458. const projectBulks = [];
  459. bulkData.forEach(item => {
  460. if (item.type === 'new') {
  461. bulks.push({
  462. insertOne: { document: item.data }
  463. });
  464. } else if (item.type === 'update') {
  465. bulks.push({
  466. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  467. });
  468. } else if (item.type === 'updateProject') {
  469. projectBulks.push({
  470. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  471. });
  472. } else {
  473. bulks.push({
  474. deleteOne: { filter: { ID: item.data.ID } }
  475. });
  476. }
  477. });
  478. if (bulks.length) {
  479. await bill_Model.bulkWrite(bulks);
  480. }
  481. if (projectBulks.length) {
  482. await projectModel.bulkWrite(projectBulks);
  483. }
  484. }
  485. };
  486. async function pasteOtherData(data) {
  487. let bills = data.bills;
  488. let quantity_details = data.quantity_details;
  489. let ration_coes = data.ration_coes;
  490. let ration_installations = data.ration_installations;
  491. let ration_templates = data.ration_templates;
  492. let updateData = data.updateData;
  493. let uModel = null;
  494. let tasks = [];
  495. //生成更新任务
  496. for(let u of updateData){
  497. if(u.type == "bills"){
  498. uModel = bill_Model;
  499. }else {
  500. uModel = ration_Model;
  501. }
  502. let tem = {
  503. updateOne:{
  504. filter:u.query,
  505. update :u.doc
  506. }
  507. };
  508. tasks.push(tem);
  509. }
  510. bills.length > 0 ? await insertMany(bills,bill_Model):'';
  511. quantity_details.length > 0 ? await insertMany(quantity_details,quantity_detail_model):'';
  512. ration_coes.length > 0 ? await insertMany(ration_coes,ration_coe_Model):'';
  513. ration_installations.length > 0 ? await insertMany(ration_installations,ration_installation_Model):'';
  514. ration_templates.length > 0? await insertMany(ration_templates,ration_template_Model):'';
  515. tasks.length>0?await uModel.bulkWrite(tasks):'';
  516. return {bills:bills,quantity_details:quantity_details,ration_coes:ration_coes,ration_installations:ration_installations,ration_templates:ration_templates,updateData:updateData}
  517. }
  518. async function pasteRationsAndRationGLJ (rations,ration_gljs,compilation) {
  519. let projectGljModel = new GLJListModel();
  520. let gljMap = {}, new_ration_gljs=[],projectID=null,projectGLJList =[];
  521. if(rations.length > 0) projectID = rations[0].projectID;
  522. if(projectID==null && ration_gljs.length > 0) projectID = ration_gljs[0].projectID;
  523. if(projectID == null) return {rations:rations,new_ration_gljs:new_ration_gljs};
  524. let [unitFileId,ext] = await ration_glj_facade.prepareExtData(projectID,compilation);
  525. //先根据定额类型的工料机,插入到项目工料机中
  526. for(let r of rations){
  527. if(r.type == rationType.gljRation){
  528. let projectGLJ = await getProjectGLJ(r,rationKeyArray,gljMap,unitFileId,ext);
  529. projectGLJList.push(projectGLJ);
  530. }
  531. }
  532. for(let rg of ration_gljs){
  533. let projectGLJ = await getProjectGLJ(rg,gljKeyArray,gljMap,unitFileId,ext);
  534. let temRecord = ration_glj_facade.createNewRecord(rg);
  535. rg.rcode?temRecord.rcode = rg.rcode:'';
  536. rg.hasOwnProperty("customQuantity")?temRecord.customQuantity = rg.customQuantity:'';
  537. new_ration_gljs.push(temRecord);
  538. projectGLJList.push(projectGLJ);
  539. }
  540. rations.length>0?await insertMany(rations,ration_Model):'';
  541. new_ration_gljs.length>0?await insertMany(new_ration_gljs,ration_glj_Model):'';
  542. return {rations:rations,new_ration_gljs:new_ration_gljs,projectGLJList:projectGLJList};
  543. async function getProjectGLJ (glj,keyArray,gljMap,unitFileId,ext) {
  544. let keyIndex = projectGljModel.getIndex(glj,keyArray);
  545. let pgljResult = null;
  546. if(gljMap[keyIndex]){
  547. pgljResult = gljMap[keyIndex]
  548. }else {
  549. let p_glj = ration_glj_facade.getGLJSearchInfo(glj);
  550. pgljResult = await projectGljModel.addList(p_glj,unitFileId,ext);//逐条添加到项目工料机
  551. gljMap[keyIndex] = pgljResult;
  552. }
  553. setResult(glj,pgljResult);
  554. return pgljResult
  555. }
  556. function setResult(glj,result ) {
  557. let typeString = result.type+'';
  558. glj.marketPrice = result.unit_price.market_price;
  559. glj.adjustPrice = result.unit_price.base_price;
  560. glj.basePrice = result.unit_price.base_price;
  561. glj.isAdd = result.unit_price.is_add;
  562. glj.projectGLJID = result.id;
  563. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  564. glj.isEstimate = result.is_evaluate;
  565. }
  566. }
  567. }
  568. function generateBillTasks(data) {
  569. let tasks=[];
  570. let user_id = data.user_id,projectID = data.projectID;
  571. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
  572. if(data.delete && data.delete.length > 0){
  573. for(let d_ID of data.delete){
  574. //原先是假删除,现在改成真删除
  575. let task = {
  576. deleteOne:{
  577. filter:{
  578. ID:d_ID,
  579. projectID:projectID
  580. }
  581. }
  582. };
  583. /* let task={
  584. updateOne:{
  585. filter:{
  586. ID:d_ID,
  587. projectID:projectID
  588. },
  589. update :{
  590. deleteInfo:deleteInfo
  591. }
  592. }
  593. };*/
  594. tasks.push(task);
  595. }
  596. }
  597. if(data.update && data.update.length > 0){
  598. for(let u_data of data.update){
  599. let task ={
  600. updateOne:{
  601. filter : {
  602. ID:u_data.ID,
  603. projectID:projectID
  604. },
  605. update : u_data.data
  606. }
  607. };
  608. tasks.push(task);
  609. }
  610. }
  611. if(data.create && data.create.length > 0){
  612. for(let n_data of data.create){
  613. let task = {
  614. insertOne :{
  615. document:n_data
  616. }
  617. };
  618. tasks.push(task);
  619. }
  620. }
  621. return tasks;
  622. }
  623. async function insertMany(datas,model) {
  624. let tem = [];
  625. console.log(datas);
  626. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  627. let newList = datas.splice(0,1000);//一次插入1000条
  628. await model.insertMany(newList);
  629. tem = tem.concat(newList);
  630. }
  631. await model.insertMany(datas);
  632. if(tem.length > 0) datas.push(...tem);//还原数组
  633. }