pm_facade.js 88 KB

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