ration_facade.js 52 KB

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