pm_facade.js 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  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. prepareShareList,
  13. getShareList,
  14. addShareList,
  15. updateShareList,
  16. deleteShareList,
  17. getShareInfoMap,
  18. getRecentShareList,
  19. getProjectShareList,
  20. moveProject:moveProject,
  21. accessToCopyProject,
  22. copyProject:copyProject,
  23. copyExample: copyExample,
  24. setupSummaryFields: setupSummaryFields,
  25. getSummaryInfo: getSummaryInfo,
  26. getSummaryInfoByTender: getSummaryInfoByTender,
  27. getIndexReportData: getIndexReportData,
  28. getTendersFeeInfo: getTendersFeeInfo,
  29. getConstructionProject: getConstructionProject,
  30. getFullPath: getFullPath,
  31. projectType: projectType,
  32. getPosterityProjects: getPosterityProjects,
  33. isShare: isShare,
  34. isFirst: isFirst,
  35. getShareInfo: getShareInfo,
  36. prepareInitialData: prepareInitialData,
  37. changeFile:changeFile,
  38. getBasicInfo: getBasicInfo,
  39. getProjectFeature: getProjectFeature,
  40. getProjectByGranularity: getProjectByGranularity,
  41. importProject: importProject,
  42. getProjectPlaceholder: getProjectPlaceholder,
  43. exportProject:exportProject,
  44. importProjects:importProjects,//建筑这里重名了,这比养护加多了个s
  45. initOverHeightItems: initOverHeightItems,
  46. uploadToken:uploadToken,
  47. downLoadProjectFile:downLoadProjectFile,
  48. importChongqingProject:importChongqingProject,
  49. importProcessChecking:importProcessChecking,
  50. importInterface,
  51. isTenderOverrun,
  52. getWelcomeInfo:getWelcomeInfo
  53. };
  54. let mongoose = require('mongoose');
  55. let _ = require("lodash");
  56. let feeRate_facade = require('../../fee_rates/facade/fee_rates_facade');
  57. let glj_facade = require('../../glj/facade/glj_facade');
  58. let project_facade = require('../../main/facade/project_facade');
  59. let logger = require("../../../logs/log_helper").logger;
  60. const uuidV1 = require('uuid/v1');
  61. let projectModel = mongoose.model('projects');
  62. let projectSettingModel = mongoose.model('proj_setting');
  63. let billsModel = mongoose.model('bills');
  64. let rationModel = mongoose.model('ration');
  65. let gljListModel = mongoose.model("glj_list");
  66. let calcProgramsModel = mongoose.model('calc_programs');
  67. let labourCoesModel = mongoose.model('labour_coes');
  68. let feeRateModel = mongoose.model('fee_rates');
  69. let feeRateFileModel = mongoose.model('fee_rate_file');
  70. let unitPriceFileModel = mongoose.model("unit_price_file");
  71. let mixRatioModel = mongoose.model("mix_ratio");
  72. let unitPriceModel = mongoose.model("unit_price");
  73. let installationFeeModel = mongoose.model("installation_fee");
  74. let rationGLJModel = mongoose.model('ration_glj');
  75. let rationCoeModel = mongoose.model('ration_coe');
  76. let rationInstallationModel = mongoose.model('ration_installation');
  77. let quantityDetailModel = mongoose.model('quantity_detail');
  78. let rationTemplateModel = mongoose.model('ration_template');
  79. let userModel = mongoose.model('user');
  80. let compleGljSectionModel = mongoose.model('complementary_glj_section');
  81. let compleGljSectionTModel = mongoose.model('complementary_glj_section_templates');
  82. let compilationModel = mongoose.model('compilation');
  83. let engineeringModel = mongoose.model('engineering_lib');
  84. let basicInfoModel = mongoose.model('std_basic_info_lib');
  85. let projectFeatureModel = mongoose.model('std_project_feature_lib');
  86. let productModel = mongoose.model('product');
  87. let stdRationItemModel = mongoose.model('std_ration_lib_ration_items');
  88. let stdGljItemModel = mongoose.model('std_glj_lib_gljList');
  89. import BillsTemplateModel from "../models/templates/bills_template_model";
  90. let evaluateListModel = mongoose.model("evaluate_list");
  91. let bidListModel = mongoose.model("bid_evaluation_list");
  92. let contractorListModel = mongoose.model("contractor_list");
  93. let featureLibModel = mongoose.model("std_project_feature_lib");
  94. let importLogsModel = mongoose.model("import_logs");
  95. const overHeightLibModel = mongoose.model('std_over_height_lib');
  96. const shareListModel = mongoose.model('share_list');
  97. let welcomeModel = mongoose.model("welcome_setting");
  98. let scMathUtil = require('../../../public/scMathUtil').getUtil();
  99. let counter = require('../../../public/counter/counter');
  100. import SectionTreeDao from '../../complementary_ration_lib/models/sectionTreeModel';
  101. let sectionTreeDao = new SectionTreeDao();
  102. import CounterModel from "../../glj/models/counter_model";
  103. import moment from 'moment-timezone';
  104. const { fixedFlag } = require('../../../public/common_constants');
  105. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  106. import {
  107. defaultDecimal,
  108. billsQuantityDecimal,
  109. displaySetting,
  110. calcOptions,
  111. tenderSetting,
  112. G_FILE_VER
  113. } from '../models/project_property_template';
  114. let labourCoeFacade = require('../../main/facade/labour_coe_facade');
  115. let calcProgramFacade = require('../../main/facade/calc_program_facade');
  116. let mainColLibModel = mongoose.model('std_main_col_lib');
  117. import EngineeringLibModel from "../../users/models/engineering_lib_model";
  118. let installationFacade = require('../../main/facade/installation_facade');
  119. let cipher = require('../../../public/cipher');
  120. let qiniu = require("qiniu");
  121. let fs = require("fs");
  122. let path = require("path");
  123. let request = require("request");
  124. const systemSettingMiddleware = require('../../main/middleware/system_setting');
  125. let qiniu_config = {
  126. "AccessKey": "_gR1ed4vi1vT2G2YITGSf4_H0fJu_nRS9Tzk3T4z",
  127. "SecretKey": "ty4zd0FHqgEDaiVzSLC8DfHlai99aS7bspLkw6s6",
  128. "Bucket": "yun-update",
  129. "Domain": "http://serverupdate.smartcost.com.cn"
  130. };
  131. let mac = new qiniu.auth.digest.Mac(qiniu_config.AccessKey, qiniu_config.SecretKey);
  132. // 重构了分享的数据结构,原本存在projects表的shareInfo数组中
  133. // 为了更好地适应新功能及以后拓展功能,现将分享信息存放在单独的share_list表中
  134. // 为了适应旧数据,需要在share_list没有数据的时候,将原本的分享信息复制到share_list中,同时生成联系人
  135. // TODO: 上线后这个方法执行过后,应该删除此方法
  136. async function prepareShareList() {
  137. const shareListCount = await shareListModel.count({});
  138. console.log(shareListCount);
  139. if (shareListCount) {
  140. return;
  141. }
  142. logger.info('================================enterPrepareShareList================================================');
  143. // 将项目的shareInfo数据复制到share_list表中
  144. const projects = await projectModel.find({'shareInfo.0': {$exists: true}}, '-_id ID userID shareInfo').lean();
  145. if (!projects.length) {
  146. return;
  147. }
  148. const shareList = [];
  149. const userMap = {}; // 给生成联系人做准备
  150. projects.forEach(project => {
  151. const ownerContacts = userMap[project.userID] || (userMap[project.userID] = []);
  152. project.shareInfo.forEach(shareItem => {
  153. if (!shareItem.shareDate) {
  154. return;
  155. }
  156. const receiverContacts = userMap[shareItem.userID] || (userMap[shareItem.userID] = []);
  157. receiverContacts.push(project.userID);
  158. const newItem = {
  159. ID: uuidV1(),
  160. projectID: project.ID,
  161. owner: project.userID,
  162. receiver: shareItem.userID,
  163. allowCopy: shareItem.allowCopy,
  164. allowCooperate: shareItem.allowCooperate,
  165. shareDate: shareItem.shareDate,
  166. updateDate: shareItem.shareDate
  167. };
  168. ownerContacts.push(shareItem.userID);
  169. shareList.push(newItem);
  170. });
  171. });
  172. // 插入分享信息
  173. const shareListPromise = shareListModel.insertMany(shareList);
  174. const tasks = [shareListPromise];
  175. // 更新用户信息
  176. const userTasks = [];
  177. Object.entries(userMap).forEach(([userID, contacts]) => {
  178. contacts = [...new Set(contacts)]
  179. .map(user => ({ userID: user }));
  180. const task = {
  181. updateOne: {
  182. filter: {
  183. _id: mongoose.Types.ObjectId(userID)
  184. },
  185. update: {
  186. contacts
  187. }
  188. }
  189. };
  190. userTasks.push(task);
  191. });
  192. if (userTasks.length) {
  193. tasks.push(userModel.bulkWrite(userTasks));
  194. }
  195. await Promise.all(tasks);
  196. }
  197. // 获取分享列表
  198. async function getShareList(query) {
  199. return await shareListModel.find(query, '-_id').lean();
  200. }
  201. async function addShareList(docs) {
  202. await shareListModel.insertMany(docs);
  203. }
  204. async function deleteShareList(query) {
  205. await shareListModel.deleteMany(query);
  206. }
  207. async function updateShareList(updateData) {
  208. const bulks = updateData.map(item => (
  209. {
  210. updateOne: {
  211. filter: item.query,
  212. update: item.update
  213. }
  214. }
  215. ));
  216. if (bulks.length) {
  217. await shareListModel.bulkWrite(bulks);
  218. }
  219. }
  220. // 根据项目ID获取项目shareInfo字段的数据映射(前端旧逻辑依赖项目本身的shareInfo字段)
  221. async function getShareInfoMap(projectIDs, shareList = null) {
  222. if (!shareList) {
  223. shareList = await getShareList({projectID: {$in: projectIDs}});
  224. }
  225. // 将相同项目的分享信息进行映射
  226. const map = {};
  227. shareList.forEach(item => {
  228. const shareInfo = map[item.projectID] || (map[item.projectID] = []);
  229. shareInfo.push({
  230. userID: item.receiver,
  231. shareDate: item.shareDate,
  232. updateDate: item.updateDate,
  233. allowCopy: item.allowCopy,
  234. allowCooperate: item.allowCooperate
  235. });
  236. });
  237. return map;
  238. }
  239. // 获取最近分享(只算分享出去的记录)
  240. async function getRecentShareList(userID, count) {
  241. const shareList = await getShareList({owner: userID});
  242. shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate));
  243. const set = new Set();
  244. for(const item of shareList) {
  245. if (set.size === count) {
  246. break;
  247. }
  248. set.add(item.receiver);
  249. }
  250. const sortedIDList = [...set];
  251. const userIDList = sortedIDList.map(userID => mongoose.Types.ObjectId(userID));
  252. const users = await userModel.find({_id: {$in: userIDList}}, 'real_name mobile company').lean();
  253. users.sort((a, b) => sortedIDList.indexOf(a._id.toString()) - sortedIDList.indexOf(b._id.toString()));
  254. return users;
  255. }
  256. // 获取某项目的分享记录
  257. async function getProjectShareList(projectID) {
  258. const sharedList = await shareListModel.find({ projectID }).lean();
  259. const userIDs = [];
  260. const userMap = {};
  261. sharedList.forEach(item => {
  262. userIDs.push(item.receiver);
  263. userMap[item.receiver] = item;
  264. });
  265. const userObjectIDs = userIDs.map(userID => mongoose.Types.ObjectId(userID));
  266. const users = await userModel.find({_id: {$in: userObjectIDs}}, 'real_name mobile company').lean();
  267. users.forEach(user => {
  268. const matched = userMap[user._id];
  269. if (matched) {
  270. user.allowCopy = matched.allowCopy;
  271. user.allowCooperate = matched.allowCooperate;
  272. }
  273. });
  274. return users;
  275. }
  276. //拷贝例题项目
  277. //@param {String}userID {Array}projIDs拷贝的例题项目ID(建设项目、文件夹)@return {Boolean}
  278. async function copyExample(userID, compilation, projIDs){
  279. let allProjs = [],
  280. IDMapping = {},
  281. projMapping = {};
  282. //例题项目不可为单项工程、单位工程、只能是建设项目、文件夹,否则不自动新建例题项目(这里不报错,让用户没有感觉)
  283. let parentExample = await projectModel.find({ID: {$in: projIDs}, $or: notDeleted}).lean();
  284. if (parentExample.length === 0) {
  285. return false;
  286. }
  287. allProjs = allProjs.concat(parentExample);
  288. for (let i = 0; i < parentExample.length; i++) {
  289. let data = parentExample[i];
  290. if (data.projType === projectType.tender || data.projType === projectType.engineering) {
  291. return false;
  292. }
  293. //设置成顶节点,最后一个节点设置成末节
  294. data.ParentID = -1;
  295. if (i === parentExample.length - 1) {
  296. data.NextSiblingID = -1;
  297. }
  298. }
  299. //获取所有的子项目
  300. let posterityProjs = await getPosterityProjects(projIDs);
  301. allProjs = allProjs.concat(posterityProjs);
  302. let projCounter = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, allProjs.length);
  303. //旧ID与新ID映射
  304. for (let i = 0; i < allProjs.length; i++) {
  305. let data = allProjs[i];
  306. let newID = projCounter.sequence_value - (allProjs.length - 1) + i;
  307. IDMapping[data.ID] = newID;
  308. projMapping[newID] = data;
  309. }
  310. //return;
  311. //设置新的树结构数据
  312. let newDate = new Date(),
  313. parentBulks = [];
  314. const projectMaps = [];
  315. for (let data of allProjs) {
  316. let orgID = data.ID;
  317. data.ID = IDMapping[data.ID];
  318. data.ParentID = IDMapping[data.ParentID] ? IDMapping[data.ParentID] : -1;
  319. data.NextSiblingID = IDMapping[data.NextSiblingID] ? IDMapping[data.NextSiblingID] : -1;
  320. data.createDateTime = newDate;
  321. data.userID = userID;
  322. data.compilation = compilation;
  323. data.shareInfo = [];
  324. if (data.projType !== projectType.tender) {
  325. let newData = _.cloneDeep(data);
  326. delete newData._id;
  327. // await projectModel.create(newData);
  328. parentBulks.push({insertOne: {document: newData}});
  329. } else {
  330. //拷贝单位工程
  331. let rootProjectID = projMapping[data.ParentID].ParentID;
  332. let projectMap = {
  333. copy: {
  334. document: {userID: userID, ID: orgID, NextSiblingID: data.NextSiblingID, ParentID: data.ParentID, name: data.name, shareInfo: [],
  335. compilation: compilation, fileVer: data.fileVer, projType: data.projType, property: {rootProjectID: rootProjectID}}
  336. }
  337. };
  338. await copyProject(userID, compilation, {projectMap}, data.ID, true);
  339. projectMaps.push(projectMap);
  340. }
  341. }
  342. //最末顶层项目(兼容测试时已存在有项目,正常用户第一次进费用定额,该费用定额不存在项目)
  343. let lastProj = await projectModel.findOne({userID: userID, compilation: compilation, ParentID: -1, NextSiblingID: -1, $or: notDeleted});
  344. if (lastProj) {
  345. parentBulks.push({updateOne: {filter: {ID: lastProj.ID}, update: {$set: {NextSiblingID: parentExample[0].ID}}}});
  346. }
  347. // 处理项目数据
  348. const projectTasks = [projectModel.bulkWrite(parentBulks), createProject(projectMaps)];
  349. await Promise.all(projectTasks);
  350. return true;
  351. }
  352. async function accessToCopyProject(userID, compilationID, data, newProjectID) {
  353. const logData = {
  354. key: uuidV1(),
  355. content: '正在拷贝项目,请稍候……',
  356. userID,
  357. compilationID,
  358. status: 'start',
  359. create_time: +new Date()
  360. };
  361. await importLogsModel.create(logData);
  362. handleCopyProject(logData.key, userID, compilationID,data,newProjectID);
  363. return 'copying project';
  364. }
  365. async function handleCopyProject(key, userID, compilationID, data, newProjectID) {
  366. const doc = { status: 'finish' };
  367. try {
  368. const projectMap = await copyProject(userID, compilationID, data, newProjectID);
  369. doc.projectID = projectMap.copy.document.ID;
  370. } catch (err) {
  371. doc.status = 'error';
  372. doc.errorMsg = String(err);
  373. } finally {
  374. await importLogsModel.update({ key }, doc);
  375. }
  376. }
  377. async function copyProject(userID, compilationID,data,newProjectID = null, delayProjectTask = false) {
  378. let projectMap = data.projectMap;
  379. let originalID = projectMap['copy'].document.ID;
  380. if (!newProjectID) {
  381. newProjectID = await getCounterID("projects");
  382. }
  383. let newFeeName = null,newUnitName = null;
  384. let calcProgramFileID = uuidV1();//新的计算程序文件ID
  385. let labourCoeFileID = uuidV1();//新的人工调整系数文件ID
  386. let feeRateFileID = uuidV1();//新的费率文件ID
  387. let unitPriceFileID = await getCounterID("unit_price_file");//新的单价文件ID
  388. let originalProject = await projectModel.findOne({'ID':originalID});//查找最新的那项目信息,前端缓存的数据有可能不是最新的
  389. if(!originalProject){
  390. throw new Error('没有找到对应的项目,复制失败!');
  391. }
  392. let property = originalProject.property;
  393. if(projectMap['copy'].document.property){//更新项目属性信息
  394. setProperty(property,projectMap['copy'].document.property);
  395. }
  396. let originalProperty = _.cloneDeep(property);
  397. projectMap['copy'].document.property = property;
  398. logger.info("复制项目: 旧项目ID: "+originalID+ " ------- 新项目ID: "+newProjectID);
  399. //费率文件、单价文件重名检查
  400. let feeRate = await feeRateFileModel.findOne({rootProjectID:originalProperty.rootProjectID,name:originalProperty.feeFile.name,deleteInfo:null});
  401. if(feeRate){//存在重名的文件
  402. newFeeName = originalProperty.feeFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  403. projectMap['copy'].document.property.feeFile.name = newFeeName;
  404. }
  405. let unitPriceFile = await unitPriceFileModel.findOne({root_project_id: originalProperty.rootProjectID,name:originalProperty.unitPriceFile.name,deleteInfo: null});
  406. if(unitPriceFile){//存在重名的文件
  407. newUnitName = originalProperty.unitPriceFile.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '复制)';
  408. projectMap['copy'].document.property.unitPriceFile.name = newUnitName;
  409. }
  410. //更新项目的属性;
  411. projectMap['copy'].document.ID = newProjectID;
  412. if(projectMap['copy'].document.property.calcProgramFile){
  413. projectMap['copy'].document.property.calcProgramFile.ID = calcProgramFileID;
  414. }
  415. if(projectMap['copy'].document.property.labourCoeFile){
  416. projectMap['copy'].document.property.labourCoeFile.ID = labourCoeFileID;
  417. }
  418. if(projectMap['copy'].document.property.feeFile){
  419. projectMap['copy'].document.property.feeFile.id = feeRateFileID;
  420. }
  421. if(projectMap['copy'].document.property.unitPriceFile){
  422. projectMap['copy'].document.property.unitPriceFile.id = unitPriceFileID;
  423. }
  424. projectMap['copy'].document.userID = userID;
  425. projectMap['copy'].document.compilation = compilationID;
  426. projectMap['copy'].document.createDateTime = new Date();
  427. //清单、定额ID生成任务
  428. let IDtasks = [
  429. createIDsAndReturn(originalID,billsModel),
  430. createIDsAndReturn(originalID,rationModel),
  431. getProjectGLJIDAndReturn(originalID,newProjectID)
  432. ];
  433. let [billMap,rationMap,projectGLJMap] = await Promise.all(IDtasks);
  434. //所有复制任务异步处理,提升效率 复制清单,定额,4个文件,项目工料机, 定额工料机,人工系数,工程量明细,定额安装增加费,安装增加费
  435. let copyTasks = [
  436. copyProjectSetting(originalID,newProjectID),
  437. copyBills(newProjectID,billMap),
  438. copyRations(newProjectID,billMap.uuidMaping,rationMap,projectGLJMap.IDMap),
  439. copyProjectGLJ(projectGLJMap.datas),
  440. copyInstallFee(originalID,newProjectID),
  441. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationGLJModel),
  442. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationCoeModel),
  443. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,quantityDetailModel),
  444. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationInstallationModel),
  445. copyRationSubList(originalID,newProjectID,billMap.uuidMaping,rationMap.uuidMaping,projectGLJMap.IDMap,rationTemplateModel),
  446. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,evaluateListModel),
  447. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,bidListModel),
  448. copyMaterialList(originalID,newProjectID,projectGLJMap.IDMap,contractorListModel),
  449. ];
  450. if(originalProperty.calcProgramFile){
  451. copyTasks.push(commonCopy(newProjectID,originalProperty.calcProgramFile.ID,calcProgramFileID,calcProgramsModel));
  452. }
  453. if(originalProperty.labourCoeFile){
  454. copyTasks.push(commonCopy(newProjectID,originalProperty.labourCoeFile.ID,labourCoeFileID,labourCoesModel));
  455. }
  456. if(originalProperty.feeFile){
  457. copyTasks.push(copyFeeRate(originalProperty.rootProjectID,userID,originalProperty.feeFile.id,feeRateFileID,newFeeName));
  458. }
  459. if(originalProperty.unitPriceFile){
  460. copyTasks.push(copyUnitPriceFile(newProjectID,originalProperty.rootProjectID,userID,originalProperty.unitPriceFile.id,unitPriceFileID,newUnitName));
  461. }
  462. await Promise.all(copyTasks);
  463. // 最后再处理项目数据
  464. // 可能会有最后再在外层方法插入项目数据的需求,如拷贝例题,暂时先不在这里插入项目数据
  465. if (delayProjectTask) {
  466. return [projectMap];
  467. } else {
  468. const projectMaps = await createProject([projectMap]);
  469. return projectMaps[0];
  470. }
  471. }
  472. async function createIDsAndReturn(originalID,model) {
  473. let uuidMaping = {};//做ID映射
  474. let datas = [];
  475. let result = await model.find({"projectID": originalID}, '-_id');
  476. uuidMaping['-1'] = -1;
  477. //建立uuid-ID映射
  478. for(let d of result){
  479. uuidMaping[d.ID] = uuidV1();
  480. datas.push(d._doc);
  481. }
  482. return{uuidMaping:uuidMaping,datas:datas};
  483. }
  484. async function getProjectGLJIDAndReturn(originalID,newProjectID) {
  485. let IDMap = {};
  486. let datas = [];
  487. let result = await gljListModel.find({project_id:originalID}, '-_id');
  488. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, result.length);
  489. for(let i = 0; i < result.length; i++){
  490. let d = result[i];
  491. let newID = gljCount.sequence_value - (result.length - 1) + i;
  492. //let newID = await getCounterID("glj_list");
  493. IDMap[d.id] = newID;
  494. d._doc.project_id = newProjectID;
  495. d._doc.id = newID;
  496. datas.push(d._doc);
  497. }
  498. return{IDMap:IDMap,datas:datas};
  499. }
  500. async function createProject(projectMaps) {//复制项目
  501. let tasks = [];
  502. for (const projectMap of projectMaps) {
  503. if(projectMap['update']){//如果复制后存在前一个节点,则更新其NextSiblingID
  504. tasks.push({updateOne:{filter : projectMap['update'].query, update : {NextSiblingID:projectMap['copy'].document.ID}}});
  505. }
  506. tasks.push({insertOne: {document: projectMap['copy'].document}});//复制任务
  507. }
  508. await projectModel.bulkWrite(tasks);
  509. return projectMaps;
  510. }
  511. async function copyProjectSetting(originalID,newProjectID) {
  512. let result = null;
  513. let setting = await projectSettingModel.findOne({"projectID": originalID}, '-_id');
  514. if(setting){
  515. setting._doc.projectID =newProjectID;
  516. result = await projectSettingModel.create(setting._doc);
  517. }
  518. return result;
  519. }
  520. async function copyBills(newProjectID,billMap) {
  521. let uuidMaping = billMap.uuidMaping;//做ID映射
  522. for(let doc of billMap.datas){
  523. doc = getCopyBillDatas(doc,newProjectID,uuidMaping);
  524. }
  525. await insertMany(billMap.datas,billsModel);
  526. return billMap.datas;
  527. }
  528. function getCopyBillDatas(doc,newProjectID,uuidMaping) {
  529. doc.projectID = newProjectID;
  530. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  531. doc.ParentID = uuidMaping[doc.ParentID] ? uuidMaping[doc.ParentID] : -1;
  532. doc.NextSiblingID = uuidMaping[doc.NextSiblingID] ? uuidMaping[doc.NextSiblingID] : -1;
  533. //对于有基数计算的节点,需要替换计算基数中引用的ID为新的ID
  534. if(doc.calcBase && doc.calcBase != ""){
  535. let idArr = scMathUtil.getFIDArr(doc.calcBase);
  536. for(let re of idArr){
  537. let oID = re.substr(1);//去掉开头的@字符
  538. if(!uuidMaping[oID]) continue;
  539. doc.calcBase = doc.calcBase.replace(new RegExp(oID, "g"),uuidMaping[oID]);
  540. }
  541. }
  542. return doc;
  543. }
  544. async function copyRations(newProjectID,billsIDMap,rationMap,projectGLJIDMap) {
  545. let uuidMaping = rationMap.uuidMaping;
  546. for(let doc of rationMap.datas){
  547. doc = getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap);
  548. }
  549. if(rationMap.datas.length > 0){
  550. await insertMany(rationMap.datas,rationModel);
  551. }
  552. return rationMap.datas;
  553. }
  554. function getCopyRationData(doc,newProjectID,billsIDMap,uuidMaping,projectGLJIDMap){
  555. doc.projectID = newProjectID;
  556. doc.ID = uuidMaping[doc.ID] ? uuidMaping[doc.ID] : -1;
  557. if(doc.billsItemID){
  558. doc.billsItemID = billsIDMap[doc.billsItemID]?billsIDMap[doc.billsItemID]:-1;
  559. }
  560. if(doc.referenceRationID) doc.referenceRationID = uuidMaping[doc.referenceRationID]?uuidMaping[doc.referenceRationID]:undefined;
  561. //绑定定类型的工料机 项目工料机ID
  562. doc.type==3&&doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  563. return doc;
  564. }
  565. async function copyProjectGLJ(gljList) {
  566. await insertMany(gljList,gljListModel);
  567. }
  568. async function commonCopy(newProjectID,oldID,newID,model) { //对于只需更新ID和projectID的文件的复制
  569. let result = null;
  570. let file = await model.findOne({"ID": oldID}, '-_id');
  571. if(file){
  572. file._doc.ID = newID;
  573. file._doc.projectID =newProjectID;
  574. result = await model.create(file._doc);
  575. }
  576. return result;
  577. }
  578. async function copyFeeRate(rootProjectID,userID,originalFeeRateFileID,feeRateFileID,newName) {//复制费率和费率文件
  579. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(originalFeeRateFileID);
  580. let newFeeRateID = uuidV1();
  581. if(feeRate){
  582. feeRate._doc.ID = newFeeRateID;
  583. await feeRateModel.create(feeRate._doc);
  584. }
  585. if(feeRateFile){
  586. feeRateFile._doc.ID = feeRateFileID;
  587. newName?feeRateFile._doc.name = newName:'';
  588. feeRateFile._doc.userID = userID;
  589. feeRateFile._doc.rootProjectID = rootProjectID;
  590. feeRateFile._doc.feeRateID = newFeeRateID;
  591. await feeRateFileModel.create(feeRateFile._doc);
  592. }
  593. }
  594. async function copyUnitPriceFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName) {//复制单价文件、组成物
  595. let taskList = [
  596. copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName),
  597. copySubList(originaluUnitPriceFileID,unitPriceFileID,mixRatioModel),
  598. copySubList(originaluUnitPriceFileID,unitPriceFileID,unitPriceModel)
  599. ];
  600. return await Promise.all(taskList);
  601. async function copyFile(newProjectID,rootProjectID,userID,originaluUnitPriceFileID,unitPriceFileID,newName){
  602. let unitPriceFile = await unitPriceFileModel.findOne({id:originaluUnitPriceFileID}, '-_id');
  603. if(unitPriceFile){
  604. unitPriceFile._doc.id = unitPriceFileID;
  605. newName?unitPriceFile._doc.name = newName:'';
  606. unitPriceFile._doc.project_id = newProjectID;
  607. unitPriceFile._doc.user_id = userID;
  608. unitPriceFile._doc.root_project_id = rootProjectID
  609. }
  610. await unitPriceFileModel.create(unitPriceFile._doc);
  611. }
  612. async function copySubList(srcFID,newFID,model) {
  613. let mList = await model.find({unit_price_file_id: srcFID}, '-_id');
  614. let rList = [];
  615. for(let m of mList){
  616. m._doc.unit_price_file_id = newFID;
  617. m._doc.id = await getCounterID(model.modelName);
  618. rList.push(m._doc);
  619. }
  620. await insertMany(rList,model)
  621. }
  622. }
  623. async function copyInstallFee(originalPID,newProjectID) {
  624. let result = null;
  625. let installationFee = await installationFeeModel.find({projectID:originalPID}, '-_id');
  626. let newList = [];
  627. for(let i of installationFee ){
  628. i._doc.ID = uuidV1();
  629. i._doc.projectID = newProjectID;
  630. newList.push(i._doc);
  631. }
  632. if(newList.length >0){
  633. result = await installationFeeModel.insertMany(newList);
  634. }
  635. return result;
  636. }
  637. async function copyRationSubList(originalPID,newProjectID,billIDMap,rationIDMap,projectGLJIDMap,model) {// 定额工料机,附注条件,工程量明细,定额安装增加费,模板子目
  638. let subList = await model.find({projectID:originalPID}, '-_id');
  639. let newList =[];
  640. for(let s of subList){
  641. s._doc = getCopyRationSubData(s._doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  642. /* s._doc.ID = uuidV1();
  643. s._doc.projectID = newProjectID;
  644. s._doc.rationID&&rationIDMap[s._doc.rationID]?s._doc.rationID = rationIDMap[s._doc.rationID]:'';
  645. s._doc.billID&&billIDMap[s._doc.billID]?s._doc.billID = billIDMap[s._doc.billID]:'';
  646. s._doc.billsItemID&&billIDMap[s._doc.billsItemID]?s._doc.billsItemID = billIDMap[s._doc.billsItemID]:'';
  647. s._doc.projectGLJID&&projectGLJIDMap[s._doc.projectGLJID]?s._doc.projectGLJID = projectGLJIDMap[s._doc.projectGLJID]:'';
  648. if(s._doc.templateList && s._doc.templateList.length > 0 ){
  649. for(let t of s._doc.templateList){
  650. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  651. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  652. }
  653. }*/
  654. newList.push(s._doc);
  655. }
  656. await insertMany(newList,model);
  657. }
  658. async function copyMaterialList(originalPID,newProjectID,projectGLJIDMap,model) {//暂估材料等信息
  659. let materialList = await model.find({projectID:originalPID}, '-_id').lean();
  660. let newList = [];
  661. for(let m of materialList){
  662. newList.push(getNewMaterial(m,newProjectID,projectGLJIDMap))
  663. }
  664. await insertMany(newList,model);
  665. }
  666. function getNewMaterial(m,newProjectID,projectGLJIDMap) {
  667. m.ID = uuidV1();
  668. m.projectID = newProjectID;
  669. if(projectGLJIDMap[m.projectGLJID]) m.projectGLJID = projectGLJIDMap[m.projectGLJID];
  670. return m;
  671. }
  672. function getCopyRationSubData(doc,newProjectID,billIDMap,rationIDMap,projectGLJIDMap){
  673. doc.ID = uuidV1();
  674. doc.projectID = newProjectID;
  675. doc.rationID&&rationIDMap[doc.rationID]?doc.rationID = rationIDMap[doc.rationID]:'';
  676. doc.billID&&billIDMap[doc.billID]?doc.billID = billIDMap[doc.billID]:'';
  677. doc.billsItemID&&billIDMap[doc.billsItemID]?doc.billsItemID = billIDMap[doc.billsItemID]:'';
  678. doc.projectGLJID&&projectGLJIDMap[doc.projectGLJID]?doc.projectGLJID = projectGLJIDMap[doc.projectGLJID]:'';
  679. if(doc.templateList && doc.templateList.length > 0 ){
  680. for(let t of doc.templateList){
  681. if(t.billID && billIDMap[t.billID]) t.billID = billIDMap[t.billID];
  682. if(t.fxID && billIDMap[t.fxID]) t.fxID = billIDMap[t.fxID];
  683. }
  684. }
  685. return doc;
  686. }
  687. async function moveProject(data) {
  688. data = JSON.parse(data);
  689. let projectMap = data.projectMap,feeRateMap = data.feeRateMap,unitPriceMap = data.unitPriceMap;
  690. let projectTasks = [],feeRateTask=[],feeRateFileTask=[],unitPriceTask=[],unitPriceFileTask=[],mixRatioTask=[];
  691. let feeUniqMap=[],priceUniqMap={};//费率、单价文件唯一映射表当移动多个项目时,任务有可能出现重复的情况
  692. if(!_.isEmpty(feeRateMap)&&data.rootProjectID){//如果费率有修改
  693. let feeRates =await feeRate_facade.getFeeRatesByProject(data.rootProjectID);//取目标建设项目的所有费率文件,重名检查
  694. for(let projectID in feeRateMap){
  695. let rename = feeRateMap[projectID].name;
  696. let feeRateID = feeRateMap[projectID].query.ID;
  697. let checkFee = _.find(feeRates,{'name':rename});
  698. let newID = feeRateID;
  699. if(checkFee){//说明费率名字已存在,需要重命名
  700. rename = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  701. projectMap[projectID]['update']['property.feeFile.name'] = rename;
  702. if(feeRateMap[projectID].action == 'move'){
  703. feeRateMap[projectID].update.name = rename;
  704. }
  705. }
  706. if(feeRateMap[projectID].action == 'copy'){
  707. newID = feeUniqMap[feeRateID]?feeUniqMap[feeRateID].ID:uuidV1();
  708. feeRateMap[projectID].name = rename;
  709. feeRateMap[projectID].ID = newID;
  710. projectMap[projectID]['update']['property.feeFile.id'] = newID;
  711. }
  712. if(!feeUniqMap[feeRateID]){
  713. await generateFeeRateTask(feeRateMap[projectID],feeRateTask,feeRateFileTask);
  714. feeUniqMap[feeRateID] = {name:rename,ID:newID};
  715. }
  716. }
  717. }
  718. if(!_.isEmpty(unitPriceMap)&&data.rootProjectID) {//如果单价文件有修改
  719. let unitPriceFiles = await unitPriceFileModel.find({root_project_id: data.rootProjectID, deleteInfo: null});
  720. for(let projectID in unitPriceMap){
  721. let checkUn = _.find(unitPriceFiles,{'name':unitPriceMap[projectID].name});
  722. let rename = unitPriceMap[projectID].name;
  723. let unitPriceID = unitPriceMap[projectID].query.id;
  724. let newID = unitPriceID;
  725. if(checkUn){//重名检查
  726. rename = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].name:rename + '(' + new Date().Format('MM-dd hh:mm:ss') + '移动)';
  727. projectMap[projectID]['update']['property.unitPriceFile.name'] = rename;
  728. if(unitPriceMap[projectID].action =='move'){
  729. unitPriceMap[projectID].update.name = rename;
  730. }
  731. }
  732. if(unitPriceMap[projectID].action =='copy'){
  733. newID = priceUniqMap[unitPriceID]?priceUniqMap[unitPriceID].id: await getCounterID("unit_price_file");
  734. unitPriceMap[projectID].name = rename;
  735. unitPriceMap[projectID].id = newID;
  736. projectMap[projectID]['update']['property.unitPriceFile.id'] = newID;
  737. }
  738. if(!priceUniqMap[unitPriceID]){
  739. await generateUnitPriceTask(unitPriceMap[projectID],projectID,data.user_id,unitPriceTask,unitPriceFileTask,mixRatioTask);
  740. priceUniqMap[unitPriceID] = {name:rename,id:newID};
  741. }
  742. }
  743. }
  744. if(!_.isEmpty(projectMap)){
  745. for(let projectID in projectMap){
  746. projectTasks.push({updateOne:{filter : projectMap[projectID].query, update : projectMap[projectID].update}});
  747. }
  748. }
  749. projectTasks.length>0?await projectModel.bulkWrite(projectTasks):'';
  750. feeRateTask.length>0?await feeRateModel.bulkWrite(feeRateTask):'';
  751. feeRateFileTask.length>0?await feeRateFileModel.bulkWrite(feeRateFileTask):'';
  752. unitPriceFileTask.length>0?await unitPriceFileModel.bulkWrite(unitPriceFileTask):'';
  753. unitPriceTask.length>0?await insertMany(unitPriceTask,unitPriceModel):'';
  754. mixRatioTask.length>0?await insertMany(mixRatioTask,mixRatioModel):'';
  755. return projectMap;
  756. }
  757. async function generateFeeRateTask(data,feeRateTask,feeRateFileTask) {
  758. if(data.action == 'move'){
  759. let task = {
  760. updateOne:{
  761. filter : data.query,
  762. update : data.update
  763. }
  764. };
  765. feeRateFileTask.push(task);
  766. }
  767. if(data.action == 'copy'){//copy 费率的时候用insertOne方法
  768. let [feeRateFile,feeRate] =await feeRate_facade.getFeeRateByID(data.query.ID);
  769. let newFeeRateID = uuidV1();
  770. let newFeeRate = {
  771. ID:newFeeRateID,
  772. rates:feeRate.rates
  773. };
  774. let newFeeRateFile = {
  775. ID:data.ID,
  776. rootProjectID:data.rootProjectID,
  777. userID:feeRateFile.userID,
  778. name:data.name,
  779. libID:feeRateFile.libID,
  780. libName:feeRateFile.libName,
  781. feeRateID:newFeeRateID
  782. };
  783. feeRateTask.push({insertOne :{document:newFeeRate}});
  784. feeRateFileTask.push({insertOne :{document:newFeeRateFile}});
  785. }
  786. }
  787. async function generateUnitPriceTask(data,projectID,user_id,unitPriceTask,unitPriceFileTask,mixRatioTask){
  788. if(data.action == 'move'){
  789. let task = {
  790. updateOne:{
  791. filter : data.query,
  792. update : data.update
  793. }
  794. };
  795. unitPriceFileTask.push(task);
  796. }
  797. if(data.action == 'copy'){
  798. let newUnitFile = {
  799. id:data.id,
  800. name: data.name,
  801. project_id:projectID,
  802. user_id:user_id,
  803. root_project_id: data.rootProjectID
  804. };
  805. unitPriceFileTask.push({insertOne :{document:newUnitFile}});
  806. let mixRatios = await mixRatioModel.find({unit_price_file_id: data.query.id});
  807. mixRatios = JSON.stringify(mixRatios);
  808. mixRatios = JSON.parse(mixRatios);
  809. for(let m of mixRatios){
  810. delete m._id; // 删除原有id信息
  811. delete m.id;
  812. m.unit_price_file_id = data.id;
  813. m.id = await getCounterID('mix_ratio');
  814. mixRatioTask.push(m);
  815. }
  816. let unitPrices = await unitPriceModel.find({unit_price_file_id: data.query.id});//unit_price_file_id
  817. unitPrices = JSON.stringify(unitPrices);
  818. unitPrices = JSON.parse(unitPrices);
  819. for(let u of unitPrices){
  820. delete u._id; // 删除原有id信息
  821. delete u.id;
  822. u.unit_price_file_id = data.id;
  823. u.id = await getCounterID('unit_price');
  824. unitPriceTask.push(u);
  825. }
  826. }
  827. }
  828. async function getCounterID(collectionName){
  829. let counterModel = new CounterModel();
  830. return await counterModel.getId(collectionName);
  831. }
  832. async function insertMany(datas,model) {
  833. while (datas.length>1000){//因为mongoose限制了批量插入的条数为1000.所以超出限制后需要分批插入
  834. let newList = datas.splice(0,1000);//一次插入1000条
  835. await model.insertMany(newList);
  836. }
  837. await model.insertMany(datas);
  838. }
  839. function setProperty(Obj,updateData) {
  840. for(let ukey in updateData){
  841. if(_.isObject(updateData[ukey]) && _.isObject(Obj[ukey])){
  842. setProperty(Obj[ukey],updateData[ukey]);
  843. }else {
  844. Obj[ukey] = updateData[ukey];
  845. }
  846. }
  847. }
  848. function isDef(v){
  849. return typeof v !== 'undefined' && v !== null;
  850. }
  851. function getTotalFee(bills, feeName) {
  852. if(!isDef(bills)){
  853. return 0;
  854. }
  855. if(!isDef(bills.fees) || bills.fees.length <= 0){
  856. return 0;
  857. }
  858. for(let fee of bills.fees){
  859. if(isDef(fee.fieldName) && fee.fieldName === feeName){
  860. return isDef(fee.tenderTotalFee)
  861. ? fee.tenderTotalFee
  862. : isDef(fee.totalFee)
  863. ? fee.totalFee
  864. : 0;
  865. }
  866. }
  867. return 0;
  868. }
  869. function summarizeToParent(parent, child, fields = null) {
  870. const decimal = -2;
  871. if (!fields) {
  872. fields = ['engineeringCost', 'subEngineering', 'measure', 'safetyConstruction', 'other', 'charge', 'tax', 'estimate'];
  873. }
  874. for (let field of fields) {
  875. parent[field] = scMathUtil.roundTo(parseFloat(parent[field]) + parseFloat(child[field]), decimal);
  876. }
  877. }
  878. function getBuildingArea(projFeature){
  879. if(!projFeature || projFeature.length === 0){
  880. return null;
  881. }
  882. for(let f of projFeature){
  883. if(f.key === 'buildingArea'){
  884. return f.value;
  885. }
  886. }
  887. return null;
  888. }
  889. //根据单位工程ID获取经济指标信息
  890. //@param {Number}prj_id @return {Object}
  891. async function getIndexReportData(prj_id, filters) {
  892. return await project_facade.getIndexReportData(prj_id, filters);
  893. }
  894. // 根据树结构数据排序
  895. function getSortedDataByTree(data) {
  896. // NextSiblingID-数据映射
  897. const mapping = {};
  898. data.forEach(item => {
  899. // 错误数据兼容处理
  900. // 由于之前的导入建设项目,会导致最后的一个项目的NextSiblingID为空,为非正确的-1
  901. // 因此把项目中NextSibling为空的数据设置为NextSiblingID为-1
  902. if (!item.NextSiblingID) {
  903. item.NextSiblingID = -1;
  904. }
  905. mapping[item.NextSiblingID] = item;
  906. });
  907. let lastItem = data.find(item => +item.NextSiblingID === -1);
  908. if (!lastItem) {
  909. return data;
  910. }
  911. const rst = [lastItem];
  912. let preItem = mapping[lastItem.ID];
  913. while (preItem) {
  914. rst.unshift(preItem);
  915. preItem = mapping[preItem.ID];
  916. }
  917. // 根据树结构排序形成的新数组与旧数组项数不同,说明树结构数据有问题(断链),则返回原本数据。
  918. return rst.length === data.length ? rst : data;
  919. }
  920. //根据单位工程ID获取汇总信息
  921. //@param {Number}tenderID {String}summaryType @return {Object}
  922. async function getSummaryInfoByTender(tenderID, summaryType) {
  923. const notDeleted = [{deleteInfo: null}, {'deleteInfo.deleted': false}];
  924. let tender = await projectModel.findOne({ID: tenderID, $or: notDeleted});
  925. let parent,
  926. parentName,
  927. compilationIllustration;
  928. let summaryList = [];
  929. if(!tender){
  930. return null;
  931. }
  932. let engineering = await projectModel.findOne({ID: tender.ParentID, $or: notDeleted});
  933. if(!engineering){
  934. return null;
  935. }
  936. let project = await projectModel.findOne({ID: engineering.ParentID, $or: notDeleted});
  937. if(!project){
  938. return null;
  939. }
  940. let summaryInfo = await getSummaryInfo([project.ID]);
  941. if(summaryType === projectType.engineering){ // 汇总到单项工程级别
  942. parent = engineering;
  943. let tenders = await projectModel.find({ParentID: engineering.ID, $or: notDeleted}).lean();
  944. tenders = getSortedDataByTree(tenders);
  945. for(let t of tenders){
  946. if(summaryInfo[t.ID]){
  947. summaryInfo[t.ID]['name'] = t.name ? t.name : '';
  948. summaryList.push(summaryInfo[t.ID]);
  949. }
  950. }
  951. } else { // 汇总到建设项目级别
  952. parent = project;
  953. let engs = await projectModel.find({ParentID: project.ID, $or: notDeleted}).lean();
  954. engs = getSortedDataByTree(engs);
  955. for(let e of engs){
  956. if(summaryInfo[e.ID]){
  957. summaryInfo[e.ID]['name'] = e.name ? e.name : '';
  958. summaryList.push(summaryInfo[e.ID]);
  959. }
  960. }
  961. }
  962. // 项目名称
  963. parentName = parent && parent.name
  964. ? parent.name
  965. : '';
  966. // 编制说明
  967. compilationIllustration = parent && parent.property && parent.property.compilationIllustration
  968. ? parent.property.compilationIllustration
  969. : '';
  970. return {
  971. parent: {
  972. name: parentName,
  973. compilationIllustration: compilationIllustration},
  974. subList: summaryList
  975. };
  976. }
  977. //获取单位工程的各标段费用信息(不进行汇总)
  978. async function getTendersFeeInfo(tenders) {
  979. let IDMapping = {};
  980. //固定清单类别与汇总金额字段映射
  981. let flagFieldMapping = {};
  982. flagFieldMapping[fixedFlag.ENGINEERINGCOST] = 'engineeringCost';
  983. flagFieldMapping[fixedFlag.SUB_ENGINERRING] = 'subEngineering';
  984. flagFieldMapping[fixedFlag.MEASURE] = 'measure';
  985. flagFieldMapping[fixedFlag.SAFETY_CONSTRUCTION] = 'safetyConstruction';
  986. flagFieldMapping[fixedFlag.OTHER] = 'other';
  987. flagFieldMapping[fixedFlag.CHARGE] = 'charge';
  988. flagFieldMapping[fixedFlag.TAX] = 'tax';
  989. let tenderIDs = [];
  990. if(tenders.length > 0){
  991. for(let tender of tenders){
  992. tenderIDs.push(tender.ID);
  993. IDMapping[tender.ID] = {engineeringCost: 0, subEngineering: 0, measure: 0, safetyConstruction: 0, other: 0, charge: 0, tax: 0, estimate: 0, rate: 0, buildingArea: '', perCost: ''};
  994. IDMapping[tender.ID]['buildingArea'] = '';
  995. }
  996. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金
  997. let needFlags = [fixedFlag.ENGINEERINGCOST, fixedFlag.SUB_ENGINERRING, fixedFlag.MEASURE,
  998. fixedFlag.SAFETY_CONSTRUCTION, fixedFlag.CHARGE, fixedFlag.OTHER, fixedFlag.TAX];
  999. //获取单位工程汇总金额需要用到的所有清单
  1000. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: notDeleted},
  1001. '-_id projectID fees flags');
  1002. //进行单位工程级别的汇总
  1003. for(let bills of allBills){
  1004. let billsFlag = bills.flags[0]['flag'];
  1005. let costField = flagFieldMapping[billsFlag];
  1006. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1007. //暂估合价(工程造价暂估合价)
  1008. if (billsFlag === fixedFlag.ENGINEERINGCOST){
  1009. IDMapping[bills.projectID]['estimate'] = getTotalFee(bills, 'estimate');
  1010. }
  1011. }
  1012. //占造价比例、单方造价
  1013. for(let tender of tenders){
  1014. let tenderInfo = IDMapping[tender.ID];
  1015. tenderInfo.rate = '';
  1016. //单方造价
  1017. tenderInfo.perCost = '';
  1018. }
  1019. }
  1020. return IDMapping;
  1021. }
  1022. const defaultSummaryField = {
  1023. [fixedFlag.ENGINEERINGCOST]: {
  1024. items: [
  1025. { name: 'engineeringCost', feeName: 'common' },
  1026. { name: 'estimate', feeName: 'estimate' }
  1027. ]
  1028. },
  1029. [fixedFlag.SUB_ENGINERRING]: {
  1030. items: [{ name: 'subEngineering', feeName: 'common' }]
  1031. },
  1032. [fixedFlag.MEASURE]: {
  1033. items: [{ name: 'measure', feeName: 'common' }]
  1034. },
  1035. [fixedFlag.SAFETY_CONSTRUCTION]: {
  1036. items: [{ name: 'safetyConstruction', feeName: 'common' }]
  1037. },
  1038. [fixedFlag.OTHER]: {
  1039. items: [{ name: 'other', feeName: 'common' }]
  1040. },
  1041. [fixedFlag.CHARGE]: {
  1042. items: [{ name: 'charge', feeName: 'common' }]
  1043. },
  1044. [fixedFlag.TAX]: {
  1045. items: [{ name: 'tax', feeName: 'common' }]
  1046. }
  1047. };
  1048. // 项目管理界面需要显示的汇总字段
  1049. function setupSummaryFields(summaryInfo, projects, fields = null) {
  1050. if (!fields) {
  1051. fields = [
  1052. 'engineeringCost',
  1053. 'subEngineering',
  1054. 'measure',
  1055. 'safetyConstruction',
  1056. 'other',
  1057. 'charge',
  1058. 'tax',
  1059. 'rate',
  1060. 'buildingArea',
  1061. 'perCost'
  1062. ];
  1063. }
  1064. for(const proj of projects){
  1065. const summaryProj = summaryInfo[proj.ID];
  1066. if(summaryProj){
  1067. for (const field of fields) {
  1068. proj[field] = summaryProj[field];
  1069. }
  1070. }
  1071. }
  1072. }
  1073. async function getSummaryInfo(projectIDs, summaryField = defaultSummaryField){
  1074. function initFees(target, summaryField) {
  1075. for (const flag in summaryField) {
  1076. const summaryItem = summaryField[flag];
  1077. summaryItem.items.forEach(item => {
  1078. target[item.name] = 0;
  1079. });
  1080. }
  1081. }
  1082. //ID与汇总信息映射
  1083. let IDMapping = {};
  1084. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1085. //设置建设项目的总建筑面积
  1086. for(let project of projects){
  1087. let grossArea = '';
  1088. if(project.property && project.property.basicInformation){
  1089. for(let basicInfo of project.property.basicInformation){
  1090. if(basicInfo.key === 'basicInfo'){
  1091. for(let k of basicInfo.items){
  1092. if(k.key === 'grossArea'){
  1093. grossArea = k.value;
  1094. }
  1095. }
  1096. }
  1097. }
  1098. }
  1099. IDMapping[project.ID] = {rate: 0, buildingArea: grossArea, perCost: ''};
  1100. initFees(IDMapping[project.ID], summaryField);
  1101. }
  1102. //单项工程
  1103. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1104. let tenders = [];
  1105. let engIDs = [];
  1106. for(let eng of engineerings){
  1107. engIDs.push(eng.ID);
  1108. IDMapping[eng.ID] = {rate: 0, buildingArea: '', perCost: ''};
  1109. initFees(IDMapping[eng.ID], summaryField);
  1110. }
  1111. //单位工程
  1112. if(engIDs.length > 0){
  1113. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1114. }
  1115. let tenderIDs = [];
  1116. if(tenders.length > 0){
  1117. for(let tender of tenders){
  1118. tenderIDs.push(tender.ID);
  1119. IDMapping[tender.ID] = {rate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1120. initFees(IDMapping[tender.ID], summaryField);
  1121. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1122. if(buildingArea){
  1123. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1124. }
  1125. }
  1126. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1127. let needFlags = Object.getOwnPropertyNames(summaryField);
  1128. //获取单位工程汇总金额需要用到的所有清单
  1129. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1130. '-_id projectID fees flags');
  1131. //进行单位工程级别的汇总
  1132. for(let bills of allBills){
  1133. let billsFlag = bills.flags[0]['flag'];
  1134. // 设置上单位工程需要汇总的字段金额
  1135. const summaryItem = summaryField[billsFlag];
  1136. summaryItem.items.forEach(costItem => {
  1137. IDMapping[bills.projectID][costItem.name] = getTotalFee(bills, costItem.feeName);
  1138. });
  1139. }
  1140. const summaryNames = [];
  1141. for (const flag in summaryField) {
  1142. summaryField[flag].items.forEach(item => summaryNames.push(item.name));
  1143. }
  1144. //进行单项工程级别的汇总
  1145. for(let tender of tenders){
  1146. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryNames);
  1147. }
  1148. //进行建设项目级别的汇总
  1149. for(let eng of engineerings){
  1150. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryNames);
  1151. }
  1152. //占造价比例、单方造价
  1153. const rateDecimal = -2;
  1154. const perCostDecimal = -2;
  1155. for(let tender of tenders){
  1156. let tenderInfo = IDMapping[tender.ID];
  1157. let engInfo = IDMapping[tender.ParentID];
  1158. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1159. //单方造价
  1160. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1161. ? tenderInfo.buildingArea.toString().trim()
  1162. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1163. }
  1164. for(let eng of engineerings){
  1165. let engInfo = IDMapping[eng.ID];
  1166. let projInfo = IDMapping[eng.ParentID];
  1167. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1168. }
  1169. //建设项目占造价比例及单方造价
  1170. for(let project of projects){
  1171. let projectInfo = IDMapping[project.ID];
  1172. projectInfo.rate = 100;
  1173. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1174. ? projectInfo.buildingArea.toString().trim()
  1175. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1176. }
  1177. }
  1178. return IDMapping;
  1179. }
  1180. /* async function getSummaryInfo(projectIDs, feeFields = null, engineeringCostFields = null){
  1181. function initFees(obj, feeFields, engineeringCostFields) {
  1182. for (let data of feeFields) {
  1183. obj[data.v] = 0;
  1184. }
  1185. for (let data of engineeringCostFields) {
  1186. obj[data.k] = 0;
  1187. }
  1188. }
  1189. if (!feeFields) {
  1190. feeFields = [
  1191. {k: fixedFlag.ENGINEERINGCOST, v: 'engineeringCost'},
  1192. {k: fixedFlag.SUB_ENGINERRING, v: 'subEngineering'},
  1193. {k: fixedFlag.MEASURE, v: 'measure'},
  1194. {k: fixedFlag.SAFETY_CONSTRUCTION, v: 'safetyConstruction'},
  1195. {k: fixedFlag.OTHER, v: 'other'},
  1196. {k: fixedFlag.CHARGE, v: 'charge'},
  1197. {k: fixedFlag.TAX, v: 'tax'}
  1198. ];
  1199. }
  1200. // 项目总造价的各个费用,k为汇总的字段,v为工程造价的费用字段
  1201. if (!engineeringCostFields) {
  1202. engineeringCostFields = [{ k: 'estimate', v: 'estimate' }];
  1203. }
  1204. //ID与汇总信息映射
  1205. let IDMapping = {};
  1206. //固定清单类别与汇总金额字段映射
  1207. let flagFieldMapping = {};
  1208. for (let data of feeFields) {
  1209. flagFieldMapping[data.k] = data.v;
  1210. }
  1211. let projects = await projectModel.find({ID: {$in : projectIDs}, projType: projectType.project, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1212. //设置建设项目的总建筑面积
  1213. for(let project of projects){
  1214. let grossArea = '';
  1215. if(project.property && project.property.basicInformation){
  1216. for(let basicInfo of project.property.basicInformation){
  1217. if(basicInfo.key === 'basicInfo'){
  1218. for(let k of basicInfo.items){
  1219. if(k.key === 'grossArea'){
  1220. grossArea = k.value;
  1221. }
  1222. }
  1223. }
  1224. }
  1225. }
  1226. IDMapping[project.ID] = {rate: 0, buildingArea: grossArea, perCost: ''};
  1227. initFees(IDMapping[project.ID], feeFields, engineeringCostFields);
  1228. console.log(IDMapping[project.ID]);
  1229. }
  1230. //单项工程
  1231. let engineerings = await projectModel.find({ParentID: {$in : projectIDs}, projType: projectType.engineering, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1232. let tenders = [];
  1233. let engIDs = [];
  1234. for(let eng of engineerings){
  1235. engIDs.push(eng.ID);
  1236. IDMapping[eng.ID] = {rate: 0, buildingArea: '', perCost: ''};
  1237. initFees(IDMapping[eng.ID], feeFields, engineeringCostFields);
  1238. }
  1239. //单位工程
  1240. if(engIDs.length > 0){
  1241. tenders = await projectModel.find({ParentID: {$in : engIDs}, projType: projectType.tender, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]});
  1242. }
  1243. let tenderIDs = [];
  1244. if(tenders.length > 0){
  1245. for(let tender of tenders){
  1246. tenderIDs.push(tender.ID);
  1247. IDMapping[tender.ID] = {rate: 0, buildingArea: '', perCost: '', changeMark:tender.changeMark,property:tender.property};
  1248. initFees(IDMapping[tender.ID], feeFields, engineeringCostFields);
  1249. let buildingArea = getBuildingArea(tender.property.projectFeature);
  1250. if(buildingArea){
  1251. IDMapping[tender.ID]['buildingArea'] = buildingArea;
  1252. }
  1253. }
  1254. //需要获取的清单固定类别综合合价:工程造价、分部分项、措施项目、安全文明施工专项、规费、其他项目、税金...
  1255. let needFlags = feeFields.map(data => data.k);
  1256. //获取单位工程汇总金额需要用到的所有清单
  1257. let allBills = await billsModel.find({projectID: {$in: tenderIDs}, 'flags.flag': {$in: needFlags}, $or: [{deleteInfo: null}, {'deleteInfo.deleted': false}]},
  1258. '-_id projectID fees flags');
  1259. //进行单位工程级别的汇总
  1260. for(let bills of allBills){
  1261. let billsFlag = bills.flags[0]['flag'];
  1262. let costField = flagFieldMapping[billsFlag];
  1263. IDMapping[bills.projectID][costField] = getTotalFee(bills, 'common');
  1264. // 工程造价各费用
  1265. if (billsFlag === fixedFlag.ENGINEERINGCOST){
  1266. engineeringCostFields.forEach(({k, v}) => {
  1267. IDMapping[bills.projectID][k] = getTotalFee(bills, v);
  1268. });
  1269. }
  1270. }
  1271. let summaryFields = [...feeFields, ...engineeringCostFields].map(data => data.v);
  1272. //进行单项工程级别的汇总
  1273. for(let tender of tenders){
  1274. summarizeToParent(IDMapping[tender.ParentID], IDMapping[tender.ID], summaryFields);
  1275. }
  1276. //进行建设项目级别的汇总
  1277. for(let eng of engineerings){
  1278. summarizeToParent(IDMapping[eng.ParentID], IDMapping[eng.ID], summaryFields);
  1279. }
  1280. //占造价比例、单方造价
  1281. const rateDecimal = -2;
  1282. const perCostDecimal = -2;
  1283. for(let tender of tenders){
  1284. let tenderInfo = IDMapping[tender.ID];
  1285. let engInfo = IDMapping[tender.ParentID];
  1286. tenderInfo.rate = engInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(tenderInfo.engineeringCost * 100 / engInfo.engineeringCost, rateDecimal);
  1287. //单方造价
  1288. tenderInfo.perCost = tenderInfo.buildingArea.toString().trim() === '' || tenderInfo.buildingArea == 0
  1289. ? tenderInfo.buildingArea.toString().trim()
  1290. : scMathUtil.roundTo(tenderInfo.engineeringCost / tenderInfo.buildingArea, perCostDecimal);
  1291. }
  1292. for(let eng of engineerings){
  1293. let engInfo = IDMapping[eng.ID];
  1294. let projInfo = IDMapping[eng.ParentID];
  1295. engInfo.rate = !isDef(projInfo) || projInfo.engineeringCost == 0 ? 0 : scMathUtil.roundTo(engInfo.engineeringCost * 100 / projInfo.engineeringCost, rateDecimal);
  1296. }
  1297. //建设项目占造价比例及单方造价
  1298. for(let project of projects){
  1299. let projectInfo = IDMapping[project.ID];
  1300. projectInfo.rate = 100;
  1301. projectInfo.perCost = projectInfo.buildingArea.toString().trim() === '' || projectInfo.buildingArea == 0
  1302. ? projectInfo.buildingArea.toString().trim()
  1303. : scMathUtil.roundTo(projectInfo.engineeringCost / projectInfo.buildingArea, perCostDecimal);
  1304. }
  1305. }
  1306. return IDMapping;
  1307. } */
  1308. //根据项目ID获取所属建设项目
  1309. //@param {Number}projectID @return {Object}
  1310. async function getConstructionProject(projectID){
  1311. function returnProject(project){
  1312. if(!project || project.projType === projectType.folder){
  1313. return null;
  1314. }
  1315. if(project.projType === projectType.project){
  1316. return project;
  1317. }
  1318. }
  1319. let project = await projectModel.findOne({ID: projectID, $or: notDeleted});
  1320. let returnV = returnProject(project);
  1321. if(returnV !== undefined){
  1322. return returnV;
  1323. }
  1324. let parent = await projectModel.findOne({ID: project.ParentID, $or: notDeleted});
  1325. returnV = returnProject(parent);
  1326. if(returnV !== undefined){
  1327. return returnV;
  1328. }
  1329. let grandParent = await projectModel.findOne({ID: parent.ParentID, $or: notDeleted});
  1330. returnV = returnProject(grandParent);
  1331. return returnV !== undefined ? returnV : null;
  1332. }
  1333. //获取单位工程完整目录结构
  1334. //@param {Number}projectID @return {Arry}
  1335. async function getFullPath(projectID) {
  1336. let fullPath = [];
  1337. let project = await projectModel.findOne({ID: projectID, $or: notDeleted}, '-_id ParentID name');
  1338. if(project){
  1339. fullPath.push(project.name);
  1340. await getParent(project.ParentID);
  1341. }
  1342. fullPath = fullPath.reverse();
  1343. return fullPath;
  1344. async function getParent(ParentID) {
  1345. if(ParentID != -1){
  1346. let parent = await projectModel.findOne({ID: ParentID, $or: notDeleted}, '-_id ParentID name');
  1347. if(parent){
  1348. fullPath.push(parent.name);
  1349. await getParent(parent.ParentID);
  1350. }
  1351. }
  1352. }
  1353. }
  1354. // 获取项目链上,自身、父项、爷爷项...的ID
  1355. async function getUpChainIDs(projectID) {
  1356. const rst = [];
  1357. while (projectID != -1) {
  1358. rst.push(projectID);
  1359. const project = await projectModel.findOne({ ID: projectID }, '-_id ParentID').lean();
  1360. projectID = project ? project.ParentID : -1;
  1361. }
  1362. return rst;
  1363. }
  1364. //获取projectIDs文件下所有子项目(默认不包括projectIDs本身)
  1365. async function getPosterityProjects(projectIDs, includeSelf = false) {
  1366. let rst = [];
  1367. if (includeSelf) {
  1368. const projects = await projectModel.find({ID: {$in: projectIDs}, $or: notDeleted}, '-_id').lean();
  1369. if (projects) {
  1370. rst.push(...projects);
  1371. }
  1372. }
  1373. async function getProjects(parentIDs) {
  1374. if (parentIDs.length > 0) {
  1375. let newIDs = [];
  1376. let projs = await projectModel.find({ParentID: {$in: parentIDs}, $or: notDeleted}, '-_id').lean();
  1377. for (let proj of projs) {
  1378. // 兼容旧的错误数据,可能ParentID和ID相同
  1379. if (parentIDs.includes(proj.ID)) {
  1380. continue;
  1381. }
  1382. rst.push(proj);
  1383. newIDs.push(proj.ID);
  1384. }
  1385. await getProjects(newIDs);
  1386. }
  1387. }
  1388. await getProjects(projectIDs);
  1389. return rst;
  1390. }
  1391. //根据项目获得分享信息(分享层级不一定在项目级)(以最新为准)
  1392. async function getShareInfo(userID, projectID) {
  1393. // 接受到的分享项目
  1394. const upChainIDs = await getUpChainIDs(projectID);
  1395. const shareList = await getShareList({receiver: userID, projectID: {$in: upChainIDs}});
  1396. // 返回最新的分享
  1397. //return shareList.sort((a, b) => Date.parse(b.shareDate) - Date.parse(a.shareDate))[0];
  1398. return shareList.sort((a, b) => Date.parse(b.updateDate) - Date.parse(a.updateDate))[0];
  1399. }
  1400. //打开的单位工程是否是被分享的.
  1401. async function isShare(userId, project){
  1402. //判断是否是打开分享的项目,属于分享文件的子项也算
  1403. while (project) {
  1404. for(let shareData of project.shareInfo){
  1405. if(shareData.userID === userId){
  1406. return true;
  1407. }
  1408. }
  1409. project = await projectModel.findOne({ID: project.ParentID}, '-_id shareInfo ID ParentID');
  1410. }
  1411. return false;
  1412. }
  1413. //用户是否第一次进入费用定额
  1414. async function isFirst(userId, compilationId) {
  1415. let userData = await userModel.findOne({_id: mongoose.Types.ObjectId(userId)}, '-_id used_list');
  1416. let first = false;
  1417. if (userData) {
  1418. first = !_.find(userData.used_list, function (o) {
  1419. return o.compilationId === compilationId;
  1420. });;
  1421. }
  1422. return first;
  1423. }
  1424. async function importChongqingProject(data) {
  1425. let log_data = {
  1426. key:data.key,
  1427. content: '正在导入例题,请稍候……',
  1428. userID:data.user_id,
  1429. compilationID: data.session.sessionCompilation._id,
  1430. status:"start",
  1431. create_time:+new Date()
  1432. };
  1433. await importLogsModel.create(log_data);
  1434. doImport(data.user_id,data.session.sessionCompilation._id,data.session.sessionCompilation.adProjects,data.key);
  1435. return "start importing";
  1436. async function doImport(user_id,compilationId,projectIDs,key) {
  1437. let doc = {status:"finish"};
  1438. try {
  1439. let r = await copyExample(user_id,compilationId,projectIDs);
  1440. if(r == false){
  1441. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1442. doc.status = "error";
  1443. }
  1444. }catch (error){
  1445. console.log(error);
  1446. doc.errorMsg = "导入失败,请检查项目是否存在!";
  1447. doc.status = "error";
  1448. }finally {
  1449. await importLogsModel.update({key:key},doc);
  1450. }
  1451. }
  1452. }
  1453. function testTimeout(time) {
  1454. return new Promise(resolve => setTimeout(resolve, time));
  1455. }
  1456. //用户第一次进入费用定额的数据准备
  1457. async function prepareInitialData(userId, compilation, example) {
  1458. let first = await isFirst(userId, compilation);
  1459. if (first) {
  1460. await updateUsedList(userId, compilation);
  1461. const logData = {
  1462. key: uuidV1(),
  1463. content: '正在加载例题,请稍候……',
  1464. userID: userId,
  1465. compilationID: compilation,
  1466. status: 'start',
  1467. create_time: +new Date()
  1468. };
  1469. await importLogsModel.create(logData);
  1470. initData(logData.key, userId, compilation, example);
  1471. return 'start prepareInitialData';
  1472. }
  1473. async function initData(key, userId, compilation, example) {
  1474. const doc = { status: 'finish' };
  1475. try {
  1476. let prepareTask = [
  1477. copyCompleRationSection(userId, compilation),
  1478. copyCompleGljSection(userId, compilation)
  1479. ];
  1480. if (example && example.length > 0) {
  1481. prepareTask.push(copyExample(userId, compilation, example));
  1482. }
  1483. await Promise.all(prepareTask);
  1484. } catch (error) {
  1485. doc.errorMsg = '加载例题失败,请检查例题项目是否存在!';
  1486. doc.status = 'error';
  1487. } finally {
  1488. await importLogsModel.update({ key }, doc);
  1489. }
  1490. }
  1491. }
  1492. async function updateUsedList(userId, compilation) {
  1493. await userModel.update({_id: mongoose.Types.ObjectId(userId)}, {$push: {used_list: {compilationId: compilation}}});
  1494. }
  1495. //拷贝补充定额章节树
  1496. async function copyCompleRationSection(userId, compilationId) {
  1497. await sectionTreeDao.copyDataFromTemplate(userId, compilationId);
  1498. }
  1499. //拷贝补充人材机分类树
  1500. async function copyCompleGljSection(userId, compilationId) {
  1501. // 如果已有数据则不再生成
  1502. const count = await compleGljSectionModel.count({userId, compilationId});
  1503. if (count) {
  1504. return;
  1505. }
  1506. let templateData = await compleGljSectionTModel.find({compilationId: compilationId});
  1507. if (templateData.length > 0) {
  1508. let insertDatas = [],
  1509. uuidMapping = {};
  1510. //将ID替换成UUID
  1511. for (let temData of templateData) {
  1512. uuidMapping[temData.ID] = uuidV1();
  1513. }
  1514. for(let temData of templateData) {
  1515. let insertD = {
  1516. userId: userId,
  1517. compilationId: compilationId,
  1518. Name: temData.Name,
  1519. ID: uuidMapping[temData.ID],
  1520. ParentID: uuidMapping[temData.ParentID] || -1,
  1521. NextSiblingID: uuidMapping[temData.NextSiblingID] || -1,
  1522. };
  1523. insertDatas.push(insertD);
  1524. }
  1525. //插入数据
  1526. await compleGljSectionModel.insertMany(insertDatas);
  1527. }
  1528. }
  1529. async function changeFile(datas,userID,fileID,name,from,type){//from 费率或单价文件,type从单前建设项目还是从其它建设项目中复制
  1530. let projectIDs = [],newFile = {id:fileID,name:name};//计录从其它项目中复制的文件,选中多个的时候只需复制一次
  1531. let projectUpdateType = from == "feeRateFile"?"feeRate":"unitFile";
  1532. for(let d of datas){
  1533. let tem_file = from == "feeRateFile"? await feeRate_facade.changeFeeRateFile(d, newFile,type,userID):await glj_facade.changeUnitFile(d, newFile,type,userID);
  1534. if(type == 1 && tem_file){//从建设项目复制时,只有第一次需要复制,剩下的就相当于使用同个建设项目的情况了
  1535. let newID = from == "feeRateFile"?tem_file.ID:tem_file.id;
  1536. newFile = {id:newID,name:tem_file.name};
  1537. type = 0;
  1538. }
  1539. projectIDs.push({ID:d.projectID})
  1540. }
  1541. await project_facade.markProjectsToChange(projectIDs,projectUpdateType)//项目标记为待刷新状态
  1542. }
  1543. //获取费用定额绑定的基本信息库数据
  1544. async function getBasicInfo(compilationID, fileKind = null) {
  1545. let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(compilationID)});
  1546. if (!compilation) {
  1547. return null;
  1548. }
  1549. let billValuation = compilation.bill_valuation.find(function (data) {
  1550. return data.enable;
  1551. });
  1552. if (!billValuation) {
  1553. return null;
  1554. }
  1555. let engineerings = await engineeringModel.find({valuationID: billValuation.id});
  1556. let engineering = engineerings.find(function (data) {
  1557. return data.info_lib && data.info_lib.length > 0;
  1558. });
  1559. if (!engineering || !engineering.info_lib || !engineering.info_lib[0]) {
  1560. return null;
  1561. }
  1562. let infoLib = await basicInfoModel.findOne({ID: engineering.info_lib[0].id});
  1563. //提取文件类型中需要的数据 (投标项目可能不需要招标的一些信息)
  1564. if (fileKind && infoLib && infoLib.info && infoLib.info.length) {
  1565. let strMap = {
  1566. 1: '投标', //投标
  1567. 2: '招标', //招标
  1568. 3: '控制价' //控制价
  1569. };
  1570. let needfulData = infoLib.info.filter(data => !data.fileKind || data.fileKind === strMap[fileKind]);
  1571. needfulData.forEach(nData => {
  1572. let needfulSub = nData.items.filter(sData => !sData.fileKind || sData.fileKind === strMap[fileKind]);
  1573. nData.items = needfulSub;
  1574. });
  1575. infoLib.info = needfulData;
  1576. }
  1577. return infoLib;
  1578. }
  1579. async function getProjectFeature(valuationID, engineeringName, feeName) {
  1580. let engineering = await engineeringModel.findOne({valuationID: valuationID, name: engineeringName, feeName: feeName});
  1581. if (!engineering || !engineering.feature_lib || !engineering.feature_lib[0]) {
  1582. return null;
  1583. }
  1584. let featureLib = await projectFeatureModel.findOne({ID: engineering.feature_lib[0].id});
  1585. return featureLib;
  1586. }
  1587. //根据单位工程,获取建设项目-单项工程-单位工程,不包含无单位工程的单项工程
  1588. //@param {Number}tenderID(单位工程ID) {Number}granularity(颗粒度 1:建设项目 2:单项工程 3:单位工程)
  1589. async function getProjectByGranularity(tenderID, granularity, summaryField, userID, versionName) {
  1590. const GRANULARITY = {
  1591. PROJECT: 1,
  1592. ENGINEERING: 2,
  1593. TENDER: 3
  1594. };
  1595. let theTender = await projectModel.findOne({userID: userID, ID: tenderID}).lean(); //加上session的userID,防止tenderID被篡改过
  1596. if (!theTender) {
  1597. return null;
  1598. }
  1599. let theEngineering = await projectModel.findOne({ID: theTender.ParentID}).lean();
  1600. if (!theEngineering) {
  1601. return null;
  1602. }
  1603. let constructionProject = await projectModel.findOne({ID: theEngineering.ParentID}).lean();
  1604. if (!constructionProject) {
  1605. return null;
  1606. }
  1607. let engineerings;
  1608. if (granularity === GRANULARITY.PROJECT) {
  1609. engineerings = await projectModel.find({ParentID: constructionProject.ID, $or: notDeleted}).lean();
  1610. for (let eng of engineerings) {
  1611. eng.children = await projectModel.find({ParentID: eng.ID, $or: notDeleted}).lean();
  1612. }
  1613. } else {
  1614. engineerings = [theEngineering];
  1615. if (granularity === GRANULARITY.ENGINEERING) {
  1616. theEngineering.children = await projectModel.find({ParentID: theEngineering.ID, $or: notDeleted}).lean();
  1617. } else {
  1618. theEngineering.children = [theTender];
  1619. }
  1620. }
  1621. constructionProject.children = engineerings;
  1622. //获取汇总信息
  1623. constructionProject.summaryInfo = await getSummaryInfo([constructionProject.ID], summaryField);
  1624. //获取编制软件信息: 软件公司;软件名;版本号;授权信息; base64
  1625. let product = await productModel.findOne({});
  1626. let company = product.company || '珠海纵横创新软件有限公司',
  1627. version = product.version || '';
  1628. constructionProject.softInfo = `${company};${versionName};${version};${userID}`;
  1629. return constructionProject;
  1630. }
  1631. //获取项目数据占位ID
  1632. async function getProjectPlaceholder(data) {
  1633. let rst = {};
  1634. //项目本身数据
  1635. if (data.projectCount) {
  1636. let projectCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.project, data.projectCount);
  1637. rst.project = projectCount.sequence_value - data.projectCount + 1;
  1638. }
  1639. //项目人材机数据
  1640. if (data.projectGLJCount) {
  1641. let projectGLJCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJCount);
  1642. rst.projectGLJ = projectGLJCount.sequence_value - data.projectGLJCount + 1;
  1643. }
  1644. //组成物数据
  1645. if (data.ratioCount) {
  1646. let ratioCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.mix_ratio, data.ratioCount);
  1647. rst.ratio = ratioCount.sequence_value - data.ratioCount + 1;
  1648. }
  1649. //单价文件数据
  1650. if (data.unitPriceFileCount) {
  1651. let unitPriceFileCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price_file, data.unitPriceFileCount);
  1652. rst.unitPriceFile = unitPriceFileCount.sequence_value - data.unitPriceFileCount + 1;
  1653. }
  1654. //单价数据
  1655. if (data.unitPriceCount) {
  1656. let unitPriceCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.unit_price, data.unitPriceCount);
  1657. rst.unitPrice = unitPriceCount.sequence_value - data.unitPriceCount + 1;
  1658. }
  1659. return rst;
  1660. }
  1661. /*
  1662. * 接口导入 项目详细数据都导入完成了,再生成项目数据(项目管理界面数据)
  1663. * */
  1664. async function importProject(importObj, userID, compilationID) {
  1665. let toInsertProjects = [importObj]; //待新增项目数据
  1666. await setupProject(importObj);
  1667. //设置项目ID及相关数据
  1668. for (let curEng of importObj.engs) {
  1669. await setupProject(curEng);
  1670. toInsertProjects.push(curEng);
  1671. for (let curTender of curEng.tenders) {
  1672. await setupProject(curTender.tender);
  1673. //插入单位工程的详细数据
  1674. await importTenderDetail(curTender);
  1675. toInsertProjects.push(curTender.tender);
  1676. }
  1677. delete curEng.tenders;
  1678. }
  1679. delete importObj.engs;
  1680. //项目内部数据设置、新增完毕后,插入项目本身的数据,更新前节点数据
  1681. let bulks = [];
  1682. //如果有前节点,更新前节点
  1683. if (importObj.preID !== -1) {
  1684. bulks.push({
  1685. updateOne: {filter: {ID: importObj.preID}, update: {$set: {NextSiblingID: importObj.ID}}}
  1686. });
  1687. }
  1688. for (let insertP of toInsertProjects) {
  1689. bulks.push({
  1690. insertOne: {document: insertP}
  1691. });
  1692. }
  1693. if (bulks.length > 0) {
  1694. await projectModel.bulkWrite(bulks);
  1695. }
  1696. return importObj.ID; // 返回建设项目ID
  1697. // TODO 删除
  1698. let summaryInfo = await getSummaryInfo([importObj.ID]);
  1699. //设置汇总字段
  1700. for(let proj of toInsertProjects){
  1701. let summaryProj = summaryInfo[proj.ID];
  1702. if(summaryProj){
  1703. proj.engineeringCost = summaryProj.engineeringCost;
  1704. proj.subEngineering = summaryProj.subEngineering;
  1705. proj.measure = summaryProj.measure;
  1706. proj.safetyConstruction = summaryProj.safetyConstruction;
  1707. proj.other = summaryProj.other;
  1708. proj.charge = summaryProj.charge;
  1709. proj.tax = summaryProj.tax;
  1710. proj.rate = summaryProj.rate;
  1711. proj.buildingArea = summaryProj.buildingArea;
  1712. proj.perCost = summaryProj.perCost;
  1713. }
  1714. }
  1715. return toInsertProjects;
  1716. //给项目数据设置一些需要的数据
  1717. async function setupProject(data) {
  1718. data.userID = userID;
  1719. data.compilation = compilationID;
  1720. data.fileVer = G_FILE_VER;
  1721. data.createDateTime = new Date();
  1722. if (data.projType === 'Project') {
  1723. await setupConstruct(data);
  1724. } else if (data.projType === 'Tender') {
  1725. await setupTender(data);
  1726. }
  1727. }
  1728. //给建设项目设置一些数据
  1729. async function setupConstruct(data) {
  1730. //更新基本信息, 按照key匹配
  1731. let infoLib = await getBasicInfo(data.compilation, data.property.fileKind);
  1732. if (infoLib) {
  1733. //标准基本信息库的数据打平
  1734. let flatDatas = [];
  1735. infoLib.info.forEach(ifData => flatDatas.push(...ifData.items));
  1736. data.basicInformation.forEach(importI => {
  1737. flatDatas.forEach(item => {
  1738. if (item.key === 'engineeringName') {
  1739. item.value = data.name;
  1740. } else if (item.key === 'fileKind') {
  1741. item.value = {'1': '投标', '2': '招标'}[data.property.fileKind]
  1742. } else if (item.key === 'taxModel') {
  1743. item.value = {'1': '一般计税法', '2': '简易计税法'}[data.property.taxType]
  1744. }
  1745. if (item.key === importI.key) {
  1746. item.value = importI.value;
  1747. }
  1748. });
  1749. });
  1750. }
  1751. data.property.basicInformation = infoLib ? infoLib.info : [];
  1752. }
  1753. //给单位工程设置一些数据
  1754. async function setupTender(data) {
  1755. if (!data.property.decimal) {
  1756. //小数位数 需要修改,所以深拷贝
  1757. data.property.decimal = JSON.parse(JSON.stringify(defaultDecimal));
  1758. // 定额工程量、人材机消耗量精度设为最大6
  1759. data.property.decimal.ration.quantity = 6;
  1760. data.property.decimal.glj.quantity = 6;
  1761. }
  1762. //清单工程量精度 需要修改,所以深拷贝
  1763. data.property.billsQuantityDecimal = JSON.parse(JSON.stringify(billsQuantityDecimal));
  1764. // 清单工程量精度默认为4
  1765. const billsQuantityDecimalValue = data.property.billsQuantityDecimalValue || 4;
  1766. data.property.billsQuantityDecimal.forEach(data => data.decimal = billsQuantityDecimalValue);
  1767. //呈现选项
  1768. data.property.displaySetting = displaySetting;
  1769. data.property.billsCalcMode = 0;
  1770. data.property.zanguCalcMode = 0;
  1771. //计算选项
  1772. data.property.calcOptions = calcOptions;
  1773. //安装增加费
  1774. if(data.property.isInstall === true || data.property.isInstall === 'true'){//判断是否安装工程
  1775. await installationFacade.copyInstallationFeeFromLib(data.ID, data.property.engineering_id);
  1776. }
  1777. //锁定清单
  1778. data.property.lockBills = true;
  1779. //工料机单价调整系数
  1780. data.property.tenderSetting = tenderSetting;
  1781. //工程特征相关更新 (配对更新+追加)
  1782. let featureLib = await getProjectFeature(data.property.valuation, data.property.engineeringName, data.property.feeStandardName);
  1783. if (featureLib) {
  1784. //把导入的数据设置到默认生成的数据中,按名称匹配 (导入项不确定,因此无法确定获取项的key)
  1785. // 只匹配第一层
  1786. const unmatched = [];
  1787. data.projectFeature.forEach(importF => {
  1788. let matchData = featureLib.feature.find(f => f.dispName === importF.dispName);
  1789. if (matchData) {
  1790. matchData.value = importF.value;
  1791. if (importF.items) {
  1792. matchData.items = importF.items;
  1793. }
  1794. } else {
  1795. unmatched.push(importF);
  1796. }
  1797. });
  1798. featureLib.feature.push(...unmatched);
  1799. //设置工程专业的值为费用标准的值..
  1800. featureLib.feature.forEach(f => {
  1801. if (f.key === 'engineering') {
  1802. f.value = data.property.feeStandardName;
  1803. }
  1804. });
  1805. }
  1806. data.property.projectFeature = featureLib ? featureLib.feature : [];
  1807. // 指标信息相关设置
  1808. await project_facade.setSEILibData(data.property);
  1809. }
  1810. }
  1811. //插入单位工程内部详细数据
  1812. async function importTenderDetail(tenderData) {
  1813. //单价文件
  1814. let upFile = {
  1815. id: tenderData.tender.property.unitPriceFile.id,
  1816. name: tenderData.tender.name,
  1817. project_id: tenderData.tender.ID,
  1818. user_id: tenderData.tender.userID,
  1819. root_project_id: tenderData.tender.property.rootProjectID
  1820. };
  1821. await unitPriceFileModel.create(upFile);
  1822. //费率文件
  1823. let feeRateFileID = await feeRate_facade.newFeeRateFile(tenderData.tender.userID, tenderData.tender);
  1824. tenderData.tender.property.feeFile = feeRateFileID ? feeRateFileID : -1;
  1825. //人工系数文件
  1826. let lcFile = await labourCoeFacade.newProjectLabourCoe(tenderData.tender);
  1827. tenderData.tender.property.labourCoeFile = lcFile ? lcFile : null;
  1828. let cpFile = await calcProgramFacade.newProjectCalcProgramFile(tenderData.tender);
  1829. tenderData.tender.property.calcProgramFile = cpFile ? cpFile : null;
  1830. //列设置
  1831. let engineeringModel = new EngineeringLibModel();
  1832. let engineering = await engineeringModel.getEngineering(tenderData.tender.property.engineering_id);
  1833. let mainTreeCol = await mainColLibModel.findOne({ID: tenderData.tender.property.colLibID});
  1834. await projectSettingModel.create({projectID: tenderData.tender.ID, main_tree_col: mainTreeCol.main_tree_col, glj_col: engineering.glj_col});
  1835. //清单
  1836. if (tenderData.bills.length) {
  1837. await billsModel.insertMany(tenderData.bills);
  1838. }
  1839. // 工程量明细
  1840. if (tenderData.quantityDetails && tenderData.quantityDetails.length) {
  1841. await quantityDetailModel.insertMany(tenderData.quantityDetails);
  1842. }
  1843. //投标文件中,才会有下面这些数据
  1844. if (enterDetail(tenderData)) {
  1845. //匹配标准数据,更新一些标准数据
  1846. await setupStdData(tenderData);
  1847. let task = [];
  1848. //定额
  1849. if (tenderData.ration.length) {
  1850. task.push(rationModel.insertMany(tenderData.ration))
  1851. }
  1852. //定额人材机
  1853. if (tenderData.rationGLJ.length) {
  1854. task.push(rationGLJModel.insertMany(tenderData.rationGLJ));
  1855. }
  1856. //定额调整系数
  1857. if (tenderData.rationCoe.length) {
  1858. task.push(rationCoeModel.insertMany(tenderData.rationCoe));
  1859. }
  1860. //项目人材机
  1861. if (tenderData.projectGLJ.length) {
  1862. task.push(gljListModel.insertMany(tenderData.projectGLJ));
  1863. }
  1864. // 承包人材料
  1865. if (tenderData.contractorList.length) {
  1866. task.push(contractorListModel.insertMany(tenderData.contractorList));
  1867. }
  1868. // 评标材料表
  1869. if (tenderData.bidEvaluationList.length) {
  1870. task.push(bidListModel.insertMany(tenderData.bidEvaluationList));
  1871. }
  1872. // 暂估价材料表
  1873. if (tenderData.evaluationList.length) {
  1874. task.push(evaluateListModel.insertMany(tenderData.evaluationList));
  1875. }
  1876. //组成物
  1877. if (tenderData.mixRatio.length) {
  1878. task.push(mixRatioModel.insertMany(tenderData.mixRatio));
  1879. }
  1880. //单价文件
  1881. if (tenderData.unitPrice.length) {
  1882. task.push(unitPriceModel.insertMany(tenderData.unitPrice));
  1883. }
  1884. await Promise.all(task);
  1885. }
  1886. //继续处理定额等数据
  1887. function enterDetail(tenderData) {
  1888. return tenderData.ration.length ||
  1889. tenderData.rationGLJ.length ||
  1890. tenderData.projectGLJ.length ||
  1891. tenderData.mixRatio.length ||
  1892. tenderData.unitPrice.length;
  1893. }
  1894. }
  1895. //匹配标准数据,需要匹配标准定额,更新导入的定额人材机的定额消耗量等数据
  1896. async function setupStdData(tenderData) {
  1897. //获取标准定额数据 (定额子目的编码查找)
  1898. let matchRationCodes = [...new Set(tenderData.ration.map(ration => ration.code))];
  1899. if (!matchRationCodes.length) {
  1900. return;
  1901. }
  1902. //限制在当前费用定额可用的定额库里查找
  1903. let stdRations = await stdRationItemModel.find({code: {$in: matchRationCodes}, rationRepId: {$in: tenderData.tender.rationLibIDs}},
  1904. '-_id -rationAssList -rationCoeList -rationInstList');
  1905. //标准定额code - 映射
  1906. let stdRationCodeMap = {};
  1907. stdRations.forEach(stdRation => stdRationCodeMap[stdRation.code] = stdRation);
  1908. //获取标准人材机数据 (人材机汇总的编码查找)
  1909. let matchGLJCodes = [...new Set(tenderData.projectGLJ.map(pGLJ => pGLJ.original_code))];
  1910. if (!matchGLJCodes.length) {
  1911. return;
  1912. }
  1913. //限制在当前费用定额可用的人材机库里查找
  1914. let stdGLJs = await stdGljItemModel.find({code: {$in: matchGLJCodes}, repositoryId: {$in: tenderData.tender.gljLibIDs}},
  1915. '-_id -component -priceProperty');
  1916. //标准人材机code - 映射
  1917. let stdGLJCodeMap = {};
  1918. stdGLJs.forEach(stdGLJ => stdGLJCodeMap[stdGLJ.code] = stdGLJ);
  1919. //更新定额数据
  1920. tenderData.ration.forEach(r => {
  1921. let stdRation = stdRationCodeMap[r.code];
  1922. if (stdRation) {
  1923. r.caption = stdRation.caption;
  1924. r.from = 'std';
  1925. r.libID = stdRation.rationRepId;
  1926. r.stdID = stdRation.ID;
  1927. r.prefix = stdRation.rationRepId == tenderData.tender.defaultRationLib ? '' : '借';
  1928. r.content = stdRation.jobContent;
  1929. r.manageFeeRate = stdRation.manageFeeRate;
  1930. if (stdRation.feeType) {
  1931. r.programID = stdRation.feeType;
  1932. } else {
  1933. // 是标准定额,但是该标准定额取费专业为空,取定额取费专业(后台配置项)
  1934. r.programID = tenderData.tender.property.engineering;
  1935. }
  1936. } else {
  1937. r.from = 'cpt';
  1938. r.prefix = '补';
  1939. }
  1940. });
  1941. //更新定额人材机数据
  1942. tenderData.rationGLJ.forEach(rGLJ => {
  1943. rGLJ.from = 'cpt';
  1944. //匹配定额
  1945. let stdRation = stdRationCodeMap[rGLJ.rationCode];
  1946. if (stdRation) {
  1947. //根据导入数据的定额人材机编码匹配人材机
  1948. let stdGLJ = stdGLJCodeMap[rGLJ.original_code];
  1949. if (stdGLJ) {
  1950. rGLJ.from = 'std';
  1951. rGLJ.GLJID = stdGLJ.ID;
  1952. rGLJ.type = stdGLJ.gljType;
  1953. rGLJ.shortName = stdGLJ.shortName;
  1954. rGLJ.repositoryId = stdGLJ.repositoryId;
  1955. rGLJ.model = stdGLJ.model;
  1956. rGLJ.adjCoe = stdGLJ.adjCoe;
  1957. //找匹配到的标准定额中定额人材机的相应人材机,更新定额消耗
  1958. let stdRationGLJ = stdRation.rationGljList.find(data => data.gljId === stdGLJ.ID);
  1959. if (stdRationGLJ) {
  1960. rGLJ.rationItemQuantity = stdRationGLJ.consumeAmt;
  1961. }
  1962. }
  1963. }
  1964. });
  1965. //更新人材机汇总数据
  1966. tenderData.projectGLJ.forEach(pGLJ => {
  1967. if (!pGLJ.specs) {
  1968. pGLJ.specs = null;
  1969. }
  1970. let stdGLJ = stdGLJCodeMap[pGLJ.original_code];
  1971. if (stdGLJ) {
  1972. pGLJ.glj_id = stdGLJ.ID;
  1973. pGLJ.model = stdGLJ.model;
  1974. if (pGLJ.type !== stdGLJ.gljType) { //更新组成物connect_key
  1975. let keyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', pGLJ.type].join('|-|');
  1976. let ratios = tenderData.mixRatio.filter(ratio =>
  1977. ratio.connect_key === keyStr);
  1978. let newKeyStr = [pGLJ.code || 'null', pGLJ.name || 'null', pGLJ.specs || 'null', pGLJ.unit || 'null', stdGLJ.gljType || 'null'].join('|-|');
  1979. ratios.forEach(ratio => ratio.connect_key = newKeyStr);
  1980. }
  1981. pGLJ.type = stdGLJ.gljType; //更新类型,标准的数据类型更准确,导入的类型数据有细分识别不了
  1982. }
  1983. });
  1984. //更新单价文件数据
  1985. tenderData.unitPrice.forEach(up => {
  1986. let stdGLJ = stdGLJCodeMap[up.original_code];
  1987. if (stdGLJ) {
  1988. up.glj_id = stdGLJ.ID;
  1989. up.type = stdGLJ.gljType;
  1990. up.short_name = stdGLJ.shortName;
  1991. if (stdGLJ.taxRate) {
  1992. up.taxRate = stdGLJ.taxRate;
  1993. }
  1994. }
  1995. });
  1996. //更新组成物数据
  1997. tenderData.mixRatio.forEach(ratio => {
  1998. let stdGLJ = stdGLJCodeMap[ratio.code];
  1999. if (stdGLJ) {
  2000. ratio.glj_id = stdGLJ.ID;
  2001. ratio.type = stdGLJ.gljType;
  2002. }
  2003. });
  2004. }
  2005. async function exportProject(userID,data){//导出建设项目
  2006. if(data.type == 'main'){
  2007. return await exportMainData(userID,data.projectID);
  2008. }else {
  2009. return await exportTenderData(data);
  2010. }
  2011. }
  2012. async function exportMainData(userID,projectID) {
  2013. let result = {userID:userID,projects:[],type:'Project'};//type 备用属性,表示导出的类型,目前导出的都是整个建设项目
  2014. let tenderIDs = [];
  2015. let project = await projectModel.findOne({ID:projectID});
  2016. if(!project) throw new Error("没有找到该建设项目:"+projectID);
  2017. result['compilationID'] = project.compilation;
  2018. result['from'] = "construction";
  2019. result.projects.push(project);
  2020. let subProjects = await projectModel.find({"$or": [{'ParentID':projectID}, {"property.rootProjectID": projectID}]});
  2021. for(let s of subProjects){
  2022. if(!s.deleteInfo || !s.deleteInfo.deleted){
  2023. result.projects.push(s);
  2024. if(s.projType =="Tender") tenderIDs.push(s.ID);
  2025. }
  2026. }
  2027. let files = {unitFiles:await exportUnitFiles(projectID),feeRateFiles:await exportFeeRateFiles(projectID)};
  2028. result.files = files;
  2029. result = cipher.aesEncrypt(JSON.stringify(result));
  2030. result +="|----|" +JSON.stringify(tenderIDs);
  2031. return result;
  2032. }
  2033. async function exportUnitFiles(rootProjectID){
  2034. let unitFiles = [];
  2035. let files = await unitPriceFileModel.find({root_project_id:rootProjectID});
  2036. for(let f of files){
  2037. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  2038. let tem = {unitFile:f};
  2039. tem.unitPrices = await unitPriceModel.find({unit_price_file_id:f.id});
  2040. tem.mixRatios = await mixRatioModel.find({unit_price_file_id:f.id});
  2041. unitFiles.push(tem);
  2042. }
  2043. return unitFiles;
  2044. }
  2045. async function exportFeeRateFiles(rootProjectID) {
  2046. let feeRateFiles = [];
  2047. let files = await feeRateFileModel.find({rootProjectID:rootProjectID});
  2048. for(let f of files){
  2049. if(f.deleteInfo && f.deleteInfo.deleted == true) continue;
  2050. let tem = {feeRateFile:f};
  2051. tem.feeRate = await feeRateModel.findOne({ID:f.feeRateID});
  2052. feeRateFiles.push(tem);
  2053. }
  2054. return feeRateFiles;
  2055. }
  2056. async function exportTenderData(data){
  2057. let result = {};
  2058. let projectSetting = await projectSettingModel.findOne({"projectID": data.projectID}, '-_id');
  2059. if(projectSetting) result['projSetting'] = projectSetting;
  2060. result.bills = await billsModel.find({"projectID": data.projectID});
  2061. result.rations = await rationModel.find({'$or': [{projectID: data.projectID, deleteInfo: null}, {projectID: data.projectID, 'deleteInfo.deleted': {$in: [null, false]}}]});
  2062. result.projectGLJs = await gljListModel.find({'project_id':data.projectID});
  2063. result.installationFees = await installationFeeModel.find({projectID:data.projectID});
  2064. result.rationGLJs = await rationGLJModel.find({projectID:data.projectID});
  2065. result.rationCoes = await rationCoeModel.find({projectID:data.projectID});
  2066. result.quantityDetails = await quantityDetailModel.find({projectID:data.projectID});
  2067. result.rationInstallations = await rationInstallationModel.find({projectID:data.projectID});
  2068. result.rationTemplates = await rationTemplateModel.find({projectID:data.projectID});
  2069. result.calcProgramsFile = await calcProgramsModel.findOne({projectID:data.projectID});
  2070. result.labourCoes = await labourCoesModel.findOne({projectID:data.projectID});
  2071. result.evaluateList = await evaluateListModel.find({projectID:data.projectID}, '-_id').lean();
  2072. result.bidList = await bidListModel.find({projectID:data.projectID}, '-_id').lean();
  2073. result.contractorList = await contractorListModel.find({projectID:data.projectID}, '-_id').lean();
  2074. return cipher.aesEncrypt(JSON.stringify(result));
  2075. }
  2076. async function downLoadProjectFile(info) {
  2077. let result = {error:0};
  2078. let bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  2079. let publicBucketDomain = qiniu_config.Domain;// "http://serverupdate.smartcost.com.cn";//这里不支持https
  2080. let deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  2081. let privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, info.key, deadline);
  2082. console.log(privateDownloadUrl);
  2083. let data = {
  2084. key:info.key,
  2085. content: '正在导入建设项目,请稍候……',
  2086. userID:info.session.sessionUser.id,
  2087. compilationID: info.session.sessionCompilation._id,
  2088. status:"start",
  2089. create_time:+new Date()
  2090. };
  2091. await importLogsModel.create(data);
  2092. doDownLoadAndImport(privateDownloadUrl,info);
  2093. return result;
  2094. }
  2095. async function doDownLoadAndImport(privateDownloadUrl,info) {
  2096. let stream = fs.createWriteStream(path.join(__dirname, "../../../tmp/"+info.key));//
  2097. request(privateDownloadUrl).pipe(stream).on("close", async function (err) {
  2098. console.log("文件[" + info.key + "]下载完毕");
  2099. let doc = {status:"finish"};
  2100. try {
  2101. let data = fs.readFileSync(stream.path,'utf-8');
  2102. let result = await importProjects(data,{session:info.session},info.updateData);
  2103. if(result.error == 1){
  2104. doc.errorMsg = result.msg;
  2105. doc.status = "error";
  2106. } else {
  2107. doc.projectID = result.constructionProjectID;
  2108. }
  2109. }catch (error){
  2110. console.log(error);
  2111. doc.errorMsg = "导入失败,请检查文件!";
  2112. doc.status = "error";
  2113. }finally {
  2114. await importLogsModel.update({key:info.key},doc);
  2115. fs.unlinkSync(stream.path);
  2116. }
  2117. });
  2118. }
  2119. async function importProcessChecking(data){
  2120. let result = {error:0};
  2121. const query = data.key ? { key: data.key } : { userID: data.userID, compilationID: data.compilationID };
  2122. let log = await importLogsModel.findOne(query);
  2123. if(log){
  2124. if(log.status == "finish"){
  2125. result.status = "complete";
  2126. await importLogsModel.remove(query);
  2127. // 获取导入的项目数据
  2128. if (log.projectID) {
  2129. const projects = await getPosterityProjects([log.projectID], true);
  2130. if (!(projects.length === 1 && projects[0].projType === projectType.tender)) { // 处理的是建设项目数据
  2131. const summaryInfo = await getSummaryInfo([log.projectID]);
  2132. setupSummaryFields(summaryInfo, projects);
  2133. }
  2134. result.data = projects;
  2135. }
  2136. }else if(log.status == "start"){
  2137. result.status = "processing";
  2138. result.content = log.content;
  2139. }else if(log.status == "error"){
  2140. result.error = 1;
  2141. result.msg = log.errorMsg;
  2142. await importLogsModel.remove(query);
  2143. }
  2144. }else {
  2145. result.status = "complete";
  2146. }
  2147. return result;
  2148. }
  2149. // 从cdn服务器下载文件,key就是文件名
  2150. async function downloadFileSync(key) {
  2151. const filePath = path.join(__dirname, '../../../tmp/', key);
  2152. const bucketManager2 = new qiniu.rs.BucketManager(mac, null);
  2153. const publicBucketDomain = qiniu_config.Domain; // "http://serverupdate.smartcost.com.cn";//这里不支持https
  2154. const deadline = parseInt(Date.now() / 1000) + 3600; // 1小时过期
  2155. const privateDownloadUrl = bucketManager2.privateDownloadUrl(publicBucketDomain, key, deadline);
  2156. const stream = fs.createWriteStream(filePath);
  2157. return new Promise((resolve, reject) => {
  2158. request(privateDownloadUrl)
  2159. .pipe(stream)
  2160. .on('close', () => {
  2161. // 读取文件返回字符串
  2162. const srcData = fs.readFileSync(stream.path,'utf-8');
  2163. resolve({
  2164. path: stream.path,
  2165. srcData: srcData
  2166. });
  2167. })
  2168. .on('error', reject);
  2169. });
  2170. }
  2171. // 导入接口
  2172. async function importInterface(key, session) {
  2173. const logData = {
  2174. key: key,
  2175. content: '正在导入接口文件,请稍候……',
  2176. userID: session.sessionUser.id,
  2177. compilationID: session.sessionCompilation._id,
  2178. status: 'start',
  2179. create_time: +new Date()
  2180. };
  2181. await importLogsModel.create(logData);
  2182. handleImportInterface(key, session);
  2183. return 'importing interface';
  2184. }
  2185. async function handleImportInterface(key, session) {
  2186. const doc = { status: 'finish' };
  2187. // 源文件内容文本
  2188. let downloadFilePath = '';
  2189. try {
  2190. const { path, srcData } = await downloadFileSync(key);
  2191. downloadFilePath = path;
  2192. if (!srcData) {
  2193. throw '无有效数据';
  2194. }
  2195. const userID = session.sessionUser.id;
  2196. const compilationID = session.sessionCompilation._id;
  2197. const importData = JSON.parse(srcData);
  2198. let tenderCount = 0;
  2199. importData.engs.forEach(eng => {
  2200. eng.tenders.forEach(() => {
  2201. tenderCount += 1;
  2202. });
  2203. });
  2204. if (await isTenderOverrun(tenderCount, session)) {
  2205. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  2206. }
  2207. const projectID = await importProject(importData, userID, compilationID);
  2208. doc.projectID = projectID;
  2209. } catch (err) {
  2210. doc.errorMsg = typeof err === 'string' ? err : '导入接口失败,请检查接口文件!';
  2211. doc.status = 'error';
  2212. } finally {
  2213. await importLogsModel.update({ key }, doc);
  2214. fs.unlinkSync(downloadFilePath);
  2215. }
  2216. }
  2217. /* async function importInterface(key, session) {
  2218. // 源文件内容文本
  2219. let downloadFilePath = '';
  2220. try {
  2221. const { path, srcData } = await downloadFileSync(key);
  2222. downloadFilePath = path;
  2223. if (!srcData) {
  2224. throw '无有效数据';
  2225. }
  2226. const userID = session.sessionUser.id;
  2227. const compilationID = session.sessionCompilation._id;
  2228. const importData = JSON.parse(srcData);
  2229. let tenderCount = 0;
  2230. importData.engs.forEach(eng => {
  2231. eng.tenders.forEach(tender => {
  2232. tenderCount += 1;
  2233. });
  2234. });
  2235. if (await isTenderOverrun(tenderCount, session)) {
  2236. throw '您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。';
  2237. }
  2238. const projectData = await importProject(importData, userID, compilationID);
  2239. return projectData;
  2240. } catch (err) {
  2241. throw err;
  2242. } finally {
  2243. fs.unlinkSync(downloadFilePath);
  2244. }
  2245. } */
  2246. async function importProjects(data,req,updateData) {
  2247. let result = {error:0};
  2248. let stringArr = data.split("|----|");
  2249. let datas = [];
  2250. for(let s of stringArr){
  2251. datas.push(JSON.parse(cipher.aesDecrypt(s)));
  2252. }
  2253. let mainData = datas.length > 0 ?datas[0]:null;
  2254. if(mainData){
  2255. if(mainData.from && mainData.from != "construction"){
  2256. result.error = 1;
  2257. result.msg = "导入失败:您要导入的文件是由“纵横公路养护云版”导出,当前软件是“大司空云计价”,请选择正确的软件再进行操作!";
  2258. }else if(mainData.compilationID != req.session.sessionCompilation._id){
  2259. const fileCompilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(mainData.compilationID)}, 'name');
  2260. const fileCompilationName = fileCompilation ? fileCompilation.name : '未知的费用定额';
  2261. const curCompilationName = req.session.sessionCompilation.name;
  2262. result.error = 1;
  2263. result.msg = `导入失败:您要导入的文件是由“${fileCompilationName}”导出,当前软件是“${curCompilationName}”,请选择正确的费用定额再进行操作!`;
  2264. }else {
  2265. const tenders = mainData.projects.filter(item => item.projType === projectType.tender);
  2266. const tenderOverrun = await isTenderOverrun(tenders.length, req.session);
  2267. if (tenderOverrun) {
  2268. result.error = 1;
  2269. result.msg = `您创建的项目个数超限,请联系我们的客服人员,或者导出建设项目保存到本地备份,删除云上数据。`;
  2270. }
  2271. let [constructionProjectID,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap] = await handleMainProjectDatas(mainData,updateData,req.session.sessionUser.id);
  2272. result.constructionProjectID = constructionProjectID;
  2273. if(datas.length > 1 ){
  2274. for(let i = 1;i<datas.length;i++){
  2275. await handleEachProject(datas[i],projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap)
  2276. }
  2277. }
  2278. }
  2279. }
  2280. return result;
  2281. }
  2282. async function handleEachProject(data,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap){
  2283. let bills = [],rations = [],projectGLJs = [],rationGLJs=[],rationCoes=[],quantityDetails=[],rationInstallations=[],rationTemplates=[],evaluateList=[],bidList=[],contractorList=[];
  2284. let newProjectSetting =null,newCalcProgramsFile = null,newLabourCoe = null;
  2285. let billsIDMap = {},projectGLJIDMap={},rationIDMap = {};
  2286. let newProjectID = projectIDMap[data.projSetting.projectID];
  2287. //生成新的清单;
  2288. if(data.bills && data.bills.length > 0){
  2289. for(let b of data.bills){
  2290. billsIDMap[b.ID] = uuidV1();
  2291. }
  2292. for(let b of data.bills){
  2293. delete b._id;
  2294. b = getCopyBillDatas(b,newProjectID,billsIDMap);
  2295. bills.push(b);
  2296. }
  2297. }
  2298. //生成项目工料机数据
  2299. if(data.projectGLJs && data.projectGLJs.length > 0){
  2300. let gljCount = await counter.counterDAO.getIDAfterCountSync(counter.moduleName.glj_list, data.projectGLJs.length);
  2301. for(let i = 0; i < data.projectGLJs.length; i++){
  2302. let d = data.projectGLJs[i];
  2303. delete d._id;
  2304. let newID = gljCount.sequence_value - (data.projectGLJs.length - 1) + i;
  2305. projectGLJIDMap[d.id] = newID;
  2306. d.project_id = newProjectID;
  2307. d.id = newID;
  2308. projectGLJs.push(d);
  2309. }
  2310. }
  2311. //生成新的定额
  2312. if(data.rations && data.rations.length > 0){
  2313. for(let r of data.rations){
  2314. rationIDMap[r.ID] = uuidV1();
  2315. }
  2316. for(let r of data.rations){
  2317. delete r._id;
  2318. r = getCopyRationData(r,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2319. rations.push(r);
  2320. }
  2321. }
  2322. //生成定额下挂的定额工料机等等数据
  2323. if(data.rationGLJs && data.rationGLJs.length > 0) rationGLJs = setRationSubList(data.rationGLJs,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2324. if(data.rationCoes && data.rationCoes.length > 0) rationCoes = setRationSubList(data.rationCoes,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2325. if(data.quantityDetails && data.quantityDetails.length > 0) quantityDetails = setRationSubList(data.quantityDetails,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2326. if(data.rationInstallations && data.rationInstallations.length > 0) rationInstallations = setRationSubList(data.rationInstallations,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2327. if(data.rationTemplates && data.rationTemplates.length > 0) rationTemplates = setRationSubList(data.rationTemplates,newProjectID,billsIDMap,rationIDMap,projectGLJIDMap);
  2328. if(data.evaluateList && data.evaluateList.length > 0) evaluateList = setMaterialList(data.evaluateList,newProjectID,projectGLJIDMap);
  2329. if(data.bidList && data.bidList.length > 0) bidList = setMaterialList(data.bidList,newProjectID,projectGLJIDMap);
  2330. if(data.contractorList && data.contractorList.length > 0) contractorList = setMaterialList(data.contractorList,newProjectID,projectGLJIDMap);
  2331. //生成projectSetting 文件
  2332. if(data.projSetting){
  2333. data.projSetting.projectID =newProjectID;
  2334. newProjectSetting = data.projSetting;
  2335. delete newProjectSetting._id;
  2336. }
  2337. //生成计算程序文件,系数文件
  2338. if(data.calcProgramsFile && calcProgramFileIDMap[data.calcProgramsFile.ID]){
  2339. data.calcProgramsFile.ID = calcProgramFileIDMap[data.calcProgramsFile.ID];
  2340. data.calcProgramsFile.projectID = newProjectID;
  2341. newCalcProgramsFile = data.calcProgramsFile;
  2342. delete newCalcProgramsFile._id;
  2343. }
  2344. if(data.labourCoes && labourCoeFileIDMap[data.labourCoes.ID]){
  2345. data.labourCoes.ID = labourCoeFileIDMap[data.labourCoes.ID];
  2346. data.labourCoes.projectID = newProjectID;
  2347. newLabourCoe = data.labourCoes;
  2348. delete newLabourCoe._id;
  2349. }
  2350. if(newProjectSetting) await projectSettingModel.create(newProjectSetting);
  2351. if(bills.length > 0) await insertMany(bills,billsModel);
  2352. if(rations.length > 0) await insertMany(rations,rationModel);
  2353. if(projectGLJs.length > 0) await insertMany(projectGLJs,gljListModel);
  2354. if(rationGLJs.length > 0) await insertMany(rationGLJs,rationGLJModel);
  2355. if(rationCoes.length > 0) await insertMany(rationCoes,rationCoeModel);
  2356. if(quantityDetails.length > 0) await insertMany(quantityDetails,quantityDetailModel);
  2357. if(rationInstallations.length > 0) await insertMany(rationInstallations,rationInstallationModel);
  2358. if(rationTemplates.length > 0) await insertMany(rationTemplates,rationTemplateModel);
  2359. if(evaluateList.length > 0) await insertMany(evaluateList,evaluateListModel);
  2360. if(bidList.length > 0) await insertMany(bidList,bidListModel);
  2361. if(contractorList.length > 0) await insertMany(contractorList,contractorListModel);
  2362. if(newCalcProgramsFile) await calcProgramsModel.create(newCalcProgramsFile);
  2363. if(newLabourCoe) await labourCoesModel.create(newLabourCoe);
  2364. }
  2365. function setMaterialList(datas,newProjectID,projectGLJIDMap){
  2366. let arrs = [];
  2367. for(let d of datas){
  2368. arrs.push(getNewMaterial(d,newProjectID,projectGLJIDMap))
  2369. }
  2370. return arrs
  2371. }
  2372. function setRationSubList(datas,newProjectID,billIDMap,rationIDMap,projectGLJIDMap) {
  2373. let arrs = [];
  2374. for(let d of datas){
  2375. delete d._id;
  2376. d = getCopyRationSubData(d,newProjectID,billIDMap,rationIDMap,projectGLJIDMap);
  2377. arrs.push(d);
  2378. }
  2379. return arrs;
  2380. }
  2381. async function handleMainProjectDatas(mainData,updateData,userID) {
  2382. let mainProjectID = -1;
  2383. let projectIDMap = {},feeRateFileIDMap={},unitPriceFileIDMap={},labourCoeFileIDMap={},calcProgramFileIDMap={};
  2384. let tasks = [];
  2385. projectIDMap[-1] = -1;//最后一个项目的nextID为-1的情况
  2386. let constructionProjectID;
  2387. //生成新的projectID
  2388. for(let p of mainData.projects){
  2389. let newProjectID = await getCounterID("projects");
  2390. projectIDMap[p.ID] = newProjectID;
  2391. if(p.projType == "Project") {
  2392. mainProjectID = newProjectID;
  2393. constructionProjectID = newProjectID;
  2394. }
  2395. if(p.projType == "Tender"){
  2396. if(p.property.calcProgramFile) calcProgramFileIDMap[p.property.calcProgramFile.ID] = uuidV1();//新的计算程序文件ID
  2397. if(p.property.labourCoeFile) labourCoeFileIDMap[p.property.labourCoeFile.ID] = uuidV1();//新的人工调整系数文件ID
  2398. if(p.property.feeFile) feeRateFileIDMap[p.property.feeFile.id] = uuidV1();//新的费率文件ID
  2399. if(p.property.unitPriceFile) unitPriceFileIDMap[p.property.unitPriceFile.id] = await getCounterID("unit_price_file");//新的单价文件ID
  2400. }
  2401. }
  2402. if(mainProjectID == -1) throw new Error("文件里面没包含建设项目信息!");
  2403. //处理项目信息 ----- 费率文件,单价文件ID信息要重新生成----to do
  2404. for(let p of mainData.projects){
  2405. delete p._id;
  2406. delete p.__v;
  2407. p.ID = projectIDMap[p.ID];
  2408. if(p.ID == mainProjectID){//对于建设项目,要父和下一节点ID要使用前端传入的位置ID
  2409. p.ParentID = updateData.self.ParentID;
  2410. p.NextSiblingID = updateData.self.NextSiblingID;
  2411. if(updateData.update){//树节构中的上一节点的下一节点设置为本建设项目ID;
  2412. tasks.push({updateOne:{filter : updateData.update.query, update : {NextSiblingID:mainProjectID}}});
  2413. }
  2414. //查看是否重名;
  2415. let temp = await projectModel.findOne({userID:userID,ParentID:p.ParentID,name:p.name});
  2416. if(temp) p.name = p.name + '(' + moment(Date.now()).tz("Asia/Shanghai").format('MM-DD HH:mm:ss') + '导入)';
  2417. }else {
  2418. p.ParentID = projectIDMap[p.ParentID];
  2419. p.NextSiblingID = projectIDMap[p.NextSiblingID];
  2420. }
  2421. p.userID =userID;
  2422. p.shareInfo=[];
  2423. if(p.projType == "Tender"){
  2424. if(p.property.calcProgramFile) p.property.calcProgramFile.ID = calcProgramFileIDMap[p.property.calcProgramFile.ID];
  2425. if(p.property.labourCoeFile) p.property.labourCoeFile.ID = labourCoeFileIDMap[p.property.labourCoeFile.ID];
  2426. if(p.property.feeFile) p.property.feeFile.id = feeRateFileIDMap[p.property.feeFile.id];
  2427. if(p.property.unitPriceFile) p.property.unitPriceFile.id = unitPriceFileIDMap[p.property.unitPriceFile.id];
  2428. p.property.rootProjectID = mainProjectID
  2429. }
  2430. tasks.push({insertOne: {document: p}})
  2431. }
  2432. //项目树节构数据生成:
  2433. await projectModel.bulkWrite(tasks);
  2434. //生成所有的费率文件
  2435. await importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID);
  2436. //生成所有的单价文件
  2437. await importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID);
  2438. return [constructionProjectID,projectIDMap,labourCoeFileIDMap,calcProgramFileIDMap]
  2439. }
  2440. async function importUnitPriceFiles(mainData,projectIDMap,unitPriceFileIDMap,userID) {
  2441. if(!mainData.files.unitFiles) return;
  2442. let unitFiles = [],unitPrices =[],mixRatios=[],freights=[],originals=[];
  2443. for(let f of mainData.files.unitFiles){
  2444. let file = f.unitFile,prices = f.unitPrices,mixs = f.mixRatios,fres = f.freights,ors = f.originals;
  2445. //生成单价文件
  2446. delete file._id;
  2447. file.id = unitPriceFileIDMap[file.id]?unitPriceFileIDMap[file.id]:await getCounterID("unit_price_file");
  2448. file.project_id = projectIDMap[file.project_id];
  2449. file.root_project_id = projectIDMap[file.root_project_id];
  2450. file.user_id = userID;
  2451. unitFiles.push(file);
  2452. //生成子数据
  2453. if(prices) await setSubList(prices,unitPrices,file.id,unitPriceModel);
  2454. if(mixs) await setSubList(mixs,mixRatios,file.id,mixRatioModel);
  2455. }
  2456. if(unitFiles.length > 0) await insertMany(unitFiles,unitPriceFileModel);
  2457. if(unitPrices.length > 0) await insertMany(unitPrices,unitPriceModel);
  2458. if(mixRatios.length > 0) await insertMany(mixRatios,mixRatioModel);
  2459. async function setSubList(oList,nList,fileID,model,UUID=false) {
  2460. for(let o of oList){
  2461. delete o._id;
  2462. o.unit_price_file_id = fileID;
  2463. UUID == true?o.ID = uuidV1():o.id = await getCounterID(model.modelName);
  2464. nList.push(o)
  2465. }
  2466. }
  2467. }
  2468. async function importFeeRateFiles(mainData,projectIDMap,feeRateFileIDMap,userID) {
  2469. let feeRateFiles = [], feeRates = [];
  2470. if(!mainData.files.feeRateFiles) return;
  2471. for(let f of mainData.files.feeRateFiles){
  2472. //生成费率记录
  2473. let rate = f.feeRate;
  2474. delete rate._id;
  2475. rate.ID = uuidV1();
  2476. feeRates.push(rate);
  2477. //生成费率文件记录
  2478. let file = f.feeRateFile;
  2479. delete file._id;
  2480. file.ID = feeRateFileIDMap[file.ID]?feeRateFileIDMap[file.ID]:uuidV1();
  2481. file.userID = userID;
  2482. file.rootProjectID = projectIDMap[file.rootProjectID];
  2483. file.feeRateID = rate.ID;
  2484. feeRateFiles.push(file);
  2485. }
  2486. if(feeRateFiles.length > 0) await insertMany(feeRateFiles,feeRateFileModel);
  2487. if(feeRates.length > 0) await insertMany(feeRates,feeRateModel);
  2488. }
  2489. // 初始化
  2490. async function initOverHeightItems(engineeringID) {
  2491. const defaultData = [];
  2492. const engineering = await engineeringModel.findById(engineeringID);
  2493. const overHeightLibs = engineering.over_height_lib;
  2494. if (!overHeightLibs || !overHeightLibs.length) {
  2495. return defaultData;
  2496. }
  2497. const overHeightLibID = overHeightLibs[0].id;
  2498. const overHeightLib = await overHeightLibModel.findOne({ID: overHeightLibID});
  2499. return overHeightLib ? overHeightLib.list : defaultData;
  2500. }
  2501. function uploadToken() {
  2502. let options = {
  2503. scope: qiniu_config.Bucket,
  2504. deleteAfterDays: 1,
  2505. returnBody:
  2506. '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
  2507. };
  2508. let putPolicy = new qiniu.rs.PutPolicy(options);
  2509. let token = putPolicy.uploadToken(mac);
  2510. let result = {
  2511. uptoken: token,
  2512. domain: qiniu_config.Domain
  2513. }
  2514. return result
  2515. }
  2516. // 有些方法无法通过中间件就检查单位工程数量是否超限
  2517. // 需要到具体的业务代码中进行判断
  2518. // 这个方法就是具体业务代码中,需要检查单位工程数量是否超限用
  2519. async function isTenderOverrun(tenderCount, session) {
  2520. const userID = session.sessionUser.id;
  2521. const compilation = session.sessionCompilation._id;
  2522. const compilationVersion = session.compilationVersion || '免费';
  2523. let systemSetting = session.systemSetting || (session.systemSetting = await systemSettingMiddleware.getSystemSetting());
  2524. // 这种情况只有在刚上线此功能时会出现,不考虑时间差
  2525. if (!systemSetting) {
  2526. return false;
  2527. }
  2528. const type = compilationVersion.includes('免费') ? 'normal' : 'professional';
  2529. const limit = systemSetting[type].project;
  2530. const curTenderCount = await projectModel.count({userID, compilation, projType: 'Tender', '$or':[{deleteInfo: null}, {'deleteInfo.completeDeleted': false}]});
  2531. return tenderCount + curTenderCount > limit;
  2532. }
  2533. async function getWelcomeInfo(compilationId,sessionUser,isFree=true) {
  2534. let welcom_setting = await welcomeModel.findOne({compilationId:compilationId});
  2535. let isShow = false;
  2536. let context = "";
  2537. let setting = null
  2538. if(welcom_setting){
  2539. setting = isFree? welcom_setting.normal:welcom_setting.professional;//区分专业版和免费版
  2540. }
  2541. if(setting){
  2542. if(setting.showType == 0) return [false,""];//关闭
  2543. context = setting.context;
  2544. if(setting.showType == 1){//每天一次
  2545. let dataString =moment(Date.now()).tz("Asia/Shanghai").format('YYYY-MM-DD');//今天的日期字符串
  2546. let userInfo =await userModel.findOne({_id: mongoose.Types.ObjectId(sessionUser.id)});
  2547. if (dataString != userInfo.welcomeShowTime){//今天没登录过
  2548. isShow = true;
  2549. await userModel.update({_id: mongoose.Types.ObjectId(sessionUser.id)},{welcomeShowTime:dataString})
  2550. }
  2551. }else if(setting.showType == 2){//每次登录显示
  2552. isShow = sessionUser.newLogin?true:false;
  2553. sessionUser.newLogin = false
  2554. }
  2555. }
  2556. return [isShow,context]
  2557. }