ration_facade.js 51 KB

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