pm_facade.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  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 parentName;
  628. let summaryList = [];
  629. if(!tender){
  630. return null;
  631. }
  632. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  633. if(!engineering){
  634. return null;
  635. }
  636. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  637. if(!project){
  638. return null;
  639. }
  640. let summaryInfo = await getSummaryInfo([project.ID]);
  641. if(summaryType === projectType.engineering){
  642. parentName = engineering.name ? engineering.name : '';
  643. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted});
  644. for(let t of tenders){
  645. if(summaryInfo[t.ID]){
  646. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  647. summaryList.push(summaryInfo[t.ID]);
  648. }
  649. }
  650. }
  651. else {
  652. parentName = project.name ? project.name : '';
  653. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted});
  654. for(let e of engs){
  655. if(summaryInfo[e.ID]){
  656. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  657. summaryList.push(summaryInfo[e.ID]);
  658. }
  659. }
  660. }
  661. return {parent: {name: parentName}, subList: summaryList};
  662. }
  663. //获取单位工程的各标段费用信息(不进行汇总)
  664. async function getTendersFeeInfo(tenders) {
  665. let IDMapping = {};
  666. //固定清单类别与汇总金额字段映射
  667. let flagFieldMapping = {};
  668. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  669. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  670. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  671. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  672. flagFieldMapping[billsFlags.OTHER] = 'other';
  673. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  674. flagFieldMapping[billsFlags.TAX] = 'tax';
  675. let tenderIDs = [];
  676. if(tenders.length > 0){
  677. for(let tender of tenders){
  678. tenderIDs.push(tender.ID);
  679. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  680. IDMapping[tender.ID]['buildingArea'] = '';
  681. }
  682. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  683. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  684. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  685. //获取单位工程汇总金额需要用到的所有清单
  686. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  687. '-_id projectID fees flags');
  688. //进行单位工程级别的汇总
  689. for(let bills of allBills){
  690. let billsFlag = bills.flags[0]['flag'];
  691. let costField = flagFieldMapping[billsFlag];
  692. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  693. //暂估合价(工程造价暂估合价)
  694. if (billsFlag === billsFlags.ENGINEERINGCOST){
  695. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  696. }
  697. }
  698. //占造价比例、单方造价
  699. for(let tender of tenders){
  700. let tenderInfo = IDMapping[tender.ID];
  701. tenderInfo.rate = '';
  702. //单方造价
  703. tenderInfo.perCost = '';
  704. }
  705. }
  706. return IDMapping;
  707. }
  708. async function getSummaryInfo(projectIDs, feeFields = null){
  709. function initFees(obj, feeFields) {
  710. for (let data of feeFields) {
  711. obj[data.v] = 0;
  712. }
  713. }
  714. if (!feeFields) {
  715. feeFields = [
  716. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  717. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  718. {k: billsFlags.MEASURE, v: 'measure'},
  719. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  720. {k: billsFlags.OTHER, v: 'other'},
  721. {k: billsFlags.CHARGE, v: 'charge'},
  722. {k: billsFlags.TAX, v: 'tax'}
  723. ];
  724. }
  725. //ID与汇总信息映射
  726. let IDMapping = {};
  727. //固定清单类别与汇总金额字段映射
  728. let flagFieldMapping = {};
  729. for (let data of feeFields) {
  730. flagFieldMapping[data.k] = data.v;
  731. }
  732. /*flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  733. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  734. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  735. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  736. flagFieldMapping[billsFlags.OTHER] = 'other';
  737. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  738. flagFieldMapping[billsFlags.TAX] = 'tax';*/
  739. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  740. //设置建设项目的总建筑面积
  741. for(let project of projects){
  742. let grossArea = '';
  743. if(project.property && project.property.basicInformation){
  744. for(let basicInfo of project.property.basicInformation){
  745. if(basicInfo.key === 'basicInfo'){
  746. for(let k of basicInfo.items){
  747. if(k.key === 'grossArea'){
  748. grossArea = k.value;
  749. }
  750. }
  751. }
  752. }
  753. }
  754. //IDMapping[project.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  755. IDMapping[project.ID] = {estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  756. initFees(IDMapping[project.ID], feeFields);
  757. console.log(IDMapping[project.ID]);
  758. }
  759. //单项工程
  760. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  761. //单位工程
  762. let tenders = [];
  763. let engIDs = [];
  764. for(let eng of engineerings){
  765. engIDs.push(eng.ID);
  766. //IDMapping[eng.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  767. IDMapping[eng.ID] = {estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  768. initFees(IDMapping[eng.ID], feeFields);
  769. }
  770. if(engIDs.length > 0){
  771. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  772. }
  773. let tenderIDs = [];
  774. if(tenders.length > 0){
  775. for(let tender of tenders){
  776. tenderIDs.push(tender.ID);
  777. /*IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, rate: 0, estimate: 0,
  778. buildingArea: '', perCost: '',changeMark:tender.changeMark,property:tender.property};*/
  779. IDMapping[tender.ID] = {rate: 0, estimate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  780. initFees(IDMapping[tender.ID], feeFields);
  781. let buildingArea = getBuildingArea(tender.property.projectFeature);
  782. if(buildingArea){
  783. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  784. }
  785. }
  786. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  787. /*let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  788. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];*/
  789. let needFlags = feeFields.map(data => data.k);
  790. //获取单位工程汇总金额需要用到的所有清单
  791. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  792. '-_id projectID fees flags');
  793. //进行单位工程级别的汇总
  794. for(let bills of allBills){
  795. let billsFlag = bills.flags[0]['flag'];
  796. let costField = flagFieldMapping[billsFlag];
  797. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  798. //暂估合价(工程造价暂估合价)
  799. if (billsFlag === billsFlags.ENGINEERINGCOST){
  800. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  801. }
  802. }
  803. let summaryFields = feeFields.map(data => data.v);
  804. summaryFields.push('estimate');
  805. //进行单项工程级别的汇总
  806. for(let tender of tenders){
  807. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  808. }
  809. //进行建设项目级别的汇总
  810. for(let eng of engineerings){
  811. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  812. }
  813. //占造价比例、单方造价
  814. const rateDecimal = -2;
  815. const perCostDecimal = -2;
  816. for(let tender of tenders){
  817. let tenderInfo = IDMapping[tender.ID];
  818. let engInfo = IDMapping[tender.ParentID];
  819. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  820. //单方造价
  821. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0 ?
  822. tenderInfo.buildingArea.toString().trim() : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  823. }
  824. for(let eng of engineerings){
  825. let engInfo = IDMapping[eng.ID];
  826. let projInfo = IDMapping[eng.ParentID];
  827. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  828. }
  829. //建设项目占造价比例及单方造价
  830. for(let project of projects){
  831. let projectInfo = IDMapping[project.ID];
  832. projectInfo.rate = 100;
  833. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0 ?
  834. projectInfo.buildingArea.toString().trim() : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  835. }
  836. }
  837. return IDMapping;
  838. }
  839. //根据项目ID获取所属建设项目
  840. //@param {Number}projectID @return {Object}
  841. async function getConstructionProject(projectID){
  842. function returnProject(project){
  843. if(!project || project.projType === projectType.folder){
  844. return null;
  845. }
  846. if(project.projType === projectType.project){
  847. return project;
  848. }
  849. }
  850. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  851. let returnV = returnProject(project);
  852. if(returnV !== undefined){
  853. return returnV;
  854. }
  855. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  856. returnV = returnProject(parent);
  857. if(returnV !== undefined){
  858. return returnV;
  859. }
  860. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  861. returnV = returnProject(grandParent);
  862. return returnV !== undefined ? returnV : null;
  863. }
  864. //获取单位工程完整目录结构
  865. //@param {Number}projectID @return {Arry}
  866. async function getFullPath(projectID) {
  867. let fullPath = [];
  868. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  869. if(project){
  870. fullPath.push(project.name);
  871. await getParent(project.ParentID);
  872. }
  873. fullPath = fullPath.reverse();
  874. return fullPath;
  875. async function getParent(ParentID) {
  876. if(ParentID != -1){
  877. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  878. if(parent){
  879. fullPath.push(parent.name);
  880. await getParent(parent.ParentID);
  881. }
  882. }
  883. }
  884. }
  885. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  886. async function getPosterityProjects(projectIDs) {
  887. let rst = [];
  888. async function getProjects(IDs) {
  889. if (IDs.length > 0) {
  890. let newIDs = [];
  891. let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
  892. for (let proj of projs) {
  893. rst.push(proj);
  894. newIDs.push(proj.ID);
  895. }
  896. await getProjects(newIDs);
  897. }
  898. }
  899. await getProjects(projectIDs);
  900. return rst;
  901. }
  902. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  903. //@param {String}userId {Object}tender @return {Object} || {null}
  904. async function getShareInfo(userId, project) {
  905. //与该用户相关的分享
  906. let shareList = [];
  907. while (project) {
  908. for(let shareData of project.shareInfo){
  909. if(shareData.userID === userId){
  910. shareList.push(shareData);
  911. break;
  912. }
  913. }
  914. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  915. }
  916. //获取最新分享
  917. shareList.sort(function (a, b) {
  918. let aV = Date.parse(a.shareDate),
  919. bV = Date.parse(b.shareDate);
  920. if (aV > bV) {
  921. return -1;
  922. } else if (aV < bV) {
  923. return 1;
  924. }
  925. return 0;
  926. });
  927. return shareList[0] || null;
  928. }
  929. //打开的单位工程是否是被分享的.
  930. async function isShare(userId, project){
  931. //判断是否是打开分享的项目,属于分享文件的子项也算
  932. while (project) {
  933. for(let shareData of project.shareInfo){
  934. if(shareData.userID === userId){
  935. return true;
  936. }
  937. }
  938. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  939. }
  940. return false;
  941. }
  942. //用户是否第一次进入费用定额
  943. async function isFirst(userId, compilationId) {
  944. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  945. let first = false;
  946. if (userData) {
  947. first = !_.find(userData.used_list, function (o) {
  948. return o.compilationId === compilationId;
  949. });;
  950. }
  951. return first;
  952. }
  953. //用户第一次进入费用定额的数据准备
  954. async function prepareInitialData(userId, compilation, example) {
  955. let first = await isFirst(userId, compilation);
  956. if (first) {
  957. await updateUsedList(userId, compilation);
  958. let prepareTask = [
  959. copyCompleRationSection(userId, compilation),
  960. copyCompleGljSection(userId, compilation)
  961. ];
  962. if (example && example.length > 0) {
  963. prepareTask.push(copyExample(userId, compilation, example));
  964. }
  965. await Promise.all(prepareTask);
  966. }
  967. }
  968. async function updateUsedList(userId, compilation) {
  969. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  970. }
  971. //拷贝补充定额章节树
  972. async function copyCompleRationSection(userId, compilationId) {
  973. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  974. }
  975. //拷贝补充人材机分类树
  976. async function copyCompleGljSection(userId, compilationId) {
  977. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  978. if (templateData.length > 0) {
  979. let insertDatas = [],
  980. uuidMapping = {};
  981. //将ID替换成UUID
  982. for (let temData of templateData) {
  983. uuidMapping[temData.ID] = uuidV1();
  984. }
  985. for(let temData of templateData) {
  986. let insertD = {
  987. userId: userId,
  988. compilationId: compilationId,
  989. Name: temData.Name,
  990. ID: uuidMapping[temData.ID],
  991. ParentID: uuidMapping[temData.ParentID] || -1,
  992. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  993. };
  994. insertDatas.push(insertD);
  995. }
  996. //插入数据
  997. await compleGljSectionModel.insertMany(insertDatas);
  998. }
  999. }
  1000. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1001. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1002. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1003. for(let d of datas){
  1004. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1005. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1006. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1007. newFile = {id:newID,name:tem_file.name};
  1008. type = 0;
  1009. }
  1010. projectIDs.push({ID:d.projectID})
  1011. }
  1012. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1013. }
  1014. //获取费用定额绑定的基本信息库数据
  1015. async function getBasicInfo(compilationID, fileKind = null) {
  1016. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1017. if (!compilation) {
  1018. return null;
  1019. }
  1020. let billValuation = compilation.bill_valuation.find(function (data) {
  1021. return data.enable;
  1022. });
  1023. if (!billValuation) {
  1024. return null;
  1025. }
  1026. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1027. let engineering = engineerings.find(function (data) {
  1028. return data.info_lib && data.info_lib.length > 0;
  1029. });
  1030. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1031. return null;
  1032. }
  1033. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1034. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1035. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1036. let strMap = {
  1037. 1: 'tender', //投标
  1038. 2: 'bid', //招标
  1039. 3: 'control' //控制价
  1040. };
  1041. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1042. needfulData.forEach(nData => {
  1043. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1044. nData.items = needfulSub;
  1045. });
  1046. infoLib.info = needfulData;
  1047. }
  1048. return infoLib;
  1049. }
  1050. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1051. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1052. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1053. return null;
  1054. }
  1055. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1056. return featureLib;
  1057. }
  1058. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1059. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1060. async function getProjectByGranularity(tenderID, granularity, userID, versionName) {
  1061. const GRANULARITY = {
  1062. PROJECT: 1,
  1063. ENGINEERING: 2,
  1064. TENDER: 3
  1065. };
  1066. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}); //加上session的userID,防止tenderID被篡改过
  1067. if (!theTender) {
  1068. return null;
  1069. }
  1070. let theEngineering = await projectModel.findOne({ID: theTender.ParentID});
  1071. if (!theEngineering) {
  1072. return null;
  1073. }
  1074. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID});
  1075. if (!constructionProject) {
  1076. return null;
  1077. }
  1078. let engineerings;
  1079. if (granularity === GRANULARITY.PROJECT) {
  1080. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted});
  1081. for (let eng of engineerings) {
  1082. eng._doc.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted});
  1083. }
  1084. } else {
  1085. engineerings = [theEngineering];
  1086. if (granularity === GRANULARITY.ENGINEERING) {
  1087. theEngineering._doc.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted});
  1088. } else {
  1089. theEngineering._doc.children = [theTender];
  1090. }
  1091. }
  1092. constructionProject._doc.children = engineerings;
  1093. //获取汇总信息
  1094. let feeFields = [
  1095. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  1096. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  1097. {k: billsFlags.MEASURE, v: 'measure'},
  1098. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1099. {k: billsFlags.OTHER, v: 'other'},
  1100. {k: billsFlags.CHARGE, v: 'charge'},
  1101. {k: billsFlags.PROVISIONAL, v: 'provisional'},
  1102. {k: billsFlags.MATERIAL_PROVISIONAL, v: 'materialProvisional'},
  1103. {k: billsFlags.ENGINEERING_ESITIMATE, v: 'engineeringEstimate'},
  1104. {k: billsFlags.DAYWORK, v: 'daywork'},
  1105. {k: billsFlags.TURN_KEY_CONTRACT, v: 'turnKeyContract'},
  1106. {k: billsFlags.CLAIM_VISA, v: 'claimVisa'},
  1107. {k: billsFlags.TAX, v: 'tax'}
  1108. ];
  1109. constructionProject._doc.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields);
  1110. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1111. let product = await productModel.findOne({});
  1112. let company = product.company || '珠海纵横创新软件有限公司',
  1113. version = product.version || '';
  1114. constructionProject._doc.softInfo = `${company};${versionName};${version};${userID}`;
  1115. return constructionProject;
  1116. }
  1117. //获取项目数据占位ID
  1118. async function getProjectPlaceholder(data) {
  1119. let rst = {};
  1120. //项目本身数据
  1121. if (data.projectCount) {
  1122. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1123. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1124. }
  1125. //项目人材机数据
  1126. if (data.projectGLJCount) {
  1127. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1128. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1129. }
  1130. //组成物数据
  1131. if (data.ratioCount) {
  1132. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1133. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1134. }
  1135. //单价文件数据
  1136. if (data.unitPriceFileCount) {
  1137. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1138. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1139. }
  1140. //单价数据
  1141. if (data.unitPriceCount) {
  1142. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1143. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1144. }
  1145. return rst;
  1146. }
  1147. /*
  1148. * 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1149. * */
  1150. async function importProject(importObj, userID, compilationID) {
  1151. let toInsertProjects = [importObj]; //待新增项目数据
  1152. await setupProject(importObj);
  1153. //设置项目ID及相关数据
  1154. for (let curEng of importObj.engs) {
  1155. await setupProject(curEng);
  1156. toInsertProjects.push(curEng);
  1157. for (let curTender of curEng.tenders) {
  1158. await setupProject(curTender.tender);
  1159. //插入单位工程的详细数据
  1160. await importTenderDetail(curTender);
  1161. toInsertProjects.push(curTender.tender);
  1162. }
  1163. delete curEng.tenders;
  1164. }
  1165. delete importObj.engs;
  1166. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1167. let bulks = [];
  1168. //如果有前节点,更新前节点
  1169. if (importObj.preID !== -1) {
  1170. bulks.push({
  1171. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1172. });
  1173. }
  1174. for (let insertP of toInsertProjects) {
  1175. bulks.push({
  1176. insertOne: {document: insertP}
  1177. });
  1178. }
  1179. if (bulks.length > 0) {
  1180. await projectModel.bulkWrite(bulks);
  1181. }
  1182. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1183. //设置汇总字段
  1184. for(let proj of toInsertProjects){
  1185. let summaryProj = summaryInfo[proj.ID];
  1186. if(summaryProj){
  1187. proj.engineeringCost = summaryProj.engineeringCost;
  1188. proj.subEngineering = summaryProj.subEngineering;
  1189. proj.measure = summaryProj.measure;
  1190. proj.safetyConstruction = summaryProj.safetyConstruction;
  1191. proj.other = summaryProj.other;
  1192. proj.charge = summaryProj.charge;
  1193. proj.tax = summaryProj.tax;
  1194. proj.rate = summaryProj.rate;
  1195. proj.buildingArea = summaryProj.buildingArea;
  1196. proj.perCost = summaryProj.perCost;
  1197. }
  1198. }
  1199. return toInsertProjects;
  1200. //给项目数据设置一些需要的数据
  1201. async function setupProject(data) {
  1202. data.userID = userID;
  1203. data.compilation = compilationID;
  1204. data.fileVer = G_FILE_VER;
  1205. data.createDateTime = new Date();
  1206. if (data.projType === 'Project') {
  1207. await setupConstruct(data);
  1208. } else if (data.projType === 'Tender') {
  1209. await setupTender(data);
  1210. }
  1211. }
  1212. //给建设项目设置一些数据
  1213. async function setupConstruct(data) {
  1214. //更新基本信息, 按照key匹配
  1215. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1216. if (infoLib) {
  1217. //标准基本信息库的数据打平
  1218. let flatDatas = [];
  1219. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1220. data.basicInformation.forEach(importI => {
  1221. flatDatas.forEach(item => {
  1222. if (item.key === 'engineeringName') {
  1223. item.value = data.name;
  1224. } else if (item.key === 'fileKind') {
  1225. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1226. } else if (item.key === 'taxModel') {
  1227. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1228. }
  1229. if (item.key === importI.key) {
  1230. item.value = importI.value;
  1231. }
  1232. });
  1233. });
  1234. }
  1235. data.property.basicInformation = infoLib ? infoLib.info : [];
  1236. }
  1237. //给单位工程设置一些数据
  1238. async function setupTender(data) {
  1239. //小数位数
  1240. data.property.decimal = defaultDecimal;
  1241. //清单工程量精度
  1242. data.property.billsQuantityDecimal = billsQuantityDecimal;
  1243. //呈现选项
  1244. data.property.displaySetting = displaySetting;
  1245. data.property.billsCalcMode = 0;
  1246. data.property.zanguCalcMode = 0;
  1247. //计算选项
  1248. data.property.calcOptions = calcOptions;
  1249. //安装增加费
  1250. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1251. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1252. }
  1253. //锁定清单
  1254. data.property.lockBills = false;
  1255. //工料机单价调整系数
  1256. data.property.tenderSetting = tenderSetting;
  1257. //工程特征相关更新
  1258. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1259. if (featureLib) {
  1260. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1261. data.projectFeature.forEach(importF => {
  1262. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1263. if (matchData) {
  1264. matchData.value = importF.value;
  1265. }
  1266. });
  1267. //设置工程专业的值为费用标准的值..
  1268. featureLib.feature.forEach(f => {
  1269. if (f.key === 'engineering') {
  1270. f.value = data.property.feeStandardName;
  1271. }
  1272. });
  1273. }
  1274. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1275. }
  1276. }
  1277. //插入单位工程内部详细数据
  1278. async function importTenderDetail(tenderData) {
  1279. //单价文件
  1280. let upFile = {
  1281. id: tenderData.tender.property.unitPriceFile.id,
  1282. name: tenderData.tender.name,
  1283. project_id: tenderData.tender.ID,
  1284. user_id: tenderData.tender.userID,
  1285. root_project_id: tenderData.tender.property.rootProjectID
  1286. };
  1287. await unitPriceFileModel.create(upFile);
  1288. //费率文件
  1289. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1290. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1291. //人工系数文件
  1292. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1293. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1294. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1295. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1296. //列设置
  1297. let engineeringModel = new EngineeringLibModel();
  1298. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1299. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1300. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1301. //清单
  1302. if (tenderData.bills.length) {
  1303. await billsModel.insertMany(tenderData.bills);
  1304. }
  1305. //投标文件中,才会有下面这些数据
  1306. if (enterDetail(tenderData)) {
  1307. //匹配标准数据,更新一些标准数据
  1308. await setupStdData(tenderData);
  1309. let task = [];
  1310. //定额
  1311. if (tenderData.ration.length) {
  1312. task.push(rationModel.insertMany(tenderData.ration))
  1313. }
  1314. //定额人材机
  1315. if (tenderData.rationGLJ.length) {
  1316. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1317. }
  1318. //定额调整系数
  1319. if (tenderData.rationCoe.length) {
  1320. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1321. }
  1322. //项目人材机
  1323. if (tenderData.projectGLJ.length) {
  1324. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1325. }
  1326. //组成物
  1327. if (tenderData.mixRatio.length) {
  1328. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1329. }
  1330. //单价文件
  1331. if (tenderData.unitPrice.length) {
  1332. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1333. }
  1334. await Promise.all(task);
  1335. }
  1336. //继续处理定额等数据
  1337. function enterDetail(tenderData) {
  1338. return tenderData.ration.length ||
  1339. tenderData.rationGLJ.length ||
  1340. tenderData.projectGLJ.length ||
  1341. tenderData.mixRatio.length ||
  1342. tenderData.unitPrice.length;
  1343. }
  1344. }
  1345. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1346. async function setupStdData(tenderData) {
  1347. //获取标准定额数据 (定额子目的编码查找)
  1348. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1349. if (!matchRationCodes.length) {
  1350. return;
  1351. }
  1352. //限制在当前费用定额可用的定额库里查找
  1353. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1354. '-_id -rationAssList -rationCoeList -rationInstList');
  1355. //标准定额code - 映射
  1356. let stdRationCodeMap = {};
  1357. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1358. //获取标准人材机数据 (人材机汇总的编码查找)
  1359. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1360. if (!matchGLJCodes.length) {
  1361. return;
  1362. }
  1363. //限制在当前费用定额可用的人材机库里查找
  1364. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1365. '-_id -component -priceProperty');
  1366. //标准人材机code - 映射
  1367. let stdGLJCodeMap = {};
  1368. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1369. //更新定额数据
  1370. tenderData.ration.forEach(r => {
  1371. let stdRation = stdRationCodeMap[r.code];
  1372. if (stdRation) {
  1373. r.caption = stdRation.caption;
  1374. r.from = 'std';
  1375. r.libID = stdRation.rationRepId;
  1376. r.stdID = stdRation.ID;
  1377. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1378. r.content = stdRation.jobContent;
  1379. } else {
  1380. r.from = 'cpt';
  1381. r.prefix = '补';
  1382. }
  1383. });
  1384. //更新定额人材机数据
  1385. tenderData.rationGLJ.forEach(rGLJ => {
  1386. rGLJ.from = 'cpt';
  1387. //匹配定额
  1388. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1389. if (stdRation) {
  1390. //根据导入数据的定额人材机编码匹配人材机
  1391. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1392. if (stdGLJ) {
  1393. rGLJ.from = 'std';
  1394. rGLJ.GLJID = stdGLJ.ID;
  1395. rGLJ.type = stdGLJ.gljType;
  1396. rGLJ.shortName = stdGLJ.shortName;
  1397. rGLJ.repositoryId = stdGLJ.repositoryId;
  1398. rGLJ.model = stdGLJ.model;
  1399. rGLJ.adjCoe = stdGLJ.adjCoe;
  1400. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1401. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1402. if (stdRationGLJ) {
  1403. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1404. }
  1405. }
  1406. }
  1407. });
  1408. //更新人材机汇总数据
  1409. tenderData.projectGLJ.forEach(pGLJ => {
  1410. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1411. if (stdGLJ) {
  1412. pGLJ.glj_id = stdGLJ.ID;
  1413. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1414. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1415. let ratios = tenderData.mixRatio.filter(ratio =>
  1416. ratio.connect_key === keyStr);
  1417. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1418. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1419. }
  1420. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1421. }
  1422. });
  1423. //更新单价文件数据
  1424. tenderData.unitPrice.forEach(up => {
  1425. let stdGLJ = stdGLJCodeMap[up.original_code];
  1426. if (stdGLJ) {
  1427. up.glj_id = stdGLJ.ID;
  1428. up.type = stdGLJ.gljType;
  1429. up.short_name = stdGLJ.shortName;
  1430. }
  1431. });
  1432. //更新组成物数据
  1433. tenderData.mixRatio.forEach(ratio => {
  1434. let stdGLJ = stdGLJCodeMap[ratio.code];
  1435. if (stdGLJ) {
  1436. ratio.glj_id = stdGLJ.ID;
  1437. ratio.type = stdGLJ.gljType;
  1438. }
  1439. });
  1440. }