ration_facade.js 53 KB

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