Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

include MAU, goals & errors into reports

Blue Mouse18b135f913ae
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 7d3f84f46..c29d17f31 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -63,6 +63,7 @@ import {
hash,
millisecondsToSeconds,
sumArrays,
+ formatDuration,
} from '../common/utils'
import { PageviewsDto } from './dto/pageviews.dto'
import { EventsDto } from './dto/events.dto'
@@ -1518,6 +1519,117 @@ export class AnalyticsService {
return result
}
+ convertSummaryToReportFormat(summary: IOverall): any {
+ const result = {}
+
+ for (const pid of _keys(summary)) {
+ const { current, previous } = summary[pid]
+
+ result[pid] = {
+ // Existing metrics
+ pageviews: current.all,
+ previousPageviews: previous.all,
+ percChangePageviews: calculateRelativePercentage(
+ previous.all,
+ current.all,
+ ),
+
+ uniqueVisitors: current.unique,
+ previousUniqueVisitors: previous.unique,
+ percChangeUnique: calculateRelativePercentage(
+ previous.unique,
+ current.unique,
+ ),
+
+ // Active Users (MAU/WAU)
+ activeUsers: current.users || 0,
+ previousActiveUsers: previous.users || 0,
+ percChangeUsers: calculateRelativePercentage(
+ previous.users || 0,
+ current.users || 0,
+ ),
+
+ // Average Session Duration
+ avgDuration: formatDuration(current.sdur),
+ avgDurationSeconds: _round(current.sdur || 0),
+ previousAvgDuration: formatDuration(previous.sdur),
+ previousAvgDurationSeconds: _round(previous.sdur || 0),
+ percChangeDuration: calculateRelativePercentage(
+ previous.sdur || 0,
+ current.sdur || 0,
+ ),
+
+ // Bounce Rate
+ bounceRate: _round(current.bounceRate || 0, 1),
+ previousBounceRate: _round(previous.bounceRate || 0, 1),
+ // For bounce rate, lower is better, so we invert the change
+ bounceRateChange: _round(
+ (current.bounceRate || 0) - (previous.bounceRate || 0),
+ 1,
+ ),
+ }
+ }
+
+ return result
+ }
+
+ async getTopCountryForReport(
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ ): Promise<{ cc: string; count: number } | null> {
+ const query = `
+ SELECT
+ cc,
+ count() as count
+ FROM analytics
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND cc IS NOT NULL
+ AND cc != ''
+ GROUP BY cc
+ ORDER BY count DESC
+ LIMIT 1
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, groupFrom, groupTo },
+ })
+ .then(resultSet => resultSet.json<{ cc: string; count: number }>())
+
+ return data[0] || null
+ }
+
+ async getErrorCountForReport(
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ ): Promise<{ count: number; uniqueErrors: number }> {
+ const query = `
+ SELECT
+ count() as count,
+ count(DISTINCT eid) as uniqueErrors
+ FROM errors
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { pid, groupFrom, groupTo },
+ })
+ .then(resultSet =>
+ resultSet.json<{ count: number; uniqueErrors: number }>(),
+ )
+
+ return data[0] || { count: 0, uniqueErrors: 0 }
+ }
+
async getAnalyticsSummary(
pids: string[],
timeBucket?: string,
diff --git a/backend/apps/cloud/src/common/templates/en/project-report.html b/backend/apps/cloud/src/common/templates/en/project-report.html
index 9cec48076..60f618cd4 100644
--- a/backend/apps/cloud/src/common/templates/en/project-report.html
+++ b/backend/apps/cloud/src/common/templates/en/project-report.html
@@ -49,62 +49,310 @@
<font align="center"
style="font-size: 52px; line-height: 55px; font-weight: 300; letter-spacing: -1.5px;">
<span align="center"
- style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; font-size: 44px; color: #1a1a1a;">
+ style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; font-size: 38px; color: #1a1a1a; font-weight: 600;">
Your {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type
"M"}}Monthly{{/ifEquals}}{{#ifEquals type "Q"}}Quarterly{{/ifEquals}} Report
</span>
</font>
- <div style="height: 10px; line-height: 10px; font-size: 9px;">&nbsp;</div>
+ <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
<font style="font-size: 36px; line-height: 45px; font-weight: 300; letter-spacing: -1px;">
<span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- color: #5e5e5e;
- font-size: 30px;
- line-height: 45px;
- font-weight: 300;
- letter-spacing: -1px;
- ">
- For the {{date}} period
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ color: #5e5e5e;
+ font-size: 18px;
+ line-height: 28px;
+ font-weight: 400;
+ ">
+ {{date}}
</span>
</font>
- <div style="height: 38px; line-height: 38px; font-size: 36px;">&nbsp;</div>
- <table cellpadding="0" cellspacing="0" border="0" width="88%"
- style="width: 88% !important; min-width: 88%; max-width: 88%;">
+ <div style="height: 30px; line-height: 30px; font-size: 28px;">&nbsp;</div>
+
+ {{#each projects}}
+ <!-- Project Card -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #f8fafc; border-radius: 12px; margin-bottom: 24px; border: 1px solid #e2e8f0;">
<tr>
- <td align="left" valign="top">
- <font face="'Source Sans Pro', sans-serif" color="#6d6d6d"
- style="font-size: 17px; line-height: 23px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- color: #6d6d6d;
- font-size: 17px;
- line-height: 23px;
- ">
- {{#each projects}}
- <h3 style="margin-bottom: 5px;">{{name}}</h3>
- <b>Unique visitors:</b> {{data.thisWeekUnique}} ({{#greater data.percChangeUnique 0}}<span
- style="color: #059669;">+{{data.percChangeUnique}}%</span>{{else}}<span
- style="color: #DC2626;">{{data.percChangeUnique}}%</span>{{/greater}})<br />
- <b>Pageviews:</b> {{data.thisWeek}} ({{#greater data.percChange 0}}<span
- style="color: #059669;">+{{data.percChange}}%</span>{{else}}<span
- style="color: #DC2626;">{{data.percChange}}%</span>{{/greater}})<br /><br />
- {{/each}}
+ <td style="padding: 24px;">
+ <!-- Project Name -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%">
+ <tr>
+ <td>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 22px;
+ font-weight: 600;
+ color: #1e293b;
+ ">{{name}}</span>
+ {{#if topCountry}}
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ color: #64748b;
+ margin-left: 8px;
+ ">Top country: {{topCountry}}</span>
+ {{/if}}
+ </td>
+ </tr>
+ </table>
+ <div style="height: 20px; line-height: 20px; font-size: 18px;">&nbsp;</div>
+
+ <!-- Primary Metrics Grid -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%">
+ <tr>
+ <!-- Active Users -->
+ <td width="33%" valign="top" style="padding-right: 12px;">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
+ <tr>
+ <td style="padding: 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Active Users</span>
+ <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ ">{{data.activeUsers}}</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ font-weight: 500;
+ margin-left: 6px;
+ {{#greater data.percChangeUsers 0}}color: #059669;{{else}}color: #DC2626;{{/greater}}
+ ">{{#greater data.percChangeUsers 0}}+{{/greater}}{{data.percChangeUsers}}%</span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Unique Visitors -->
+ <td width="33%" valign="top" style="padding-right: 12px;">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
+ <tr>
+ <td style="padding: 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Unique Visitors</span>
+ <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ ">{{data.uniqueVisitors}}</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ font-weight: 500;
+ margin-left: 6px;
+ {{#greater data.percChangeUnique 0}}color: #059669;{{else}}color: #DC2626;{{/greater}}
+ ">{{#greater data.percChangeUnique 0}}+{{/greater}}{{data.percChangeUnique}}%</span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Pageviews -->
+ <td width="33%" valign="top">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
+ <tr>
+ <td style="padding: 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Pageviews</span>
+ <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ ">{{data.pageviews}}</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ font-weight: 500;
+ margin-left: 6px;
+ {{#greater data.percChangePageviews 0}}color: #059669;{{else}}color: #DC2626;{{/greater}}
+ ">{{#greater data.percChangePageviews 0}}+{{/greater}}{{data.percChangePageviews}}%</span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+
+ <div style="height: 12px; line-height: 12px; font-size: 10px;">&nbsp;</div>
+
+ <!-- Secondary Metrics -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%">
+ <tr>
+ <!-- Avg. Session Duration -->
+ <td width="50%" valign="top" style="padding-right: 12px;">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
+ <tr>
+ <td style="padding: 14px 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Avg. Session</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 18px;
+ font-weight: 600;
+ color: #0f172a;
+ float: right;
+ ">{{data.avgDuration}}</span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Bounce Rate -->
+ <td width="50%" valign="top">
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
+ <tr>
+ <td style="padding: 14px 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Bounce Rate</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 18px;
+ font-weight: 600;
+ color: #0f172a;
+ float: right;
+ ">{{data.bounceRate}}%</span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
- <i style="white-space: pre-line;">
- <span style="font-style: normal;">&#128161;</span>
- {{tip}}
- </i>
+ {{#if goals}}
+ <div style="height: 16px; line-height: 16px; font-size: 14px;">&nbsp;</div>
+ <!-- Goals Section -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #ecfdf5; border-radius: 8px; border: 1px solid #a7f3d0;">
+ <tr>
+ <td style="padding: 14px 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 600;
+ color: #059669;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Goal Conversions</span>
+ <div style="height: 10px; line-height: 10px; font-size: 8px;">&nbsp;</div>
+ {{#each goals}}
+ <div style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ color: #065f46;
+ margin-bottom: 4px;
+ ">
+ <strong>{{name}}:</strong> {{conversions}} conversions ({{conversionRate}}% rate)
+ </div>
+ {{/each}}
+ </td>
+ </tr>
+ </table>
+ {{/if}}
- <br /><br />
+ {{#if errors}}
+ <div style="height: 12px; line-height: 12px; font-size: 10px;">&nbsp;</div>
+ <!-- Errors Section -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #fef2f2; border-radius: 8px; border: 1px solid #fecaca;">
+ <tr>
+ <td style="padding: 14px 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 600;
+ color: #dc2626;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ ">Errors Detected</span>
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ color: #991b1b;
+ float: right;
+ ">{{errors.count}} total ({{errors.uniqueErrors}} unique)</span>
+ </td>
+ </tr>
+ </table>
+ {{/if}}
+ </td>
+ </tr>
+ </table>
+ {{/each}}
- Do not want to receive these emails? <a href="{{unsubscribeUrl}}"
- target="_blank">Click here</a> to unsubscribe.
- </span>
- </font>
- <div style="height: 30px; line-height: 30px; font-size: 28px;">&nbsp;</div>
+ <!-- Tip Section -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%"
+ style="background: #fffbeb; border-radius: 8px; border: 1px solid #fde68a; margin-top: 8px;">
+ <tr>
+ <td style="padding: 16px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 14px;
+ color: #92400e;
+ line-height: 1.6;
+ ">
+ <span style="font-size: 16px;">💡</span> <strong>Tip:</strong> {{tip}}
+ </span>
</td>
</tr>
</table>
+
+ <div style="height: 24px; line-height: 24px; font-size: 22px;">&nbsp;</div>
+
+ <!-- Unsubscribe -->
+ <table cellpadding="0" cellspacing="0" border="0" width="100%">
+ <tr>
+ <td align="center" style="padding-bottom: 24px;">
+ <span style="
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
+ font-size: 13px;
+ color: #94a3b8;
+ ">
+ Don't want these emails? <a href="{{unsubscribeUrl}}" target="_blank"
+ style="color: #64748b; text-decoration: underline;">Unsubscribe</a>
+ </span>
+ </td>
+ </tr>
+ </table>
+
</td>
</tr>
</table>
@@ -120,4 +368,4 @@
</table>
</body>
-</html>
\ No newline at end of file
+</html>
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index 0fee9de63..d431c99a0 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -321,3 +321,36 @@ export const sumArrays = (source: number[], target: number[]) => {
return result
}
+
+/**
+ * Format duration in seconds to human-readable format (e.g., "3m 42s")
+ * @param seconds Duration in seconds
+ * @returns Formatted duration string
+ */
+export const formatDuration = (seconds: number | null | undefined): string => {
+ if (!seconds || seconds <= 0) return '0s'
+
+ const roundedSeconds = Math.round(seconds)
+
+ if (roundedSeconds < 60) {
+ return `${roundedSeconds}s`
+ }
+
+ const minutes = Math.floor(roundedSeconds / 60)
+ const remainingSeconds = roundedSeconds % 60
+
+ if (minutes < 60) {
+ return remainingSeconds > 0
+ ? `${minutes}m ${remainingSeconds}s`
+ : `${minutes}m`
+ }
+
+ const hours = Math.floor(minutes / 60)
+ const remainingMinutes = minutes % 60
+
+ if (remainingMinutes > 0) {
+ return `${hours}h ${remainingMinutes}m`
+ }
+
+ return `${hours}h`
+}
diff --git a/backend/apps/cloud/src/task-manager/task-manager.module.ts b/backend/apps/cloud/src/task-manager/task-manager.module.ts
index d99a41475..358535db0 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.module.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.module.ts
@@ -14,6 +14,7 @@ import { AppLoggerModule } from '../logger/logger.module'
import { Message } from '../integrations/telegram/entities/message.entity'
import { DiscordModule } from '../integrations/discord/discord.module'
import { SlackModule } from '../integrations/slack/slack.module'
+import { GoalModule } from '../goal/goal.module'
@Module({
imports: [
@@ -29,6 +30,7 @@ import { SlackModule } from '../integrations/slack/slack.module'
PayoutsModule,
DiscordModule,
SlackModule,
+ GoalModule,
],
providers: [TaskManagerService, TelegramService],
exports: [TaskManagerService],
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index a682606d7..236c27c87 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -30,6 +30,8 @@ import { LetterTemplate } from '../mailer/letter'
import { AnalyticsService } from '../analytics/analytics.service'
import { SaltService } from '../analytics/salt.service'
import { PayoutsService } from '../payouts/payouts.service'
+import { GoalService } from '../goal/goal.service'
+import { Goal, GoalType, GoalMatchType } from '../goal/entity/goal.entity'
import { PayoutStatus } from '../payouts/entities/payouts.entity'
import {
ACCOUNT_PLANS,
@@ -294,8 +296,102 @@ export class TaskManagerService {
private readonly discordService: DiscordService,
private readonly slackService: SlackService,
private readonly saltService: SaltService,
+ private readonly goalService: GoalService,
) {}
+ /**
+ * Build goal match condition for querying conversions
+ */
+ private buildGoalMatchCondition(
+ goal: Goal,
+ _table: 'analytics' | 'customEV',
+ ): { condition: string; params: Record<string, string> } {
+ const params: Record<string, string> = {}
+
+ if (goal.type === GoalType.CUSTOM_EVENT) {
+ if (goal.matchType === GoalMatchType.EXACT) {
+ params.goalValue = goal.value || ''
+ return { condition: `ev = {goalValue:String}`, params }
+ } else {
+ params.goalValue = `%${goal.value || ''}%`
+ return { condition: `ev LIKE {goalValue:String}`, params }
+ }
+ }
+
+ // Pageview goal
+ if (goal.matchType === GoalMatchType.EXACT) {
+ params.goalValue = goal.value || ''
+ return { condition: `pg = {goalValue:String}`, params }
+ } else {
+ params.goalValue = `%${goal.value || ''}%`
+ return { condition: `pg LIKE {goalValue:String}`, params }
+ }
+ }
+
+ /**
+ * Get goal conversions for a specific period
+ */
+ async getGoalConversionsForReport(
+ goal: Goal,
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ ): Promise<{ conversions: number; conversionRate: number }> {
+ const table = goal.type === GoalType.CUSTOM_EVENT ? 'customEV' : 'analytics'
+ const { condition: matchCondition, params: matchParams } =
+ this.buildGoalMatchCondition(goal, table)
+
+ // Get conversions
+ const conversionsQuery = `
+ SELECT
+ count(*) as conversions,
+ uniqExact(psid) as uniqueSessions
+ FROM ${table}
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND ${matchCondition}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data: conversionsData } = await clickhouse
+ .query({
+ query: conversionsQuery,
+ query_params: {
+ pid,
+ groupFrom,
+ groupTo,
+ ...matchParams,
+ },
+ })
+ .then(resultSet =>
+ resultSet.json<{ conversions: number; uniqueSessions: number }>(),
+ )
+
+ const conversions = conversionsData[0]?.conversions || 0
+ const uniqueSessions = conversionsData[0]?.uniqueSessions || 0
+
+ // Get total sessions for conversion rate
+ const totalSessionsQuery = `
+ SELECT uniqExact(psid) as totalSessions
+ FROM analytics
+ WHERE
+ pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data: totalData } = await clickhouse
+ .query({
+ query: totalSessionsQuery,
+ query_params: { pid, groupFrom, groupTo },
+ })
+ .then(resultSet => resultSet.json<{ totalSessions: number }>())
+
+ const totalSessions = totalData[0]?.totalSessions || 1
+ const conversionRate = Math.round((uniqueSessions / totalSessions) * 100)
+
+ return { conversions, conversionRate }
+ }
+
generateUnsubscribeUrl(
id: string,
type: '3rdparty' | 'user-reports',
@@ -323,22 +419,27 @@ export class TaskManagerService {
const users = await this.userService.getReportUsers(reportFrequency)
- const now = dayjs.utc().format('DD.MM.YYYY')
+ const now = dayjs.utc()
+ const nowFormatted = now.format('DD.MM.YYYY')
const timeAgo = dayjs
.utc()
// @ts-expect-error
.subtract(...params.dayjsParams)
- .format('DD.MM.YYYY')
- const date = `${timeAgo} - ${now}`
+ const timeAgoFormatted = timeAgo.format('DD.MM.YYYY')
+ const date = `${timeAgoFormatted} - ${nowFormatted}`
const tip = getRandomTip()
+ // Date range for additional queries
+ const groupFrom = timeAgo.format('YYYY-MM-DD 00:00:00')
+ const groupTo = now.format('YYYY-MM-DD 23:59:59')
+
const promises = _map(users, async user => {
const { id, email, projects } = user
const unsubscribeUrl = this.generateUnsubscribeUrl(id, 'user-reports')
const ids = _map(projects, p => p.id)
- const data = this.analyticsService.convertSummaryToObsoleteFormat(
+ const data = this.analyticsService.convertSummaryToReportFormat(
await this.analyticsService.getAnalyticsSummary(
ids,
undefined,
@@ -346,13 +447,72 @@ export class TaskManagerService {
),
)
+ // Fetch additional data for each project
+ const projectsWithExtraData = await Promise.all(
+ _map(ids, async (pid, index) => {
+ const projectData = data[pid] || {}
+
+ // Fetch top country
+ const topCountry = await this.analyticsService.getTopCountryForReport(
+ pid,
+ groupFrom,
+ groupTo,
+ )
+
+ // Fetch error count
+ const errorStats = await this.analyticsService.getErrorCountForReport(
+ pid,
+ groupFrom,
+ groupTo,
+ )
+
+ // Fetch goals with conversions (only if they have any conversions)
+ const projectGoals = await this.goalService.findByProject(pid)
+ const goalsWithConversions = await Promise.all(
+ _map(projectGoals, async goal => {
+ const { conversions, conversionRate } =
+ await this.getGoalConversionsForReport(
+ goal,
+ pid,
+ groupFrom,
+ groupTo,
+ )
+ return {
+ name: goal.name,
+ conversions,
+ conversionRate,
+ }
+ }),
+ )
+
+ // Only include goals that have conversions
+ const activeGoals = _filter(
+ goalsWithConversions,
+ g => g.conversions > 0,
+ )
+
+ return {
+ data: projectData,
+ name: projects[index].name,
+ topCountry: topCountry?.cc || null,
+ // Only include errors if there are any
+ errors:
+ errorStats.count > 0
+ ? {
+ count: errorStats.count,
+ uniqueErrors: errorStats.uniqueErrors,
+ }
+ : null,
+ // Only include goals if there are any with conversions
+ goals: activeGoals.length > 0 ? activeGoals : null,
+ }
+ }),
+ )
+
const result = {
type: params.type,
date,
- projects: _map(ids, (pid, index) => ({
- data: data[pid],
- name: projects[index].name,
- })),
+ projects: projectsWithExtraData,
tip,
unsubscribeUrl,
}
@@ -381,15 +541,20 @@ export class TaskManagerService {
const subscribers =
await this.projectService.getSubscribersForReports(reportFrequency)
- const now = dayjs.utc().format('DD.MM.YYYY')
+ const now = dayjs.utc()
+ const nowFormatted = now.format('DD.MM.YYYY')
const timeAgo = dayjs
.utc()
// @ts-expect-error
.subtract(...params.dayjsParams)
- .format('DD.MM.YYYY')
- const date = `${timeAgo} - ${now}`
+ const timeAgoFormatted = timeAgo.format('DD.MM.YYYY')
+ const date = `${timeAgoFormatted} - ${nowFormatted}`
const tip = getRandomTip()
+ // Date range for additional queries
+ const groupFrom = timeAgo.format('YYYY-MM-DD 00:00:00')
+ const groupTo = now.format('YYYY-MM-DD 23:59:59')
+
const promises = _map(subscribers, async subscriber => {
const { id, email } = subscriber
const projects = await this.projectService.getSubscriberProjects(id)
@@ -397,7 +562,7 @@ export class TaskManagerService {
const unsubscribeUrl = this.generateUnsubscribeUrl(id, '3rdparty')
const ids = projects.map(project => project.id)
- const data = this.analyticsService.convertSummaryToObsoleteFormat(
+ const data = this.analyticsService.convertSummaryToReportFormat(
await this.analyticsService.getAnalyticsSummary(
ids,
undefined,
@@ -405,13 +570,72 @@ export class TaskManagerService {
),
)
+ // Fetch additional data for each project
+ const projectsWithExtraData = await Promise.all(
+ _map(ids, async (pid, index) => {
+ const projectData = data[pid] || {}
+
+ // Fetch top country
+ const topCountry = await this.analyticsService.getTopCountryForReport(
+ pid,
+ groupFrom,
+ groupTo,
+ )
+
+ // Fetch error count
+ const errorStats = await this.analyticsService.getErrorCountForReport(
+ pid,
+ groupFrom,
+ groupTo,
+ )
+
+ // Fetch goals with conversions (only if they have any conversions)
+ const projectGoals = await this.goalService.findByProject(pid)
+ const goalsWithConversions = await Promise.all(
+ _map(projectGoals, async goal => {
+ const { conversions, conversionRate } =
+ await this.getGoalConversionsForReport(
+ goal,
+ pid,
+ groupFrom,
+ groupTo,
+ )
+ return {
+ name: goal.name,
+ conversions,
+ conversionRate,
+ }
+ }),
+ )
+
+ // Only include goals that have conversions
+ const activeGoals = _filter(
+ goalsWithConversions,
+ g => g.conversions > 0,
+ )
+
+ return {
+ data: projectData,
+ name: projects[index].name,
+ topCountry: topCountry?.cc || null,
+ // Only include errors if there are any
+ errors:
+ errorStats.count > 0
+ ? {
+ count: errorStats.count,
+ uniqueErrors: errorStats.uniqueErrors,
+ }
+ : null,
+ // Only include goals if there are any with conversions
+ goals: activeGoals.length > 0 ? activeGoals : null,
+ }
+ }),
+ )
+
const result = {
type: params.type,
date,
- projects: _map(ids, (pid, index) => ({
- data: data[pid],
- name: projects[index].name,
- })),
+ projects: projectsWithExtraData,
tip,
unsubscribeUrl,
}