bill_facade.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. let ration_installation_Model = mongoose.model('ration_installation');
  17. let ration_template_Model = mongoose.model('ration_template');
  18. let bill_Model = require('../models/bills').model;
  19. let billsLibDao = require("../../bills_lib/models/bills_lib_interfaces");
  20. const pmFacade = require('../../pm/facade/pm_facade');
  21. const { getSortedTreeData } = require('../../../public/common_util');
  22. const { billType, constructionFeeNodeID, constructionEquipmentFeeNodeID, BudgetArea, fixedFlag } = require('../../../public/common_constants');
  23. const uuidV1 = require('uuid/v1');
  24. const GLJController = require("../../glj/controllers/glj_controller");
  25. const GLJListModel = require('../../glj/models/glj_list_model');
  26. let _ = require("lodash");
  27. module.exports={
  28. getSectionInfo : async function (data) {
  29. let conditions=[];
  30. let fxList=[];
  31. let sectionInfo ={};
  32. for(let libID in data){
  33. let codes=[];
  34. let temp={};
  35. codes= _.keys(data[libID]);
  36. temp['billsLibId']=libID;
  37. temp['code'] = {"$in": codes};
  38. conditions.push(temp);
  39. }
  40. if(conditions.length>0){
  41. fxList = await Bills_Lib.find({"$or":conditions});
  42. }
  43. if(fxList.length>0){
  44. let sectionIDs = {};
  45. for(let f of fxList){
  46. if(f._doc.sectionInfo){
  47. f._doc.sectionInfo.first?sectionIDs[f._doc.sectionInfo.first]=true:"";
  48. f._doc.sectionInfo.second?sectionIDs[f._doc.sectionInfo.second]=true:"";
  49. f._doc.sectionInfo.third?sectionIDs[f._doc.sectionInfo.third]=true:"";
  50. }
  51. }
  52. let IDList = _.keys(sectionIDs);
  53. let sectionList = await Bills_Lib.find({'ID':{'$in':IDList}});
  54. let sectionMap = _.mapKeys(sectionList,'ID');
  55. let fxMap = _.mapKeys(fxList,'code');
  56. sectionInfo={
  57. fxMap:fxMap,
  58. sectionMap :sectionMap
  59. }
  60. return sectionInfo;
  61. }
  62. return null;
  63. },
  64. reorganizeFBFX:async function(data){
  65. let result = {};
  66. let tasks = generateBillTasks(data);
  67. if(data.delete && data.delete.length > 0){
  68. let qd_query={projectID: data.projectID, billID: {"$in": data.delete}};
  69. await quantity_detail.deleteByQuery(qd_query) ;
  70. }
  71. if(tasks.length > 0){
  72. result =await bill_Model.bulkWrite(tasks);
  73. }
  74. return result;
  75. },
  76. pasteBlock : async function(data,compilation){
  77. let pasteTasks = [
  78. pasteRationsAndRationGLJ(data.rations,data.ration_gljs,compilation),//这一步会花费比较多时间
  79. pasteOtherData(data)
  80. ];
  81. let [rationsAndRationGLJ,resultMap] = await Promise.all(pasteTasks);
  82. let gljController = new GLJController();
  83. // let projectGLJ = await gljController.getProjectGLJsByProjectID(data.projectID);
  84. resultMap.rations = rationsAndRationGLJ.rations;
  85. resultMap.ration_gljs = rationsAndRationGLJ.new_ration_gljs;
  86. resultMap.projectGLJList = rationsAndRationGLJ.projectGLJList;
  87. // resultMap.gljData = projectGLJ.data;
  88. return resultMap;
  89. },
  90. createNewBills:async function(newDatas){
  91. // billsLibDao.getStdBillsByCode 从这里取数据
  92. let results = [];
  93. for(let bills of newDatas){
  94. let stdB = await billsLibDao.getStdBillsByCode({billsLibId:bills.billsLibId,code:bills.billsLocation});
  95. if(stdB){
  96. stdB = JSON.parse(JSON.stringify(stdB));
  97. if(!bills.unit && /\//.test(stdB.unit)){
  98. bills.unit = stdB.unit.split(/\//)[0];
  99. }
  100. //处理项目特征和工作内容,现在默认都添加到项目特征列中
  101. stdB.itemCharacterText = "[项目特征]\n[工作内容]\n"+stdB.jobContentText;
  102. stdB.jobContentText="";
  103. bills = _.merge(stdB,bills);
  104. }
  105. delete bills.billsLocation;
  106. results.push(bills);
  107. }
  108. if(results.length > 0){
  109. await bill_Model.create(results);
  110. }
  111. return results;
  112. },
  113. insertBills: async function(datas) {
  114. let bulks = [];
  115. for (let data of datas) {
  116. if (data.updateType === 'update') {
  117. bulks.push({updateOne: {filter: {ID: data.updateData.ID}, update: {NextSiblingID: data.updateData.NextSiblingID}}});
  118. } else {
  119. bulks.push({insertOne: {document: data.updateData}});
  120. }
  121. }
  122. if (bulks.length > 0) {
  123. await bill_Model.bulkWrite(bulks);
  124. }
  125. },
  126. // 获取概算汇总数据(拍好序的)
  127. getBudgetSummary: async function (constructionID) {
  128. // 获取建设项目清单数据(工程建设其他费用 - 建设项目总概算)部分
  129. const constructionOtherFeeBills = await bill_Model.find({ projectID: constructionID }).lean();
  130. const sortedOtherFeeBills = getSortedTreeData('-1', constructionOtherFeeBills);
  131. sortedOtherFeeBills.forEach(item => item.area = BudgetArea.CONSTRUCTION_OTHER_FEE);
  132. // 获取工程费用数据
  133. const constructionFeeBills = await this.getConstructionFeeData(constructionID, sortedOtherFeeBills[0].ID);
  134. return [...constructionFeeBills, ...sortedOtherFeeBills];
  135. },
  136. // 获取工程费用数据,作为概算汇总数据的拼接树数据
  137. getConstructionFeeData: async function (constructionID, nextID) {
  138. const projects = await pmFacade.getPosterityProjects([constructionID], true, { _id: 0, ID: 1, ParentID: 1, NextSiblingID: 1, name: 1, 'property.feeStandardName': 1});
  139. const construction = projects.find(p => p.ID === constructionID);
  140. const items = getSortedTreeData(construction.ParentID, projects);
  141. // 转换为uuid
  142. const IDMap = {};
  143. items.forEach((item, index) => {
  144. if (index == 0) {
  145. IDMap[item.ID] = constructionFeeNodeID;
  146. } else {
  147. IDMap[item.ID] = uuidV1()
  148. }
  149. });
  150. // 将项目调整为工程费用数据
  151. let curConstructionID;
  152. let curSingleNo = 0;
  153. let curSingleID;
  154. let curUnitNo = 0;
  155. let latestSingleNode;
  156. items.forEach((item, index) => {
  157. item.area = BudgetArea.CONSTRUCTION_FEE;
  158. item.ID = IDMap[item.ID];
  159. item.ParentID = IDMap[item.ParentID] || '-1';
  160. item.NextSiblingID = IDMap[item.NextSiblingID] || '-1';
  161. if (index === 0) {
  162. curConstructionID = item.ID;
  163. item.type = billType.DXFY;
  164. item.flags = [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_FEE }];
  165. item.code = '1';
  166. item.name = '工程费用';
  167. item.NextSiblingID = nextID;
  168. } else {
  169. item.type = billType.BILL;
  170. if (item.ParentID === curConstructionID) {
  171. latestSingleNode = item;
  172. curSingleNo += 1;
  173. curUnitNo = 0;
  174. curSingleID = item.ID;
  175. item.code = `1.${curSingleNo}`
  176. } else if (item.ParentID === curSingleID) {
  177. curUnitNo += 1;
  178. item.code = `1.${curSingleNo}.${curUnitNo}`
  179. }
  180. }
  181. });
  182. const constructionFeeNode = items[0];
  183. // 设备及工器具购置费
  184. const constructionEquipmentNode = {
  185. type: billType.BILL,
  186. area: BudgetArea.CONSTRUCTION_FEE,
  187. flags: [{ fieldName: 'fixed', flag: fixedFlag.CONSTRUCTION_EQUIPMENT_FEE }],
  188. ID: constructionEquipmentFeeNodeID,
  189. ParentID: constructionFeeNode.ID,
  190. NextSiblingID: '-1',
  191. code: `1.${curSingleNo + 1}`,
  192. name: '设备及工器具购置费',
  193. };
  194. latestSingleNode.NextSiblingID = constructionEquipmentNode.ID;
  195. items.push(constructionEquipmentNode);
  196. return items;
  197. },
  198. bulkOperation: async function (bulkData) {
  199. const bulks = [];
  200. bulkData.forEach(item => {
  201. if (item.type === 'new') {
  202. bulks.push({
  203. insertOne: { document: item.data }
  204. });
  205. } else if (item.type === 'update') {
  206. bulks.push({
  207. updateOne: { filter: { ID: item.data.ID }, update: { $set: item.data } }
  208. });
  209. } else {
  210. bulks.push({
  211. deleteOne: { filter: { ID: item.data.ID } }
  212. });
  213. }
  214. });
  215. if (bulks.length) {
  216. await bill_Model.bulkWrite(bulks);
  217. }
  218. }
  219. };
  220. async function pasteOtherData(data) {
  221. let bills = data.bills;
  222. let quantity_details = data.quantity_details;
  223. let ration_coes = data.ration_coes;
  224. let ration_installations = data.ration_installations;
  225. let ration_templates = data.ration_templates;
  226. let updateData = data.updateData;
  227. let uModel = null;
  228. let tasks = [];
  229. //生成更新任务
  230. for(let u of updateData){
  231. if(u.type == "bills"){
  232. uModel = bill_Model;
  233. }else {
  234. uModel = ration_Model;
  235. }
  236. let tem = {
  237. updateOne:{
  238. filter:u.query,
  239. update :u.doc
  240. }
  241. };
  242. tasks.push(tem);
  243. }
  244. bills.length > 0 ? await insertMany(bills,bill_Model):'';
  245. quantity_details.length > 0 ? await insertMany(quantity_details,quantity_detail_model):'';
  246. ration_coes.length > 0 ? await insertMany(ration_coes,ration_coe_Model):'';
  247. ration_installations.length > 0 ? await insertMany(ration_installations,ration_installation_Model):'';
  248. ration_templates.length > 0? await insertMany(ration_templates,ration_template_Model):'';
  249. tasks.length>0?await uModel.bulkWrite(tasks):'';
  250. return {bills:bills,quantity_details:quantity_details,ration_coes:ration_coes,ration_installations:ration_installations,ration_templates:ration_templates,updateData:updateData}
  251. }
  252. async function pasteRationsAndRationGLJ (rations,ration_gljs,compilation) {
  253. let projectGljModel = new GLJListModel();
  254. let gljMap = {}, new_ration_gljs=[],projectID=null,projectGLJList =[];
  255. if(rations.length > 0) projectID = rations[0].projectID;
  256. if(projectID==null && ration_gljs.length > 0) projectID = ration_gljs[0].projectID;
  257. if(projectID == null) return {rations:rations,new_ration_gljs:new_ration_gljs};
  258. let [unitFileId,ext] = await ration_glj_facade.prepareExtData(projectID,compilation);
  259. //先根据定额类型的工料机,插入到项目工料机中
  260. for(let r of rations){
  261. if(r.type == rationType.gljRation){
  262. let projectGLJ = await getProjectGLJ(r,rationKeyArray,gljMap,unitFileId,ext);
  263. projectGLJList.push(projectGLJ);
  264. }
  265. }
  266. for(let rg of ration_gljs){
  267. let projectGLJ = await getProjectGLJ(rg,gljKeyArray,gljMap,unitFileId,ext);
  268. let temRecord = ration_glj_facade.createNewRecord(rg);
  269. rg.rcode?temRecord.rcode = rg.rcode:'';
  270. rg.hasOwnProperty("customQuantity")?temRecord.customQuantity = rg.customQuantity:'';
  271. new_ration_gljs.push(temRecord);
  272. projectGLJList.push(projectGLJ);
  273. }
  274. rations.length>0?await insertMany(rations,ration_Model):'';
  275. new_ration_gljs.length>0?await insertMany(new_ration_gljs,ration_glj_Model):'';
  276. return {rations:rations,new_ration_gljs:new_ration_gljs,projectGLJList:projectGLJList};
  277. async function getProjectGLJ (glj,keyArray,gljMap,unitFileId,ext) {
  278. let keyIndex = projectGljModel.getIndex(glj,keyArray);
  279. let pgljResult = null;
  280. if(gljMap[keyIndex]){
  281. pgljResult = gljMap[keyIndex]
  282. }else {
  283. let p_glj = ration_glj_facade.getGLJSearchInfo(glj);
  284. pgljResult = await projectGljModel.addList(p_glj,unitFileId,ext);//逐条添加到项目工料机
  285. gljMap[keyIndex] = pgljResult;
  286. }
  287. setResult(glj,pgljResult);
  288. return pgljResult
  289. }
  290. function setResult(glj,result ) {
  291. let typeString = result.type+'';
  292. glj.marketPrice = result.unit_price.market_price;
  293. glj.adjustPrice = result.unit_price.base_price;
  294. glj.basePrice = result.unit_price.base_price;
  295. glj.isAdd = result.unit_price.is_add;
  296. glj.projectGLJID = result.id;
  297. if (typeString.startsWith("2")||typeString=='4'||typeString=='5') {//只有材料类型才显示是否暂估
  298. glj.isEstimate = result.is_evaluate;
  299. }
  300. }
  301. }
  302. function generateBillTasks(data) {
  303. let tasks=[];
  304. let user_id = data.user_id,projectID = data.projectID;
  305. let deleteInfo={deleted: true, deleteDateTime: new Date(), deleteBy: user_id};
  306. if(data.delete && data.delete.length > 0){
  307. for(let d_ID of data.delete){
  308. //原先是假删除,现在改成真删除
  309. let task = {
  310. deleteOne:{
  311. filter:{
  312. ID:d_ID,
  313. projectID:projectID
  314. }
  315. }
  316. };
  317. /* let task={
  318. updateOne:{
  319. filter:{
  320. ID:d_ID,
  321. projectID:projectID
  322. },
  323. update :{
  324. deleteInfo:deleteInfo
  325. }
  326. }
  327. };*/
  328. tasks.push(task);
  329. }
  330. }
  331. if(data.update && data.update.length > 0){
  332. for(let u_data of data.update){
  333. let task ={
  334. updateOne:{
  335. filter : {
  336. ID:u_data.ID,
  337. projectID:projectID
  338. },
  339. update : u_data.data
  340. }
  341. };
  342. tasks.push(task);
  343. }
  344. }
  345. if(data.create && data.create.length > 0){
  346. for(let n_data of data.create){
  347. let task = {
  348. insertOne :{
  349. document:n_data
  350. }
  351. };
  352. tasks.push(task);
  353. }
  354. }
  355. return tasks;
  356. }
  357. async function insertMany(datas,model) {
  358. let tem = [];
  359. console.log(datas);
  360. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  361. let newList = datas.splice(0,1000);//一次插入1000条
  362. await model.insertMany(newList);
  363. tem = tem.concat(newList);
  364. }
  365. await model.insertMany(datas);
  366. if(tem.length > 0) datas.push(...tem);//还原数组
  367. }