pm_facade.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. /**
  2. * Created by zhang on 2018/4/17.
  3. */
  4. const projectType = {
  5. folder: 'Folder',
  6. tender: 'Tender',
  7. project: 'Project',
  8. engineering: 'Engineering',
  9. };
  10. //先导出后require可以解决循环引用问题
  11. module.exports={
  12. moveProject:moveProject,
  13. copyProject:copyProject,
  14. copyExample: copyExample,
  15. getSummaryInfo: getSummaryInfo,
  16. getSummaryInfoByTender: getSummaryInfoByTender,
  17. getTendersFeeInfo: getTendersFeeInfo,
  18. getConstructionProject: getConstructionProject,
  19. getFullPath: getFullPath,
  20. projectType: projectType,
  21. getPosterityProjects: getPosterityProjects,
  22. isShare: isShare,
  23. isFirst: isFirst,
  24. getShareInfo: getShareInfo,
  25. prepareInitialData: prepareInitialData,
  26. changeFile:changeFile,
  27. getBasicInfo: getBasicInfo,
  28. getProjectFeature: getProjectFeature,
  29. getProjectByGranularity: getProjectByGranularity,
  30. importProject: importProject,
  31. getProjectPlaceholder: getProjectPlaceholder
  32. };
  33. let mongoose = require('mongoose');
  34. let _ = require("lodash");
  35. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  36. let glj_facade = require('../../glj/facade/glj_facade');
  37. let project_facade = require('../../main/facade/project_facade');
  38. let logger = require("../../../logs/log_helper").logger;
  39. const uuidV1 = require('uuid/v1');
  40. let projectModel = mongoose.model('projects');
  41. let projectSettingModel = mongoose.model('proj_setting');
  42. let billsModel = mongoose.model('bills');
  43. let rationModel = mongoose.model('ration');
  44. let gljListModel = mongoose.model("glj_list");
  45. let calcProgramsModel = mongoose.model('calc_programs');
  46. let labourCoesModel = mongoose.model('labour_coes');
  47. let feeRateModel = mongoose.model('fee_rates');
  48. let feeRateFileModel = mongoose.model('fee_rate_file');
  49. let unitPriceFileModel = mongoose.model("unit_price_file");
  50. let mixRatioModel = mongoose.model("mix_ratio");
  51. let unitPriceModel = mongoose.model("unit_price");
  52. let installationFeeModel = mongoose.model("installation_fee");
  53. let rationGLJModel = mongoose.model('ration_glj');
  54. let rationCoeModel = mongoose.model('ration_coe');
  55. let rationInstallationModel = mongoose.model('ration_installation');
  56. let quantityDetailModel = mongoose.model('quantity_detail');
  57. let rationTemplateModel = mongoose.model('ration_template');
  58. let userModel = mongoose.model('user');
  59. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  60. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  61. let compilationModel = mongoose.model('compilation');
  62. let engineeringModel = mongoose.model('engineering_lib');
  63. let basicInfoModel = mongoose.model('std_basic_info_lib');
  64. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  65. let productModel = mongoose.model('product');
  66. let stdRationItemModel = mongoose.model('std_ration_lib_ration_items');
  67. let stdGljItemModel = mongoose.model('std_glj_lib_gljList');
  68. import BillsTemplateModel from "../models/templates/bills_template_model";
  69. let featureLibModel = mongoose.model("std_project_feature_lib");
  70. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  71. let counter = require('../../../public/counter/counter');
  72. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  73. let sectionTreeDao = new SectionTreeDao();
  74. import CounterModel from "../../glj/models/counter_model";
  75. import moment from 'moment';
  76. import billsFlags from '../../common/const/bills_fixed';
  77. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  78. import {
  79. defaultDecimal,
  80. billsQuantityDecimal,
  81. displaySetting,
  82. calcOptions,
  83. tenderSetting,
  84. G_FILE_VER
  85. } from '../models/project_property_template';
  86. let labourCoeFacade = require('../../main/facade/labour_coe_facade');
  87. let calcProgramFacade = require('../../main/facade/calc_program_facade');
  88. let mainColLibModel = mongoose.model('std_main_col_lib');
  89. import EngineeringLibModel from "../../users/models/engineering_lib_model";
  90. let installationFacade = require('../../main/facade/installation_facade');
  91. //拷贝例题项目
  92. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  93. async function copyExample(userID, compilation, projIDs){
  94. let allProjs = [],
  95. IDMapping = {},
  96. projMapping = {};
  97. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  98. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted});
  99. if (parentExample.length === 0) {
  100. return false;
  101. }
  102. allProjs = allProjs.concat(parentExample);
  103. for (let i = 0; i < parentExample.length; i++) {
  104. let data = parentExample[i];
  105. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  106. return false;
  107. }
  108. //设置成顶节点,最后一个节点设置成末节
  109. data.ParentID = -1;
  110. if (i === parentExample.length - 1) {
  111. data.NextSiblingID = -1;
  112. }
  113. }
  114. //获取所有的子项目
  115. let posterityProjs = await getPosterityProjects(projIDs);
  116. allProjs = allProjs.concat(posterityProjs);
  117. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  118. //旧ID与新ID映射
  119. for (let i = 0; i < allProjs.length; i++) {
  120. let data = allProjs[i];
  121. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  122. IDMapping[data.ID] = newID;
  123. projMapping[newID] = data;
  124. }
  125. //return;
  126. //设置新的树结构数据
  127. let newDate = new Date(),
  128. parentBulks = [];
  129. for (let data of allProjs) {
  130. let orgID = data.ID;
  131. data.ID = IDMapping[data.ID];
  132. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  133. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  134. data.createDateTime = newDate;
  135. data.userID = userID;
  136. data.compilation = compilation;
  137. data.shareInfo = [];
  138. if (data.projType !== projectType.tender) {
  139. let newData = _.cloneDeep(data._doc);
  140. delete newData._id;
  141. // await projectModel.create(newData);
  142. parentBulks.push({insertOne: {document: newData}});
  143. } else {
  144. //拷贝单位工程
  145. let rootProjectID = projMapping[data.ParentID].ParentID;
  146. let projectMap = {
  147. copy: {
  148. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  149. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  150. }
  151. };
  152. await copyProject(userID, compilation, {projectMap}, data.ID);
  153. }
  154. }
  155. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  156. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  157. if (lastProj) {
  158. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  159. }
  160. //拷贝父级文件
  161. await projectModel.bulkWrite(parentBulks);
  162. return true;
  163. }
  164. async function copyProject(userID, compilationID,data,newProjectID = null) {
  165. let projectMap = data.projectMap;
  166. let originalID = projectMap['copy'].document.ID;
  167. if (!newProjectID) {
  168. newProjectID = await getCounterID("projects");
  169. }
  170. let newFeeName = null,newUnitName = null;
  171. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  172. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  173. let feeRateFileID = uuidV1();//新的费率文件ID
  174. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  175. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  176. if(!originalProject){
  177. throw new Error('没有找到对应的项目,复制失败!');
  178. }
  179. let property = originalProject.property;
  180. if(projectMap['copy'].document.property){//更新项目属性信息
  181. setProperty(property,projectMap['copy'].document.property);
  182. }
  183. let originalProperty = _.cloneDeep(property);
  184. projectMap['copy'].document.property = property;
  185. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  186. //费率文件、单价文件重名检查
  187. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  188. if(feeRate){//存在重名的文件
  189. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  190. projectMap['copy'].document.property.feeFile.name = newFeeName;
  191. }
  192. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  193. if(unitPriceFile){//存在重名的文件
  194. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  195. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  196. }
  197. //更新项目的属性;
  198. projectMap['copy'].document.ID = newProjectID;
  199. if(projectMap['copy'].document.property.calcProgramFile){
  200. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  201. }
  202. if(projectMap['copy'].document.property.labourCoeFile){
  203. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  204. }
  205. if(projectMap['copy'].document.property.feeFile){
  206. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  207. }
  208. if(projectMap['copy'].document.property.unitPriceFile){
  209. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  210. }
  211. projectMap['copy'].document.userID = userID;
  212. projectMap['copy'].document.compilation = compilationID;
  213. projectMap['copy'].document.createDateTime = new Date();
  214. //清单、定额ID生成任务
  215. let IDtasks = [
  216. createIDsAndReturn(originalID,billsModel),
  217. createIDsAndReturn(originalID,rationModel),
  218. getProjectGLJIDAndReturn(originalID,newProjectID)
  219. ];
  220. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  221. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  222. let copyTasks = [
  223. createProject(projectMap),
  224. copyProjectSetting(originalID,newProjectID),
  225. copyBills(newProjectID,billMap),
  226. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  227. copyProjectGLJ(projectGLJMap.datas),
  228. copyInstallFee(originalID,newProjectID),
  229. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  230. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  231. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  232. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  233. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel)
  234. ];
  235. if(originalProperty.calcProgramFile){
  236. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  237. }
  238. if(originalProperty.labourCoeFile){
  239. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  240. }
  241. if(originalProperty.feeFile){
  242. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  243. }
  244. if(originalProperty.unitPriceFile){
  245. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  246. }
  247. let p = await Promise.all(copyTasks);
  248. return p[0];
  249. }
  250. async function createIDsAndReturn(originalID,model) {
  251. let uuidMaping = {};//做ID映射
  252. let datas = [];
  253. let result = await model.find({"projectID": originalID}, '-_id');
  254. uuidMaping['-1'] = -1;
  255. //建立uuid-ID映射
  256. for(let d of result){
  257. uuidMaping[d.ID] = uuidV1();
  258. datas.push(d._doc);
  259. }
  260. return{uuidMaping:uuidMaping,datas:datas};
  261. }
  262. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  263. let IDMap = {};
  264. let datas = [];
  265. let result = await gljListModel.find({project_id:originalID}, '-_id');
  266. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  267. for(let i = 0; i < result.length; i++){
  268. let d = result[i];
  269. let newID = gljCount.sequence_value - (result.length - 1) + i;
  270. //let newID = await getCounterID("glj_list");
  271. IDMap[d.id] = newID;
  272. d._doc.project_id = newProjectID;
  273. d._doc.id = newID;
  274. datas.push(d._doc);
  275. }
  276. return{IDMap:IDMap,datas:datas};
  277. }
  278. async function createProject(projectMap) {//复制项目
  279. let tasks = [];
  280. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  281. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  282. }
  283. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  284. await projectModel.bulkWrite(tasks);
  285. return projectMap;
  286. }
  287. async function copyProjectSetting(originalID,newProjectID) {
  288. let result = null;
  289. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  290. if(setting){
  291. setting._doc.projectID =newProjectID;
  292. result = await projectSettingModel.create(setting._doc);
  293. }
  294. return result;
  295. }
  296. async function copyBills(newProjectID,billMap) {
  297. let uuidMaping = billMap.uuidMaping;//做ID映射
  298. for(let doc of billMap.datas){
  299. doc.projectID = newProjectID;
  300. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  301. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  302. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  303. }
  304. await insertMany(billMap.datas,billsModel);
  305. return billMap.datas;
  306. }
  307. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  308. let uuidMaping = rationMap.uuidMaping;
  309. for(let doc of rationMap.datas){
  310. doc.projectID = newProjectID;
  311. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  312. if(doc.billsItemID){
  313. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  314. }
  315. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  316. //绑定定类型的工料机 项目工料机ID
  317. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  318. }
  319. if(rationMap.datas.length > 0){
  320. await insertMany(rationMap.datas,rationModel);
  321. }
  322. return rationMap.datas;
  323. }
  324. async function copyProjectGLJ(gljList) {
  325. await insertMany(gljList,gljListModel);
  326. }
  327. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  328. let result = null;
  329. let file = await model.findOne({"ID": oldID}, '-_id');
  330. if(file){
  331. file._doc.ID = newID;
  332. file._doc.projectID =newProjectID;
  333. result = await model.create(file._doc);
  334. }
  335. return result;
  336. }
  337. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  338. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  339. let newFeeRateID = uuidV1();
  340. if(feeRate){
  341. feeRate._doc.ID = newFeeRateID;
  342. await feeRateModel.create(feeRate._doc);
  343. }
  344. if(feeRateFile){
  345. feeRateFile._doc.ID = feeRateFileID;
  346. newName?feeRateFile._doc.name = newName:'';
  347. feeRateFile._doc.userID = userID;
  348. feeRateFile._doc.rootProjectID = rootProjectID;
  349. feeRateFile._doc.feeRateID = newFeeRateID;
  350. await feeRateFileModel.create(feeRateFile._doc);
  351. }
  352. }
  353. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  354. let taskList = [
  355. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  356. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  357. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  358. ];
  359. return await Promise.all(taskList);
  360. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  361. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  362. if(unitPriceFile){
  363. unitPriceFile._doc.id = unitPriceFileID;
  364. newName?unitPriceFile._doc.name = newName:'';
  365. unitPriceFile._doc.project_id = newProjectID;
  366. unitPriceFile._doc.user_id = userID;
  367. unitPriceFile._doc.root_project_id = rootProjectID
  368. }
  369. await unitPriceFileModel.create(unitPriceFile._doc);
  370. }
  371. async function copySubList(srcFID,newFID,model) {
  372. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  373. let rList = [];
  374. for(let m of mList){
  375. m._doc.unit_price_file_id = newFID;
  376. m._doc.id = await getCounterID(model.modelName);
  377. rList.push(m._doc);
  378. }
  379. await insertMany(rList,model)
  380. }
  381. }
  382. async function copyInstallFee(originalPID,newProjectID) {
  383. let result = null;
  384. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  385. let newList = [];
  386. for(let i of installationFee ){
  387. i._doc.ID = uuidV1();
  388. i._doc.projectID = newProjectID;
  389. newList.push(i._doc);
  390. }
  391. if(newList.length >0){
  392. result = await installationFeeModel.insertMany(newList);
  393. }
  394. return result;
  395. }
  396. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  397. let subList = await model.find({projectID:originalPID}, '-_id');
  398. let newList =[];
  399. for(let s of subList){
  400. s._doc.ID = uuidV1();
  401. s._doc.projectID = newProjectID;
  402. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  403. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  404. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  405. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  406. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  407. for(let t of s._doc.templateList){
  408. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  409. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  410. }
  411. }
  412. newList.push(s._doc);
  413. }
  414. await insertMany(newList,model);
  415. }
  416. async function moveProject(data) {
  417. data = JSON.parse(data);
  418. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  419. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  420. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  421. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  422. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  423. for(let projectID in feeRateMap){
  424. let rename = feeRateMap[projectID].name;
  425. let feeRateID = feeRateMap[projectID].query.ID;
  426. let checkFee = _.find(feeRates,{'name':rename});
  427. let newID = feeRateID;
  428. if(checkFee){//说明费率名字已存在,需要重命名
  429. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  430. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  431. if(feeRateMap[projectID].action == 'move'){
  432. feeRateMap[projectID].update.name = rename;
  433. }
  434. }
  435. if(feeRateMap[projectID].action == 'copy'){
  436. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  437. feeRateMap[projectID].name = rename;
  438. feeRateMap[projectID].ID = newID;
  439. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  440. }
  441. if(!feeUniqMap[feeRateID]){
  442. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  443. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  444. }
  445. }
  446. }
  447. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  448. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  449. for(let projectID in unitPriceMap){
  450. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  451. let rename = unitPriceMap[projectID].name;
  452. let unitPriceID = unitPriceMap[projectID].query.id;
  453. let newID = unitPriceID;
  454. if(checkUn){//重名检查
  455. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  456. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  457. if(unitPriceMap[projectID].action =='move'){
  458. unitPriceMap[projectID].update.name = rename;
  459. }
  460. }
  461. if(unitPriceMap[projectID].action =='copy'){
  462. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  463. unitPriceMap[projectID].name = rename;
  464. unitPriceMap[projectID].id = newID;
  465. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  466. }
  467. if(!priceUniqMap[unitPriceID]){
  468. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  469. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  470. }
  471. }
  472. }
  473. if(!_.isEmpty(projectMap)){
  474. for(let projectID in projectMap){
  475. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  476. }
  477. }
  478. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  479. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  480. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  481. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  482. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  483. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  484. return projectMap;
  485. }
  486. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  487. if(data.action == 'move'){
  488. let task = {
  489. updateOne:{
  490. filter : data.query,
  491. update : data.update
  492. }
  493. };
  494. feeRateFileTask.push(task);
  495. }
  496. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  497. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  498. let newFeeRateID = uuidV1();
  499. let newFeeRate = {
  500. ID:newFeeRateID,
  501. rates:feeRate.rates
  502. };
  503. let newFeeRateFile = {
  504. ID:data.ID,
  505. rootProjectID:data.rootProjectID,
  506. userID:feeRateFile.userID,
  507. name:data.name,
  508. libID:feeRateFile.libID,
  509. libName:feeRateFile.libName,
  510. feeRateID:newFeeRateID
  511. };
  512. feeRateTask.push({insertOne :{document:newFeeRate}});
  513. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  514. }
  515. }
  516. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  517. if(data.action == 'move'){
  518. let task = {
  519. updateOne:{
  520. filter : data.query,
  521. update : data.update
  522. }
  523. };
  524. unitPriceFileTask.push(task);
  525. }
  526. if(data.action == 'copy'){
  527. let newUnitFile = {
  528. id:data.id,
  529. name: data.name,
  530. project_id:projectID,
  531. user_id:user_id,
  532. root_project_id: data.rootProjectID
  533. };
  534. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  535. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  536. mixRatios = JSON.stringify(mixRatios);
  537. mixRatios = JSON.parse(mixRatios);
  538. for(let m of mixRatios){
  539. delete m._id; // 删除原有id信息
  540. delete m.id;
  541. m.unit_price_file_id = data.id;
  542. m.id = await getCounterID('mix_ratio');
  543. mixRatioTask.push(m);
  544. }
  545. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  546. unitPrices = JSON.stringify(unitPrices);
  547. unitPrices = JSON.parse(unitPrices);
  548. for(let u of unitPrices){
  549. delete u._id; // 删除原有id信息
  550. delete u.id;
  551. u.unit_price_file_id = data.id;
  552. u.id = await getCounterID('unit_price');
  553. unitPriceTask.push(u);
  554. }
  555. }
  556. }
  557. async function getCounterID(collectionName){
  558. let counterModel = new CounterModel();
  559. return await counterModel.getId(collectionName);
  560. }
  561. async function insertMany(datas,model) {
  562. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  563. let newList = datas.splice(0,1000);//一次插入1000条
  564. await model.insertMany(newList);
  565. }
  566. await model.insertMany(datas);
  567. }
  568. function setProperty(Obj,updateData) {
  569. for(let ukey in updateData){
  570. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  571. setProperty(Obj[ukey],updateData[ukey]);
  572. }else {
  573. Obj[ukey] = updateData[ukey];
  574. }
  575. }
  576. }
  577. function isDef(v){
  578. return typeof v !== 'undefined' && v !== null;
  579. }
  580. function getTotalFee(bills, feeName) {
  581. if(!isDef(bills)){
  582. return 0;
  583. }
  584. if(!isDef(bills.fees) || bills.fees.length <= 0){
  585. return 0;
  586. }
  587. for(let fee of bills.fees){
  588. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  589. return isDef(fee.totalFee) ? fee.totalFee : 0;
  590. }
  591. }
  592. return 0;
  593. }
  594. function summarizeToParent(parent, child, fields = null) {
  595. const decimal = -2;
  596. if (!fields) {
  597. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  598. }
  599. for (let field of fields) {
  600. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  601. }
  602. /* const decimal = -2;
  603. parent.engineeringCost = scMathUtil.roundTo(parseFloat(parent.engineeringCost) + parseFloat(child.engineeringCost), decimal);
  604. parent.subEngineering = scMathUtil.roundTo(parseFloat(parent.subEngineering) + parseFloat(child.subEngineering), decimal);
  605. parent.measure = scMathUtil.roundTo(parseFloat(parent.measure) + parseFloat(child.measure), decimal);
  606. parent.safetyConstruction = scMathUtil.roundTo(parseFloat(parent.safetyConstruction) + parseFloat(child.safetyConstruction), decimal);
  607. parent.other = scMathUtil.roundTo(parseFloat(parent.other) + parseFloat(child.other), decimal);
  608. parent.charge = scMathUtil.roundTo(parseFloat(parent.charge) + parseFloat(child.charge), decimal);
  609. parent.tax = scMathUtil.roundTo(parseFloat(parent.tax) + parseFloat(child.tax), decimal);*/
  610. }
  611. function getBuildingArea(projFeature){
  612. if(!projFeature || projFeature.length === 0){
  613. return null;
  614. }
  615. for(let f of projFeature){
  616. if(f.key === 'buildingArea'){
  617. return f.value;
  618. }
  619. }
  620. return null;
  621. }
  622. //根据单位工程ID获取汇总信息
  623. //@param {Number}tenderID {String}summaryType @return {Object}
  624. async function getSummaryInfoByTender(tenderID, summaryType) {
  625. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  626. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  627. let parent,
  628. parentName,
  629. compilationIllustration;
  630. let summaryList = [];
  631. if(!tender){
  632. return null;
  633. }
  634. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  635. if(!engineering){
  636. return null;
  637. }
  638. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  639. if(!project){
  640. return null;
  641. }
  642. let summaryInfo = await getSummaryInfo([project.ID]);
  643. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  644. parent = engineering;
  645. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted});
  646. for(let t of tenders){
  647. if(summaryInfo[t.ID]){
  648. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  649. summaryList.push(summaryInfo[t.ID]);
  650. }
  651. }
  652. } else { // 汇总到建设项目级别
  653. parent = project;
  654. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted});
  655. for(let e of engs){
  656. if(summaryInfo[e.ID]){
  657. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  658. summaryList.push(summaryInfo[e.ID]);
  659. }
  660. }
  661. }
  662. // 项目名称
  663. parentName = parent && parent.name
  664. ? parent.name
  665. : '';
  666. // 编制说明
  667. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  668. ? parent.property.compilationIllustration
  669. : '';
  670. return {
  671. parent: {
  672. name: parentName,
  673. compilationIllustration: compilationIllustration},
  674. subList: summaryList
  675. };
  676. }
  677. //获取单位工程的各标段费用信息(不进行汇总)
  678. async function getTendersFeeInfo(tenders) {
  679. let IDMapping = {};
  680. //固定清单类别与汇总金额字段映射
  681. let flagFieldMapping = {};
  682. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  683. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  684. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  685. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  686. flagFieldMapping[billsFlags.OTHER] = 'other';
  687. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  688. flagFieldMapping[billsFlags.TAX] = 'tax';
  689. let tenderIDs = [];
  690. if(tenders.length > 0){
  691. for(let tender of tenders){
  692. tenderIDs.push(tender.ID);
  693. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  694. IDMapping[tender.ID]['buildingArea'] = '';
  695. }
  696. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  697. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  698. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  699. //获取单位工程汇总金额需要用到的所有清单
  700. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  701. '-_id projectID fees flags');
  702. //进行单位工程级别的汇总
  703. for(let bills of allBills){
  704. let billsFlag = bills.flags[0]['flag'];
  705. let costField = flagFieldMapping[billsFlag];
  706. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  707. //暂估合价(工程造价暂估合价)
  708. if (billsFlag === billsFlags.ENGINEERINGCOST){
  709. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  710. }
  711. }
  712. //占造价比例、单方造价
  713. for(let tender of tenders){
  714. let tenderInfo = IDMapping[tender.ID];
  715. tenderInfo.rate = '';
  716. //单方造价
  717. tenderInfo.perCost = '';
  718. }
  719. }
  720. return IDMapping;
  721. }
  722. async function getSummaryInfo(projectIDs, feeFields = null){
  723. function initFees(obj, feeFields) {
  724. for (let data of feeFields) {
  725. obj[data.v] = 0;
  726. }
  727. }
  728. if (!feeFields) {
  729. feeFields = [
  730. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  731. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  732. {k: billsFlags.MEASURE, v: 'measure'},
  733. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  734. {k: billsFlags.OTHER, v: 'other'},
  735. {k: billsFlags.CHARGE, v: 'charge'},
  736. {k: billsFlags.TAX, v: 'tax'}
  737. ];
  738. }
  739. //ID与汇总信息映射
  740. let IDMapping = {};
  741. //固定清单类别与汇总金额字段映射
  742. let flagFieldMapping = {};
  743. for (let data of feeFields) {
  744. flagFieldMapping[data.k] = data.v;
  745. }
  746. /*flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  747. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  748. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  749. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  750. flagFieldMapping[billsFlags.OTHER] = 'other';
  751. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  752. flagFieldMapping[billsFlags.TAX] = 'tax';*/
  753. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  754. //设置建设项目的总建筑面积
  755. for(let project of projects){
  756. let grossArea = '';
  757. if(project.property && project.property.basicInformation){
  758. for(let basicInfo of project.property.basicInformation){
  759. if(basicInfo.key === 'basicInfo'){
  760. for(let k of basicInfo.items){
  761. if(k.key === 'grossArea'){
  762. grossArea = k.value;
  763. }
  764. }
  765. }
  766. }
  767. }
  768. //IDMapping[project.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  769. IDMapping[project.ID] = {estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  770. initFees(IDMapping[project.ID], feeFields);
  771. console.log(IDMapping[project.ID]);
  772. }
  773. //单项工程
  774. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  775. //单位工程
  776. let tenders = [];
  777. let engIDs = [];
  778. for(let eng of engineerings){
  779. engIDs.push(eng.ID);
  780. //IDMapping[eng.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  781. IDMapping[eng.ID] = {estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  782. initFees(IDMapping[eng.ID], feeFields);
  783. }
  784. if(engIDs.length > 0){
  785. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  786. }
  787. let tenderIDs = [];
  788. if(tenders.length > 0){
  789. for(let tender of tenders){
  790. tenderIDs.push(tender.ID);
  791. /*IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, rate: 0, estimate: 0,
  792. buildingArea: '', perCost: '',changeMark:tender.changeMark,property:tender.property};*/
  793. IDMapping[tender.ID] = {rate: 0, estimate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  794. initFees(IDMapping[tender.ID], feeFields);
  795. let buildingArea = getBuildingArea(tender.property.projectFeature);
  796. if(buildingArea){
  797. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  798. }
  799. }
  800. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  801. /*let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  802. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];*/
  803. let needFlags = feeFields.map(data => data.k);
  804. //获取单位工程汇总金额需要用到的所有清单
  805. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  806. '-_id projectID fees flags');
  807. //进行单位工程级别的汇总
  808. for(let bills of allBills){
  809. let billsFlag = bills.flags[0]['flag'];
  810. let costField = flagFieldMapping[billsFlag];
  811. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  812. //暂估合价(工程造价暂估合价)
  813. if (billsFlag === billsFlags.ENGINEERINGCOST){
  814. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  815. }
  816. }
  817. let summaryFields = feeFields.map(data => data.v);
  818. summaryFields.push('estimate');
  819. //进行单项工程级别的汇总
  820. for(let tender of tenders){
  821. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  822. }
  823. //进行建设项目级别的汇总
  824. for(let eng of engineerings){
  825. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  826. }
  827. //占造价比例、单方造价
  828. const rateDecimal = -2;
  829. const perCostDecimal = -2;
  830. for(let tender of tenders){
  831. let tenderInfo = IDMapping[tender.ID];
  832. let engInfo = IDMapping[tender.ParentID];
  833. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  834. //单方造价
  835. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0 ?
  836. tenderInfo.buildingArea.toString().trim() : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  837. }
  838. for(let eng of engineerings){
  839. let engInfo = IDMapping[eng.ID];
  840. let projInfo = IDMapping[eng.ParentID];
  841. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  842. }
  843. //建设项目占造价比例及单方造价
  844. for(let project of projects){
  845. let projectInfo = IDMapping[project.ID];
  846. projectInfo.rate = 100;
  847. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0 ?
  848. projectInfo.buildingArea.toString().trim() : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  849. }
  850. }
  851. return IDMapping;
  852. }
  853. //根据项目ID获取所属建设项目
  854. //@param {Number}projectID @return {Object}
  855. async function getConstructionProject(projectID){
  856. function returnProject(project){
  857. if(!project || project.projType === projectType.folder){
  858. return null;
  859. }
  860. if(project.projType === projectType.project){
  861. return project;
  862. }
  863. }
  864. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  865. let returnV = returnProject(project);
  866. if(returnV !== undefined){
  867. return returnV;
  868. }
  869. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  870. returnV = returnProject(parent);
  871. if(returnV !== undefined){
  872. return returnV;
  873. }
  874. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  875. returnV = returnProject(grandParent);
  876. return returnV !== undefined ? returnV : null;
  877. }
  878. //获取单位工程完整目录结构
  879. //@param {Number}projectID @return {Arry}
  880. async function getFullPath(projectID) {
  881. let fullPath = [];
  882. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  883. if(project){
  884. fullPath.push(project.name);
  885. await getParent(project.ParentID);
  886. }
  887. fullPath = fullPath.reverse();
  888. return fullPath;
  889. async function getParent(ParentID) {
  890. if(ParentID != -1){
  891. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  892. if(parent){
  893. fullPath.push(parent.name);
  894. await getParent(parent.ParentID);
  895. }
  896. }
  897. }
  898. }
  899. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  900. async function getPosterityProjects(projectIDs) {
  901. let rst = [];
  902. async function getProjects(IDs) {
  903. if (IDs.length > 0) {
  904. let newIDs = [];
  905. let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
  906. for (let proj of projs) {
  907. rst.push(proj);
  908. newIDs.push(proj.ID);
  909. }
  910. await getProjects(newIDs);
  911. }
  912. }
  913. await getProjects(projectIDs);
  914. return rst;
  915. }
  916. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  917. //@param {String}userId {Object}tender @return {Object} || {null}
  918. async function getShareInfo(userId, project) {
  919. //与该用户相关的分享
  920. let shareList = [];
  921. while (project) {
  922. for(let shareData of project.shareInfo){
  923. if(shareData.userID === userId){
  924. shareList.push(shareData);
  925. break;
  926. }
  927. }
  928. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  929. }
  930. //获取最新分享
  931. shareList.sort(function (a, b) {
  932. let aV = Date.parse(a.shareDate),
  933. bV = Date.parse(b.shareDate);
  934. if (aV > bV) {
  935. return -1;
  936. } else if (aV < bV) {
  937. return 1;
  938. }
  939. return 0;
  940. });
  941. return shareList[0] || null;
  942. }
  943. //打开的单位工程是否是被分享的.
  944. async function isShare(userId, project){
  945. //判断是否是打开分享的项目,属于分享文件的子项也算
  946. while (project) {
  947. for(let shareData of project.shareInfo){
  948. if(shareData.userID === userId){
  949. return true;
  950. }
  951. }
  952. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  953. }
  954. return false;
  955. }
  956. //用户是否第一次进入费用定额
  957. async function isFirst(userId, compilationId) {
  958. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  959. let first = false;
  960. if (userData) {
  961. first = !_.find(userData.used_list, function (o) {
  962. return o.compilationId === compilationId;
  963. });;
  964. }
  965. return first;
  966. }
  967. //用户第一次进入费用定额的数据准备
  968. async function prepareInitialData(userId, compilation, example) {
  969. let first = await isFirst(userId, compilation);
  970. if (first) {
  971. await updateUsedList(userId, compilation);
  972. let prepareTask = [
  973. copyCompleRationSection(userId, compilation),
  974. copyCompleGljSection(userId, compilation)
  975. ];
  976. if (example && example.length > 0) {
  977. prepareTask.push(copyExample(userId, compilation, example));
  978. }
  979. await Promise.all(prepareTask);
  980. }
  981. }
  982. async function updateUsedList(userId, compilation) {
  983. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  984. }
  985. //拷贝补充定额章节树
  986. async function copyCompleRationSection(userId, compilationId) {
  987. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  988. }
  989. //拷贝补充人材机分类树
  990. async function copyCompleGljSection(userId, compilationId) {
  991. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  992. if (templateData.length > 0) {
  993. let insertDatas = [],
  994. uuidMapping = {};
  995. //将ID替换成UUID
  996. for (let temData of templateData) {
  997. uuidMapping[temData.ID] = uuidV1();
  998. }
  999. for(let temData of templateData) {
  1000. let insertD = {
  1001. userId: userId,
  1002. compilationId: compilationId,
  1003. Name: temData.Name,
  1004. ID: uuidMapping[temData.ID],
  1005. ParentID: uuidMapping[temData.ParentID] || -1,
  1006. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1007. };
  1008. insertDatas.push(insertD);
  1009. }
  1010. //插入数据
  1011. await compleGljSectionModel.insertMany(insertDatas);
  1012. }
  1013. }
  1014. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1015. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1016. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1017. for(let d of datas){
  1018. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1019. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1020. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1021. newFile = {id:newID,name:tem_file.name};
  1022. type = 0;
  1023. }
  1024. projectIDs.push({ID:d.projectID})
  1025. }
  1026. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1027. }
  1028. //获取费用定额绑定的基本信息库数据
  1029. async function getBasicInfo(compilationID, fileKind = null) {
  1030. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1031. if (!compilation) {
  1032. return null;
  1033. }
  1034. let billValuation = compilation.bill_valuation.find(function (data) {
  1035. return data.enable;
  1036. });
  1037. if (!billValuation) {
  1038. return null;
  1039. }
  1040. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1041. let engineering = engineerings.find(function (data) {
  1042. return data.info_lib && data.info_lib.length > 0;
  1043. });
  1044. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1045. return null;
  1046. }
  1047. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1048. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1049. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1050. let strMap = {
  1051. 1: 'tender', //投标
  1052. 2: 'bid', //招标
  1053. 3: 'control' //控制价
  1054. };
  1055. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1056. needfulData.forEach(nData => {
  1057. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1058. nData.items = needfulSub;
  1059. });
  1060. infoLib.info = needfulData;
  1061. }
  1062. return infoLib;
  1063. }
  1064. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1065. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1066. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1067. return null;
  1068. }
  1069. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1070. return featureLib;
  1071. }
  1072. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1073. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1074. async function getProjectByGranularity(tenderID, granularity, userID, versionName) {
  1075. const GRANULARITY = {
  1076. PROJECT: 1,
  1077. ENGINEERING: 2,
  1078. TENDER: 3
  1079. };
  1080. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}); //加上session的userID,防止tenderID被篡改过
  1081. if (!theTender) {
  1082. return null;
  1083. }
  1084. let theEngineering = await projectModel.findOne({ID: theTender.ParentID});
  1085. if (!theEngineering) {
  1086. return null;
  1087. }
  1088. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID});
  1089. if (!constructionProject) {
  1090. return null;
  1091. }
  1092. let engineerings;
  1093. if (granularity === GRANULARITY.PROJECT) {
  1094. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted});
  1095. for (let eng of engineerings) {
  1096. eng._doc.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted});
  1097. }
  1098. } else {
  1099. engineerings = [theEngineering];
  1100. if (granularity === GRANULARITY.ENGINEERING) {
  1101. theEngineering._doc.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted});
  1102. } else {
  1103. theEngineering._doc.children = [theTender];
  1104. }
  1105. }
  1106. constructionProject._doc.children = engineerings;
  1107. //获取汇总信息
  1108. let feeFields = [
  1109. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  1110. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  1111. {k: billsFlags.MEASURE, v: 'measure'},
  1112. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1113. {k: billsFlags.OTHER, v: 'other'},
  1114. {k: billsFlags.CHARGE, v: 'charge'},
  1115. {k: billsFlags.PROVISIONAL, v: 'provisional'},
  1116. {k: billsFlags.MATERIAL_PROVISIONAL, v: 'materialProvisional'},
  1117. {k: billsFlags.ENGINEERING_ESITIMATE, v: 'engineeringEstimate'},
  1118. {k: billsFlags.DAYWORK, v: 'daywork'},
  1119. {k: billsFlags.TURN_KEY_CONTRACT, v: 'turnKeyContract'},
  1120. {k: billsFlags.CLAIM_VISA, v: 'claimVisa'},
  1121. {k: billsFlags.TAX, v: 'tax'}
  1122. ];
  1123. constructionProject._doc.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields);
  1124. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1125. let product = await productModel.findOne({});
  1126. let company = product.company || '珠海纵横创新软件有限公司',
  1127. version = product.version || '';
  1128. constructionProject._doc.softInfo = `${company};${versionName};${version};${userID}`;
  1129. return constructionProject;
  1130. }
  1131. //获取项目数据占位ID
  1132. async function getProjectPlaceholder(data) {
  1133. let rst = {};
  1134. //项目本身数据
  1135. if (data.projectCount) {
  1136. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1137. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1138. }
  1139. //项目人材机数据
  1140. if (data.projectGLJCount) {
  1141. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1142. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1143. }
  1144. //组成物数据
  1145. if (data.ratioCount) {
  1146. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1147. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1148. }
  1149. //单价文件数据
  1150. if (data.unitPriceFileCount) {
  1151. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1152. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1153. }
  1154. //单价数据
  1155. if (data.unitPriceCount) {
  1156. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1157. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1158. }
  1159. return rst;
  1160. }
  1161. /*
  1162. * 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1163. * */
  1164. async function importProject(importObj, userID, compilationID) {
  1165. let toInsertProjects = [importObj]; //待新增项目数据
  1166. await setupProject(importObj);
  1167. //设置项目ID及相关数据
  1168. for (let curEng of importObj.engs) {
  1169. await setupProject(curEng);
  1170. toInsertProjects.push(curEng);
  1171. for (let curTender of curEng.tenders) {
  1172. await setupProject(curTender.tender);
  1173. //插入单位工程的详细数据
  1174. await importTenderDetail(curTender);
  1175. toInsertProjects.push(curTender.tender);
  1176. }
  1177. delete curEng.tenders;
  1178. }
  1179. delete importObj.engs;
  1180. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1181. let bulks = [];
  1182. //如果有前节点,更新前节点
  1183. if (importObj.preID !== -1) {
  1184. bulks.push({
  1185. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1186. });
  1187. }
  1188. for (let insertP of toInsertProjects) {
  1189. bulks.push({
  1190. insertOne: {document: insertP}
  1191. });
  1192. }
  1193. if (bulks.length > 0) {
  1194. await projectModel.bulkWrite(bulks);
  1195. }
  1196. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1197. //设置汇总字段
  1198. for(let proj of toInsertProjects){
  1199. let summaryProj = summaryInfo[proj.ID];
  1200. if(summaryProj){
  1201. proj.engineeringCost = summaryProj.engineeringCost;
  1202. proj.subEngineering = summaryProj.subEngineering;
  1203. proj.measure = summaryProj.measure;
  1204. proj.safetyConstruction = summaryProj.safetyConstruction;
  1205. proj.other = summaryProj.other;
  1206. proj.charge = summaryProj.charge;
  1207. proj.tax = summaryProj.tax;
  1208. proj.rate = summaryProj.rate;
  1209. proj.buildingArea = summaryProj.buildingArea;
  1210. proj.perCost = summaryProj.perCost;
  1211. }
  1212. }
  1213. return toInsertProjects;
  1214. //给项目数据设置一些需要的数据
  1215. async function setupProject(data) {
  1216. data.userID = userID;
  1217. data.compilation = compilationID;
  1218. data.fileVer = G_FILE_VER;
  1219. data.createDateTime = new Date();
  1220. if (data.projType === 'Project') {
  1221. await setupConstruct(data);
  1222. } else if (data.projType === 'Tender') {
  1223. await setupTender(data);
  1224. }
  1225. }
  1226. //给建设项目设置一些数据
  1227. async function setupConstruct(data) {
  1228. //更新基本信息, 按照key匹配
  1229. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1230. if (infoLib) {
  1231. //标准基本信息库的数据打平
  1232. let flatDatas = [];
  1233. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1234. data.basicInformation.forEach(importI => {
  1235. flatDatas.forEach(item => {
  1236. if (item.key === 'engineeringName') {
  1237. item.value = data.name;
  1238. } else if (item.key === 'fileKind') {
  1239. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1240. } else if (item.key === 'taxModel') {
  1241. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1242. }
  1243. if (item.key === importI.key) {
  1244. item.value = importI.value;
  1245. }
  1246. });
  1247. });
  1248. }
  1249. data.property.basicInformation = infoLib ? infoLib.info : [];
  1250. }
  1251. //给单位工程设置一些数据
  1252. async function setupTender(data) {
  1253. //小数位数
  1254. data.property.decimal = defaultDecimal;
  1255. //清单工程量精度
  1256. data.property.billsQuantityDecimal = billsQuantityDecimal;
  1257. //呈现选项
  1258. data.property.displaySetting = displaySetting;
  1259. data.property.billsCalcMode = 0;
  1260. data.property.zanguCalcMode = 0;
  1261. //计算选项
  1262. data.property.calcOptions = calcOptions;
  1263. //安装增加费
  1264. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1265. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1266. }
  1267. //锁定清单
  1268. data.property.lockBills = false;
  1269. //工料机单价调整系数
  1270. data.property.tenderSetting = tenderSetting;
  1271. //工程特征相关更新
  1272. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1273. if (featureLib) {
  1274. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1275. data.projectFeature.forEach(importF => {
  1276. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1277. if (matchData) {
  1278. matchData.value = importF.value;
  1279. }
  1280. });
  1281. //设置工程专业的值为费用标准的值..
  1282. featureLib.feature.forEach(f => {
  1283. if (f.key === 'engineering') {
  1284. f.value = data.property.feeStandardName;
  1285. }
  1286. });
  1287. }
  1288. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1289. }
  1290. }
  1291. //插入单位工程内部详细数据
  1292. async function importTenderDetail(tenderData) {
  1293. //单价文件
  1294. let upFile = {
  1295. id: tenderData.tender.property.unitPriceFile.id,
  1296. name: tenderData.tender.name,
  1297. project_id: tenderData.tender.ID,
  1298. user_id: tenderData.tender.userID,
  1299. root_project_id: tenderData.tender.property.rootProjectID
  1300. };
  1301. await unitPriceFileModel.create(upFile);
  1302. //费率文件
  1303. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1304. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1305. //人工系数文件
  1306. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1307. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1308. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1309. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1310. //列设置
  1311. let engineeringModel = new EngineeringLibModel();
  1312. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1313. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1314. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1315. //清单
  1316. if (tenderData.bills.length) {
  1317. await billsModel.insertMany(tenderData.bills);
  1318. }
  1319. //投标文件中,才会有下面这些数据
  1320. if (enterDetail(tenderData)) {
  1321. //匹配标准数据,更新一些标准数据
  1322. await setupStdData(tenderData);
  1323. let task = [];
  1324. //定额
  1325. if (tenderData.ration.length) {
  1326. task.push(rationModel.insertMany(tenderData.ration))
  1327. }
  1328. //定额人材机
  1329. if (tenderData.rationGLJ.length) {
  1330. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1331. }
  1332. //定额调整系数
  1333. if (tenderData.rationCoe.length) {
  1334. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1335. }
  1336. //项目人材机
  1337. if (tenderData.projectGLJ.length) {
  1338. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1339. }
  1340. //组成物
  1341. if (tenderData.mixRatio.length) {
  1342. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1343. }
  1344. //单价文件
  1345. if (tenderData.unitPrice.length) {
  1346. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1347. }
  1348. await Promise.all(task);
  1349. }
  1350. //继续处理定额等数据
  1351. function enterDetail(tenderData) {
  1352. return tenderData.ration.length ||
  1353. tenderData.rationGLJ.length ||
  1354. tenderData.projectGLJ.length ||
  1355. tenderData.mixRatio.length ||
  1356. tenderData.unitPrice.length;
  1357. }
  1358. }
  1359. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1360. async function setupStdData(tenderData) {
  1361. //获取标准定额数据 (定额子目的编码查找)
  1362. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1363. if (!matchRationCodes.length) {
  1364. return;
  1365. }
  1366. //限制在当前费用定额可用的定额库里查找
  1367. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1368. '-_id -rationAssList -rationCoeList -rationInstList');
  1369. //标准定额code - 映射
  1370. let stdRationCodeMap = {};
  1371. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1372. //获取标准人材机数据 (人材机汇总的编码查找)
  1373. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1374. if (!matchGLJCodes.length) {
  1375. return;
  1376. }
  1377. //限制在当前费用定额可用的人材机库里查找
  1378. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1379. '-_id -component -priceProperty');
  1380. //标准人材机code - 映射
  1381. let stdGLJCodeMap = {};
  1382. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1383. //更新定额数据
  1384. tenderData.ration.forEach(r => {
  1385. let stdRation = stdRationCodeMap[r.code];
  1386. if (stdRation) {
  1387. r.caption = stdRation.caption;
  1388. r.from = 'std';
  1389. r.libID = stdRation.rationRepId;
  1390. r.stdID = stdRation.ID;
  1391. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1392. r.content = stdRation.jobContent;
  1393. if (stdRation.feeType) {
  1394. r.programID = stdRation.feeType;
  1395. }
  1396. } else {
  1397. r.from = 'cpt';
  1398. r.prefix = '补';
  1399. }
  1400. });
  1401. //更新定额人材机数据
  1402. tenderData.rationGLJ.forEach(rGLJ => {
  1403. rGLJ.from = 'cpt';
  1404. //匹配定额
  1405. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1406. if (stdRation) {
  1407. //根据导入数据的定额人材机编码匹配人材机
  1408. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1409. if (stdGLJ) {
  1410. rGLJ.from = 'std';
  1411. rGLJ.GLJID = stdGLJ.ID;
  1412. rGLJ.type = stdGLJ.gljType;
  1413. rGLJ.shortName = stdGLJ.shortName;
  1414. rGLJ.repositoryId = stdGLJ.repositoryId;
  1415. rGLJ.model = stdGLJ.model;
  1416. rGLJ.adjCoe = stdGLJ.adjCoe;
  1417. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1418. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1419. if (stdRationGLJ) {
  1420. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1421. }
  1422. }
  1423. }
  1424. });
  1425. //更新人材机汇总数据
  1426. tenderData.projectGLJ.forEach(pGLJ => {
  1427. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1428. if (stdGLJ) {
  1429. pGLJ.glj_id = stdGLJ.ID;
  1430. pGLJ.model = stdGLJ.model;
  1431. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1432. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1433. let ratios = tenderData.mixRatio.filter(ratio =>
  1434. ratio.connect_key === keyStr);
  1435. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1436. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1437. }
  1438. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1439. }
  1440. });
  1441. //更新单价文件数据
  1442. tenderData.unitPrice.forEach(up => {
  1443. let stdGLJ = stdGLJCodeMap[up.original_code];
  1444. if (stdGLJ) {
  1445. up.glj_id = stdGLJ.ID;
  1446. up.type = stdGLJ.gljType;
  1447. up.short_name = stdGLJ.shortName;
  1448. }
  1449. });
  1450. //更新组成物数据
  1451. tenderData.mixRatio.forEach(ratio => {
  1452. let stdGLJ = stdGLJCodeMap[ratio.code];
  1453. if (stdGLJ) {
  1454. ratio.glj_id = stdGLJ.ID;
  1455. ratio.type = stdGLJ.gljType;
  1456. }
  1457. });
  1458. }