ration_facade.js 45 KB

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