ration_facade.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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. const users = [std.userId];
  416. if(std.hasOwnProperty('rationGljList') && std.rationGljList.length > 0){
  417. let stdGLJID =[];//标准工料机ID数组
  418. let cptGLJID=[];//补充工料机ID数组
  419. //let stdGLJID = _.map(std.rationGljList,'gljId');
  420. for(let tem_g of std.rationGljList){
  421. if(tem_g.type == 'complementary'){
  422. if (tem_g.fromUser && !users.includes(tem_g.fromUser)) {
  423. users.push(tem_g.fromUser);
  424. }
  425. cptGLJID.push(tem_g.gljId);
  426. }else {
  427. stdGLJID.push(tem_g.gljId);
  428. }
  429. }
  430. let stdGLJList = stdGLJID.length > 0 ? await std_glj_lib_gljList_model.find({'ID':{'$in':stdGLJID}}):[];//速度优化-------先一次性取出所有的工料机列表
  431. let stdGLJMap = _.indexBy(stdGLJList, 'ID');
  432. let cptGLJList = cptGLJID.length > 0 ? await complementary_glj_model.find({'userId':{$in: users},'ID':{'$in':cptGLJID}}):[];
  433. let cptGLJMap = _.indexBy(cptGLJList, 'ID');
  434. let stdGLJMapTime = +new Date();
  435. console.log("找到工料机映射表时间-------------------------------"+(stdGLJMapTime - first));
  436. for(let sub of std.rationGljList){
  437. let newGLJ = {};
  438. newGLJ.ID = uuidV1();
  439. newGLJ.projectID = newRation.projectID;
  440. newGLJ.GLJID = sub.gljId;
  441. newGLJ.rationID = newRation.ID;
  442. newGLJ.billsItemID = newRation.billsItemID;
  443. newGLJ.rationItemQuantity = sub.consumeAmt;
  444. newGLJ.quantity = sub.consumeAmt;
  445. newGLJ.glj_repository_id = std.rationRepId;
  446. let std_glj = null;
  447. if(sub.type == 'complementary'){//有可能来自标准工料机库或补充工料机库
  448. if (sub.fromUser) {
  449. newGLJ.fromUser = sub.fromUser;
  450. }
  451. std_glj = cptGLJMap[sub.gljId];
  452. newGLJ.from = 'cpt';
  453. }else {
  454. std_glj = stdGLJMap[sub.gljId];
  455. newGLJ.from = 'std';
  456. }
  457. //多单价情况处理
  458. if(ext && ext.priceField && std_glj && std_glj.priceProperty && std_glj.priceProperty[ext.priceField] !== null && std_glj.priceProperty[ext.priceField] !== undefined){
  459. std_glj.basePrice = std_glj.priceProperty[ext.priceField];
  460. }
  461. if(std_glj){
  462. newGLJ.name = std_glj.name;
  463. newGLJ.code = std_glj.code;
  464. newGLJ.original_code = std_glj.code;
  465. newGLJ.unit = std_glj.unit;
  466. newGLJ.specs = std_glj.specs;
  467. newGLJ.model = std_glj.model;
  468. newGLJ.basePrice = std_glj.basePrice;
  469. newGLJ.marketPrice = std_glj.basePrice;
  470. newGLJ.taxRate= std_glj.taxRate;
  471. newGLJ.shortName = std_glj.shortName;
  472. newGLJ.type = std_glj.gljType;
  473. newGLJ.repositoryId = std_glj.repositoryId;
  474. newGLJ.adjCoe = std_glj.adjCoe;
  475. newGLJ.materialType = std_glj.materialType;
  476. newGLJ.materialCoe = std_glj.materialCoe;
  477. newGLJ.materialIndexType = std_glj.materialIndexType;
  478. newGLJ.materialIndexUnit = std_glj.materialIndexUnit;
  479. newGLJ.materialIndexCoe = std_glj.materialIndexCoe;
  480. newGLJ.createType = 'normal';
  481. let tindex = getIndex(newGLJ);
  482. if(std_glj.component && std_glj.component.length > 0) mixRatioMap[tindex] = std_glj.component;
  483. let tdata = ration_glj_facade.getGLJSearchInfo(newGLJ);
  484. gljKeyMap[tindex] = tdata;
  485. gljCodes.push(tdata.code);
  486. newRationGLJList.push(newGLJ);
  487. // let [info,projectGLJ] = await ration_glj_facade.getInfoFromProjectGLJ(newGLJ,unitPriceFileId,ext);
  488. // newGLJ = ration_glj_facade.createNewRecord(info);
  489. // newRationGLJList.push(newGLJ);
  490. // rationGLJShowList.push(info);
  491. // projectGLJList.push(projectGLJ)
  492. }
  493. //let InfoFromProjectGLJ = +new Date();
  494. //console.log("找到项目工料机时间-------------------------------"+(InfoFromProjectGLJ - std_gljTime));
  495. }
  496. [newRationGLJList, projectGLJList] = await getProjectGLJinfo(newRation.projectID,newRationGLJList,gljKeyMap,gljCodes,mixRatioMap,unitPriceFileId,ext);
  497. }
  498. let before = +new Date();
  499. console.log("总查询时间为-------------------------------"+(before-first));
  500. if(newRationGLJList.length>0){
  501. await ration_glj.insertMany(newRationGLJList);
  502. }
  503. let after = +new Date();
  504. console.log("实际插入时间为-------------------------------"+(after-before));
  505. console.log("总操作时间为-------------------------------"+(after-first));
  506. return [newRationGLJList,projectGLJList]
  507. }
  508. async function getProjectGLJinfo(projectID,t_newRationGLJList,gljKeyMap,gljCodes,mixRatioMap,unitPriceFileId,ext){//批量插入或查找项目工料机信息
  509. //先根据工料机编号在项目工料机中查找工料机是否存在
  510. let projectGLJMap={};
  511. let projectGLJList = [];
  512. let newProjectGLJList=[];//工料机ID要重新去取
  513. let connectKeyList = [];
  514. let newRationGLJList = [];
  515. let gljListModel = new GLJListModel();
  516. let t_projectGLJList = await projectGLJModel.find({'project_id':projectID,'code':{'$in':gljCodes}}).lean();
  517. for(let pg of t_projectGLJList){
  518. let pindex = getIndex(pg);
  519. projectGLJMap[pindex] = pg;
  520. }
  521. for(let key in gljKeyMap){
  522. if(!projectGLJMap[key]){//如果项目工料机不存在,则添加
  523. newProjectGLJList.push(gljKeyMap[key]);
  524. projectGLJMap[key] = gljKeyMap[key];
  525. }
  526. //查看组成物
  527. if(gljListModel.ownCompositionTypes.indexOf(gljKeyMap[key].type)!=-1){//有组成物的类型
  528. connectKeyList.push(key);
  529. }
  530. }
  531. let [existMixRatioMap,mixRatioInsertData,missCodeList] = await getMixRatioInfo(projectID,projectGLJMap,newProjectGLJList,mixRatioMap,connectKeyList,unitPriceFileId,ext);
  532. if(missCodeList.length > 0) gljCodes = gljCodes.concat(missCodeList);
  533. let [unitPriceMap,newUnitPriceList] = await getUnitPriceData(newProjectGLJList,gljCodes,unitPriceFileId);
  534. if(newUnitPriceList.length > 0) await unitPriceModel.insertMany(newUnitPriceList);
  535. if(mixRatioInsertData.length > 0) await mixRatioModel.insertMany(mixRatioInsertData);
  536. //插入项目工料机
  537. if(newProjectGLJList.length > 0){
  538. await setIDfromCounter("glj_list",newProjectGLJList);
  539. await projectGLJModel.insertMany(newProjectGLJList);
  540. }
  541. //组装数据
  542. for(let ration_glj of t_newRationGLJList){
  543. let rkey = getIndex(ration_glj);
  544. let pglj = projectGLJMap[rkey];
  545. let subList = [];
  546. setUnitPrice(pglj,unitPriceMap);
  547. if(existMixRatioMap[rkey]){//如果有组成物
  548. for(let m of existMixRatioMap[rkey]){
  549. let mpglj = projectGLJMap[getIndex(m)]
  550. if(mpglj){
  551. let cglj = _.clone(mpglj);
  552. setUnitPrice(cglj,unitPriceMap);
  553. cglj.ratio_data = m;
  554. subList.push(cglj);
  555. }else{
  556. throw `组成物${m.name}对应的项目工料机没有找到`;
  557. }
  558. }
  559. pglj.subList =subList;
  560. }
  561. ration_glj.projectGLJID = pglj.id;
  562. newRationGLJList.push(ration_glj_facade.createNewRecord(ration_glj));
  563. projectGLJList.push(pglj);
  564. }
  565. return [newRationGLJList, projectGLJList];
  566. function setUnitPrice(p,unitPriceMap){
  567. p.unit_price = unitPriceMap[getIndex(p)];
  568. }
  569. }
  570. async function getUnitPriceData(newProjectGLJList,gljCodes,unitPriceFileId){
  571. let unitPriceMap = {};
  572. let newUnitPriceList = [];
  573. let unitPriceList = await unitPriceModel.find({unit_price_file_id: unitPriceFileId,'code':{'$in':gljCodes}}).lean();
  574. for(let u of unitPriceList){
  575. unitPriceMap[getIndex(u)]=u;
  576. }
  577. for(let np of newProjectGLJList){
  578. let pkey = getIndex(np);
  579. if(unitPriceMap[pkey]) continue;
  580. let insertData = {
  581. code: np.code,
  582. base_price: np.base_price,
  583. market_price: np.market_price,
  584. unit_price_file_id: unitPriceFileId,
  585. name: np.name,
  586. taxRate:np.taxRate,
  587. specs:np.specs?np.specs:'',
  588. original_code:np.original_code,
  589. unit:np.unit?np.unit:'',
  590. type: np.type,
  591. short_name: np.shortName !== undefined ? np.shortName : '',
  592. glj_id: np.glj_id,
  593. is_add:0,
  594. grossWeightCoe:np.grossWeightCoe,
  595. purchaseStorageRate:np.purchaseStorageRate,
  596. offSiteTransportLossRate:np.offSiteTransportLossRate,
  597. handlingLossRate:np.handlingLossRate
  598. };
  599. if(np.from=='cpt') insertData.is_add=1;//如果是来自补充工料机,则都添加新增标记
  600. if(insertData.code != insertData.original_code) insertData.is_add=1;//添加的时候如果是复制整块来的,可能在源项目中是新增的工料机,这里也要添上(暂时可能还用不到)
  601. newUnitPriceList.push(insertData);
  602. unitPriceMap[pkey] = insertData;
  603. }
  604. if(newUnitPriceList.length > 0) await setIDfromCounter("unit_price",newUnitPriceList);
  605. return [unitPriceMap,newUnitPriceList];
  606. }
  607. async function getMixRatioInfo(projectID,projectGLJMap,newProjectGLJList,mixRatioMap,connectKeyList,unitPriceFileId,ext){//取组成物信息,得到缺少的组成物情况
  608. let missCodeList = []; //所有组成物信息的编码,用来统一查询对应的项目工料机是否存在
  609. let existMixRatioMap ={};
  610. let codeMap={};//用来去重
  611. let mixRatioInsertData = [];
  612. // 1. 先检查现在的组成物表中,是否有相关信息 - 生成映射记录
  613. if(connectKeyList.length > 0){//有组成物的话从数据库中取出组成物信息
  614. let mixRatioList = await mixRatioModel.find({'unit_price_file_id': unitPriceFileId,'connect_key': {'$in':connectKeyList}}).lean();
  615. for(let m of mixRatioList){
  616. //组成物信息分组,查看哪些是已经存在的
  617. existMixRatioMap[m.connect_key]?existMixRatioMap[m.connect_key].push(m):existMixRatioMap[m.connect_key]=[m];
  618. //查看组成物对应的项目工料机是否存在,如果不存在,要插入项目工料机
  619. let mkey = getIndex(m);
  620. if(!projectGLJMap[mkey] && !codeMap[m.code]){//如果之前查出来的项目工料机中不包含组成物的信息,要加到missCode里面再查找一次项目工料机看是否存在
  621. missCodeList.push(m.code);
  622. codeMap[m.code] = true;
  623. }
  624. }
  625. // 2 将第一步得到的映射表 与在标准库查询父工料机得到的映射表对比,得出哪些组物成还需要添加,获得库ID
  626. let stdIDs = [];
  627. let comIDs = [];
  628. let missMixRatioGroup = [];
  629. for(let ck of connectKeyList){//查看项目中组成物信息是否已经存在,如果不存在,则用插定额时获取的组成物信息从数据库中获取
  630. if(!existMixRatioMap[ck] && mixRatioMap[ck] && mixRatioMap[ck].length > 0){//组成物信息不存在
  631. let pglj = projectGLJMap[ck];//取出父数据
  632. let from = pglj.from === undefined|| pglj.from ===null || pglj.from === ""?'std' : pglj.from;
  633. for(let c of mixRatioMap[ck]){
  634. if(from == "std"){//标准的工料机只来自标准的
  635. stdIDs.push(c.ID);
  636. }else{
  637. c.isStd?stdIDs.push(c.ID):comIDs.push(c.ID);
  638. }
  639. }
  640. missMixRatioGroup.push({'connect_key':ck,'list':mixRatioMap[ck],'from':from});
  641. }
  642. }
  643. //3.统一查询所有组成物在标准库中的详细信息
  644. let stdMixMap = {};
  645. //整理需插入的组成物列表的数据
  646. //来自标准工料机
  647. if(stdIDs.length > 0){
  648. stdIDs = _.uniq(stdIDs);//去重
  649. let stdMixList = await std_glj_lib_gljList_model.find({'ID':{'$in':stdIDs}}).lean();
  650. for(let sm of stdMixList){
  651. stdMixMap[sm.ID] = sm;
  652. let skey = getIndex(sm,['code','name','specs','unit','gljType']);
  653. if(!projectGLJMap[skey] && !codeMap[sm.code]){
  654. missCodeList.push(sm.code);
  655. codeMap[sm.code] = true;
  656. }
  657. }
  658. }
  659. //来自组成物工料机
  660. let comMixMap = {};
  661. if(comIDs.length > 0){
  662. comIDs = _.uniq(comIDs);//去重
  663. let comMixList = await complementaryGljLibModel.find({'ID':{'$in':comIDs}}).lean();
  664. for(let cm of comMixList){
  665. comMixMap[cm.ID] = cm;
  666. let ckey = getIndex(cm,['code','name','specs','unit','gljType']);
  667. if(!projectGLJMap[ckey] && codeMap[cm.code]){
  668. missCodeList.push(cm.code);
  669. codeMap[cm.code] = true;
  670. }
  671. }
  672. }
  673. //4.生成需要插入组成物表的数据
  674. for(let mg of missMixRatioGroup){//整理需要插入组成物列表的数据
  675. for(let tc of mg.list){
  676. let consumpiton = tc.consumeAmt;
  677. //只有标准的工料机的组成物才会有多单价、多组成物消耗量的情况
  678. if(mg.from == 'std' && ext && ext.quantityField &&( tc.consumeAmtProperty[ext.quantityField]!= undefined && tc.consumeAmtProperty[ext.quantityField]!=null)){
  679. consumpiton = tc.consumeAmtProperty[ext.quantityField];
  680. }
  681. let mfrom = mg.from == 'std' || tc.isStd?'std':'cpt';
  682. let tmp = mfrom == 'std'?stdMixMap[tc.ID]:comMixMap[tc.ID];//取出之前库中查到的工料机
  683. let mixRatioData = {
  684. consumption: consumpiton,
  685. glj_id: tmp.ID,
  686. unit_price_file_id: unitPriceFileId,
  687. connect_key: mg.connect_key,
  688. type: tmp.gljType,
  689. code: tmp.code,
  690. specs:tmp.specs?tmp.specs:"",
  691. name:tmp.name,
  692. unit:tmp.unit?tmp.unit:'',
  693. from:mfrom
  694. };
  695. mixRatioInsertData.push(mixRatioData);
  696. }
  697. }
  698. if(mixRatioInsertData.length > 0) await setIDfromCounter("mix_ratio",mixRatioInsertData,existMixRatioMap,'connect_key');
  699. //await mixRatioModel.insertMany(mixRatioInsertData); 因为没有事务添加组成物数据要放在添加单价文件数据之后
  700. //5.查询组成物对应的项目工料机是否存在,如果不存在,生成项目工料机信息
  701. let projectGLJList = await projectGLJModel.find({'project_id':projectID,'code':{'$in':missCodeList}}).lean();
  702. for(let pg of projectGLJList){
  703. let pindex = getIndex(pg);
  704. projectGLJMap[pindex] = pg;
  705. }
  706. let lessMix = [];//组成物表存在,项目工料机不存在的数据
  707. let lessMixMap = {};//防止重复添加
  708. for(let connect_key in existMixRatioMap){
  709. let mixRatios = existMixRatioMap[connect_key];
  710. for(let m of mixRatios){
  711. let mk = getIndex(m);
  712. if(!projectGLJMap[mk] && !lessMixMap[mk]){//如果组成物对应的项目工料机不存在
  713. let nglj = null;
  714. if(m.from == 'std'){//这里有值,说明是刚添加到组成物文件中的数据
  715. nglj = stdMixMap[m.glj_id];
  716. }else if(m.from == 'cpt'){//这里有值,说明是刚添加到组成物文件中的数据
  717. nglj = comMixMap[m.glj_id];
  718. }
  719. if(nglj){
  720. nglj.from = m.from;
  721. let np = getProjectGLJNewData(nglj,projectID,ext);
  722. newProjectGLJList.push(np);
  723. projectGLJMap[mk] = np;
  724. }else{//这里没找到,说明是组成物文件里有,但是项目工料机没有的数据
  725. lessMix.push(m);
  726. }
  727. lessMixMap[mk] = true;//只要处理过一次,就不用再重新处理了,机械组成物,比如柴油这些,会出现多次
  728. }
  729. }
  730. }
  731. //6. 组成物文件里有,但是项目工料机没有的数据(共用单价文件等情况产生)
  732. let lessIDList=[];
  733. let uniqMap ={};//去重
  734. let lessStdMix = [];//防止组成物中改了名称等,但是通过glj_id取出来的是还没改前的原始数据
  735. if(lessMix.length > 0){
  736. for(let lm of lessMix){
  737. let parentglj = projectGLJMap[lm.connect_key];
  738. if(!parentglj) throw `含有组成物工料机${lm.connect_key},没有找到,添加定额失败`;
  739. if((parentglj.from == "std" || lm.from == "std") && lm.code!="80CCS"){//车船税特殊处理
  740. if(!uniqMap[lm.glj_id]){
  741. lessIDList.push(lm.glj_id);
  742. uniqMap[lm.glj_id] = lm;
  743. }
  744. lessStdMix.push(lm);
  745. }else {//来自组成物的直接设置
  746. lm.from = 'cpt';
  747. lm.gljType = lm.type;
  748. let t_mg = getProjectGLJNewData(lm,projectID);
  749. newProjectGLJList.push(t_mg);
  750. projectGLJMap[getIndex(lm)] = t_mg;
  751. }
  752. }
  753. }
  754. if(lessIDList.length > 0){
  755. let less_stds = await std_glj_lib_gljList_model.find({'ID':{'$in':lessIDList}}).lean();
  756. let less_stds_map = {};
  757. for(let les of less_stds){
  758. less_stds_map[les.ID] = les;
  759. }
  760. for(let t_l_m of lessStdMix){
  761. let t_nglj = less_stds_map[t_l_m.glj_id];
  762. t_nglj.from = 'std';
  763. //防止组成物中改了名称等,但是通过glj_id取出来的是还没改前的原始数据
  764. t_nglj.name = t_l_m.name;
  765. t_nglj.code = t_l_m.code;
  766. t_nglj.gljType = t_l_m.type;
  767. t_nglj.specs = t_l_m.specs;
  768. t_nglj.unit = t_l_m.unit;
  769. let t_np = getProjectGLJNewData(t_nglj,projectID,ext);
  770. newProjectGLJList.push(t_np);
  771. projectGLJMap[getIndex(t_l_m)] = t_np;
  772. }
  773. }
  774. }
  775. return [existMixRatioMap,mixRatioInsertData,missCodeList]
  776. }
  777. function getProjectGLJNewData(tmp,projectId,ext){
  778. let gljData = {
  779. glj_id: tmp.ID,
  780. repositoryId:tmp.repositoryId,
  781. project_id: projectId,
  782. code: tmp.code,
  783. name: tmp.name,
  784. specs: tmp.specs?tmp.specs:'',
  785. unit: tmp.unit === undefined ? '' : tmp.unit,
  786. type: tmp.gljType,
  787. adjCoe:tmp.adjCoe,
  788. original_code:tmp.code,
  789. materialType: tmp.materialType, //三材类别
  790. materialCoe: tmp.materialCoe,
  791. base_price: tmp.basePrice,
  792. market_price: tmp.basePrice,
  793. is_evaluate:0,
  794. is_eval_material:0,
  795. no_tax_eqp:0,
  796. is_adjust_price:0,
  797. is_main_material:0,
  798. is_contractor_material:0,
  799. supply_quantity:0,
  800. supply:0,
  801. from:tmp.from?tmp.from:"std"
  802. };
  803. // 现在定额库可以引用其他费用定额的,比如广东可能套用部颁的定额,因此就算广东费用定额是多单价的,也可能会引用单个单价的人材机
  804. if(gljData.from == 'std' && ext && ext.priceField &&( tmp.priceProperty && tmp.priceProperty[ext.priceField]!= undefined && tmp.priceProperty[ext.priceField]!=null)){
  805. const basePrice = scMathUtil.roundTo(tmp.priceProperty[ext.priceField],-6);
  806. gljData.base_price = basePrice;
  807. gljData.market_price = basePrice;
  808. }
  809. return gljData;
  810. }
  811. async function setIDfromCounter(name,list,map,keyfield){//map,keyfield
  812. let update = {$inc: {sequence_value: list.length}};
  813. let condition = {_id: name};
  814. let options = {new: true};
  815. // 先查找更新
  816. let counter = await counterModel.findOneAndUpdate(condition, update, options);
  817. let firstID = counter.sequence_value - (list.length - 1);
  818. for(let a of list){
  819. a.id = firstID;
  820. firstID+=1
  821. if(map && keyfield){
  822. let key = a[keyfield];
  823. map[key]?map[key].push(a):map[key]=[a]
  824. }
  825. }
  826. }
  827. async function deleRationSubRecode(projectID,rationID,cleanzmhs=false) {//删除挂在定额下的数据,如工程量明细,定额工料机等
  828. let delete_query={projectID: projectID, rationID: rationID};
  829. //删除工程量明细
  830. await deleteSubListByQuery(delete_query,cleanzmhs) ;
  831. }
  832. async function deleteSubListByQuery(delete_query,cleanzmhs=false) {
  833. if(cleanzmhs == false){//清空子目换算即cleanzmh==true时不需要清空工程量明细、模板关联子目、安装增加费
  834. await quantity_detail.deleteByQuery(delete_query) ;//删除工程量明细
  835. await rationInstallationModel.deleteMany(delete_query);//删除安装增加费
  836. await rationTemplateModel.deleteMany(delete_query);//删除模板关联子目
  837. }
  838. //to do稳定土也要删除
  839. await ration_coe.deleteMany(delete_query);//删除附注条件
  840. await ration_glj.deleteMany(delete_query);//删除定额工料机
  841. }
  842. async function updateCoeAdjust(data,compilation) {
  843. let replace = [],projectGLJList=[];
  844. await ration_coe.update({ID:data.ID},data.doc);
  845. //添加单个工料机的情况
  846. if (data.add.length > 0){
  847. let [tg,pl] = await ration_glj_facade.insertAddTypeGLJ(data.add,compilation);
  848. if(pl.length > 0) projectGLJList = projectGLJList.concat(pl);
  849. }
  850. if(data.delete.length > 0) await ration_glj_facade.deleteGLJ(data.delete);
  851. //替换工料机的情况
  852. if (data.replace.length > 0){
  853. for(let r of data.replace){
  854. let [rg,pg] = await ration_glj_facade.replaceGLJByData(r,compilation);
  855. replace.push(rg) ;
  856. projectGLJList.push(pg);
  857. }
  858. }
  859. let cal_result = await glj_calculate_facade.calculateQuantity({projectID:data.projectID,rationID:data.rationID},null,true);
  860. let coe = {
  861. query:{ID:data.ID,projectID:data.projectID},
  862. doc:data.doc
  863. };
  864. let ration_glj ={
  865. quantityRefresh:true,
  866. glj_result:cal_result.glj_result
  867. };
  868. let ration = {
  869. ID:cal_result.rationID,
  870. adjustState:cal_result.adjustState,
  871. name:cal_result.rationName
  872. };
  873. return {coe:coe,ration_glj:ration_glj,ration:ration,add:data.add,delete:data.delete,replace:replace,projectGLJList:projectGLJList}
  874. }
  875. async function updateRation(std,defaultLibID,rationID,billsItemID,projectID,calQuantity,cleanzmh=false) {
  876. // insertNewRation
  877. let ration ={};
  878. if (std.owner) {
  879. // 别人分享的定额
  880. ration.fromUser = std.owner;
  881. }
  882. ration.code = std.code;
  883. ration.name = std.name;
  884. ration.caption = std.caption;
  885. ration.unit = std.unit;
  886. if (std.type === 'std') {
  887. ration.libID = std.rationRepId;
  888. ration.stdID = std.ID;
  889. }
  890. ration.content = std.jobContent;
  891. ration.manageFeeRate = std.manageFeeRate;
  892. ration.adjustState = '';
  893. ration.isFromDetail=0;
  894. ration.isSubcontract=false;
  895. ration.fees=[];
  896. if (std.chapter) {
  897. ration.comments = std.chapter.explanation;
  898. ration.ruleText = std.chapter.ruleText;
  899. }
  900. ration.from = std.type === 'complementary' ? 'cpt' : 'std';
  901. //定额前缀 none:0, complementary:1, borrow: 2
  902. ration.prefix = '';
  903. if(parseInt(defaultLibID) !== std.rationRepId){//定额是默认定额库中的时,只显示编号;
  904. ration.prefix = '借';//定额不是默认定额库中的、且不是补充定额库中的时, 在定额编号前显示“借”。
  905. if(ration.from === 'cpt') ration.prefix = '补';//定额是补充定额库中的时,在定额编号前显示“补”;
  906. }
  907. ration.rationAssList = createRationAss(std);//生成辅助定额
  908. if(cleanzmh==false){//如果是清空子目换算,即cleanzmh==true 保留定额工程量、工程量表达式、含量(分解系数)、取费专业(取费类别)
  909. if(std.feeType == undefined || std.feeType == null || std.feeType ==''){//定额取费专业为空的情况下,取项目属性中的定额取费专业ID
  910. ration.programID = await getProgramForProject(projectID);
  911. }else {
  912. ration.programID = std.feeType;
  913. }
  914. if(calQuantity){
  915. await CalculateQuantity(ration,billsItemID,projectID);
  916. }
  917. }
  918. let unsetObject = {
  919. "marketUnitFee":1,
  920. 'marketTotalFee':1,
  921. "maskName":1
  922. };
  923. let newRation = await ration_model.model.findOneAndUpdate({ID:rationID,projectID:projectID},{"$set":ration,"$unset":unsetObject},{new: true});//;
  924. return newRation;
  925. }
  926. async function setEmptyRation(projectID,rationID){
  927. let ration ={};
  928. ration.code = "";
  929. ration.name = "";
  930. ration.caption = "";
  931. ration.unit = "";
  932. ration.libID = null;
  933. ration.content = "";
  934. ration.adjustState = '';
  935. ration.isFromDetail=0;
  936. ration.isSubcontract=false;
  937. ration.fees=[];
  938. ration.comments = "";
  939. ration.ruleText = "";
  940. ration.quantity="";
  941. ration.contain="";
  942. ration.quantityEXP="";
  943. ration.from = 'std';
  944. //定额前缀 none:0, complementary:1, borrow: 2
  945. ration.prefix = '';
  946. ration.rationAssList = [];
  947. ration.marketUnitFee ="";
  948. ration.marketTotalFee ="";
  949. ration.maskName = "";
  950. ration.targetTotalFee ='';
  951. ration.targetUnitFee = "";
  952. ration.deleteInfo = null;
  953. ration.quantityCoe = {};
  954. ration.rationQuantityCoe="";
  955. ration.tenderQuantity = "";
  956. ration.programID = null;
  957. let newRation = await ration_model.model.findOneAndUpdate({ID:rationID,projectID:projectID},{"$set":ration},{new: true});//;
  958. return {ration:newRation,ration_gljs:[],ration_coes:[],ration_installs:[]};
  959. }
  960. function createRationAss(std) {
  961. let rationAssList = [];//生成辅助定额
  962. if(std.hasOwnProperty('rationAssList')&&std.rationAssList.length>0){
  963. let assGroup = _.groupBy(std.rationAssList,'name');
  964. for(let key in assGroup){
  965. let assList = assGroup[key];
  966. let ass = assList[0];
  967. ass._doc.actualValue = ass.stdValue;
  968. ass._doc.isAdjust = 0;
  969. if(_.isString(ass._doc.assistCode)) ass._doc.assistCode = ass._doc.assistCode.replace("\n","");
  970. if(_.isString(ass._doc.thirdRationCode)) ass._doc.thirdRationCode = ass._doc.thirdRationCode.replace("\n","");
  971. if(assList.length > 1){
  972. ass._doc.groupList = JSON.parse(JSON.stringify(assList)) ;
  973. ass._doc.maxValue = assList[assList.length-1]._doc.maxValue;
  974. }
  975. rationAssList.push(ass);
  976. }
  977. }
  978. return rationAssList;
  979. }
  980. async function CalculateQuantity (ration,billsItemID,projectID) {
  981. // calculate ration Quantity
  982. let project = await projectModel.findOne({ID:projectID});
  983. let decimalObject =await decimal_facade.getProjectDecimal(projectID,project);
  984. let quantity_decimal = (decimalObject&&decimalObject.ration&&decimalObject.ration.quantity)?decimalObject.ration.quantity:3;
  985. let pbill = await bill_model.model.findOne({projectID:projectID,ID:billsItemID});
  986. let t_unit = ration.unit?ration.unit.replace(/^\d+/,""):"";
  987. if(t_unit!=pbill.unit){//如果定额工程量的单位去除前面的数字后不等于清单单位,定额工程量保持不变
  988. return ;
  989. }
  990. let billsQuantity = pbill.quantity ? pbill.quantity : 0;
  991. let bill_decimal = await decimal_facade.getBillsQuantityDecimal(projectID,pbill.unit,project);
  992. billsQuantity=scMathUtil.roundForObj(billsQuantity,bill_decimal);
  993. ration.quantityEXP="QDL";
  994. ration.quantity = scMathUtil.roundForObj(billsQuantity / FilterNumberFromUnit(ration.unit),quantity_decimal);//不管是否打勾都做转换
  995. ration.contain = scMathUtil.roundForObj(ration.quantity/billsQuantity,6);
  996. };
  997. async function getProgramForProject(projectID){
  998. let project = await projectModel.findOne({ID:projectID});
  999. return project.property.engineering;
  1000. }
  1001. function FilterNumberFromUnit (unit) {
  1002. let reg = new RegExp('^[0-9]+');
  1003. if (reg.test(unit)) {
  1004. return parseInt(unit.match(reg)[0]);
  1005. } else {
  1006. return 1;
  1007. }
  1008. };
  1009. function getIndex(obj,tpops){
  1010. let pops = tpops?tpops:['code','name','specs','unit','type'];
  1011. let t_index = '';
  1012. let k_arr=[];
  1013. for(let p of pops){
  1014. let tmpK = (obj[p]==undefined||obj[p]==null||obj[p]=='')?'null':obj[p];
  1015. k_arr.push(tmpK);
  1016. }
  1017. t_index=k_arr.join("|-|");
  1018. return t_index;
  1019. }