pm_facade.js 86 KB

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