ration_facade.js 52 KB

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