ration_facade.js 48 KB

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