ration_facade.js 53 KB

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