pm_facade.js 115 KB

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