ration_facade.js 51 KB

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