🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Implement marketing unsubscribe functionality and onboarding email sc… (#805)
Bill Yangc527aa9a48b9
diff --git a/client/public/rybbit-text-black.png b/client/public/rybbit-text-black.pngnew file mode 100644index 000000000..17118e240Binary files /dev/null and b/client/public/rybbit-text-black.png differdiff --git a/docker-compose.cloud.yml b/docker-compose.cloud.ymlindex 27a76dd57..f557c91e1 100644--- a/docker-compose.cloud.yml+++ b/docker-compose.cloud.yml@@ -123,9 +123,6 @@ services:- REDIS_HOST=redis- REDIS_PORT=6379- REDIS_PASSWORD=${REDIS_PASSWORD:-changeme}- # Axiom logging configuration (optional)- - AXIOM_DATASET=${AXIOM_DATASET}- - AXIOM_TOKEN=${AXIOM_TOKEN}- MAPBOX_TOKEN=${MAPBOX_TOKEN}- TURNSTILE_SECRET_KEY=${TURNSTILE_SECRET_KEY}- IPAPI_KEY=${IPAPI_KEY}diff --git a/docs/content/docs/architecture.mdx b/docs/content/docs/architecture.mdxindex 6d294c4e4..b3a3bf93d 100644--- a/docs/content/docs/architecture.mdx+++ b/docs/content/docs/architecture.mdx@@ -115,7 +115,6 @@ graph TB- **ORM**: Drizzle ORM- **Authentication**: Better Auth with session management- **Validation**: Zod schemas-- **Logging**: Pino with Axiom integration (cloud)- **Rate Limiting**: Fastify rate limit plugin### Database Layer@@ -180,7 +179,6 @@ graph TB**Cloud Additions:**- R2 integration for session replay storage-- Axiom logging integration- Stripe webhook handling## Data Flowdiff --git a/server/.env.example b/server/.env.exampleindex 01e7cf702..6e94203e1 100644--- a/server/.env.example+++ b/server/.env.example@@ -37,7 +37,3 @@ R2_ACCESS_KEY_ID=R2_SECRET_ACCESS_KEY=R2_BUCKET_NAME=R2_PUBLIC_URL=--# Axiom logging (optional)-AXIOM_DATASET=-AXIOM_TOKEN=\ No newline at end of filediff --git a/server/AXIOM_SETUP.md b/server/AXIOM_SETUP.mddeleted file mode 100644index 03539179f..000000000--- a/server/AXIOM_SETUP.md+++ /dev/null@@ -1,121 +0,0 @@-# Axiom Logging Setup--This guide explains how to configure Axiom for centralized logging in the Rybbit server.--## Prerequisites--1. Create an Axiom account at https://axiom.co-2. Create a new dataset for your logs (e.g., "rybbit-logs")-3. Generate an API token with ingest permissions--## Configuration--Add the following environment variables to your `.env` file:--```env-# Axiom logging-AXIOM_DATASET=your-dataset-name-AXIOM_TOKEN=xaat-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx-```--## How It Works--### Development Mode-When both `AXIOM_DATASET` and `AXIOM_TOKEN` are set in development:-- Logs are sent directly to Axiom using the Pino transport-- This is useful for testing your Axiom integration--Without Axiom credentials in development:-- Logs use pino-pretty for readable console output--### Production Mode-In production with Axiom configured:-- Logs are sent to both Axiom AND stdout simultaneously-- You can view logs in Axiom for powerful searching and analytics-- You can still use `docker logs` to see logs locally-- No additional piping or configuration needed--## Production Setup--For production, you have several options:--### Option 1: Using Axiom's log forwarder-```bash-# Install axiom CLI-curl -fsSL https://install.axiom.co/install.sh | sh--# Run your app and pipe to Axiom-npm start | axiom ingest $AXIOM_DATASET -t $AXIOM_TOKEN-```--### Option 2: Docker Compose-```yaml-services:- app:- image: your-app- environment:- - NODE_ENV=production- logging:- driver: "json-file"-- log-forwarder:- image: axiomhq/axiom-forwarder- environment:- - AXIOM_DATASET=${AXIOM_DATASET}- - AXIOM_TOKEN=${AXIOM_TOKEN}- volumes:- - /var/lib/docker/containers:/var/lib/docker/containers:ro-```--### Option 3: Direct in Development-Set your environment variables and logs will be sent directly to Axiom:-```bash-AXIOM_DATASET=your-dataset AXIOM_TOKEN=your-token npm run dev-```--## Log Structure--All logs include:-- Service name (e.g., "monitor-scheduler", "notification-service")-- Structured data as the first parameter-- Log level (info, warn, error, debug)-- Timestamp and other metadata--Example:-```javascript-logger.info({ monitorId: 123, region: "us-east-1" }, "Health check completed");-```--## Viewing Logs in Axiom--1. Go to your Axiom dashboard-2. Select your dataset-3. Use APL (Axiom Processing Language) to query logs:--```apl-// View all errors-| where level == "error"--// View logs from a specific service-| where service == "notification-service"--// View logs for a specific monitor-| where monitorId == 123-```--## Benefits--- Centralized logging across all services-- Powerful search and analytics-- Real-time log streaming-- Alerts and dashboards-- No log rotation needed-- Cost-effective for high volume--## Troubleshooting--If logs aren't appearing in Axiom:-1. Check that environment variables are set correctly-2. Verify the API token has ingest permissions-3. Check the dataset name matches exactly-4. Look for connection errors in stdout logs\ No newline at end of filediff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.tsindex 37061e0f4..bd08fc01c 100644--- a/server/src/api/sessionReplay/recordSessionReplay.ts+++ b/server/src/api/sessionReplay/recordSessionReplay.ts@@ -6,6 +6,7 @@ import { usageService } from "../../services/usageService.js";import { RecordSessionReplayRequest } from "../../types/sessionReplay.js";import { getIpAddress } from "../../utils.js";import { logger } from "../../lib/logger/logger.js";+import { getLocation } from "../../db/geolocation/geolocation.js";const recordSessionReplaySchema = z.object({userId: z.string(),@@ -35,7 +36,8 @@ export async function recordSessionReplay() {try {// Get the site configuration to get the numeric siteId- const { siteId, excludedIPs, excludedCountries, sessionReplay } = (await siteConfig.getConfig(request.params.siteId)) ?? {};+ const { siteId, excludedIPs, excludedCountries, sessionReplay } =+ (await siteConfig.getConfig(request.params.siteId)) ?? {};if (!sessionReplay) {logger.info(`[SessionReplay] Skipping event for site ${siteId} - session replay not enabled`);@@ -67,7 +69,6 @@ export async function recordSessionReplay(// Check if the country should be excluded from trackingif (excludedCountries && excludedCountries.length > 0) {- const { getLocation } = await import("../../db/geolocation/geolocation.js");const locationResults = await getLocation([requestIP]);const locationData = locationResults[requestIP];diff --git a/server/src/api/user/index.ts b/server/src/api/user/index.tsindex c02f957e9..bdbfbb599 100644--- a/server/src/api/user/index.ts+++ b/server/src/api/user/index.ts@@ -6,6 +6,7 @@ export { listOrganizationMembers } from "./listOrganizationMembers.js";// Account Settingsexport { updateAccountSettings } from "./updateAccountSettings.js";+export { unsubscribeMarketing, oneClickUnsubscribeMarketing } from "./unsubscribeMarketing.js";// API Keysexport { listApiKeys } from "./listApiKeys.js";diff --git a/server/src/api/user/unsubscribeMarketing.ts b/server/src/api/user/unsubscribeMarketing.tsnew file mode 100644index 000000000..b9d470b84--- /dev/null+++ b/server/src/api/user/unsubscribeMarketing.ts@@ -0,0 +1,128 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { eq } from "drizzle-orm";+import { DateTime } from "luxon";+import { db } from "../../db/postgres/postgres.js";+import { user } from "../../db/postgres/schema.js";+import { unsubscribeContact, cancelScheduledEmail } from "../../lib/email/email.js";+import { onboardingTipsService } from "../../services/onboardingTips/onboardingTipsService.js";++// Authenticated user unsubscribe+export const unsubscribeMarketing = async (+ request: FastifyRequest,+ reply: FastifyReply+) => {+ try {+ const userId = request.user?.id;+ if (!userId) {+ return reply.status(401).send({ error: "Unauthorized" });+ }++ // Get user data+ const [userData] = await db+ .select({+ email: user.email,+ scheduledTipEmailIds: user.scheduledTipEmailIds,+ })+ .from(user)+ .where(eq(user.id, userId));++ if (!userData) {+ return reply.status(404).send({ error: "User not found" });+ }++ // Cancel scheduled tip emails+ const emailIds = (userData.scheduledTipEmailIds as string[]) || [];+ await onboardingTipsService.cancelScheduledEmails(emailIds);++ // Clear the scheduled email IDs+ await db+ .update(user)+ .set({+ scheduledTipEmailIds: [],+ updatedAt: DateTime.now().toISO(),+ })+ .where(eq(user.id, userId));++ // Mark contact as unsubscribed in Resend+ await unsubscribeContact(userData.email);++ return reply.send({ success: true, message: "Successfully unsubscribed from marketing emails" });+ } catch (error) {+ console.error("Error unsubscribing from marketing emails:", error);+ return reply.status(500).send({ error: "Failed to unsubscribe" });+ }+};++// One-click unsubscribe handler+// GET: User clicks link in email - show confirmation page+// POST: Email client's List-Unsubscribe-Post - return 200 OK+export const oneClickUnsubscribeMarketing = async (+ request: FastifyRequest<{ Querystring: { email?: string } }>,+ reply: FastifyReply+) => {+ try {+ const email = request.query.email;+ const isGetRequest = request.method === "GET";++ if (!email) {+ if (isGetRequest) {+ return reply.status(400).type("text/html").send(`+ <!DOCTYPE html>+ <html><head><title>Unsubscribe - Rybbit</title></head>+ <body style="font-family: sans-serif; max-width: 600px; margin: 50px auto; text-align: center;">+ <h1>Invalid Request</h1>+ <p>Email address is required to unsubscribe.</p>+ </body></html>+ `);+ }+ return reply.status(400).send({ error: "Email is required" });+ }++ // Find user by email+ const [userData] = await db+ .select({+ id: user.id,+ scheduledTipEmailIds: user.scheduledTipEmailIds,+ })+ .from(user)+ .where(eq(user.email, email));++ if (userData) {+ // Cancel scheduled tip emails+ const emailIds = (userData.scheduledTipEmailIds as string[]) || [];+ await onboardingTipsService.cancelScheduledEmails(emailIds);++ // Clear the scheduled email IDs+ await db+ .update(user)+ .set({+ scheduledTipEmailIds: [],+ updatedAt: DateTime.now().toISO(),+ })+ .where(eq(user.id, userData.id));+ }++ // Mark contact as unsubscribed in Resend (even if user not found in our DB)+ await unsubscribeContact(email);++ // For GET requests (link clicks), show confirmation page+ if (isGetRequest) {+ return reply.status(200).type("text/html").send(`+ <!DOCTYPE html>+ <html><head><title>Unsubscribed - Rybbit</title></head>+ <body style="font-family: sans-serif; max-width: 600px; margin: 50px auto; text-align: center;">+ <h1>Unsubscribed</h1>+ <p>You have been successfully unsubscribed from Rybbit marketing emails.</p>+ <p style="color: #666; margin-top: 20px;">You can close this page.</p>+ </body></html>+ `);+ }++ // For POST requests (email client List-Unsubscribe), return 200 OK as per RFC 8058+ return reply.status(200).send();+ } catch (error) {+ console.error("Error in one-click unsubscribe:", error);+ // Still return 200 to not confuse email clients+ return reply.status(200).send();+ }+};diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 8baf0df29..e29e73bcf 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -41,6 +41,7 @@ export const user = pgTable(// deprecatedmonthlyEventCount: integer().default(0),sendAutoEmailReports: boolean().default(true),+ scheduledTipEmailIds: jsonb("scheduled_tip_email_ids").$type<string[]>().default([]),},table => [unique("user_username_unique").on(table.username), unique("user_email_unique").on(table.email)]);diff --git a/server/src/index.ts b/server/src/index.tsindex 9cdd3cc7c..455de4b1a 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -55,6 +55,7 @@ import {gscCallback,selectGSCProperty,} from "./api/gsc/index.js";+import { updateInvitationSiteAccess, updateMemberSiteAccess } from "./api/memberAccess/index.js";import {deleteSessionReplay,getSessionReplayEvents,@@ -95,28 +96,30 @@ import {getUserOrganizations,listApiKeys,listOrganizationMembers,+ oneClickUnsubscribeMarketing,+ unsubscribeMarketing,updateAccountSettings,} from "./api/user/index.js";-import { updateInvitationSiteAccess, updateMemberSiteAccess } from "./api/memberAccess/index.js";import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";import { initPostgres } from "./db/postgres/initPostgres.js";-import { mapHeaders } from "./lib/auth-utils.js";-import { auth } from "./lib/auth.js";-import { IS_CLOUD } from "./lib/const.js";-import { trackEvent } from "./services/tracker/trackEvent.js";-import { handleIdentify } from "./services/tracker/identifyService.js";-import { telemetryService } from "./services/telemetryService.js";-import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";import {- requireAuth,+ allowPublicSiteAccess,requireAdmin,+ requireAuth,+ requireOrgAdminFromParams,+ requireOrgMember,requireSiteAccess,requireSiteAdminAccess,- allowPublicSiteAccess,- requireOrgMember,- requireOrgAdminFromParams,resolveSiteId,} from "./lib/auth-middleware.js";+import { mapHeaders } from "./lib/auth-utils.js";+import { auth } from "./lib/auth.js";+import { IS_CLOUD } from "./lib/const.js";+import { reengagementService } from "./services/reengagement/reengagementService.js";+import { telemetryService } from "./services/telemetryService.js";+import { handleIdentify } from "./services/tracker/identifyService.js";+import { trackEvent } from "./services/tracker/trackEvent.js";+import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";// Pre-composed middleware chains for common auth patterns// Cast as any to work around Fastify's type inference limitations with preHandler@@ -131,49 +134,22 @@ const orgAdminParams = { preHandler: [requireOrgAdminFromParams] as any };const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);-const hasAxiom = !!(process.env.AXIOM_DATASET && process.env.AXIOM_TOKEN);-const server = Fastify({+ disableRequestLogging: true,logger: {- level: process.env.LOG_LEVEL || (process.env.NODE_ENV === "development" ? "debug" : "info"),- transport:- process.env.NODE_ENV === "production" && IS_CLOUD && hasAxiom- ? {- targets: [- // Send to Axiom- {- target: "@axiomhq/pino",- level: process.env.LOG_LEVEL || "info",- options: {- dataset: process.env.AXIOM_DATASET,- token: process.env.AXIOM_TOKEN,- },- },- // Pretty print to stdout for Docker logs- {- target: "pino-pretty",- level: process.env.LOG_LEVEL || "info",- options: {- colorize: true,- singleLine: true,- translateTime: "HH:MM:ss",- ignore: "pid,hostname,name",- destination: 1, // stdout- },- },- ],- }- : process.env.NODE_ENV === "development"- ? {- target: "pino-pretty",- options: {- colorize: true,- singleLine: true,- translateTime: "HH:MM:ss",- ignore: "pid,hostname,name",- },- }- : undefined, // Production without Axiom - plain JSON to stdout+ // level: process.env.LOG_LEVEL || (process.env.NODE_ENV === "development" ? "debug" : "info"),+ level: "debug",+ transport: {+ target: "pino-pretty",+ level: process.env.LOG_LEVEL || "debug",+ options: {+ colorize: true,+ singleLine: true,+ translateTime: "HH:MM:ss",+ ignore: "pid,hostname,name",+ destination: 1, // stdout+ },+ },serializers: {req(request) {return {@@ -336,6 +312,9 @@ async function userRoutes(fastify: FastifyInstance) {fastify.get("/config", getConfig); // Public - returns app configfastify.get("/user/organizations", authOnly, getUserOrganizations);fastify.post("/user/account-settings", authOnly, updateAccountSettings);+ fastify.post("/user/unsubscribe-marketing", authOnly, unsubscribeMarketing);+ fastify.get("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for link clicks+ fastify.post("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe headerfastify.get("/user/api-keys", authOnly, listApiKeys);fastify.post("/user/api-keys", authOnly, createApiKey);fastify.delete("/user/api-keys/:keyId", authOnly, deleteApiKey);@@ -404,17 +383,13 @@ const start = async () => {telemetryService.startTelemetryCron();if (IS_CLOUD) {weeklyReportService.startWeeklyReportCron();+ reengagementService.startReengagementCron();}// Start the server firstawait server.listen({ port: 3001, host: "0.0.0.0" });server.log.info("Server is listening on http://0.0.0.0:3001");- // Test Axiom logging- if (hasAxiom) {- server.log.info({ axiom: true, dataset: process.env.AXIOM_DATASET }, "Axiom logging is configured");- }-// if (process.env.NODE_ENV === "production") {// // Initialize uptime monitoring service in the background (non-blocking)// uptimeServicediff --git a/server/src/lib/auth.ts b/server/src/lib/auth.tsindex 9ee3dbc9f..d5d58251a 100644--- a/server/src/lib/auth.ts+++ b/server/src/lib/auth.ts@@ -9,7 +9,8 @@ import { db } from "../db/postgres/postgres.js";import * as schema from "../db/postgres/schema.js";import { invitation, member, memberSiteAccess, user } from "../db/postgres/schema.js";import { DISABLE_SIGNUP, IS_CLOUD } from "./const.js";-import { sendInvitationEmail, sendOtpEmail, sendWelcomeEmail } from "./email/email.js";+import { addContactToAudience, sendInvitationEmail, sendOtpEmail, sendWelcomeEmail } from "./email/email.js";+import { onboardingTipsService } from "../services/onboardingTips/onboardingTipsService.js";dotenv.config();@@ -102,6 +103,11 @@ export const auth = betterAuth({defaultValue: true,input: true,},+ // scheduledTipEmailIds: {+ // type: "string[]",+ // required: false,+ // defaultValue: [],+ // },},deleteUser: {enabled: true,@@ -122,13 +128,29 @@ export const auth = betterAuth({databaseHooks: {user: {create: {- after: async () => {+ after: async u => {+ console.log(u);const users = await db.select().from(schema.user).orderBy(asc(user.createdAt));// If this is the first user, make them an adminif (users.length === 1) {await db.update(user).set({ role: "admin" }).where(eq(user.id, users[0].id));}++ sendWelcomeEmail(u.email, u.name);+ // Add contact to marketing audience and schedule onboarding emails+ try {+ await addContactToAudience(u.email, u.name);++ const emailIds = await onboardingTipsService.scheduleOnboardingEmails(u.email, u.name);++ // Store scheduled email IDs for potential cancellation+ if (emailIds.length > 0) {+ await db.update(user).set({ scheduledTipEmailIds: emailIds }).where(eq(user.id, u.id));+ }+ } catch (error) {+ console.error("Error setting up onboarding emails:", error);+ }},},update: {@@ -154,13 +176,6 @@ export const auth = betterAuth({},hooks: {after: createAuthMiddleware(async ctx => {- if (ctx.path.startsWith("/sign-up") && IS_CLOUD) {- const newSession = ctx.context.newSession;- if (newSession) {- sendWelcomeEmail(newSession.user.email, newSession.user.name);- }- }-// Handle invitation acceptance - copy site access from invitation to memberif (ctx.path === "/organization/accept-invitation") {try {diff --git a/server/src/lib/email/email.ts b/server/src/lib/email/email.tsindex 75562c233..18aa84887 100644--- a/server/src/lib/email/email.ts+++ b/server/src/lib/email/email.ts@@ -3,16 +3,75 @@ import { render } from "@react-email/components";import { IS_CLOUD } from "../const.js";import { InvitationEmail } from "./templates/InvitationEmail.js";import { LimitExceededEmail } from "./templates/LimitExceededEmail.js";+import { OnboardingTipEmail } from "./templates/OnboardingTipEmail.js";import { OtpEmail, type OtpEmailType } from "./templates/OtpEmail.js";+import { ReengagementEmail } from "./templates/ReengagementEmail.js";import { WeeklyReportEmail } from "./templates/WeeklyReportEmail.js";import type { OrganizationReport } from "../../services/weekyReports/weeklyReportTypes.js";+import type { OnboardingTipContent } from "../../services/onboardingTips/onboardingTipsContent.js";+import type { ReengagementContent } from "../../services/reengagement/reengagementContent.js";let resend: Resend | undefined;+let marketingAudienceId: string | null = null;if (IS_CLOUD) {resend = new Resend(process.env.RESEND_API_KEY);}+// Marketing audience management+export const getOrCreateMarketingAudience = async (): Promise<string> => {+ if (marketingAudienceId) return marketingAudienceId;+ if (!resend) throw new Error("Resend not initialized");++ // List existing audiences to check if "Marketing" exists+ const { data: audiences } = await resend.audiences.list();+ const existing = audiences?.data?.find((a: { name: string }) => a.name === "Marketing");++ if (existing) {+ marketingAudienceId = existing.id;+ return existing.id;+ }++ // Create new audience+ const { data } = await resend.audiences.create({ name: "Marketing" });+ marketingAudienceId = data!.id;+ return data!.id;+};++export const addContactToAudience = async (email: string, firstName?: string): Promise<void> => {+ if (!resend) return;+ try {+ const audienceId = await getOrCreateMarketingAudience();+ await resend.contacts.create({ audienceId, email, firstName, unsubscribed: false });+ } catch (error) {+ console.error("Failed to add contact to audience:", error);+ }+};++export const isContactUnsubscribed = async (email: string): Promise<boolean> => {+ if (!resend) return false;+ try {+ const audienceId = await getOrCreateMarketingAudience();+ const { data: contact } = await resend.contacts.get({ audienceId, email });+ // If contact doesn't exist or is unsubscribed, return true to skip sending+ if (!contact) return true;+ return contact.unsubscribed ?? false;+ } catch (error) {+ // If contact doesn't exist (404), don't send email+ return true;+ }+};++export const unsubscribeContact = async (email: string): Promise<void> => {+ if (!resend) return;+ try {+ const audienceId = await getOrCreateMarketingAudience();+ await resend.contacts.update({ audienceId, email, unsubscribed: true });+ } catch (error) {+ console.error("Failed to unsubscribe contact:", error);+ }+};+export const sendEmail = async (email: string, subject: string, html: string) => {if (!resend) {return;@@ -21,7 +80,7 @@ export const sendEmail = async (email: string, subject: string, html: string) =>}try {const response = await resend.emails.send({- from: "Rybbit <[email protected]>",+ from: "Rybbit <[email protected]>",to: email,subject,html,@@ -116,7 +175,7 @@ Bill`;try {await resend.emails.send({- from: "Bill from Rybbit <[email protected]>",+ from: "Bill from Rybbit <[email protected]>",replyTo: "[email protected]",to: email,subject: "Welcome to Rybbit!",@@ -126,3 +185,95 @@ Bill`;console.error("Failed to send welcome email:", error);}};++// Scheduled onboarding tip email - returns the email ID for cancellation+export const scheduleOnboardingTipEmail = async (+ email: string,+ userName: string,+ tipContent: OnboardingTipContent,+ scheduledAt: string+): Promise<string | null> => {+ if (!resend) return null;++ const unsubscribeUrl = `${process.env.BASE_URL}/api/user/unsubscribe-marketing-oneclick?email=${encodeURIComponent(email)}`;++ try {+ const html = await render(+ OnboardingTipEmail({+ userName,+ body: tipContent.body,+ linkText: tipContent.linkText,+ linkUrl: tipContent.linkUrl,+ unsubscribeUrl,+ })+ );++ const response = await resend.emails.send({+ from: "Rybbit <[email protected]>",+ to: email,+ subject: tipContent.subject,+ html,+ scheduledAt,+ headers: {+ "List-Unsubscribe": `<${unsubscribeUrl}>`,+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ },+ });++ return response.data?.id ?? null;+ } catch (error) {+ console.error("Failed to schedule onboarding tip email:", error);+ return null;+ }+};++// Cancel a scheduled email+export const cancelScheduledEmail = async (emailId: string): Promise<void> => {+ if (!resend) return;+ try {+ await resend.emails.cancel(emailId);+ } catch (error) {+ console.error("Failed to cancel scheduled email:", error);+ }+};++// Send re-engagement email+export const sendReengagementEmail = async (+ email: string,+ userName: string,+ content: ReengagementContent,+ siteId: number,+ domain: string+): Promise<void> => {+ if (!resend) return;++ const unsubscribeUrl = `${process.env.BASE_URL}/api/user/unsubscribe-marketing-oneclick?email=${encodeURIComponent(email)}`;++ try {+ const html = await render(+ ReengagementEmail({+ userName,+ day: content.day,+ title: content.title,+ message: content.message,+ ctaText: content.ctaText,+ siteId,+ domain,+ unsubscribeUrl,+ })+ );++ await resend.emails.send({+ from: "Rybbit <[email protected]>",+ to: email,+ subject: content.subject,+ html,+ headers: {+ "List-Unsubscribe": `<${unsubscribeUrl}>`,+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ },+ });+ } catch (error) {+ console.error("Failed to send re-engagement email:", error);+ }+};diff --git a/server/src/lib/email/templates/OnboardingTipEmail.tsx b/server/src/lib/email/templates/OnboardingTipEmail.tsxnew file mode 100644index 000000000..0b2acb3a0--- /dev/null+++ b/server/src/lib/email/templates/OnboardingTipEmail.tsx@@ -0,0 +1,94 @@+import {+ Body,+ Container,+ Head,+ Hr,+ Html,+ Img,+ Link,+ Preview,+ Text,+ Tailwind,+ pixelBasedPreset,+} from "@react-email/components";+import * as React from "react";++interface OnboardingTipEmailProps {+ userName: string;+ body: string;+ linkText?: string;+ linkUrl?: string;+ unsubscribeUrl: string;+}++export const OnboardingTipEmail = ({ userName, body, linkText, linkUrl, unsubscribeUrl }: OnboardingTipEmailProps) => {+ const currentYear = new Date().getFullYear();+ const greeting = userName ? `Hi ${userName}` : "Hi there";++ // Split body into paragraphs+ const paragraphs = body.split("\n\n").filter(p => p.trim());++ return (+ <Html>+ <Head />+ <Preview>{paragraphs[0]?.substring(0, 100) || "A message from Rybbit"}</Preview>+ <Tailwind+ config={{+ presets: [pixelBasedPreset],+ theme: {+ extend: {+ colors: {+ brand: "#10b981",+ darkText: "#111827",+ mutedText: "#6b7280",+ borderColor: "#e5e7eb",+ },+ },+ },+ }}+ >+ <Body className="bg-white font-sans">+ <Container className="mx-auto py-8 px-6 max-w-[600px]">+ <Img+ src="https://app.rybbit.io/rybbit-text-black.png"+ alt="Rybbit"+ width="120"+ height="28"+ className="mb-8"+ />++ <Text className="text-darkText text-base leading-relaxed mb-4">{greeting},</Text>++ {paragraphs.map((paragraph, index) => (+ <Text key={index} className="text-darkText text-base leading-relaxed mb-4">+ {paragraph}+ </Text>+ ))}++ {linkUrl && linkText && (+ <Text className="text-darkText text-base leading-relaxed mb-4">+ <Link href={linkUrl} className="text-brand underline">+ {linkText}+ </Link>+ </Text>+ )}++ <Text className="text-darkText text-base leading-relaxed mt-8">+ You can reply to this email,+ <br />+ Bill – Founder of Rybbit+ </Text>++ <Hr className="border-borderColor my-8" />++ <Text className="text-mutedText text-xs">+ <Link href={unsubscribeUrl} className="text-mutedText underline">+ Unsubscribe+ </Link>+ </Text>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};diff --git a/server/src/lib/email/templates/ReengagementEmail.tsx b/server/src/lib/email/templates/ReengagementEmail.tsxnew file mode 100644index 000000000..d5aaa6632--- /dev/null+++ b/server/src/lib/email/templates/ReengagementEmail.tsx@@ -0,0 +1,114 @@+import {+ Body,+ Container,+ Head,+ Hr,+ Html,+ Img,+ Link,+ Preview,+ Text,+ Tailwind,+ pixelBasedPreset,+} from "@react-email/components";+import * as React from "react";++interface ReengagementEmailProps {+ userName: string;+ day: number;+ title: string;+ message: string;+ ctaText: string;+ siteId: number;+ domain: string;+ unsubscribeUrl: string;+}++const DOCS_URL = "https://www.rybbit.io/docs";++export const ReengagementEmail = ({+ userName,+ day,+ title,+ message,+ ctaText,+ siteId,+ domain,+ unsubscribeUrl,+}: ReengagementEmailProps) => {+ const greeting = userName ? `Hi ${userName}` : "Hi there";+ const dashboardUrl = `https://app.rybbit.io/${siteId}`;+ const messageWithDomain = message.replace("{domain}", domain);++ // Split message into paragraphs+ const paragraphs = messageWithDomain.split("\n\n").filter(p => p.trim());++ return (+ <Html>+ <Head />+ <Preview>{title}</Preview>+ <Tailwind+ config={{+ presets: [pixelBasedPreset],+ theme: {+ extend: {+ colors: {+ brand: "#10b981",+ darkText: "#111827",+ mutedText: "#6b7280",+ borderColor: "#e5e7eb",+ },+ },+ },+ }}+ >+ <Body className="bg-white font-sans">+ <Container className="mx-auto py-8 px-6 max-w-[600px]">+ <Img+ src="https://app.rybbit.io/rybbit-text-black.png"+ alt="Rybbit"+ width="120"+ height="28"+ className="mb-8"+ />++ <Text className="text-darkText text-base leading-relaxed mb-4">{greeting},</Text>++ {paragraphs.map((paragraph, index) => (+ <Text key={index} className="text-darkText text-base leading-relaxed mb-4">+ {paragraph}+ </Text>+ ))}++ <Text className="text-darkText text-base leading-relaxed mb-4">+ <Link href={dashboardUrl} className="text-brand underline">+ {ctaText}+ </Link>+ </Text>++ <Text className="text-mutedText text-sm leading-relaxed mb-4">+ Need help?{" "}+ <Link href={DOCS_URL} className="text-mutedText underline">+ View our setup guide+ </Link>+ </Text>++ <Text className="text-darkText text-base leading-relaxed mt-8">+ You can reply to this email,+ <br />+ Bill – Founder of Rybbit+ </Text>++ <Hr className="border-borderColor my-8" />++ <Text className="text-mutedText text-xs">+ <Link href={unsubscribeUrl} className="text-mutedText underline">+ Unsubscribe+ </Link>+ </Text>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};diff --git a/server/src/lib/logger/LOGGING.md b/server/src/lib/logger/LOGGING.mdindex 98296e104..75ae5d8af 100644--- a/server/src/lib/logger/LOGGING.md+++ b/server/src/lib/logger/LOGGING.md@@ -130,8 +130,6 @@ Replace console statements with appropriate logger calls:- `LOG_LEVEL`: Set the minimum log level (trace, debug, info, warn, error, fatal)- `NODE_ENV`: Determines log format (production vs development)-- `AXIOM_DATASET`: Axiom dataset name for centralized logging (optional)-- `AXIOM_TOKEN`: Axiom API token for log ingestion (optional)## Example Service Refactoringdiff --git a/server/src/lib/logger/logger.ts b/server/src/lib/logger/logger.tsindex 4c321021a..72cb57cae 100644--- a/server/src/lib/logger/logger.ts+++ b/server/src/lib/logger/logger.ts@@ -1,66 +1,19 @@import type { FastifyBaseLogger } from "fastify";import { pino } from "pino";-import { IS_CLOUD } from "../const.js";--const isDevelopment = process.env.NODE_ENV === "development";-const isProduction = process.env.NODE_ENV === "production";-const hasAxiom = !!(process.env.AXIOM_DATASET && process.env.AXIOM_TOKEN);export const createLogger = (name: string): FastifyBaseLogger => {- // Production with Axiom - send to both Axiom and stdout- if (isProduction && hasAxiom && IS_CLOUD) {- return pino({- name,- level: process.env.LOG_LEVEL || "info",- transport: {- targets: [- // Send to Axiom- {- target: "@axiomhq/pino",- level: process.env.LOG_LEVEL || "info",- options: {- dataset: process.env.AXIOM_DATASET,- token: process.env.AXIOM_TOKEN,- },- },- // Pretty print to stdout for Docker logs- {- target: "pino-pretty",- level: process.env.LOG_LEVEL || "info",- options: {- colorize: true,- singleLine: true,- translateTime: "HH:MM:ss",- ignore: "pid,hostname,name",- destination: 1, // stdout- },- },- ],- },- }) as FastifyBaseLogger;- }-- // Development mode with pretty printing- if (isDevelopment) {- return pino({- name,- level: process.env.LOG_LEVEL || "debug",- transport: {- target: "pino-pretty",- options: {- colorize: true,- singleLine: true,- translateTime: "HH:MM:ss",- ignore: "pid,hostname,name",- },- },- }) as FastifyBaseLogger;- }-- // Production without Axiom - plain JSON to stdoutreturn pino({name,- level: process.env.LOG_LEVEL || "info",+ level: process.env.LOG_LEVEL || "debug",+ transport: {+ target: "pino-pretty",+ options: {+ colorize: true,+ singleLine: true,+ translateTime: "HH:MM:ss",+ ignore: "pid,hostname,name",+ },+ },}) as FastifyBaseLogger;};diff --git a/server/src/services/onboardingTips/onboardingTipsContent.ts b/server/src/services/onboardingTips/onboardingTipsContent.tsnew file mode 100644index 000000000..9e36acd87--- /dev/null+++ b/server/src/services/onboardingTips/onboardingTipsContent.ts@@ -0,0 +1,73 @@+export interface OnboardingTipContent {+ day: number;+ subject: string;+ body: string;+ linkText?: string;+ linkUrl?: string;+}++export const ONBOARDING_TIPS: OnboardingTipContent[] = [+ {+ day: 1,+ subject: "You made the right choice",+ body: `Thanks for signing up for Rybbit. You've joined thousands of developers who care about respecting their users' privacy.++Unlike traditional analytics tools, Rybbit doesn't use cookies, doesn't track users across websites, and doesn't sell your data to advertisers. Your visitors stay anonymous, and you still get the insights you need.++We built Rybbit because we were tired of tools that treat users as products. Privacy shouldn't mean giving up on understanding your audience.++If you're curious how we compare to other tools, check out our comparison page.`,+ linkText: "View comparison",+ linkUrl: "https://rybbit.com/docs/comparison",+ },+ {+ day: 2,+ subject: "Why your metrics might look different than GA",+ body: `If you've been using Google Analytics before, you might notice your Rybbit numbers look different. That's actually a good thing.++Adblockers block Google Analytics. They rarely block Rybbit. So for the first time, you're probably seeing your real traffic - and it's likely higher than GA ever showed you.++We're also lightweight and privacy-focused, which means browsers and privacy tools treat us differently than traditional trackers.++Those missing visitors in GA? They were always there. You just couldn't see them.`,+ },+ {+ day: 3,+ subject: "Track what matters with custom events",+ body: `Pageviews tell you what pages people visit. Custom events tell you what they actually do.++Track button clicks, form submissions, video plays - anything that matters to your business. It's one line of code:++window.rybbit.event("signup_clicked")++Or use data attributes directly in your HTML:++<button data-rybbit-event="signup_clicked">Sign Up</button>++Events show up in your dashboard and can be used as funnel steps or goal triggers.`,+ linkText: "Read the full guide",+ linkUrl: "https://rybbit.com/docs/track-events",+ },+ {+ day: 4,+ subject: "Turn pageviews into insights",+ body: `Raw traffic numbers are interesting, but conversions are what matter.++Goals let you track specific outcomes - signups, purchases, downloads. Set a goal for "/thank-you" and see how many visitors actually convert, broken down by source, device, and more.++Funnels go deeper. Define a multi-step process (view product -> add to cart -> checkout -> purchase) and see exactly where users drop off. Finding a 60% drop-off at checkout? Now you know where to focus.`,+ linkText: "Set up your first goal",+ linkUrl: "https://rybbit.com/docs/web-analytics/goals-tab",+ },+ {+ day: 5,+ subject: "Build with your data",+ body: `Everything in your Rybbit dashboard is available through our API.++Build custom dashboards, set up alerts when traffic spikes, pipe data into your own tools, create reports for clients - the data is yours to use however you want.++Authentication is simple (API key in header), and the endpoints mirror what you see in the UI. Query pageviews, events, sessions, funnels - whatever you need.`,+ linkText: "Get started with the API",+ linkUrl: "https://rybbit.com/docs/api/getting-started",+ },+];diff --git a/server/src/services/onboardingTips/onboardingTipsService.ts b/server/src/services/onboardingTips/onboardingTipsService.tsnew file mode 100644index 000000000..5c328c43b--- /dev/null+++ b/server/src/services/onboardingTips/onboardingTipsService.ts@@ -0,0 +1,40 @@+import { DateTime } from "luxon";+import { scheduleOnboardingTipEmail, cancelScheduledEmail } from "../../lib/email/email.js";+import { ONBOARDING_TIPS } from "./onboardingTipsContent.js";++class OnboardingTipsService {+ /**+ * Schedule all 7 onboarding tip emails at signup+ * Returns array of Resend email IDs for cancellation+ */+ async scheduleOnboardingEmails(email: string, name?: string): Promise<string[]> {+ const emailIds: string[] = [];+ const now = DateTime.utc();++ for (const tip of ONBOARDING_TIPS) {+ // Schedule email for day N at 9am UTC+ const scheduledAt = now.plus({ days: tip.day }).set({ hour: 9, minute: 0, second: 0 }).toISO();++ if (!scheduledAt) continue;++ const emailId = await scheduleOnboardingTipEmail(email, name || "", tip, scheduledAt);++ if (emailId) {+ emailIds.push(emailId);+ }+ }++ return emailIds;+ }++ /**+ * Cancel all scheduled tip emails for a user+ */+ async cancelScheduledEmails(emailIds: string[]): Promise<void> {+ for (const emailId of emailIds) {+ await cancelScheduledEmail(emailId);+ }+ }+}++export const onboardingTipsService = new OnboardingTipsService();diff --git a/server/src/services/reengagement/reengagementContent.ts b/server/src/services/reengagement/reengagementContent.tsnew file mode 100644index 000000000..2a74002fb--- /dev/null+++ b/server/src/services/reengagement/reengagementContent.ts@@ -0,0 +1,34 @@+export interface ReengagementContent {+ day: number;+ subject: string;+ title: string;+ message: string;+ ctaText: string;+}++export const REENGAGEMENT_EMAILS: Record<number, ReengagementContent> = {+ 3: {+ day: 3,+ subject: "Need help getting started with Rybbit?",+ title: "We noticed you haven't added your tracking script yet",+ message:+ "It looks like we haven't received any data from {domain} yet. Adding Rybbit is quick and easy - just one line of code. If you're running into any issues or have questions, just reply to this email and we'll help you get set up.",+ ctaText: "Go to Dashboard",+ },+ 7: {+ day: 7,+ subject: "Your Rybbit analytics are waiting",+ title: "It's been a week - let's get you started",+ message:+ "You signed up for Rybbit a week ago but we still haven't received any analytics data for {domain}. We'd hate for you to miss out on understanding your website traffic. Need help with installation? Our setup takes less than 5 minutes.",+ ctaText: "Go to Dashboard",+ },+ 14: {+ day: 14,+ subject: "Last chance: Start tracking your analytics",+ title: "We're here to help",+ message:+ "It's been two weeks since you signed up and we haven't seen any data from {domain}. If you're having trouble with the setup or if Rybbit isn't the right fit, we'd love to know. Reply to this email and let us know how we can help.",+ ctaText: "Go to Dashboard",+ },+};diff --git a/server/src/services/reengagement/reengagementService.ts b/server/src/services/reengagement/reengagementService.tsnew file mode 100644index 000000000..99292f990--- /dev/null+++ b/server/src/services/reengagement/reengagementService.ts@@ -0,0 +1,186 @@+import { and, between, eq, inArray } from "drizzle-orm";+import { DateTime } from "luxon";+import * as cron from "node-cron";+import { clickhouse } from "../../db/clickhouse/clickhouse.js";+import { db } from "../../db/postgres/postgres.js";+import { member, sites, user } from "../../db/postgres/schema.js";+import { IS_CLOUD } from "../../lib/const.js";+import { isContactUnsubscribed, sendReengagementEmail } from "../../lib/email/email.js";+import { createServiceLogger } from "../../lib/logger/logger.js";+import { REENGAGEMENT_EMAILS } from "./reengagementContent.js";++class ReengagementService {+ private cronTask: cron.ScheduledTask | null = null;+ private logger = createServiceLogger("reengagement");++ constructor() {}++ /**+ * Get a site for reengagement email+ * Only returns a siteId if ALL sites have no events (user hasn't started tracking at all)+ */+ private async getSiteWithoutEvents(+ userId: string+ ): Promise<{ hasEvents: boolean; siteId: number | null; domain: string | null }> {+ try {+ // Find organizations where the user is an owner+ const userOrgs = await db+ .select({ organizationId: member.organizationId })+ .from(member)+ .where(and(eq(member.userId, userId), eq(member.role, "owner")));++ if (userOrgs.length === 0) {+ return { hasEvents: false, siteId: null, domain: null };+ }++ const orgIds = userOrgs.map(o => o.organizationId);++ // Find sites belonging to these organizations+ const userSites = await db+ .select({ siteId: sites.siteId, domain: sites.domain })+ .from(sites)+ .where(inArray(sites.organizationId, orgIds));++ if (userSites.length === 0) {+ return { hasEvents: false, siteId: null, domain: null };+ }++ const siteIds = userSites.map(s => s.siteId);++ // Check if ANY site has events+ const result = await clickhouse.query({+ query: `+ SELECT 1 FROM events+ WHERE site_id IN ({siteIds:Array(Int32)})+ LIMIT 1+ `,+ format: "JSONEachRow",+ query_params: {+ siteIds,+ },+ });++ const data = await result.json<{ 1: number }>();++ // If any site has events, don't send reengagement email+ if (data.length > 0) {+ return { hasEvents: true, siteId: null, domain: null };+ }++ // No sites have events - return the first site for the dashboard link+ return { hasEvents: false, siteId: userSites[0].siteId, domain: userSites[0].domain };+ } catch (error) {+ this.logger.error({ error, userId }, "Error checking user sites for events");+ return { hasEvents: true, siteId: null, domain: null }; // On error, assume they have events (don't send email)+ }+ }++ /**+ * Process re-engagement emails for a specific day+ */+ private async processDay(targetDay: 3 | 7 | 14): Promise<void> {+ const now = DateTime.utc();+ const content = REENGAGEMENT_EMAILS[targetDay];++ if (!content) {+ this.logger.error({ targetDay }, "No content found for target day");+ return;+ }++ // Find users who signed up exactly targetDay days ago+ const targetStart = now.minus({ days: targetDay }).startOf("day");+ const targetEnd = targetStart.endOf("day");++ try {+ const users = await db+ .select({+ id: user.id,+ email: user.email,+ name: user.name,+ })+ .from(user)+ .where(and(between(user.createdAt, targetStart.toSQL()!, targetEnd.toSQL()!)));++ this.logger.info({ targetDay, userCount: users.length }, "Processing re-engagement emails");++ for (const userData of users) {+ // Check if user has a site without events+ const { hasEvents, siteId, domain } = await this.getSiteWithoutEvents(userData.id);+ if (hasEvents) {+ this.logger.debug({ userId: userData.id }, "User has events, skipping");+ continue;+ }++ if (!siteId || !domain) {+ this.logger.debug({ userId: userData.id }, "User has no sites, skipping");+ continue;+ }++ // Check if contact is unsubscribed+ const unsubscribed = await isContactUnsubscribed(userData.email);+ if (unsubscribed) {+ this.logger.debug({ userId: userData.id }, "User is unsubscribed, skipping");+ continue;+ }++ // Send re-engagement email+ await sendReengagementEmail(userData.email, userData.name, content, siteId, domain);+ this.logger.info({ userId: userData.id, day: targetDay, siteId, domain }, "Sent re-engagement email");+ break;+ }+ } catch (error) {+ this.logger.error({ error, targetDay }, "Error processing re-engagement emails");+ }+ }++ /**+ * Process all re-engagement emails (days 3, 7, 14)+ */+ async processReengagementEmails(): Promise<void> {+ this.logger.info("Starting re-engagement email processing");++ await this.processDay(3);+ await this.processDay(7);+ await this.processDay(14);++ this.logger.info("Completed re-engagement email processing");+ }++ /**+ * Start the daily cron job (10am UTC)+ */+ startReengagementCron(): void {+ if (!IS_CLOUD) {+ return;+ }++ if (this.cronTask) {+ this.logger.warn("Re-engagement cron already running");+ return;+ }++ // Run daily at 10am UTC+ this.cronTask = cron.schedule(+ "0 10 * * *",+ async () => {+ await this.processReengagementEmails();+ },+ { timezone: "UTC" }+ );++ this.logger.info("Re-engagement cron started - runs daily at 10am UTC");+ }++ /**+ * Stop the cron job+ */+ stopReengagementCron(): void {+ if (this.cronTask) {+ this.cronTask.stop();+ this.cronTask = null;+ this.logger.info("Re-engagement cron stopped");+ }+ }+}++export const reengagementService = new ReengagementService();diff --git a/server/src/services/tracker/identifyService.ts b/server/src/services/tracker/identifyService.tsindex 2e5ae6e3e..49e3c2a8c 100644--- a/server/src/services/tracker/identifyService.ts+++ b/server/src/services/tracker/identifyService.ts@@ -21,7 +21,7 @@ const identifyPayloadSchema = z.object({.record(z.unknown()).optional().refine(- (traits) => {+ traits => {if (!traits) return true;const size = new TextEncoder().encode(JSON.stringify(traits)).length;return size <= MAX_TRAITS_SIZE;@@ -78,8 +78,6 @@ export async function handleIdentify(request: FastifyRequest, reply: FastifyReplanonymousId,userId: user_id,});-- logger.info({ siteId, anonymousId, userId: user_id }, "Created new user alias");} else if (existingAlias[0].userId !== user_id) {// Anonymous ID already linked to a different user - log but don't errorlogger.warn(@@ -114,9 +112,7 @@ export async function handleIdentify(request: FastifyRequest, reply: FastifyRepl...((existingProfile[0].traits as Record<string, unknown>) || {}),...traits,};- const mergedTraits = Object.fromEntries(- Object.entries(merged).filter(([_, value]) => value !== null)- );+ const mergedTraits = Object.fromEntries(Object.entries(merged).filter(([_, value]) => value !== null));await db.update(userProfiles)@@ -125,20 +121,14 @@ export async function handleIdentify(request: FastifyRequest, reply: FastifyReplupdatedAt: new Date().toISOString(),}).where(and(eq(userProfiles.siteId, siteId), eq(userProfiles.userId, user_id)));-- logger.info({ siteId, userId: user_id }, "Updated user profile traits");} else {// Create new profile (filter out null values)- const filteredTraits = Object.fromEntries(- Object.entries(traits).filter(([_, value]) => value !== null)- );+ const filteredTraits = Object.fromEntries(Object.entries(traits).filter(([_, value]) => value !== null));await db.insert(userProfiles).values({siteId,userId: user_id,traits: filteredTraits,});-- logger.info({ siteId, userId: user_id }, "Created new user profile");}} catch (error) {logger.error({ siteId, userId: user_id, error }, "Error updating user profile");diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex 034ec6442..0986c6e9f 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -7,6 +7,7 @@ import { sessionsService } from "../sessions/sessionsService.js";import { usageService } from "../usageService.js";import { pageviewQueue } from "./pageviewQueue.js";import { createBasePayload } from "./utils.js";+import { getLocation } from "../../db/geolocation/geolocation.js";// Define Zod schema for validationexport const trackingPayloadSchema = z.discriminatedUnion("type", [@@ -257,7 +258,6 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {// Check if the country should be excluded from trackingif (siteConfiguration.excludedCountries && siteConfiguration.excludedCountries.length > 0) {- const { getLocation } = await import("../../db/geolocation/geolocation.js");const locationResults = await getLocation([requestIP]);const locationData = locationResults[requestIP];diff --git a/server/src/services/usageService.ts b/server/src/services/usageService.tsindex 9ae162471..e8d2e194c 100644--- a/server/src/services/usageService.ts+++ b/server/src/services/usageService.ts@@ -37,9 +37,6 @@ class UsageService {{ timezone: "UTC" });- // Run immediately on startup- this.updateOrganizationsMonthlyUsage();-this.logger.info("Monthly usage check cron initialized (runs every 30 minutes)");}}