ration_facade.js 50 KB

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