bill_facade.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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, getEngineeringFeeType } = require('../../../public/common_util');
  23. const { billType, constructionFeeNodeID, constructionEquipmentFeeNodeID, BudgetArea, fixedFlag } = require('../../../public/common_constants');
  24. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  25. const uuidV1 = require('uuid/v1');
  26. const GLJController = require("../../glj/controllers/glj_controller");
  27. const GLJListModel = require('../../glj/models/glj_list_model');
  28. let _ = require("lodash");
  29. module.exports={
  30. getSectionInfo : async function (data) {
  31. let conditions=[];
  32. let fxList=[];
  33. let sectionInfo ={};
  34. for(let libID in data){
  35. let codes=[];
  36. let temp={};
  37. codes= _.keys(data[libID]);
  38. temp['billsLibId']=libID;
  39. temp['code'] = {"$in": codes};
  40. conditions.push(temp);
  41. }
  42. if(conditions.length>0){
  43. fxList = await Bills_Lib.find({"$or":conditions});
  44. }
  45. if(fxList.length>0){
  46. let sectionIDs = {};
  47. for(let f of fxList){
  48. if(f._doc.sectionInfo){
  49. f._doc.sectionInfo.first?sectionIDs[f._doc.sectionInfo.first]=true:"";
  50. f._doc.sectionInfo.second?sectionIDs[f._doc.sectionInfo.second]=true:"";
  51. f._doc.sectionInfo.third?sectionIDs[f._doc.sectionInfo.third]=true:"";
  52. }
  53. }
  54. let IDList = _.keys(sectionIDs);
  55. let sectionList = await Bills_Lib.find({'ID':{'$in':IDList}});
  56. let sectionMap = _.mapKeys(sectionList,'ID');
  57. let fxMap = _.mapKeys(fxList,'code');
  58. sectionInfo={
  59. fxMap:fxMap,
  60. sectionMap :sectionMap
  61. }
  62. return sectionInfo;
  63. }
  64. return null;
  65. },
  66. reorganizeFBFX:async function(data){
  67. let result = {};
  68. let tasks = generateBillTasks(data);
  69. if(data.delete && data.delete.length > 0){
  70. let qd_query={projectID: data.projectID, billID: {"$in": data.delete}};
  71. await quantity_detail.deleteByQuery(qd_query) ;
  72. }
  73. if(tasks.length > 0){
  74. result =await bill_Model.bulkWrite(tasks);
  75. }
  76. return result;
  77. },
  78. pasteBlock : async function(data,compilation){
  79. let pasteTasks = [
  80. pasteRationsAndRationGLJ(data.rations,data.ration_gljs,compilation),//这一步会花费比较多时间
  81. pasteOtherData(data)
  82. ];
  83. let [rationsAndRationGLJ,resultMap] = await Promise.all(pasteTasks);
  84. let gljController = new GLJController();
  85. // let projectGLJ = await gljController.getProjectGLJsByProjectID(data.projectID);
  86. resultMap.rations = rationsAndRationGLJ.rations;
  87. resultMap.ration_gljs = rationsAndRationGLJ.new_ration_gljs;
  88. resultMap.projectGLJList = rationsAndRationGLJ.projectGLJList;
  89. // resultMap.gljData = projectGLJ.data;
  90. return resultMap;
  91. },
  92. createNewBills:async function(newDatas){
  93. // billsLibDao.getStdBillsByCode 从这里取数据
  94. let results = [];
  95. for(let bills of newDatas){
  96. let stdB = await billsLibDao.getStdBillsByCode({billsLibId:bills.billsLibId,code:bills.billsLocation});
  97. if(stdB){
  98. stdB = JSON.parse(JSON.stringify(stdB));
  99. if(!bills.unit && /\//.test(stdB.unit)){
  100. bills.unit = stdB.unit.split(/\//)[0];
  101. }
  102. //处理项目特征和工作内容,现在默认都添加到项目特征列中
  103. stdB.itemCharacterText = "[项目特征]\n[工作内容]\n"+stdB.jobContentText;
  104. stdB.jobContentText="";
  105. bills = _.merge(stdB,bills);
  106. }
  107. delete bills.billsLocation;
  108. results.push(bills);
  109. }
  110. if(results.length > 0){
  111. await bill_Model.create(results);
  112. }
  113. return results;
  114. },
  115. insertBills: async function(datas) {
  116. let bulks = [];
  117. for (let data of datas) {
  118. if (data.updateType === 'update') {
  119. bulks.push({updateOne: {filter: {ID: data.updateData.ID}, update: {NextSiblingID: data.updateData.NextSiblingID}}});
  120. } else {
  121. bulks.push({insertOne: {document: data.updateData}});
  122. }
  123. }
  124. if (bulks.length > 0) {
  125. await bill_Model.bulkWrite(bulks);
  126. }
  127. },
  128. // 获取单位工程ID 工程费用 映射表
  129. getUnitsBudgetMap: async function (unitIDs) {
  130. const rst = {};
  131. unitIDs.forEach(unitID => {
  132. rst[unitID] = 1000000;
  133. });
  134. return rst;
  135. },
  136. // 获取设备购置费
  137. getEquipmentFee: async function (unitIDs) {
  138. return 5000.15;
  139. },
  140. // 获取概算汇总初始化数据
  141. initialBudgetSummary: async function (constructionID) {
  142. const treeData = await this.getBudgetSummary(constructionID);
  143. const construction = await projectModel.findOne({ ID: constructionID }, { 'property.costGrowthRate': 1, 'property.growthPeriod': 1 }).lean();
  144. const costGrowthRate = construction && construction.property && construction.property.costGrowthRate || 0;
  145. const growthPeriod = construction && construction.property && construction.property.growthPeriod || 0;
  146. return {
  147. treeData,
  148. costGrowthRate,
  149. growthPeriod,
  150. }
  151. },
  152. // 获取概算汇总数据(拍好序的)
  153. getBudgetSummary: async function (constructionID) {
  154. // 获取建设项目清单数据(工程建设其他费用 - 建设项目总概算)部分
  155. const constructionOtherFeeBills = await bill_Model.find({ projectID: constructionID }).lean();
  156. const sortedOtherFeeBills = getSortedTreeData('-1', constructionOtherFeeBills);
  157. sortedOtherFeeBills.forEach(item => item.area = BudgetArea.CONSTRUCTION_OTHER_FEE);
  158. // 获取工程费用数据
  159. const constructionFeeBills = await this.getConstructionFeeData(constructionID, sortedOtherFeeBills[0].ID);
  160. // 汇算工程费用
  161. await this.summarizeData(constructionFeeBills);
  162. const rst = [...constructionFeeBills, ...sortedOtherFeeBills];
  163. // 方便报表取数据,规范数据
  164. rst.forEach(item => {
  165. item.code = item.code || '';
  166. item.name = item.name || '';
  167. item.unit = item.unit || '';
  168. item.quantity = item.quantity || '';
  169. const buildingFeeItem = item.fees && item.fees.find(f => f.fieldName === 'building');
  170. const installFeeItem = item.fees && item.fees.find(f => f.fieldName === 'installation');
  171. const equipmentFeeItem = item.fees && item.fees.find(f => f.fieldName === 'equipment');
  172. const otherFeeItem = item.fees && item.fees.find(f => f.fieldName === 'other');
  173. const totalFeeItem = item.fees && item.fees.find(f => f.fieldName === 'common');
  174. item.buildingFee = buildingFeeItem ? buildingFeeItem.totalFee : 0;
  175. item.installationFee = installFeeItem ? installFeeItem.totalFee : 0;
  176. item.equipmentFee = equipmentFeeItem ? equipmentFeeItem.totalFee : 0;
  177. item.otherFee = otherFeeItem ? otherFeeItem.totalFee : 0;
  178. item.totalFee = totalFeeItem ? totalFeeItem.totalFee : 0;
  179. item.rate = '0';
  180. });
  181. return rst;
  182. },
  183. // 获取工程费用数据,作为概算汇总数据的拼接树数据
  184. getConstructionFeeData: async function (constructionID, nextID) {
  185. const projects = await pmFacade.getPosterityProjects([constructionID], true, { _id: 0, ID: 1, ParentID: 1, NextSiblingID: 1, name: 1, projType: 1, 'property.engineeringName': 1});
  186. const construction = projects.find(p => p.ID === constructionID);
  187. const items = getSortedTreeData(construction.ParentID, projects);
  188. // 转换为uuid
  189. const IDMap = {};
  190. items.forEach((item, index) => {
  191. //保留项目ID
  192. item.orgProjectID = item.ID;
  193. if (index == 0) {
  194. IDMap[item.ID] = constructionFeeNodeID;
  195. } else {
  196. IDMap[item.ID] = uuidV1()
  197. }
  198. });
  199. // 将项目调整为工程费用数据
  200. let curConstructionID;
  201. let curSingleNo = 0;
  202. let curSingleID;
  203. let curUnitNo = 0;
  204. let latestSingleNode;
  205. items.forEach((item, index) => {
  206. item.area = BudgetArea.CONSTRUCTION_FEE;
  207. item.ID = IDMap[item.ID];
  208. item.ParentID = IDMap[item.ParentID] || '-1';
  209. item.NextSiblingID = IDMap[item.NextSiblingID] || '-1';
  210. if (index === 0) {
  211. curConstructionID = item.ID;
  212. item.type = billType.DXFY;
  213. item.flags = [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_FEE }];
  214. item.code = '1';
  215. item.name = '工程费用';
  216. item.NextSiblingID = nextID;
  217. } else {
  218. item.type = billType.BILL;
  219. if (item.ParentID === curConstructionID) {
  220. latestSingleNode = item;
  221. curSingleNo += 1;
  222. curUnitNo = 0;
  223. curSingleID = item.ID;
  224. item.code = `1.${curSingleNo}`
  225. } else if (item.ParentID === curSingleID) {
  226. curUnitNo += 1;
  227. item.code = `1.${curSingleNo}.${curUnitNo}`
  228. }
  229. }
  230. });
  231. const constructionFeeNode = items[0];
  232. // 设备及工器具购置费
  233. const constructionEquipmentNode = {
  234. type: billType.BILL,
  235. area: BudgetArea.CONSTRUCTION_FEE,
  236. flags: [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_EQUIPMENT_FEE }],
  237. ID: constructionEquipmentFeeNodeID,
  238. ParentID: constructionFeeNode.ID,
  239. NextSiblingID: '-1',
  240. code: `1.${curSingleNo + 1}`,
  241. name: '设备及工器具购置费',
  242. };
  243. latestSingleNode.NextSiblingID = constructionEquipmentNode.ID;
  244. items.push(constructionEquipmentNode);
  245. return items;
  246. },
  247. // 汇算数据
  248. summarizeData: async function (items) {
  249. const processDecimal = 6;
  250. const construction = items.find(item => item.projType === pmFacade.projectType.project);
  251. if (!construction) {
  252. return;
  253. }
  254. const singles = items.filter(item => item.projType === pmFacade.projectType.engineering);
  255. const units = items.filter(item => item.projType === pmFacade.projectType.tender);
  256. if (!singles.length || !units.length) {
  257. return;
  258. }
  259. const unitProjectIDs = units.map(unit => unit.orgProjectID);
  260. // 获取第一个单位工程的小数位数(清单合价)
  261. const theUnit = await projectModel.findOne({ ID: unitProjectIDs[0] }, { _id: 0, 'property.decimal': 1 }).lean();
  262. const decimal = theUnit && theUnit.property && theUnit.property.decimal && theUnit.property.decimal.bills && theUnit.property.decimal.bills.totalPrice || 2;
  263. // 获取单位工程 工程费用映射表
  264. const unitBudgetMap = await this.getUnitsBudgetMap(unitProjectIDs);
  265. // 汇算
  266. const constructionFeeObj = { total: 0, building: 0, installation: 0 };
  267. for (const single of singles) {
  268. const singleFeeObj = { total: 0, building: 0, installation: 0 };
  269. const refUnits = units.filter(unit => unit.ParentID === single.ID);
  270. for (const unit of refUnits) {
  271. const unitFee = unitBudgetMap[unit.orgProjectID];
  272. // 汇算到单项工程
  273. singleFeeObj.total = scMathUtil.roundForObj(singleFeeObj.total + unitFee, processDecimal);
  274. const unitFeeObj = { total: unitFee || 0, building: 0, installation: 0 };
  275. // 建筑工程费、安装工程费
  276. const feeType = getEngineeringFeeType(unit.property && unit.property.engineeringName || '');
  277. if (feeType) {
  278. unitFeeObj[feeType] = unitFee;
  279. singleFeeObj[feeType] = scMathUtil.roundForObj(singleFeeObj[feeType] + unitFee, processDecimal);
  280. }
  281. unit.fees = feeObj2Fees(unitFeeObj);
  282. }
  283. single.fees = feeObj2Fees(singleFeeObj);
  284. // 汇算到建设项目
  285. constructionFeeObj.total = scMathUtil.roundForObj(constructionFeeObj.total + singleFeeObj.total, processDecimal);
  286. constructionFeeObj.building = scMathUtil.roundForObj(constructionFeeObj.building + singleFeeObj.building, processDecimal);
  287. constructionFeeObj.installation = scMathUtil.roundForObj(constructionFeeObj.installation + singleFeeObj.installation, processDecimal);
  288. }
  289. construction.fees = feeObj2Fees(constructionFeeObj);
  290. // 获取设备购置费
  291. const equipmentFee = await this.getEquipmentFee(unitProjectIDs);
  292. const equipmentItem = items.find(item => item.flags && item.flags[0] && item.flags[0].flag === fixedFlag.CONSTRUCTION_EQUIPMENT_FEE);
  293. const equipmentFeeObj = { fieldName: 'equipment', totalFee: equipmentFee };
  294. if (equipmentItem) {
  295. equipmentItem.fees = [equipmentFeeObj];
  296. }
  297. construction.fees.push(equipmentFeeObj);
  298. function feeObj2Fees(feeObj) {
  299. return [
  300. { fieldName: 'common', totalFee: scMathUtil.roundForObj(feeObj.total, decimal) },
  301. { fieldName: 'building', totalFee: scMathUtil.roundForObj(feeObj.building, decimal) },
  302. { fieldName: 'installation', totalFee: scMathUtil.roundForObj(feeObj.installation, decimal) },
  303. ];
  304. }
  305. },
  306. bulkOperation: async function (bulkData) {
  307. const bulks = [];
  308. const projectBulks = [];
  309. bulkData.forEach(item => {
  310. if (item.type === 'new') {
  311. bulks.push({
  312. insertOne: { document: item.data }
  313. });
  314. } else if (item.type === 'update') {
  315. bulks.push({
  316. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  317. });
  318. } else if (item.type === 'updateProject') {
  319. projectBulks.push({
  320. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  321. });
  322. } else {
  323. bulks.push({
  324. deleteOne: { filter: { ID: item.data.ID } }
  325. });
  326. }
  327. });
  328. if (bulks.length) {
  329. await bill_Model.bulkWrite(bulks);
  330. }
  331. if (projectBulks.length) {
  332. await projectModel.bulkWrite(projectBulks);
  333. }
  334. }
  335. };
  336. async function pasteOtherData(data) {
  337. let bills = data.bills;
  338. let quantity_details = data.quantity_details;
  339. let ration_coes = data.ration_coes;
  340. let ration_installations = data.ration_installations;
  341. let ration_templates = data.ration_templates;
  342. let updateData = data.updateData;
  343. let uModel = null;
  344. let tasks = [];
  345. //生成更新任务
  346. for(let u of updateData){
  347. if(u.type == "bills"){
  348. uModel = bill_Model;
  349. }else {
  350. uModel = ration_Model;
  351. }
  352. let tem = {
  353. updateOne:{
  354. filter:u.query,
  355. update :u.doc
  356. }
  357. };
  358. tasks.push(tem);
  359. }
  360. bills.length > 0 ? await insertMany(bills,bill_Model):'';
  361. quantity_details.length > 0 ? await insertMany(quantity_details,quantity_detail_model):'';
  362. ration_coes.length > 0 ? await insertMany(ration_coes,ration_coe_Model):'';
  363. ration_installations.length > 0 ? await insertMany(ration_installations,ration_installation_Model):'';
  364. ration_templates.length > 0? await insertMany(ration_templates,ration_template_Model):'';
  365. tasks.length>0?await uModel.bulkWrite(tasks):'';
  366. return {bills:bills,quantity_details:quantity_details,ration_coes:ration_coes,ration_installations:ration_installations,ration_templates:ration_templates,updateData:updateData}
  367. }
  368. async function pasteRationsAndRationGLJ (rations,ration_gljs,compilation) {
  369. let projectGljModel = new GLJListModel();
  370. let gljMap = {}, new_ration_gljs=[],projectID=null,projectGLJList =[];
  371. if(rations.length > 0) projectID = rations[0].projectID;
  372. if(projectID==null && ration_gljs.length > 0) projectID = ration_gljs[0].projectID;
  373. if(projectID == null) return {rations:rations,new_ration_gljs:new_ration_gljs};
  374. let [unitFileId,ext] = await ration_glj_facade.prepareExtData(projectID,compilation);
  375. //先根据定额类型的工料机,插入到项目工料机中
  376. for(let r of rations){
  377. if(r.type == rationType.gljRation){
  378. let projectGLJ = await getProjectGLJ(r,rationKeyArray,gljMap,unitFileId,ext);
  379. projectGLJList.push(projectGLJ);
  380. }
  381. }
  382. for(let rg of ration_gljs){
  383. let projectGLJ = await getProjectGLJ(rg,gljKeyArray,gljMap,unitFileId,ext);
  384. let temRecord = ration_glj_facade.createNewRecord(rg);
  385. rg.rcode?temRecord.rcode = rg.rcode:'';
  386. rg.hasOwnProperty("customQuantity")?temRecord.customQuantity = rg.customQuantity:'';
  387. new_ration_gljs.push(temRecord);
  388. projectGLJList.push(projectGLJ);
  389. }
  390. rations.length>0?await insertMany(rations,ration_Model):'';
  391. new_ration_gljs.length>0?await insertMany(new_ration_gljs,ration_glj_Model):'';
  392. return {rations:rations,new_ration_gljs:new_ration_gljs,projectGLJList:projectGLJList};
  393. async function getProjectGLJ (glj,keyArray,gljMap,unitFileId,ext) {
  394. let keyIndex = projectGljModel.getIndex(glj,keyArray);
  395. let pgljResult = null;
  396. if(gljMap[keyIndex]){
  397. pgljResult = gljMap[keyIndex]
  398. }else {
  399. let p_glj = ration_glj_facade.getGLJSearchInfo(glj);
  400. pgljResult = await projectGljModel.addList(p_glj,unitFileId,ext);//逐条添加到项目工料机
  401. gljMap[keyIndex] = pgljResult;
  402. }
  403. setResult(glj,pgljResult);
  404. return pgljResult
  405. }
  406. function setResult(glj,result ) {
  407. let typeString = result.type+'';
  408. glj.marketPrice = result.unit_price.market_price;
  409. glj.adjustPrice = result.unit_price.base_price;
  410. glj.basePrice = result.unit_price.base_price;
  411. glj.isAdd = result.unit_price.is_add;
  412. glj.projectGLJID = result.id;
  413. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  414. glj.isEstimate = result.is_evaluate;
  415. }
  416. }
  417. }
  418. function generateBillTasks(data) {
  419. let tasks=[];
  420. let user_id = data.user_id,projectID = data.projectID;
  421. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
  422. if(data.delete && data.delete.length > 0){
  423. for(let d_ID of data.delete){
  424. //原先是假删除,现在改成真删除
  425. let task = {
  426. deleteOne:{
  427. filter:{
  428. ID:d_ID,
  429. projectID:projectID
  430. }
  431. }
  432. };
  433. /* let task={
  434. updateOne:{
  435. filter:{
  436. ID:d_ID,
  437. projectID:projectID
  438. },
  439. update :{
  440. deleteInfo:deleteInfo
  441. }
  442. }
  443. };*/
  444. tasks.push(task);
  445. }
  446. }
  447. if(data.update && data.update.length > 0){
  448. for(let u_data of data.update){
  449. let task ={
  450. updateOne:{
  451. filter : {
  452. ID:u_data.ID,
  453. projectID:projectID
  454. },
  455. update : u_data.data
  456. }
  457. };
  458. tasks.push(task);
  459. }
  460. }
  461. if(data.create && data.create.length > 0){
  462. for(let n_data of data.create){
  463. let task = {
  464. insertOne :{
  465. document:n_data
  466. }
  467. };
  468. tasks.push(task);
  469. }
  470. }
  471. return tasks;
  472. }
  473. async function insertMany(datas,model) {
  474. let tem = [];
  475. console.log(datas);
  476. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  477. let newList = datas.splice(0,1000);//一次插入1000条
  478. await model.insertMany(newList);
  479. tem = tem.concat(newList);
  480. }
  481. await model.insertMany(datas);
  482. if(tem.length > 0) datas.push(...tem);//还原数组
  483. }