pm_facade.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362
  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. prepareShareList,
  13. getShareList,
  14. addShareList,
  15. updateShareList,
  16. deleteShareList,
  17. getShareInfoMap,
  18. getRecentShareList,
  19. moveProject:moveProject,
  20. copyProject:copyProject,
  21. copyExample: copyExample,
  22. getSummaryInfo: getSummaryInfo,
  23. getSummaryInfoByTender: getSummaryInfoByTender,
  24. getIndexReportData: getIndexReportData,
  25. getTendersFeeInfo: getTendersFeeInfo,
  26. getConstructionProject: getConstructionProject,
  27. getFullPath: getFullPath,
  28. projectType: projectType,
  29. getPosterityProjects: getPosterityProjects,
  30. isShare: isShare,
  31. isFirst: isFirst,
  32. getShareInfo: getShareInfo,
  33. prepareInitialData: prepareInitialData,
  34. changeFile:changeFile,
  35. getBasicInfo: getBasicInfo,
  36. getProjectFeature: getProjectFeature,
  37. getProjectByGranularity: getProjectByGranularity,
  38. importProject: importProject,
  39. getProjectPlaceholder: getProjectPlaceholder,
  40. exportProject:exportProject,
  41. importProjects:importProjects,//建筑这里重名了,这比养护加多了个s
  42. initOverHeightItems: initOverHeightItems,
  43. uploadToken:uploadToken,
  44. downLoadProjectFile:downLoadProjectFile,
  45. importChongqingProject:importChongqingProject,
  46. importProcessChecking:importProcessChecking,
  47. importInterface,
  48. isTenderOverrun,
  49. getWelcomeInfo:getWelcomeInfo
  50. };
  51. let mongoose = require('mongoose');
  52. let _ = require("lodash");
  53. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  54. let glj_facade = require('../../glj/facade/glj_facade');
  55. let project_facade = require('../../main/facade/project_facade');
  56. let logger = require("../../../logs/log_helper").logger;
  57. const uuidV1 = require('uuid/v1');
  58. let projectModel = mongoose.model('projects');
  59. let projectSettingModel = mongoose.model('proj_setting');
  60. let billsModel = mongoose.model('bills');
  61. let rationModel = mongoose.model('ration');
  62. let gljListModel = mongoose.model("glj_list");
  63. let calcProgramsModel = mongoose.model('calc_programs');
  64. let labourCoesModel = mongoose.model('labour_coes');
  65. let feeRateModel = mongoose.model('fee_rates');
  66. let feeRateFileModel = mongoose.model('fee_rate_file');
  67. let unitPriceFileModel = mongoose.model("unit_price_file");
  68. let mixRatioModel = mongoose.model("mix_ratio");
  69. let unitPriceModel = mongoose.model("unit_price");
  70. let installationFeeModel = mongoose.model("installation_fee");
  71. let rationGLJModel = mongoose.model('ration_glj');
  72. let rationCoeModel = mongoose.model('ration_coe');
  73. let rationInstallationModel = mongoose.model('ration_installation');
  74. let quantityDetailModel = mongoose.model('quantity_detail');
  75. let rationTemplateModel = mongoose.model('ration_template');
  76. let userModel = mongoose.model('user');
  77. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  78. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  79. let compilationModel = mongoose.model('compilation');
  80. let engineeringModel = mongoose.model('engineering_lib');
  81. let basicInfoModel = mongoose.model('std_basic_info_lib');
  82. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  83. let productModel = mongoose.model('product');
  84. let stdRationItemModel = mongoose.model('std_ration_lib_ration_items');
  85. let stdGljItemModel = mongoose.model('std_glj_lib_gljList');
  86. import BillsTemplateModel from "../models/templates/bills_template_model";
  87. let evaluateListModel = mongoose.model("evaluate_list");
  88. let bidListModel = mongoose.model("bid_evaluation_list");
  89. let contractorListModel = mongoose.model("contractor_list");
  90. let featureLibModel = mongoose.model("std_project_feature_lib");
  91. let importLogsModel = mongoose.model("import_logs");
  92. const overHeightLibModel = mongoose.model('std_over_height_lib');
  93. const shareListModel = mongoose.model('share_list');
  94. let welcomeModel = mongoose.model("welcome_setting");
  95. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  96. let counter = require('../../../public/counter/counter');
  97. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  98. let sectionTreeDao = new SectionTreeDao();
  99. import CounterModel from "../../glj/models/counter_model";
  100. import moment from 'moment-timezone';
  101. import billsFlags from '../../common/const/bills_fixed';
  102. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  103. import {
  104. defaultDecimal,
  105. billsQuantityDecimal,
  106. displaySetting,
  107. calcOptions,
  108. tenderSetting,
  109. G_FILE_VER
  110. } from '../models/project_property_template';
  111. let labourCoeFacade = require('../../main/facade/labour_coe_facade');
  112. let calcProgramFacade = require('../../main/facade/calc_program_facade');
  113. let mainColLibModel = mongoose.model('std_main_col_lib');
  114. import EngineeringLibModel from "../../users/models/engineering_lib_model";
  115. let installationFacade = require('../../main/facade/installation_facade');
  116. let cipher = require('../../../public/cipher');
  117. let qiniu = require("qiniu");
  118. let fs = require("fs");
  119. let path = require("path");
  120. let request = require("request");
  121. const systemSettingMiddleware = require('../../main/middleware/system_setting');
  122. let qiniu_config = {
  123. "AccessKey": "_gR1ed4vi1vT2G2YITGSf4_H0fJu_nRS9Tzk3T4z",
  124. "SecretKey": "ty4zd0FHqgEDaiVzSLC8DfHlai99aS7bspLkw6s6",
  125. "Bucket": "yun-update",
  126. "Domain": "http://serverupdate.smartcost.com.cn"
  127. };
  128. let mac = new qiniu.auth.digest.Mac(qiniu_config.AccessKey, qiniu_config.SecretKey);
  129. // 重构了分享的数据结构,原本存在projects表的shareInfo数组中
  130. // 为了更好地适应新功能及以后拓展功能,现将分享信息存放在单独的share_list表中
  131. // 为了适应旧数据,需要在share_list没有数据的时候,将原本的分享信息复制到share_list中,同时生成联系人
  132. // TODO: 上线后这个方法执行过后,应该删除此方法
  133. async function prepareShareList() {
  134. const shareListCount = await shareListModel.count({});
  135. console.log(shareListCount);
  136. if (shareListCount) {
  137. return;
  138. }
  139. logger.info('================================enterPrepareShareList================================================');
  140. // 将项目的shareInfo数据复制到share_list表中
  141. const projects = await projectModel.find({'shareInfo.0': {$exists: true}}, '-_id ID userID shareInfo').lean();
  142. if (!projects.length) {
  143. return;
  144. }
  145. const shareList = [];
  146. const userMap = {}; // 给生成联系人做准备
  147. projects.forEach(project => {
  148. const ownerContacts = userMap[project.userID] || (userMap[project.userID] = []);
  149. project.shareInfo.forEach(shareItem => {
  150. if (!shareItem.shareDate) {
  151. return;
  152. }
  153. const receiverContacts = userMap[shareItem.userID] || (userMap[shareItem.userID] = []);
  154. receiverContacts.push(project.userID);
  155. const newItem = {
  156. ID: uuidV1(),
  157. projectID: project.ID,
  158. owner: project.userID,
  159. receiver: shareItem.userID,
  160. allowCopy: shareItem.allowCopy,
  161. allowCooperate: shareItem.allowCooperate,
  162. shareDate: shareItem.shareDate,
  163. updateDate: shareItem.shareDate
  164. };
  165. ownerContacts.push(shareItem.userID);
  166. shareList.push(newItem);
  167. });
  168. });
  169. // 插入分享信息
  170. const shareListPromise = shareListModel.insertMany(shareList);
  171. const tasks = [shareListPromise];
  172. // 更新用户信息
  173. const userTasks = [];
  174. Object.entries(userMap).forEach(([userID, contacts]) => {
  175. contacts = [...new Set(contacts)]
  176. .map(user => ({ userID: user }));
  177. const task = {
  178. updateOne: {
  179. filter: {
  180. _id: mongoose.Types.ObjectId(userID)
  181. },
  182. update: {
  183. contacts
  184. }
  185. }
  186. };
  187. userTasks.push(task);
  188. });
  189. if (userTasks.length) {
  190. tasks.push(userModel.bulkWrite(userTasks));
  191. }
  192. await Promise.all(tasks);
  193. }
  194. // 获取分享列表
  195. async function getShareList(query) {
  196. return await shareListModel.find(query, '-_id').lean();
  197. }
  198. async function addShareList(docs) {
  199. await shareListModel.insertMany(docs);
  200. }
  201. async function deleteShareList(query) {
  202. await shareListModel.deleteMany(query);
  203. }
  204. async function updateShareList(updateData) {
  205. const bulks = updateData.map(item => (
  206. {
  207. updateOne: {
  208. filter: item.query,
  209. update: item.update
  210. }
  211. }
  212. ));
  213. if (bulks.length) {
  214. await shareListModel.bulkWrite(bulks);
  215. }
  216. }
  217. // 根据项目ID获取项目shareInfo字段的数据映射(前端旧逻辑依赖项目本身的shareInfo字段)
  218. async function getShareInfoMap(projectIDs, shareList = null) {
  219. if (!shareList) {
  220. shareList = await getShareList({projectID: {$in: projectIDs}});
  221. }
  222. // 将相同项目的分享信息进行映射
  223. const map = {};
  224. shareList.forEach(item => {
  225. const shareInfo = map[item.projectID] || (map[item.projectID] = []);
  226. shareInfo.push({
  227. userID: item.receiver,
  228. shareDate: item.shareDate,
  229. updateDate: item.updateDate,
  230. allowCopy: item.allowCopy,
  231. allowCooperate: item.allowCooperate
  232. });
  233. });
  234. return map;
  235. }
  236. // 获取最近分享(只算分享出去的记录)
  237. async function getRecentShareList(userID, count) {
  238. const shareList = await getShareList({owner: userID});
  239. shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate));
  240. const set = new Set();
  241. for(const item of shareList) {
  242. if (set.size === count) {
  243. break;
  244. }
  245. set.add(item.receiver);
  246. }
  247. const sortedIDList = [...set];
  248. const userIDList = sortedIDList.map(userID => mongoose.Types.ObjectId(userID));
  249. const users = await userModel.find({_id: {$in: userIDList}}, 'real_name mobile company').lean();
  250. users.sort((a, b) => sortedIDList.indexOf(a._id.toString()) - sortedIDList.indexOf(b._id.toString()));
  251. return users;
  252. }
  253. //拷贝例题项目
  254. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  255. async function copyExample(userID, compilation, projIDs){
  256. let allProjs = [],
  257. IDMapping = {},
  258. projMapping = {};
  259. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  260. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted}).lean();
  261. if (parentExample.length === 0) {
  262. return false;
  263. }
  264. allProjs = allProjs.concat(parentExample);
  265. for (let i = 0; i < parentExample.length; i++) {
  266. let data = parentExample[i];
  267. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  268. return false;
  269. }
  270. //设置成顶节点,最后一个节点设置成末节
  271. data.ParentID = -1;
  272. if (i === parentExample.length - 1) {
  273. data.NextSiblingID = -1;
  274. }
  275. }
  276. //获取所有的子项目
  277. let posterityProjs = await getPosterityProjects(projIDs);
  278. allProjs = allProjs.concat(posterityProjs);
  279. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  280. //旧ID与新ID映射
  281. for (let i = 0; i < allProjs.length; i++) {
  282. let data = allProjs[i];
  283. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  284. IDMapping[data.ID] = newID;
  285. projMapping[newID] = data;
  286. }
  287. //return;
  288. //设置新的树结构数据
  289. let newDate = new Date(),
  290. parentBulks = [];
  291. for (let data of allProjs) {
  292. let orgID = data.ID;
  293. data.ID = IDMapping[data.ID];
  294. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  295. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  296. data.createDateTime = newDate;
  297. data.userID = userID;
  298. data.compilation = compilation;
  299. data.shareInfo = [];
  300. if (data.projType !== projectType.tender) {
  301. let newData = _.cloneDeep(data);
  302. delete newData._id;
  303. // await projectModel.create(newData);
  304. parentBulks.push({insertOne: {document: newData}});
  305. } else {
  306. //拷贝单位工程
  307. let rootProjectID = projMapping[data.ParentID].ParentID;
  308. let projectMap = {
  309. copy: {
  310. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  311. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  312. }
  313. };
  314. await copyProject(userID, compilation, {projectMap}, data.ID);
  315. }
  316. }
  317. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  318. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  319. if (lastProj) {
  320. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  321. }
  322. //拷贝父级文件
  323. await projectModel.bulkWrite(parentBulks);
  324. return true;
  325. }
  326. async function copyProject(userID, compilationID,data,newProjectID = null) {
  327. let projectMap = data.projectMap;
  328. let originalID = projectMap['copy'].document.ID;
  329. if (!newProjectID) {
  330. newProjectID = await getCounterID("projects");
  331. }
  332. let newFeeName = null,newUnitName = null;
  333. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  334. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  335. let feeRateFileID = uuidV1();//新的费率文件ID
  336. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  337. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  338. if(!originalProject){
  339. throw new Error('没有找到对应的项目,复制失败!');
  340. }
  341. let property = originalProject.property;
  342. if(projectMap['copy'].document.property){//更新项目属性信息
  343. setProperty(property,projectMap['copy'].document.property);
  344. }
  345. let originalProperty = _.cloneDeep(property);
  346. projectMap['copy'].document.property = property;
  347. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  348. //费率文件、单价文件重名检查
  349. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  350. if(feeRate){//存在重名的文件
  351. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  352. projectMap['copy'].document.property.feeFile.name = newFeeName;
  353. }
  354. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  355. if(unitPriceFile){//存在重名的文件
  356. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  357. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  358. }
  359. //更新项目的属性;
  360. projectMap['copy'].document.ID = newProjectID;
  361. if(projectMap['copy'].document.property.calcProgramFile){
  362. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  363. }
  364. if(projectMap['copy'].document.property.labourCoeFile){
  365. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  366. }
  367. if(projectMap['copy'].document.property.feeFile){
  368. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  369. }
  370. if(projectMap['copy'].document.property.unitPriceFile){
  371. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  372. }
  373. projectMap['copy'].document.userID = userID;
  374. projectMap['copy'].document.compilation = compilationID;
  375. projectMap['copy'].document.createDateTime = new Date();
  376. //清单、定额ID生成任务
  377. let IDtasks = [
  378. createIDsAndReturn(originalID,billsModel),
  379. createIDsAndReturn(originalID,rationModel),
  380. getProjectGLJIDAndReturn(originalID,newProjectID)
  381. ];
  382. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  383. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  384. let copyTasks = [
  385. createProject(projectMap),
  386. copyProjectSetting(originalID,newProjectID),
  387. copyBills(newProjectID,billMap),
  388. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  389. copyProjectGLJ(projectGLJMap.datas),
  390. copyInstallFee(originalID,newProjectID),
  391. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  392. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  393. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  394. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  395. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel),
  396. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,evaluateListModel),
  397. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,bidListModel),
  398. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,contractorListModel),
  399. ];
  400. if(originalProperty.calcProgramFile){
  401. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  402. }
  403. if(originalProperty.labourCoeFile){
  404. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  405. }
  406. if(originalProperty.feeFile){
  407. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  408. }
  409. if(originalProperty.unitPriceFile){
  410. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  411. }
  412. let p = await Promise.all(copyTasks);
  413. return p[0];
  414. }
  415. async function createIDsAndReturn(originalID,model) {
  416. let uuidMaping = {};//做ID映射
  417. let datas = [];
  418. let result = await model.find({"projectID": originalID}, '-_id');
  419. uuidMaping['-1'] = -1;
  420. //建立uuid-ID映射
  421. for(let d of result){
  422. uuidMaping[d.ID] = uuidV1();
  423. datas.push(d._doc);
  424. }
  425. return{uuidMaping:uuidMaping,datas:datas};
  426. }
  427. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  428. let IDMap = {};
  429. let datas = [];
  430. let result = await gljListModel.find({project_id:originalID}, '-_id');
  431. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  432. for(let i = 0; i < result.length; i++){
  433. let d = result[i];
  434. let newID = gljCount.sequence_value - (result.length - 1) + i;
  435. //let newID = await getCounterID("glj_list");
  436. IDMap[d.id] = newID;
  437. d._doc.project_id = newProjectID;
  438. d._doc.id = newID;
  439. datas.push(d._doc);
  440. }
  441. return{IDMap:IDMap,datas:datas};
  442. }
  443. async function createProject(projectMap) {//复制项目
  444. let tasks = [];
  445. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  446. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  447. }
  448. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  449. await projectModel.bulkWrite(tasks);
  450. return projectMap;
  451. }
  452. async function copyProjectSetting(originalID,newProjectID) {
  453. let result = null;
  454. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  455. if(setting){
  456. setting._doc.projectID =newProjectID;
  457. result = await projectSettingModel.create(setting._doc);
  458. }
  459. return result;
  460. }
  461. async function copyBills(newProjectID,billMap) {
  462. let uuidMaping = billMap.uuidMaping;//做ID映射
  463. for(let doc of billMap.datas){
  464. doc = getCopyBillDatas(doc,newProjectID,uuidMaping);
  465. }
  466. await insertMany(billMap.datas,billsModel);
  467. return billMap.datas;
  468. }
  469. function getCopyBillDatas(doc,newProjectID,uuidMaping) {
  470. doc.projectID = newProjectID;
  471. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  472. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  473. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  474. //对于有基数计算的节点,需要替换计算基数中引用的ID为新的ID
  475. if(doc.calcBase && doc.calcBase != ""){
  476. let idArr = scMathUtil.getFIDArr(doc.calcBase);
  477. for(let re of idArr){
  478. let oID = re.substr(1);//去掉开头的@字符
  479. if(!uuidMaping[oID]) continue;
  480. doc.calcBase = doc.calcBase.replace(new RegExp(oID, "g"),uuidMaping[oID]);
  481. }
  482. }
  483. return doc;
  484. }
  485. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  486. let uuidMaping = rationMap.uuidMaping;
  487. for(let doc of rationMap.datas){
  488. doc = getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap);
  489. }
  490. if(rationMap.datas.length > 0){
  491. await insertMany(rationMap.datas,rationModel);
  492. }
  493. return rationMap.datas;
  494. }
  495. function getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap){
  496. doc.projectID = newProjectID;
  497. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  498. if(doc.billsItemID){
  499. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  500. }
  501. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  502. //绑定定类型的工料机 项目工料机ID
  503. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  504. return doc;
  505. }
  506. async function copyProjectGLJ(gljList) {
  507. await insertMany(gljList,gljListModel);
  508. }
  509. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  510. let result = null;
  511. let file = await model.findOne({"ID": oldID}, '-_id');
  512. if(file){
  513. file._doc.ID = newID;
  514. file._doc.projectID =newProjectID;
  515. result = await model.create(file._doc);
  516. }
  517. return result;
  518. }
  519. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  520. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  521. let newFeeRateID = uuidV1();
  522. if(feeRate){
  523. feeRate._doc.ID = newFeeRateID;
  524. await feeRateModel.create(feeRate._doc);
  525. }
  526. if(feeRateFile){
  527. feeRateFile._doc.ID = feeRateFileID;
  528. newName?feeRateFile._doc.name = newName:'';
  529. feeRateFile._doc.userID = userID;
  530. feeRateFile._doc.rootProjectID = rootProjectID;
  531. feeRateFile._doc.feeRateID = newFeeRateID;
  532. await feeRateFileModel.create(feeRateFile._doc);
  533. }
  534. }
  535. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  536. let taskList = [
  537. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  538. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  539. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  540. ];
  541. return await Promise.all(taskList);
  542. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  543. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  544. if(unitPriceFile){
  545. unitPriceFile._doc.id = unitPriceFileID;
  546. newName?unitPriceFile._doc.name = newName:'';
  547. unitPriceFile._doc.project_id = newProjectID;
  548. unitPriceFile._doc.user_id = userID;
  549. unitPriceFile._doc.root_project_id = rootProjectID
  550. }
  551. await unitPriceFileModel.create(unitPriceFile._doc);
  552. }
  553. async function copySubList(srcFID,newFID,model) {
  554. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  555. let rList = [];
  556. for(let m of mList){
  557. m._doc.unit_price_file_id = newFID;
  558. m._doc.id = await getCounterID(model.modelName);
  559. rList.push(m._doc);
  560. }
  561. await insertMany(rList,model)
  562. }
  563. }
  564. async function copyInstallFee(originalPID,newProjectID) {
  565. let result = null;
  566. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  567. let newList = [];
  568. for(let i of installationFee ){
  569. i._doc.ID = uuidV1();
  570. i._doc.projectID = newProjectID;
  571. newList.push(i._doc);
  572. }
  573. if(newList.length >0){
  574. result = await installationFeeModel.insertMany(newList);
  575. }
  576. return result;
  577. }
  578. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  579. let subList = await model.find({projectID:originalPID}, '-_id');
  580. let newList =[];
  581. for(let s of subList){
  582. s._doc = getCopyRationSubData(s._doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  583. /* s._doc.ID = uuidV1();
  584. s._doc.projectID = newProjectID;
  585. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  586. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  587. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  588. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  589. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  590. for(let t of s._doc.templateList){
  591. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  592. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  593. }
  594. }*/
  595. newList.push(s._doc);
  596. }
  597. await insertMany(newList,model);
  598. }
  599. async function copyMaterialList(originalPID,newProjectID,projectGLJIDMap,model) {//暂估材料等信息
  600. let materialList = await model.find({projectID:originalPID}, '-_id').lean();
  601. let newList = [];
  602. for(let m of materialList){
  603. newList.push(getNewMaterial(m,newProjectID,projectGLJIDMap))
  604. }
  605. await insertMany(newList,model);
  606. }
  607. function getNewMaterial(m,newProjectID,projectGLJIDMap) {
  608. m.ID = uuidV1();
  609. m.projectID = newProjectID;
  610. if(projectGLJIDMap[m.projectGLJID]) m.projectGLJID = projectGLJIDMap[m.projectGLJID];
  611. return m;
  612. }
  613. function getCopyRationSubData(doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap){
  614. doc.ID = uuidV1();
  615. doc.projectID = newProjectID;
  616. doc.rationID&&rationIDMap[doc.rationID]?doc.rationID = rationIDMap[doc.rationID]:'';
  617. doc.billID&&billIDMap[doc.billID]?doc.billID = billIDMap[doc.billID]:'';
  618. doc.billsItemID&&billIDMap[doc.billsItemID]?doc.billsItemID = billIDMap[doc.billsItemID]:'';
  619. doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  620. if(doc.templateList && doc.templateList.length > 0 ){
  621. for(let t of doc.templateList){
  622. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  623. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  624. }
  625. }
  626. return doc;
  627. }
  628. async function moveProject(data) {
  629. data = JSON.parse(data);
  630. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  631. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  632. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  633. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  634. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  635. for(let projectID in feeRateMap){
  636. let rename = feeRateMap[projectID].name;
  637. let feeRateID = feeRateMap[projectID].query.ID;
  638. let checkFee = _.find(feeRates,{'name':rename});
  639. let newID = feeRateID;
  640. if(checkFee){//说明费率名字已存在,需要重命名
  641. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  642. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  643. if(feeRateMap[projectID].action == 'move'){
  644. feeRateMap[projectID].update.name = rename;
  645. }
  646. }
  647. if(feeRateMap[projectID].action == 'copy'){
  648. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  649. feeRateMap[projectID].name = rename;
  650. feeRateMap[projectID].ID = newID;
  651. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  652. }
  653. if(!feeUniqMap[feeRateID]){
  654. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  655. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  656. }
  657. }
  658. }
  659. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  660. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  661. for(let projectID in unitPriceMap){
  662. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  663. let rename = unitPriceMap[projectID].name;
  664. let unitPriceID = unitPriceMap[projectID].query.id;
  665. let newID = unitPriceID;
  666. if(checkUn){//重名检查
  667. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  668. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  669. if(unitPriceMap[projectID].action =='move'){
  670. unitPriceMap[projectID].update.name = rename;
  671. }
  672. }
  673. if(unitPriceMap[projectID].action =='copy'){
  674. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  675. unitPriceMap[projectID].name = rename;
  676. unitPriceMap[projectID].id = newID;
  677. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  678. }
  679. if(!priceUniqMap[unitPriceID]){
  680. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  681. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  682. }
  683. }
  684. }
  685. if(!_.isEmpty(projectMap)){
  686. for(let projectID in projectMap){
  687. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  688. }
  689. }
  690. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  691. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  692. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  693. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  694. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  695. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  696. return projectMap;
  697. }
  698. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  699. if(data.action == 'move'){
  700. let task = {
  701. updateOne:{
  702. filter : data.query,
  703. update : data.update
  704. }
  705. };
  706. feeRateFileTask.push(task);
  707. }
  708. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  709. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  710. let newFeeRateID = uuidV1();
  711. let newFeeRate = {
  712. ID:newFeeRateID,
  713. rates:feeRate.rates
  714. };
  715. let newFeeRateFile = {
  716. ID:data.ID,
  717. rootProjectID:data.rootProjectID,
  718. userID:feeRateFile.userID,
  719. name:data.name,
  720. libID:feeRateFile.libID,
  721. libName:feeRateFile.libName,
  722. feeRateID:newFeeRateID
  723. };
  724. feeRateTask.push({insertOne :{document:newFeeRate}});
  725. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  726. }
  727. }
  728. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  729. if(data.action == 'move'){
  730. let task = {
  731. updateOne:{
  732. filter : data.query,
  733. update : data.update
  734. }
  735. };
  736. unitPriceFileTask.push(task);
  737. }
  738. if(data.action == 'copy'){
  739. let newUnitFile = {
  740. id:data.id,
  741. name: data.name,
  742. project_id:projectID,
  743. user_id:user_id,
  744. root_project_id: data.rootProjectID
  745. };
  746. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  747. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  748. mixRatios = JSON.stringify(mixRatios);
  749. mixRatios = JSON.parse(mixRatios);
  750. for(let m of mixRatios){
  751. delete m._id; // 删除原有id信息
  752. delete m.id;
  753. m.unit_price_file_id = data.id;
  754. m.id = await getCounterID('mix_ratio');
  755. mixRatioTask.push(m);
  756. }
  757. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  758. unitPrices = JSON.stringify(unitPrices);
  759. unitPrices = JSON.parse(unitPrices);
  760. for(let u of unitPrices){
  761. delete u._id; // 删除原有id信息
  762. delete u.id;
  763. u.unit_price_file_id = data.id;
  764. u.id = await getCounterID('unit_price');
  765. unitPriceTask.push(u);
  766. }
  767. }
  768. }
  769. async function getCounterID(collectionName){
  770. let counterModel = new CounterModel();
  771. return await counterModel.getId(collectionName);
  772. }
  773. async function insertMany(datas,model) {
  774. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  775. let newList = datas.splice(0,1000);//一次插入1000条
  776. await model.insertMany(newList);
  777. }
  778. await model.insertMany(datas);
  779. }
  780. function setProperty(Obj,updateData) {
  781. for(let ukey in updateData){
  782. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  783. setProperty(Obj[ukey],updateData[ukey]);
  784. }else {
  785. Obj[ukey] = updateData[ukey];
  786. }
  787. }
  788. }
  789. function isDef(v){
  790. return typeof v !== 'undefined' && v !== null;
  791. }
  792. function getTotalFee(bills, feeName) {
  793. if(!isDef(bills)){
  794. return 0;
  795. }
  796. if(!isDef(bills.fees) || bills.fees.length <= 0){
  797. return 0;
  798. }
  799. for(let fee of bills.fees){
  800. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  801. return isDef(fee.tenderTotalFee)
  802. ? fee.tenderTotalFee
  803. : isDef(fee.totalFee)
  804. ? fee.totalFee
  805. : 0;
  806. }
  807. }
  808. return 0;
  809. }
  810. function summarizeToParent(parent, child, fields = null) {
  811. const decimal = -2;
  812. if (!fields) {
  813. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  814. }
  815. for (let field of fields) {
  816. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  817. }
  818. }
  819. function getBuildingArea(projFeature){
  820. if(!projFeature || projFeature.length === 0){
  821. return null;
  822. }
  823. for(let f of projFeature){
  824. if(f.key === 'buildingArea'){
  825. return f.value;
  826. }
  827. }
  828. return null;
  829. }
  830. //根据单位工程ID获取经济指标信息
  831. //@param {Number}prj_id @return {Object}
  832. async function getIndexReportData(prj_id, filters) {
  833. return await project_facade.getIndexReportData(prj_id, filters);
  834. }
  835. // 根据树结构数据排序
  836. function getSortedDataByTree(data) {
  837. // NextSiblingID-数据映射
  838. const mapping = {};
  839. data.forEach(item => {
  840. // 错误数据兼容处理
  841. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  842. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  843. if (!item.NextSiblingID) {
  844. item.NextSiblingID = -1;
  845. }
  846. mapping[item.NextSiblingID] = item;
  847. });
  848. let lastItem = data.find(item => +item.NextSiblingID === -1);
  849. if (!lastItem) {
  850. return data;
  851. }
  852. const rst = [lastItem];
  853. let preItem = mapping[lastItem.ID];
  854. while (preItem) {
  855. rst.unshift(preItem);
  856. preItem = mapping[preItem.ID];
  857. }
  858. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  859. return rst.length === data.length ? rst : data;
  860. }
  861. //根据单位工程ID获取汇总信息
  862. //@param {Number}tenderID {String}summaryType @return {Object}
  863. async function getSummaryInfoByTender(tenderID, summaryType) {
  864. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  865. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  866. let parent,
  867. parentName,
  868. compilationIllustration;
  869. let summaryList = [];
  870. if(!tender){
  871. return null;
  872. }
  873. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  874. if(!engineering){
  875. return null;
  876. }
  877. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  878. if(!project){
  879. return null;
  880. }
  881. let summaryInfo = await getSummaryInfo([project.ID]);
  882. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  883. parent = engineering;
  884. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted}).lean();
  885. tenders = getSortedDataByTree(tenders);
  886. for(let t of tenders){
  887. if(summaryInfo[t.ID]){
  888. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  889. summaryList.push(summaryInfo[t.ID]);
  890. }
  891. }
  892. } else { // 汇总到建设项目级别
  893. parent = project;
  894. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  895. engs = getSortedDataByTree(engs);
  896. for(let e of engs){
  897. if(summaryInfo[e.ID]){
  898. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  899. summaryList.push(summaryInfo[e.ID]);
  900. }
  901. }
  902. }
  903. // 项目名称
  904. parentName = parent && parent.name
  905. ? parent.name
  906. : '';
  907. // 编制说明
  908. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  909. ? parent.property.compilationIllustration
  910. : '';
  911. return {
  912. parent: {
  913. name: parentName,
  914. compilationIllustration: compilationIllustration},
  915. subList: summaryList
  916. };
  917. }
  918. //获取单位工程的各标段费用信息(不进行汇总)
  919. async function getTendersFeeInfo(tenders) {
  920. let IDMapping = {};
  921. //固定清单类别与汇总金额字段映射
  922. let flagFieldMapping = {};
  923. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  924. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  925. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  926. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  927. flagFieldMapping[billsFlags.OTHER] = 'other';
  928. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  929. flagFieldMapping[billsFlags.TAX] = 'tax';
  930. let tenderIDs = [];
  931. if(tenders.length > 0){
  932. for(let tender of tenders){
  933. tenderIDs.push(tender.ID);
  934. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  935. IDMapping[tender.ID]['buildingArea'] = '';
  936. }
  937. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  938. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  939. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  940. //获取单位工程汇总金额需要用到的所有清单
  941. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  942. '-_id projectID fees flags');
  943. //进行单位工程级别的汇总
  944. for(let bills of allBills){
  945. let billsFlag = bills.flags[0]['flag'];
  946. let costField = flagFieldMapping[billsFlag];
  947. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  948. //暂估合价(工程造价暂估合价)
  949. if (billsFlag === billsFlags.ENGINEERINGCOST){
  950. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  951. }
  952. }
  953. //占造价比例、单方造价
  954. for(let tender of tenders){
  955. let tenderInfo = IDMapping[tender.ID];
  956. tenderInfo.rate = '';
  957. //单方造价
  958. tenderInfo.perCost = '';
  959. }
  960. }
  961. return IDMapping;
  962. }
  963. async function getSummaryInfo(projectIDs, feeFields = null, engineeringCostFields = null){
  964. function initFees(obj, feeFields, engineeringCostFields) {
  965. for (let data of feeFields) {
  966. obj[data.v] = 0;
  967. }
  968. for (let data of engineeringCostFields) {
  969. obj[data.k] = 0;
  970. }
  971. }
  972. if (!feeFields) {
  973. feeFields = [
  974. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  975. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  976. {k: billsFlags.MEASURE, v: 'measure'},
  977. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  978. {k: billsFlags.OTHER, v: 'other'},
  979. {k: billsFlags.CHARGE, v: 'charge'},
  980. {k: billsFlags.TAX, v: 'tax'}
  981. ];
  982. }
  983. // 项目总造价的各个费用,k为汇总的字段,v为工程造价的费用字段
  984. if (!engineeringCostFields) {
  985. engineeringCostFields = [{ k: 'estimate', v: 'estimate' }];
  986. }
  987. //ID与汇总信息映射
  988. let IDMapping = {};
  989. //固定清单类别与汇总金额字段映射
  990. let flagFieldMapping = {};
  991. for (let data of feeFields) {
  992. flagFieldMapping[data.k] = data.v;
  993. }
  994. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  995. //设置建设项目的总建筑面积
  996. for(let project of projects){
  997. let grossArea = '';
  998. if(project.property && project.property.basicInformation){
  999. for(let basicInfo of project.property.basicInformation){
  1000. if(basicInfo.key === 'basicInfo'){
  1001. for(let k of basicInfo.items){
  1002. if(k.key === 'grossArea'){
  1003. grossArea = k.value;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. }
  1009. IDMapping[project.ID] = {rate: 0, buildingArea: grossArea, perCost: ''};
  1010. initFees(IDMapping[project.ID], feeFields, engineeringCostFields);
  1011. console.log(IDMapping[project.ID]);
  1012. }
  1013. //单项工程
  1014. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1015. let tenders = [];
  1016. let engIDs = [];
  1017. for(let eng of engineerings){
  1018. engIDs.push(eng.ID);
  1019. IDMapping[eng.ID] = {rate: 0, buildingArea: '', perCost: ''};
  1020. initFees(IDMapping[eng.ID], feeFields, engineeringCostFields);
  1021. }
  1022. //单位工程
  1023. if(engIDs.length > 0){
  1024. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1025. }
  1026. let tenderIDs = [];
  1027. if(tenders.length > 0){
  1028. for(let tender of tenders){
  1029. tenderIDs.push(tender.ID);
  1030. IDMapping[tender.ID] = {rate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1031. initFees(IDMapping[tender.ID], feeFields, engineeringCostFields);
  1032. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1033. if(buildingArea){
  1034. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1035. }
  1036. }
  1037. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1038. let needFlags = feeFields.map(data => data.k);
  1039. //获取单位工程汇总金额需要用到的所有清单
  1040. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1041. '-_id projectID fees flags');
  1042. //进行单位工程级别的汇总
  1043. for(let bills of allBills){
  1044. let billsFlag = bills.flags[0]['flag'];
  1045. let costField = flagFieldMapping[billsFlag];
  1046. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1047. // 工程造价各费用
  1048. if (billsFlag === billsFlags.ENGINEERINGCOST){
  1049. engineeringCostFields.forEach(({k, v}) => {
  1050. IDMapping[bills.projectID][k] = getTotalFee(bills, v);
  1051. });
  1052. }
  1053. }
  1054. let summaryFields = [...feeFields, ...engineeringCostFields].map(data => data.v);
  1055. //进行单项工程级别的汇总
  1056. for(let tender of tenders){
  1057. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  1058. }
  1059. //进行建设项目级别的汇总
  1060. for(let eng of engineerings){
  1061. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  1062. }
  1063. //占造价比例、单方造价
  1064. const rateDecimal = -2;
  1065. const perCostDecimal = -2;
  1066. for(let tender of tenders){
  1067. let tenderInfo = IDMapping[tender.ID];
  1068. let engInfo = IDMapping[tender.ParentID];
  1069. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1070. //单方造价
  1071. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1072. ? tenderInfo.buildingArea.toString().trim()
  1073. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1074. }
  1075. for(let eng of engineerings){
  1076. let engInfo = IDMapping[eng.ID];
  1077. let projInfo = IDMapping[eng.ParentID];
  1078. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1079. }
  1080. //建设项目占造价比例及单方造价
  1081. for(let project of projects){
  1082. let projectInfo = IDMapping[project.ID];
  1083. projectInfo.rate = 100;
  1084. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1085. ? projectInfo.buildingArea.toString().trim()
  1086. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1087. }
  1088. }
  1089. return IDMapping;
  1090. }
  1091. //根据项目ID获取所属建设项目
  1092. //@param {Number}projectID @return {Object}
  1093. async function getConstructionProject(projectID){
  1094. function returnProject(project){
  1095. if(!project || project.projType === projectType.folder){
  1096. return null;
  1097. }
  1098. if(project.projType === projectType.project){
  1099. return project;
  1100. }
  1101. }
  1102. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  1103. let returnV = returnProject(project);
  1104. if(returnV !== undefined){
  1105. return returnV;
  1106. }
  1107. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  1108. returnV = returnProject(parent);
  1109. if(returnV !== undefined){
  1110. return returnV;
  1111. }
  1112. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  1113. returnV = returnProject(grandParent);
  1114. return returnV !== undefined ? returnV : null;
  1115. }
  1116. //获取单位工程完整目录结构
  1117. //@param {Number}projectID @return {Arry}
  1118. async function getFullPath(projectID) {
  1119. let fullPath = [];
  1120. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  1121. if(project){
  1122. fullPath.push(project.name);
  1123. await getParent(project.ParentID);
  1124. }
  1125. fullPath = fullPath.reverse();
  1126. return fullPath;
  1127. async function getParent(ParentID) {
  1128. if(ParentID != -1){
  1129. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  1130. if(parent){
  1131. fullPath.push(parent.name);
  1132. await getParent(parent.ParentID);
  1133. }
  1134. }
  1135. }
  1136. }
  1137. // 获取项目链上,自身、父项、爷爷项...的ID
  1138. async function getUpChainIDs(projectID) {
  1139. const rst = [];
  1140. while (projectID != -1) {
  1141. rst.push(projectID);
  1142. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  1143. projectID = project ? project.ParentID : -1;
  1144. }
  1145. return rst;
  1146. }
  1147. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  1148. async function getPosterityProjects(projectIDs) {
  1149. let rst = [];
  1150. async function getProjects(parentIDs) {
  1151. if (parentIDs.length > 0) {
  1152. let newIDs = [];
  1153. let projs = await projectModel.find({ParentID: {$in: parentIDs}, $or: notDeleted}, '-_id').lean();
  1154. for (let proj of projs) {
  1155. // 兼容旧的错误数据,可能ParentID和ID相同
  1156. if (parentIDs.includes(proj.ID)) {
  1157. continue;
  1158. }
  1159. rst.push(proj);
  1160. newIDs.push(proj.ID);
  1161. }
  1162. await getProjects(newIDs);
  1163. }
  1164. }
  1165. await getProjects(projectIDs);
  1166. return rst;
  1167. }
  1168. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  1169. async function getShareInfo(userID, projectID) {
  1170. // 接受到的分享项目
  1171. const upChainIDs = await getUpChainIDs(projectID);
  1172. const shareList = await getShareList({receiver: userID, projectID: {$in: upChainIDs}});
  1173. // 返回最新的分享
  1174. //return shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate))[0];
  1175. return shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate))[0];
  1176. }
  1177. //打开的单位工程是否是被分享的.
  1178. async function isShare(userId, project){
  1179. //判断是否是打开分享的项目,属于分享文件的子项也算
  1180. while (project) {
  1181. for(let shareData of project.shareInfo){
  1182. if(shareData.userID === userId){
  1183. return true;
  1184. }
  1185. }
  1186. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1187. }
  1188. return false;
  1189. }
  1190. //用户是否第一次进入费用定额
  1191. async function isFirst(userId, compilationId) {
  1192. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1193. let first = false;
  1194. if (userData) {
  1195. first = !_.find(userData.used_list, function (o) {
  1196. return o.compilationId === compilationId;
  1197. });;
  1198. }
  1199. return first;
  1200. }
  1201. async function importChongqingProject(data) {
  1202. let log_data = {
  1203. key:data.key,
  1204. userID:data.user_id,
  1205. status:"start",
  1206. create_time:+new Date()
  1207. };
  1208. await importLogsModel.create(log_data);
  1209. doImport(data.user_id,data.session.sessionCompilation._id,data.session.sessionCompilation.adProjects,data.key);
  1210. return "start importing";
  1211. async function doImport(user_id,compilationId,projectIDs,key) {
  1212. let doc = {status:"finish"};
  1213. try {
  1214. let r = await copyExample(user_id,compilationId,projectIDs);
  1215. if(r == false){
  1216. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1217. doc.status = "error";
  1218. }
  1219. }catch (error){
  1220. console.log(error);
  1221. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1222. doc.status = "error";
  1223. }finally {
  1224. await importLogsModel.update({key:key},doc);
  1225. }
  1226. }
  1227. }
  1228. //用户第一次进入费用定额的数据准备
  1229. async function prepareInitialData(userId, compilation, example) {
  1230. let first = await isFirst(userId, compilation);
  1231. if (first) {
  1232. await updateUsedList(userId, compilation);
  1233. let prepareTask = [
  1234. copyCompleRationSection(userId, compilation),
  1235. copyCompleGljSection(userId, compilation)
  1236. ];
  1237. if (example && example.length > 0) {
  1238. prepareTask.push(copyExample(userId, compilation, example));
  1239. }
  1240. await Promise.all(prepareTask);
  1241. }
  1242. }
  1243. async function updateUsedList(userId, compilation) {
  1244. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1245. }
  1246. //拷贝补充定额章节树
  1247. async function copyCompleRationSection(userId, compilationId) {
  1248. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1249. }
  1250. //拷贝补充人材机分类树
  1251. async function copyCompleGljSection(userId, compilationId) {
  1252. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  1253. if (templateData.length > 0) {
  1254. let insertDatas = [],
  1255. uuidMapping = {};
  1256. //将ID替换成UUID
  1257. for (let temData of templateData) {
  1258. uuidMapping[temData.ID] = uuidV1();
  1259. }
  1260. for(let temData of templateData) {
  1261. let insertD = {
  1262. userId: userId,
  1263. compilationId: compilationId,
  1264. Name: temData.Name,
  1265. ID: uuidMapping[temData.ID],
  1266. ParentID: uuidMapping[temData.ParentID] || -1,
  1267. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1268. };
  1269. insertDatas.push(insertD);
  1270. }
  1271. //插入数据
  1272. await compleGljSectionModel.insertMany(insertDatas);
  1273. }
  1274. }
  1275. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1276. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1277. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1278. for(let d of datas){
  1279. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1280. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1281. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1282. newFile = {id:newID,name:tem_file.name};
  1283. type = 0;
  1284. }
  1285. projectIDs.push({ID:d.projectID})
  1286. }
  1287. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1288. }
  1289. //获取费用定额绑定的基本信息库数据
  1290. async function getBasicInfo(compilationID, fileKind = null) {
  1291. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1292. if (!compilation) {
  1293. return null;
  1294. }
  1295. let billValuation = compilation.bill_valuation.find(function (data) {
  1296. return data.enable;
  1297. });
  1298. if (!billValuation) {
  1299. return null;
  1300. }
  1301. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1302. let engineering = engineerings.find(function (data) {
  1303. return data.info_lib && data.info_lib.length > 0;
  1304. });
  1305. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1306. return null;
  1307. }
  1308. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1309. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1310. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1311. let strMap = {
  1312. 1: 'tender', //投标
  1313. 2: 'bid', //招标
  1314. 3: 'control' //控制价
  1315. };
  1316. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1317. needfulData.forEach(nData => {
  1318. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1319. nData.items = needfulSub;
  1320. });
  1321. infoLib.info = needfulData;
  1322. }
  1323. return infoLib;
  1324. }
  1325. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1326. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1327. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1328. return null;
  1329. }
  1330. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1331. return featureLib;
  1332. }
  1333. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1334. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1335. async function getProjectByGranularity(tenderID, granularity, summaryObj, userID, versionName) {
  1336. const GRANULARITY = {
  1337. PROJECT: 1,
  1338. ENGINEERING: 2,
  1339. TENDER: 3
  1340. };
  1341. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}).lean(); //加上session的userID,防止tenderID被篡改过
  1342. if (!theTender) {
  1343. return null;
  1344. }
  1345. let theEngineering = await projectModel.findOne({ID: theTender.ParentID}).lean();
  1346. if (!theEngineering) {
  1347. return null;
  1348. }
  1349. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID}).lean();
  1350. if (!constructionProject) {
  1351. return null;
  1352. }
  1353. let engineerings;
  1354. if (granularity === GRANULARITY.PROJECT) {
  1355. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted}).lean();
  1356. for (let eng of engineerings) {
  1357. eng.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted}).lean();
  1358. }
  1359. } else {
  1360. engineerings = [theEngineering];
  1361. if (granularity === GRANULARITY.ENGINEERING) {
  1362. theEngineering.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted}).lean();
  1363. } else {
  1364. theEngineering.children = [theTender];
  1365. }
  1366. }
  1367. constructionProject.children = engineerings;
  1368. //获取汇总信息
  1369. const { feeFields, engineeringCostFields } = summaryObj;
  1370. constructionProject.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields, engineeringCostFields);
  1371. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1372. let product = await productModel.findOne({});
  1373. let company = product.company || '珠海纵横创新软件有限公司',
  1374. version = product.version || '';
  1375. constructionProject.softInfo = `${company};${versionName};${version};${userID}`;
  1376. return constructionProject;
  1377. }
  1378. //获取项目数据占位ID
  1379. async function getProjectPlaceholder(data) {
  1380. let rst = {};
  1381. //项目本身数据
  1382. if (data.projectCount) {
  1383. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1384. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1385. }
  1386. //项目人材机数据
  1387. if (data.projectGLJCount) {
  1388. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1389. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1390. }
  1391. //组成物数据
  1392. if (data.ratioCount) {
  1393. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1394. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1395. }
  1396. //单价文件数据
  1397. if (data.unitPriceFileCount) {
  1398. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1399. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1400. }
  1401. //单价数据
  1402. if (data.unitPriceCount) {
  1403. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1404. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1405. }
  1406. return rst;
  1407. }
  1408. /*
  1409. * 接口导入 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1410. * */
  1411. async function importProject(importObj, userID, compilationID) {
  1412. let toInsertProjects = [importObj]; //待新增项目数据
  1413. await setupProject(importObj);
  1414. //设置项目ID及相关数据
  1415. for (let curEng of importObj.engs) {
  1416. await setupProject(curEng);
  1417. toInsertProjects.push(curEng);
  1418. for (let curTender of curEng.tenders) {
  1419. await setupProject(curTender.tender);
  1420. //插入单位工程的详细数据
  1421. await importTenderDetail(curTender);
  1422. toInsertProjects.push(curTender.tender);
  1423. }
  1424. delete curEng.tenders;
  1425. }
  1426. delete importObj.engs;
  1427. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1428. let bulks = [];
  1429. //如果有前节点,更新前节点
  1430. if (importObj.preID !== -1) {
  1431. bulks.push({
  1432. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1433. });
  1434. }
  1435. for (let insertP of toInsertProjects) {
  1436. bulks.push({
  1437. insertOne: {document: insertP}
  1438. });
  1439. }
  1440. if (bulks.length > 0) {
  1441. await projectModel.bulkWrite(bulks);
  1442. }
  1443. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1444. //设置汇总字段
  1445. for(let proj of toInsertProjects){
  1446. let summaryProj = summaryInfo[proj.ID];
  1447. if(summaryProj){
  1448. proj.engineeringCost = summaryProj.engineeringCost;
  1449. proj.subEngineering = summaryProj.subEngineering;
  1450. proj.measure = summaryProj.measure;
  1451. proj.safetyConstruction = summaryProj.safetyConstruction;
  1452. proj.other = summaryProj.other;
  1453. proj.charge = summaryProj.charge;
  1454. proj.tax = summaryProj.tax;
  1455. proj.rate = summaryProj.rate;
  1456. proj.buildingArea = summaryProj.buildingArea;
  1457. proj.perCost = summaryProj.perCost;
  1458. }
  1459. }
  1460. return toInsertProjects;
  1461. //给项目数据设置一些需要的数据
  1462. async function setupProject(data) {
  1463. data.userID = userID;
  1464. data.compilation = compilationID;
  1465. data.fileVer = G_FILE_VER;
  1466. data.createDateTime = new Date();
  1467. if (data.projType === 'Project') {
  1468. await setupConstruct(data);
  1469. } else if (data.projType === 'Tender') {
  1470. await setupTender(data);
  1471. }
  1472. }
  1473. //给建设项目设置一些数据
  1474. async function setupConstruct(data) {
  1475. //更新基本信息, 按照key匹配
  1476. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1477. if (infoLib) {
  1478. //标准基本信息库的数据打平
  1479. let flatDatas = [];
  1480. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1481. data.basicInformation.forEach(importI => {
  1482. flatDatas.forEach(item => {
  1483. if (item.key === 'engineeringName') {
  1484. item.value = data.name;
  1485. } else if (item.key === 'fileKind') {
  1486. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1487. } else if (item.key === 'taxModel') {
  1488. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1489. }
  1490. if (item.key === importI.key) {
  1491. item.value = importI.value;
  1492. }
  1493. });
  1494. });
  1495. }
  1496. data.property.basicInformation = infoLib ? infoLib.info : [];
  1497. }
  1498. //给单位工程设置一些数据
  1499. async function setupTender(data) {
  1500. //小数位数 需要修改,所以深拷贝
  1501. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  1502. // 定额工程量、人材机消耗量精度设为最大6
  1503. data.property.decimal.ration.quantity = 6;
  1504. data.property.decimal.glj.quantity = 6;
  1505. //清单工程量精度 需要修改,所以深拷贝
  1506. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1507. // 清单工程量精度设置最大4
  1508. data.property.billsQuantityDecimal.forEach(data => data.decimal = 4);
  1509. //呈现选项
  1510. data.property.displaySetting = displaySetting;
  1511. data.property.billsCalcMode = 0;
  1512. data.property.zanguCalcMode = 0;
  1513. //计算选项
  1514. data.property.calcOptions = calcOptions;
  1515. //安装增加费
  1516. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1517. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1518. }
  1519. //锁定清单
  1520. data.property.lockBills = true;
  1521. //工料机单价调整系数
  1522. data.property.tenderSetting = tenderSetting;
  1523. //工程特征相关更新
  1524. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1525. if (featureLib) {
  1526. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1527. data.projectFeature.forEach(importF => {
  1528. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1529. if (matchData) {
  1530. matchData.value = importF.value;
  1531. }
  1532. });
  1533. //设置工程专业的值为费用标准的值..
  1534. featureLib.feature.forEach(f => {
  1535. if (f.key === 'engineering') {
  1536. f.value = data.property.feeStandardName;
  1537. }
  1538. });
  1539. }
  1540. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1541. // 指标信息相关设置
  1542. await project_facade.setSEILibData(data.property);
  1543. }
  1544. }
  1545. //插入单位工程内部详细数据
  1546. async function importTenderDetail(tenderData) {
  1547. //单价文件
  1548. let upFile = {
  1549. id: tenderData.tender.property.unitPriceFile.id,
  1550. name: tenderData.tender.name,
  1551. project_id: tenderData.tender.ID,
  1552. user_id: tenderData.tender.userID,
  1553. root_project_id: tenderData.tender.property.rootProjectID
  1554. };
  1555. await unitPriceFileModel.create(upFile);
  1556. //费率文件
  1557. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1558. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1559. //人工系数文件
  1560. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1561. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1562. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1563. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1564. //列设置
  1565. let engineeringModel = new EngineeringLibModel();
  1566. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1567. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1568. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1569. //清单
  1570. if (tenderData.bills.length) {
  1571. await billsModel.insertMany(tenderData.bills);
  1572. }
  1573. //投标文件中,才会有下面这些数据
  1574. if (enterDetail(tenderData)) {
  1575. //匹配标准数据,更新一些标准数据
  1576. await setupStdData(tenderData);
  1577. let task = [];
  1578. //定额
  1579. if (tenderData.ration.length) {
  1580. task.push(rationModel.insertMany(tenderData.ration))
  1581. }
  1582. //定额人材机
  1583. if (tenderData.rationGLJ.length) {
  1584. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1585. }
  1586. //定额调整系数
  1587. if (tenderData.rationCoe.length) {
  1588. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1589. }
  1590. //项目人材机
  1591. if (tenderData.projectGLJ.length) {
  1592. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1593. }
  1594. // 承包人材料
  1595. if (tenderData.contractorList.length) {
  1596. task.push(contractorListModel.insertMany(tenderData.contractorList));
  1597. }
  1598. // 评标材料表
  1599. if (tenderData.bidEvaluationList.length) {
  1600. task.push(bidListModel.insertMany(tenderData.bidEvaluationList));
  1601. }
  1602. // 暂估价材料表
  1603. if (tenderData.evaluationList.length) {
  1604. task.push(evaluateListModel.insertMany(tenderData.evaluationList));
  1605. }
  1606. //组成物
  1607. if (tenderData.mixRatio.length) {
  1608. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1609. }
  1610. //单价文件
  1611. if (tenderData.unitPrice.length) {
  1612. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1613. }
  1614. await Promise.all(task);
  1615. }
  1616. //继续处理定额等数据
  1617. function enterDetail(tenderData) {
  1618. return tenderData.ration.length ||
  1619. tenderData.rationGLJ.length ||
  1620. tenderData.projectGLJ.length ||
  1621. tenderData.mixRatio.length ||
  1622. tenderData.unitPrice.length;
  1623. }
  1624. }
  1625. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1626. async function setupStdData(tenderData) {
  1627. //获取标准定额数据 (定额子目的编码查找)
  1628. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1629. if (!matchRationCodes.length) {
  1630. return;
  1631. }
  1632. //限制在当前费用定额可用的定额库里查找
  1633. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1634. '-_id -rationAssList -rationCoeList -rationInstList');
  1635. //标准定额code - 映射
  1636. let stdRationCodeMap = {};
  1637. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1638. //获取标准人材机数据 (人材机汇总的编码查找)
  1639. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1640. if (!matchGLJCodes.length) {
  1641. return;
  1642. }
  1643. //限制在当前费用定额可用的人材机库里查找
  1644. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1645. '-_id -component -priceProperty');
  1646. //标准人材机code - 映射
  1647. let stdGLJCodeMap = {};
  1648. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1649. //更新定额数据
  1650. tenderData.ration.forEach(r => {
  1651. let stdRation = stdRationCodeMap[r.code];
  1652. if (stdRation) {
  1653. r.caption = stdRation.caption;
  1654. r.from = 'std';
  1655. r.libID = stdRation.rationRepId;
  1656. r.stdID = stdRation.ID;
  1657. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1658. r.content = stdRation.jobContent;
  1659. if (stdRation.feeType) {
  1660. r.programID = stdRation.feeType;
  1661. } else {
  1662. // 是标准定额,但是该标准定额取费专业为空,取定额取费专业(后台配置项)
  1663. r.programID = tenderData.tender.property.engineering;
  1664. }
  1665. } else {
  1666. r.from = 'cpt';
  1667. r.prefix = '补';
  1668. }
  1669. });
  1670. //更新定额人材机数据
  1671. tenderData.rationGLJ.forEach(rGLJ => {
  1672. rGLJ.from = 'cpt';
  1673. //匹配定额
  1674. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1675. if (stdRation) {
  1676. //根据导入数据的定额人材机编码匹配人材机
  1677. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1678. if (stdGLJ) {
  1679. rGLJ.from = 'std';
  1680. rGLJ.GLJID = stdGLJ.ID;
  1681. rGLJ.type = stdGLJ.gljType;
  1682. rGLJ.shortName = stdGLJ.shortName;
  1683. rGLJ.repositoryId = stdGLJ.repositoryId;
  1684. rGLJ.model = stdGLJ.model;
  1685. rGLJ.adjCoe = stdGLJ.adjCoe;
  1686. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1687. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1688. if (stdRationGLJ) {
  1689. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1690. }
  1691. }
  1692. }
  1693. });
  1694. //更新人材机汇总数据
  1695. tenderData.projectGLJ.forEach(pGLJ => {
  1696. if (!pGLJ.specs) {
  1697. pGLJ.specs = null;
  1698. }
  1699. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1700. if (stdGLJ) {
  1701. pGLJ.glj_id = stdGLJ.ID;
  1702. pGLJ.model = stdGLJ.model;
  1703. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1704. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1705. let ratios = tenderData.mixRatio.filter(ratio =>
  1706. ratio.connect_key === keyStr);
  1707. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1708. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1709. }
  1710. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1711. }
  1712. });
  1713. //更新单价文件数据
  1714. tenderData.unitPrice.forEach(up => {
  1715. let stdGLJ = stdGLJCodeMap[up.original_code];
  1716. if (stdGLJ) {
  1717. up.glj_id = stdGLJ.ID;
  1718. up.type = stdGLJ.gljType;
  1719. up.short_name = stdGLJ.shortName;
  1720. }
  1721. });
  1722. //更新组成物数据
  1723. tenderData.mixRatio.forEach(ratio => {
  1724. let stdGLJ = stdGLJCodeMap[ratio.code];
  1725. if (stdGLJ) {
  1726. ratio.glj_id = stdGLJ.ID;
  1727. ratio.type = stdGLJ.gljType;
  1728. }
  1729. });
  1730. }
  1731. async function exportProject(userID,data){//导出建设项目
  1732. if(data.type == 'main'){
  1733. return await exportMainData(userID,data.projectID);
  1734. }else {
  1735. return await exportTenderData(data);
  1736. }
  1737. }
  1738. async function exportMainData(userID,projectID) {
  1739. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  1740. let tenderIDs = [];
  1741. let project = await projectModel.findOne({ID:projectID});
  1742. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  1743. result['compilationID'] = project.compilation;
  1744. result['from'] = "construction";
  1745. result.projects.push(project);
  1746. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  1747. for(let s of subProjects){
  1748. if(!s.deleteInfo || !s.deleteInfo.deleted){
  1749. result.projects.push(s);
  1750. if(s.projType =="Tender") tenderIDs.push(s.ID);
  1751. }
  1752. }
  1753. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  1754. result.files = files;
  1755. result = cipher.aesEncrypt(JSON.stringify(result));
  1756. result +="|----|" +JSON.stringify(tenderIDs);
  1757. return result;
  1758. }
  1759. async function exportUnitFiles(rootProjectID){
  1760. let unitFiles = [];
  1761. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  1762. for(let f of files){
  1763. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1764. let tem = {unitFile:f};
  1765. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1766. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1767. unitFiles.push(tem);
  1768. }
  1769. return unitFiles;
  1770. }
  1771. async function exportFeeRateFiles(rootProjectID) {
  1772. let feeRateFiles = [];
  1773. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1774. for(let f of files){
  1775. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1776. let tem = {feeRateFile:f};
  1777. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1778. feeRateFiles.push(tem);
  1779. }
  1780. return feeRateFiles;
  1781. }
  1782. async function exportTenderData(data){
  1783. let result = {};
  1784. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1785. if(projectSetting) result['projSetting'] = projectSetting;
  1786. result.bills = await billsModel.find({"projectID": data.projectID});
  1787. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1788. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1789. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1790. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1791. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1792. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1793. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1794. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1795. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1796. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1797. result.evaluateList = await evaluateListModel.find({projectID:data.projectID}, '-_id').lean();
  1798. result.bidList = await bidListModel.find({projectID:data.projectID}, '-_id').lean();
  1799. result.contractorList = await contractorListModel.find({projectID:data.projectID}, '-_id').lean();
  1800. return cipher.aesEncrypt(JSON.stringify(result));
  1801. }
  1802. async function downLoadProjectFile(info) {
  1803. let result = {error:0};
  1804. let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1805. let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
  1806. let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1807. let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
  1808. console.log(privateDownloadUrl);
  1809. let data = {
  1810. key:info.key,
  1811. userID:info.session.sessionUser.id,
  1812. status:"start",
  1813. create_time:+new Date()
  1814. };
  1815. await importLogsModel.create(data);
  1816. doDownLoadAndImport(privateDownloadUrl,info);
  1817. return result;
  1818. }
  1819. async function doDownLoadAndImport(privateDownloadUrl,info) {
  1820. let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/"+info.key));//
  1821. request(privateDownloadUrl).pipe(stream).on("close", async function (err) {
  1822. console.log("文件[" + info.key + "]下载完毕");
  1823. let doc = {status:"finish"};
  1824. try {
  1825. let data = fs.readFileSync(stream.path,'utf-8');
  1826. let result = await importProjects(data,{session:info.session},info.updateData);
  1827. if(result.error == 1){
  1828. doc.errorMsg = result.msg;
  1829. doc.status = "error";
  1830. }
  1831. }catch (error){
  1832. console.log(error);
  1833. doc.errorMsg = "导入失败,请检查文件!";
  1834. doc.status = "error";
  1835. }finally {
  1836. await importLogsModel.update({key:info.key},doc);
  1837. fs.unlinkSync(stream.path);
  1838. }
  1839. });
  1840. }
  1841. async function importProcessChecking(data){
  1842. let result = {error:0};
  1843. let log = await importLogsModel.findOne({key:data.key});
  1844. if(log){
  1845. if(log.status == "finish"){
  1846. result.status = "complete";
  1847. await importLogsModel.remove({key:data.key});
  1848. }else if(log.status == "start"){
  1849. result.status = "processing";
  1850. }else if(log.status == "error"){
  1851. result.error = 1;
  1852. result.msg = log.errorMsg;
  1853. await importLogsModel.remove({key:data.key});
  1854. }
  1855. }else {
  1856. result.error = 1;
  1857. result.msg = `导入过程中发生错误!`;
  1858. }
  1859. return result;
  1860. }
  1861. // 从cdn服务器下载文件,key就是文件名
  1862. async function downloadFileSync(key) {
  1863. const filePath = path.join(__dirname, '../../../tmp/', key);
  1864. const bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1865. const publicBucketDomain = qiniu_config.Domain; // "http://serverupdate.smartcost.com.cn";//这里不支持https
  1866. const deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1867. const privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, key, deadline);
  1868. const stream = fs.createWriteStream(filePath);
  1869. return new Promise((resolve, reject) => {
  1870. request(privateDownloadUrl)
  1871. .pipe(stream)
  1872. .on('close', () => {
  1873. // 读取文件返回字符串
  1874. const srcData = fs.readFileSync(stream.path,'utf-8');
  1875. resolve({
  1876. path: stream.path,
  1877. srcData: srcData
  1878. });
  1879. })
  1880. .on('error', reject);
  1881. });
  1882. }
  1883. // 导入接口
  1884. async function importInterface(key, session) {
  1885. // 源文件内容文本
  1886. let downloadFilePath = '';
  1887. try {
  1888. const { path, srcData } = await downloadFileSync(key);
  1889. downloadFilePath = path;
  1890. if (!srcData) {
  1891. throw '无有效数据';
  1892. }
  1893. const userID = session.sessionUser.id;
  1894. const compilationID = session.sessionCompilation._id;
  1895. const importData = JSON.parse(srcData);
  1896. let tenderCount = 0;
  1897. importData.engs.forEach(eng => {
  1898. eng.tenders.forEach(tender => {
  1899. tenderCount += 1;
  1900. });
  1901. });
  1902. if (await isTenderOverrun(tenderCount, session)) {
  1903. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  1904. }
  1905. const projectData = await importProject(importData, userID, compilationID);
  1906. return projectData;
  1907. } catch (err) {
  1908. throw err;
  1909. } finally {
  1910. fs.unlinkSync(downloadFilePath);
  1911. }
  1912. }
  1913. async function importProjects(data,req,updateData) {
  1914. let result = {error:0};
  1915. let stringArr = data.split("|----|");
  1916. let datas = [];
  1917. for(let s of stringArr){
  1918. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1919. }
  1920. let mainData = datas.length > 0 ?datas[0]:null;
  1921. if(mainData){
  1922. if(mainData.from && mainData.from != "construction"){
  1923. result.error = 1;
  1924. result.msg = "导入失败:您要导入的文件是由“纵横公路养护云版”导出,当前软件是“大司空云计价”,请选择正确的软件再进行操作!";
  1925. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  1926. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  1927. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的费用定额';
  1928. const curCompilationName = req.session.sessionCompilation.name;
  1929. result.error = 1;
  1930. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的费用定额再进行操作!`;
  1931. }else {
  1932. const tenders = mainData.projects.filter(item => item.projType === projectType.tender);
  1933. const tenderOverrun = await isTenderOverrun(tenders.length, req.session);
  1934. if (tenderOverrun) {
  1935. result.error = 1;
  1936. result.msg = `您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。`;
  1937. }
  1938. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
  1939. if(datas.length > 1 ){
  1940. for(let i = 1;i<datas.length;i++){
  1941. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1942. }
  1943. }
  1944. }
  1945. }
  1946. return result;
  1947. }
  1948. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1949. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[];
  1950. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1951. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1952. let newProjectID = projectIDMap[data.projSetting.projectID];
  1953. //生成新的清单;
  1954. if(data.bills && data.bills.length > 0){
  1955. for(let b of data.bills){
  1956. billsIDMap[b.ID] = uuidV1();
  1957. }
  1958. for(let b of data.bills){
  1959. delete b._id;
  1960. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1961. bills.push(b);
  1962. }
  1963. }
  1964. //生成项目工料机数据
  1965. if(data.projectGLJs && data.projectGLJs.length > 0){
  1966. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1967. for(let i = 0; i < data.projectGLJs.length; i++){
  1968. let d = data.projectGLJs[i];
  1969. delete d._id;
  1970. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1971. projectGLJIDMap[d.id] = newID;
  1972. d.project_id = newProjectID;
  1973. d.id = newID;
  1974. projectGLJs.push(d);
  1975. }
  1976. }
  1977. //生成新的定额
  1978. if(data.rations && data.rations.length > 0){
  1979. for(let r of data.rations){
  1980. rationIDMap[r.ID] = uuidV1();
  1981. }
  1982. for(let r of data.rations){
  1983. delete r._id;
  1984. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1985. rations.push(r);
  1986. }
  1987. }
  1988. //生成定额下挂的定额工料机等等数据
  1989. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1990. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1991. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1992. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1993. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1994. if(data.evaluateList && data.evaluateList.length > 0) evaluateList = setMaterialList(data.evaluateList,newProjectID,projectGLJIDMap);
  1995. if(data.bidList && data.bidList.length > 0) bidList = setMaterialList(data.bidList,newProjectID,projectGLJIDMap);
  1996. if(data.contractorList && data.contractorList.length > 0) contractorList = setMaterialList(data.contractorList,newProjectID,projectGLJIDMap);
  1997. //生成projectSetting 文件
  1998. if(data.projSetting){
  1999. data.projSetting.projectID =newProjectID;
  2000. newProjectSetting = data.projSetting;
  2001. delete newProjectSetting._id;
  2002. }
  2003. //生成计算程序文件,系数文件
  2004. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  2005. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  2006. data.calcProgramsFile.projectID = newProjectID;
  2007. newCalcProgramsFile = data.calcProgramsFile;
  2008. delete newCalcProgramsFile._id;
  2009. }
  2010. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  2011. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  2012. data.labourCoes.projectID = newProjectID;
  2013. newLabourCoe = data.labourCoes;
  2014. delete newLabourCoe._id;
  2015. }
  2016. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  2017. if(bills.length > 0) await insertMany(bills,billsModel);
  2018. if(rations.length > 0) await insertMany(rations,rationModel);
  2019. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  2020. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  2021. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  2022. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  2023. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  2024. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  2025. if(evaluateList.length > 0) await insertMany(evaluateList,evaluateListModel);
  2026. if(bidList.length > 0) await insertMany(bidList,bidListModel);
  2027. if(contractorList.length > 0) await insertMany(contractorList,contractorListModel);
  2028. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  2029. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  2030. }
  2031. function setMaterialList(datas,newProjectID,projectGLJIDMap){
  2032. let arrs = [];
  2033. for(let d of datas){
  2034. arrs.push(getNewMaterial(d,newProjectID,projectGLJIDMap))
  2035. }
  2036. return arrs
  2037. }
  2038. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  2039. let arrs = [];
  2040. for(let d of datas){
  2041. delete d._id;
  2042. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  2043. arrs.push(d);
  2044. }
  2045. return arrs;
  2046. }
  2047. async function handleMainProjectDatas(mainData,updateData,userID) {
  2048. let mainProjectID = -1;
  2049. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  2050. let tasks = [];
  2051. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  2052. //生成新的projectID
  2053. for(let p of mainData.projects){
  2054. let newProjectID = await getCounterID("projects");
  2055. projectIDMap[p.ID] = newProjectID;
  2056. if(p.projType == "Project") mainProjectID = newProjectID;
  2057. if(p.projType == "Tender"){
  2058. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  2059. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  2060. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  2061. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  2062. }
  2063. }
  2064. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  2065. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  2066. for(let p of mainData.projects){
  2067. delete p._id;
  2068. delete p.__v;
  2069. p.ID = projectIDMap[p.ID];
  2070. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  2071. p.ParentID = updateData.self.ParentID;
  2072. p.NextSiblingID = updateData.self.NextSiblingID;
  2073. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  2074. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  2075. }
  2076. //查看是否重名;
  2077. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  2078. if(temp) p.name = p.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '导入)';
  2079. }else {
  2080. p.ParentID = projectIDMap[p.ParentID];
  2081. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  2082. }
  2083. p.userID =userID;
  2084. p.shareInfo=[];
  2085. if(p.projType == "Tender"){
  2086. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  2087. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  2088. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  2089. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  2090. p.property.rootProjectID = mainProjectID
  2091. }
  2092. tasks.push({insertOne: {document: p}})
  2093. }
  2094. //项目树节构数据生成:
  2095. await projectModel.bulkWrite(tasks);
  2096. //生成所有的费率文件
  2097. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  2098. //生成所有的单价文件
  2099. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  2100. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  2101. }
  2102. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  2103. if(!mainData.files.unitFiles) return;
  2104. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  2105. for(let f of mainData.files.unitFiles){
  2106. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  2107. //生成单价文件
  2108. delete file._id;
  2109. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  2110. file.project_id = projectIDMap[file.project_id];
  2111. file.root_project_id = projectIDMap[file.root_project_id];
  2112. file.user_id = userID;
  2113. unitFiles.push(file);
  2114. //生成子数据
  2115. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  2116. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  2117. }
  2118. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  2119. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  2120. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  2121. async function setSubList(oList,nList,fileID,model,UUID=false) {
  2122. for(let o of oList){
  2123. delete o._id;
  2124. o.unit_price_file_id = fileID;
  2125. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  2126. nList.push(o)
  2127. }
  2128. }
  2129. }
  2130. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  2131. let feeRateFiles = [], feeRates = [];
  2132. if(!mainData.files.feeRateFiles) return;
  2133. for(let f of mainData.files.feeRateFiles){
  2134. //生成费率记录
  2135. let rate = f.feeRate;
  2136. delete rate._id;
  2137. rate.ID = uuidV1();
  2138. feeRates.push(rate);
  2139. //生成费率文件记录
  2140. let file = f.feeRateFile;
  2141. delete file._id;
  2142. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  2143. file.userID = userID;
  2144. file.rootProjectID = projectIDMap[file.rootProjectID];
  2145. file.feeRateID = rate.ID;
  2146. feeRateFiles.push(file);
  2147. }
  2148. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  2149. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  2150. }
  2151. // 初始化
  2152. async function initOverHeightItems(engineeringID) {
  2153. const defaultData = [];
  2154. const engineering = await engineeringModel.findById(engineeringID);
  2155. const overHeightLibs = engineering.over_height_lib;
  2156. if (!overHeightLibs || !overHeightLibs.length) {
  2157. return defaultData;
  2158. }
  2159. const overHeightLibID = overHeightLibs[0].id;
  2160. const overHeightLib = await overHeightLibModel.findOne({ID: overHeightLibID});
  2161. return overHeightLib ? overHeightLib.list : defaultData;
  2162. }
  2163. function uploadToken() {
  2164. let options = {
  2165. scope: qiniu_config.Bucket,
  2166. deleteAfterDays: 1,
  2167. returnBody:
  2168. '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
  2169. };
  2170. let putPolicy = new qiniu.rs.PutPolicy(options);
  2171. let token = putPolicy.uploadToken(mac);
  2172. let result = {
  2173. uptoken: token,
  2174. domain: qiniu_config.Domain
  2175. }
  2176. return result
  2177. }
  2178. // 有些方法无法通过中间件就检查单位工程数量是否超限
  2179. // 需要到具体的业务代码中进行判断
  2180. // 这个方法就是具体业务代码中,需要检查单位工程数量是否超限用
  2181. async function isTenderOverrun(tenderCount, session) {
  2182. const userID = session.sessionUser.id;
  2183. const compilation = session.sessionCompilation._id;
  2184. const compilationVersion = session.compilationVersion || '免费';
  2185. let systemSetting = session.systemSetting || (session.systemSetting = await systemSettingMiddleware.getSystemSetting());
  2186. // 这种情况只有在刚上线此功能时会出现,不考虑时间差
  2187. if (!systemSetting) {
  2188. return false;
  2189. }
  2190. const type = compilationVersion.includes('免费') ? 'normal' : 'professional';
  2191. const limit = systemSetting[type].project;
  2192. const curTenderCount = await projectModel.count({userID, compilation, projType: 'Tender', '$or':[{deleteInfo: null}, {'deleteInfo.completeDeleted': false}]});
  2193. return tenderCount + curTenderCount > limit;
  2194. }
  2195. async function getWelcomeInfo(compilationId,sessionUser) {
  2196. let setting = await welcomeModel.findOne({compilationId:compilationId});
  2197. let isShow = false;
  2198. let context = "";
  2199. if(setting){
  2200. if(setting.showType == 0) return [false,""];//关闭
  2201. context = setting.context;
  2202. if(setting.showType == 1){//每天一次
  2203. let dataString =moment(Date.now()).tz("Asia/Shanghai").format('YYYY-MM-DD');//今天的日期字符串
  2204. let userInfo =await userModel.findOne({_id: mongoose.Types.ObjectId(sessionUser.id)});
  2205. if (dataString != userInfo.welcomeShowTime){//今天没登录过
  2206. isShow = true;
  2207. await userModel.update({_id: mongoose.Types.ObjectId(sessionUser.id)},{welcomeShowTime:dataString})
  2208. }
  2209. }else if(setting.showType == 2){//每次登录显示
  2210. isShow = sessionUser.newLogin?true:false;
  2211. sessionUser.newLogin = false
  2212. }
  2213. }
  2214. return [isShow,context]
  2215. }