ration_facade.js 50 KB

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