pm_facade.js 82 KB

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