ration_facade.js 45 KB

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