pm_facade.js 65 KB

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