pm_facade.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923
  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 => mapping[item.NextSiblingID] = item);
  669. let lastItem = data.find(item => +item.NextSiblingID === -1);
  670. if (!lastItem) {
  671. return data;
  672. }
  673. const rst = [lastItem];
  674. let preItem = mapping[lastItem.ID];
  675. while (preItem) {
  676. rst.unshift(preItem);
  677. preItem = mapping[preItem.ID];
  678. }
  679. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  680. return rst.length === data.length ? rst : data;
  681. }
  682. //根据单位工程ID获取汇总信息
  683. //@param {Number}tenderID {String}summaryType @return {Object}
  684. async function getSummaryInfoByTender(tenderID, summaryType) {
  685. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  686. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  687. let parent,
  688. parentName,
  689. compilationIllustration;
  690. let summaryList = [];
  691. if(!tender){
  692. return null;
  693. }
  694. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  695. if(!engineering){
  696. return null;
  697. }
  698. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  699. if(!project){
  700. return null;
  701. }
  702. let summaryInfo = await getSummaryInfo([project.ID]);
  703. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  704. parent = engineering;
  705. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted});
  706. tenders = getSortedDataByTree(tenders);
  707. for(let t of tenders){
  708. if(summaryInfo[t.ID]){
  709. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  710. summaryList.push(summaryInfo[t.ID]);
  711. }
  712. }
  713. } else { // 汇总到建设项目级别
  714. parent = project;
  715. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted});
  716. engs = getSortedDataByTree(engs);
  717. for(let e of engs){
  718. if(summaryInfo[e.ID]){
  719. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  720. summaryList.push(summaryInfo[e.ID]);
  721. }
  722. }
  723. }
  724. // 项目名称
  725. parentName = parent && parent.name
  726. ? parent.name
  727. : '';
  728. // 编制说明
  729. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  730. ? parent.property.compilationIllustration
  731. : '';
  732. return {
  733. parent: {
  734. name: parentName,
  735. compilationIllustration: compilationIllustration},
  736. subList: summaryList
  737. };
  738. }
  739. //获取单位工程的各标段费用信息(不进行汇总)
  740. async function getTendersFeeInfo(tenders) {
  741. let IDMapping = {};
  742. //固定清单类别与汇总金额字段映射
  743. let flagFieldMapping = {};
  744. flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  745. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  746. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  747. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  748. flagFieldMapping[billsFlags.OTHER] = 'other';
  749. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  750. flagFieldMapping[billsFlags.TAX] = 'tax';
  751. let tenderIDs = [];
  752. if(tenders.length > 0){
  753. for(let tender of tenders){
  754. tenderIDs.push(tender.ID);
  755. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  756. IDMapping[tender.ID]['buildingArea'] = '';
  757. }
  758. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  759. let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  760. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];
  761. //获取单位工程汇总金额需要用到的所有清单
  762. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  763. '-_id projectID fees flags');
  764. //进行单位工程级别的汇总
  765. for(let bills of allBills){
  766. let billsFlag = bills.flags[0]['flag'];
  767. let costField = flagFieldMapping[billsFlag];
  768. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  769. //暂估合价(工程造价暂估合价)
  770. if (billsFlag === billsFlags.ENGINEERINGCOST){
  771. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  772. }
  773. }
  774. //占造价比例、单方造价
  775. for(let tender of tenders){
  776. let tenderInfo = IDMapping[tender.ID];
  777. tenderInfo.rate = '';
  778. //单方造价
  779. tenderInfo.perCost = '';
  780. }
  781. }
  782. return IDMapping;
  783. }
  784. async function getSummaryInfo(projectIDs, feeFields = null){
  785. function initFees(obj, feeFields) {
  786. for (let data of feeFields) {
  787. obj[data.v] = 0;
  788. }
  789. }
  790. if (!feeFields) {
  791. feeFields = [
  792. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  793. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  794. {k: billsFlags.MEASURE, v: 'measure'},
  795. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  796. {k: billsFlags.OTHER, v: 'other'},
  797. {k: billsFlags.CHARGE, v: 'charge'},
  798. {k: billsFlags.TAX, v: 'tax'}
  799. ];
  800. }
  801. //ID与汇总信息映射
  802. let IDMapping = {};
  803. //固定清单类别与汇总金额字段映射
  804. let flagFieldMapping = {};
  805. for (let data of feeFields) {
  806. flagFieldMapping[data.k] = data.v;
  807. }
  808. /*flagFieldMapping[billsFlags.ENGINEERINGCOST] = 'engineeringCost';
  809. flagFieldMapping[billsFlags.SUB_ENGINERRING] = 'subEngineering';
  810. flagFieldMapping[billsFlags.MEASURE] = 'measure';
  811. flagFieldMapping[billsFlags.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  812. flagFieldMapping[billsFlags.OTHER] = 'other';
  813. flagFieldMapping[billsFlags.CHARGE] = 'charge';
  814. flagFieldMapping[billsFlags.TAX] = 'tax';*/
  815. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  816. //设置建设项目的总建筑面积
  817. for(let project of projects){
  818. let grossArea = '';
  819. if(project.property && project.property.basicInformation){
  820. for(let basicInfo of project.property.basicInformation){
  821. if(basicInfo.key === 'basicInfo'){
  822. for(let k of basicInfo.items){
  823. if(k.key === 'grossArea'){
  824. grossArea = k.value;
  825. }
  826. }
  827. }
  828. }
  829. }
  830. //IDMapping[project.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  831. IDMapping[project.ID] = {estimate: 0, rate: 0, buildingArea: grossArea, perCost: ''};
  832. initFees(IDMapping[project.ID], feeFields);
  833. console.log(IDMapping[project.ID]);
  834. }
  835. //单项工程
  836. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  837. //单位工程
  838. let tenders = [];
  839. let engIDs = [];
  840. for(let eng of engineerings){
  841. engIDs.push(eng.ID);
  842. //IDMapping[eng.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  843. IDMapping[eng.ID] = {estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  844. initFees(IDMapping[eng.ID], feeFields);
  845. }
  846. if(engIDs.length > 0){
  847. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  848. }
  849. let tenderIDs = [];
  850. if(tenders.length > 0){
  851. for(let tender of tenders){
  852. tenderIDs.push(tender.ID);
  853. /*IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, rate: 0, estimate: 0,
  854. buildingArea: '', perCost: '',changeMark:tender.changeMark,property:tender.property};*/
  855. IDMapping[tender.ID] = {rate: 0, estimate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  856. initFees(IDMapping[tender.ID], feeFields);
  857. let buildingArea = getBuildingArea(tender.property.projectFeature);
  858. if(buildingArea){
  859. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  860. }
  861. }
  862. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  863. /*let needFlags = [billsFlags.ENGINEERINGCOST, billsFlags.SUB_ENGINERRING, billsFlags.MEASURE,
  864. billsFlags.SAFETY_CONSTRUCTION, billsFlags.CHARGE, billsFlags.OTHER, billsFlags.TAX];*/
  865. let needFlags = feeFields.map(data => data.k);
  866. //获取单位工程汇总金额需要用到的所有清单
  867. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  868. '-_id projectID fees flags');
  869. //进行单位工程级别的汇总
  870. for(let bills of allBills){
  871. let billsFlag = bills.flags[0]['flag'];
  872. let costField = flagFieldMapping[billsFlag];
  873. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  874. //暂估合价(工程造价暂估合价)
  875. if (billsFlag === billsFlags.ENGINEERINGCOST){
  876. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  877. }
  878. }
  879. let summaryFields = feeFields.map(data => data.v);
  880. summaryFields.push('estimate');
  881. //进行单项工程级别的汇总
  882. for(let tender of tenders){
  883. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  884. }
  885. //进行建设项目级别的汇总
  886. for(let eng of engineerings){
  887. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  888. }
  889. //占造价比例、单方造价
  890. const rateDecimal = -2;
  891. const perCostDecimal = -2;
  892. for(let tender of tenders){
  893. let tenderInfo = IDMapping[tender.ID];
  894. let engInfo = IDMapping[tender.ParentID];
  895. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  896. //单方造价
  897. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0 ?
  898. tenderInfo.buildingArea.toString().trim() : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  899. }
  900. for(let eng of engineerings){
  901. let engInfo = IDMapping[eng.ID];
  902. let projInfo = IDMapping[eng.ParentID];
  903. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  904. }
  905. //建设项目占造价比例及单方造价
  906. for(let project of projects){
  907. let projectInfo = IDMapping[project.ID];
  908. projectInfo.rate = 100;
  909. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0 ?
  910. projectInfo.buildingArea.toString().trim() : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  911. }
  912. }
  913. return IDMapping;
  914. }
  915. //根据项目ID获取所属建设项目
  916. //@param {Number}projectID @return {Object}
  917. async function getConstructionProject(projectID){
  918. function returnProject(project){
  919. if(!project || project.projType === projectType.folder){
  920. return null;
  921. }
  922. if(project.projType === projectType.project){
  923. return project;
  924. }
  925. }
  926. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  927. let returnV = returnProject(project);
  928. if(returnV !== undefined){
  929. return returnV;
  930. }
  931. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  932. returnV = returnProject(parent);
  933. if(returnV !== undefined){
  934. return returnV;
  935. }
  936. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  937. returnV = returnProject(grandParent);
  938. return returnV !== undefined ? returnV : null;
  939. }
  940. //获取单位工程完整目录结构
  941. //@param {Number}projectID @return {Arry}
  942. async function getFullPath(projectID) {
  943. let fullPath = [];
  944. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  945. if(project){
  946. fullPath.push(project.name);
  947. await getParent(project.ParentID);
  948. }
  949. fullPath = fullPath.reverse();
  950. return fullPath;
  951. async function getParent(ParentID) {
  952. if(ParentID != -1){
  953. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  954. if(parent){
  955. fullPath.push(parent.name);
  956. await getParent(parent.ParentID);
  957. }
  958. }
  959. }
  960. }
  961. //获取projectIDs文件下所有子项目(不包括projectIDs本身)
  962. async function getPosterityProjects(projectIDs) {
  963. let rst = [];
  964. async function getProjects(IDs) {
  965. if (IDs.length > 0) {
  966. let newIDs = [];
  967. let projs = await projectModel.find({ParentID: {$in: IDs}, $or: notDeleted}, '-_id');
  968. for (let proj of projs) {
  969. rst.push(proj);
  970. newIDs.push(proj.ID);
  971. }
  972. await getProjects(newIDs);
  973. }
  974. }
  975. await getProjects(projectIDs);
  976. return rst;
  977. }
  978. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  979. //@param {String}userId {Object}tender @return {Object} || {null}
  980. async function getShareInfo(userId, project) {
  981. //与该用户相关的分享
  982. let shareList = [];
  983. while (project) {
  984. for(let shareData of project.shareInfo){
  985. if(shareData.userID === userId){
  986. shareList.push(shareData);
  987. break;
  988. }
  989. }
  990. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  991. }
  992. //获取最新分享
  993. shareList.sort(function (a, b) {
  994. let aV = Date.parse(a.shareDate),
  995. bV = Date.parse(b.shareDate);
  996. if (aV > bV) {
  997. return -1;
  998. } else if (aV < bV) {
  999. return 1;
  1000. }
  1001. return 0;
  1002. });
  1003. return shareList[0] || null;
  1004. }
  1005. //打开的单位工程是否是被分享的.
  1006. async function isShare(userId, project){
  1007. //判断是否是打开分享的项目,属于分享文件的子项也算
  1008. while (project) {
  1009. for(let shareData of project.shareInfo){
  1010. if(shareData.userID === userId){
  1011. return true;
  1012. }
  1013. }
  1014. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1015. }
  1016. return false;
  1017. }
  1018. //用户是否第一次进入费用定额
  1019. async function isFirst(userId, compilationId) {
  1020. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1021. let first = false;
  1022. if (userData) {
  1023. first = !_.find(userData.used_list, function (o) {
  1024. return o.compilationId === compilationId;
  1025. });;
  1026. }
  1027. return first;
  1028. }
  1029. //用户第一次进入费用定额的数据准备
  1030. async function prepareInitialData(userId, compilation, example) {
  1031. let first = await isFirst(userId, compilation);
  1032. if (first) {
  1033. await updateUsedList(userId, compilation);
  1034. let prepareTask = [
  1035. copyCompleRationSection(userId, compilation),
  1036. copyCompleGljSection(userId, compilation)
  1037. ];
  1038. if (example && example.length > 0) {
  1039. prepareTask.push(copyExample(userId, compilation, example));
  1040. }
  1041. await Promise.all(prepareTask);
  1042. }
  1043. }
  1044. async function updateUsedList(userId, compilation) {
  1045. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1046. }
  1047. //拷贝补充定额章节树
  1048. async function copyCompleRationSection(userId, compilationId) {
  1049. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1050. }
  1051. //拷贝补充人材机分类树
  1052. async function copyCompleGljSection(userId, compilationId) {
  1053. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  1054. if (templateData.length > 0) {
  1055. let insertDatas = [],
  1056. uuidMapping = {};
  1057. //将ID替换成UUID
  1058. for (let temData of templateData) {
  1059. uuidMapping[temData.ID] = uuidV1();
  1060. }
  1061. for(let temData of templateData) {
  1062. let insertD = {
  1063. userId: userId,
  1064. compilationId: compilationId,
  1065. Name: temData.Name,
  1066. ID: uuidMapping[temData.ID],
  1067. ParentID: uuidMapping[temData.ParentID] || -1,
  1068. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1069. };
  1070. insertDatas.push(insertD);
  1071. }
  1072. //插入数据
  1073. await compleGljSectionModel.insertMany(insertDatas);
  1074. }
  1075. }
  1076. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1077. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1078. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1079. for(let d of datas){
  1080. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1081. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1082. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1083. newFile = {id:newID,name:tem_file.name};
  1084. type = 0;
  1085. }
  1086. projectIDs.push({ID:d.projectID})
  1087. }
  1088. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1089. }
  1090. //获取费用定额绑定的基本信息库数据
  1091. async function getBasicInfo(compilationID, fileKind = null) {
  1092. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1093. if (!compilation) {
  1094. return null;
  1095. }
  1096. let billValuation = compilation.bill_valuation.find(function (data) {
  1097. return data.enable;
  1098. });
  1099. if (!billValuation) {
  1100. return null;
  1101. }
  1102. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1103. let engineering = engineerings.find(function (data) {
  1104. return data.info_lib && data.info_lib.length > 0;
  1105. });
  1106. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1107. return null;
  1108. }
  1109. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1110. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1111. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1112. let strMap = {
  1113. 1: 'tender', //投标
  1114. 2: 'bid', //招标
  1115. 3: 'control' //控制价
  1116. };
  1117. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1118. needfulData.forEach(nData => {
  1119. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1120. nData.items = needfulSub;
  1121. });
  1122. infoLib.info = needfulData;
  1123. }
  1124. return infoLib;
  1125. }
  1126. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1127. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1128. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1129. return null;
  1130. }
  1131. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1132. return featureLib;
  1133. }
  1134. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1135. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1136. async function getProjectByGranularity(tenderID, granularity, userID, versionName) {
  1137. const GRANULARITY = {
  1138. PROJECT: 1,
  1139. ENGINEERING: 2,
  1140. TENDER: 3
  1141. };
  1142. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}); //加上session的userID,防止tenderID被篡改过
  1143. if (!theTender) {
  1144. return null;
  1145. }
  1146. let theEngineering = await projectModel.findOne({ID: theTender.ParentID});
  1147. if (!theEngineering) {
  1148. return null;
  1149. }
  1150. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID});
  1151. if (!constructionProject) {
  1152. return null;
  1153. }
  1154. let engineerings;
  1155. if (granularity === GRANULARITY.PROJECT) {
  1156. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted});
  1157. for (let eng of engineerings) {
  1158. eng._doc.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted});
  1159. }
  1160. } else {
  1161. engineerings = [theEngineering];
  1162. if (granularity === GRANULARITY.ENGINEERING) {
  1163. theEngineering._doc.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted});
  1164. } else {
  1165. theEngineering._doc.children = [theTender];
  1166. }
  1167. }
  1168. constructionProject._doc.children = engineerings;
  1169. //获取汇总信息
  1170. let feeFields = [
  1171. {k: billsFlags.ENGINEERINGCOST, v: 'engineeringCost'},
  1172. {k: billsFlags.SUB_ENGINERRING, v: 'subEngineering'},
  1173. {k: billsFlags.MEASURE, v: 'measure'},
  1174. {k: billsFlags.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1175. {k: billsFlags.OTHER, v: 'other'},
  1176. {k: billsFlags.CHARGE, v: 'charge'},
  1177. {k: billsFlags.PROVISIONAL, v: 'provisional'},
  1178. {k: billsFlags.MATERIAL_PROVISIONAL, v: 'materialProvisional'},
  1179. {k: billsFlags.ENGINEERING_ESITIMATE, v: 'engineeringEstimate'},
  1180. {k: billsFlags.DAYWORK, v: 'daywork'},
  1181. {k: billsFlags.TURN_KEY_CONTRACT, v: 'turnKeyContract'},
  1182. {k: billsFlags.CLAIM_VISA, v: 'claimVisa'},
  1183. {k: billsFlags.TAX, v: 'tax'}
  1184. ];
  1185. constructionProject._doc.summaryInfo = await getSummaryInfo([constructionProject.ID], feeFields);
  1186. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1187. let product = await productModel.findOne({});
  1188. let company = product.company || '珠海纵横创新软件有限公司',
  1189. version = product.version || '';
  1190. constructionProject._doc.softInfo = `${company};${versionName};${version};${userID}`;
  1191. return constructionProject;
  1192. }
  1193. //获取项目数据占位ID
  1194. async function getProjectPlaceholder(data) {
  1195. let rst = {};
  1196. //项目本身数据
  1197. if (data.projectCount) {
  1198. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1199. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1200. }
  1201. //项目人材机数据
  1202. if (data.projectGLJCount) {
  1203. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1204. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1205. }
  1206. //组成物数据
  1207. if (data.ratioCount) {
  1208. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1209. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1210. }
  1211. //单价文件数据
  1212. if (data.unitPriceFileCount) {
  1213. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1214. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1215. }
  1216. //单价数据
  1217. if (data.unitPriceCount) {
  1218. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1219. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1220. }
  1221. return rst;
  1222. }
  1223. /*
  1224. * 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1225. * */
  1226. async function importProject(importObj, userID, compilationID) {
  1227. let toInsertProjects = [importObj]; //待新增项目数据
  1228. await setupProject(importObj);
  1229. //设置项目ID及相关数据
  1230. for (let curEng of importObj.engs) {
  1231. await setupProject(curEng);
  1232. toInsertProjects.push(curEng);
  1233. for (let curTender of curEng.tenders) {
  1234. await setupProject(curTender.tender);
  1235. //插入单位工程的详细数据
  1236. await importTenderDetail(curTender);
  1237. toInsertProjects.push(curTender.tender);
  1238. }
  1239. delete curEng.tenders;
  1240. }
  1241. delete importObj.engs;
  1242. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1243. let bulks = [];
  1244. //如果有前节点,更新前节点
  1245. if (importObj.preID !== -1) {
  1246. bulks.push({
  1247. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1248. });
  1249. }
  1250. for (let insertP of toInsertProjects) {
  1251. bulks.push({
  1252. insertOne: {document: insertP}
  1253. });
  1254. }
  1255. if (bulks.length > 0) {
  1256. await projectModel.bulkWrite(bulks);
  1257. }
  1258. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1259. //设置汇总字段
  1260. for(let proj of toInsertProjects){
  1261. let summaryProj = summaryInfo[proj.ID];
  1262. if(summaryProj){
  1263. proj.engineeringCost = summaryProj.engineeringCost;
  1264. proj.subEngineering = summaryProj.subEngineering;
  1265. proj.measure = summaryProj.measure;
  1266. proj.safetyConstruction = summaryProj.safetyConstruction;
  1267. proj.other = summaryProj.other;
  1268. proj.charge = summaryProj.charge;
  1269. proj.tax = summaryProj.tax;
  1270. proj.rate = summaryProj.rate;
  1271. proj.buildingArea = summaryProj.buildingArea;
  1272. proj.perCost = summaryProj.perCost;
  1273. }
  1274. }
  1275. return toInsertProjects;
  1276. //给项目数据设置一些需要的数据
  1277. async function setupProject(data) {
  1278. data.userID = userID;
  1279. data.compilation = compilationID;
  1280. data.fileVer = G_FILE_VER;
  1281. data.createDateTime = new Date();
  1282. if (data.projType === 'Project') {
  1283. await setupConstruct(data);
  1284. } else if (data.projType === 'Tender') {
  1285. await setupTender(data);
  1286. }
  1287. }
  1288. //给建设项目设置一些数据
  1289. async function setupConstruct(data) {
  1290. //更新基本信息, 按照key匹配
  1291. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1292. if (infoLib) {
  1293. //标准基本信息库的数据打平
  1294. let flatDatas = [];
  1295. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1296. data.basicInformation.forEach(importI => {
  1297. flatDatas.forEach(item => {
  1298. if (item.key === 'engineeringName') {
  1299. item.value = data.name;
  1300. } else if (item.key === 'fileKind') {
  1301. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1302. } else if (item.key === 'taxModel') {
  1303. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1304. }
  1305. if (item.key === importI.key) {
  1306. item.value = importI.value;
  1307. }
  1308. });
  1309. });
  1310. }
  1311. data.property.basicInformation = infoLib ? infoLib.info : [];
  1312. }
  1313. //给单位工程设置一些数据
  1314. async function setupTender(data) {
  1315. //小数位数 需要修改,所以深拷贝
  1316. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  1317. // 定额工程量、人材机消耗量精度设为最大6
  1318. data.property.decimal.ration.quantity = 6;
  1319. data.property.decimal.glj.quantity = 6;
  1320. //清单工程量精度 需要修改,所以深拷贝
  1321. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1322. // 清单工程量精度设置最大4
  1323. data.property.billsQuantityDecimal.forEach(data => data.decimal = 4);
  1324. //呈现选项
  1325. data.property.displaySetting = displaySetting;
  1326. data.property.billsCalcMode = 0;
  1327. data.property.zanguCalcMode = 0;
  1328. //计算选项
  1329. data.property.calcOptions = calcOptions;
  1330. //安装增加费
  1331. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1332. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1333. }
  1334. //锁定清单
  1335. data.property.lockBills = true;
  1336. //工料机单价调整系数
  1337. data.property.tenderSetting = tenderSetting;
  1338. //工程特征相关更新
  1339. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1340. if (featureLib) {
  1341. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1342. data.projectFeature.forEach(importF => {
  1343. let matchData = featureLib.feature.find(f => f.dispName === importF.name);
  1344. if (matchData) {
  1345. matchData.value = importF.value;
  1346. }
  1347. });
  1348. //设置工程专业的值为费用标准的值..
  1349. featureLib.feature.forEach(f => {
  1350. if (f.key === 'engineering') {
  1351. f.value = data.property.feeStandardName;
  1352. }
  1353. });
  1354. }
  1355. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1356. // 指标信息相关设置
  1357. await project_facade.setSEILibData(data.property);
  1358. }
  1359. }
  1360. //插入单位工程内部详细数据
  1361. async function importTenderDetail(tenderData) {
  1362. //单价文件
  1363. let upFile = {
  1364. id: tenderData.tender.property.unitPriceFile.id,
  1365. name: tenderData.tender.name,
  1366. project_id: tenderData.tender.ID,
  1367. user_id: tenderData.tender.userID,
  1368. root_project_id: tenderData.tender.property.rootProjectID
  1369. };
  1370. await unitPriceFileModel.create(upFile);
  1371. //费率文件
  1372. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1373. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1374. //人工系数文件
  1375. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1376. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1377. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1378. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1379. //列设置
  1380. let engineeringModel = new EngineeringLibModel();
  1381. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1382. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1383. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1384. //清单
  1385. if (tenderData.bills.length) {
  1386. await billsModel.insertMany(tenderData.bills);
  1387. }
  1388. //投标文件中,才会有下面这些数据
  1389. if (enterDetail(tenderData)) {
  1390. //匹配标准数据,更新一些标准数据
  1391. await setupStdData(tenderData);
  1392. let task = [];
  1393. //定额
  1394. if (tenderData.ration.length) {
  1395. task.push(rationModel.insertMany(tenderData.ration))
  1396. }
  1397. //定额人材机
  1398. if (tenderData.rationGLJ.length) {
  1399. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1400. }
  1401. //定额调整系数
  1402. if (tenderData.rationCoe.length) {
  1403. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1404. }
  1405. //项目人材机
  1406. if (tenderData.projectGLJ.length) {
  1407. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1408. }
  1409. //组成物
  1410. if (tenderData.mixRatio.length) {
  1411. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1412. }
  1413. //单价文件
  1414. if (tenderData.unitPrice.length) {
  1415. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1416. }
  1417. await Promise.all(task);
  1418. }
  1419. //继续处理定额等数据
  1420. function enterDetail(tenderData) {
  1421. return tenderData.ration.length ||
  1422. tenderData.rationGLJ.length ||
  1423. tenderData.projectGLJ.length ||
  1424. tenderData.mixRatio.length ||
  1425. tenderData.unitPrice.length;
  1426. }
  1427. }
  1428. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1429. async function setupStdData(tenderData) {
  1430. //获取标准定额数据 (定额子目的编码查找)
  1431. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1432. if (!matchRationCodes.length) {
  1433. return;
  1434. }
  1435. //限制在当前费用定额可用的定额库里查找
  1436. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1437. '-_id -rationAssList -rationCoeList -rationInstList');
  1438. //标准定额code - 映射
  1439. let stdRationCodeMap = {};
  1440. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1441. //获取标准人材机数据 (人材机汇总的编码查找)
  1442. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1443. if (!matchGLJCodes.length) {
  1444. return;
  1445. }
  1446. //限制在当前费用定额可用的人材机库里查找
  1447. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1448. '-_id -component -priceProperty');
  1449. //标准人材机code - 映射
  1450. let stdGLJCodeMap = {};
  1451. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1452. //更新定额数据
  1453. tenderData.ration.forEach(r => {
  1454. let stdRation = stdRationCodeMap[r.code];
  1455. if (stdRation) {
  1456. r.caption = stdRation.caption;
  1457. r.from = 'std';
  1458. r.libID = stdRation.rationRepId;
  1459. r.stdID = stdRation.ID;
  1460. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1461. r.content = stdRation.jobContent;
  1462. if (stdRation.feeType) {
  1463. r.programID = stdRation.feeType;
  1464. }
  1465. } else {
  1466. r.from = 'cpt';
  1467. r.prefix = '补';
  1468. }
  1469. });
  1470. //更新定额人材机数据
  1471. tenderData.rationGLJ.forEach(rGLJ => {
  1472. rGLJ.from = 'cpt';
  1473. //匹配定额
  1474. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1475. if (stdRation) {
  1476. //根据导入数据的定额人材机编码匹配人材机
  1477. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1478. if (stdGLJ) {
  1479. rGLJ.from = 'std';
  1480. rGLJ.GLJID = stdGLJ.ID;
  1481. rGLJ.type = stdGLJ.gljType;
  1482. rGLJ.shortName = stdGLJ.shortName;
  1483. rGLJ.repositoryId = stdGLJ.repositoryId;
  1484. rGLJ.model = stdGLJ.model;
  1485. rGLJ.adjCoe = stdGLJ.adjCoe;
  1486. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1487. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1488. if (stdRationGLJ) {
  1489. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1490. }
  1491. }
  1492. }
  1493. });
  1494. //更新人材机汇总数据
  1495. tenderData.projectGLJ.forEach(pGLJ => {
  1496. if (!pGLJ.specs) {
  1497. pGLJ.specs = null;
  1498. }
  1499. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1500. if (stdGLJ) {
  1501. pGLJ.glj_id = stdGLJ.ID;
  1502. pGLJ.model = stdGLJ.model;
  1503. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1504. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1505. let ratios = tenderData.mixRatio.filter(ratio =>
  1506. ratio.connect_key === keyStr);
  1507. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1508. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1509. }
  1510. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1511. }
  1512. });
  1513. //更新单价文件数据
  1514. tenderData.unitPrice.forEach(up => {
  1515. let stdGLJ = stdGLJCodeMap[up.original_code];
  1516. if (stdGLJ) {
  1517. up.glj_id = stdGLJ.ID;
  1518. up.type = stdGLJ.gljType;
  1519. up.short_name = stdGLJ.shortName;
  1520. }
  1521. });
  1522. //更新组成物数据
  1523. tenderData.mixRatio.forEach(ratio => {
  1524. let stdGLJ = stdGLJCodeMap[ratio.code];
  1525. if (stdGLJ) {
  1526. ratio.glj_id = stdGLJ.ID;
  1527. ratio.type = stdGLJ.gljType;
  1528. }
  1529. });
  1530. }
  1531. async function exportProject(userID,data){//导出建设项目
  1532. if(data.type == 'main'){
  1533. return await exportMainData(userID,data.projectID);
  1534. }else {
  1535. return await exportTenderData(data);
  1536. }
  1537. }
  1538. async function exportMainData(userID,projectID) {
  1539. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  1540. let tenderIDs = [];
  1541. let project = await projectModel.findOne({ID:projectID});
  1542. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  1543. result['compilationID'] = project.compilation;
  1544. result.projects.push(project);
  1545. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  1546. for(let s of subProjects){
  1547. if(!s.deleteInfo || !s.deleteInfo.deleted){
  1548. result.projects.push(s);
  1549. if(s.projType =="Tender") tenderIDs.push(s.ID);
  1550. }
  1551. }
  1552. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  1553. result.files = files;
  1554. result = cipher.aesEncrypt(JSON.stringify(result));
  1555. result +="|----|" +JSON.stringify(tenderIDs);
  1556. return result;
  1557. }
  1558. async function exportUnitFiles(rootProjectID){
  1559. let unitFiles = [];
  1560. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  1561. for(let f of files){
  1562. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1563. let tem = {unitFile:f};
  1564. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  1565. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  1566. unitFiles.push(tem);
  1567. }
  1568. return unitFiles;
  1569. }
  1570. async function exportFeeRateFiles(rootProjectID) {
  1571. let feeRateFiles = [];
  1572. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  1573. for(let f of files){
  1574. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  1575. let tem = {feeRateFile:f};
  1576. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  1577. feeRateFiles.push(tem);
  1578. }
  1579. return feeRateFiles;
  1580. }
  1581. async function exportTenderData(data){
  1582. let result = {};
  1583. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  1584. if(projectSetting) result['projSetting'] = projectSetting;
  1585. result.bills = await billsModel.find({"projectID": data.projectID});
  1586. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  1587. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  1588. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  1589. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  1590. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  1591. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  1592. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  1593. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  1594. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  1595. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  1596. return cipher.aesEncrypt(JSON.stringify(result));
  1597. }
  1598. async function importProjects(data,req,fields) {
  1599. let result = {error:0};
  1600. let stringArr = data.split("|----|");
  1601. let datas = [];
  1602. for(let s of stringArr){
  1603. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  1604. }
  1605. let mainData = datas.length > 0 ?datas[0]:null;
  1606. if(mainData){
  1607. if(mainData.compilationID != req.session.sessionCompilation._id){
  1608. result.error = 1;
  1609. result.msg = "编办不同,无法导入,请重新选择!";
  1610. }else {
  1611. let [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,JSON.parse(fields.updateData[0]),req.session.sessionUser.id);
  1612. if(datas.length > 1 ){
  1613. for(let i = 1;i<datas.length;i++){
  1614. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  1615. }
  1616. }
  1617. }
  1618. }
  1619. return result;
  1620. }
  1621. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  1622. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[];
  1623. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  1624. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  1625. let newProjectID = projectIDMap[data.projSetting.projectID];
  1626. //生成新的清单;
  1627. if(data.bills && data.bills.length > 0){
  1628. for(let b of data.bills){
  1629. billsIDMap[b.ID] = uuidV1();
  1630. }
  1631. for(let b of data.bills){
  1632. delete b._id;
  1633. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  1634. bills.push(b);
  1635. }
  1636. }
  1637. //生成项目工料机数据
  1638. if(data.projectGLJs && data.projectGLJs.length > 0){
  1639. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  1640. for(let i = 0; i < data.projectGLJs.length; i++){
  1641. let d = data.projectGLJs[i];
  1642. delete d._id;
  1643. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  1644. projectGLJIDMap[d.id] = newID;
  1645. d.project_id = newProjectID;
  1646. d.id = newID;
  1647. projectGLJs.push(d);
  1648. }
  1649. }
  1650. //生成新的定额
  1651. if(data.rations && data.rations.length > 0){
  1652. for(let r of data.rations){
  1653. rationIDMap[r.ID] = uuidV1();
  1654. }
  1655. for(let r of data.rations){
  1656. delete r._id;
  1657. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1658. rations.push(r);
  1659. }
  1660. }
  1661. //生成定额下挂的定额工料机等等数据
  1662. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1663. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1664. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1665. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1666. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  1667. //生成projectSetting 文件
  1668. if(data.projSetting){
  1669. data.projSetting.projectID =newProjectID;
  1670. newProjectSetting = data.projSetting;
  1671. delete newProjectSetting._id;
  1672. }
  1673. //生成计算程序文件,系数文件
  1674. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  1675. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  1676. data.calcProgramsFile.projectID = newProjectID;
  1677. newCalcProgramsFile = data.calcProgramsFile;
  1678. delete newCalcProgramsFile._id;
  1679. }
  1680. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  1681. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  1682. data.labourCoes.projectID = newProjectID;
  1683. newLabourCoe = data.labourCoes;
  1684. delete newLabourCoe._id;
  1685. }
  1686. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  1687. if(bills.length > 0) await insertMany(bills,billsModel);
  1688. if(rations.length > 0) await insertMany(rations,rationModel);
  1689. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  1690. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  1691. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  1692. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  1693. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  1694. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  1695. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  1696. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  1697. }
  1698. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  1699. let arrs = [];
  1700. for(let d of datas){
  1701. delete d._id;
  1702. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  1703. arrs.push(d);
  1704. }
  1705. return arrs;
  1706. }
  1707. async function handleMainProjectDatas(mainData,updateData,userID) {
  1708. let mainProjectID = -1;
  1709. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  1710. let tasks = [];
  1711. //生成新的projectID
  1712. for(let p of mainData.projects){
  1713. let newProjectID = await getCounterID("projects");
  1714. projectIDMap[p.ID] = newProjectID;
  1715. if(p.projType == "Project") mainProjectID = newProjectID;
  1716. if(p.projType == "Tender"){
  1717. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  1718. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  1719. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  1720. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  1721. }
  1722. }
  1723. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  1724. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  1725. for(let p of mainData.projects){
  1726. delete p._id;
  1727. delete p.__v;
  1728. p.ID = projectIDMap[p.ID];
  1729. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  1730. p.ParentID = updateData.self.ParentID;
  1731. p.NextSiblingID = updateData.self.NextSiblingID;
  1732. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  1733. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  1734. }
  1735. //查看是否重名;
  1736. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  1737. if(temp) p.name = p.name + '(' + moment(Date.now()).format('MM-DD HH:mm:ss') + '导入)';
  1738. }else {
  1739. p.ParentID = projectIDMap[p.ParentID];
  1740. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  1741. }
  1742. p.userID =userID;
  1743. p.shareInfo=[];
  1744. if(p.projType == "Tender"){
  1745. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  1746. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  1747. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  1748. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  1749. p.property.rootProjectID = mainProjectID
  1750. }
  1751. tasks.push({insertOne: {document: p}})
  1752. }
  1753. //项目树节构数据生成:
  1754. await projectModel.bulkWrite(tasks);
  1755. //生成所有的费率文件
  1756. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  1757. //生成所有的单价文件
  1758. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  1759. return [projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  1760. }
  1761. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  1762. if(!mainData.files.unitFiles) return;
  1763. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  1764. for(let f of mainData.files.unitFiles){
  1765. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  1766. //生成单价文件
  1767. delete file._id;
  1768. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  1769. file.project_id = projectIDMap[file.project_id];
  1770. file.root_project_id = projectIDMap[file.root_project_id];
  1771. file.user_id = userID;
  1772. unitFiles.push(file);
  1773. //生成子数据
  1774. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  1775. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  1776. }
  1777. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  1778. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  1779. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  1780. async function setSubList(oList,nList,fileID,model,UUID=false) {
  1781. for(let o of oList){
  1782. delete o._id;
  1783. o.unit_price_file_id = fileID;
  1784. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  1785. nList.push(o)
  1786. }
  1787. }
  1788. }
  1789. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  1790. let feeRateFiles = [], feeRates = [];
  1791. if(!mainData.files.feeRateFiles) return;
  1792. for(let f of mainData.files.feeRateFiles){
  1793. //生成费率记录
  1794. let rate = f.feeRate;
  1795. delete rate._id;
  1796. rate.ID = uuidV1();
  1797. feeRates.push(rate);
  1798. //生成费率文件记录
  1799. let file = f.feeRateFile;
  1800. delete file._id;
  1801. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  1802. file.userID = userID;
  1803. file.rootProjectID = projectIDMap[file.rootProjectID];
  1804. file.feeRateID = rate.ID;
  1805. feeRateFiles.push(file);
  1806. }
  1807. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  1808. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  1809. }