pm_facade.js 93 KB

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