pm_facade.js 132 KB

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