ration_facade.js 46 KB

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