ration_facade.js 51 KB

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