pm_facade.js 69 KB

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