pm_facade.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. };
  30. let mongoose = require('mongoose');
  31. let _ = require("lodash");
  32. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  33. let glj_facade = require('../../glj/facade/glj_facade');
  34. let project_facade = require('../../main/facade/project_facade');
  35. let logger = require("../../../logs/log_helper").logger;
  36. const uuidV1 = require('uuid/v1');
  37. let projectModel = mongoose.model('projects');
  38. let projectSettingModel = mongoose.model('proj_setting');
  39. let billsModel = mongoose.model('bills');
  40. let rationModel = mongoose.model('ration');
  41. let gljListModel = mongoose.model("glj_list");
  42. let calcProgramsModel = mongoose.model('calc_programs');
  43. let labourCoesModel = mongoose.model('labour_coes');
  44. let feeRateModel = mongoose.model('fee_rates');
  45. let feeRateFileModel = mongoose.model('fee_rate_file');
  46. let unitPriceFileModel = mongoose.model("unit_price_file");
  47. let mixRatioModel = mongoose.model("mix_ratio");
  48. let unitPriceModel = mongoose.model("unit_price");
  49. let installationFeeModel = mongoose.model("installation_fee");
  50. let rationGLJModel = mongoose.model('ration_glj');
  51. let rationCoeModel = mongoose.model('ration_coe');
  52. let rationInstallationModel = mongoose.model('ration_installation');
  53. let quantityDetailModel = mongoose.model('quantity_detail');
  54. let rationTemplateModel = mongoose.model('ration_template');
  55. let userModel = mongoose.model('user');
  56. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  57. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  58. let compilationModel = mongoose.model('compilation');
  59. let engineeringModel = mongoose.model('engineering_lib');
  60. let basicInfoModel = mongoose.model('std_basic_info_lib');
  61. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  62. let featureLibModel = mongoose.model("std_project_feature_lib");
  63. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  64. let counter = require('../../../public/counter/counter');
  65. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  66. let sectionTreeDao = new SectionTreeDao();
  67. import CounterModel from "../../glj/models/counter_model";
  68. import moment from 'moment';
  69. import billsFlags from '../../common/const/bills_fixed';
  70. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  71. //拷贝例题项目
  72. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  73. async function copyExample(userID, compilation, projIDs){
  74. let allProjs = [],
  75. IDMapping = {},
  76. projMapping = {};
  77. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  78. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted});
  79. if (parentExample.length === 0) {
  80. return false;
  81. }
  82. allProjs = allProjs.concat(parentExample);
  83. for (let i = 0; i < parentExample.length; i++) {
  84. let data = parentExample[i];
  85. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  86. return false;
  87. }
  88. //设置成顶节点,最后一个节点设置成末节
  89. data.ParentID = -1;
  90. if (i === parentExample.length - 1) {
  91. data.NextSiblingID = -1;
  92. }
  93. }
  94. //获取所有的子项目
  95. let posterityProjs = await getPosterityProjects(projIDs);
  96. allProjs = allProjs.concat(posterityProjs);
  97. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  98. //旧ID与新ID映射
  99. for (let i = 0; i < allProjs.length; i++) {
  100. let data = allProjs[i];
  101. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  102. IDMapping[data.ID] = newID;
  103. projMapping[newID] = data;
  104. }
  105. //return;
  106. //设置新的树结构数据
  107. let newDate = new Date(),
  108. parentBulks = [];
  109. for (let data of allProjs) {
  110. let orgID = data.ID;
  111. data.ID = IDMapping[data.ID];
  112. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  113. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  114. data.createDateTime = newDate;
  115. data.userID = userID;
  116. data.compilation = compilation;
  117. data.shareInfo = [];
  118. if (data.projType !== projectType.tender) {
  119. let newData = _.cloneDeep(data._doc);
  120. delete newData._id;
  121. // await projectModel.create(newData);
  122. parentBulks.push({insertOne: {document: newData}});
  123. } else {
  124. //拷贝单位工程
  125. let rootProjectID = projMapping[data.ParentID].ParentID;
  126. let projectMap = {
  127. copy: {
  128. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  129. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  130. }
  131. };
  132. await copyProject(userID, compilation, {projectMap}, data.ID);
  133. }
  134. }
  135. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  136. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  137. if (lastProj) {
  138. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  139. }
  140. //拷贝父级文件
  141. await projectModel.bulkWrite(parentBulks);
  142. return true;
  143. }
  144. async function copyProject(userID, compilationID,data,newProjectID = null) {
  145. let projectMap = data.projectMap;
  146. let originalID = projectMap['copy'].document.ID;
  147. if (!newProjectID) {
  148. newProjectID = await getCounterID("projects");
  149. }
  150. let newFeeName = null,newUnitName = null;
  151. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  152. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  153. let feeRateFileID = uuidV1();//新的费率文件ID
  154. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  155. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  156. if(!originalProject){
  157. throw new Error('没有找到对应的项目,复制失败!');
  158. }
  159. let property = originalProject.property;
  160. if(projectMap['copy'].document.property){//更新项目属性信息
  161. setProperty(property,projectMap['copy'].document.property);
  162. }
  163. let originalProperty = _.cloneDeep(property);
  164. projectMap['copy'].document.property = property;
  165. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  166. //费率文件、单价文件重名检查
  167. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  168. if(feeRate){//存在重名的文件
  169. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  170. projectMap['copy'].document.property.feeFile.name = newFeeName;
  171. }
  172. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  173. if(unitPriceFile){//存在重名的文件
  174. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  175. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  176. }
  177. //更新项目的属性;
  178. projectMap['copy'].document.ID = newProjectID;
  179. if(projectMap['copy'].document.property.calcProgramFile){
  180. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  181. }
  182. if(projectMap['copy'].document.property.labourCoeFile){
  183. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  184. }
  185. if(projectMap['copy'].document.property.feeFile){
  186. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  187. }
  188. if(projectMap['copy'].document.property.unitPriceFile){
  189. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  190. }
  191. projectMap['copy'].document.userID = userID;
  192. projectMap['copy'].document.compilation = compilationID;
  193. projectMap['copy'].document.createDateTime = new Date();
  194. //清单、定额ID生成任务
  195. let IDtasks = [
  196. createIDsAndReturn(originalID,billsModel),
  197. createIDsAndReturn(originalID,rationModel),
  198. getProjectGLJIDAndReturn(originalID,newProjectID)
  199. ];
  200. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  201. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  202. let copyTasks = [
  203. createProject(projectMap),
  204. copyProjectSetting(originalID,newProjectID),
  205. copyBills(newProjectID,billMap),
  206. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  207. copyProjectGLJ(projectGLJMap.datas),
  208. copyInstallFee(originalID,newProjectID),
  209. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  210. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  211. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  212. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  213. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel)
  214. ];
  215. if(originalProperty.calcProgramFile){
  216. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  217. }
  218. if(originalProperty.labourCoeFile){
  219. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  220. }
  221. if(originalProperty.feeFile){
  222. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  223. }
  224. if(originalProperty.unitPriceFile){
  225. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  226. }
  227. let p = await Promise.all(copyTasks);
  228. return p[0];
  229. }
  230. async function createIDsAndReturn(originalID,model) {
  231. let uuidMaping = {};//做ID映射
  232. let datas = [];
  233. let result = await model.find({"projectID": originalID}, '-_id');
  234. uuidMaping['-1'] = -1;
  235. //建立uuid-ID映射
  236. for(let d of result){
  237. uuidMaping[d.ID] = uuidV1();
  238. datas.push(d._doc);
  239. }
  240. return{uuidMaping:uuidMaping,datas:datas};
  241. }
  242. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  243. let IDMap = {};
  244. let datas = [];
  245. let result = await gljListModel.find({project_id:originalID}, '-_id');
  246. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  247. for(let i = 0; i < result.length; i++){
  248. let d = result[i];
  249. let newID = gljCount.sequence_value - (result.length - 1) + i;
  250. //let newID = await getCounterID("glj_list");
  251. IDMap[d.id] = newID;
  252. d._doc.project_id = newProjectID;
  253. d._doc.id = newID;
  254. datas.push(d._doc);
  255. }
  256. return{IDMap:IDMap,datas:datas};
  257. }
  258. async function createProject(projectMap) {//复制项目
  259. let tasks = [];
  260. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  261. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  262. }
  263. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  264. await projectModel.bulkWrite(tasks);
  265. return projectMap;
  266. }
  267. async function copyProjectSetting(originalID,newProjectID) {
  268. let result = null;
  269. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  270. if(setting){
  271. setting._doc.projectID =newProjectID;
  272. result = await projectSettingModel.create(setting._doc);
  273. }
  274. return result;
  275. }
  276. async function copyBills(newProjectID,billMap) {
  277. let uuidMaping = billMap.uuidMaping;//做ID映射
  278. for(let doc of billMap.datas){
  279. doc.projectID = newProjectID;
  280. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  281. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  282. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  283. }
  284. await insertMany(billMap.datas,billsModel);
  285. return billMap.datas;
  286. }
  287. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  288. let uuidMaping = rationMap.uuidMaping;
  289. for(let doc of rationMap.datas){
  290. doc.projectID = newProjectID;
  291. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  292. if(doc.billsItemID){
  293. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  294. }
  295. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  296. //绑定定类型的工料机 项目工料机ID
  297. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  298. }
  299. if(rationMap.datas.length > 0){
  300. await insertMany(rationMap.datas,rationModel);
  301. }
  302. return rationMap.datas;
  303. }
  304. async function copyProjectGLJ(gljList) {
  305. await insertMany(gljList,gljListModel);
  306. }
  307. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  308. let result = null;
  309. let file = await model.findOne({"ID": oldID}, '-_id');
  310. if(file){
  311. file._doc.ID = newID;
  312. file._doc.projectID =newProjectID;
  313. result = await model.create(file._doc);
  314. }
  315. return result;
  316. }
  317. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  318. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  319. let newFeeRateID = uuidV1();
  320. if(feeRate){
  321. feeRate._doc.ID = newFeeRateID;
  322. await feeRateModel.create(feeRate._doc);
  323. }
  324. if(feeRateFile){
  325. feeRateFile._doc.ID = feeRateFileID;
  326. newName?feeRateFile._doc.name = newName:'';
  327. feeRateFile._doc.userID = userID;
  328. feeRateFile._doc.rootProjectID = rootProjectID;
  329. feeRateFile._doc.feeRateID = newFeeRateID;
  330. await feeRateFileModel.create(feeRateFile._doc);
  331. }
  332. }
  333. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  334. let taskList = [
  335. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  336. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  337. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  338. ];
  339. return await Promise.all(taskList);
  340. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  341. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  342. if(unitPriceFile){
  343. unitPriceFile._doc.id = unitPriceFileID;
  344. newName?unitPriceFile._doc.name = newName:'';
  345. unitPriceFile._doc.project_id = newProjectID;
  346. unitPriceFile._doc.user_id = userID;
  347. unitPriceFile._doc.root_project_id = rootProjectID
  348. }
  349. await unitPriceFileModel.create(unitPriceFile._doc);
  350. }
  351. async function copySubList(srcFID,newFID,model) {
  352. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  353. let rList = [];
  354. for(let m of mList){
  355. m._doc.unit_price_file_id = newFID;
  356. m._doc.id = await getCounterID(model.modelName);
  357. rList.push(m._doc);
  358. }
  359. await insertMany(rList,model)
  360. }
  361. }
  362. async function copyInstallFee(originalPID,newProjectID) {
  363. let result = null;
  364. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  365. let newList = [];
  366. for(let i of installationFee ){
  367. i._doc.ID = uuidV1();
  368. i._doc.projectID = newProjectID;
  369. newList.push(i._doc);
  370. }
  371. if(newList.length >0){
  372. result = await installationFeeModel.insertMany(newList);
  373. }
  374. return result;
  375. }
  376. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  377. let subList = await model.find({projectID:originalPID}, '-_id');
  378. let newList =[];
  379. for(let s of subList){
  380. s._doc.ID = uuidV1();
  381. s._doc.projectID = newProjectID;
  382. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  383. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  384. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  385. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  386. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  387. for(let t of s._doc.templateList){
  388. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  389. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  390. }
  391. }
  392. newList.push(s._doc);
  393. }
  394. await insertMany(newList,model);
  395. }
  396. async function moveProject(data) {
  397. data = JSON.parse(data);
  398. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  399. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  400. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  401. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  402. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  403. for(let projectID in feeRateMap){
  404. let rename = feeRateMap[projectID].name;
  405. let feeRateID = feeRateMap[projectID].query.ID;
  406. let checkFee = _.find(feeRates,{'name':rename});
  407. let newID = feeRateID;
  408. if(checkFee){//说明费率名字已存在,需要重命名
  409. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  410. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  411. if(feeRateMap[projectID].action == 'move'){
  412. feeRateMap[projectID].update.name = rename;
  413. }
  414. }
  415. if(feeRateMap[projectID].action == 'copy'){
  416. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  417. feeRateMap[projectID].name = rename;
  418. feeRateMap[projectID].ID = newID;
  419. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  420. }
  421. if(!feeUniqMap[feeRateID]){
  422. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  423. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  424. }
  425. }
  426. }
  427. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  428. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  429. for(let projectID in unitPriceMap){
  430. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  431. let rename = unitPriceMap[projectID].name;
  432. let unitPriceID = unitPriceMap[projectID].query.id;
  433. let newID = unitPriceID;
  434. if(checkUn){//重名检查
  435. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  436. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  437. if(unitPriceMap[projectID].action =='move'){
  438. unitPriceMap[projectID].update.name = rename;
  439. }
  440. }
  441. if(unitPriceMap[projectID].action =='copy'){
  442. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  443. unitPriceMap[projectID].name = rename;
  444. unitPriceMap[projectID].id = newID;
  445. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  446. }
  447. if(!priceUniqMap[unitPriceID]){
  448. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  449. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  450. }
  451. }
  452. }
  453. if(!_.isEmpty(projectMap)){
  454. for(let projectID in projectMap){
  455. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  456. }
  457. }
  458. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  459. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  460. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  461. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  462. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  463. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  464. return projectMap;
  465. }
  466. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  467. if(data.action == 'move'){
  468. let task = {
  469. updateOne:{
  470. filter : data.query,
  471. update : data.update
  472. }
  473. };
  474. feeRateFileTask.push(task);
  475. }
  476. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  477. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  478. let newFeeRateID = uuidV1();
  479. let newFeeRate = {
  480. ID:newFeeRateID,
  481. rates:feeRate.rates
  482. };
  483. let newFeeRateFile = {
  484. ID:data.ID,
  485. rootProjectID:data.rootProjectID,
  486. userID:feeRateFile.userID,
  487. name:data.name,
  488. libID:feeRateFile.libID,
  489. libName:feeRateFile.libName,
  490. feeRateID:newFeeRateID
  491. };
  492. feeRateTask.push({insertOne :{document:newFeeRate}});
  493. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  494. }
  495. }
  496. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  497. if(data.action == 'move'){
  498. let task = {
  499. updateOne:{
  500. filter : data.query,
  501. update : data.update
  502. }
  503. };
  504. unitPriceFileTask.push(task);
  505. }
  506. if(data.action == 'copy'){
  507. let newUnitFile = {
  508. id:data.id,
  509. name: data.name,
  510. project_id:projectID,
  511. user_id:user_id,
  512. root_project_id: data.rootProjectID
  513. };
  514. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  515. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  516. mixRatios = JSON.stringify(mixRatios);
  517. mixRatios = JSON.parse(mixRatios);
  518. for(let m of mixRatios){
  519. delete m._id; // 删除原有id信息
  520. delete m.id;
  521. m.unit_price_file_id = data.id;
  522. m.id = await getCounterID('mix_ratio');
  523. mixRatioTask.push(m);
  524. }
  525. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  526. unitPrices = JSON.stringify(unitPrices);
  527. unitPrices = JSON.parse(unitPrices);
  528. for(let u of unitPrices){
  529. delete u._id; // 删除原有id信息
  530. delete u.id;
  531. u.unit_price_file_id = data.id;
  532. u.id = await getCounterID('unit_price');
  533. unitPriceTask.push(u);
  534. }
  535. }
  536. }
  537. async function getCounterID(collectionName){
  538. let counterModel = new CounterModel();
  539. return await counterModel.getId(collectionName);
  540. }
  541. async function insertMany(datas,model) {
  542. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  543. let newList = datas.splice(0,1000);//一次插入1000条
  544. await model.insertMany(newList);
  545. }
  546. await model.insertMany(datas);
  547. }
  548. function setProperty(Obj,updateData) {
  549. for(let ukey in updateData){
  550. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  551. setProperty(Obj[ukey],updateData[ukey]);
  552. }else {
  553. Obj[ukey] = updateData[ukey];
  554. }
  555. }
  556. }
  557. function isDef(v){
  558. return typeof v !== 'undefined' && v !== null;
  559. }
  560. function getTotalFee(bills, feeName) {
  561. if(!isDef(bills)){
  562. return 0;
  563. }
  564. if(!isDef(bills.fees) || bills.fees.length <= 0){
  565. return 0;
  566. }
  567. for(let fee of bills.fees){
  568. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  569. return isDef(fee.totalFee) ? fee.totalFee : 0;
  570. }
  571. }
  572. return 0;
  573. }
  574. function summarizeToParent(parent, child) {
  575. const decimal = -2;
  576. let costFields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  577. for (let field of costFields) {
  578. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  579. }
  580. /* const decimal = -2;
  581. parent.engineeringCost = scMathUtil.roundTo(parseFloat(parent.engineeringCost) + parseFloat(child.engineeringCost), decimal);
  582. parent.subEngineering = scMathUtil.roundTo(parseFloat(parent.subEngineering) + parseFloat(child.subEngineering), decimal);
  583. parent.measure = scMathUtil.roundTo(parseFloat(parent.measure) + parseFloat(child.measure), decimal);
  584. parent.safetyConstruction = scMathUtil.roundTo(parseFloat(parent.safetyConstruction) + parseFloat(child.safetyConstruction), decimal);
  585. parent.other = scMathUtil.roundTo(parseFloat(parent.other) + parseFloat(child.other), decimal);
  586. parent.charge = scMathUtil.roundTo(parseFloat(parent.charge) + parseFloat(child.charge), decimal);
  587. parent.tax = scMathUtil.roundTo(parseFloat(parent.tax) + parseFloat(child.tax), decimal);*/
  588. }
  589. function getBuildingArea(projFeature){
  590. if(!projFeature || projFeature.length === 0){
  591. return null;
  592. }
  593. for(let f of projFeature){
  594. if(f.key === 'buildingArea'){
  595. return f.value;
  596. }
  597. }
  598. return null;
  599. }
  600. //根据单位工程ID获取汇总信息
  601. //@param {Number}tenderID {String}summaryType @return {Object}
  602. async function getSummaryInfoByTender(tenderID, summaryType) {
  603. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  604. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  605. let parentName;
  606. let summaryList = [];
  607. if(!tender){
  608. return null;
  609. }
  610. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  611. if(!engineering){
  612. return null;
  613. }
  614. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  615. if(!project){
  616. return null;
  617. }
  618. let summaryInfo = await getSummaryInfo([project.ID]);
  619. if(summaryType === projectType.engineering){
  620. parentName = engineering.name ? engineering.name : '';
  621. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted});
  622. for(let t of tenders){
  623. if(summaryInfo[t.ID]){
  624. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  625. summaryList.push(summaryInfo[t.ID]);
  626. }
  627. }
  628. }
  629. else {
  630. parentName = project.name ? project.name : '';
  631. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted});
  632. for(let e of engs){
  633. if(summaryInfo[e.ID]){
  634. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  635. summaryList.push(summaryInfo[e.ID]);
  636. }
  637. }
  638. }
  639. return {parent: {name: parentName}, subList: summaryList};
  640. }
  641. //获取单位工程的各标段费用信息(不进行汇总)
  642. async function getTendersFeeInfo(tenders) {
  643. let IDMapping = {};
  644. //固定清单类别与汇总金额字段映射
  645. let flagFieldMapping = {};
  646. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  647. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  648. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  649. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  650. flagFieldMapping[billsFlags.OTHER] = 'other';
  651. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  652. flagFieldMapping[billsFlags.TAX] = 'tax';
  653. let tenderIDs = [];
  654. if(tenders.length > 0){
  655. for(let tender of tenders){
  656. tenderIDs.push(tender.ID);
  657. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  658. IDMapping[tender.ID]['buildingArea'] = '';
  659. }
  660. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  661. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  662. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  663. //获取单位工程汇总金额需要用到的所有清单
  664. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  665. '-_id projectID fees flags');
  666. //进行单位工程级别的汇总
  667. for(let bills of allBills){
  668. let billsFlag = bills.flags[0]['flag'];
  669. let costField = flagFieldMapping[billsFlag];
  670. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  671. //暂估合价(工程造价暂估合价)
  672. if (billsFlag === billsFlags.ENGINEERINGCOST){
  673. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  674. }
  675. }
  676. //占造价比例、单方造价
  677. for(let tender of tenders){
  678. let tenderInfo = IDMapping[tender.ID];
  679. tenderInfo.rate = '';
  680. //单方造价
  681. tenderInfo.perCost = '';
  682. }
  683. }
  684. return IDMapping;
  685. }
  686. async function getSummaryInfo(projectIDs){
  687. //ID与汇总信息映射
  688. let IDMapping = {};
  689. //固定清单类别与汇总金额字段映射
  690. let flagFieldMapping = {};
  691. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  692. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  693. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  694. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  695. flagFieldMapping[billsFlags.OTHER] = 'other';
  696. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  697. flagFieldMapping[billsFlags.TAX] = 'tax';
  698. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  699. //设置建设项目的总建筑面积
  700. for(let project of projects){
  701. let grossArea = '';
  702. if(project.property && project.property.basicInformation){
  703. for(let basicInfo of project.property.basicInformation){
  704. if(basicInfo.key === 'basicInfo'){
  705. for(let k of basicInfo.items){
  706. if(k.key === 'grossArea'){
  707. grossArea = k.value;
  708. }
  709. }
  710. }
  711. }
  712. }
  713. IDMapping[project.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  714. }
  715. //单项工程
  716. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  717. //单位工程
  718. let tenders = [];
  719. let engIDs = [];
  720. for(let eng of engineerings){
  721. engIDs.push(eng.ID);
  722. IDMapping[eng.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  723. }
  724. if(engIDs.length > 0){
  725. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  726. }
  727. let tenderIDs = [];
  728. if(tenders.length > 0){
  729. for(let tender of tenders){
  730. tenderIDs.push(tender.ID);
  731. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, rate: 0, estimate: 0,
  732. buildingArea: '', perCost: '',changeMark:tender.changeMark,property:tender.property};
  733. let buildingArea = getBuildingArea(tender.property.projectFeature);
  734. if(buildingArea){
  735. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  736. }
  737. }
  738. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  739. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  740. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  741. //获取单位工程汇总金额需要用到的所有清单
  742. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  743. '-_id projectID fees flags');
  744. //进行单位工程级别的汇总
  745. for(let bills of allBills){
  746. let billsFlag = bills.flags[0]['flag'];
  747. let costField = flagFieldMapping[billsFlag];
  748. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  749. //暂估合价(工程造价暂估合价)
  750. if (billsFlag === billsFlags.ENGINEERINGCOST){
  751. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  752. }
  753. }
  754. //进行单项工程级别的汇总
  755. for(let tender of tenders){
  756. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID]);
  757. }
  758. //进行建设项目级别的汇总
  759. for(let eng of engineerings){
  760. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID]);
  761. }
  762. //占造价比例、单方造价
  763. const rateDecimal = -2;
  764. const perCostDecimal = -2;
  765. for(let tender of tenders){
  766. let tenderInfo = IDMapping[tender.ID];
  767. let engInfo = IDMapping[tender.ParentID];
  768. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  769. //单方造价
  770. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0 ?
  771. tenderInfo.buildingArea.toString().trim() : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  772. }
  773. for(let eng of engineerings){
  774. let engInfo = IDMapping[eng.ID];
  775. let projInfo = IDMapping[eng.ParentID];
  776. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  777. }
  778. //建设项目占造价比例及单方造价
  779. for(let project of projects){
  780. let projectInfo = IDMapping[project.ID];
  781. projectInfo.rate = 100;
  782. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0 ?
  783. projectInfo.buildingArea.toString().trim() : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  784. }
  785. }
  786. return IDMapping;
  787. }
  788. //根据项目ID获取所属建设项目
  789. //@param {Number}projectID @return {Object}
  790. async function getConstructionProject(projectID){
  791. function returnProject(project){
  792. if(!project || project.projType === projectType.folder){
  793. return null;
  794. }
  795. if(project.projType === projectType.project){
  796. return project;
  797. }
  798. }
  799. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  800. let returnV = returnProject(project);
  801. if(returnV !== undefined){
  802. return returnV;
  803. }
  804. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  805. returnV = returnProject(parent);
  806. if(returnV !== undefined){
  807. return returnV;
  808. }
  809. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  810. returnV = returnProject(grandParent);
  811. return returnV !== undefined ? returnV : null;
  812. }
  813. //获取单位工程完整目录结构
  814. //@param {Number}projectID @return {Arry}
  815. async function getFullPath(projectID) {
  816. let fullPath = [];
  817. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  818. if(project){
  819. fullPath.push(project.name);
  820. await getParent(project.ParentID);
  821. }
  822. fullPath = fullPath.reverse();
  823. return fullPath;
  824. async function getParent(ParentID) {
  825. if(ParentID != -1){
  826. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  827. if(parent){
  828. fullPath.push(parent.name);
  829. await getParent(parent.ParentID);
  830. }
  831. }
  832. }
  833. }
  834. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  835. async function getPosterityProjects(projectIDs) {
  836. let rst = [];
  837. async function getProjects(IDs) {
  838. if (IDs.length > 0) {
  839. let newIDs = [];
  840. let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
  841. for (let proj of projs) {
  842. rst.push(proj);
  843. newIDs.push(proj.ID);
  844. }
  845. await getProjects(newIDs);
  846. }
  847. }
  848. await getProjects(projectIDs);
  849. return rst;
  850. }
  851. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  852. //@param {String}userId {Object}tender @return {Object} || {null}
  853. async function getShareInfo(userId, project) {
  854. //与该用户相关的分享
  855. let shareList = [];
  856. while (project) {
  857. for(let shareData of project.shareInfo){
  858. if(shareData.userID === userId){
  859. shareList.push(shareData);
  860. break;
  861. }
  862. }
  863. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  864. }
  865. //获取最新分享
  866. shareList.sort(function (a, b) {
  867. let aV = Date.parse(a.shareDate),
  868. bV = Date.parse(b.shareDate);
  869. if (aV > bV) {
  870. return -1;
  871. } else if (aV < bV) {
  872. return 1;
  873. }
  874. return 0;
  875. });
  876. return shareList[0] || null;
  877. }
  878. //打开的单位工程是否是被分享的.
  879. async function isShare(userId, project){
  880. //判断是否是打开分享的项目,属于分享文件的子项也算
  881. while (project) {
  882. for(let shareData of project.shareInfo){
  883. if(shareData.userID === userId){
  884. return true;
  885. }
  886. }
  887. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  888. }
  889. return false;
  890. }
  891. //用户是否第一次进入费用定额
  892. async function isFirst(userId, compilationId) {
  893. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  894. let first = false;
  895. if (userData) {
  896. first = !_.find(userData.used_list, function (o) {
  897. return o.compilationId === compilationId;
  898. });;
  899. }
  900. return first;
  901. }
  902. //用户第一次进入费用定额的数据准备
  903. async function prepareInitialData(userId, compilation, example) {
  904. let first = await isFirst(userId, compilation);
  905. if (first) {
  906. await updateUsedList(userId, compilation);
  907. let prepareTask = [
  908. copyCompleRationSection(userId, compilation),
  909. copyCompleGljSection(userId, compilation)
  910. ];
  911. if (example && example.length > 0) {
  912. prepareTask.push(copyExample(userId, compilation, example));
  913. }
  914. await Promise.all(prepareTask);
  915. }
  916. }
  917. async function updateUsedList(userId, compilation) {
  918. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  919. }
  920. //拷贝补充定额章节树
  921. async function copyCompleRationSection(userId, compilationId) {
  922. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  923. }
  924. //拷贝补充人材机分类树
  925. async function copyCompleGljSection(userId, compilationId) {
  926. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  927. if (templateData.length > 0) {
  928. let insertDatas = [],
  929. uuidMapping = {};
  930. //将ID替换成UUID
  931. for (let temData of templateData) {
  932. uuidMapping[temData.ID] = uuidV1();
  933. }
  934. for(let temData of templateData) {
  935. let insertD = {
  936. userId: userId,
  937. compilationId: compilationId,
  938. Name: temData.Name,
  939. ID: uuidMapping[temData.ID],
  940. ParentID: uuidMapping[temData.ParentID] || -1,
  941. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  942. };
  943. insertDatas.push(insertD);
  944. }
  945. //插入数据
  946. await compleGljSectionModel.insertMany(insertDatas);
  947. }
  948. }
  949. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  950. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  951. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  952. for(let d of datas){
  953. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  954. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  955. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  956. newFile = {id:newID,name:tem_file.name};
  957. type = 0;
  958. }
  959. projectIDs.push({ID:d.projectID})
  960. }
  961. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  962. }
  963. async function getBasicInfo(compilationID) {
  964. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  965. if (!compilation) {
  966. return null;
  967. }
  968. let billValuation = compilation.bill_valuation.find(function (data) {
  969. return data.enable;
  970. });
  971. if (!billValuation) {
  972. return null;
  973. }
  974. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  975. let engineering = engineerings.find(function (data) {
  976. return data.info_lib && data.info_lib.length > 0;
  977. });
  978. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  979. return null;
  980. }
  981. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  982. return infoLib;
  983. }
  984. async function getProjectFeature(valuationID, engineeringName, feeName) {
  985. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  986. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  987. return null;
  988. }
  989. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  990. return featureLib;
  991. }