statResult.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961
  1. /**
  2. * @class StatResult 基础数据结果统计模型
  3. */
  4. const BaseMod = require('./base')
  5. const Platform = require('./platform')
  6. const Channel = require('./channel')
  7. const Version = require('./version')
  8. const SessionLog = require('./sessionLog')
  9. const UserSessionLog = require('./userSessionLog')
  10. const ErrorLog = require('./errorLog')
  11. const ActiveDevices = require('./activeDevices')
  12. const ActiveUsers = require('./activeUsers')
  13. const UniIDUsers = require('./uniIDUsers')
  14. const {
  15. DateTime
  16. } = require('../lib')
  17. module.exports = class StatResult extends BaseMod {
  18. constructor() {
  19. super()
  20. this.tableName = 'result'
  21. this.platforms = []
  22. this.channels = []
  23. this.versions = []
  24. }
  25. /**
  26. * 基础数据统计
  27. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  28. * @param {Date|Time} date 指定日期或时间戳
  29. * @param {Boolean} reset 是否重置,为ture时会重置该批次数据
  30. */
  31. async stat(type, date, reset) {
  32. const allowedType = ['hour', 'day', 'week', 'month']
  33. if (!allowedType.includes(type)) {
  34. return {
  35. code: 1002,
  36. msg: 'This type is not allowed'
  37. }
  38. }
  39. if (this.debug) {
  40. console.log('result --type:' + type + ', date:' + date + ', reset:' + reset)
  41. }
  42. this.fillType = type
  43. const dateTime = new DateTime()
  44. const dateDimension = dateTime.getTimeDimensionByType(type, -1, date)
  45. this.startTime = dateDimension.startTime
  46. this.endTime = dateDimension.endTime
  47. if (this.debug) {
  48. console.log('dimension time', this.startTime + '--' + this.endTime)
  49. }
  50. // 查看当前时间段日志是否已存在,防止重复生成
  51. if (!reset) {
  52. const checkRes = await this.getCollection(this.tableName).where({
  53. dimension: this.fillType,
  54. start_time: this.startTime,
  55. end_time: this.endTime
  56. }).get()
  57. if (checkRes.data.length > 0) {
  58. console.log('log have existed')
  59. return {
  60. code: 1003,
  61. msg: 'This log have existed'
  62. }
  63. }
  64. } else {
  65. const delRes = await this.delete(this.tableName, {
  66. start_time: this.startTime,
  67. end_time: this.endTime
  68. })
  69. console.log('delete old data result:', JSON.stringify(delRes))
  70. }
  71. // 周月数据单独统计
  72. if (['week', 'month'].includes(this.fillType)) {
  73. return await this.statWeekOrMonth()
  74. }
  75. // 数据获取
  76. this.sessionLog = new SessionLog()
  77. const statRes = await this.aggregate(this.sessionLog.tableName, {
  78. project: {
  79. appid: 1,
  80. version: 1,
  81. platform: 1,
  82. channel: 1,
  83. is_first_visit: 1,
  84. page_count: 1,
  85. duration: 1,
  86. create_time: 1
  87. },
  88. match: {
  89. create_time: {
  90. $gte: this.startTime,
  91. $lte: this.endTime
  92. }
  93. },
  94. group: {
  95. _id: {
  96. appid: '$appid',
  97. version: '$version',
  98. platform: '$platform',
  99. channel: '$channel'
  100. },
  101. new_device_count: {
  102. $sum: '$is_first_visit'
  103. },
  104. page_view_count: {
  105. $sum: '$page_count'
  106. },
  107. total_duration: {
  108. $sum: '$duration'
  109. },
  110. session_times: {
  111. $sum: 1
  112. }
  113. },
  114. sort: {
  115. new_device_count: 1,
  116. page_view_count: 1,
  117. session_times: 1
  118. },
  119. getAll: true
  120. })
  121. let res = {
  122. code: 0,
  123. msg: 'success'
  124. }
  125. if (this.debug) {
  126. console.log('statRes', JSON.stringify(statRes))
  127. }
  128. this.fillData = []
  129. this.composes = []
  130. if (statRes.data.length > 0) {
  131. for (const i in statRes.data) {
  132. await this.fill(statRes.data[i])
  133. }
  134. }
  135. //补充数据
  136. await this.replenishStat()
  137. if (this.fillData.length > 0) {
  138. res = await this.batchInsert(this.tableName, this.fillData)
  139. }
  140. return res
  141. }
  142. /**
  143. * 按周/月统计
  144. */
  145. async statWeekOrMonth() {
  146. const statRes = await this.aggregate(this.tableName, {
  147. project: {
  148. appid: 1,
  149. version_id: 1,
  150. platform_id: 1,
  151. channel_id: 1,
  152. new_device_count: 1,
  153. new_user_count: 1,
  154. page_visit_count: 1,
  155. user_visit_times: 1,
  156. app_launch_count: 1,
  157. error_count: 1,
  158. bounce_times: 1,
  159. duration: 1,
  160. user_duration: 1,
  161. dimension: 1,
  162. start_time: 1
  163. },
  164. match: {
  165. dimension: 'day',
  166. start_time: {
  167. $gte: this.startTime,
  168. $lte: this.endTime
  169. }
  170. },
  171. group: {
  172. _id: {
  173. appid: '$appid',
  174. version_id: '$version_id',
  175. platform_id: '$platform_id',
  176. channel_id: '$channel_id'
  177. },
  178. new_device_count: {
  179. $sum: '$new_device_count'
  180. },
  181. new_user_count: {
  182. $sum: '$new_user_count'
  183. },
  184. error_count: {
  185. $sum: '$error_count'
  186. },
  187. page_count: {
  188. $sum: '$page_visit_count'
  189. },
  190. total_duration: {
  191. $sum: '$duration'
  192. },
  193. total_user_duration: {
  194. $sum: '$user_duration'
  195. },
  196. total_user_session_times: {
  197. $sum: '$user_session_times'
  198. },
  199. session_times: {
  200. $sum: '$app_launch_count'
  201. },
  202. total_bounce_times: {
  203. $sum: '$bounce_times'
  204. }
  205. },
  206. sort: {
  207. new_device_count: 1,
  208. error_count: 1,
  209. page_count: 1
  210. },
  211. getAll: true
  212. })
  213. let res = {
  214. code: 0,
  215. msg: 'success'
  216. }
  217. if (this.debug) {
  218. console.log('statRes', JSON.stringify(statRes))
  219. }
  220. this.activeDevices = new ActiveDevices()
  221. this.activeUsers = new ActiveUsers()
  222. this.fillData = []
  223. this.composes = []
  224. if (statRes.data.length > 0) {
  225. for (const i in statRes.data) {
  226. await this.getWeekOrMonthData(statRes.data[i])
  227. }
  228. }
  229. //补充数据
  230. await this.replenishStat()
  231. if (this.fillData.length > 0) {
  232. res = await this.batchInsert(this.tableName, this.fillData)
  233. }
  234. return res
  235. }
  236. /**
  237. * 获取周/月维度的填充数据
  238. * @param {Object} data 统计数据
  239. */
  240. async getWeekOrMonthData(data) {
  241. const matchCondition = {
  242. ...data._id,
  243. create_time: {
  244. $gte: this.startTime,
  245. $lte: this.endTime
  246. }
  247. }
  248. // 查询活跃设备数
  249. const statVisitDeviceRes = await this.getCollection(this.activeDevices.tableName).where({
  250. ...matchCondition,
  251. dimension: this.fillType
  252. }).count()
  253. let activeDeviceCount = 0
  254. if (statVisitDeviceRes && statVisitDeviceRes.total > 0) {
  255. activeDeviceCount = statVisitDeviceRes.total
  256. }
  257. // 设备次均停留时长
  258. let avgSessionTime = 0
  259. if (data.total_duration > 0 && data.session_times > 0) {
  260. avgSessionTime = Math.round(data.total_duration / data.session_times)
  261. }
  262. // 设均停留时长
  263. let avgDeviceTime = 0
  264. if (data.total_duration > 0 && activeDeviceCount > 0) {
  265. avgDeviceTime = Math.round(data.total_duration / activeDeviceCount)
  266. }
  267. // 跳出率
  268. let bounceRate = 0
  269. if (data.total_bounce_times > 0 && data.session_times > 0) {
  270. bounceRate = data.total_bounce_times * 100 / data.session_times
  271. bounceRate = parseFloat(bounceRate.toFixed(2))
  272. }
  273. // 累计设备数
  274. let totalDevices = data.new_device_count
  275. const totalDeviceRes = await this.getCollection(this.tableName).where({
  276. ...matchCondition,
  277. dimension: this.fillType,
  278. start_time: {
  279. $lt: this.startTime
  280. }
  281. }).orderBy('start_time', 'desc').limit(1).get()
  282. if (totalDeviceRes && totalDeviceRes.data.length > 0) {
  283. totalDevices += totalDeviceRes.data[0].total_devices
  284. }
  285. //活跃用户数
  286. const statVisitUserRes = await this.getCollection(this.activeUsers.tableName).where({
  287. ...matchCondition,
  288. dimension: this.fillType
  289. }).count()
  290. let activeUserCount = 0
  291. if (statVisitUserRes && statVisitUserRes.total > 0) {
  292. activeUserCount = statVisitUserRes.total
  293. }
  294. // 平台信息
  295. let platformInfo = null
  296. if (this.platforms && this.platforms[data._id.platform_id]) {
  297. platformInfo = this.platforms[data._id.platform_id]
  298. } else {
  299. const platform = new Platform()
  300. platformInfo = await this.getById(platform.tableName, data._id.platform_id)
  301. if (!platformInfo || platformInfo.length === 0) {
  302. platformInfo.code = ''
  303. }
  304. this.platforms[data._id.platform_id] = platformInfo
  305. }
  306. // 渠道信息
  307. let channelInfo = null
  308. if (this.channels && this.channels[data._id.channel_id]) {
  309. channelInfo = this.channels[data._id.channel_id]
  310. } else {
  311. const channel = new Channel()
  312. channelInfo = await this.getById(channel.tableName, data._id.channel_id)
  313. if (!channelInfo || channelInfo.length === 0) {
  314. channelInfo.channel_code = ''
  315. }
  316. this.channels[data._id.channel_id] = channelInfo
  317. }
  318. // 版本信息
  319. let versionInfo = null
  320. if (this.versions && this.versions[data._id.version_id]) {
  321. versionInfo = this.versions[data._id.version_id]
  322. } else {
  323. const version = new Version()
  324. versionInfo = await this.getById(version.tableName, data._id.version_id, false)
  325. if (!versionInfo || versionInfo.length === 0) {
  326. versionInfo.version = ''
  327. }
  328. this.versions[data._id.version_id] = versionInfo
  329. }
  330. //总用户数
  331. const uniIDUsers = new UniIDUsers()
  332. let totalUserCount = await uniIDUsers.getUserCount(data._id.appid, platformInfo.code, channelInfo.channel_code, versionInfo.version, {
  333. $lte: this.endTime
  334. })
  335. //人均停留时长
  336. let avgUserTime = 0
  337. if (data.total_user_duration > 0 && activeUserCount > 0) {
  338. avgUserTime = Math.round(data.total_user_duration / activeUserCount)
  339. }
  340. //用户次均访问时长
  341. let avgUserSessionTime = 0
  342. if (data.total_user_duration > 0 && data.total_user_session_times > 0) {
  343. avgUserSessionTime = Math.round(data.total_user_duration / data.total_user_session_times)
  344. }
  345. const insertParam = {
  346. appid: data._id.appid,
  347. platform_id: data._id.platform_id,
  348. channel_id: data._id.channel_id,
  349. version_id: data._id.version_id,
  350. //总设备数
  351. total_devices: totalDevices,
  352. //本时间段新增设备数
  353. new_device_count: data.new_device_count,
  354. //登录用户会话次数
  355. user_session_times: data.total_user_session_times,
  356. //活跃设备数
  357. active_device_count: activeDeviceCount,
  358. //总用户数
  359. total_users: totalUserCount,
  360. //新增用户数
  361. new_user_count: data.new_user_count,
  362. //活跃用户数
  363. active_user_count: activeUserCount,
  364. //应用启动次数 = 设备会话次数
  365. app_launch_count: data.session_times,
  366. //页面访问次数
  367. page_visit_count: data.page_view_count,
  368. //错误次数
  369. error_count: data.error_count,
  370. //会话总访问时长
  371. duration: data.total_duration,
  372. //用户会话总访问时长
  373. user_duration: data.total_user_duration,
  374. avg_device_session_time: avgSessionTime,
  375. avg_user_session_time: avgUserSessionTime,
  376. avg_device_time: avgDeviceTime,
  377. avg_user_time: avgUserTime,
  378. bounce_times: data.total_bounce_times,
  379. bounce_rate: bounceRate,
  380. retention: {},
  381. dimension: this.fillType,
  382. stat_date: new DateTime().getDate('Ymd', this.startTime),
  383. start_time: this.startTime,
  384. end_time: this.endTime
  385. }
  386. this.fillData.push(insertParam)
  387. this.composes.push(data._id.appid + '_' + data._id.platform_id + '_' + data._id.channel_id + '_' + data
  388. ._id.version_id)
  389. return insertParam
  390. }
  391. /**
  392. * 基础填充数据-目前只有小时和天维度的数据
  393. * @param {Object} data 统计数据
  394. */
  395. async fill(data) {
  396. // 平台信息
  397. let platformInfo = null
  398. if (this.platforms && this.platforms[data._id.platform]) {
  399. //暂存下数据,减少读库
  400. platformInfo = this.platforms[data._id.platform]
  401. } else {
  402. const platform = new Platform()
  403. platformInfo = await platform.getPlatformAndCreate(data._id.platform, null)
  404. if (!platformInfo || platformInfo.length === 0) {
  405. platformInfo._id = ''
  406. }
  407. this.platforms[data._id.platform] = platformInfo
  408. if (this.debug) {
  409. console.log('platformInfo', JSON.stringify(platformInfo))
  410. }
  411. }
  412. // 渠道信息
  413. let channelInfo = null
  414. const channelKey = data._id.appid + '_' + platformInfo._id + '_' + data._id.channel
  415. if (this.channels && this.channels[channelKey]) {
  416. channelInfo = this.channels[channelKey]
  417. } else {
  418. const channel = new Channel()
  419. channelInfo = await channel.getChannelAndCreate(data._id.appid, platformInfo._id, data._id.channel)
  420. if (!channelInfo || channelInfo.length === 0) {
  421. channelInfo._id = ''
  422. }
  423. this.channels[channelKey] = channelInfo
  424. if (this.debug) {
  425. console.log('channelInfo', JSON.stringify(channelInfo))
  426. }
  427. }
  428. // 版本信息
  429. let versionInfo = null
  430. const versionKey = data._id.appid + '_' + data._id.platform + '_' + data._id.version
  431. if (this.versions && this.versions[versionKey]) {
  432. versionInfo = this.versions[versionKey]
  433. } else {
  434. const version = new Version()
  435. versionInfo = await version.getVersionAndCreate(data._id.appid, data._id.platform, data._id.version)
  436. if (!versionInfo || versionInfo.length === 0) {
  437. versionInfo._id = ''
  438. }
  439. this.versions[versionKey] = versionInfo
  440. if (this.debug) {
  441. console.log('versionInfo', JSON.stringify(versionInfo))
  442. }
  443. }
  444. // 访问设备数统计
  445. const matchCondition = data._id
  446. Object.assign(matchCondition, {
  447. create_time: {
  448. $gte: this.startTime,
  449. $lte: this.endTime
  450. }
  451. })
  452. const statVisitDeviceRes = await this.aggregate(this.sessionLog.tableName, {
  453. project: {
  454. appid: 1,
  455. version: 1,
  456. platform: 1,
  457. channel: 1,
  458. device_id: 1,
  459. create_time: 1
  460. },
  461. match: matchCondition,
  462. group: [{
  463. _id: {
  464. device_id: '$device_id'
  465. }
  466. }, {
  467. _id: {},
  468. total_devices: {
  469. $sum: 1
  470. }
  471. }]
  472. })
  473. let activeDeviceCount = 0
  474. if (statVisitDeviceRes.data.length > 0) {
  475. activeDeviceCount = statVisitDeviceRes.data[0].total_devices
  476. }
  477. // 错误数量统计
  478. const errorLog = new ErrorLog()
  479. const statErrorRes = await this.getCollection(errorLog.tableName).where(matchCondition).count()
  480. let errorCount = 0
  481. if (statErrorRes && statErrorRes.total > 0) {
  482. errorCount = statErrorRes.total
  483. }
  484. // 设备的次均停留时长,设备访问总时长/设备会话次数
  485. let avgSessionTime = 0
  486. if (data.total_duration > 0 && data.session_times > 0) {
  487. avgSessionTime = Math.round(data.total_duration / data.session_times)
  488. }
  489. // 设均停留时长
  490. let avgDeviceTime = 0
  491. if (data.total_duration > 0 && activeDeviceCount > 0) {
  492. avgDeviceTime = Math.round(data.total_duration / activeDeviceCount)
  493. }
  494. // 跳出率
  495. let bounceTimes = 0
  496. const bounceRes = await this.getCollection(this.sessionLog.tableName).where({
  497. ...matchCondition,
  498. page_count: 1
  499. }).count()
  500. if (bounceRes && bounceRes.total > 0) {
  501. bounceTimes = bounceRes.total
  502. }
  503. let bounceRate = 0
  504. if (bounceTimes > 0 && data.session_times > 0) {
  505. bounceRate = bounceTimes * 100 / data.session_times
  506. bounceRate = parseFloat(bounceRate.toFixed(2))
  507. }
  508. // 应用启动次数 = 会话次数
  509. const launchCount = data.session_times
  510. // 累计设备数
  511. let totalDevices = data.new_device_count
  512. const totalDeviceRes = await this.getCollection(this.tableName).where({
  513. appid: data._id.appid,
  514. platform_id: platformInfo._id,
  515. channel_id: channelInfo._id,
  516. version_id: versionInfo._id,
  517. dimension: this.fillType,
  518. start_time: {
  519. $lt: this.startTime
  520. }
  521. }).orderBy('start_time', 'desc').limit(1).get()
  522. if (totalDeviceRes && totalDeviceRes.data.length > 0) {
  523. totalDevices += totalDeviceRes.data[0].total_devices
  524. }
  525. //活跃用户数
  526. const userSessionLog = new UserSessionLog()
  527. let activeUserCount = 0
  528. const activeUserCountRes = await this.aggregate(userSessionLog.tableName, {
  529. project: {
  530. appid: 1,
  531. version: 1,
  532. platform: 1,
  533. channel: 1,
  534. uid: 1,
  535. create_time: 1
  536. },
  537. match: matchCondition,
  538. group: [{
  539. _id: {
  540. uid: '$uid'
  541. }
  542. }, {
  543. _id: {},
  544. total_users: {
  545. $sum: 1
  546. }
  547. }]
  548. })
  549. if (activeUserCountRes && activeUserCountRes.data.length > 0) {
  550. activeUserCount = activeUserCountRes.data[0].total_users
  551. }
  552. //新增用户数
  553. const uniIDUsers = new UniIDUsers()
  554. let newUserCount = await uniIDUsers.getUserCount(matchCondition.appid, matchCondition.platform,
  555. matchCondition.channel, matchCondition.version, {
  556. $gte: this.startTime,
  557. $lte: this.endTime
  558. })
  559. //总用户数
  560. let totalUserCount = await uniIDUsers.getUserCount(matchCondition.appid, matchCondition.platform,
  561. matchCondition.channel, matchCondition.version, {
  562. $lte: this.endTime
  563. })
  564. //用户停留总时长及总会话次数
  565. let totalUserDuration = 0
  566. let totalUserSessionTimes = 0
  567. const totalUserDurationRes = await this.aggregate(userSessionLog.tableName, {
  568. project: {
  569. appid: 1,
  570. version: 1,
  571. platform: 1,
  572. channel: 1,
  573. duration: 1,
  574. create_time: 1
  575. },
  576. match: matchCondition,
  577. group: [{
  578. _id: {},
  579. total_duration: {
  580. $sum: "$duration"
  581. },
  582. total_session_times: {
  583. $sum: 1
  584. }
  585. }]
  586. })
  587. if (totalUserDurationRes && totalUserDurationRes.data.length > 0) {
  588. totalUserDuration = totalUserDurationRes.data[0].total_duration
  589. totalUserSessionTimes = totalUserDurationRes.data[0].total_session_times
  590. }
  591. //人均停留时长
  592. let avgUserTime = 0
  593. //用户次均访问时长
  594. let avgUserSessionTime = 0
  595. if (totalUserDuration > 0 && activeUserCount > 0) {
  596. avgUserTime = Math.round(totalUserDuration / activeUserCount)
  597. avgUserSessionTime = Math.round(totalUserDuration / totalUserSessionTimes)
  598. }
  599. //设置填充数据
  600. const datetime = new DateTime()
  601. const insertParam = {
  602. appid: data._id.appid,
  603. platform_id: platformInfo._id,
  604. channel_id: channelInfo._id,
  605. version_id: versionInfo._id,
  606. total_devices: totalDevices,
  607. new_device_count: data.new_device_count,
  608. active_device_count: activeDeviceCount,
  609. total_users: totalUserCount,
  610. new_user_count: newUserCount,
  611. active_user_count: activeUserCount,
  612. user_session_times: totalUserSessionTimes,
  613. app_launch_count: launchCount,
  614. page_visit_count: data.page_view_count,
  615. error_count: errorCount,
  616. duration: data.total_duration,
  617. user_duration: totalUserDuration,
  618. avg_device_session_time: avgSessionTime,
  619. avg_user_session_time: avgUserSessionTime,
  620. avg_device_time: avgDeviceTime,
  621. avg_user_time: avgUserTime,
  622. bounce_times: bounceTimes,
  623. bounce_rate: bounceRate,
  624. retention: {},
  625. dimension: this.fillType,
  626. stat_date: datetime.getDate('Ymd', this.startTime),
  627. start_time: this.startTime,
  628. end_time: this.endTime
  629. }
  630. //数据填充
  631. this.fillData.push(insertParam)
  632. this.composes.push(data._id.appid + '_' + platformInfo._id + '_' + channelInfo._id + '_' + versionInfo
  633. ._id)
  634. return insertParam
  635. }
  636. /**
  637. * 基础统计数据补充,防止累计数据丢失
  638. */
  639. async replenishStat() {
  640. if (this.debug) {
  641. console.log('composes data', this.composes)
  642. }
  643. const datetime = new DateTime()
  644. // const {
  645. // startTime
  646. // } = datetime.getTimeDimensionByType(this.fillType, -1, this.startTime)
  647. //上一次统计时间
  648. let preStatRes = await this.getCollection(this.tableName).where({
  649. start_time: {$lt: this.startTime},
  650. dimension: this.fillType
  651. }).orderBy('start_time', 'desc').limit(1).get()
  652. let preStartTime = 0
  653. if(preStatRes && preStatRes.data.length > 0) {
  654. preStartTime = preStatRes.data[0].start_time
  655. }
  656. if (this.debug) {
  657. console.log('replenishStat-preStartTime', preStartTime)
  658. }
  659. if(!preStartTime) {
  660. return false
  661. }
  662. // 上一阶段数据
  663. const preStatData = await this.selectAll(this.tableName, {
  664. start_time: preStartTime,
  665. dimension: this.fillType
  666. }, {
  667. appid: 1,
  668. platform_id: 1,
  669. channel_id: 1,
  670. version_id: 1,
  671. total_devices: 1,
  672. total_users: 1
  673. })
  674. if (!preStatData || preStatData.data.length === 0) {
  675. return false
  676. }
  677. if (this.debug) {
  678. console.log('preStatData', JSON.stringify(preStatData))
  679. }
  680. let preKey
  681. const preKeyArr = []
  682. for (const pi in preStatData.data) {
  683. preKey = preStatData.data[pi].appid + '_' + preStatData.data[pi].platform_id + '_' + preStatData
  684. .data[pi].channel_id + '_' + preStatData.data[pi].version_id
  685. if (!this.composes.includes(preKey) && !preKeyArr.includes(preKey)) {
  686. preKeyArr.push(preKey)
  687. if (this.debug) {
  688. console.log('preKey -add', preKey)
  689. }
  690. this.fillData.push({
  691. appid: preStatData.data[pi].appid,
  692. platform_id: preStatData.data[pi].platform_id,
  693. channel_id: preStatData.data[pi].channel_id,
  694. version_id: preStatData.data[pi].version_id,
  695. total_devices: preStatData.data[pi].total_devices,
  696. new_device_count: 0,
  697. active_device_count: 0,
  698. total_users: preStatData.data[pi].total_users,
  699. new_user_count: 0,
  700. active_user_count: 0,
  701. user_session_times: 0,
  702. app_launch_count: 0,
  703. page_visit_count: 0,
  704. error_count: 0,
  705. duration: 0,
  706. user_duration: 0,
  707. avg_device_session_time: 0,
  708. avg_user_session_time: 0,
  709. avg_device_time: 0,
  710. avg_user_time: 0,
  711. bounce_times: 0,
  712. bounce_rate: 0,
  713. retention: {},
  714. dimension: this.fillType,
  715. stat_date: datetime.getDate('Ymd', this.startTime),
  716. start_time: this.startTime,
  717. end_time: this.endTime
  718. })
  719. } else if (this.debug) {
  720. console.log('preKey -have', preKey)
  721. }
  722. }
  723. return true
  724. }
  725. /**
  726. * 留存数据统计
  727. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  728. * @param {Date|Time} date 指定日期或时间戳
  729. * @param {String} mod 统计模块 device:设备,user:用户
  730. */
  731. async retentionStat(type, date, mod = 'device') {
  732. date = date ? date : new DateTime().getTimeBySetDays(-1, date)
  733. const allowedType = ['day', 'week', 'month']
  734. if (!allowedType.includes(type)) {
  735. return {
  736. code: 1002,
  737. msg: 'This type is not allowed'
  738. }
  739. }
  740. let days = []
  741. switch (type) {
  742. case 'week':
  743. case 'month':
  744. days = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  745. break
  746. default:
  747. days = [1, 2, 3, 4, 5, 6, 7, 14, 30]
  748. break
  749. }
  750. let res = {
  751. code: 0,
  752. msg: 'success'
  753. }
  754. for (const day in days) {
  755. //留存统计数据库查询较为复杂,因此这里拆分为多个维度
  756. if (mod && mod === 'user') {
  757. //用户留存统计
  758. if (type === 'day') {
  759. res = await this.userRetentionFillDayly(type, days[day], date)
  760. } else {
  761. res = await this.userRetentionFillWeekOrMonth(type, days[day], date)
  762. }
  763. } else {
  764. //设备留存统计
  765. if (type === 'day') {
  766. res = await this.deviceRetentionFillDayly(type, days[day], date)
  767. } else {
  768. res = await this.deviceRetentionFillWeekOrMonth(type, days[day], date)
  769. }
  770. }
  771. }
  772. return res
  773. }
  774. /**
  775. * 设备日留存统计数据填充
  776. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  777. * @param {Date|Time} date 指定日期或时间戳
  778. * @param {Boolean} reset 是否重置,为ture时会重置该批次数据
  779. */
  780. async deviceRetentionFillDayly(type, day, date) {
  781. if (type !== 'day') {
  782. return {
  783. code: 301,
  784. msg: 'Type error:' + type
  785. }
  786. }
  787. const dateTime = new DateTime()
  788. const {
  789. startTime,
  790. endTime
  791. } = dateTime.getTimeDimensionByType(type, 0 - day, date)
  792. if (!startTime || !endTime) {
  793. return {
  794. code: 1001,
  795. msg: 'The statistic time get failed'
  796. }
  797. }
  798. // 截止时间范围
  799. const lastTimeInfo = dateTime.getTimeDimensionByType(type, 0, date)
  800. // 获取当时批次的统计日志
  801. const resultLogRes = await this.selectAll(this.tableName, {
  802. dimension: type,
  803. start_time: startTime,
  804. end_time: endTime
  805. })
  806. // const resultLogRes = await this.getCollection(this.tableName).where({
  807. // dimension: type,
  808. // start_time: startTime,
  809. // end_time: endTime
  810. // }).get()
  811. if (this.debug) {
  812. console.log('resultLogRes', JSON.stringify(resultLogRes))
  813. }
  814. if (!resultLogRes || resultLogRes.data.length === 0) {
  815. if (this.debug) {
  816. console.log('Not found this log --' + type + ':' + day + ', start:' + startTime + ',endTime:' +
  817. endTime)
  818. }
  819. return {
  820. code: 1000,
  821. msg: 'Not found this log'
  822. }
  823. }
  824. const sessionLog = new SessionLog()
  825. const platform = new Platform()
  826. const channel = new Channel()
  827. const version = new Version()
  828. let res = null
  829. for (const resultIndex in resultLogRes.data) {
  830. const resultLog = resultLogRes.data[resultIndex]
  831. // 平台信息
  832. let platformInfo = null
  833. if (this.platforms && this.platforms[resultLog.platform_id]) {
  834. platformInfo = this.platforms[resultLog.platform_id]
  835. } else {
  836. platformInfo = await this.getById(platform.tableName, resultLog.platform_id)
  837. if (!platformInfo || platformInfo.length === 0) {
  838. platformInfo.code = ''
  839. }
  840. this.platforms[resultLog.platform_id] = platformInfo
  841. if (this.debug) {
  842. console.log('platformInfo', JSON.stringify(platformInfo))
  843. }
  844. }
  845. // 渠道信息
  846. let channelInfo = null
  847. if (this.channels && this.channels[resultLog.channel_id]) {
  848. channelInfo = this.channels[resultLog.channel_id]
  849. } else {
  850. channelInfo = await this.getById(channel.tableName, resultLog.channel_id)
  851. if (!channelInfo || channelInfo.length === 0) {
  852. channelInfo.channel_code = ''
  853. }
  854. this.channels[resultLog.channel_id] = channelInfo
  855. if (this.debug) {
  856. console.log('channelInfo', JSON.stringify(channelInfo))
  857. }
  858. }
  859. // 版本信息
  860. let versionInfo = null
  861. if (this.versions && this.versions[resultLog.version_id]) {
  862. versionInfo = this.versions[resultLog.version_id]
  863. } else {
  864. versionInfo = await this.getById(version.tableName, resultLog.version_id, false)
  865. if (!versionInfo || versionInfo.length === 0) {
  866. versionInfo.version = ''
  867. }
  868. this.versions[resultLog.version_id] = versionInfo
  869. if (this.debug) {
  870. console.log('versionInfo', JSON.stringify(versionInfo))
  871. }
  872. }
  873. // 获取该批次的活跃设备数
  874. const activeDeviceRes = await this.aggregate(sessionLog.tableName, {
  875. project: {
  876. appid: 1,
  877. version: 1,
  878. platform: 1,
  879. channel: 1,
  880. device_id: 1,
  881. create_time: 1
  882. },
  883. match: {
  884. appid: resultLog.appid,
  885. version: versionInfo.version,
  886. platform: platformInfo.code,
  887. channel: channelInfo.channel_code,
  888. create_time: {
  889. $gte: startTime,
  890. $lte: endTime
  891. }
  892. },
  893. group: {
  894. _id: {
  895. device_id: '$device_id'
  896. },
  897. create_time: {
  898. $min: '$create_time'
  899. },
  900. sessionCount: {
  901. $sum: 1
  902. }
  903. },
  904. sort: {
  905. create_time: 1,
  906. sessionCount: 1
  907. },
  908. getAll: true
  909. })
  910. if (this.debug) {
  911. console.log('activeDeviceRes', JSON.stringify(activeDeviceRes))
  912. }
  913. let activeDeviceRate = 0
  914. let activeDevices = 0
  915. if (activeDeviceRes && activeDeviceRes.data.length > 0) {
  916. const thisDayActiveDevices = activeDeviceRes.data.length
  917. const thisDayActiveDeviceIds = []
  918. for (const tau in activeDeviceRes.data) {
  919. thisDayActiveDeviceIds.push(activeDeviceRes.data[tau]._id.device_id)
  920. }
  921. if (this.debug) {
  922. console.log('thisDayActiveDeviceIds', JSON.stringify(thisDayActiveDeviceIds))
  923. }
  924. // 留存活跃设备查询
  925. const retentionActiveDeviceRes = await this.aggregate(sessionLog.tableName, {
  926. project: {
  927. appid: 1,
  928. version: 1,
  929. platform: 1,
  930. channel: 1,
  931. device_id: 1,
  932. create_time: 1
  933. },
  934. match: {
  935. appid: resultLog.appid,
  936. version: versionInfo.version,
  937. platform: platformInfo.code,
  938. channel: channelInfo.channel_code,
  939. device_id: {
  940. $in: thisDayActiveDeviceIds
  941. },
  942. create_time: {
  943. $gte: lastTimeInfo.startTime,
  944. $lte: lastTimeInfo.endTime
  945. }
  946. },
  947. group: [{
  948. _id: {
  949. device_id: '$device_id'
  950. }
  951. }, {
  952. _id: {},
  953. total_devices: {
  954. $sum: 1
  955. }
  956. }]
  957. })
  958. if (this.debug) {
  959. console.log('retentionActiveDeviceRes', JSON.stringify(retentionActiveDeviceRes))
  960. }
  961. if (retentionActiveDeviceRes && retentionActiveDeviceRes.data.length > 0) {
  962. // 活跃设备留存数
  963. activeDevices = retentionActiveDeviceRes.data[0].total_devices
  964. // 活跃设备留存率
  965. activeDeviceRate = parseFloat((activeDevices * 100 / thisDayActiveDevices).toFixed(2))
  966. }
  967. }
  968. // 获取该批次新增设备数
  969. const newDeviceRes = await this.aggregate(sessionLog.tableName, {
  970. project: {
  971. appid: 1,
  972. version: 1,
  973. platform: 1,
  974. channel: 1,
  975. is_first_visit: 1,
  976. device_id: 1,
  977. create_time: 1
  978. },
  979. match: {
  980. appid: resultLog.appid,
  981. version: versionInfo.version,
  982. platform: platformInfo.code,
  983. channel: channelInfo.channel_code,
  984. is_first_visit: 1,
  985. create_time: {
  986. $gte: startTime,
  987. $lte: endTime
  988. }
  989. },
  990. group: {
  991. _id: {
  992. device_id: '$device_id'
  993. },
  994. create_time: {
  995. $min: '$create_time'
  996. },
  997. sessionCount: {
  998. $sum: 1
  999. }
  1000. },
  1001. sort: {
  1002. create_time: 1,
  1003. sessionCount: 1
  1004. },
  1005. getAll: true
  1006. })
  1007. let newDeviceRate = 0
  1008. let newDevices = 0
  1009. if (newDeviceRes && newDeviceRes.data.length > 0) {
  1010. const thisDayNewDevices = newDeviceRes.data.length
  1011. const thisDayNewDeviceIds = []
  1012. for (const tau in newDeviceRes.data) {
  1013. thisDayNewDeviceIds.push(newDeviceRes.data[tau]._id.device_id)
  1014. }
  1015. if (this.debug) {
  1016. console.log('thisDayNewDeviceIds', JSON.stringify(thisDayNewDeviceIds))
  1017. }
  1018. // 留存的设备查询
  1019. const retentionNewDeviceRes = await this.aggregate(sessionLog.tableName, {
  1020. project: {
  1021. appid: 1,
  1022. version: 1,
  1023. platform: 1,
  1024. channel: 1,
  1025. device_id: 1,
  1026. create_time: 1
  1027. },
  1028. match: {
  1029. appid: resultLog.appid,
  1030. version: versionInfo.version,
  1031. platform: platformInfo.code,
  1032. channel: channelInfo.channel_code,
  1033. device_id: {
  1034. $in: thisDayNewDeviceIds
  1035. },
  1036. create_time: {
  1037. $gte: lastTimeInfo.startTime,
  1038. $lte: lastTimeInfo.endTime
  1039. }
  1040. },
  1041. group: [{
  1042. _id: {
  1043. device_id: '$device_id'
  1044. }
  1045. }, {
  1046. _id: {},
  1047. total_devices: {
  1048. $sum: 1
  1049. }
  1050. }]
  1051. })
  1052. if (retentionNewDeviceRes && retentionNewDeviceRes.data.length > 0) {
  1053. // 新增设备留存数
  1054. newDevices = retentionNewDeviceRes.data[0].total_devices
  1055. // 新增设备留存率
  1056. newDeviceRate = parseFloat((newDevices * 100 / thisDayNewDevices).toFixed(2))
  1057. }
  1058. }
  1059. // 数据更新
  1060. const retentionData = resultLog.retention
  1061. const dataKey = type.substr(0, 1) + '_' + day
  1062. if (!retentionData.active_device) {
  1063. retentionData.active_device = {}
  1064. }
  1065. retentionData.active_device[dataKey] = {
  1066. device_count: activeDevices,
  1067. device_rate: activeDeviceRate
  1068. }
  1069. if (!retentionData.new_device) {
  1070. retentionData.new_device = {}
  1071. }
  1072. retentionData.new_device[dataKey] = {
  1073. device_count: newDevices,
  1074. device_rate: newDeviceRate
  1075. }
  1076. if (this.debug) {
  1077. console.log('retentionData', JSON.stringify(retentionData))
  1078. }
  1079. res = await this.update(this.tableName, {
  1080. retention: retentionData
  1081. }, {
  1082. _id: resultLog._id
  1083. })
  1084. }
  1085. if (res && res.updated) {
  1086. return {
  1087. code: 0,
  1088. msg: 'success'
  1089. }
  1090. } else {
  1091. return {
  1092. code: 500,
  1093. msg: 'retention data update failed'
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * 设备周/月留存数据填充
  1099. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  1100. * @param {Date|Time} date 指定日期或时间戳
  1101. * @param {Boolean} reset 是否重置,为ture时会重置该批次数据
  1102. */
  1103. async deviceRetentionFillWeekOrMonth(type, day, date) {
  1104. if (!['week', 'month'].includes(type)) {
  1105. return {
  1106. code: 301,
  1107. msg: 'Type error:' + type
  1108. }
  1109. }
  1110. const dateTime = new DateTime()
  1111. const {
  1112. startTime,
  1113. endTime
  1114. } = dateTime.getTimeDimensionByType(type, 0 - day, date)
  1115. if (!startTime || !endTime) {
  1116. return {
  1117. code: 1001,
  1118. msg: 'The statistic time get failed'
  1119. }
  1120. }
  1121. // 截止时间范围
  1122. const lastTimeInfo = dateTime.getTimeDimensionByType(type, 0, date)
  1123. // 获取当时批次的统计日志
  1124. const resultLogRes = await this.selectAll(this.tableName, {
  1125. dimension: type,
  1126. start_time: startTime,
  1127. end_time: endTime
  1128. })
  1129. if (this.debug) {
  1130. console.log('resultLogRes', JSON.stringify(resultLogRes))
  1131. }
  1132. if (!resultLogRes || resultLogRes.data.length === 0) {
  1133. if (this.debug) {
  1134. console.log('Not found this session log --' + type + ':' + day + ', start:' + startTime +
  1135. ',endTime:' + endTime)
  1136. }
  1137. return {
  1138. code: 1000,
  1139. msg: 'Not found this session log'
  1140. }
  1141. }
  1142. const activeDevicesObj = new ActiveDevices()
  1143. let res = null;
  1144. let activeDeviceRes;
  1145. let activeDeviceRate;
  1146. let activeDevices;
  1147. let newDeviceRate;
  1148. let newDevices
  1149. for (const resultIndex in resultLogRes.data) {
  1150. const resultLog = resultLogRes.data[resultIndex]
  1151. // 获取该批次的活跃设备数
  1152. activeDeviceRes = await this.selectAll(activeDevicesObj.tableName, {
  1153. appid: resultLog.appid,
  1154. platform_id: resultLog.platform_id,
  1155. channel_id: resultLog.channel_id,
  1156. version_id: resultLog.version_id,
  1157. dimension: type,
  1158. create_time: {
  1159. $gte: startTime,
  1160. $lte: endTime
  1161. }
  1162. }, {
  1163. device_id: 1
  1164. })
  1165. if (this.debug) {
  1166. console.log('activeDeviceRes', JSON.stringify(activeDeviceRes))
  1167. }
  1168. activeDeviceRate = 0
  1169. activeDevices = 0
  1170. if (activeDeviceRes && activeDeviceRes.data.length > 0) {
  1171. const thisDayActiveDevices = activeDeviceRes.data.length
  1172. const thisDayActiveDeviceIds = []
  1173. for (const tau in activeDeviceRes.data) {
  1174. thisDayActiveDeviceIds.push(activeDeviceRes.data[tau].device_id)
  1175. }
  1176. if (this.debug) {
  1177. console.log('thisDayActiveDeviceIds', JSON.stringify(thisDayActiveDeviceIds))
  1178. }
  1179. // 留存活跃设备数
  1180. const retentionActiveDeviceRes = await this.getCollection(activeDevicesObj.tableName).where({
  1181. appid: resultLog.appid,
  1182. platform_id: resultLog.platform_id,
  1183. channel_id: resultLog.channel_id,
  1184. version_id: resultLog.version_id,
  1185. device_id: {
  1186. $in: thisDayActiveDeviceIds
  1187. },
  1188. dimension: type,
  1189. create_time: {
  1190. $gte: lastTimeInfo.startTime,
  1191. $lte: lastTimeInfo.endTime
  1192. }
  1193. }).count()
  1194. if (this.debug) {
  1195. console.log('retentionActiveDeviceRes', JSON.stringify(retentionActiveDeviceRes))
  1196. }
  1197. if (retentionActiveDeviceRes && retentionActiveDeviceRes.total > 0) {
  1198. // 活跃设备留存数
  1199. activeDevices = retentionActiveDeviceRes.total
  1200. // 活跃设备留存率
  1201. activeDeviceRate = parseFloat((activeDevices * 100 / thisDayActiveDevices).toFixed(2))
  1202. }
  1203. }
  1204. // 获取该批次的新增设备数
  1205. const newDeviceRes = await this.selectAll(activeDevicesObj.tableName, {
  1206. appid: resultLog.appid,
  1207. platform_id: resultLog.platform_id,
  1208. channel_id: resultLog.channel_id,
  1209. version_id: resultLog.version_id,
  1210. is_new: 1,
  1211. dimension: type,
  1212. create_time: {
  1213. $gte: startTime,
  1214. $lte: endTime
  1215. }
  1216. }, {
  1217. device_id: 1
  1218. })
  1219. newDeviceRate = 0
  1220. newDevices = 0
  1221. if (newDeviceRes && newDeviceRes.data.length > 0) {
  1222. const thisDayNewDevices = newDeviceRes.data.length
  1223. const thisDayNewDeviceIds = []
  1224. for (const tau in newDeviceRes.data) {
  1225. thisDayNewDeviceIds.push(newDeviceRes.data[tau].device_id)
  1226. }
  1227. // 新增设备留存数
  1228. const retentionNewDeviceRes = await this.getCollection(activeDevicesObj.tableName).where({
  1229. appid: resultLog.appid,
  1230. platform_id: resultLog.platform_id,
  1231. channel_id: resultLog.channel_id,
  1232. version_id: resultLog.version_id,
  1233. device_id: {
  1234. $in: thisDayNewDeviceIds
  1235. },
  1236. dimension: type,
  1237. create_time: {
  1238. $gte: lastTimeInfo.startTime,
  1239. $lte: lastTimeInfo.endTime
  1240. }
  1241. }).count()
  1242. if (retentionNewDeviceRes && retentionNewDeviceRes.total > 0) {
  1243. // 新增设备留存数
  1244. newDevices = retentionNewDeviceRes.total
  1245. // 新增设备留存率
  1246. newDeviceRate = parseFloat((newDevices * 100 / thisDayNewDevices).toFixed(2))
  1247. }
  1248. }
  1249. // 数据更新
  1250. const retentionData = resultLog.retention
  1251. const dataKey = type.substr(0, 1) + '_' + day
  1252. if (!retentionData.active_device) {
  1253. retentionData.active_device = {}
  1254. }
  1255. retentionData.active_device[dataKey] = {
  1256. device_count: activeDevices,
  1257. device_rate: activeDeviceRate
  1258. }
  1259. if (!retentionData.new_device) {
  1260. retentionData.new_device = {}
  1261. }
  1262. retentionData.new_device[dataKey] = {
  1263. device_count: newDevices,
  1264. device_rate: newDeviceRate
  1265. }
  1266. if (this.debug) {
  1267. console.log('retentionData', JSON.stringify(retentionData))
  1268. }
  1269. res = await this.update(this.tableName, {
  1270. retention: retentionData
  1271. }, {
  1272. _id: resultLog._id
  1273. })
  1274. }
  1275. if (res && res.updated) {
  1276. return {
  1277. code: 0,
  1278. msg: 'success'
  1279. }
  1280. } else {
  1281. return {
  1282. code: 500,
  1283. msg: 'retention data update failed'
  1284. }
  1285. }
  1286. }
  1287. /**
  1288. * 用户日留存数据填充
  1289. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  1290. * @param {Date|Time} date 指定日期或时间戳
  1291. * @param {Boolean} reset 是否重置,为ture时会重置该批次数据
  1292. */
  1293. async userRetentionFillDayly(type, day, date) {
  1294. if (type !== 'day') {
  1295. return {
  1296. code: 301,
  1297. msg: 'Type error:' + type
  1298. }
  1299. }
  1300. const dateTime = new DateTime()
  1301. const {
  1302. startTime,
  1303. endTime
  1304. } = dateTime.getTimeDimensionByType(type, 0 - day, date)
  1305. if (!startTime || !endTime) {
  1306. return {
  1307. code: 1001,
  1308. msg: 'The statistic time get failed'
  1309. }
  1310. }
  1311. // 截止时间范围
  1312. const lastTimeInfo = dateTime.getTimeDimensionByType(type, 0, date)
  1313. // 获取当时批次的统计日志
  1314. const resultLogRes = await this.selectAll(this.tableName, {
  1315. dimension: type,
  1316. start_time: startTime,
  1317. end_time: endTime
  1318. })
  1319. if (this.debug) {
  1320. console.log('resultLogRes', JSON.stringify(resultLogRes))
  1321. }
  1322. if (!resultLogRes || resultLogRes.data.length === 0) {
  1323. if (this.debug) {
  1324. console.log('Not found this log --' + type + ':' + day + ', start:' + startTime + ',endTime:' +
  1325. endTime)
  1326. }
  1327. return {
  1328. code: 1000,
  1329. msg: 'Not found this log'
  1330. }
  1331. }
  1332. const userSessionLog = new UserSessionLog()
  1333. const uniIDUsers = new UniIDUsers()
  1334. const platform = new Platform()
  1335. const channel = new Channel()
  1336. const version = new Version()
  1337. let res = null
  1338. for (const resultIndex in resultLogRes.data) {
  1339. const resultLog = resultLogRes.data[resultIndex]
  1340. // 平台信息
  1341. let platformInfo = null
  1342. if (this.platforms && this.platforms[resultLog.platform_id]) {
  1343. platformInfo = this.platforms[resultLog.platform_id]
  1344. } else {
  1345. platformInfo = await this.getById(platform.tableName, resultLog.platform_id)
  1346. if (!platformInfo || platformInfo.length === 0) {
  1347. platformInfo.code = ''
  1348. }
  1349. this.platforms[resultLog.platform_id] = platformInfo
  1350. if (this.debug) {
  1351. console.log('platformInfo', JSON.stringify(platformInfo))
  1352. }
  1353. }
  1354. // 渠道信息
  1355. let channelInfo = null
  1356. if (this.channels && this.channels[resultLog.channel_id]) {
  1357. channelInfo = this.channels[resultLog.channel_id]
  1358. } else {
  1359. channelInfo = await this.getById(channel.tableName, resultLog.channel_id)
  1360. if (!channelInfo || channelInfo.length === 0) {
  1361. channelInfo.channel_code = ''
  1362. }
  1363. this.channels[resultLog.channel_id] = channelInfo
  1364. if (this.debug) {
  1365. console.log('channelInfo', JSON.stringify(channelInfo))
  1366. }
  1367. }
  1368. // 版本信息
  1369. let versionInfo = null
  1370. if (this.versions && this.versions[resultLog.version_id]) {
  1371. versionInfo = this.versions[resultLog.version_id]
  1372. } else {
  1373. versionInfo = await this.getById(version.tableName, resultLog.version_id, false)
  1374. if (!versionInfo || versionInfo.length === 0) {
  1375. versionInfo.version = ''
  1376. }
  1377. this.versions[resultLog.version_id] = versionInfo
  1378. if (this.debug) {
  1379. console.log('versionInfo', JSON.stringify(versionInfo))
  1380. }
  1381. }
  1382. // 获取该时间段内的活跃用户
  1383. const activeUserRes = await this.aggregate(userSessionLog.tableName, {
  1384. project: {
  1385. appid: 1,
  1386. version: 1,
  1387. platform: 1,
  1388. channel: 1,
  1389. uid: 1,
  1390. create_time: 1
  1391. },
  1392. match: {
  1393. appid: resultLog.appid,
  1394. version: versionInfo.version,
  1395. platform: platformInfo.code,
  1396. channel: channelInfo.channel_code,
  1397. create_time: {
  1398. $gte: startTime,
  1399. $lte: endTime
  1400. }
  1401. },
  1402. group: {
  1403. _id: {
  1404. uid: '$uid'
  1405. },
  1406. create_time: {
  1407. $min: '$create_time'
  1408. },
  1409. sessionCount: {
  1410. $sum: 1
  1411. }
  1412. },
  1413. sort: {
  1414. create_time: 1,
  1415. sessionCount: 1
  1416. },
  1417. getAll: true
  1418. })
  1419. if (this.debug) {
  1420. console.log('activeUserRes', JSON.stringify(activeUserRes))
  1421. }
  1422. //活跃用户留存率
  1423. let activeUserRate = 0
  1424. //活跃用户留存数
  1425. let activeUsers = 0
  1426. if (activeUserRes && activeUserRes.data.length > 0) {
  1427. const thisDayActiveUsers = activeUserRes.data.length
  1428. //获取该时间段内的活跃用户编号,这里没用lookup联查是因为数据量较大时lookup效率很低
  1429. const thisDayActiveUids = []
  1430. for (let tau in activeUserRes.data) {
  1431. thisDayActiveUids.push(activeUserRes.data[tau]._id.uid)
  1432. }
  1433. if (this.debug) {
  1434. console.log('thisDayActiveUids', JSON.stringify(thisDayActiveUids))
  1435. }
  1436. // 留存活跃用户数
  1437. const retentionActiveUserRes = await this.aggregate(userSessionLog.tableName, {
  1438. project: {
  1439. appid: 1,
  1440. version: 1,
  1441. platform: 1,
  1442. channel: 1,
  1443. uid: 1,
  1444. create_time: 1
  1445. },
  1446. match: {
  1447. appid: resultLog.appid,
  1448. version: versionInfo.version,
  1449. platform: platformInfo.code,
  1450. channel: channelInfo.channel_code,
  1451. uid: {
  1452. $in: thisDayActiveUids
  1453. },
  1454. create_time: {
  1455. $gte: lastTimeInfo.startTime,
  1456. $lte: lastTimeInfo.endTime
  1457. }
  1458. },
  1459. group: [{
  1460. _id: {
  1461. uid: '$uid'
  1462. }
  1463. }, {
  1464. _id: {},
  1465. total_users: {
  1466. $sum: 1
  1467. }
  1468. }]
  1469. })
  1470. if (this.debug) {
  1471. console.log('retentionActiveUserRes', JSON.stringify(retentionActiveUserRes))
  1472. }
  1473. if (retentionActiveUserRes && retentionActiveUserRes.data.length > 0) {
  1474. // 活跃用户留存数
  1475. activeUsers = retentionActiveUserRes.data[0].total_users
  1476. // 活跃用户留存率
  1477. activeUserRate = parseFloat((activeUsers * 100 / thisDayActiveUsers).toFixed(2))
  1478. }
  1479. }
  1480. //新增用户编号
  1481. const thisDayNewUids = await uniIDUsers.getUserIds(resultLog.appid, platformInfo.code, channelInfo.channel_code, versionInfo.version, {
  1482. $gte: startTime,
  1483. $lte: endTime
  1484. })
  1485. //新增用户留存率
  1486. let newUserRate = 0
  1487. //新增用户留存数
  1488. let newUsers = 0
  1489. if (thisDayNewUids.length > 0) {
  1490. // 现在依然活跃的用户数
  1491. const retentionNewUserRes = await this.aggregate(userSessionLog.tableName, {
  1492. project: {
  1493. appid: 1,
  1494. version: 1,
  1495. platform: 1,
  1496. channel: 1,
  1497. uid: 1,
  1498. create_time: 1
  1499. },
  1500. match: {
  1501. appid: resultLog.appid,
  1502. version: versionInfo.version,
  1503. platform: platformInfo.code,
  1504. channel: channelInfo.channel_code,
  1505. uid: {
  1506. $in: thisDayNewUids
  1507. },
  1508. create_time: {
  1509. $gte: lastTimeInfo.startTime,
  1510. $lte: lastTimeInfo.endTime
  1511. }
  1512. },
  1513. group: [{
  1514. _id: {
  1515. uid: '$uid'
  1516. }
  1517. }, {
  1518. _id: {},
  1519. total_users: {
  1520. $sum: 1
  1521. }
  1522. }]
  1523. })
  1524. if (retentionNewUserRes && retentionNewUserRes.data.length > 0) {
  1525. // 新增用户留存数
  1526. newUsers = retentionNewUserRes.data[0].total_users
  1527. // 新增用户留存率
  1528. newUserRate = parseFloat((newUsers * 100 / thisDayNewUids.length).toFixed(2))
  1529. }
  1530. }
  1531. // 数据更新
  1532. const retentionData = resultLog.retention
  1533. const dataKey = type.substr(0, 1) + '_' + day
  1534. if (!retentionData.active_user) {
  1535. retentionData.active_user = {}
  1536. }
  1537. retentionData.active_user[dataKey] = {
  1538. user_count: activeUsers,
  1539. user_rate: activeUserRate
  1540. }
  1541. if (!retentionData.new_user) {
  1542. retentionData.new_user = {}
  1543. }
  1544. retentionData.new_user[dataKey] = {
  1545. user_count: newUsers,
  1546. user_rate: newUserRate
  1547. }
  1548. if (this.debug) {
  1549. console.log('retentionData', JSON.stringify(retentionData))
  1550. }
  1551. res = await this.update(this.tableName, {
  1552. retention: retentionData
  1553. }, {
  1554. _id: resultLog._id
  1555. })
  1556. }
  1557. if (res && res.updated) {
  1558. return {
  1559. code: 0,
  1560. msg: 'success'
  1561. }
  1562. } else {
  1563. return {
  1564. code: 500,
  1565. msg: 'retention data update failed'
  1566. }
  1567. }
  1568. }
  1569. /**
  1570. * 用户周/月留存数据填充
  1571. * @param {String} type 统计类型 hour:实时统计 day:按天统计,week:按周统计 month:按月统计
  1572. * @param {Date|Time} date 指定日期或时间戳
  1573. * @param {Boolean} reset 是否重置,为ture时会重置该批次数据
  1574. */
  1575. async userRetentionFillWeekOrMonth(type, day, date) {
  1576. if (!['week', 'month'].includes(type)) {
  1577. return {
  1578. code: 301,
  1579. msg: 'Type error:' + type
  1580. }
  1581. }
  1582. const dateTime = new DateTime()
  1583. const {
  1584. startTime,
  1585. endTime
  1586. } = dateTime.getTimeDimensionByType(type, 0 - day, date)
  1587. if (!startTime || !endTime) {
  1588. return {
  1589. code: 1001,
  1590. msg: 'The statistic time get failed'
  1591. }
  1592. }
  1593. // 截止时间范围
  1594. const lastTimeInfo = dateTime.getTimeDimensionByType(type, 0, date)
  1595. // 获取当时批次的统计日志
  1596. const resultLogRes = await this.selectAll(this.tableName, {
  1597. dimension: type,
  1598. start_time: startTime,
  1599. end_time: endTime
  1600. })
  1601. if (this.debug) {
  1602. console.log('resultLogRes', JSON.stringify(resultLogRes))
  1603. }
  1604. if (!resultLogRes || resultLogRes.data.length === 0) {
  1605. if (this.debug) {
  1606. console.log('Not found this session log --' + type + ':' + day + ', start:' + startTime +
  1607. ',endTime:' + endTime)
  1608. }
  1609. return {
  1610. code: 1000,
  1611. msg: 'Not found this session log'
  1612. }
  1613. }
  1614. const activeUserObj = new ActiveUsers()
  1615. const uniIDUsers = new UniIDUsers()
  1616. const platform = new Platform()
  1617. const channel = new Channel()
  1618. const version = new Version()
  1619. let res = null
  1620. //活跃用户留存率
  1621. let activeUserRate
  1622. //活跃用户留存数
  1623. let activeUsers
  1624. //新增用户留存率
  1625. let newUserRate
  1626. //新增用户留存数
  1627. let newUsers
  1628. for (const resultIndex in resultLogRes.data) {
  1629. const resultLog = resultLogRes.data[resultIndex]
  1630. // 平台信息
  1631. let platformInfo = null
  1632. if (this.platforms && this.platforms[resultLog.platform_id]) {
  1633. platformInfo = this.platforms[resultLog.platform_id]
  1634. } else {
  1635. platformInfo = await this.getById(platform.tableName, resultLog.platform_id)
  1636. if (!platformInfo || platformInfo.length === 0) {
  1637. platformInfo.code = ''
  1638. }
  1639. this.platforms[resultLog.platform_id] = platformInfo
  1640. if (this.debug) {
  1641. console.log('platformInfo', JSON.stringify(platformInfo))
  1642. }
  1643. }
  1644. // 渠道信息
  1645. let channelInfo = null
  1646. if (this.channels && this.channels[resultLog.channel_id]) {
  1647. channelInfo = this.channels[resultLog.channel_id]
  1648. } else {
  1649. channelInfo = await this.getById(channel.tableName, resultLog.channel_id)
  1650. if (!channelInfo || channelInfo.length === 0) {
  1651. channelInfo.channel_code = ''
  1652. }
  1653. this.channels[resultLog.channel_id] = channelInfo
  1654. if (this.debug) {
  1655. console.log('channelInfo', JSON.stringify(channelInfo))
  1656. }
  1657. }
  1658. // 版本信息
  1659. let versionInfo = null
  1660. if (this.versions && this.versions[resultLog.version_id]) {
  1661. versionInfo = this.versions[resultLog.version_id]
  1662. } else {
  1663. versionInfo = await this.getById(version.tableName, resultLog.version_id, false)
  1664. if (!versionInfo || versionInfo.length === 0) {
  1665. versionInfo.version = ''
  1666. }
  1667. this.versions[resultLog.version_id] = versionInfo
  1668. if (this.debug) {
  1669. console.log('versionInfo', JSON.stringify(versionInfo))
  1670. }
  1671. }
  1672. // 获取该批次的活跃用户数
  1673. const activeUserRes = await this.selectAll(activeUserObj.tableName, {
  1674. appid: resultLog.appid,
  1675. platform_id: resultLog.platform_id,
  1676. channel_id: resultLog.channel_id,
  1677. version_id: resultLog.version_id,
  1678. dimension: type,
  1679. create_time: {
  1680. $gte: startTime,
  1681. $lte: endTime
  1682. }
  1683. }, {
  1684. uid: 1
  1685. })
  1686. if (this.debug) {
  1687. console.log('activeUserRes', JSON.stringify(activeUserRes))
  1688. }
  1689. activeUserRate = 0
  1690. activeUsers = 0
  1691. if (activeUserRes && activeUserRes.data.length > 0) {
  1692. const thisDayactiveUsers = activeUserRes.data.length
  1693. const thisDayActiveDeviceIds = []
  1694. for (const tau in activeUserRes.data) {
  1695. thisDayActiveDeviceIds.push(activeUserRes.data[tau].uid)
  1696. }
  1697. if (this.debug) {
  1698. console.log('thisDayActiveDeviceIds', JSON.stringify(thisDayActiveDeviceIds))
  1699. }
  1700. // 留存活跃用户数
  1701. const retentionactiveUserRes = await this.getCollection(activeUserObj.tableName).where({
  1702. appid: resultLog.appid,
  1703. platform_id: resultLog.platform_id,
  1704. channel_id: resultLog.channel_id,
  1705. version_id: resultLog.version_id,
  1706. uid: {
  1707. $in: thisDayActiveDeviceIds
  1708. },
  1709. dimension: type,
  1710. create_time: {
  1711. $gte: lastTimeInfo.startTime,
  1712. $lte: lastTimeInfo.endTime
  1713. }
  1714. }).count()
  1715. if (this.debug) {
  1716. console.log('retentionactiveUserRes', JSON.stringify(retentionactiveUserRes))
  1717. }
  1718. if (retentionactiveUserRes && retentionactiveUserRes.total > 0) {
  1719. // 活跃用户留存数
  1720. activeUsers = retentionactiveUserRes.total
  1721. // 活跃用户留存率
  1722. activeUserRate = parseFloat((activeUsers * 100 / thisDayactiveUsers).toFixed(2))
  1723. }
  1724. }
  1725. //新增用户编号
  1726. const thisDayNewUids = await uniIDUsers.getUserIds(resultLog.appid, platformInfo.code, channelInfo.channel_code, versionInfo.version, {
  1727. $gte: startTime,
  1728. $lte: endTime
  1729. })
  1730. // 新增用户留存率
  1731. newUserRate = 0
  1732. // 新增用户留存数
  1733. newUsers = 0
  1734. if(thisDayNewUids && thisDayNewUids.length > 0) {
  1735. // 新增用户留存数
  1736. const retentionnewUserRes = await this.getCollection(activeUserObj.tableName).where({
  1737. appid: resultLog.appid,
  1738. platform_id: resultLog.platform_id,
  1739. channel_id: resultLog.channel_id,
  1740. version_id: resultLog.version_id,
  1741. uid: {
  1742. $in: thisDayNewUids
  1743. },
  1744. dimension: type,
  1745. create_time: {
  1746. $gte: lastTimeInfo.startTime,
  1747. $lte: lastTimeInfo.endTime
  1748. }
  1749. }).count()
  1750. if (retentionnewUserRes && retentionnewUserRes.total > 0) {
  1751. // 新增用户留存数
  1752. newUsers = retentionnewUserRes.total
  1753. // 新增用户留存率
  1754. newUserRate = parseFloat((newUsers * 100 / thisDayNewUids.length).toFixed(2))
  1755. }
  1756. }
  1757. // 数据更新
  1758. const retentionData = resultLog.retention
  1759. const dataKey = type.substr(0, 1) + '_' + day
  1760. if (!retentionData.active_user) {
  1761. retentionData.active_user = {}
  1762. }
  1763. retentionData.active_user[dataKey] = {
  1764. user_count: activeUsers,
  1765. user_rate: activeUserRate
  1766. }
  1767. if (!retentionData.new_user) {
  1768. retentionData.new_user = {}
  1769. }
  1770. retentionData.new_user[dataKey] = {
  1771. user_count: newUsers,
  1772. user_rate: newUserRate
  1773. }
  1774. if (this.debug) {
  1775. console.log('retentionData', JSON.stringify(retentionData))
  1776. }
  1777. res = await this.update(this.tableName, {
  1778. retention: retentionData
  1779. }, {
  1780. _id: resultLog._id
  1781. })
  1782. }
  1783. if (res && res.updated) {
  1784. return {
  1785. code: 0,
  1786. msg: 'success'
  1787. }
  1788. } else {
  1789. return {
  1790. code: 500,
  1791. msg: 'retention data update failed'
  1792. }
  1793. }
  1794. }
  1795. /**
  1796. * 清理实时统计的日志
  1797. * @param {Number} days 实时统计日志保留天数
  1798. */
  1799. async cleanHourLog(days = 7) {
  1800. console.log('clean hour logs - day:', days)
  1801. const dateTime = new DateTime()
  1802. const res = await this.delete(this.tableName, {
  1803. dimension: 'hour',
  1804. start_time: {
  1805. $lt: dateTime.getTimeBySetDays(0 - days)
  1806. }
  1807. })
  1808. if (!res.code) {
  1809. console.log('clean hour logs - res:', res)
  1810. }
  1811. }
  1812. }