ration_facade.js 50 KB

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