pm_facade.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  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. getProjectFeature:getProjectFeature,
  21. getProgressiveInterval: getProgressiveInterval,
  22. projectType: projectType,
  23. getPosterityProjects: getPosterityProjects,
  24. isShare: isShare,
  25. isFirst: isFirst,
  26. getShareInfo: getShareInfo,
  27. prepareInitialData: prepareInitialData,
  28. changeFile:changeFile,
  29. checkFiles:checkFiles,
  30. copyForSectionError: copyForSectionError,
  31. exportProject:exportProject,
  32. importProject:importProject
  33. };
  34. let mongoose = require('mongoose');
  35. let _ = require("lodash");
  36. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  37. let glj_facade = require('../../glj/facade/glj_facade');
  38. let project_facade = require('../../main/facade/project_facade');
  39. let logger = require("../../../logs/log_helper").logger;
  40. const uuidV1 = require('uuid/v1');
  41. let projectModel = mongoose.model('projects');
  42. let projectSettingModel = mongoose.model('proj_setting');
  43. let billsModel = mongoose.model('bills');
  44. let rationModel = mongoose.model('ration');
  45. let gljListModel = mongoose.model("glj_list");
  46. let calcProgramsModel = mongoose.model('calc_programs');
  47. let labourCoesModel = mongoose.model('labour_coes');
  48. let feeRateModel = mongoose.model('fee_rates');
  49. let feeRateFileModel = mongoose.model('fee_rate_file');
  50. let unitPriceFileModel = mongoose.model("unit_price_file");
  51. let mixRatioModel = mongoose.model("mix_ratio");
  52. let freightModel = mongoose.model("freight_calc");
  53. let originalModel = mongoose.model("original_calc");
  54. let unitPriceModel = mongoose.model("unit_price");
  55. let installationFeeModel = mongoose.model("installation_fee");
  56. let rationGLJModel = mongoose.model('ration_glj');
  57. let rationCoeModel = mongoose.model('ration_coe');
  58. let rationInstallationModel = mongoose.model('ration_installation');
  59. let quantityDetailModel = mongoose.model('quantity_detail');
  60. let rationTemplateModel = mongoose.model('ration_template');
  61. let userModel = mongoose.model('user');
  62. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  63. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  64. let progressiveModel = mongoose.model('std_progressive_lib');
  65. let featureLibModel = mongoose.model("std_project_feature_lib");
  66. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  67. let counter = require('../../../public/counter/counter');
  68. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  69. let sectionTreeDao = new SectionTreeDao();
  70. import CounterModel from "../../glj/models/counter_model";
  71. import moment from 'moment';
  72. import billsFlags from '../../common/const/bills_fixed';
  73. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  74. let cipher = require('../../../public/cipher');
  75. const compilationModel = mongoose.model('compilation');
  76. //拷贝例题项目
  77. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  78. async function copyExample(userID, compilation, projIDs){
  79. let allProjs = [],
  80. IDMapping = {},
  81. projMapping = {};
  82. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  83. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted});
  84. if (parentExample.length === 0) {
  85. return false;
  86. }
  87. allProjs = allProjs.concat(parentExample);
  88. for (let i = 0; i < parentExample.length; i++) {
  89. let data = parentExample[i];
  90. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  91. return false;
  92. }
  93. //设置成顶节点,最后一个节点设置成末节
  94. data.ParentID = -1;
  95. if (i === parentExample.length - 1) {
  96. data.NextSiblingID = -1;
  97. }
  98. }
  99. //获取所有的子项目
  100. let posterityProjs = await getPosterityProjects(projIDs);
  101. allProjs = allProjs.concat(posterityProjs);
  102. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  103. //旧ID与新ID映射
  104. for (let i = 0; i < allProjs.length; i++) {
  105. let data = allProjs[i];
  106. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  107. IDMapping[data.ID] = newID;
  108. projMapping[newID] = data;
  109. }
  110. //return;
  111. //设置新的树结构数据
  112. let newDate = new Date(),
  113. parentBulks = [];
  114. for (let data of allProjs) {
  115. let orgID = data.ID;
  116. data.ID = IDMapping[data.ID];
  117. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  118. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  119. data.createDateTime = newDate;
  120. data.userID = userID;
  121. data.compilation = compilation;
  122. data.shareInfo = [];
  123. if (data.projType !== projectType.tender) {
  124. let newData = _.cloneDeep(data._doc);
  125. delete newData._id;
  126. // await projectModel.create(newData);
  127. parentBulks.push({insertOne: {document: newData}});
  128. } else {
  129. //拷贝单位工程
  130. let rootProjectID = projMapping[data.ParentID].ID;
  131. let projectMap = {
  132. copy: {
  133. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  134. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  135. }
  136. };
  137. await copyProject(userID, compilation, {projectMap}, data.ID);
  138. }
  139. }
  140. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  141. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  142. if (lastProj) {
  143. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  144. }
  145. //拷贝父级文件
  146. await projectModel.bulkWrite(parentBulks);
  147. return true;
  148. }
  149. async function copyProject(userID, compilationID,data,newProjectID = null) {
  150. let projectMap = data.projectMap;
  151. let originalID = projectMap['copy'].document.ID;
  152. if (!newProjectID) {
  153. newProjectID = await getCounterID("projects");
  154. }
  155. let newFeeName = null,newUnitName = null;
  156. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  157. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  158. let feeRateFileID = uuidV1();//新的费率文件ID
  159. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  160. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  161. if(!originalProject){
  162. throw new Error('没有找到对应的项目,复制失败!');
  163. }
  164. let property = originalProject.property;
  165. if(projectMap['copy'].document.property){//更新项目属性信息
  166. setProperty(property,projectMap['copy'].document.property);
  167. }
  168. let originalProperty = _.cloneDeep(property);
  169. projectMap['copy'].document.property = property;
  170. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  171. //费率文件、单价文件重名检查
  172. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  173. if(feeRate){//存在重名的文件
  174. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  175. projectMap['copy'].document.property.feeFile.name = newFeeName;
  176. }
  177. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  178. if(unitPriceFile){//存在重名的文件
  179. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '复制)';
  180. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  181. }
  182. //更新项目的属性;
  183. projectMap['copy'].document.ID = newProjectID;
  184. if(projectMap['copy'].document.property.calcProgramFile){
  185. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  186. }
  187. if(projectMap['copy'].document.property.labourCoeFile){
  188. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  189. }
  190. if(projectMap['copy'].document.property.feeFile){
  191. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  192. }
  193. if(projectMap['copy'].document.property.unitPriceFile){
  194. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  195. }
  196. projectMap['copy'].document.userID = userID;
  197. projectMap['copy'].document.compilation = compilationID;
  198. projectMap['copy'].document.createDateTime = new Date();
  199. //清单、定额ID生成任务
  200. let IDtasks = [
  201. createIDsAndReturn(originalID,billsModel),
  202. createIDsAndReturn(originalID,rationModel),
  203. getProjectGLJIDAndReturn(originalID,newProjectID)
  204. ];
  205. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  206. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  207. let copyTasks = [
  208. createProject(projectMap),
  209. copyProjectSetting(originalID,newProjectID),
  210. copyBills(newProjectID,billMap),
  211. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  212. copyProjectGLJ(projectGLJMap.datas),
  213. copyInstallFee(originalID,newProjectID),
  214. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  215. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  216. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  217. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  218. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel)
  219. ];
  220. if(originalProperty.calcProgramFile){
  221. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  222. }
  223. if(originalProperty.labourCoeFile){
  224. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  225. }
  226. if(originalProperty.feeFile){
  227. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  228. }
  229. if(originalProperty.unitPriceFile){
  230. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  231. }
  232. let p = await Promise.all(copyTasks);
  233. return p[0];
  234. }
  235. async function createIDsAndReturn(originalID,model) {
  236. let uuidMaping = {};//做ID映射
  237. let datas = [];
  238. let result = await model.find({"projectID": originalID}, '-_id');
  239. uuidMaping['-1'] = -1;
  240. //建立uuid-ID映射
  241. for(let d of result){
  242. uuidMaping[d.ID] = uuidV1();
  243. datas.push(d._doc);
  244. }
  245. return{uuidMaping:uuidMaping,datas:datas};
  246. }
  247. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  248. let IDMap = {};
  249. let datas = [];
  250. let result = await gljListModel.find({project_id:originalID}, '-_id');
  251. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  252. for(let i = 0; i < result.length; i++){
  253. let d = result[i];
  254. let newID = gljCount.sequence_value - (result.length - 1) + i;
  255. //let newID = await getCounterID("glj_list");
  256. IDMap[d.id] = newID;
  257. d._doc.project_id = newProjectID;
  258. d._doc.id = newID;
  259. datas.push(d._doc);
  260. }
  261. return{IDMap:IDMap,datas:datas};
  262. }
  263. async function createProject(projectMap) {//复制项目
  264. let tasks = [];
  265. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  266. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  267. }
  268. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  269. await projectModel.bulkWrite(tasks);
  270. return projectMap;
  271. }
  272. async function copyProjectSetting(originalID,newProjectID) {
  273. let result = null;
  274. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  275. if(setting){
  276. setting._doc.projectID =newProjectID;
  277. result = await projectSettingModel.create(setting._doc);
  278. }
  279. return result;
  280. }
  281. async function copyBills(newProjectID,billMap) {
  282. let uuidMaping = billMap.uuidMaping;//做ID映射
  283. for(let doc of billMap.datas){
  284. doc = getCopyBillDatas(doc,newProjectID,uuidMaping)
  285. }
  286. await insertMany(billMap.datas,billsModel);
  287. return billMap.datas;
  288. }
  289. function getCopyBillDatas(doc,newProjectID,uuidMaping) {
  290. doc.projectID = newProjectID;
  291. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  292. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  293. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  294. //对于有基数计算的节点,需要替换计算基数中引用的ID为新的ID
  295. if(doc.calcBase && doc.calcBase != ""){
  296. let idArr = scMathUtil.getFIDArr(doc.calcBase);
  297. for(let re of idArr){
  298. let oID = re.substr(1);//去掉开头的@字符
  299. if(!uuidMaping[oID]) continue;
  300. doc.calcBase = doc.calcBase.replace(new RegExp(oID, "g"),uuidMaping[oID]);
  301. }
  302. }
  303. return doc;
  304. }
  305. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  306. let uuidMaping = rationMap.uuidMaping;
  307. for(let doc of rationMap.datas){
  308. doc = getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap);
  309. }
  310. if(rationMap.datas.length > 0){
  311. await insertMany(rationMap.datas,rationModel);
  312. }
  313. return rationMap.datas;
  314. }
  315. function getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap){
  316. doc.projectID = newProjectID;
  317. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  318. if(doc.billsItemID){
  319. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  320. }
  321. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  322. //绑定定类型的工料机 项目工料机ID
  323. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  324. return doc;
  325. }
  326. async function copyProjectGLJ(gljList) {
  327. await insertMany(gljList,gljListModel);
  328. }
  329. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  330. let result = null;
  331. let file = await model.findOne({"ID": oldID}, '-_id');
  332. if(file){
  333. file._doc.ID = newID;
  334. file._doc.projectID =newProjectID;
  335. result = await model.create(file._doc);
  336. }
  337. return result;
  338. }
  339. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  340. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  341. let newFeeRateID = uuidV1();
  342. if(feeRate){
  343. feeRate._doc.ID = newFeeRateID;
  344. await feeRateModel.create(feeRate._doc);
  345. }
  346. if(feeRateFile){
  347. feeRateFile._doc.ID = feeRateFileID;
  348. newName?feeRateFile._doc.name = newName:'';
  349. feeRateFile._doc.userID = userID;
  350. feeRateFile._doc.rootProjectID = rootProjectID;
  351. feeRateFile._doc.feeRateID = newFeeRateID;
  352. await feeRateFileModel.create(feeRateFile._doc);
  353. }
  354. }
  355. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  356. let taskList = [
  357. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  358. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  359. copySubList(originaluUnitPriceFileID,unitPriceFileID,freightModel,true),
  360. copySubList(originaluUnitPriceFileID,unitPriceFileID,originalModel,true),
  361. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  362. ];
  363. return await Promise.all(taskList);
  364. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  365. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  366. if(unitPriceFile){
  367. unitPriceFile._doc.id = unitPriceFileID;
  368. newName?unitPriceFile._doc.name = newName:'';
  369. unitPriceFile._doc.project_id = newProjectID;
  370. unitPriceFile._doc.user_id = userID;
  371. unitPriceFile._doc.root_project_id = rootProjectID
  372. }
  373. await unitPriceFileModel.create(unitPriceFile._doc);
  374. }
  375. async function copySubList(srcFID,newFID,model,UUID=false) {
  376. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  377. let rList = [];
  378. for(let m of mList){
  379. m._doc.unit_price_file_id = newFID;
  380. UUID == true?m._doc.ID = uuidV1():m._doc.id = await getCounterID(model.modelName);
  381. rList.push(m._doc);
  382. }
  383. await insertMany(rList,model)
  384. }
  385. }
  386. async function copyInstallFee(originalPID,newProjectID) {
  387. let result = null;
  388. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  389. let newList = [];
  390. for(let i of installationFee ){
  391. i._doc.ID = uuidV1();
  392. i._doc.projectID = newProjectID;
  393. newList.push(i._doc);
  394. }
  395. if(newList.length >0){
  396. result = await installationFeeModel.insertMany(newList);
  397. }
  398. return result;
  399. }
  400. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费
  401. let subList = await model.find({projectID:originalPID}, '-_id');
  402. let newList =[];
  403. for(let s of subList){
  404. s._doc = getCopyRationSubData(s._doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  405. /* s._doc.ID = uuidV1();
  406. s._doc.projectID = newProjectID;
  407. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  408. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  409. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  410. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  411. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  412. for(let t of s._doc.templateList){
  413. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  414. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  415. }
  416. }*/
  417. newList.push(s._doc);
  418. }
  419. await insertMany(newList,model);
  420. }
  421. function getCopyRationSubData(doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap){
  422. doc.ID = uuidV1();
  423. doc.projectID = newProjectID;
  424. doc.rationID&&rationIDMap[doc.rationID]?doc.rationID = rationIDMap[doc.rationID]:'';
  425. doc.billID&&billIDMap[doc.billID]?doc.billID = billIDMap[doc.billID]:'';
  426. doc.billsItemID&&billIDMap[doc.billsItemID]?doc.billsItemID = billIDMap[doc.billsItemID]:'';
  427. doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  428. if(doc.templateList && doc.templateList.length > 0 ){
  429. for(let t of doc.templateList){
  430. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  431. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  432. }
  433. }
  434. return doc;
  435. }
  436. async function moveProject(data) {
  437. data = JSON.parse(data);
  438. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  439. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  440. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  441. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  442. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  443. for(let projectID in feeRateMap){
  444. let rename = feeRateMap[projectID].name;
  445. let feeRateID = feeRateMap[projectID].query.ID;
  446. let checkFee = _.find(feeRates,{'name':rename});
  447. let newID = feeRateID;
  448. if(checkFee){//说明费率名字已存在,需要重命名
  449. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  450. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  451. if(feeRateMap[projectID].action == 'move'){
  452. feeRateMap[projectID].update.name = rename;
  453. }
  454. }
  455. if(feeRateMap[projectID].action == 'copy'){
  456. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  457. feeRateMap[projectID].name = rename;
  458. feeRateMap[projectID].ID = newID;
  459. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  460. }
  461. if(!feeUniqMap[feeRateID]){
  462. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  463. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  464. }
  465. }
  466. }
  467. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  468. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  469. for(let projectID in unitPriceMap){
  470. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  471. let rename = unitPriceMap[projectID].name;
  472. let unitPriceID = unitPriceMap[projectID].query.id;
  473. let newID = unitPriceID;
  474. if(checkUn){//重名检查
  475. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  476. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  477. if(unitPriceMap[projectID].action =='move'){
  478. unitPriceMap[projectID].update.name = rename;
  479. }
  480. }
  481. if(unitPriceMap[projectID].action =='copy'){
  482. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  483. unitPriceMap[projectID].name = rename;
  484. unitPriceMap[projectID].id = newID;
  485. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  486. }
  487. if(!priceUniqMap[unitPriceID]){
  488. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  489. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  490. }
  491. }
  492. }
  493. if(!_.isEmpty(projectMap)){
  494. for(let projectID in projectMap){
  495. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  496. }
  497. }
  498. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  499. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  500. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  501. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  502. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  503. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  504. return projectMap;
  505. }
  506. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  507. if(data.action == 'move'){
  508. let task = {
  509. updateOne:{
  510. filter : data.query,
  511. update : data.update
  512. }
  513. };
  514. feeRateFileTask.push(task);
  515. }
  516. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  517. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  518. let newFeeRateID = uuidV1();
  519. let newFeeRate = {
  520. ID:newFeeRateID,
  521. rates:feeRate.rates
  522. };
  523. let newFeeRateFile = {
  524. ID:data.ID,
  525. rootProjectID:data.rootProjectID,
  526. userID:feeRateFile.userID,
  527. name:data.name,
  528. libID:feeRateFile.libID,
  529. libName:feeRateFile.libName,
  530. feeRateID:newFeeRateID
  531. };
  532. feeRateTask.push({insertOne :{document:newFeeRate}});
  533. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  534. }
  535. }
  536. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  537. if(data.action == 'move'){
  538. let task = {
  539. updateOne:{
  540. filter : data.query,
  541. update : data.update
  542. }
  543. };
  544. unitPriceFileTask.push(task);
  545. }
  546. if(data.action == 'copy'){
  547. let newUnitFile = {
  548. id:data.id,
  549. name: data.name,
  550. project_id:projectID,
  551. user_id:user_id,
  552. root_project_id: data.rootProjectID
  553. };
  554. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  555. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  556. mixRatios = JSON.stringify(mixRatios);
  557. mixRatios = JSON.parse(mixRatios);
  558. for(let m of mixRatios){
  559. delete m._id; // 删除原有id信息
  560. delete m.id;
  561. m.unit_price_file_id = data.id;
  562. m.id = await getCounterID('mix_ratio');
  563. mixRatioTask.push(m);
  564. }
  565. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  566. unitPrices = JSON.stringify(unitPrices);
  567. unitPrices = JSON.parse(unitPrices);
  568. for(let u of unitPrices){
  569. delete u._id; // 删除原有id信息
  570. delete u.id;
  571. u.unit_price_file_id = data.id;
  572. u.id = await getCounterID('unit_price');
  573. unitPriceTask.push(u);
  574. }
  575. }
  576. }
  577. async function getCounterID(collectionName){
  578. let counterModel = new CounterModel();
  579. return await counterModel.getId(collectionName);
  580. }
  581. async function insertMany(datas,model) {
  582. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  583. let newList = datas.splice(0,1000);//一次插入1000条
  584. await model.insertMany(newList);
  585. }
  586. await model.insertMany(datas);
  587. }
  588. function setProperty(Obj,updateData) {
  589. for(let ukey in updateData){
  590. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  591. setProperty(Obj[ukey],updateData[ukey]);
  592. }else {
  593. Obj[ukey] = updateData[ukey];
  594. }
  595. }
  596. }
  597. function isDef(v){
  598. return typeof v !== 'undefined' && v !== null;
  599. }
  600. function getCommonTotalFee(bills) {
  601. if(!isDef(bills)){
  602. return 0;
  603. }
  604. if(!isDef(bills.fees) || bills.fees.length <= 0){
  605. return 0;
  606. }
  607. for(let fee of bills.fees){
  608. if(isDef(fee.fieldName) && fee.fieldName === 'common'){
  609. return isDef(fee.totalFee) ? fee.totalFee : 0;
  610. }
  611. }
  612. return 0;
  613. }
  614. function summarizeToParent(parent, child) {
  615. const decimal = -2;
  616. let costFields = ['totalCost'];
  617. for (let field of costFields) {
  618. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  619. }
  620. }
  621. function getBuildingArea(projFeature){
  622. if(!projFeature || projFeature.length === 0){
  623. return null;
  624. }
  625. for(let f of projFeature){
  626. if(f.key === 'buildingArea'){
  627. return f.value;
  628. }
  629. }
  630. return null;
  631. }
  632. // 根据树结构数据排序
  633. function getSortedDataByTree(data) {
  634. // NextSiblingID-数据映射
  635. const mapping = {};
  636. data.forEach(item => {
  637. // 错误数据兼容处理
  638. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  639. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  640. if (!item.NextSiblingID) {
  641. item.NextSiblingID = -1;
  642. }
  643. mapping[item.NextSiblingID] = item;
  644. });
  645. let lastItem = data.find(item => +item.NextSiblingID === -1);
  646. if (!lastItem) {
  647. return data;
  648. }
  649. const rst = [lastItem];
  650. let preItem = mapping[lastItem.ID];
  651. while (preItem) {
  652. rst.unshift(preItem);
  653. preItem = mapping[preItem.ID];
  654. }
  655. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  656. return rst.length === data.length ? rst : data;
  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 parentName;
  664. let summaryList = [];
  665. if(!tender){
  666. return null;
  667. }
  668. let project = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  669. if(!project){
  670. return null;
  671. }
  672. let summaryInfo = await getSummaryInfo([project.ID]);
  673. // 汇总到建设项目层(没有单项工程层了)
  674. if (summaryType === projectType.project) {
  675. parentName = project.name ? project.name : '';
  676. let tenders = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  677. tenders = getSortedDataByTree(tenders);
  678. for(let t of tenders){
  679. if(summaryInfo[t.ID]){
  680. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  681. summaryList.push(summaryInfo[t.ID]);
  682. }
  683. }
  684. }
  685. return {parent: {name: parentName}, subList: summaryList};
  686. }
  687. //获取单位工程的各标段费用信息(不进行汇总)
  688. async function getTendersFeeInfo(tenders) {
  689. let IDMapping = {};
  690. //固定清单类别与汇总金额字段映射
  691. let flagFieldMapping = {};
  692. flagFieldMapping[billsFlags.TOTAL_COST] = 'totalCost';
  693. let tenderIDs = [];
  694. if(tenders.length > 0){
  695. for(let tender of tenders){
  696. tenderIDs.push(tender.ID);
  697. IDMapping[tender.ID] = {totalCost: 0};
  698. }
  699. //需要获取的清单固定类别综合合价:总造价
  700. let needFlags = [billsFlags.TOTAL_COST];
  701. //获取单位工程汇总金额需要用到的所有清单
  702. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  703. '-_id projectID fees flags');
  704. //进行单位工程级别的汇总
  705. for(let bills of allBills){
  706. let billsFlag = bills.flags[0]['flag'];
  707. let costField = flagFieldMapping[billsFlag];
  708. IDMapping[bills.projectID][costField] = getCommonTotalFee(bills);
  709. }
  710. }
  711. return IDMapping;
  712. }
  713. //@param {Array}projectIDs(建设项目ID) @return {Object}
  714. async function getSummaryInfo(projectIDs){
  715. //ID与汇总信息映射
  716. let IDMapping = {};
  717. //固定清单类别与汇总金额字段映射
  718. let flagFieldMapping = {};
  719. flagFieldMapping[billsFlags.TOTAL_COST] = 'totalCost';
  720. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  721. //设置建设项目的总建筑面积
  722. for(let project of projects){
  723. IDMapping[project.ID] = {totalCost: 0};
  724. }
  725. //单位工程
  726. let tenders = [];
  727. if(projectIDs.length > 0){
  728. tenders = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  729. }
  730. let tenderIDs = [];
  731. if(tenders.length > 0){
  732. for(let tender of tenders){
  733. tenderIDs.push(tender.ID);
  734. IDMapping[tender.ID] = {totalCost: 0, changeMark:tender.changeMark,property:tender.property};//property:tender.property
  735. }
  736. //需要获取的清单固定类别综合合价:总造价
  737. let needFlags = [billsFlags.TOTAL_COST];
  738. //获取单位工程汇总金额需要用到的所有清单
  739. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  740. '-_id projectID fees flags');
  741. //进行单位工程级别的汇总
  742. for(let bills of allBills){
  743. let billsFlag = bills.flags[0]['flag'];
  744. let costField = flagFieldMapping[billsFlag];
  745. IDMapping[bills.projectID][costField] = getCommonTotalFee(bills);
  746. }
  747. //进行建设项目级别的汇总
  748. for(let tender of tenders){
  749. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID]);
  750. }
  751. }
  752. return IDMapping;
  753. }
  754. //根据项目ID获取所属建设项目
  755. //@param {Number}projectID @return {Object}
  756. async function getConstructionProject(projectID){
  757. function returnProject(project){
  758. if(!project || project.projType === projectType.folder){
  759. return null;
  760. }
  761. if(project.projType === projectType.project){
  762. return project;
  763. }
  764. }
  765. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  766. let returnV = returnProject(project);
  767. if(returnV !== undefined){
  768. return returnV;
  769. }
  770. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  771. returnV = returnProject(parent);
  772. if(returnV !== undefined){
  773. return returnV;
  774. }
  775. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  776. returnV = returnProject(grandParent);
  777. return returnV !== undefined ? returnV : null;
  778. }
  779. //获取单位工程完整目录结构
  780. //@param {Number}projectID @return {Arry}
  781. async function getFullPath(projectID) {
  782. let fullPath = [];
  783. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  784. if(project){
  785. fullPath.push(project.name);
  786. await getParent(project.ParentID);
  787. }
  788. fullPath = fullPath.reverse();
  789. return fullPath;
  790. async function getParent(ParentID) {
  791. if(ParentID != -1){
  792. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  793. if(parent){
  794. fullPath.push(parent.name);
  795. await getParent(parent.ParentID);
  796. }
  797. }
  798. }
  799. }
  800. //@param {String}libID(工程特征库ID) {Object}assign(需要赋值的key-value)
  801. async function getProjectFeature(libID, assign) {
  802. let lib = await featureLibModel.findOne({'ID':libID});
  803. if (lib) {
  804. for (let key in assign) {
  805. let obj = _.find(lib.feature, {key: key});
  806. if (obj) {
  807. obj.value = assign[key];
  808. }
  809. }
  810. return lib.feature;
  811. } else {
  812. return [];
  813. }
  814. }
  815. //获取累进区间数据
  816. async function getProgressiveInterval(libID) {
  817. let lib = await progressiveModel.findOne({ID: libID});
  818. return lib ? lib.data : [];
  819. }
  820. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  821. async function getPosterityProjects(projectIDs) {
  822. let rst = [];
  823. async function getProjects(IDs) {
  824. if (IDs.length > 0) {
  825. let newIDs = [];
  826. let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
  827. for (let proj of projs) {
  828. rst.push(proj);
  829. newIDs.push(proj.ID);
  830. }
  831. await getProjects(newIDs);
  832. }
  833. }
  834. await getProjects(projectIDs);
  835. return rst;
  836. }
  837. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  838. //@param {String}userId {Object}tender @return {Object} || {null}
  839. async function getShareInfo(userId, project) {
  840. //与该用户相关的分享
  841. let shareList = [];
  842. while (project) {
  843. for(let shareData of project.shareInfo){
  844. if(shareData.userID === userId){
  845. shareList.push(shareData);
  846. break;
  847. }
  848. }
  849. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  850. }
  851. //获取最新分享
  852. shareList.sort(function (a, b) {
  853. let aV = Date.parse(a.shareDate),
  854. bV = Date.parse(b.shareDate);
  855. if (aV > bV) {
  856. return -1;
  857. } else if (aV < bV) {
  858. return 1;
  859. }
  860. return 0;
  861. });
  862. return shareList[0] || null;
  863. }
  864. //打开的单位工程是否是被分享的.
  865. async function isShare(userId, project){
  866. //判断是否是打开分享的项目,属于分享文件的子项也算
  867. while (project) {
  868. for(let shareData of project.shareInfo){
  869. if(shareData.userID === userId){
  870. return true;
  871. }
  872. }
  873. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  874. }
  875. return false;
  876. }
  877. //用户是否第一次进入费用定额
  878. async function isFirst(userId, compilationId) {
  879. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  880. let isFirst = false;
  881. if (userData) {
  882. isFirst = !_.find(userData.used_list, function (o) {
  883. return o.compilationId === compilationId;
  884. });;
  885. }
  886. return isFirst;
  887. }
  888. //用户第一次进入费用定额的数据准备
  889. async function prepareInitialData(userId, compilation, example) {
  890. let first = await isFirst(userId, compilation);
  891. if (first) {
  892. await updateUsedList(userId, compilation);
  893. let prepareTask = [
  894. copyCompleRationSection(userId, compilation),
  895. copyCompleGljSection(userId, compilation)
  896. ];
  897. if (example && example.length > 0) {
  898. prepareTask.push(copyExample(userId, compilation, example));
  899. }
  900. await Promise.all(prepareTask);
  901. }
  902. }
  903. async function updateUsedList(userId, compilation) {
  904. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  905. }
  906. //拷贝补充定额章节树
  907. async function copyCompleRationSection(userId, compilationId) {
  908. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  909. }
  910. /*
  911. * 解决问题:
  912. * 发布了编办之后,才设置了人材机库模板,导致已登录的用户不存在人材机库的分类树
  913. * 为该编办下,人材机分类模板为空的用户,拷贝模板数据
  914. * */
  915. async function copyForSectionError(compilation) {
  916. let users = await userModel.find({}, '_id');
  917. for (let user of users) {
  918. let userId = user._id.toString();
  919. let existCount = await compleGljSectionModel.find({userId}).count();
  920. if (existCount === 0) {
  921. await copyCompleGljSection(userId, compilation);
  922. }
  923. }
  924. }
  925. //拷贝补充人材机分类树
  926. async function copyCompleGljSection(userId, compilationId) {
  927. const count = await compleGljSectionModel.count({userId, compilationId});
  928. if (count > 0) {
  929. return;
  930. }
  931. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  932. if (templateData.length > 0) {
  933. let insertDatas = [],
  934. uuidMapping = {};
  935. //将ID替换成UUID
  936. for (let temData of templateData) {
  937. uuidMapping[temData.ID] = uuidV1();
  938. }
  939. for(let temData of templateData) {
  940. let insertD = {
  941. userId: userId,
  942. compilationId: compilationId,
  943. Name: temData.Name,
  944. ID: uuidMapping[temData.ID],
  945. ParentID: uuidMapping[temData.ParentID] || -1,
  946. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  947. };
  948. insertDatas.push(insertD);
  949. }
  950. //插入数据
  951. await compleGljSectionModel.insertMany(insertDatas);
  952. }
  953. }
  954. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  955. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  956. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  957. for(let d of datas){
  958. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  959. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  960. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  961. newFile = {id:newID,name:tem_file.name};
  962. type = 0;
  963. }
  964. projectIDs.push({ID:d.projectID})
  965. }
  966. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  967. }
  968. async function exportProject(userID,data){//导出建设项目
  969. if(data.type == 'main'){
  970. return await exportMainData(userID,data.projectID);
  971. }else {
  972. return await exportTenderData(data);
  973. }
  974. }
  975. async function exportMainData(userID,projectID) {
  976. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  977. let tenderIDs = [];
  978. let project = await projectModel.findOne({ID:projectID});
  979. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  980. result['compilationID'] = project.compilation;
  981. result['from'] = "yanghu";
  982. result.projects.push(project);
  983. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  984. for(let s of subProjects){
  985. if(!s.deleteInfo || !s.deleteInfo.deleted){
  986. result.projects.push(s);
  987. if(s.projType =="Tender") tenderIDs.push(s.ID);
  988. }
  989. }
  990. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  991. result.files = files;
  992. result = cipher.aesEncrypt(JSON.stringify(result));
  993. result +="|----|" +JSON.stringify(tenderIDs);
  994. return result;
  995. }
  996. async function exportUnitFiles(rootProjectID){
  997. let unitFiles = [];
  998. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  999. for(let f of files){
  1000. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1001. let tem = {unitFile:f};
  1002. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1003. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1004. tem.freights = await freightModel.find({unit_price_file_id:f.id});
  1005. tem.originals = await originalModel.find({unit_price_file_id:f.id});
  1006. unitFiles.push(tem);
  1007. }
  1008. return unitFiles;
  1009. }
  1010. async function exportFeeRateFiles(rootProjectID) {
  1011. let feeRateFiles = [];
  1012. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1013. for(let f of files){
  1014. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1015. let tem = {feeRateFile:f};
  1016. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1017. feeRateFiles.push(tem);
  1018. }
  1019. return feeRateFiles;
  1020. }
  1021. async function exportTenderData(data){
  1022. let result = {};
  1023. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1024. if(projectSetting) result['projSetting'] = projectSetting;
  1025. result.bills = await billsModel.find({"projectID": data.projectID});
  1026. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1027. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1028. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1029. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1030. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1031. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1032. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1033. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1034. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1035. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1036. return cipher.aesEncrypt(JSON.stringify(result));
  1037. }
  1038. async function importProject(data,req,fields) {
  1039. let result = {error:0};
  1040. let stringArr = data.split("|----|");
  1041. let datas = [];
  1042. for(let s of stringArr){
  1043. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1044. }
  1045. let mainData = datas.length > 0 ?datas[0]:null;
  1046. if(mainData){
  1047. if(mainData.from && mainData.from != "yanghu"){
  1048. result.error = 1;
  1049. result.msg = "导入失败:您要导入的文件是由“大司空云计价”导出,当前软件是“纵横公路养护云版”,请选择正确的软件再进行操作!";
  1050. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  1051. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  1052. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的编制办法';
  1053. const curCompilationName = req.session.sessionCompilation.name;
  1054. result.error = 1;
  1055. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的编制办法再进行操作!`;
  1056. }else {
  1057. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,JSON.parse(fields.updateData[0]),req.session.sessionUser.id);
  1058. if(datas.length > 1 ){
  1059. for(let i = 1;i<datas.length;i++){
  1060. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1061. }
  1062. }
  1063. }
  1064. }
  1065. return result;
  1066. }
  1067. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1068. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[];
  1069. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1070. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1071. let newProjectID = projectIDMap[data.projSetting.projectID];
  1072. //生成新的清单;
  1073. if(data.bills && data.bills.length > 0){
  1074. for(let b of data.bills){
  1075. billsIDMap[b.ID] = uuidV1();
  1076. }
  1077. for(let b of data.bills){
  1078. delete b._id;
  1079. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1080. bills.push(b);
  1081. }
  1082. }
  1083. //生成项目工料机数据
  1084. if(data.projectGLJs && data.projectGLJs.length > 0){
  1085. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1086. for(let i = 0; i < data.projectGLJs.length; i++){
  1087. let d = data.projectGLJs[i];
  1088. delete d._id;
  1089. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1090. projectGLJIDMap[d.id] = newID;
  1091. d.project_id = newProjectID;
  1092. d.id = newID;
  1093. projectGLJs.push(d);
  1094. }
  1095. }
  1096. //生成新的定额
  1097. if(data.rations && data.rations.length > 0){
  1098. for(let r of data.rations){
  1099. rationIDMap[r.ID] = uuidV1();
  1100. }
  1101. for(let r of data.rations){
  1102. delete r._id;
  1103. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1104. rations.push(r);
  1105. }
  1106. }
  1107. //生成定额下挂的定额工料机等等数据
  1108. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1109. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1110. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1111. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1112. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1113. //生成projectSetting 文件
  1114. if(data.projSetting){
  1115. data.projSetting.projectID =newProjectID;
  1116. newProjectSetting = data.projSetting;
  1117. delete newProjectSetting._id;
  1118. }
  1119. //生成计算程序文件,系数文件
  1120. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  1121. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  1122. data.calcProgramsFile.projectID = newProjectID;
  1123. newCalcProgramsFile = data.calcProgramsFile;
  1124. delete newCalcProgramsFile._id;
  1125. }
  1126. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  1127. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  1128. data.labourCoes.projectID = newProjectID;
  1129. newLabourCoe = data.labourCoes;
  1130. delete newLabourCoe._id;
  1131. }
  1132. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  1133. if(bills.length > 0) await insertMany(bills,billsModel);
  1134. if(rations.length > 0) await insertMany(rations,rationModel);
  1135. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  1136. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  1137. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  1138. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  1139. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  1140. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  1141. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  1142. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  1143. }
  1144. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  1145. let arrs = [];
  1146. for(let d of datas){
  1147. delete d._id;
  1148. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  1149. arrs.push(d);
  1150. }
  1151. return arrs;
  1152. }
  1153. async function handleMainProjectDatas(mainData,updateData,userID) {
  1154. let mainProjectID = -1;
  1155. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  1156. let tasks = [];
  1157. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  1158. //生成新的projectID
  1159. for(let p of mainData.projects){
  1160. let newProjectID = await getCounterID("projects");
  1161. projectIDMap[p.ID] = newProjectID;
  1162. if(p.projType == "Project") mainProjectID = newProjectID;
  1163. if(p.projType == "Tender"){
  1164. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  1165. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  1166. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  1167. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  1168. }
  1169. }
  1170. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  1171. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  1172. for(let p of mainData.projects){
  1173. delete p._id;
  1174. delete p.__v;
  1175. p.ID = projectIDMap[p.ID];
  1176. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  1177. p.ParentID = updateData.self.ParentID;
  1178. p.NextSiblingID = updateData.self.NextSiblingID;
  1179. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  1180. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  1181. }
  1182. //查看是否重名;
  1183. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  1184. if(temp) p.name = p.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '导入)';
  1185. }else {
  1186. p.ParentID = projectIDMap[p.ParentID];
  1187. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  1188. }
  1189. p.userID =userID;
  1190. p.shareInfo=[];
  1191. if(p.projType == "Tender"){
  1192. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  1193. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  1194. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  1195. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  1196. p.property.rootProjectID = mainProjectID
  1197. }
  1198. tasks.push({insertOne: {document: p}})
  1199. }
  1200. //项目树节构数据生成:
  1201. await projectModel.bulkWrite(tasks);
  1202. //生成所有的费率文件
  1203. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  1204. //生成所有的单价文件
  1205. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  1206. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  1207. }
  1208. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  1209. if(!mainData.files.unitFiles) return;
  1210. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  1211. for(let f of mainData.files.unitFiles){
  1212. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  1213. //生成单价文件
  1214. delete file._id;
  1215. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  1216. file.project_id = projectIDMap[file.project_id];
  1217. file.root_project_id = projectIDMap[file.root_project_id];
  1218. file.user_id = userID;
  1219. unitFiles.push(file);
  1220. //生成子数据
  1221. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  1222. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  1223. if(fres) await setSubList(fres,freights,file.id,freightModel,true);
  1224. if(ors) await setSubList(ors,originals,file.id,originalModel,true);
  1225. }
  1226. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  1227. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  1228. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  1229. if(freights.length > 0) await insertMany(freights,freightModel);
  1230. if(originals.length > 0) await insertMany(originals,originalModel);
  1231. async function setSubList(oList,nList,fileID,model,UUID=false) {
  1232. for(let o of oList){
  1233. delete o._id;
  1234. o.unit_price_file_id = fileID;
  1235. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  1236. nList.push(o)
  1237. }
  1238. }
  1239. }
  1240. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  1241. let feeRateFiles = [], feeRates = [];
  1242. if(!mainData.files.feeRateFiles) return;
  1243. for(let f of mainData.files.feeRateFiles){
  1244. //生成费率记录
  1245. let rate = f.feeRate;
  1246. delete rate._id;
  1247. rate.ID = uuidV1();
  1248. feeRates.push(rate);
  1249. //生成费率文件记录
  1250. let file = f.feeRateFile;
  1251. delete file._id;
  1252. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  1253. file.userID = userID;
  1254. file.rootProjectID = projectIDMap[file.rootProjectID];
  1255. file.feeRateID = rate.ID;
  1256. feeRateFiles.push(file);
  1257. }
  1258. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  1259. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  1260. }
  1261. // 检查单价、费率文件,处理rootProjectID为-1的旧数据(以前的初始化例题bug造成)
  1262. async function checkFiles(projects) {
  1263. // fileID - tenderID 映射
  1264. const mapping = {};
  1265. const tenderItems = [];
  1266. const unitFileIDs = [];
  1267. const rateFileIDs = [];
  1268. const task = [];
  1269. projects.forEach(project => {
  1270. const isErrorRootProjectTender = project.projType === projectType.tender && project.property.rootProjectID === -1;
  1271. if (isErrorRootProjectTender) {
  1272. tenderItems.push({ ID: project.ID, ParentID: project.ParentID });
  1273. const priceFileID = project.property.unitPriceFile.id;
  1274. const feeFileID = project.property.feeFile.id;
  1275. if (!mapping[priceFileID]) {
  1276. mapping[priceFileID] = project;
  1277. unitFileIDs.push(priceFileID);
  1278. }
  1279. if (!mapping[feeFileID]) {
  1280. mapping[feeFileID] = project;
  1281. rateFileIDs.push(feeFileID);
  1282. }
  1283. }
  1284. });
  1285. // 检查是否存在rootProjectID为-1的
  1286. const errorUnitFiles = await unitPriceFileModel.find({id: {$in: unitFileIDs}, root_project_id: -1});
  1287. const errorRateFiles = await feeRateFileModel.find({ID: {$in: rateFileIDs}, rootProjectID: -1});
  1288. const unitFileTask = errorUnitFiles.map(file => {
  1289. const rootProjectID = mapping[file.id].ParentID;
  1290. return {
  1291. updateOne: {
  1292. filter: {id: file.id},
  1293. update: {$set: {root_project_id: rootProjectID}}
  1294. }
  1295. };
  1296. });
  1297. if (unitFileTask.length) {
  1298. task.push(unitPriceFileModel.bulkWrite(unitFileTask));
  1299. }
  1300. const rateFileTask = errorRateFiles.map(file => {
  1301. const rootProjectID = mapping[file.ID].ParentID;
  1302. return {
  1303. updateOne: {
  1304. filter: {ID: file.ID},
  1305. update: {$set: {rootProjectID: rootProjectID}}
  1306. }
  1307. };
  1308. });
  1309. if (rateFileTask.length) {
  1310. task.push(feeRateFileModel.bulkWrite(rateFileTask));
  1311. }
  1312. const tenderTask = tenderItems.map(item => {
  1313. return {
  1314. updateOne: {
  1315. filter: {ID: item.ID},
  1316. update: {$set: {'property.rootProjectID': item.ParentID}}
  1317. }
  1318. }
  1319. });
  1320. if (tenderTask.length) {
  1321. task.push(projectModel.bulkWrite(tenderTask));
  1322. }
  1323. await Promise.all(task);
  1324. }