pm_facade.js 120 KB

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