bill_facade.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. getBudgetSummary: async function (constructionID) {
  142. // 获取建设项目清单数据(工程建设其他费用 - 建设项目总概算)部分
  143. const constructionOtherFeeBills = await bill_Model.find({ projectID: constructionID }).lean();
  144. const sortedOtherFeeBills = getSortedTreeData('-1', constructionOtherFeeBills);
  145. sortedOtherFeeBills.forEach(item => item.area = BudgetArea.CONSTRUCTION_OTHER_FEE);
  146. // 获取工程费用数据
  147. const constructionFeeBills = await this.getConstructionFeeData(constructionID, sortedOtherFeeBills[0].ID);
  148. // 汇算工程费用
  149. await this.summarizeData(constructionFeeBills);
  150. return [...constructionFeeBills, ...sortedOtherFeeBills];
  151. },
  152. // 获取工程费用数据,作为概算汇总数据的拼接树数据
  153. getConstructionFeeData: async function (constructionID, nextID) {
  154. const projects = await pmFacade.getPosterityProjects([constructionID], true, { _id: 0, ID: 1, ParentID: 1, NextSiblingID: 1, name: 1, projType: 1, 'property.engineeringName': 1});
  155. const construction = projects.find(p => p.ID === constructionID);
  156. const items = getSortedTreeData(construction.ParentID, projects);
  157. // 转换为uuid
  158. const IDMap = {};
  159. items.forEach((item, index) => {
  160. //保留项目ID
  161. item.orgProjectID = item.ID;
  162. if (index == 0) {
  163. IDMap[item.ID] = constructionFeeNodeID;
  164. } else {
  165. IDMap[item.ID] = uuidV1()
  166. }
  167. });
  168. // 将项目调整为工程费用数据
  169. let curConstructionID;
  170. let curSingleNo = 0;
  171. let curSingleID;
  172. let curUnitNo = 0;
  173. let latestSingleNode;
  174. items.forEach((item, index) => {
  175. item.area = BudgetArea.CONSTRUCTION_FEE;
  176. item.ID = IDMap[item.ID];
  177. item.ParentID = IDMap[item.ParentID] || '-1';
  178. item.NextSiblingID = IDMap[item.NextSiblingID] || '-1';
  179. if (index === 0) {
  180. curConstructionID = item.ID;
  181. item.type = billType.DXFY;
  182. item.flags = [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_FEE }];
  183. item.code = '1';
  184. item.name = '工程费用';
  185. item.NextSiblingID = nextID;
  186. } else {
  187. item.type = billType.BILL;
  188. if (item.ParentID === curConstructionID) {
  189. latestSingleNode = item;
  190. curSingleNo += 1;
  191. curUnitNo = 0;
  192. curSingleID = item.ID;
  193. item.code = `1.${curSingleNo}`
  194. } else if (item.ParentID === curSingleID) {
  195. curUnitNo += 1;
  196. item.code = `1.${curSingleNo}.${curUnitNo}`
  197. }
  198. }
  199. });
  200. const constructionFeeNode = items[0];
  201. // 设备及工器具购置费
  202. const constructionEquipmentNode = {
  203. type: billType.BILL,
  204. area: BudgetArea.CONSTRUCTION_FEE,
  205. flags: [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_EQUIPMENT_FEE }],
  206. ID: constructionEquipmentFeeNodeID,
  207. ParentID: constructionFeeNode.ID,
  208. NextSiblingID: '-1',
  209. code: `1.${curSingleNo + 1}`,
  210. name: '设备及工器具购置费',
  211. };
  212. latestSingleNode.NextSiblingID = constructionEquipmentNode.ID;
  213. items.push(constructionEquipmentNode);
  214. return items;
  215. },
  216. // 汇算数据
  217. summarizeData: async function (items) {
  218. const processDecimal = 6;
  219. const construction = items.find(item => item.projType === pmFacade.projectType.project);
  220. if (!construction) {
  221. return;
  222. }
  223. const singles = items.filter(item => item.projType === pmFacade.projectType.engineering);
  224. const units = items.filter(item => item.projType === pmFacade.projectType.tender);
  225. if (!singles.length || !units.length) {
  226. return;
  227. }
  228. const unitProjectIDs = units.map(unit => unit.orgProjectID);
  229. // 获取第一个单位工程的小数位数(清单合价)
  230. const theUnit = await projectModel.findOne({ ID: unitProjectIDs[0] }, { _id: 0, 'property.decimal': 1 }).lean();
  231. const decimal = theUnit && theUnit.property && theUnit.property.decimal && theUnit.property.decimal.bills && theUnit.property.decimal.bills.totalPrice || 2;
  232. // 获取单位工程 工程费用映射表
  233. const unitBudgetMap = await this.getUnitsBudgetMap(unitProjectIDs);
  234. // 汇算
  235. const constructionFeeObj = { total: 0, building: 0, installation: 0 };
  236. for (const single of singles) {
  237. const singleFeeObj = { total: 0, building: 0, installation: 0 };
  238. const refUnits = units.filter(unit => unit.ParentID === single.ID);
  239. for (const unit of refUnits) {
  240. const unitFee = unitBudgetMap[unit.orgProjectID];
  241. // 汇算到单项工程
  242. singleFeeObj.total = scMathUtil.roundForObj(singleFeeObj.total + unitFee, processDecimal);
  243. const unitFeeObj = { total: unitFee || 0, building: 0, installation: 0 };
  244. // 建筑工程费、安装工程费
  245. const feeType = getEngineeringFeeType(unit.property && unit.property.engineeringName || '');
  246. if (feeType) {
  247. unitFeeObj[feeType] = unitFee;
  248. singleFeeObj[feeType] = scMathUtil.roundForObj(singleFeeObj[feeType] + unitFee, processDecimal);
  249. }
  250. unit.fees = feeObj2Fees(unitFeeObj);
  251. }
  252. single.fees = feeObj2Fees(singleFeeObj);
  253. // 汇算到建设项目
  254. constructionFeeObj.total = scMathUtil.roundForObj(constructionFeeObj.total + singleFeeObj.total, processDecimal);
  255. constructionFeeObj.building = scMathUtil.roundForObj(constructionFeeObj.building + singleFeeObj.building, processDecimal);
  256. constructionFeeObj.installation = scMathUtil.roundForObj(constructionFeeObj.installation + singleFeeObj.installation, processDecimal);
  257. }
  258. construction.fees = feeObj2Fees(constructionFeeObj);
  259. // 获取设备购置费
  260. const equipmentFee = await this.getEquipmentFee(unitProjectIDs);
  261. const equipmentItem = items.find(item => item.flags && item.flags[0] && item.flags[0].flag === fixedFlag.CONSTRUCTION_EQUIPMENT_FEE);
  262. const equipmentFeeObj = { fieldName: 'equipment', totalFee: equipmentFee };
  263. if (equipmentItem) {
  264. equipmentItem.fees = [equipmentFeeObj];
  265. }
  266. construction.fees.push(equipmentFeeObj);
  267. function feeObj2Fees(feeObj) {
  268. return [
  269. { fieldName: 'common', totalFee: scMathUtil.roundForObj(feeObj.total, decimal) },
  270. { fieldName: 'building', totalFee: scMathUtil.roundForObj(feeObj.building, decimal) },
  271. { fieldName: 'installation', totalFee: scMathUtil.roundForObj(feeObj.installation, decimal) },
  272. ];
  273. }
  274. },
  275. bulkOperation: async function (bulkData) {
  276. const bulks = [];
  277. bulkData.forEach(item => {
  278. if (item.type === 'new') {
  279. bulks.push({
  280. insertOne: { document: item.data }
  281. });
  282. } else if (item.type === 'update') {
  283. bulks.push({
  284. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  285. });
  286. } else {
  287. bulks.push({
  288. deleteOne: { filter: { ID: item.data.ID } }
  289. });
  290. }
  291. });
  292. if (bulks.length) {
  293. await bill_Model.bulkWrite(bulks);
  294. }
  295. }
  296. };
  297. async function pasteOtherData(data) {
  298. let bills = data.bills;
  299. let quantity_details = data.quantity_details;
  300. let ration_coes = data.ration_coes;
  301. let ration_installations = data.ration_installations;
  302. let ration_templates = data.ration_templates;
  303. let updateData = data.updateData;
  304. let uModel = null;
  305. let tasks = [];
  306. //生成更新任务
  307. for(let u of updateData){
  308. if(u.type == "bills"){
  309. uModel = bill_Model;
  310. }else {
  311. uModel = ration_Model;
  312. }
  313. let tem = {
  314. updateOne:{
  315. filter:u.query,
  316. update :u.doc
  317. }
  318. };
  319. tasks.push(tem);
  320. }
  321. bills.length > 0 ? await insertMany(bills,bill_Model):'';
  322. quantity_details.length > 0 ? await insertMany(quantity_details,quantity_detail_model):'';
  323. ration_coes.length > 0 ? await insertMany(ration_coes,ration_coe_Model):'';
  324. ration_installations.length > 0 ? await insertMany(ration_installations,ration_installation_Model):'';
  325. ration_templates.length > 0? await insertMany(ration_templates,ration_template_Model):'';
  326. tasks.length>0?await uModel.bulkWrite(tasks):'';
  327. return {bills:bills,quantity_details:quantity_details,ration_coes:ration_coes,ration_installations:ration_installations,ration_templates:ration_templates,updateData:updateData}
  328. }
  329. async function pasteRationsAndRationGLJ (rations,ration_gljs,compilation) {
  330. let projectGljModel = new GLJListModel();
  331. let gljMap = {}, new_ration_gljs=[],projectID=null,projectGLJList =[];
  332. if(rations.length > 0) projectID = rations[0].projectID;
  333. if(projectID==null && ration_gljs.length > 0) projectID = ration_gljs[0].projectID;
  334. if(projectID == null) return {rations:rations,new_ration_gljs:new_ration_gljs};
  335. let [unitFileId,ext] = await ration_glj_facade.prepareExtData(projectID,compilation);
  336. //先根据定额类型的工料机,插入到项目工料机中
  337. for(let r of rations){
  338. if(r.type == rationType.gljRation){
  339. let projectGLJ = await getProjectGLJ(r,rationKeyArray,gljMap,unitFileId,ext);
  340. projectGLJList.push(projectGLJ);
  341. }
  342. }
  343. for(let rg of ration_gljs){
  344. let projectGLJ = await getProjectGLJ(rg,gljKeyArray,gljMap,unitFileId,ext);
  345. let temRecord = ration_glj_facade.createNewRecord(rg);
  346. rg.rcode?temRecord.rcode = rg.rcode:'';
  347. rg.hasOwnProperty("customQuantity")?temRecord.customQuantity = rg.customQuantity:'';
  348. new_ration_gljs.push(temRecord);
  349. projectGLJList.push(projectGLJ);
  350. }
  351. rations.length>0?await insertMany(rations,ration_Model):'';
  352. new_ration_gljs.length>0?await insertMany(new_ration_gljs,ration_glj_Model):'';
  353. return {rations:rations,new_ration_gljs:new_ration_gljs,projectGLJList:projectGLJList};
  354. async function getProjectGLJ (glj,keyArray,gljMap,unitFileId,ext) {
  355. let keyIndex = projectGljModel.getIndex(glj,keyArray);
  356. let pgljResult = null;
  357. if(gljMap[keyIndex]){
  358. pgljResult = gljMap[keyIndex]
  359. }else {
  360. let p_glj = ration_glj_facade.getGLJSearchInfo(glj);
  361. pgljResult = await projectGljModel.addList(p_glj,unitFileId,ext);//逐条添加到项目工料机
  362. gljMap[keyIndex] = pgljResult;
  363. }
  364. setResult(glj,pgljResult);
  365. return pgljResult
  366. }
  367. function setResult(glj,result ) {
  368. let typeString = result.type+'';
  369. glj.marketPrice = result.unit_price.market_price;
  370. glj.adjustPrice = result.unit_price.base_price;
  371. glj.basePrice = result.unit_price.base_price;
  372. glj.isAdd = result.unit_price.is_add;
  373. glj.projectGLJID = result.id;
  374. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  375. glj.isEstimate = result.is_evaluate;
  376. }
  377. }
  378. }
  379. function generateBillTasks(data) {
  380. let tasks=[];
  381. let user_id = data.user_id,projectID = data.projectID;
  382. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
  383. if(data.delete && data.delete.length > 0){
  384. for(let d_ID of data.delete){
  385. //原先是假删除,现在改成真删除
  386. let task = {
  387. deleteOne:{
  388. filter:{
  389. ID:d_ID,
  390. projectID:projectID
  391. }
  392. }
  393. };
  394. /* let task={
  395. updateOne:{
  396. filter:{
  397. ID:d_ID,
  398. projectID:projectID
  399. },
  400. update :{
  401. deleteInfo:deleteInfo
  402. }
  403. }
  404. };*/
  405. tasks.push(task);
  406. }
  407. }
  408. if(data.update && data.update.length > 0){
  409. for(let u_data of data.update){
  410. let task ={
  411. updateOne:{
  412. filter : {
  413. ID:u_data.ID,
  414. projectID:projectID
  415. },
  416. update : u_data.data
  417. }
  418. };
  419. tasks.push(task);
  420. }
  421. }
  422. if(data.create && data.create.length > 0){
  423. for(let n_data of data.create){
  424. let task = {
  425. insertOne :{
  426. document:n_data
  427. }
  428. };
  429. tasks.push(task);
  430. }
  431. }
  432. return tasks;
  433. }
  434. async function insertMany(datas,model) {
  435. let tem = [];
  436. console.log(datas);
  437. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  438. let newList = datas.splice(0,1000);//一次插入1000条
  439. await model.insertMany(newList);
  440. tem = tem.concat(newList);
  441. }
  442. await model.insertMany(datas);
  443. if(tem.length > 0) datas.push(...tem);//还原数组
  444. }