pm_facade.js 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  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 = JSON.parse(JSON.stringify(defaultDecimal));
  1291. // 定额工程量、人材机消耗量精度设为最大6
  1292. data.property.decimal.ration.quantity = 6;
  1293. data.property.decimal.glj.quantity = 6;
  1294. //清单工程量精度 需要修改,所以深拷贝
  1295. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1296. // 清单工程量精度设置最大4
  1297. data.property.billsQuantityDecimal.forEach(data => data.decimal = 4);
  1298. //呈现选项
  1299. data.property.displaySetting = displaySetting;
  1300. data.property.billsCalcMode = 0;
  1301. data.property.zanguCalcMode = 0;
  1302. //计算选项
  1303. data.property.calcOptions = calcOptions;
  1304. //安装增加费
  1305. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1306. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1307. }
  1308. //锁定清单
  1309. data.property.lockBills = true;
  1310. //工料机单价调整系数
  1311. data.property.tenderSetting = tenderSetting;
  1312. //工程特征相关更新
  1313. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1314. if (featureLib) {
  1315. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1316. data.projectFeature.forEach(importF => {
  1317. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1318. if (matchData) {
  1319. matchData.value = importF.value;
  1320. }
  1321. });
  1322. //设置工程专业的值为费用标准的值..
  1323. featureLib.feature.forEach(f => {
  1324. if (f.key === 'engineering') {
  1325. f.value = data.property.feeStandardName;
  1326. }
  1327. });
  1328. }
  1329. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1330. }
  1331. }
  1332. //插入单位工程内部详细数据
  1333. async function importTenderDetail(tenderData) {
  1334. //单价文件
  1335. let upFile = {
  1336. id: tenderData.tender.property.unitPriceFile.id,
  1337. name: tenderData.tender.name,
  1338. project_id: tenderData.tender.ID,
  1339. user_id: tenderData.tender.userID,
  1340. root_project_id: tenderData.tender.property.rootProjectID
  1341. };
  1342. await unitPriceFileModel.create(upFile);
  1343. //费率文件
  1344. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1345. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1346. //人工系数文件
  1347. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1348. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1349. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1350. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1351. //列设置
  1352. let engineeringModel = new EngineeringLibModel();
  1353. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1354. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1355. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1356. //清单
  1357. if (tenderData.bills.length) {
  1358. await billsModel.insertMany(tenderData.bills);
  1359. }
  1360. //投标文件中,才会有下面这些数据
  1361. if (enterDetail(tenderData)) {
  1362. //匹配标准数据,更新一些标准数据
  1363. await setupStdData(tenderData);
  1364. let task = [];
  1365. //定额
  1366. if (tenderData.ration.length) {
  1367. task.push(rationModel.insertMany(tenderData.ration))
  1368. }
  1369. //定额人材机
  1370. if (tenderData.rationGLJ.length) {
  1371. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1372. }
  1373. //定额调整系数
  1374. if (tenderData.rationCoe.length) {
  1375. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1376. }
  1377. //项目人材机
  1378. if (tenderData.projectGLJ.length) {
  1379. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1380. }
  1381. //组成物
  1382. if (tenderData.mixRatio.length) {
  1383. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1384. }
  1385. //单价文件
  1386. if (tenderData.unitPrice.length) {
  1387. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1388. }
  1389. await Promise.all(task);
  1390. }
  1391. //继续处理定额等数据
  1392. function enterDetail(tenderData) {
  1393. return tenderData.ration.length ||
  1394. tenderData.rationGLJ.length ||
  1395. tenderData.projectGLJ.length ||
  1396. tenderData.mixRatio.length ||
  1397. tenderData.unitPrice.length;
  1398. }
  1399. }
  1400. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1401. async function setupStdData(tenderData) {
  1402. //获取标准定额数据 (定额子目的编码查找)
  1403. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1404. if (!matchRationCodes.length) {
  1405. return;
  1406. }
  1407. //限制在当前费用定额可用的定额库里查找
  1408. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1409. '-_id -rationAssList -rationCoeList -rationInstList');
  1410. //标准定额code - 映射
  1411. let stdRationCodeMap = {};
  1412. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1413. //获取标准人材机数据 (人材机汇总的编码查找)
  1414. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1415. if (!matchGLJCodes.length) {
  1416. return;
  1417. }
  1418. //限制在当前费用定额可用的人材机库里查找
  1419. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1420. '-_id -component -priceProperty');
  1421. //标准人材机code - 映射
  1422. let stdGLJCodeMap = {};
  1423. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1424. //更新定额数据
  1425. tenderData.ration.forEach(r => {
  1426. let stdRation = stdRationCodeMap[r.code];
  1427. if (stdRation) {
  1428. r.caption = stdRation.caption;
  1429. r.from = 'std';
  1430. r.libID = stdRation.rationRepId;
  1431. r.stdID = stdRation.ID;
  1432. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1433. r.content = stdRation.jobContent;
  1434. if (stdRation.feeType) {
  1435. r.programID = stdRation.feeType;
  1436. }
  1437. } else {
  1438. r.from = 'cpt';
  1439. r.prefix = '补';
  1440. }
  1441. });
  1442. //更新定额人材机数据
  1443. tenderData.rationGLJ.forEach(rGLJ => {
  1444. rGLJ.from = 'cpt';
  1445. //匹配定额
  1446. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1447. if (stdRation) {
  1448. //根据导入数据的定额人材机编码匹配人材机
  1449. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1450. if (stdGLJ) {
  1451. rGLJ.from = 'std';
  1452. rGLJ.GLJID = stdGLJ.ID;
  1453. rGLJ.type = stdGLJ.gljType;
  1454. rGLJ.shortName = stdGLJ.shortName;
  1455. rGLJ.repositoryId = stdGLJ.repositoryId;
  1456. rGLJ.model = stdGLJ.model;
  1457. rGLJ.adjCoe = stdGLJ.adjCoe;
  1458. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1459. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1460. if (stdRationGLJ) {
  1461. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1462. }
  1463. }
  1464. }
  1465. });
  1466. //更新人材机汇总数据
  1467. tenderData.projectGLJ.forEach(pGLJ => {
  1468. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1469. if (stdGLJ) {
  1470. pGLJ.glj_id = stdGLJ.ID;
  1471. pGLJ.model = stdGLJ.model;
  1472. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1473. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1474. let ratios = tenderData.mixRatio.filter(ratio =>
  1475. ratio.connect_key === keyStr);
  1476. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1477. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1478. }
  1479. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1480. }
  1481. });
  1482. //更新单价文件数据
  1483. tenderData.unitPrice.forEach(up => {
  1484. let stdGLJ = stdGLJCodeMap[up.original_code];
  1485. if (stdGLJ) {
  1486. up.glj_id = stdGLJ.ID;
  1487. up.type = stdGLJ.gljType;
  1488. up.short_name = stdGLJ.shortName;
  1489. }
  1490. });
  1491. //更新组成物数据
  1492. tenderData.mixRatio.forEach(ratio => {
  1493. let stdGLJ = stdGLJCodeMap[ratio.code];
  1494. if (stdGLJ) {
  1495. ratio.glj_id = stdGLJ.ID;
  1496. ratio.type = stdGLJ.gljType;
  1497. }
  1498. });
  1499. }
  1500. async function exportProject(userID,data){//导出建设项目
  1501. if(data.type == 'main'){
  1502. return await exportMainData(userID,data.projectID);
  1503. }else {
  1504. return await exportTenderData(data);
  1505. }
  1506. }
  1507. async function exportMainData(userID,projectID) {
  1508. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  1509. let tenderIDs = [];
  1510. let project = await projectModel.findOne({ID:projectID});
  1511. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  1512. result['compilationID'] = project.compilation;
  1513. result.projects.push(project);
  1514. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  1515. for(let s of subProjects){
  1516. if(!s.deleteInfo || !s.deleteInfo.deleted){
  1517. result.projects.push(s);
  1518. if(s.projType =="Tender") tenderIDs.push(s.ID);
  1519. }
  1520. }
  1521. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  1522. result.files = files;
  1523. result = cipher.aesEncrypt(JSON.stringify(result));
  1524. result +="|----|" +JSON.stringify(tenderIDs);
  1525. return result;
  1526. }
  1527. async function exportUnitFiles(rootProjectID){
  1528. let unitFiles = [];
  1529. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  1530. for(let f of files){
  1531. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1532. let tem = {unitFile:f};
  1533. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1534. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1535. unitFiles.push(tem);
  1536. }
  1537. return unitFiles;
  1538. }
  1539. async function exportFeeRateFiles(rootProjectID) {
  1540. let feeRateFiles = [];
  1541. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1542. for(let f of files){
  1543. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1544. let tem = {feeRateFile:f};
  1545. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1546. feeRateFiles.push(tem);
  1547. }
  1548. return feeRateFiles;
  1549. }
  1550. async function exportTenderData(data){
  1551. let result = {};
  1552. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1553. if(projectSetting) result['projSetting'] = projectSetting;
  1554. result.bills = await billsModel.find({"projectID": data.projectID});
  1555. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1556. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1557. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1558. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1559. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1560. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1561. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1562. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1563. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1564. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1565. return cipher.aesEncrypt(JSON.stringify(result));
  1566. }
  1567. async function importProjects(data,req,fields) {
  1568. let result = {error:0};
  1569. let stringArr = data.split("|----|");
  1570. let datas = [];
  1571. for(let s of stringArr){
  1572. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1573. }
  1574. let mainData = datas.length > 0 ?datas[0]:null;
  1575. if(mainData){
  1576. if(mainData.compilationID != req.session.sessionCompilation._id){
  1577. result.error = 1;
  1578. result.msg = "编办不同,无法导入,请重新选择!";
  1579. }else {
  1580. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,JSON.parse(fields.updateData[0]),req.session.sessionUser.id);
  1581. if(datas.length > 1 ){
  1582. for(let i = 1;i<datas.length;i++){
  1583. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1584. }
  1585. }
  1586. }
  1587. }
  1588. return result;
  1589. }
  1590. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1591. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[];
  1592. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1593. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1594. let newProjectID = projectIDMap[data.projSetting.projectID];
  1595. //生成新的清单;
  1596. if(data.bills && data.bills.length > 0){
  1597. for(let b of data.bills){
  1598. billsIDMap[b.ID] = uuidV1();
  1599. }
  1600. for(let b of data.bills){
  1601. delete b._id;
  1602. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1603. bills.push(b);
  1604. }
  1605. }
  1606. //生成项目工料机数据
  1607. if(data.projectGLJs && data.projectGLJs.length > 0){
  1608. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1609. for(let i = 0; i < data.projectGLJs.length; i++){
  1610. let d = data.projectGLJs[i];
  1611. delete d._id;
  1612. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1613. projectGLJIDMap[d.id] = newID;
  1614. d.project_id = newProjectID;
  1615. d.id = newID;
  1616. projectGLJs.push(d);
  1617. }
  1618. }
  1619. //生成新的定额
  1620. if(data.rations && data.rations.length > 0){
  1621. for(let r of data.rations){
  1622. rationIDMap[r.ID] = uuidV1();
  1623. }
  1624. for(let r of data.rations){
  1625. delete r._id;
  1626. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1627. rations.push(r);
  1628. }
  1629. }
  1630. //生成定额下挂的定额工料机等等数据
  1631. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1632. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1633. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1634. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1635. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1636. //生成projectSetting 文件
  1637. if(data.projSetting){
  1638. data.projSetting.projectID =newProjectID;
  1639. newProjectSetting = data.projSetting;
  1640. delete newProjectSetting._id;
  1641. }
  1642. //生成计算程序文件,系数文件
  1643. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  1644. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  1645. data.calcProgramsFile.projectID = newProjectID;
  1646. newCalcProgramsFile = data.calcProgramsFile;
  1647. delete newCalcProgramsFile._id;
  1648. }
  1649. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  1650. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  1651. data.labourCoes.projectID = newProjectID;
  1652. newLabourCoe = data.labourCoes;
  1653. delete newLabourCoe._id;
  1654. }
  1655. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  1656. if(bills.length > 0) await insertMany(bills,billsModel);
  1657. if(rations.length > 0) await insertMany(rations,rationModel);
  1658. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  1659. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  1660. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  1661. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  1662. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  1663. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  1664. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  1665. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  1666. }
  1667. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  1668. let arrs = [];
  1669. for(let d of datas){
  1670. delete d._id;
  1671. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  1672. arrs.push(d);
  1673. }
  1674. return arrs;
  1675. }
  1676. async function handleMainProjectDatas(mainData,updateData,userID) {
  1677. let mainProjectID = -1;
  1678. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  1679. let tasks = [];
  1680. //生成新的projectID
  1681. for(let p of mainData.projects){
  1682. let newProjectID = await getCounterID("projects");
  1683. projectIDMap[p.ID] = newProjectID;
  1684. if(p.projType == "Project") mainProjectID = newProjectID;
  1685. if(p.projType == "Tender"){
  1686. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  1687. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  1688. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  1689. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  1690. }
  1691. }
  1692. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  1693. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  1694. for(let p of mainData.projects){
  1695. delete p._id;
  1696. delete p.__v;
  1697. p.ID = projectIDMap[p.ID];
  1698. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  1699. p.ParentID = updateData.self.ParentID;
  1700. p.NextSiblingID = updateData.self.NextSiblingID;
  1701. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  1702. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  1703. }
  1704. //查看是否重名;
  1705. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  1706. if(temp) p.name = p.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '导入)';
  1707. }else {
  1708. p.ParentID = projectIDMap[p.ParentID];
  1709. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  1710. }
  1711. p.userID =userID;
  1712. p.shareInfo=[];
  1713. if(p.projType == "Tender"){
  1714. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  1715. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  1716. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  1717. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  1718. p.property.rootProjectID = mainProjectID
  1719. }
  1720. tasks.push({insertOne: {document: p}})
  1721. }
  1722. //项目树节构数据生成:
  1723. await projectModel.bulkWrite(tasks);
  1724. //生成所有的费率文件
  1725. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  1726. //生成所有的单价文件
  1727. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  1728. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  1729. }
  1730. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  1731. if(!mainData.files.unitFiles) return;
  1732. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  1733. for(let f of mainData.files.unitFiles){
  1734. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  1735. //生成单价文件
  1736. delete file._id;
  1737. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  1738. file.project_id = projectIDMap[file.project_id];
  1739. file.root_project_id = projectIDMap[file.root_project_id];
  1740. file.user_id = userID;
  1741. unitFiles.push(file);
  1742. //生成子数据
  1743. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  1744. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  1745. }
  1746. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  1747. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  1748. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  1749. async function setSubList(oList,nList,fileID,model,UUID=false) {
  1750. for(let o of oList){
  1751. delete o._id;
  1752. o.unit_price_file_id = fileID;
  1753. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  1754. nList.push(o)
  1755. }
  1756. }
  1757. }
  1758. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  1759. let feeRateFiles = [], feeRates = [];
  1760. if(!mainData.files.feeRateFiles) return;
  1761. for(let f of mainData.files.feeRateFiles){
  1762. //生成费率记录
  1763. let rate = f.feeRate;
  1764. delete rate._id;
  1765. rate.ID = uuidV1();
  1766. feeRates.push(rate);
  1767. //生成费率文件记录
  1768. let file = f.feeRateFile;
  1769. delete file._id;
  1770. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  1771. file.userID = userID;
  1772. file.rootProjectID = projectIDMap[file.rootProjectID];
  1773. file.feeRateID = rate.ID;
  1774. feeRateFiles.push(file);
  1775. }
  1776. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  1777. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  1778. }