ration_facade.js 53 KB

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