pm_facade.js 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357
  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.totalFee) ? fee.totalFee : 0;
  802. }
  803. }
  804. return 0;
  805. }
  806. function summarizeToParent(parent, child, fields = null) {
  807. const decimal = -2;
  808. if (!fields) {
  809. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  810. }
  811. for (let field of fields) {
  812. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  813. }
  814. }
  815. function getBuildingArea(projFeature){
  816. if(!projFeature || projFeature.length === 0){
  817. return null;
  818. }
  819. for(let f of projFeature){
  820. if(f.key === 'buildingArea'){
  821. return f.value;
  822. }
  823. }
  824. return null;
  825. }
  826. //根据单位工程ID获取经济指标信息
  827. //@param {Number}prj_id @return {Object}
  828. async function getIndexReportData(prj_id, filters) {
  829. return await project_facade.getIndexReportData(prj_id, filters);
  830. }
  831. // 根据树结构数据排序
  832. function getSortedDataByTree(data) {
  833. // NextSiblingID-数据映射
  834. const mapping = {};
  835. data.forEach(item => {
  836. // 错误数据兼容处理
  837. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  838. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  839. if (!item.NextSiblingID) {
  840. item.NextSiblingID = -1;
  841. }
  842. mapping[item.NextSiblingID] = item;
  843. });
  844. let lastItem = data.find(item => +item.NextSiblingID === -1);
  845. if (!lastItem) {
  846. return data;
  847. }
  848. const rst = [lastItem];
  849. let preItem = mapping[lastItem.ID];
  850. while (preItem) {
  851. rst.unshift(preItem);
  852. preItem = mapping[preItem.ID];
  853. }
  854. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  855. return rst.length === data.length ? rst : data;
  856. }
  857. //根据单位工程ID获取汇总信息
  858. //@param {Number}tenderID {String}summaryType @return {Object}
  859. async function getSummaryInfoByTender(tenderID, summaryType) {
  860. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  861. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  862. let parent,
  863. parentName,
  864. compilationIllustration;
  865. let summaryList = [];
  866. if(!tender){
  867. return null;
  868. }
  869. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  870. if(!engineering){
  871. return null;
  872. }
  873. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  874. if(!project){
  875. return null;
  876. }
  877. let summaryInfo = await getSummaryInfo([project.ID]);
  878. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  879. parent = engineering;
  880. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted}).lean();
  881. tenders = getSortedDataByTree(tenders);
  882. for(let t of tenders){
  883. if(summaryInfo[t.ID]){
  884. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  885. summaryList.push(summaryInfo[t.ID]);
  886. }
  887. }
  888. } else { // 汇总到建设项目级别
  889. parent = project;
  890. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  891. engs = getSortedDataByTree(engs);
  892. for(let e of engs){
  893. if(summaryInfo[e.ID]){
  894. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  895. summaryList.push(summaryInfo[e.ID]);
  896. }
  897. }
  898. }
  899. // 项目名称
  900. parentName = parent && parent.name
  901. ? parent.name
  902. : '';
  903. // 编制说明
  904. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  905. ? parent.property.compilationIllustration
  906. : '';
  907. return {
  908. parent: {
  909. name: parentName,
  910. compilationIllustration: compilationIllustration},
  911. subList: summaryList
  912. };
  913. }
  914. //获取单位工程的各标段费用信息(不进行汇总)
  915. async function getTendersFeeInfo(tenders) {
  916. let IDMapping = {};
  917. //固定清单类别与汇总金额字段映射
  918. let flagFieldMapping = {};
  919. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  920. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  921. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  922. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  923. flagFieldMapping[billsFlags.OTHER] = 'other';
  924. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  925. flagFieldMapping[billsFlags.TAX] = 'tax';
  926. let tenderIDs = [];
  927. if(tenders.length > 0){
  928. for(let tender of tenders){
  929. tenderIDs.push(tender.ID);
  930. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  931. IDMapping[tender.ID]['buildingArea'] = '';
  932. }
  933. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  934. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  935. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  936. //获取单位工程汇总金额需要用到的所有清单
  937. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  938. '-_id projectID fees flags');
  939. //进行单位工程级别的汇总
  940. for(let bills of allBills){
  941. let billsFlag = bills.flags[0]['flag'];
  942. let costField = flagFieldMapping[billsFlag];
  943. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  944. //暂估合价(工程造价暂估合价)
  945. if (billsFlag === billsFlags.ENGINEERINGCOST){
  946. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  947. }
  948. }
  949. //占造价比例、单方造价
  950. for(let tender of tenders){
  951. let tenderInfo = IDMapping[tender.ID];
  952. tenderInfo.rate = '';
  953. //单方造价
  954. tenderInfo.perCost = '';
  955. }
  956. }
  957. return IDMapping;
  958. }
  959. async function getSummaryInfo(projectIDs, feeFields = null, engineeringCostFields = null){
  960. function initFees(obj, feeFields, engineeringCostFields) {
  961. for (let data of feeFields) {
  962. obj[data.v] = 0;
  963. }
  964. for (let data of engineeringCostFields) {
  965. obj[data.k] = 0;
  966. }
  967. }
  968. if (!feeFields) {
  969. feeFields = [
  970. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  971. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  972. {k: billsFlags.MEASURE, v: 'measure'},
  973. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  974. {k: billsFlags.OTHER, v: 'other'},
  975. {k: billsFlags.CHARGE, v: 'charge'},
  976. {k: billsFlags.TAX, v: 'tax'}
  977. ];
  978. }
  979. // 项目总造价的各个费用,k为汇总的字段,v为工程造价的费用字段
  980. if (!engineeringCostFields) {
  981. engineeringCostFields = [{ k: 'estimate', v: 'estimate' }];
  982. }
  983. //ID与汇总信息映射
  984. let IDMapping = {};
  985. //固定清单类别与汇总金额字段映射
  986. let flagFieldMapping = {};
  987. for (let data of feeFields) {
  988. flagFieldMapping[data.k] = data.v;
  989. }
  990. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  991. //设置建设项目的总建筑面积
  992. for(let project of projects){
  993. let grossArea = '';
  994. if(project.property && project.property.basicInformation){
  995. for(let basicInfo of project.property.basicInformation){
  996. if(basicInfo.key === 'basicInfo'){
  997. for(let k of basicInfo.items){
  998. if(k.key === 'grossArea'){
  999. grossArea = k.value;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. IDMapping[project.ID] = {rate: 0, buildingArea: grossArea, perCost: ''};
  1006. initFees(IDMapping[project.ID], feeFields, engineeringCostFields);
  1007. console.log(IDMapping[project.ID]);
  1008. }
  1009. //单项工程
  1010. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1011. let tenders = [];
  1012. let engIDs = [];
  1013. for(let eng of engineerings){
  1014. engIDs.push(eng.ID);
  1015. IDMapping[eng.ID] = {rate: 0, buildingArea: '', perCost: ''};
  1016. initFees(IDMapping[eng.ID], feeFields, engineeringCostFields);
  1017. }
  1018. //单位工程
  1019. if(engIDs.length > 0){
  1020. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1021. }
  1022. let tenderIDs = [];
  1023. if(tenders.length > 0){
  1024. for(let tender of tenders){
  1025. tenderIDs.push(tender.ID);
  1026. IDMapping[tender.ID] = {rate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1027. initFees(IDMapping[tender.ID], feeFields, engineeringCostFields);
  1028. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1029. if(buildingArea){
  1030. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1031. }
  1032. }
  1033. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1034. let needFlags = feeFields.map(data => data.k);
  1035. //获取单位工程汇总金额需要用到的所有清单
  1036. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1037. '-_id projectID fees flags');
  1038. //进行单位工程级别的汇总
  1039. for(let bills of allBills){
  1040. let billsFlag = bills.flags[0]['flag'];
  1041. let costField = flagFieldMapping[billsFlag];
  1042. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1043. // 工程造价各费用
  1044. if (billsFlag === billsFlags.ENGINEERINGCOST){
  1045. engineeringCostFields.forEach(({k, v}) => {
  1046. IDMapping[bills.projectID][k] = getTotalFee(bills, v);
  1047. });
  1048. }
  1049. }
  1050. let summaryFields = [...feeFields, ...engineeringCostFields].map(data => data.v);
  1051. //进行单项工程级别的汇总
  1052. for(let tender of tenders){
  1053. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  1054. }
  1055. //进行建设项目级别的汇总
  1056. for(let eng of engineerings){
  1057. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  1058. }
  1059. //占造价比例、单方造价
  1060. const rateDecimal = -2;
  1061. const perCostDecimal = -2;
  1062. for(let tender of tenders){
  1063. let tenderInfo = IDMapping[tender.ID];
  1064. let engInfo = IDMapping[tender.ParentID];
  1065. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1066. //单方造价
  1067. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1068. ? tenderInfo.buildingArea.toString().trim()
  1069. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1070. }
  1071. for(let eng of engineerings){
  1072. let engInfo = IDMapping[eng.ID];
  1073. let projInfo = IDMapping[eng.ParentID];
  1074. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1075. }
  1076. //建设项目占造价比例及单方造价
  1077. for(let project of projects){
  1078. let projectInfo = IDMapping[project.ID];
  1079. projectInfo.rate = 100;
  1080. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1081. ? projectInfo.buildingArea.toString().trim()
  1082. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1083. }
  1084. }
  1085. return IDMapping;
  1086. }
  1087. //根据项目ID获取所属建设项目
  1088. //@param {Number}projectID @return {Object}
  1089. async function getConstructionProject(projectID){
  1090. function returnProject(project){
  1091. if(!project || project.projType === projectType.folder){
  1092. return null;
  1093. }
  1094. if(project.projType === projectType.project){
  1095. return project;
  1096. }
  1097. }
  1098. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  1099. let returnV = returnProject(project);
  1100. if(returnV !== undefined){
  1101. return returnV;
  1102. }
  1103. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  1104. returnV = returnProject(parent);
  1105. if(returnV !== undefined){
  1106. return returnV;
  1107. }
  1108. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  1109. returnV = returnProject(grandParent);
  1110. return returnV !== undefined ? returnV : null;
  1111. }
  1112. //获取单位工程完整目录结构
  1113. //@param {Number}projectID @return {Arry}
  1114. async function getFullPath(projectID) {
  1115. let fullPath = [];
  1116. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  1117. if(project){
  1118. fullPath.push(project.name);
  1119. await getParent(project.ParentID);
  1120. }
  1121. fullPath = fullPath.reverse();
  1122. return fullPath;
  1123. async function getParent(ParentID) {
  1124. if(ParentID != -1){
  1125. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  1126. if(parent){
  1127. fullPath.push(parent.name);
  1128. await getParent(parent.ParentID);
  1129. }
  1130. }
  1131. }
  1132. }
  1133. // 获取项目链上,自身、父项、爷爷项...的ID
  1134. async function getUpChainIDs(projectID) {
  1135. const rst = [];
  1136. while (projectID != -1) {
  1137. rst.push(projectID);
  1138. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  1139. projectID = project ? project.ParentID : -1;
  1140. }
  1141. return rst;
  1142. }
  1143. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  1144. async function getPosterityProjects(projectIDs) {
  1145. let rst = [];
  1146. async function getProjects(parentIDs) {
  1147. if (parentIDs.length > 0) {
  1148. let newIDs = [];
  1149. let projs = await projectModel.find({ParentID: {$in: parentIDs}, $or: notDeleted}, '-_id').lean();
  1150. for (let proj of projs) {
  1151. // 兼容旧的错误数据,可能ParentID和ID相同
  1152. if (parentIDs.includes(proj.ID)) {
  1153. continue;
  1154. }
  1155. rst.push(proj);
  1156. newIDs.push(proj.ID);
  1157. }
  1158. await getProjects(newIDs);
  1159. }
  1160. }
  1161. await getProjects(projectIDs);
  1162. return rst;
  1163. }
  1164. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  1165. async function getShareInfo(userID, projectID) {
  1166. // 接受到的分享项目
  1167. const upChainIDs = await getUpChainIDs(projectID);
  1168. const shareList = await getShareList({receiver: userID, projectID: {$in: upChainIDs}});
  1169. // 返回最新的分享
  1170. //return shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate))[0];
  1171. return shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate))[0];
  1172. }
  1173. //打开的单位工程是否是被分享的.
  1174. async function isShare(userId, project){
  1175. //判断是否是打开分享的项目,属于分享文件的子项也算
  1176. while (project) {
  1177. for(let shareData of project.shareInfo){
  1178. if(shareData.userID === userId){
  1179. return true;
  1180. }
  1181. }
  1182. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1183. }
  1184. return false;
  1185. }
  1186. //用户是否第一次进入费用定额
  1187. async function isFirst(userId, compilationId) {
  1188. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1189. let first = false;
  1190. if (userData) {
  1191. first = !_.find(userData.used_list, function (o) {
  1192. return o.compilationId === compilationId;
  1193. });;
  1194. }
  1195. return first;
  1196. }
  1197. async function importChongqingProject(data) {
  1198. let log_data = {
  1199. key:data.key,
  1200. userID:data.user_id,
  1201. status:"start",
  1202. create_time:+new Date()
  1203. };
  1204. await importLogsModel.create(log_data);
  1205. doImport(data.user_id,data.session.sessionCompilation._id,data.session.sessionCompilation.adProjects,data.key);
  1206. return "start importing";
  1207. async function doImport(user_id,compilationId,projectIDs,key) {
  1208. let doc = {status:"finish"};
  1209. try {
  1210. let r = await copyExample(user_id,compilationId,projectIDs);
  1211. if(r == false){
  1212. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1213. doc.status = "error";
  1214. }
  1215. }catch (error){
  1216. console.log(error);
  1217. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1218. doc.status = "error";
  1219. }finally {
  1220. await importLogsModel.update({key:key},doc);
  1221. }
  1222. }
  1223. }
  1224. //用户第一次进入费用定额的数据准备
  1225. async function prepareInitialData(userId, compilation, example) {
  1226. let first = await isFirst(userId, compilation);
  1227. if (first) {
  1228. await updateUsedList(userId, compilation);
  1229. let prepareTask = [
  1230. copyCompleRationSection(userId, compilation),
  1231. copyCompleGljSection(userId, compilation)
  1232. ];
  1233. if (example && example.length > 0) {
  1234. prepareTask.push(copyExample(userId, compilation, example));
  1235. }
  1236. await Promise.all(prepareTask);
  1237. }
  1238. }
  1239. async function updateUsedList(userId, compilation) {
  1240. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1241. }
  1242. //拷贝补充定额章节树
  1243. async function copyCompleRationSection(userId, compilationId) {
  1244. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1245. }
  1246. //拷贝补充人材机分类树
  1247. async function copyCompleGljSection(userId, compilationId) {
  1248. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  1249. if (templateData.length > 0) {
  1250. let insertDatas = [],
  1251. uuidMapping = {};
  1252. //将ID替换成UUID
  1253. for (let temData of templateData) {
  1254. uuidMapping[temData.ID] = uuidV1();
  1255. }
  1256. for(let temData of templateData) {
  1257. let insertD = {
  1258. userId: userId,
  1259. compilationId: compilationId,
  1260. Name: temData.Name,
  1261. ID: uuidMapping[temData.ID],
  1262. ParentID: uuidMapping[temData.ParentID] || -1,
  1263. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1264. };
  1265. insertDatas.push(insertD);
  1266. }
  1267. //插入数据
  1268. await compleGljSectionModel.insertMany(insertDatas);
  1269. }
  1270. }
  1271. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1272. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1273. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1274. for(let d of datas){
  1275. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1276. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1277. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1278. newFile = {id:newID,name:tem_file.name};
  1279. type = 0;
  1280. }
  1281. projectIDs.push({ID:d.projectID})
  1282. }
  1283. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1284. }
  1285. //获取费用定额绑定的基本信息库数据
  1286. async function getBasicInfo(compilationID, fileKind = null) {
  1287. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1288. if (!compilation) {
  1289. return null;
  1290. }
  1291. let billValuation = compilation.bill_valuation.find(function (data) {
  1292. return data.enable;
  1293. });
  1294. if (!billValuation) {
  1295. return null;
  1296. }
  1297. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1298. let engineering = engineerings.find(function (data) {
  1299. return data.info_lib && data.info_lib.length > 0;
  1300. });
  1301. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1302. return null;
  1303. }
  1304. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1305. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1306. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1307. let strMap = {
  1308. 1: 'tender', //投标
  1309. 2: 'bid', //招标
  1310. 3: 'control' //控制价
  1311. };
  1312. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1313. needfulData.forEach(nData => {
  1314. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1315. nData.items = needfulSub;
  1316. });
  1317. infoLib.info = needfulData;
  1318. }
  1319. return infoLib;
  1320. }
  1321. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1322. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1323. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1324. return null;
  1325. }
  1326. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1327. return featureLib;
  1328. }
  1329. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1330. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1331. async function getProjectByGranularity(tenderID, granularity, summaryObj, userID, versionName) {
  1332. const GRANULARITY = {
  1333. PROJECT: 1,
  1334. ENGINEERING: 2,
  1335. TENDER: 3
  1336. };
  1337. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}).lean(); //加上session的userID,防止tenderID被篡改过
  1338. if (!theTender) {
  1339. return null;
  1340. }
  1341. let theEngineering = await projectModel.findOne({ID: theTender.ParentID}).lean();
  1342. if (!theEngineering) {
  1343. return null;
  1344. }
  1345. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID}).lean();
  1346. if (!constructionProject) {
  1347. return null;
  1348. }
  1349. let engineerings;
  1350. if (granularity === GRANULARITY.PROJECT) {
  1351. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted}).lean();
  1352. for (let eng of engineerings) {
  1353. eng.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted}).lean();
  1354. }
  1355. } else {
  1356. engineerings = [theEngineering];
  1357. if (granularity === GRANULARITY.ENGINEERING) {
  1358. theEngineering.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted}).lean();
  1359. } else {
  1360. theEngineering.children = [theTender];
  1361. }
  1362. }
  1363. constructionProject.children = engineerings;
  1364. //获取汇总信息
  1365. const { feeFields, engineeringCostFields } = summaryObj;
  1366. constructionProject.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields, engineeringCostFields);
  1367. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1368. let product = await productModel.findOne({});
  1369. let company = product.company || '珠海纵横创新软件有限公司',
  1370. version = product.version || '';
  1371. constructionProject.softInfo = `${company};${versionName};${version};${userID}`;
  1372. return constructionProject;
  1373. }
  1374. //获取项目数据占位ID
  1375. async function getProjectPlaceholder(data) {
  1376. let rst = {};
  1377. //项目本身数据
  1378. if (data.projectCount) {
  1379. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1380. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1381. }
  1382. //项目人材机数据
  1383. if (data.projectGLJCount) {
  1384. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1385. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1386. }
  1387. //组成物数据
  1388. if (data.ratioCount) {
  1389. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1390. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1391. }
  1392. //单价文件数据
  1393. if (data.unitPriceFileCount) {
  1394. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1395. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1396. }
  1397. //单价数据
  1398. if (data.unitPriceCount) {
  1399. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1400. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1401. }
  1402. return rst;
  1403. }
  1404. /*
  1405. * 接口导入 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1406. * */
  1407. async function importProject(importObj, userID, compilationID) {
  1408. let toInsertProjects = [importObj]; //待新增项目数据
  1409. await setupProject(importObj);
  1410. //设置项目ID及相关数据
  1411. for (let curEng of importObj.engs) {
  1412. await setupProject(curEng);
  1413. toInsertProjects.push(curEng);
  1414. for (let curTender of curEng.tenders) {
  1415. await setupProject(curTender.tender);
  1416. //插入单位工程的详细数据
  1417. await importTenderDetail(curTender);
  1418. toInsertProjects.push(curTender.tender);
  1419. }
  1420. delete curEng.tenders;
  1421. }
  1422. delete importObj.engs;
  1423. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1424. let bulks = [];
  1425. //如果有前节点,更新前节点
  1426. if (importObj.preID !== -1) {
  1427. bulks.push({
  1428. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1429. });
  1430. }
  1431. for (let insertP of toInsertProjects) {
  1432. bulks.push({
  1433. insertOne: {document: insertP}
  1434. });
  1435. }
  1436. if (bulks.length > 0) {
  1437. await projectModel.bulkWrite(bulks);
  1438. }
  1439. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1440. //设置汇总字段
  1441. for(let proj of toInsertProjects){
  1442. let summaryProj = summaryInfo[proj.ID];
  1443. if(summaryProj){
  1444. proj.engineeringCost = summaryProj.engineeringCost;
  1445. proj.subEngineering = summaryProj.subEngineering;
  1446. proj.measure = summaryProj.measure;
  1447. proj.safetyConstruction = summaryProj.safetyConstruction;
  1448. proj.other = summaryProj.other;
  1449. proj.charge = summaryProj.charge;
  1450. proj.tax = summaryProj.tax;
  1451. proj.rate = summaryProj.rate;
  1452. proj.buildingArea = summaryProj.buildingArea;
  1453. proj.perCost = summaryProj.perCost;
  1454. }
  1455. }
  1456. return toInsertProjects;
  1457. //给项目数据设置一些需要的数据
  1458. async function setupProject(data) {
  1459. data.userID = userID;
  1460. data.compilation = compilationID;
  1461. data.fileVer = G_FILE_VER;
  1462. data.createDateTime = new Date();
  1463. if (data.projType === 'Project') {
  1464. await setupConstruct(data);
  1465. } else if (data.projType === 'Tender') {
  1466. await setupTender(data);
  1467. }
  1468. }
  1469. //给建设项目设置一些数据
  1470. async function setupConstruct(data) {
  1471. //更新基本信息, 按照key匹配
  1472. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1473. if (infoLib) {
  1474. //标准基本信息库的数据打平
  1475. let flatDatas = [];
  1476. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1477. data.basicInformation.forEach(importI => {
  1478. flatDatas.forEach(item => {
  1479. if (item.key === 'engineeringName') {
  1480. item.value = data.name;
  1481. } else if (item.key === 'fileKind') {
  1482. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1483. } else if (item.key === 'taxModel') {
  1484. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1485. }
  1486. if (item.key === importI.key) {
  1487. item.value = importI.value;
  1488. }
  1489. });
  1490. });
  1491. }
  1492. data.property.basicInformation = infoLib ? infoLib.info : [];
  1493. }
  1494. //给单位工程设置一些数据
  1495. async function setupTender(data) {
  1496. //小数位数 需要修改,所以深拷贝
  1497. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  1498. // 定额工程量、人材机消耗量精度设为最大6
  1499. data.property.decimal.ration.quantity = 6;
  1500. data.property.decimal.glj.quantity = 6;
  1501. //清单工程量精度 需要修改,所以深拷贝
  1502. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1503. // 清单工程量精度设置最大4
  1504. data.property.billsQuantityDecimal.forEach(data => data.decimal = 4);
  1505. //呈现选项
  1506. data.property.displaySetting = displaySetting;
  1507. data.property.billsCalcMode = 0;
  1508. data.property.zanguCalcMode = 0;
  1509. //计算选项
  1510. data.property.calcOptions = calcOptions;
  1511. //安装增加费
  1512. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1513. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1514. }
  1515. //锁定清单
  1516. data.property.lockBills = true;
  1517. //工料机单价调整系数
  1518. data.property.tenderSetting = tenderSetting;
  1519. //工程特征相关更新
  1520. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1521. if (featureLib) {
  1522. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1523. data.projectFeature.forEach(importF => {
  1524. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1525. if (matchData) {
  1526. matchData.value = importF.value;
  1527. }
  1528. });
  1529. //设置工程专业的值为费用标准的值..
  1530. featureLib.feature.forEach(f => {
  1531. if (f.key === 'engineering') {
  1532. f.value = data.property.feeStandardName;
  1533. }
  1534. });
  1535. }
  1536. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1537. // 指标信息相关设置
  1538. await project_facade.setSEILibData(data.property);
  1539. }
  1540. }
  1541. //插入单位工程内部详细数据
  1542. async function importTenderDetail(tenderData) {
  1543. //单价文件
  1544. let upFile = {
  1545. id: tenderData.tender.property.unitPriceFile.id,
  1546. name: tenderData.tender.name,
  1547. project_id: tenderData.tender.ID,
  1548. user_id: tenderData.tender.userID,
  1549. root_project_id: tenderData.tender.property.rootProjectID
  1550. };
  1551. await unitPriceFileModel.create(upFile);
  1552. //费率文件
  1553. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1554. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1555. //人工系数文件
  1556. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1557. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1558. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1559. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1560. //列设置
  1561. let engineeringModel = new EngineeringLibModel();
  1562. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1563. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1564. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1565. //清单
  1566. if (tenderData.bills.length) {
  1567. await billsModel.insertMany(tenderData.bills);
  1568. }
  1569. //投标文件中,才会有下面这些数据
  1570. if (enterDetail(tenderData)) {
  1571. //匹配标准数据,更新一些标准数据
  1572. await setupStdData(tenderData);
  1573. let task = [];
  1574. //定额
  1575. if (tenderData.ration.length) {
  1576. task.push(rationModel.insertMany(tenderData.ration))
  1577. }
  1578. //定额人材机
  1579. if (tenderData.rationGLJ.length) {
  1580. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1581. }
  1582. //定额调整系数
  1583. if (tenderData.rationCoe.length) {
  1584. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1585. }
  1586. //项目人材机
  1587. if (tenderData.projectGLJ.length) {
  1588. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1589. }
  1590. // 承包人材料
  1591. if (tenderData.contractorList.length) {
  1592. task.push(contractorListModel.insertMany(tenderData.contractorList));
  1593. }
  1594. // 评标材料表
  1595. if (tenderData.bidEvaluationList.length) {
  1596. task.push(bidListModel.insertMany(tenderData.bidEvaluationList));
  1597. }
  1598. // 暂估价材料表
  1599. if (tenderData.evaluationList.length) {
  1600. task.push(evaluateListModel.insertMany(tenderData.evaluationList));
  1601. }
  1602. //组成物
  1603. if (tenderData.mixRatio.length) {
  1604. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1605. }
  1606. //单价文件
  1607. if (tenderData.unitPrice.length) {
  1608. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1609. }
  1610. await Promise.all(task);
  1611. }
  1612. //继续处理定额等数据
  1613. function enterDetail(tenderData) {
  1614. return tenderData.ration.length ||
  1615. tenderData.rationGLJ.length ||
  1616. tenderData.projectGLJ.length ||
  1617. tenderData.mixRatio.length ||
  1618. tenderData.unitPrice.length;
  1619. }
  1620. }
  1621. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1622. async function setupStdData(tenderData) {
  1623. //获取标准定额数据 (定额子目的编码查找)
  1624. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1625. if (!matchRationCodes.length) {
  1626. return;
  1627. }
  1628. //限制在当前费用定额可用的定额库里查找
  1629. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1630. '-_id -rationAssList -rationCoeList -rationInstList');
  1631. //标准定额code - 映射
  1632. let stdRationCodeMap = {};
  1633. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1634. //获取标准人材机数据 (人材机汇总的编码查找)
  1635. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1636. if (!matchGLJCodes.length) {
  1637. return;
  1638. }
  1639. //限制在当前费用定额可用的人材机库里查找
  1640. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1641. '-_id -component -priceProperty');
  1642. //标准人材机code - 映射
  1643. let stdGLJCodeMap = {};
  1644. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1645. //更新定额数据
  1646. tenderData.ration.forEach(r => {
  1647. let stdRation = stdRationCodeMap[r.code];
  1648. if (stdRation) {
  1649. r.caption = stdRation.caption;
  1650. r.from = 'std';
  1651. r.libID = stdRation.rationRepId;
  1652. r.stdID = stdRation.ID;
  1653. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1654. r.content = stdRation.jobContent;
  1655. if (stdRation.feeType) {
  1656. r.programID = stdRation.feeType;
  1657. } else {
  1658. // 是标准定额,但是该标准定额取费专业为空,取定额取费专业(后台配置项)
  1659. r.programID = tenderData.tender.property.engineering;
  1660. }
  1661. } else {
  1662. r.from = 'cpt';
  1663. r.prefix = '补';
  1664. }
  1665. });
  1666. //更新定额人材机数据
  1667. tenderData.rationGLJ.forEach(rGLJ => {
  1668. rGLJ.from = 'cpt';
  1669. //匹配定额
  1670. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1671. if (stdRation) {
  1672. //根据导入数据的定额人材机编码匹配人材机
  1673. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1674. if (stdGLJ) {
  1675. rGLJ.from = 'std';
  1676. rGLJ.GLJID = stdGLJ.ID;
  1677. rGLJ.type = stdGLJ.gljType;
  1678. rGLJ.shortName = stdGLJ.shortName;
  1679. rGLJ.repositoryId = stdGLJ.repositoryId;
  1680. rGLJ.model = stdGLJ.model;
  1681. rGLJ.adjCoe = stdGLJ.adjCoe;
  1682. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1683. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1684. if (stdRationGLJ) {
  1685. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1686. }
  1687. }
  1688. }
  1689. });
  1690. //更新人材机汇总数据
  1691. tenderData.projectGLJ.forEach(pGLJ => {
  1692. if (!pGLJ.specs) {
  1693. pGLJ.specs = null;
  1694. }
  1695. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1696. if (stdGLJ) {
  1697. pGLJ.glj_id = stdGLJ.ID;
  1698. pGLJ.model = stdGLJ.model;
  1699. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1700. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1701. let ratios = tenderData.mixRatio.filter(ratio =>
  1702. ratio.connect_key === keyStr);
  1703. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1704. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1705. }
  1706. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1707. }
  1708. });
  1709. //更新单价文件数据
  1710. tenderData.unitPrice.forEach(up => {
  1711. let stdGLJ = stdGLJCodeMap[up.original_code];
  1712. if (stdGLJ) {
  1713. up.glj_id = stdGLJ.ID;
  1714. up.type = stdGLJ.gljType;
  1715. up.short_name = stdGLJ.shortName;
  1716. }
  1717. });
  1718. //更新组成物数据
  1719. tenderData.mixRatio.forEach(ratio => {
  1720. let stdGLJ = stdGLJCodeMap[ratio.code];
  1721. if (stdGLJ) {
  1722. ratio.glj_id = stdGLJ.ID;
  1723. ratio.type = stdGLJ.gljType;
  1724. }
  1725. });
  1726. }
  1727. async function exportProject(userID,data){//导出建设项目
  1728. if(data.type == 'main'){
  1729. return await exportMainData(userID,data.projectID);
  1730. }else {
  1731. return await exportTenderData(data);
  1732. }
  1733. }
  1734. async function exportMainData(userID,projectID) {
  1735. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  1736. let tenderIDs = [];
  1737. let project = await projectModel.findOne({ID:projectID});
  1738. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  1739. result['compilationID'] = project.compilation;
  1740. result['from'] = "construction";
  1741. result.projects.push(project);
  1742. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  1743. for(let s of subProjects){
  1744. if(!s.deleteInfo || !s.deleteInfo.deleted){
  1745. result.projects.push(s);
  1746. if(s.projType =="Tender") tenderIDs.push(s.ID);
  1747. }
  1748. }
  1749. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  1750. result.files = files;
  1751. result = cipher.aesEncrypt(JSON.stringify(result));
  1752. result +="|----|" +JSON.stringify(tenderIDs);
  1753. return result;
  1754. }
  1755. async function exportUnitFiles(rootProjectID){
  1756. let unitFiles = [];
  1757. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  1758. for(let f of files){
  1759. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1760. let tem = {unitFile:f};
  1761. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1762. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1763. unitFiles.push(tem);
  1764. }
  1765. return unitFiles;
  1766. }
  1767. async function exportFeeRateFiles(rootProjectID) {
  1768. let feeRateFiles = [];
  1769. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1770. for(let f of files){
  1771. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1772. let tem = {feeRateFile:f};
  1773. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1774. feeRateFiles.push(tem);
  1775. }
  1776. return feeRateFiles;
  1777. }
  1778. async function exportTenderData(data){
  1779. let result = {};
  1780. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1781. if(projectSetting) result['projSetting'] = projectSetting;
  1782. result.bills = await billsModel.find({"projectID": data.projectID});
  1783. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1784. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1785. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1786. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1787. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1788. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1789. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1790. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1791. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1792. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1793. result.evaluateList = await evaluateListModel.find({projectID:data.projectID}, '-_id').lean();
  1794. result.bidList = await bidListModel.find({projectID:data.projectID}, '-_id').lean();
  1795. result.contractorList = await contractorListModel.find({projectID:data.projectID}, '-_id').lean();
  1796. return cipher.aesEncrypt(JSON.stringify(result));
  1797. }
  1798. async function downLoadProjectFile(info) {
  1799. let result = {error:0};
  1800. let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1801. let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
  1802. let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1803. let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
  1804. console.log(privateDownloadUrl);
  1805. let data = {
  1806. key:info.key,
  1807. userID:info.session.sessionUser.id,
  1808. status:"start",
  1809. create_time:+new Date()
  1810. };
  1811. await importLogsModel.create(data);
  1812. doDownLoadAndImport(privateDownloadUrl,info);
  1813. return result;
  1814. }
  1815. async function doDownLoadAndImport(privateDownloadUrl,info) {
  1816. let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/"+info.key));//
  1817. request(privateDownloadUrl).pipe(stream).on("close", async function (err) {
  1818. console.log("文件[" + info.key + "]下载完毕");
  1819. let doc = {status:"finish"};
  1820. try {
  1821. let data = fs.readFileSync(stream.path,'utf-8');
  1822. let result = await importProjects(data,{session:info.session},info.updateData);
  1823. if(result.error == 1){
  1824. doc.errorMsg = result.msg;
  1825. doc.status = "error";
  1826. }
  1827. }catch (error){
  1828. console.log(error);
  1829. doc.errorMsg = "导入失败,请检查文件!";
  1830. doc.status = "error";
  1831. }finally {
  1832. await importLogsModel.update({key:info.key},doc);
  1833. fs.unlinkSync(stream.path);
  1834. }
  1835. });
  1836. }
  1837. async function importProcessChecking(data){
  1838. let result = {error:0};
  1839. let log = await importLogsModel.findOne({key:data.key});
  1840. if(log){
  1841. if(log.status == "finish"){
  1842. result.status = "complete";
  1843. await importLogsModel.remove({key:data.key});
  1844. }else if(log.status == "start"){
  1845. result.status = "processing";
  1846. }else if(log.status == "error"){
  1847. result.error = 1;
  1848. result.msg = log.errorMsg;
  1849. await importLogsModel.remove({key:data.key});
  1850. }
  1851. }else {
  1852. result.error = 1;
  1853. result.msg = `导入过程中发生错误!`;
  1854. }
  1855. return result;
  1856. }
  1857. // 从cdn服务器下载文件,key就是文件名
  1858. async function downloadFileSync(key) {
  1859. const filePath = path.join(__dirname, '../../../tmp/', key);
  1860. const bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  1861. const publicBucketDomain = qiniu_config.Domain; // "http://serverupdate.smartcost.com.cn";//这里不支持https
  1862. const deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  1863. const privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, key, deadline);
  1864. const stream = fs.createWriteStream(filePath);
  1865. return new Promise((resolve, reject) => {
  1866. request(privateDownloadUrl)
  1867. .pipe(stream)
  1868. .on('close', () => {
  1869. // 读取文件返回字符串
  1870. const srcData = fs.readFileSync(stream.path,'utf-8');
  1871. resolve({
  1872. path: stream.path,
  1873. srcData: srcData
  1874. });
  1875. })
  1876. .on('error', reject);
  1877. });
  1878. }
  1879. // 导入接口
  1880. async function importInterface(key, session) {
  1881. // 源文件内容文本
  1882. let downloadFilePath = '';
  1883. try {
  1884. const { path, srcData } = await downloadFileSync(key);
  1885. downloadFilePath = path;
  1886. if (!srcData) {
  1887. throw '无有效数据';
  1888. }
  1889. const userID = session.sessionUser.id;
  1890. const compilationID = session.sessionCompilation._id;
  1891. const importData = JSON.parse(srcData);
  1892. let tenderCount = 0;
  1893. importData.engs.forEach(eng => {
  1894. eng.tenders.forEach(tender => {
  1895. tenderCount += 1;
  1896. });
  1897. });
  1898. if (await isTenderOverrun(tenderCount, session)) {
  1899. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  1900. }
  1901. const projectData = await importProject(importData, userID, compilationID);
  1902. return projectData;
  1903. } catch (err) {
  1904. throw err;
  1905. } finally {
  1906. fs.unlinkSync(downloadFilePath);
  1907. }
  1908. }
  1909. async function importProjects(data,req,updateData) {
  1910. let result = {error:0};
  1911. let stringArr = data.split("|----|");
  1912. let datas = [];
  1913. for(let s of stringArr){
  1914. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1915. }
  1916. let mainData = datas.length > 0 ?datas[0]:null;
  1917. if(mainData){
  1918. if(mainData.from && mainData.from != "construction"){
  1919. result.error = 1;
  1920. result.msg = "导入失败:您要导入的文件是由“纵横公路养护云版”导出,当前软件是“大司空云计价”,请选择正确的软件再进行操作!";
  1921. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  1922. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  1923. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的费用定额';
  1924. const curCompilationName = req.session.sessionCompilation.name;
  1925. result.error = 1;
  1926. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的费用定额再进行操作!`;
  1927. }else {
  1928. const tenders = mainData.projects.filter(item => item.projType === projectType.tender);
  1929. const tenderOverrun = await isTenderOverrun(tenders.length, req.session);
  1930. if (tenderOverrun) {
  1931. result.error = 1;
  1932. result.msg = `您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。`;
  1933. }
  1934. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
  1935. if(datas.length > 1 ){
  1936. for(let i = 1;i<datas.length;i++){
  1937. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1938. }
  1939. }
  1940. }
  1941. }
  1942. return result;
  1943. }
  1944. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1945. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[];
  1946. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1947. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1948. let newProjectID = projectIDMap[data.projSetting.projectID];
  1949. //生成新的清单;
  1950. if(data.bills && data.bills.length > 0){
  1951. for(let b of data.bills){
  1952. billsIDMap[b.ID] = uuidV1();
  1953. }
  1954. for(let b of data.bills){
  1955. delete b._id;
  1956. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1957. bills.push(b);
  1958. }
  1959. }
  1960. //生成项目工料机数据
  1961. if(data.projectGLJs && data.projectGLJs.length > 0){
  1962. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1963. for(let i = 0; i < data.projectGLJs.length; i++){
  1964. let d = data.projectGLJs[i];
  1965. delete d._id;
  1966. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1967. projectGLJIDMap[d.id] = newID;
  1968. d.project_id = newProjectID;
  1969. d.id = newID;
  1970. projectGLJs.push(d);
  1971. }
  1972. }
  1973. //生成新的定额
  1974. if(data.rations && data.rations.length > 0){
  1975. for(let r of data.rations){
  1976. rationIDMap[r.ID] = uuidV1();
  1977. }
  1978. for(let r of data.rations){
  1979. delete r._id;
  1980. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1981. rations.push(r);
  1982. }
  1983. }
  1984. //生成定额下挂的定额工料机等等数据
  1985. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1986. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1987. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1988. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1989. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1990. if(data.evaluateList && data.evaluateList.length > 0) evaluateList = setMaterialList(data.evaluateList,newProjectID,projectGLJIDMap);
  1991. if(data.bidList && data.bidList.length > 0) bidList = setMaterialList(data.bidList,newProjectID,projectGLJIDMap);
  1992. if(data.contractorList && data.contractorList.length > 0) contractorList = setMaterialList(data.contractorList,newProjectID,projectGLJIDMap);
  1993. //生成projectSetting 文件
  1994. if(data.projSetting){
  1995. data.projSetting.projectID =newProjectID;
  1996. newProjectSetting = data.projSetting;
  1997. delete newProjectSetting._id;
  1998. }
  1999. //生成计算程序文件,系数文件
  2000. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  2001. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  2002. data.calcProgramsFile.projectID = newProjectID;
  2003. newCalcProgramsFile = data.calcProgramsFile;
  2004. delete newCalcProgramsFile._id;
  2005. }
  2006. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  2007. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  2008. data.labourCoes.projectID = newProjectID;
  2009. newLabourCoe = data.labourCoes;
  2010. delete newLabourCoe._id;
  2011. }
  2012. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  2013. if(bills.length > 0) await insertMany(bills,billsModel);
  2014. if(rations.length > 0) await insertMany(rations,rationModel);
  2015. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  2016. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  2017. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  2018. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  2019. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  2020. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  2021. if(evaluateList.length > 0) await insertMany(evaluateList,evaluateListModel);
  2022. if(bidList.length > 0) await insertMany(bidList,bidListModel);
  2023. if(contractorList.length > 0) await insertMany(contractorList,contractorListModel);
  2024. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  2025. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  2026. }
  2027. function setMaterialList(datas,newProjectID,projectGLJIDMap){
  2028. let arrs = [];
  2029. for(let d of datas){
  2030. arrs.push(getNewMaterial(d,newProjectID,projectGLJIDMap))
  2031. }
  2032. return arrs
  2033. }
  2034. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  2035. let arrs = [];
  2036. for(let d of datas){
  2037. delete d._id;
  2038. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  2039. arrs.push(d);
  2040. }
  2041. return arrs;
  2042. }
  2043. async function handleMainProjectDatas(mainData,updateData,userID) {
  2044. let mainProjectID = -1;
  2045. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  2046. let tasks = [];
  2047. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  2048. //生成新的projectID
  2049. for(let p of mainData.projects){
  2050. let newProjectID = await getCounterID("projects");
  2051. projectIDMap[p.ID] = newProjectID;
  2052. if(p.projType == "Project") mainProjectID = newProjectID;
  2053. if(p.projType == "Tender"){
  2054. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  2055. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  2056. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  2057. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  2058. }
  2059. }
  2060. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  2061. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  2062. for(let p of mainData.projects){
  2063. delete p._id;
  2064. delete p.__v;
  2065. p.ID = projectIDMap[p.ID];
  2066. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  2067. p.ParentID = updateData.self.ParentID;
  2068. p.NextSiblingID = updateData.self.NextSiblingID;
  2069. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  2070. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  2071. }
  2072. //查看是否重名;
  2073. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  2074. if(temp) p.name = p.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '导入)';
  2075. }else {
  2076. p.ParentID = projectIDMap[p.ParentID];
  2077. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  2078. }
  2079. p.userID =userID;
  2080. p.shareInfo=[];
  2081. if(p.projType == "Tender"){
  2082. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  2083. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  2084. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  2085. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  2086. p.property.rootProjectID = mainProjectID
  2087. }
  2088. tasks.push({insertOne: {document: p}})
  2089. }
  2090. //项目树节构数据生成:
  2091. await projectModel.bulkWrite(tasks);
  2092. //生成所有的费率文件
  2093. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  2094. //生成所有的单价文件
  2095. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  2096. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  2097. }
  2098. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  2099. if(!mainData.files.unitFiles) return;
  2100. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  2101. for(let f of mainData.files.unitFiles){
  2102. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  2103. //生成单价文件
  2104. delete file._id;
  2105. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  2106. file.project_id = projectIDMap[file.project_id];
  2107. file.root_project_id = projectIDMap[file.root_project_id];
  2108. file.user_id = userID;
  2109. unitFiles.push(file);
  2110. //生成子数据
  2111. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  2112. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  2113. }
  2114. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  2115. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  2116. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  2117. async function setSubList(oList,nList,fileID,model,UUID=false) {
  2118. for(let o of oList){
  2119. delete o._id;
  2120. o.unit_price_file_id = fileID;
  2121. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  2122. nList.push(o)
  2123. }
  2124. }
  2125. }
  2126. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  2127. let feeRateFiles = [], feeRates = [];
  2128. if(!mainData.files.feeRateFiles) return;
  2129. for(let f of mainData.files.feeRateFiles){
  2130. //生成费率记录
  2131. let rate = f.feeRate;
  2132. delete rate._id;
  2133. rate.ID = uuidV1();
  2134. feeRates.push(rate);
  2135. //生成费率文件记录
  2136. let file = f.feeRateFile;
  2137. delete file._id;
  2138. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  2139. file.userID = userID;
  2140. file.rootProjectID = projectIDMap[file.rootProjectID];
  2141. file.feeRateID = rate.ID;
  2142. feeRateFiles.push(file);
  2143. }
  2144. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  2145. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  2146. }
  2147. // 初始化
  2148. async function initOverHeightItems(engineeringID) {
  2149. const defaultData = [];
  2150. const engineering = await engineeringModel.findById(engineeringID);
  2151. const overHeightLibs = engineering.over_height_lib;
  2152. if (!overHeightLibs || !overHeightLibs.length) {
  2153. return defaultData;
  2154. }
  2155. const overHeightLibID = overHeightLibs[0].id;
  2156. const overHeightLib = await overHeightLibModel.findOne({ID: overHeightLibID});
  2157. return overHeightLib ? overHeightLib.list : defaultData;
  2158. }
  2159. function uploadToken() {
  2160. let options = {
  2161. scope: qiniu_config.Bucket,
  2162. deleteAfterDays: 1,
  2163. returnBody:
  2164. '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
  2165. };
  2166. let putPolicy = new qiniu.rs.PutPolicy(options);
  2167. let token = putPolicy.uploadToken(mac);
  2168. let result = {
  2169. uptoken: token,
  2170. domain: qiniu_config.Domain
  2171. }
  2172. return result
  2173. }
  2174. // 有些方法无法通过中间件就检查单位工程数量是否超限
  2175. // 需要到具体的业务代码中进行判断
  2176. // 这个方法就是具体业务代码中,需要检查单位工程数量是否超限用
  2177. async function isTenderOverrun(tenderCount, session) {
  2178. const userID = session.sessionUser.id;
  2179. const compilation = session.sessionCompilation._id;
  2180. const compilationVersion = session.compilationVersion || '免费';
  2181. let systemSetting = session.systemSetting || (session.systemSetting = await systemSettingMiddleware.getSystemSetting());
  2182. // 这种情况只有在刚上线此功能时会出现,不考虑时间差
  2183. if (!systemSetting) {
  2184. return false;
  2185. }
  2186. const type = compilationVersion.includes('免费') ? 'normal' : 'professional';
  2187. const limit = systemSetting[type].project;
  2188. const curTenderCount = await projectModel.count({userID, compilation, projType: 'Tender', '$or':[{deleteInfo: null}, {'deleteInfo.completeDeleted': false}]});
  2189. return tenderCount + curTenderCount > limit;
  2190. }
  2191. async function getWelcomeInfo(compilationId,sessionUser) {
  2192. let setting = await welcomeModel.findOne({compilationId:compilationId});
  2193. let isShow = false;
  2194. let context = "";
  2195. if(setting){
  2196. if(setting.showType == 0) return [false,""];//关闭
  2197. context = setting.context;
  2198. if(setting.showType == 1){//每天一次
  2199. let dataString =moment(Date.now()).tz("Asia/Shanghai").format('YYYY-MM-DD');//今天的日期字符串
  2200. let userInfo =await userModel.findOne({_id: mongoose.Types.ObjectId(sessionUser.id)});
  2201. if (dataString != userInfo.welcomeShowTime){//今天没登录过
  2202. isShow = true;
  2203. await userModel.update({_id: mongoose.Types.ObjectId(sessionUser.id)},{welcomeShowTime:dataString})
  2204. }
  2205. }else if(setting.showType == 2){//每次登录显示
  2206. isShow = sessionUser.newLogin?true:false;
  2207. sessionUser.newLogin = false
  2208. }
  2209. }
  2210. return [isShow,context]
  2211. }