pm_facade.js 134 KB

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