pm_facade.js 83 KB

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