ration_facade.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. /**
  2. * Created by zhang on 2018/2/9.
  3. */
  4. module.exports = {
  5. replaceRations: replaceRations,
  6. addNewRation:addNewRation,
  7. updateMaterialRation:updateMaterialRation,
  8. updateDivideRation:updateDivideRation,
  9. addMaterialRation:addMaterialRation,
  10. addMultiRation: addMultiRation,
  11. getSameSectionRations:getSameSectionRations,
  12. getExtendData:getExtendData,
  13. getDefaultProgramID:getDefaultProgramID,
  14. deleteSubListByQuery:deleteSubListByQuery,
  15. updateCoeAdjust:updateCoeAdjust,
  16. getUnitPriceData:getUnitPriceData,
  17. };
  18. let mongoose = require('mongoose');
  19. const SearchDao = require('../../complementary_ration_lib/models/searchModel');
  20. const GLJListModel = require("../../glj/models/glj_list_model");
  21. const {
  22. getProjectGLJNewData,
  23. setIDfromCounter
  24. } = require('../facade/common_facade');
  25. const e = require('express');
  26. const scMathUtil = require('../../../public/scMathUtil').getUtil();
  27. let gljUtil = require('../../../public/gljUtil');
  28. let ration_glj_facade = require("../../ration_glj/facade/ration_glj_facade");
  29. let glj_calculate_facade = require("../../ration_glj/facade/glj_calculate_facade");
  30. let quantity_detail = require("../facade/quantity_detail_facade");
  31. let ration_glj = mongoose.model('ration_glj');
  32. let ration_coe = mongoose.model('ration_coe');
  33. let ration_model = require('../models/ration');
  34. let bill_model = require('../models/bills');
  35. let decimal_facade = require('./decimal_facade');
  36. let divide_facade = require('./divide_facade');
  37. let installationFeeModel = mongoose.model("installation_fee");
  38. let rationInstallationModel = mongoose.model('ration_installation');
  39. let rationTemplateModel = mongoose.model('ration_template');
  40. const uuidV1 = require('uuid/v1');
  41. let std_glj_lib_gljList_model = mongoose.model('std_glj_lib_gljList');
  42. let complementary_glj_model = mongoose.model('complementary_glj_lib');
  43. let rationItemModel = mongoose.model("std_ration_lib_ration_items");
  44. let complementaryRationModel = mongoose.model('complementary_ration_items');
  45. let freightCalcModel = mongoose.model('freight_calc');
  46. let originaltCalcModel = mongoose.model('original_calc');
  47. let coeMolde = mongoose.model('std_ration_lib_coe_list');
  48. let compleCoeModel = mongoose.model('complementary_ration_coe_list');
  49. let projectGLJModel = mongoose.model("glj_list");
  50. let mixRatioModel = mongoose.model("mix_ratio");
  51. let complementaryGljLibModel = mongoose.model('complementary_glj_lib');
  52. let _= require('lodash');
  53. const projectDao = require('../../pm/models/project_model').project;
  54. let projectModel = mongoose.model('projects');
  55. let unitPriceModel = mongoose.model('unit_price');
  56. let unitPriceFileModel = mongoose.model('unit_price_file');
  57. let vvTaxModel = mongoose.model("std_vehicleVesselTax_items");
  58. let divideModel = mongoose.model("divide_setting");
  59. const fs = require('fs');
  60. async function addNewRation(data,compilation) {
  61. let query = data.itemQuery;
  62. let stdRation = null;
  63. let startTime = +new Date();
  64. if(query){
  65. let searchDao = new SearchDao();
  66. stdRation = await searchDao.getRationItem(query.userID, compilation._id, [query.rationRepId],query.code, query.ID);
  67. //data.newData.code = query.code;
  68. }
  69. let stdRationTime = +new Date();
  70. console.log("取std定额时间-------------------------------"+(stdRationTime - startTime));
  71. if(data.brUpdate.length>0){
  72. await updateSerialNo(data.brUpdate);
  73. }
  74. let newRation =await insertNewRation(data.newData,data.defaultLibID,stdRation,data.calQuantity);
  75. let addRationGLJTime = +new Date();
  76. console.log("插入新定额时间-------------------------------"+(addRationGLJTime - stdRationTime));
  77. if(stdRation){
  78. return await addRationSubList(stdRation,newRation,data.needInstall,compilation);
  79. }else {
  80. return {ration:newRation};
  81. }
  82. }
  83. async function updateMaterialRation(data,compilation){
  84. let result = {};
  85. switch (data.actionType){
  86. case "add":
  87. result = await addMaterialRation(data,compilation);
  88. break;
  89. case "delete":
  90. result = await deleteMaterialRation(data);
  91. case "update":
  92. result = await modifyMaterialRation(data,compilation);
  93. }
  94. return result;
  95. }
  96. async function updateDivideRation(data,compilation){
  97. let result = {};
  98. switch (data.type){
  99. case "add":
  100. result = await addDivideRation(data,compilation);
  101. break;
  102. case "update":
  103. result = await modifyDivideRation(data,compilation);
  104. break;
  105. }
  106. return result;
  107. }
  108. async function deleteMaterialRation(data) {
  109. let model = data.type == "freight"?freightCalcModel:originaltCalcModel;
  110. await model.update(
  111. {ID:data.parentID},
  112. { $pull: { rations: { ID: data.rationID},ration_gljs:{rationID:data.rationID} } },
  113. { multi: true }
  114. );
  115. return data;
  116. }
  117. async function modifyMaterialRation(data,compilation) {
  118. let model = data.type == "freight"?freightCalcModel:originaltCalcModel;
  119. if(data.field == "code"){
  120. let [newRation,ration_gljs,projectGLJList] = await getNewMaterialRationDatas(data,compilation);
  121. let quantity = data.rations[data.row].quantity;
  122. newRation.quantity = quantity;
  123. data.rations[data.row] = newRation;
  124. _.remove(data.ration_gljs,{rationID:data.rationID});
  125. data.ration_gljs = data.ration_gljs.concat(ration_gljs);
  126. await model.update({'ID':data.parentID},{rations:data.rations,ration_gljs:data.ration_gljs});
  127. return {ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList}
  128. }else {
  129. let doc = {},pre = "rations.$.";
  130. let field = pre+data.field;
  131. doc[field] = data.value;
  132. if(data.ext){
  133. for(let key in data.ext){
  134. doc[pre+key] = data.ext[key];
  135. }
  136. }
  137. if(data.ration_gljs){
  138. let tasks = [];
  139. for(let g of data.ration_gljs){
  140. tasks.push({updateOne: {filter: {'ID':data.parentID,'ration_gljs.ID':g.ID}, update: {"ration_gljs.$.quantity":g.quantity}}})
  141. }
  142. await model.bulkWrite(tasks);
  143. }
  144. return await model.update({'ID':data.parentID,'rations.ID':data.rationID},doc);
  145. }
  146. }
  147. async function addMaterialRation(data,compilation) {
  148. let [newRation,ration_gljs,projectGLJList] = await getNewMaterialRationDatas(data,compilation);
  149. let model = data.type == "freight"?freightCalcModel:originaltCalcModel;
  150. await model.update({ID:data.parentID},{$push:{rations:newRation,ration_gljs:{$each:ration_gljs}}});
  151. return{ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList};
  152. }
  153. async function addDivideRation(data,compilation){
  154. let [newRation,ration_gljs,projectGLJList,ration_coes] = await getNewMaterialRationDatas(data,compilation,true);
  155. delete newRation.projectID;
  156. newRation.type=1;
  157. newRation.ParentID = data.ParentID;
  158. newRation.itemType = "定额";
  159. newRation.programID = data.programID;
  160. newRation.seq = data.seq;
  161. await divideModel.update({ID:data.divideID},{$push:{divideList:newRation,ration_gljs:{$each:ration_gljs},ration_coes:{$each:ration_coes}}});
  162. if(data.divideDatas.length > 0)await divide_facade.updateItem({ID:data.divideID,updateDatas:data.divideDatas});
  163. return{ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList,ration_coes};
  164. }
  165. async function modifyDivideRation(data,compilation){//目前只有替换分摊的定额走这个逻辑
  166. let [newRation,ration_gljs,projectGLJList,ration_coes] = await getNewMaterialRationDatas(data,compilation,true);
  167. newRation.quantity = data.oldData.quantity;
  168. newRation.type=1;
  169. newRation.itemType = "定额";
  170. if(data.oldData.programID && data.oldData.programID!="")newRation.programID = data.oldData.programID;
  171. newRation.seq = data.oldData.seq;
  172. newRation.ParentID = data.oldData.ParentID;
  173. await divideModel.update({ID:data.ID},{$push:{divideList:newRation,ration_gljs:{$each:ration_gljs},ration_coes:{$each:ration_coes}}});
  174. await divideModel.update(
  175. {ID:data.ID},
  176. {
  177. $pull: {divideList:{ID:data.rationID},ration_gljs:{rationID:data.rationID},ration_coes:{rationID:data.rationID}}
  178. },
  179. { multi: true })
  180. return {ration:newRation,ration_gljs:ration_gljs,projectGLJList:projectGLJList,ration_coes}
  181. }
  182. async function getNewMaterialRationDatas(data,compilation,withCoe = false){
  183. let searchDao = new SearchDao();
  184. let stdRation = await searchDao.getRationItem(data.userID, compilation._id, data.rationRepIds,data.code);
  185. if(!stdRation) throw "找不到指定的定额!";//new Error("找不到指定的定额!");
  186. let newRation = await createNewMaterialRation(stdRation,data.quantityDecimal,data.projectID);
  187. let [ration_gljs,projectGLJList] = await addRationGLJ(stdRation,newRation,compilation,true,data.connect_key);
  188. let result = [newRation,ration_gljs,projectGLJList]
  189. if(withCoe == true){
  190. let ration_coes = await addRationCoe(stdRation,newRation,compilation,true);
  191. result.push(ration_coes);
  192. }
  193. return result;
  194. }
  195. async function createNewMaterialRation(std,quantityDecimal,projectID){
  196. let newData = {};
  197. newData.ID = uuidV1();
  198. newData.projectID = projectID;
  199. newData.code = std.code;
  200. newData.name = std.name;
  201. newData.caption = std.caption;
  202. newData.unit = std.unit;
  203. newData.libID = std.rationRepId;
  204. newData.stdID = std.ID;
  205. newData.quantity=scMathUtil.roundForObj(1 / FilterNumberFromUnit(std.unit),quantityDecimal);
  206. newData.from = std.type === 'complementary' ? 'cpt' : 'std';
  207. newData.rationAssList =await createRationAss(std,true);
  208. if(std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
  209. newData.programID = await getProgramForProject(projectID);
  210. }else {
  211. newData.programID = std.feeType;
  212. }
  213. return newData;
  214. }
  215. async function addMultiRation(datas,compilation) {
  216. /* let rst = [];
  217. for(let data of datas){
  218. let r = await addNewRation(data,compilation);
  219. rst.push(r);
  220. }
  221. return rst; */
  222. const task = [];
  223. for (const data of datas) {
  224. task.push(addNewRation(data, compilation));
  225. }
  226. return await Promise.all(task);
  227. }
  228. async function getSameSectionRations(data,userId,compilationId){
  229. //let userId
  230. //要先根据定额获取所属章节的ID
  231. let from = data.from; //定额类型,是标准的还是用户定义的
  232. let code = data.code;
  233. let libID = data.libID;
  234. let sectionId,rations=[];
  235. if(from == 'std'){
  236. let ration = await rationItemModel.findOne({rationRepId:libID,code:code},['sectionId']);
  237. sectionId = ration? ration.sectionId:null;
  238. }else {
  239. let ration = await complementaryRationModel.findOne({userId:userId,compilationId: compilationId,code:code},['sectionId']);
  240. sectionId = ration?ration.sectionId:null;
  241. }
  242. if(sectionId){
  243. if (from == 'std') {
  244. rations = await rationItemModel.find({sectionId: sectionId});
  245. } else {
  246. rations = await complementaryRationModel.find({userId: userId, sectionId: sectionId});
  247. }
  248. rations = _.sortBy(rations,'code');
  249. }
  250. return rations
  251. }
  252. async function updateSerialNo(serialNoUpdate){
  253. let tasks=[];
  254. for(let data of serialNoUpdate){
  255. let task={
  256. updateOne:{
  257. filter:{
  258. ID:data.ID,
  259. projectID:data.projectID
  260. },
  261. update :{
  262. serialNo:data.serialNo
  263. }
  264. }
  265. };
  266. tasks.push(task);
  267. }
  268. await ration_model.model.bulkWrite(tasks);
  269. }
  270. async function insertNewRation(newData,defaultLibID,std,calQuantity) {//插入新的定额
  271. let startTime = +new Date();
  272. if(std){
  273. newData.code = std.code;
  274. newData.name = std.name;
  275. newData.caption = std.caption;
  276. newData.unit = std.unit;
  277. newData.libID = std.rationRepId;
  278. newData.stdID = std.ID;
  279. newData.content = std.jobContent;
  280. newData.annotation = std.annotation;
  281. if (std.chapter) {
  282. newData.comments = std.chapter.explanation;
  283. newData.ruleText = std.chapter.ruleText;
  284. }
  285. newData.prefix = '';
  286. newData.from = std.type === 'complementary' ? 'cpt' : 'std';
  287. if(newData.from === 'std' && defaultLibID !== std.rationRepId){//借
  288. newData.prefix = '借';
  289. } else if(newData.from === 'cpt') {
  290. newData.prefix = '补';
  291. }
  292. if(std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
  293. newData.programID = await getProgramForProject(newData.projectID);
  294. }else {
  295. newData.programID = std.feeType;
  296. }
  297. newData.rationAssList =await createRationAss(std);
  298. // calculate ration Quantity
  299. }
  300. if(calQuantity){
  301. await CalculateQuantity(newData,newData.billsItemID,newData.projectID);
  302. }
  303. let addRationGLJTime = +new Date();
  304. console.log("计算消耗量时间-------------------------------"+(addRationGLJTime - startTime));
  305. await ration_model.model.insertMany([newData]);
  306. return newData;
  307. /*ration_model.model.create(newData);
  308. return newData;*/
  309. }
  310. async function replaceRations(userID,data,compilation) {
  311. let searchDao = new SearchDao();
  312. let recodes = [];
  313. for(let recode of data.nodeInfo){
  314. let stdRation = await searchDao.getRationItem(userID,compilation._id,data.libIDs,recode.newCode, null);
  315. let newRecode = await replaceRation(recode,stdRation,data.defaultLibID,data.projectID,data.calQuantity,compilation,data.cleanzmhs);
  316. if(newRecode){
  317. recodes.push(newRecode);
  318. }else {
  319. break;
  320. }
  321. }
  322. return recodes;
  323. }
  324. async function getDefaultProgramID(data) {
  325. let searchDao = new SearchDao();
  326. let programID;
  327. let std = await searchDao.getRationItem(data.userID,data.compilationId,[data.libID],data.code, null);
  328. if(std == null||std ==undefined || std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
  329. programID = await getProgramForProject(data.projectID);
  330. }else {
  331. programID = std.feeType;
  332. }
  333. return programID;
  334. }
  335. async function replaceRation(nodeInfo,stdRation,defaultLibID,projectID,calQuantity,compilation,cleanzmhs) {
  336. if(nodeInfo.newCode == null||nodeInfo.newCode ==""){//说明是删除编号,则要变成一条空定额
  337. await deleRationSubRecode(projectID,nodeInfo.ID);//删除定额下挂的各种数据,如定额工料机等
  338. return await setEmptyRation(projectID,nodeInfo.ID);
  339. }else if(stdRation){
  340. await deleRationSubRecode(projectID,nodeInfo.ID,cleanzmhs);//删除定额下挂的各种数据,如定额工料机等
  341. let newRation = await updateRation(stdRation,defaultLibID,nodeInfo.ID,nodeInfo.billsItemID,projectID,calQuantity,cleanzmhs);//生成并插入新的定额
  342. return await addRationSubList(stdRation,newRation,nodeInfo.needInstall,compilation,cleanzmhs);
  343. }else {
  344. return null;
  345. }
  346. }
  347. async function addRationSubList(stdRation,newRation,needInstall,compilation,cleanzmhs=false) {
  348. let startTime = +new Date();
  349. let [ration_gljs,projectGLJList] = await addRationGLJ(stdRation,newRation,compilation);
  350. let addRationGLJTime = +new Date();
  351. console.log("添加定额工料机时间-----"+(addRationGLJTime - startTime));
  352. let ration_coes = await addRationCoe(stdRation,newRation,compilation);
  353. let addRationCoeTime = +new Date();
  354. console.log("添加定额coe时间-----"+(addRationCoeTime - addRationGLJTime));
  355. let ration_installations = [];
  356. let ration_template = [];
  357. if(cleanzmhs == false){//清除子目换算即cleanzmh==true时 模板子目、安装增加费不用恢复成标准的
  358. if(needInstall && stdRation.type == 'std'){//只有标准的定额才有安装增加费,补充的定额没有安装增加费
  359. ration_installations = await addRationInstallFee(stdRation,newRation);
  360. }
  361. let addRationInstallFeeTime = +new Date();
  362. console.log("添加定额install时间-----"+(addRationInstallFeeTime - addRationCoeTime));
  363. //添加定额模板子目
  364. ration_template = await addRationTemplate(stdRation,newRation);
  365. }
  366. return {ration:newRation,ration_gljs:ration_gljs,ration_coes:ration_coes,ration_installations:ration_installations,ration_templates:ration_template?[ration_template]:[],projectGLJList:projectGLJList};
  367. }
  368. async function addRationInstallFee(std,newRation) {
  369. let install_fee_list = [];
  370. if(std.hasOwnProperty('rationInstList') && std.rationInstList.length > 0){
  371. let installFee = await installationFeeModel.findOne({'projectID': newRation.projectID});
  372. if(!installFee) return;//如果没有找到项目对应的安装增加费,则不添加
  373. for(let ri of std.rationInstList){
  374. let feeItem = _.find(installFee.installFeeItem,{'ID':ri.feeItemId});
  375. let section = _.find(installFee.installSection,{'ID':ri.sectionId});
  376. if(feeItem&&section){
  377. let tem_r_i = {
  378. libID:installFee.libID,
  379. projectID:newRation.projectID,
  380. rationID:newRation.ID,
  381. feeItemId:feeItem.ID,
  382. sectionId:section.ID,
  383. itemName:feeItem.feeItem,
  384. feeType:feeItem.feeType,
  385. sectionName:section.name,
  386. unifiedSetting:1,
  387. ruleId:''
  388. };
  389. if(feeItem.isCal==1&&section.feeRuleId&&section.feeRuleId!=''){//勾选记取时并且有规则ID时才读取
  390. let feeRule = _.find(installFee.feeRule,{'ID':section.feeRuleId});
  391. if(feeRule){
  392. tem_r_i.ruleId = feeRule.ID;
  393. }
  394. }
  395. tem_r_i.ID = uuidV1();
  396. install_fee_list.push(tem_r_i);
  397. }
  398. }
  399. if(install_fee_list.length>0){
  400. await rationInstallationModel.insertMany(install_fee_list);
  401. }
  402. }
  403. return install_fee_list;
  404. }
  405. async function addRationTemplate(std,newRation) {
  406. let templateList = [];
  407. if(std.hasOwnProperty('rationTemplateList') && std.rationTemplateList.length > 0){
  408. for(let tem of std.rationTemplateList){
  409. let re_ration = await rationItemModel.findOne({rationRepId:std.rationRepId,ID:tem.rationID});
  410. if(re_ration){
  411. let template = {
  412. billID:"",
  413. fxID:"",
  414. quantity:"0",
  415. coe:"0"
  416. };
  417. template.code = re_ration.code;
  418. template.name = re_ration.name;
  419. template.type = tem.type;
  420. template.unit = re_ration.unit;
  421. template.billsLocation = tem.billsLocation;
  422. template.defaultLocation = tem.billsLocation;
  423. templateList.push(template)
  424. }
  425. }
  426. }
  427. if(templateList.length > 0){
  428. let ration_template = {};
  429. ration_template.ID = uuidV1();
  430. ration_template.projectID = newRation.projectID;
  431. ration_template.rationID = newRation.ID;
  432. ration_template.createLocation = 1; //默认模板子目分别放在措施项目下
  433. ration_template.templateList = templateList;
  434. await rationTemplateModel.create(ration_template);
  435. return ration_template;
  436. }
  437. return null;
  438. }
  439. async function addRationCoe(std,newRation,compilation,notInsert = false) {
  440. let ration_coe_list = [];
  441. let seq = 0;
  442. if(std.hasOwnProperty('rationCoeList')&&std.rationCoeList.length>0){//添加标准库的工料机
  443. for(let sub of std.rationCoeList){
  444. let libCoe;
  445. if (std.type === 'std') {
  446. libCoe = await coeMolde.findOne({'libID':std.rationRepId,'ID':sub.ID,"$or": [{"isDeleted": null}, {"isDeleted": false}]});//std.rationRepId;
  447. } else {
  448. libCoe = await compleCoeModel.findOne({ID: sub.ID, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  449. }
  450. if(libCoe){
  451. let newCoe = {};
  452. newCoe.ID = uuidV1();
  453. newCoe.coeID = sub.ID;
  454. newCoe.seq = seq;
  455. newCoe.name = libCoe.name;
  456. newCoe.content = libCoe.content;
  457. newCoe.original_code = libCoe.original_code;
  458. newCoe.option_codes = libCoe.option_codes;
  459. newCoe.option_list = libCoe.option_list;
  460. newCoe.isAdjust=0;
  461. newCoe.coes = libCoe.coes;
  462. newCoe.rationID = newRation.ID;
  463. newCoe.projectID = newRation.projectID;
  464. seq++;
  465. ration_coe_list.push(newCoe);
  466. }
  467. }
  468. }
  469. let lastCoe = await getCustomerCoe(newRation.projectID,newRation.ID,seq,compilation);
  470. ration_coe_list.push(lastCoe);
  471. if(notInsert!=true) await ration_coe.insertMany(ration_coe_list);//分摊下的时候不保存在这里
  472. return ration_coe_list;
  473. }
  474. function getCustomerCoeData() {
  475. var coeList = [
  476. {amount:1, operator:'*', gljCode:null, coeType:'定额'},
  477. { amount:1, operator:'*', gljCode:null, coeType:'人工'},
  478. { amount:1, operator:'*', gljCode:null, coeType:'材料'},
  479. { amount:1, operator:'*', gljCode:null, coeType:'机械'},
  480. /* { amount:1, operator:'*', gljCode:null, coeType:'主材'},*/
  481. { amount:1, operator:'*', gljCode:null, coeType:'设备'}
  482. ];
  483. return coeList;
  484. };
  485. async function getCustomerCoe(projectID,rationID,seq,compilation){//取自定义乘系数,根据编办不同,内容可能不同
  486. //生成默认的自定义乘系数
  487. let lastCoe ={
  488. coeID:-1,
  489. name : '自定义系数',
  490. content:'人工×1,材料×1,机械×1,设备×1',//主材×1,
  491. isAdjust:1,
  492. seq:seq,
  493. rationID : rationID,
  494. projectID : projectID
  495. };
  496. lastCoe.ID = uuidV1();
  497. lastCoe.coes = getCustomerCoeData();
  498. try {
  499. //查看编办中有没有重写路径 -- 养护中暂时没用到
  500. /* if(compilation.overWriteUrl && compilation.overWriteUrl!=""){
  501. let overWrite = require("../../.."+compilation.overWriteUrl);
  502. if(overWrite.getCusCoeContent) lastCoe.content = overWrite.getCusCoeContent();
  503. if(overWrite.getCustomerCoeData) lastCoe.coes = overWrite.getCustomerCoeData();
  504. } */
  505. return lastCoe
  506. }catch (err){
  507. console.log("读取自定义系数重写文件失败");
  508. console.log(err.message);
  509. return lastCoe
  510. }
  511. }
  512. //对于多单价,多组成物消耗量的编办,通过这个方法获取单价、组成物消耗量的字段,
  513. function getExtendData(property,compilation) {
  514. return projectDao.getExtendData(property,compilation);
  515. }
  516. async function addRationGLJ(std,newRation,compilation,isMaterial,connect_key) {
  517. let newRationGLJList = [];
  518. let rationGLJShowList = [];
  519. let projectGLJList = [];
  520. let gljKeyMap = {};
  521. let mixRatioMap={};
  522. let gljCodes=[];
  523. let unitPriceFileId = 0;
  524. let property = await projectDao.getProjectProperty(newRation.projectID);
  525. if(property){
  526. unitPriceFileId = property.unitPriceFile !== undefined ? property.unitPriceFile.id : 0;
  527. }
  528. let ext = getExtendData(property,compilation);
  529. let first = +new Date();
  530. if(std.hasOwnProperty('rationGljList') && std.rationGljList.length > 0){
  531. let stdGLJID =[];//标准工料机ID数组
  532. let cptGLJID=[];//补充工料机ID数组
  533. //let stdGLJID = _.map(std.rationGljList,'gljId');
  534. for(let tem_g of std.rationGljList){
  535. if(tem_g.type == 'complementary'){
  536. cptGLJID.push(tem_g.gljId);
  537. }else {
  538. stdGLJID.push(tem_g.gljId);
  539. }
  540. }
  541. let stdGLJList = stdGLJID.length > 0 ? await std_glj_lib_gljList_model.find({'ID':{'$in':stdGLJID}}).lean():[];//速度优化-------先一次性取出所有的工料机列表
  542. let stdGLJMap = _.indexBy(stdGLJList, 'ID');
  543. let cptGLJList = cptGLJID.length > 0 ? await complementary_glj_model.find({'userId':std.userId,'ID':{'$in':cptGLJID}}).lean():[];
  544. let cptGLJMap = _.indexBy(cptGLJList, 'ID');
  545. let stdGLJMapTime = +new Date();
  546. console.log("找到工料机映射表时间-------------------------------"+(stdGLJMapTime - first));
  547. if(isMaterial == true){//材料计算添加时要先检查
  548. for(let sub of std.rationGljList){
  549. let t_g = getStdGlj(sub,stdGLJMap,cptGLJMap,{},ext);
  550. if(t_g && connect_key == gljUtil.getIndex(t_g,['code','name','specs','unit','gljType'])) throw `本定额中包含工料机[${t_g.code}]${t_g.name},与当前工料机编号相同,添加定额失败!`;
  551. }
  552. }
  553. for(let sub of std.rationGljList){
  554. let newGLJ = {};
  555. let proportion = sub.proportion || 0;
  556. newGLJ.ID = uuidV1();
  557. newGLJ.projectID = newRation.projectID;
  558. newGLJ.GLJID = sub.gljId;
  559. newGLJ.rationID = newRation.ID;
  560. newGLJ.billsItemID = newRation.billsItemID;
  561. newGLJ.rationItemQuantity = sub.consumeAmt;
  562. newGLJ.quantity = sub.consumeAmt;
  563. newGLJ.glj_repository_id = std.rationRepId;
  564. newGLJ.rationProportion = proportion;
  565. newGLJ.adjustProportion = proportion;
  566. let std_glj = getStdGlj(sub,stdGLJMap,cptGLJMap,{},ext);
  567. if(std_glj){
  568. ration_glj_facade.setPropertyFromStd(newGLJ,std_glj);
  569. let tindex = getIndex(newGLJ);
  570. if(std_glj.component && std_glj.component.length > 0) mixRatioMap[tindex] = std_glj.component
  571. let tdata = ration_glj_facade.getGLJSearchInfo(newGLJ);
  572. gljKeyMap[tindex] = tdata;
  573. gljCodes.push(tdata.code);
  574. newRationGLJList.push(newGLJ);
  575. }
  576. }
  577. [newRationGLJList, projectGLJList] = await getProjectGLJinfo(newRation.projectID,newRationGLJList,gljKeyMap,gljCodes,mixRatioMap,unitPriceFileId,ext);
  578. let InfoFromProjectGLJ = +new Date();
  579. console.log("找到项目工料机时间-------------------------------"+(InfoFromProjectGLJ - stdGLJMapTime));
  580. }
  581. if(isMaterial == true) return [newRationGLJList,projectGLJList];//如果是材料计算的工料机,这里返回就可以了
  582. if(newRationGLJList.length>0){
  583. await ration_glj.insertMany(newRationGLJList);
  584. }
  585. let after = +new Date();
  586. console.log("总操作时间为-------------------------------"+(after-first));
  587. return [newRationGLJList,projectGLJList];
  588. }
  589. async function getProjectGLJinfo(projectID,t_newRationGLJList,gljKeyMap,gljCodes,mixRatioMap,unitPriceFileId,ext){//批量插入或查找项目工料机信息
  590. //先根据工料机编号在项目工料机中查找工料机是否存在
  591. let projectGLJMap={};
  592. let projectGLJList = [];
  593. let newProjectGLJList=[];//工料机ID要重新去取
  594. let connectKeyList = [];
  595. let CCSMap = {keyMap:{},codes:[]};//需要添加车船税的机械台班
  596. let newRationGLJList=[];
  597. let gljListModel = new GLJListModel();
  598. let t_projectGLJList = await projectGLJModel.find({'project_id':projectID,'code':{'$in':gljCodes}}).lean();
  599. for(let pg of t_projectGLJList){
  600. let pindex = getIndex(pg);
  601. projectGLJMap[pindex] = pg;
  602. }
  603. for(let key in gljKeyMap){
  604. if(!projectGLJMap[key]){//如果项目工料机不存在,则添加
  605. newProjectGLJList.push(gljKeyMap[key]);
  606. projectGLJMap[key] = gljKeyMap[key];
  607. if(gljKeyMap[key].type == 301){//如果是机械台班,需看看有没有车船税
  608. CCSMap.keyMap[key] = true;
  609. CCSMap.codes.push(gljKeyMap[key].code);
  610. }
  611. }
  612. //查看组成物
  613. if(gljListModel.ownCompositionTypes.indexOf(gljKeyMap[key].type)!=-1){//有组成物的类型
  614. connectKeyList.push(key);
  615. }
  616. }
  617. let [existMixRatioMap,mixRatioInsertData,missCodeList] = await getMixRatioInfo(projectID,projectGLJMap,newProjectGLJList,mixRatioMap,connectKeyList,unitPriceFileId,CCSMap,ext);
  618. if(missCodeList.length > 0) gljCodes = gljCodes.concat(missCodeList);
  619. //处理车般税相关,车船税是添加项目时,项目工料机,和单价文件里自动添加的 --- todo
  620. let [unitPriceMap,newUnitPriceList] = await getUnitPriceData(newProjectGLJList,gljCodes,unitPriceFileId);
  621. if(mixRatioInsertData.length > 0) await mixRatioModel.insertMany(mixRatioInsertData);
  622. //插入项目工料机
  623. if(newProjectGLJList.length > 0){
  624. await setIDfromCounter("glj_list",newProjectGLJList);
  625. await projectGLJModel.insertMany(newProjectGLJList);
  626. }
  627. //组装数据
  628. for(let ration_glj of t_newRationGLJList){
  629. let rkey = getIndex(ration_glj);
  630. let pglj = projectGLJMap[rkey];
  631. let subList = [];
  632. setUnitPrice(pglj,unitPriceMap);
  633. if(existMixRatioMap[rkey]){//如果有组成物
  634. for(let m of existMixRatioMap[rkey]){
  635. let mpglj = projectGLJMap[getIndex(m)]
  636. if(mpglj){
  637. let cglj = _.clone(mpglj);
  638. setUnitPrice(cglj,unitPriceMap);
  639. cglj.ratio_data = m;
  640. subList.push(cglj);
  641. }else{
  642. throw `组成物${m.name}对应的项目工料机没有找到`;
  643. }
  644. }
  645. pglj.subList =subList;
  646. }
  647. ration_glj.projectGLJID = pglj.id;
  648. newRationGLJList.push(ration_glj_facade.createNewRecord(ration_glj));
  649. projectGLJList.push(pglj);
  650. }
  651. return [newRationGLJList, projectGLJList];
  652. function setUnitPrice(p,unitPriceMap){
  653. p.unit_price = unitPriceMap[getIndex(p)];
  654. }
  655. }
  656. //找到并返回单价文件信息,如果没有自动插入
  657. async function getUnitPriceData(newProjectGLJList,gljCodes,unitPriceFileId){
  658. let unitPriceMap = {};
  659. let newUnitPriceList = [];
  660. let unitPriceList = await unitPriceModel.find({unit_price_file_id: unitPriceFileId,'code':{'$in':gljCodes}}).lean();
  661. for(let u of unitPriceList){
  662. unitPriceMap[getIndex(u)]=u;
  663. }
  664. for(let np of newProjectGLJList){
  665. let pkey = getIndex(np);
  666. if(unitPriceMap[pkey]) continue;
  667. let insertData = {
  668. code: np.code,
  669. base_price: np.base_price,
  670. market_price: np.market_price,
  671. unit_price_file_id: unitPriceFileId,
  672. name: np.name,
  673. specs:np.specs?np.specs:'',
  674. original_code:np.original_code,
  675. unit:np.unit?np.unit:'',
  676. type: np.type,
  677. short_name: np.shortName !== undefined ? np.shortName : '',
  678. glj_id: np.glj_id,
  679. is_add:0,
  680. grossWeightCoe:np.grossWeightCoe,
  681. purchaseStorageRate:np.purchaseStorageRate,
  682. offSiteTransportLossRate:np.offSiteTransportLossRate,
  683. handlingLossRate:np.handlingLossRate
  684. };
  685. if(np.from=='cpt') insertData.is_add=1;//如果是来自补充工料机,则都添加新增标记
  686. if(insertData.code != insertData.original_code) insertData.is_add=1;//添加的时候如果是复制整块来的,可能在源项目中是新增的工料机,这里也要添上(暂时可能还用不到)
  687. newUnitPriceList.push(insertData);
  688. unitPriceMap[pkey] = insertData;
  689. }
  690. if(newUnitPriceList.length > 0){
  691. await setIDfromCounter("unit_price",newUnitPriceList);
  692. await unitPriceModel.insertMany(newUnitPriceList);
  693. }
  694. return [unitPriceMap,newUnitPriceList];
  695. }
  696. async function getMixRatioInfo(projectID,projectGLJMap,newProjectGLJList,mixRatioMap,connectKeyList,unitPriceFileId,CCSMap,ext){//取组成物信息,得到缺少的组成物情况
  697. let missCodeList = []; //所有组成物信息的编码,用来统一查询对应的项目工料机是否存在
  698. let existMixRatioMap ={};
  699. let codeMap={};//用来去重
  700. let mixRatioInsertData = [];
  701. // 1. 先检查现在的组成物表中,是否有相关信息 - 生成映射记录
  702. if(connectKeyList.length > 0){//有组成物的话从数据库中取出组成物信息
  703. let mixRatioList = await mixRatioModel.find({'unit_price_file_id': unitPriceFileId,'connect_key': {'$in':connectKeyList}}).lean();
  704. for(let m of mixRatioList){
  705. //组成物信息分组,查看哪些是已经存在的
  706. existMixRatioMap[m.connect_key]?existMixRatioMap[m.connect_key].push(m):existMixRatioMap[m.connect_key]=[m];
  707. //查看组成物对应的项目工料机是否存在,如果不存在,要插入项目工料机
  708. let mkey = getIndex(m);
  709. if(!projectGLJMap[mkey] && !codeMap[m.code]){//如果之前查出来的项目工料机中不包含组成物的信息,要加到missCode里面再查找一次项目工料机看是否存在
  710. missCodeList.push(m.code);
  711. codeMap[m.code] = true;
  712. }
  713. }
  714. // 2 将第一步得到的映射表 与在标准库查询父工料机得到的映射表对比,得出哪些组物成还需要添加,获得库ID
  715. let stdIDs = [];
  716. let comIDs = [];
  717. let missMixRatioGroup = [];
  718. for(let ck of connectKeyList){//查看项目中组成物信息是否已经存在,如果不存在,则用插定额时获取的组成物信息从数据库中获取
  719. if(!existMixRatioMap[ck] && mixRatioMap[ck] && mixRatioMap[ck].length > 0){//组成物信息不存在
  720. let pglj = projectGLJMap[ck];//取出父数据
  721. let from = pglj.from === undefined|| pglj.from ===null || pglj.from === ""?'std' : pglj.from;
  722. for(let c of mixRatioMap[ck]){
  723. if(from == "std"){//标准的工料机只来自标准的
  724. stdIDs.push(c.ID);
  725. }else{
  726. c.isStd?stdIDs.push(c.ID):comIDs.push(c.ID);
  727. }
  728. }
  729. missMixRatioGroup.push({'connect_key':ck,'list':mixRatioMap[ck],'from':from});
  730. }
  731. }
  732. //3.统一查询所有组成物在标准库中的详细信息
  733. let stdMixMap = {};
  734. //整理需插入的组成物列表的数据
  735. //来自标准工料机
  736. if(stdIDs.length > 0){
  737. stdIDs = _.uniq(stdIDs);//去重
  738. let stdMixList = await std_glj_lib_gljList_model.find({'ID':{'$in':stdIDs}}).lean();
  739. for(let sm of stdMixList){
  740. stdMixMap[sm.ID] = sm;
  741. let skey = getIndex(sm,['code','name','specs','unit','gljType']);
  742. if(!projectGLJMap[skey] && !codeMap[sm.code]){
  743. missCodeList.push(sm.code);
  744. codeMap[sm.code] = true;
  745. }
  746. }
  747. }
  748. //来自组成物工料机
  749. let comMixMap = {};
  750. if(comIDs.length > 0){
  751. comIDs = _.uniq(comIDs);//去重
  752. let comMixList = await complementaryGljLibModel.find({'ID':{'$in':comIDs}}).lean();
  753. for(let cm of comMixList){
  754. comMixMap[cm.ID] = cm;
  755. let ckey = getIndex(cm,['code','name','specs','unit','gljType']);
  756. if(!projectGLJMap[ckey] && codeMap[cm.code]){
  757. missCodeList.push(cm.code);
  758. codeMap[cm.code] = true;
  759. }
  760. }
  761. }
  762. //4.生成需要插入组成物表的数据
  763. for(let mg of missMixRatioGroup){//整理需要插入组成物列表的数据
  764. for(let tc of mg.list){
  765. let consumpiton = tc.consumeAmt;
  766. //只有标准的工料机的组成物才会有多单价、多组成物消耗量的情况
  767. if(mg.from == 'std' && ext && ext.quantityField &&( tc.consumeAmtProperty[ext.quantityField]!= undefined && tc.consumeAmtProperty[ext.quantityField]!=null)){
  768. consumpiton = tc.consumeAmtProperty[ext.quantityField];
  769. }
  770. let mfrom = mg.from == 'std' || tc.isStd?'std':'cpt';
  771. let tmp = mfrom == 'std'?stdMixMap[tc.ID]:comMixMap[tc.ID];//取出之前库中查到的工料机
  772. let mixRatioData = {
  773. consumption: consumpiton,
  774. glj_id: tmp.ID,
  775. unit_price_file_id: unitPriceFileId,
  776. connect_key: mg.connect_key,
  777. type: tmp.gljType,
  778. code: tmp.code,
  779. specs:tmp.specs?tmp.specs:"",
  780. name:tmp.name,
  781. unit:tmp.unit?tmp.unit:'',
  782. from:mfrom
  783. };
  784. mixRatioInsertData.push(mixRatioData);
  785. }
  786. }
  787. //4.5 处理车船税问题,查询机械台班是否需要添加车船税
  788. if(CCSMap.codes.length > 0){
  789. let unitFileInfo = await unitPriceFileModel.findOne({id:unitPriceFileId}).lean();
  790. if(unitFileInfo.vvTaxFileID && unitFileInfo.vvTaxFileID!=""){
  791. let needCCS = false;
  792. let items = await vvTaxModel.find({libID:unitFileInfo.vvTaxFileID,'code':{'$in':CCSMap.codes}}).lean();
  793. for(let i of items){
  794. let ikey = getIndex(i);
  795. if(CCSMap.keyMap[ikey]){
  796. needCCS = true;
  797. mixRatioInsertData.push(gljUtil.getBaseCCSMixRatio(unitPriceFileId,i.vehicleVesselTax,ikey))
  798. }
  799. }
  800. if(needCCS && !codeMap["80CCS"]) missCodeList.push("80CCS");
  801. }
  802. }
  803. if(mixRatioInsertData.length > 0) await setIDfromCounter("mix_ratio",mixRatioInsertData,existMixRatioMap,'connect_key');
  804. //await mixRatioModel.insertMany(mixRatioInsertData); 因为没有事务添加组成物数据要放在添加单价文件数据之后
  805. //5.查询组成物对应的项目工料机是否存在,如果不存在,生成项目工料机信息
  806. let projectGLJList = await projectGLJModel.find({'project_id':projectID,'code':{'$in':missCodeList}}).lean();
  807. for(let pg of projectGLJList){
  808. let pindex = getIndex(pg);
  809. projectGLJMap[pindex] = pg;
  810. }
  811. let lessMix = [];//组成物表存在,项目工料机不存在的数据
  812. let lessMixMap = {};//防止重复添加
  813. for(let connect_key in existMixRatioMap){
  814. let mixRatios = existMixRatioMap[connect_key];
  815. for(let m of mixRatios){
  816. let mk = getIndex(m);
  817. if(!projectGLJMap[mk] && !lessMixMap[mk]){//如果组成物对应的项目工料机不存在
  818. let nglj = null;
  819. if(m.from == 'std'){//这里有值,说明是刚添加到组成物文件中的数据
  820. nglj = stdMixMap[m.glj_id];
  821. }else if(m.from == 'cpt'){//这里有值,说明是刚添加到组成物文件中的数据
  822. nglj = comMixMap[m.glj_id];
  823. }
  824. if(nglj){
  825. nglj.from = m.from;
  826. let np = getProjectGLJNewData(nglj,projectID,ext);
  827. newProjectGLJList.push(np);
  828. projectGLJMap[mk] = np;
  829. }else{//这里没找到,说明是组成物文件里有,但是项目工料机没有的数据
  830. lessMix.push(m);
  831. }
  832. lessMixMap[mk] = true;//只要处理过一次,就不用再重新处理了,机械组成物,比如柴油这些,会出现多次
  833. }
  834. }
  835. }
  836. //6. 组成物文件里有,但是项目工料机没有的数据(共用单价文件等情况产生)
  837. let lessIDList=[];
  838. let uniqMap ={};//去重
  839. let lessStdMix = [];//防止组成物中改了名称等,但是通过glj_id取出来的是还没改前的原始数据
  840. if(lessMix.length > 0){
  841. for(let lm of lessMix){
  842. let parentglj = projectGLJMap[lm.connect_key];
  843. if(!parentglj) throw `含有组成物工料机${lm.connect_key},没有找到,添加定额失败`;
  844. if((parentglj.from == "std" || lm.from == "std") && lm.code!="80CCS"){//车船税特殊处理
  845. if(!uniqMap[lm.glj_id]){
  846. lessIDList.push(lm.glj_id);
  847. uniqMap[lm.glj_id] = lm;
  848. }
  849. lessStdMix.push(lm);
  850. }else {//来自组成物的直接设置
  851. lm.from = 'cpt';
  852. lm.gljType = lm.type;
  853. let t_mg = getProjectGLJNewData(lm,projectID);
  854. newProjectGLJList.push(t_mg);
  855. projectGLJMap[getIndex(lm)] = t_mg;
  856. }
  857. }
  858. }
  859. if(lessIDList.length > 0){
  860. let less_stds = await std_glj_lib_gljList_model.find({'ID':{'$in':lessIDList}}).lean();
  861. let less_stds_map = {};
  862. for(let les of less_stds){
  863. less_stds_map[les.ID] = les;
  864. }
  865. for(let t_l_m of lessStdMix){
  866. let t_nglj = less_stds_map[t_l_m.glj_id];
  867. t_nglj.from = 'std';
  868. //防止组成物中改了名称等,但是通过glj_id取出来的是还没改前的原始数据
  869. t_nglj.name = t_l_m.name;
  870. t_nglj.code = t_l_m.code;
  871. t_nglj.gljType = t_l_m.type;
  872. t_nglj.specs = t_l_m.specs;
  873. t_nglj.unit = t_l_m.unit;
  874. let t_np = getProjectGLJNewData(t_nglj,projectID,ext);
  875. newProjectGLJList.push(t_np);
  876. projectGLJMap[getIndex(t_l_m)] = t_np;
  877. }
  878. }
  879. }
  880. return [existMixRatioMap,mixRatioInsertData,missCodeList]
  881. }
  882. function getStdGlj(sub,stdGLJMap,cptGLJMap,newGLJ,ext) {
  883. let std_glj = null;
  884. if(sub.type == 'complementary'){//有可能来自标准工料机库或补充工料机库
  885. std_glj = cptGLJMap[sub.gljId];
  886. newGLJ.from = 'cpt';
  887. }else {
  888. std_glj = stdGLJMap[sub.gljId];
  889. newGLJ.from = 'std';
  890. //多单价情况处理
  891. if(ext && ext.priceField && std_glj && std_glj.priceProperty){
  892. std_glj.basePrice = std_glj.priceProperty[ext.priceField];
  893. }
  894. }
  895. return std_glj;
  896. }
  897. async function deleRationSubRecode(projectID,rationID,cleanzmhs=false) {//删除挂在定额下的数据,如工程量明细,定额工料机等
  898. let delete_query={projectID: projectID, rationID: rationID};
  899. //删除工程量明细
  900. await deleteSubListByQuery(delete_query,cleanzmhs) ;
  901. }
  902. async function deleteSubListByQuery(delete_query,cleanzmhs=false) {
  903. if(cleanzmhs == false){//清空子目换算即cleanzmh==true时不需要清空工程量明细、模板关联子目、安装增加费
  904. await quantity_detail.deleteByQuery(delete_query) ;//删除工程量明细
  905. await rationInstallationModel.deleteMany(delete_query);//删除安装增加费
  906. await rationTemplateModel.deleteMany(delete_query);//删除模板关联子目
  907. }
  908. //to do稳定土也要删除
  909. await ration_coe.deleteMany(delete_query);//删除附注条件
  910. await ration_glj.deleteMany(delete_query);//删除定额工料机
  911. }
  912. async function updateCoeAdjust(data,compilation) {
  913. let replace = [],projectGLJList=[];
  914. await ration_coe.update({ID:data.ID},data.doc);
  915. //添加单个工料机的情况
  916. if (data.add.length > 0){
  917. let [tg,pl] = await ration_glj_facade.insertAddTypeGLJ(data.add,compilation);
  918. if(pl.length > 0) projectGLJList = projectGLJList.concat(pl);
  919. }
  920. if(data.delete.length > 0) await ration_glj_facade.deleteGLJ(data.delete);
  921. //替换工料机的情况
  922. if (data.replace.length > 0){
  923. for(let r of data.replace){
  924. let r_result = await ration_glj_facade.replaceGLJByData(r,compilation);
  925. replace.push(r_result.data) ;
  926. projectGLJList.push(r_result.projectGLJ);
  927. if(r_result.newRecodes.length > 0) data.add = data.add.concat(r_result.newRecodes);
  928. if(r_result.deleteList.length > 0) data.delete = data.delete.concat(r_result.deleteList);
  929. }
  930. }
  931. let cal_result = await glj_calculate_facade.calculateQuantity({projectID:data.projectID,rationID:data.rationID},null,true);
  932. let coe = {
  933. query:{ID:data.ID,projectID:data.projectID},
  934. doc:data.doc
  935. };
  936. let ration_glj ={
  937. quantityRefresh:true,
  938. glj_result:cal_result.glj_result
  939. };
  940. let ration = {
  941. ID:cal_result.rationID,
  942. adjustState:cal_result.adjustState,
  943. name:cal_result.rationName
  944. };
  945. return {coe:coe,ration_glj:ration_glj,ration:ration,add:data.add,delete:data.delete,replace:replace,projectGLJList:projectGLJList}
  946. }
  947. async function updateRation(std,defaultLibID,rationID,billsItemID,projectID,calQuantity,cleanzmh=false) {
  948. // insertNewRation
  949. let ration ={};
  950. ration.code = std.code;
  951. ration.name = std.name;
  952. ration.caption = std.caption;
  953. ration.unit = std.unit;
  954. if (std.type === 'std') {
  955. ration.libID = std.rationRepId;
  956. ration.stdID = std.ID;
  957. }
  958. ration.content = std.jobContent;
  959. ration.adjustState = '';
  960. ration.isFromDetail=0;
  961. ration.isSubcontract=false;
  962. ration.fees=[];
  963. if (std.chapter) {
  964. ration.comments = std.chapter.explanation;
  965. ration.ruleText = std.chapter.ruleText;
  966. }
  967. ration.from = std.type === 'complementary' ? 'cpt' : 'std';
  968. //定额前缀 none:0, complementary:1, borrow: 2
  969. ration.prefix = '';
  970. //借用优先级比补充高
  971. if(ration.from === 'std' && std.rationRepId !== parseInt(defaultLibID)){//借用
  972. ration.prefix = '借';
  973. } else if(ration.from === 'cpt') {
  974. ration.prefix = '补';
  975. }
  976. ration.rationAssList =await createRationAss(std);//生成辅助定额
  977. if(cleanzmh==false){//如果是清空子目换算,即cleanzmh==true 保留定额工程量、工程量表达式、含量(分解系数)、取费专业(取费类别)
  978. if(std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
  979. ration.programID = await getProgramForProject(projectID);
  980. }else {
  981. ration.programID = std.feeType;
  982. }
  983. if( calQuantity){
  984. await CalculateQuantity(ration,billsItemID,projectID);
  985. }
  986. }
  987. let unsetObject = {
  988. "marketUnitFee":1,
  989. 'marketTotalFee':1,
  990. "maskName":1
  991. }
  992. let newRation = await ration_model.model.findOneAndUpdate({ID:rationID,projectID:projectID},{"$set":ration,"$unset":unsetObject},{new: true});//;
  993. return newRation;
  994. }
  995. async function setEmptyRation(projectID,rationID){
  996. let ration ={};
  997. ration.code = "";
  998. ration.name = "";
  999. ration.caption = "";
  1000. ration.unit = "";
  1001. ration.libID = null;
  1002. ration.content = "";
  1003. ration.adjustState = '';
  1004. ration.isFromDetail=0;
  1005. ration.isSubcontract=false;
  1006. ration.fees=[];
  1007. ration.comments = "";
  1008. ration.ruleText = "";
  1009. ration.quantity="";
  1010. ration.contain="";
  1011. ration.quantityEXP="";
  1012. ration.from = 'std';
  1013. //定额前缀 none:0, complementary:1, borrow: 2
  1014. ration.prefix = '';
  1015. ration.rationAssList = [];
  1016. ration.marketUnitFee ="";
  1017. ration.marketTotalFee ="";
  1018. ration.maskName = "";
  1019. ration.targetTotalFee ='';
  1020. ration.targetUnitFee = "";
  1021. ration.deleteInfo = null;
  1022. ration.quantityCoe = {};
  1023. ration.rationQuantityCoe="";
  1024. ration.tenderQuantity = "";
  1025. ration.programID = null;
  1026. let newRation = await ration_model.model.findOneAndUpdate({ID:rationID,projectID:projectID},{"$set":ration},{new: true});//;
  1027. return {ration:newRation,ration_gljs:[],ration_coes:[],ration_installs:[]};
  1028. }
  1029. async function createRationAss(std,isMaterial) {
  1030. let rationAssList = [];//生成辅助定额
  1031. if(std.hasOwnProperty('rationAssList')&&std.rationAssList.length>0){
  1032. let assGroup = _.groupBy(std.rationAssList,'name');
  1033. for(let key in assGroup){
  1034. let assList = assGroup[key];
  1035. let ass = assList[0];
  1036. ass._doc.actualValue = ass.stdValue;
  1037. ass._doc.isAdjust = 0;
  1038. if(_.isString(ass._doc.assistCode)) ass._doc.assistCode = ass._doc.assistCode.replace("\n","");
  1039. if(_.isString(ass._doc.thirdRationCode)) ass._doc.thirdRationCode = ass._doc.thirdRationCode.replace("\n","");
  1040. if(assList.length > 1){
  1041. ass._doc.groupList = JSON.parse(JSON.stringify(assList)) ;
  1042. ass._doc.maxValue = assList[assList.length-1]._doc.maxValue;
  1043. }
  1044. if(isMaterial == true){//材料计算进来的,直接保存辅助定额的信息 //常规的定额以后可以考虑也这样做
  1045. let t_assRation = await rationItemModel.findOne({rationRepId:std.rationRepId,code:ass.assistCode}).lean();
  1046. if(t_assRation) ass._doc.assRation = t_assRation;
  1047. }
  1048. rationAssList.push(ass);
  1049. }
  1050. }
  1051. return rationAssList;
  1052. }
  1053. async function CalculateQuantity (ration,billsItemID,projectID) {
  1054. // calculate ration Quantity
  1055. let project = await projectModel.findOne({ID:projectID});
  1056. let decimalObject =await decimal_facade.getProjectDecimal(projectID,project);
  1057. let quantity_decimal = (decimalObject&&decimalObject.ration&&decimalObject.ration.quantity)?decimalObject.ration.quantity:3;
  1058. let pbill = await bill_model.model.findOne({projectID:projectID,ID:billsItemID});
  1059. let rationTimes = 1 ;//清单单位转定额单位的倍数,如 kg 转 t 时是1000
  1060. let t_unit = ration.unit?ration.unit:"";
  1061. let b_unit = pbill.unit?pbill.unit:"";
  1062. ration.quantityEXP="QDL";
  1063. if((/.*kg$/i).test(b_unit)){
  1064. if((/t/i).test(t_unit)) {
  1065. rationTimes = 1000;//如 kg 转 t 时是1000
  1066. ration.quantityEXP="QDL*0.001"
  1067. }
  1068. if((/10t/i).test(t_unit)){
  1069. rationTimes = 10000;//如 kg 转 10t 时是1000
  1070. ration.quantityEXP="QDL*0.0001"
  1071. }
  1072. }
  1073. /* let t_unit = ration.unit?ration.unit.replace(/^\d+/,""):""; 2019-02-01 养护去掉清单与定额单位的这个判断
  1074. if(t_unit!=pbill.unit){//如果定额工程量的单位去除前面的数字后不等于清单单位,定额工程量保持不变
  1075. return ;
  1076. }*/
  1077. let billsQuantity = pbill.quantity ? pbill.quantity : 0;
  1078. let bill_decimal = await decimal_facade.getBillsQuantityDecimal(projectID,pbill.unit,project);
  1079. let ftimes = rationTimes == 1?FilterNumberFromUnit(ration.unit):rationTimes;
  1080. billsQuantity=scMathUtil.roundForObj(billsQuantity,bill_decimal);
  1081. ration.quantity = scMathUtil.roundForObj(billsQuantity / ftimes ,quantity_decimal);//不管是否打勾都做转换
  1082. ration.contain = scMathUtil.roundForObj(ration.quantity/billsQuantity,6);
  1083. };
  1084. async function getProgramForProject(projectID){
  1085. let project = await projectModel.findOne({ID:projectID});
  1086. return project.property.engineering;
  1087. }
  1088. function FilterNumberFromUnit (unit) {
  1089. let reg = new RegExp('^[0-9]+');
  1090. if (reg.test(unit)) {
  1091. return parseInt(unit.match(reg)[0]);
  1092. } else {
  1093. return 1;
  1094. }
  1095. };
  1096. function getIndex(obj,tpops){
  1097. let pops = tpops?tpops:['code','name','specs','unit','type'];
  1098. let t_index = '';
  1099. let k_arr=[];
  1100. for(let p of pops){
  1101. let tmpK = (obj[p]==undefined||obj[p]==null||obj[p]=='')?'null':obj[p];
  1102. k_arr.push(tmpK);
  1103. }
  1104. t_index=k_arr.join("|-|");
  1105. return t_index;
  1106. }