From 5ff3ea56fb04055ab52caabac031c5a26f8463ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Wed, 25 Nov 2026 09:29:58 +0100 Subject: [PATCH 1/2] feat: add RevenueCat as a revenue source --- drizzle/0008_revenuecat.sql | 34 + drizzle/meta/0008_snapshot.json | 2281 +++++++++++++++++ drizzle/meta/_journal.json | 7 + src/app/(product)/app/accounts/actions.ts | 81 +- src/app/(product)/app/accounts/new/page.tsx | 190 +- src/app/(product)/app/accounts/page.tsx | 18 +- src/app/(product)/app/page.tsx | 4 +- .../webhooks/revenuecat/[accountId]/route.ts | 75 + .../app/accounts/account-actions.tsx | 25 +- src/components/app/accounts/account-card.tsx | 45 +- .../app/accounts/account-status.tsx | 37 +- .../app/accounts/accounts-overview.tsx | 9 +- .../app/accounts/connect-revenuecat-form.tsx | 179 ++ .../app/accounts/instant-updates.tsx | 49 +- .../accounts/revenuecat-key-permissions.tsx | 59 + src/components/app/app-nav.tsx | 2 +- src/components/app/home/setup-guide.tsx | 33 +- .../app/screens/editor/account-picker.tsx | 7 +- src/db/schema/app.ts | 71 +- src/lib/account-providers.ts | 7 + src/lib/revenuecat-permissions.ts | 61 + src/server/display/previews.test.ts | 2 +- src/server/display/queries.ts | 593 ++++- src/server/revenuecat/accounts.ts | 221 ++ src/server/revenuecat/charts.test.ts | 155 ++ src/server/revenuecat/charts.ts | 388 +++ src/server/revenuecat/errors.test.ts | 33 + src/server/revenuecat/errors.ts | 57 + src/server/revenuecat/gateway.ts | 331 +++ src/server/revenuecat/keys.test.ts | 54 + src/server/revenuecat/keys.ts | 59 + src/server/revenuecat/sync.db.test.ts | 205 ++ src/server/revenuecat/sync.ts | 318 +++ src/server/revenuecat/types.ts | 70 + src/server/revenuecat/webhooks.test.ts | 114 + src/server/revenuecat/webhooks.ts | 901 +++++++ src/server/screens.ts | 5 +- src/server/stripe/accounts.ts | 134 +- src/server/sync/index.ts | 1 + src/server/sync/policy.ts | 11 +- src/server/sync/run.ts | 11 + src/server/sync/state.ts | 2 + 42 files changed, 6642 insertions(+), 297 deletions(-) create mode 100644 drizzle/0008_revenuecat.sql create mode 100644 drizzle/meta/0008_snapshot.json create mode 100644 src/app/api/webhooks/revenuecat/[accountId]/route.ts create mode 100644 src/components/app/accounts/connect-revenuecat-form.tsx create mode 100644 src/components/app/accounts/revenuecat-key-permissions.tsx create mode 100644 src/lib/account-providers.ts create mode 100644 src/lib/revenuecat-permissions.ts create mode 100644 src/server/revenuecat/accounts.ts create mode 100644 src/server/revenuecat/charts.test.ts create mode 100644 src/server/revenuecat/charts.ts create mode 100644 src/server/revenuecat/errors.test.ts create mode 100644 src/server/revenuecat/errors.ts create mode 100644 src/server/revenuecat/gateway.ts create mode 100644 src/server/revenuecat/keys.test.ts create mode 100644 src/server/revenuecat/keys.ts create mode 100644 src/server/revenuecat/sync.db.test.ts create mode 100644 src/server/revenuecat/sync.ts create mode 100644 src/server/revenuecat/types.ts create mode 100644 src/server/revenuecat/webhooks.test.ts create mode 100644 src/server/revenuecat/webhooks.ts diff --git a/drizzle/0008_revenuecat.sql b/drizzle/0008_revenuecat.sql new file mode 100644 index 0000000..60935b5 --- /dev/null +++ b/drizzle/0008_revenuecat.sql @@ -0,0 +1,34 @@ +CREATE TABLE `revenuecat_daily_metrics` ( + `account_id` varchar(36) character set ascii collate ascii_bin NOT NULL, + `day` varchar(10) character set ascii collate ascii_bin NOT NULL, + `currency` varchar(3) NOT NULL, + `revenue` bigint NOT NULL DEFAULT 0, + `mrr_new` bigint NOT NULL DEFAULT 0, + `mrr_expansion` bigint NOT NULL DEFAULT 0, + `mrr_reactivation` bigint NOT NULL DEFAULT 0, + `mrr_contraction` bigint NOT NULL DEFAULT 0, + `mrr_churn` bigint NOT NULL DEFAULT 0, + `new_paying_customers` int NOT NULL DEFAULT 0, + `new_customers` int NOT NULL DEFAULT 0, + CONSTRAINT `revenuecat_daily_metrics_account_id_day_pk` PRIMARY KEY(`account_id`,`day`) +); +--> statement-breakpoint +CREATE TABLE `revenuecat_metrics` ( + `account_id` varchar(36) character set ascii collate ascii_bin NOT NULL, + `currency` varchar(3) NOT NULL, + `mrr` bigint NOT NULL, + `active_subscriptions` int NOT NULL DEFAULT 0, + `active_trials` int NOT NULL DEFAULT 0, + `overview_updated_at` datetime(6) NOT NULL, + `products` json NOT NULL DEFAULT ('{}'), + `created_at` datetime(6) NOT NULL DEFAULT (now(6)), + `updated_at` datetime(6) NOT NULL DEFAULT (now(6)), + CONSTRAINT `revenuecat_metrics_account_id` PRIMARY KEY(`account_id`) +); +--> statement-breakpoint +ALTER TABLE `stripe_accounts` DROP INDEX `stripe_accounts_workspace_id_stripe_account_id_livemode_index`;--> statement-breakpoint +ALTER TABLE `stripe_accounts` ADD `provider` enum('stripe','revenuecat') DEFAULT 'stripe' NOT NULL;--> statement-breakpoint +ALTER TABLE `stripe_accounts` ADD CONSTRAINT `stripe_accounts_workspace_id_stripe_account_id_livemode_index` UNIQUE(`workspace_id`,`provider`,`stripe_account_id`,`livemode`);--> statement-breakpoint +ALTER TABLE `revenuecat_daily_metrics` ADD CONSTRAINT `revenuecat_daily_metrics_account_id_stripe_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `stripe_accounts`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE `revenuecat_metrics` ADD CONSTRAINT `revenuecat_metrics_account_id_stripe_accounts_id_fk` FOREIGN KEY (`account_id`) REFERENCES `stripe_accounts`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX `revenuecat_daily_metrics_account_id_day_index` ON `revenuecat_daily_metrics` (`account_id`,`day`); \ No newline at end of file diff --git a/drizzle/meta/0008_snapshot.json b/drizzle/meta/0008_snapshot.json new file mode 100644 index 0000000..474eaaa --- /dev/null +++ b/drizzle/meta/0008_snapshot.json @@ -0,0 +1,2281 @@ +{ + "version": "5", + "dialect": "mysql", + "id": "c0861335-da4a-4cee-8670-0ff06f454dc0", + "prevId": "7d6d6b6e-a7eb-43e3-abe3-d189fcfda979", + "tables": { + "customers": { + "name": "customers", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "country": { + "name": "country", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "enum('backfill','live','reconcile')", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notified_at": { + "name": "notified_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "customers_account_id_stripe_customer_id_index": { + "name": "customers_account_id_stripe_customer_id_index", + "columns": [ + "account_id", + "stripe_customer_id" + ], + "isUnique": true + }, + "customers_account_id_occurred_at_index": { + "name": "customers_account_id_occurred_at_index", + "columns": [ + "account_id", + "occurred_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "customers_account_id_stripe_accounts_id_fk": { + "name": "customers_account_id_stripe_accounts_id_fk", + "tableFrom": "customers", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "customers_id": { + "name": "customers_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "exchange_rates": { + "name": "exchange_rates", + "columns": { + "base": { + "name": "base", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rates": { + "name": "rates", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "fetched_at": { + "name": "fetched_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "exchange_rates_base": { + "name": "exchange_rates_base", + "columns": [ + "base" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mrr_movements": { + "name": "mrr_movements", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "customer_name": { + "name": "customer_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_country": { + "name": "customer_country", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "plan_name": { + "name": "plan_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "enum('new','expansion','reactivation','contraction','churn')", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "churn_reason": { + "name": "churn_reason", + "type": "enum('canceled','scheduled','unpaid','paused')", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ends_at": { + "name": "ends_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "amount": { + "name": "amount", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "currency": { + "name": "currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "enum('backfill','live','reconcile')", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notified_at": { + "name": "notified_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripe_event_id": { + "name": "stripe_event_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "mrr_movements_account_id_occurred_at_index": { + "name": "mrr_movements_account_id_occurred_at_index", + "columns": [ + "account_id", + "occurred_at" + ], + "isUnique": false + }, + "mrr_movements_account_id_stripe_subscription_id_index": { + "name": "mrr_movements_account_id_stripe_subscription_id_index", + "columns": [ + "account_id", + "stripe_subscription_id" + ], + "isUnique": false + }, + "mrr_movements_account_id_stripe_customer_id_index": { + "name": "mrr_movements_account_id_stripe_customer_id_index", + "columns": [ + "account_id", + "stripe_customer_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "mrr_movements_account_id_stripe_accounts_id_fk": { + "name": "mrr_movements_account_id_stripe_accounts_id_fk", + "tableFrom": "mrr_movements", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "mrr_movements_id": { + "name": "mrr_movements_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "payments": { + "name": "payments", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_charge_id": { + "name": "stripe_charge_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_name": { + "name": "customer_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_email": { + "name": "customer_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_country": { + "name": "customer_country", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "amount": { + "name": "amount", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "amount_refunded": { + "name": "amount_refunded", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "currency": { + "name": "currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "connected_account_id": { + "name": "connected_account_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "application_fee": { + "name": "application_fee", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "enum('backfill','live','reconcile')", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "notified_at": { + "name": "notified_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "payments_account_id_stripe_charge_id_index": { + "name": "payments_account_id_stripe_charge_id_index", + "columns": [ + "account_id", + "stripe_charge_id" + ], + "isUnique": true + }, + "payments_account_id_occurred_at_index": { + "name": "payments_account_id_occurred_at_index", + "columns": [ + "account_id", + "occurred_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "payments_account_id_stripe_accounts_id_fk": { + "name": "payments_account_id_stripe_accounts_id_fk", + "tableFrom": "payments", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "payments_id": { + "name": "payments_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "push_devices": { + "name": "push_devices", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "screen_id": { + "name": "screen_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installation_id": { + "name": "installation_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "enum('ios','android')", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "push_token": { + "name": "push_token", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "device_token": { + "name": "device_token", + "type": "varchar(512) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "apns_environment": { + "name": "apns_environment", + "type": "enum('development','production')", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "locale": { + "name": "locale", + "type": "varchar(35)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "muted_events": { + "name": "muted_events", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('[]')" + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "push_devices_screen_id_installation_id_index": { + "name": "push_devices_screen_id_installation_id_index", + "columns": [ + "screen_id", + "installation_id" + ], + "isUnique": true + }, + "push_devices_push_token_index": { + "name": "push_devices_push_token_index", + "columns": [ + "push_token" + ], + "isUnique": false + }, + "push_devices_device_token_index": { + "name": "push_devices_device_token_index", + "columns": [ + "device_token" + ], + "isUnique": false + } + }, + "foreignKeys": { + "push_devices_screen_id_screens_id_fk": { + "name": "push_devices_screen_id_screens_id_fk", + "tableFrom": "push_devices", + "tableTo": "screens", + "columnsFrom": [ + "screen_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "push_devices_id": { + "name": "push_devices_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "push_milestones": { + "name": "push_milestones", + "columns": { + "screen_id": { + "name": "screen_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "milestone": { + "name": "milestone", + "type": "varchar(100) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": {}, + "foreignKeys": { + "push_milestones_screen_id_screens_id_fk": { + "name": "push_milestones_screen_id_screens_id_fk", + "tableFrom": "push_milestones", + "tableTo": "screens", + "columnsFrom": [ + "screen_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "push_milestones_screen_id_milestone_pk": { + "name": "push_milestones_screen_id_milestone_pk", + "columns": [ + "screen_id", + "milestone" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "revenuecat_daily_metrics": { + "name": "revenuecat_daily_metrics", + "columns": { + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "varchar(10) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "currency": { + "name": "currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revenue": { + "name": "revenue", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "mrr_new": { + "name": "mrr_new", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "mrr_expansion": { + "name": "mrr_expansion", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "mrr_reactivation": { + "name": "mrr_reactivation", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "mrr_contraction": { + "name": "mrr_contraction", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "mrr_churn": { + "name": "mrr_churn", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "new_paying_customers": { + "name": "new_paying_customers", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "new_customers": { + "name": "new_customers", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "revenuecat_daily_metrics_account_id_day_index": { + "name": "revenuecat_daily_metrics_account_id_day_index", + "columns": [ + "account_id", + "day" + ], + "isUnique": false + } + }, + "foreignKeys": { + "revenuecat_daily_metrics_account_id_stripe_accounts_id_fk": { + "name": "revenuecat_daily_metrics_account_id_stripe_accounts_id_fk", + "tableFrom": "revenuecat_daily_metrics", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "revenuecat_daily_metrics_account_id_day_pk": { + "name": "revenuecat_daily_metrics_account_id_day_pk", + "columns": [ + "account_id", + "day" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "revenuecat_metrics": { + "name": "revenuecat_metrics", + "columns": { + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "currency": { + "name": "currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mrr": { + "name": "mrr", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "active_subscriptions": { + "name": "active_subscriptions", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "active_trials": { + "name": "active_trials", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "overview_updated_at": { + "name": "overview_updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "products": { + "name": "products", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('{}')" + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": {}, + "foreignKeys": { + "revenuecat_metrics_account_id_stripe_accounts_id_fk": { + "name": "revenuecat_metrics_account_id_stripe_accounts_id_fk", + "tableFrom": "revenuecat_metrics", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "revenuecat_metrics_account_id": { + "name": "revenuecat_metrics_account_id", + "columns": [ + "account_id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "screen_accounts": { + "name": "screen_accounts", + "columns": { + "screen_id": { + "name": "screen_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "screen_accounts_screen_id_screens_id_fk": { + "name": "screen_accounts_screen_id_screens_id_fk", + "tableFrom": "screen_accounts", + "tableTo": "screens", + "columnsFrom": [ + "screen_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "screen_accounts_account_id_stripe_accounts_id_fk": { + "name": "screen_accounts_account_id_stripe_accounts_id_fk", + "tableFrom": "screen_accounts", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "screen_accounts_screen_id_account_id_pk": { + "name": "screen_accounts_screen_id_account_id_pk", + "columns": [ + "screen_id", + "account_id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "screens": { + "name": "screens", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "public_token": { + "name": "public_token", + "type": "varchar(64) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "test_event_at": { + "name": "test_event_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "screens_workspace_id_index": { + "name": "screens_workspace_id_index", + "columns": [ + "workspace_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "screens_workspace_id_organizations_id_fk": { + "name": "screens_workspace_id_organizations_id_fk", + "tableFrom": "screens", + "tableTo": "organizations", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "screens_id": { + "name": "screens_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": { + "screens_publicToken_unique": { + "name": "screens_publicToken_unique", + "columns": [ + "public_token" + ] + } + }, + "checkConstraint": {} + }, + "stripe_accounts": { + "name": "stripe_accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "enum('stripe','revenuecat')", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'stripe'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_account_id": { + "name": "stripe_account_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "livemode": { + "name": "livemode", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encrypted_secret_key": { + "name": "encrypted_secret_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_key_hint": { + "name": "secret_key_hint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_currency": { + "name": "default_currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "enum('importing','ready','error')", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'importing'" + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "backfill": { + "name": "backfill", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reconcile": { + "name": "reconcile", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events_cursor": { + "name": "events_cursor", + "type": "bigint", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "recent_event_ids": { + "name": "recent_event_ids", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('[]')" + }, + "last_event_at": { + "name": "last_event_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_synced_at": { + "name": "last_synced_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_reconciled_at": { + "name": "last_reconciled_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sync_locked_until": { + "name": "sync_locked_until", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sync_failures": { + "name": "sync_failures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "sync_requested_at": { + "name": "sync_requested_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_endpoint_id": { + "name": "webhook_endpoint_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "encrypted_webhook_secret": { + "name": "encrypted_webhook_secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_webhook_at": { + "name": "last_webhook_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "stripe_accounts_workspace_id_index": { + "name": "stripe_accounts_workspace_id_index", + "columns": [ + "workspace_id" + ], + "isUnique": false + }, + "stripe_accounts_workspace_id_stripe_account_id_livemode_index": { + "name": "stripe_accounts_workspace_id_stripe_account_id_livemode_index", + "columns": [ + "workspace_id", + "provider", + "stripe_account_id", + "livemode" + ], + "isUnique": true + } + }, + "foreignKeys": { + "stripe_accounts_workspace_id_organizations_id_fk": { + "name": "stripe_accounts_workspace_id_organizations_id_fk", + "tableFrom": "stripe_accounts", + "tableTo": "organizations", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "stripe_accounts_id": { + "name": "stripe_accounts_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "stripe_coupons": { + "name": "stripe_coupons", + "columns": { + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "coupon_id": { + "name": "coupon_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "terms": { + "name": "terms", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": {}, + "foreignKeys": { + "stripe_coupons_account_id_stripe_accounts_id_fk": { + "name": "stripe_coupons_account_id_stripe_accounts_id_fk", + "tableFrom": "stripe_coupons", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "stripe_coupons_account_id_coupon_id_pk": { + "name": "stripe_coupons_account_id_coupon_id_pk", + "columns": [ + "account_id", + "coupon_id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_subscription_id": { + "name": "stripe_subscription_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripe_customer_id": { + "name": "stripe_customer_id", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "customer_name": { + "name": "customer_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_email": { + "name": "customer_email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customer_country": { + "name": "customer_country", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "currency": { + "name": "currency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mrr": { + "name": "mrr", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "plan_name": { + "name": "plan_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "billing_interval": { + "name": "billing_interval", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trial_ends_at": { + "name": "trial_ends_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "canceled_at": { + "name": "canceled_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_at_period_end": { + "name": "cancel_at_period_end", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "subscriptions_account_id_stripe_subscription_id_index": { + "name": "subscriptions_account_id_stripe_subscription_id_index", + "columns": [ + "account_id", + "stripe_subscription_id" + ], + "isUnique": true + }, + "subscriptions_account_id_stripe_customer_id_index": { + "name": "subscriptions_account_id_stripe_customer_id_index", + "columns": [ + "account_id", + "stripe_customer_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "subscriptions_account_id_stripe_accounts_id_fk": { + "name": "subscriptions_account_id_stripe_accounts_id_fk", + "tableFrom": "subscriptions", + "tableTo": "stripe_accounts", + "columnsFrom": [ + "account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscriptions_id": { + "name": "subscriptions_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "accounts": { + "name": "accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "accounts_userId_idx": { + "name": "accounts_userId_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "accounts_user_id_users_id_fk": { + "name": "accounts_user_id_users_id_fk", + "tableFrom": "accounts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "accounts_id": { + "name": "accounts_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "invitations": { + "name": "invitations", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "expires_at": { + "name": "expires_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "inviter_id": { + "name": "inviter_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "invitations_organizationId_idx": { + "name": "invitations_organizationId_idx", + "columns": [ + "organization_id" + ], + "isUnique": false + }, + "invitations_email_idx": { + "name": "invitations_email_idx", + "columns": [ + "email" + ], + "isUnique": false + } + }, + "foreignKeys": { + "invitations_organization_id_organizations_id_fk": { + "name": "invitations_organization_id_organizations_id_fk", + "tableFrom": "invitations", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitations_inviter_id_users_id_fk": { + "name": "invitations_inviter_id_users_id_fk", + "tableFrom": "invitations", + "tableTo": "users", + "columnsFrom": [ + "inviter_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "invitations_id": { + "name": "invitations_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "members": { + "name": "members", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organization_id": { + "name": "organization_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "members_organizationId_idx": { + "name": "members_organizationId_idx", + "columns": [ + "organization_id" + ], + "isUnique": false + }, + "members_userId_idx": { + "name": "members_userId_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "members_organization_id_organizations_id_fk": { + "name": "members_organization_id_organizations_id_fk", + "tableFrom": "members", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "members_user_id_users_id_fk": { + "name": "members_user_id_users_id_fk", + "tableFrom": "members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "members_id": { + "name": "members_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organizations": { + "name": "organizations", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organizations_id": { + "name": "organizations_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": { + "organizations_slug_unique": { + "name": "organizations_slug_unique", + "columns": [ + "slug" + ] + } + }, + "checkConstraint": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "varchar(255) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_userId_idx": { + "name": "sessions_userId_idx", + "columns": [ + "user_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sessions_id": { + "name": "sessions_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": { + "sessions_token_unique": { + "name": "sessions_token_unique", + "columns": [ + "token" + ] + } + }, + "checkConstraint": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "users_id": { + "name": "users_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "columns": [ + "email" + ] + } + }, + "checkConstraint": {} + }, + "verifications": { + "name": "verifications", + "columns": { + "id": { + "name": "id", + "type": "varchar(36) character set ascii collate ascii_bin", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "identifier": { + "name": "identifier", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now(6))" + } + }, + "indexes": { + "verifications_identifier_idx": { + "name": "verifications_identifier_idx", + "columns": [ + "identifier" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "verifications_id": { + "name": "verifications_id", + "columns": [ + "id" + ] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + } + }, + "views": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "tables": {}, + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 01c99df..8f2240b 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -57,6 +57,13 @@ "when": 1791231876134, "tag": "0007_push_device_installations", "breakpoints": true + }, + { + "idx": 8, + "version": "5", + "when": 1795593875156, + "tag": "0008_revenuecat", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(product)/app/accounts/actions.ts b/src/app/(product)/app/accounts/actions.ts index 59466c4..28c3c17 100644 --- a/src/app/(product)/app/accounts/actions.ts +++ b/src/app/(product)/app/accounts/actions.ts @@ -1,9 +1,18 @@ "use server"; +import { and, eq } from "drizzle-orm"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { z } from "zod"; +import { db } from "@/db"; +import { stripeAccounts } from "@/db/schema"; import { invalidInput, type ActionResult } from "@/lib/action-result"; +import { connectRevenueCatAccount, connectRevenueCatSchema } from "@/server/revenuecat/accounts"; +import { + enableRevenueCatInstantUpdates, + revenueCatWebhookSecretSchema, + setRevenueCatWebhookSecret, +} from "@/server/revenuecat/webhooks"; import { createFirstScreen } from "@/server/screens"; import { requireWorkspace } from "@/server/session"; import { @@ -15,6 +24,7 @@ import { renameStripeAccount, type MissingPermissions, } from "@/server/stripe/accounts"; +import { ACCOUNT_NOT_FOUND } from "@/server/stripe/errors"; import { enableInstantUpdates, setWebhookSigningSecret, @@ -28,6 +38,11 @@ const connectSchema = connectAccountSchema.extend({ timeZone: z.string().max(100), }); +const connectRevenueCatActionSchema = connectRevenueCatSchema.extend({ + /** The browser's time zone, for the screen created with the first account. */ + timeZone: z.string().max(100), +}); + export async function connectAccountAction( input: z.input, ): Promise> { @@ -49,6 +64,30 @@ export async function connectAccountAction( redirect(firstScreenId ? "/app?onboarding=1" : "/app/accounts"); } +export async function connectRevenueCatAccountAction( + input: z.input, +): Promise> { + const { workspace } = await requireWorkspace(); + const parsed = connectRevenueCatActionSchema.safeParse(input); + if (!parsed.success) return invalidInput(parsed.error); + const { name, secretKey, projectId, timeZone } = parsed.data; + + const result = await connectRevenueCatAccount({ + workspaceId: workspace.id, + name, + secretKey, + projectId, + }); + if (!result.ok) return result; + + const firstScreenId = await createFirstScreen(workspace.id, { + accountId: result.accountId, + timeZone, + }); + revalidatePath("/app", "layout"); + redirect(firstScreenId ? "/app?onboarding=1" : "/app/accounts"); +} + export async function renameAccountAction(accountId: string, name: string): Promise { const { workspace } = await requireWorkspace(); const parsed = z.object({ accountId: accountIdSchema, name: accountNameSchema }).safeParse({ @@ -87,7 +126,16 @@ export async function enableInstantUpdatesAction(accountId: string): Promise { const { workspace } = await requireWorkspace(); - const parsed = z - .object({ accountId: accountIdSchema, secret: webhookSigningSecretSchema }) - .safeParse({ accountId, secret }); - if (!parsed.success) return invalidInput(parsed.error); - - const result = await setWebhookSigningSecret( - workspace.id, - parsed.data.accountId, - parsed.data.secret, - ); + const parsedId = accountIdSchema.safeParse(accountId); + if (!parsedId.success) return invalidInput(parsedId.error); + + const [account] = await db() + .select({ provider: stripeAccounts.provider }) + .from(stripeAccounts) + .where(and(eq(stripeAccounts.workspaceId, workspace.id), eq(stripeAccounts.id, parsedId.data))); + if (!account) return ACCOUNT_NOT_FOUND; + + if (account.provider === "revenuecat") { + const parsedSecret = revenueCatWebhookSecretSchema.safeParse(secret); + if (!parsedSecret.success) return invalidInput(parsedSecret.error); + const result = await setRevenueCatWebhookSecret(workspace.id, parsedId.data, parsedSecret.data); + if (result.ok) revalidatePath("/app", "layout"); + return result; + } + + const parsedSecret = webhookSigningSecretSchema.safeParse(secret); + if (!parsedSecret.success) return invalidInput(parsedSecret.error); + + const result = await setWebhookSigningSecret(workspace.id, parsedId.data, parsedSecret.data); if (result.ok) revalidatePath("/app", "layout"); return result; } diff --git a/src/app/(product)/app/accounts/new/page.tsx b/src/app/(product)/app/accounts/new/page.tsx index 95774bf..f01f4cf 100644 --- a/src/app/(product)/app/accounts/new/page.tsx +++ b/src/app/(product)/app/accounts/new/page.tsx @@ -1,75 +1,169 @@ import { ArrowUpRightIcon } from "lucide-react"; import type { Metadata } from "next"; +import Link from "next/link"; import { ConnectAccountForm } from "@/components/app/accounts/connect-account-form"; +import { ConnectRevenueCatForm } from "@/components/app/accounts/connect-revenuecat-form"; import { ConnectStep } from "@/components/app/accounts/connect-step"; import { KeyPermissions } from "@/components/app/accounts/key-permissions"; +import { RevenueCatKeyPermissions } from "@/components/app/accounts/revenuecat-key-permissions"; import { BackLink } from "@/components/app/back-link"; import { PageHeader } from "@/components/app/page-header"; import { Button } from "@/components/ui/button"; +import type { AccountProvider } from "@/lib/account-providers"; +import { REVENUECAT_DASHBOARD_URL } from "@/lib/revenuecat-permissions"; import { siteConfig } from "@/lib/site"; import { restrictedKeyCreationUrl } from "@/lib/stripe-permissions"; +import { cn } from "@/lib/utils"; -export const metadata: Metadata = { title: "Connect Stripe" }; +export const metadata: Metadata = { title: "Connect account" }; -export default function ConnectAccountPage() { +const PROVIDERS: readonly { id: AccountProvider; name: string; summary: string }[] = [ + { id: "stripe", name: "Stripe", summary: "Web subscriptions, invoices & charges" }, + { + id: "revenuecat", + name: "RevenueCat", + summary: "App Store, Google Play & mobile subscriptions", + }, +]; + +export default async function ConnectAccountPage({ searchParams }: PageProps<"/app/accounts/new">) { + const params = await searchParams; + const provider: AccountProvider = params.provider === "revenuecat" ? "revenuecat" : "stripe"; const keyUrl = restrictedKeyCreationUrl(siteConfig.name); const testKeyUrl = keyUrl.replace("dashboard.stripe.com/", "dashboard.stripe.com/test/"); return (
- Stripe accounts + Accounts - {/* On small screens the permissions sit between both steps, where they are needed. */} -
- -

- This opens Stripe with the right permissions selected. Check them against the list, then - click Create key. -

- -
+ {option.name} + {option.summary} + + ); + })} +
-
-
-

- Permissions -

+ {provider === "revenuecat" ? ( +
+

- Set these in Stripe and leave everything else on None. + Open your project in RevenueCat, go to{" "} + Project Settings › API keys, + click + New, pick{" "} + V2, and select the permissions + listed on the right.

-
- -
+ + - - - -
+
+
+

+ Permissions (API v2) +

+

+ Set these on your RevenueCat secret key and leave everything else unchecked. +

+
+ +
+ + + + + + ) : ( + /* On small screens the permissions sit between both steps, where they are needed. */ +
+ +

+ This opens Stripe with the right permissions selected. Check them against the list, + then click Create key. +

+ +
+ +
+
+

+ Permissions +

+

+ Set these in Stripe and leave everything else on None. +

+
+ +
+ + + + +
+ )} ); } diff --git a/src/app/(product)/app/accounts/page.tsx b/src/app/(product)/app/accounts/page.tsx index ab4bc23..22d349f 100644 --- a/src/app/(product)/app/accounts/page.tsx +++ b/src/app/(product)/app/accounts/page.tsx @@ -13,12 +13,13 @@ import { EmptyMedia, EmptyTitle, } from "@/components/ui/empty"; +import { revenueCatWebhookSetupInstructions } from "@/server/revenuecat/webhooks"; import { requireWorkspace } from "@/server/session"; import { listStripeAccountSummaries } from "@/server/stripe/accounts"; import { webhookSetupInstructions } from "@/server/stripe/webhooks"; import { scheduleSync } from "@/server/sync"; -export const metadata: Metadata = { title: "Stripe accounts" }; +export const metadata: Metadata = { title: "Accounts" }; export default async function AccountsPage() { const { workspace } = await requireWorkspace(); @@ -39,8 +40,8 @@ export default async function AccountsPage() { <> {importing && } 0 && connectButton} /> {accounts.length > 0 ? ( @@ -50,7 +51,11 @@ export default async function AccountsPage() { key={account.id} account={account} webhookInstructions={ - account.updates.mode === "polling" ? webhookSetupInstructions(account.id) : null + account.updates.mode === "polling" + ? account.provider === "revenuecat" + ? revenueCatWebhookSetupInstructions(account.id) + : webhookSetupInstructions(account.id) + : null } /> ))} @@ -61,9 +66,10 @@ export default async function AccountsPage() { - No Stripe account yet + No account connected yet - Connect one with a read-only key: your screens show its MRR, revenue and every sale. + Connect Stripe or RevenueCat with a read-only key: your screens show MRR, revenue and + every sale. {connectButton} diff --git a/src/app/(product)/app/page.tsx b/src/app/(product)/app/page.tsx index e2a9be3..bb463ae 100644 --- a/src/app/(product)/app/page.tsx +++ b/src/app/(product)/app/page.tsx @@ -61,7 +61,7 @@ export default async function HomePage({ searchParams }: PageProps<"/app">) { {refresh} } />
@@ -95,7 +95,7 @@ export default async function HomePage({ searchParams }: PageProps<"/app">) { )} Manage diff --git a/src/app/api/webhooks/revenuecat/[accountId]/route.ts b/src/app/api/webhooks/revenuecat/[accountId]/route.ts new file mode 100644 index 0000000..3024ea2 --- /dev/null +++ b/src/app/api/webhooks/revenuecat/[accountId]/route.ts @@ -0,0 +1,75 @@ +import { after } from "next/server"; +import { z } from "zod"; +import { notifyPhones } from "@/server/push/notify"; +import { receiveRevenueCatWebhook } from "@/server/revenuecat/webhooks"; +import { scheduleSync } from "@/server/sync"; + +/** RevenueCat webhook events are a few kilobytes; reject oversized payloads early. */ +const MAX_PAYLOAD_BYTES = 512 * 1024; + +/** + * RevenueCat calls this endpoint when a subscription or purchase event happens on a connected + * project. Live events are recorded immediately so wall screens and phones celebrate within + * seconds, then a sync keeps overview and chart aggregates aligned. + */ +export async function POST( + request: Request, + context: RouteContext<"/api/webhooks/revenuecat/[accountId]">, +) { + const accountId = z.uuid().safeParse((await context.params).accountId); + if (!accountId.success) return Response.json({ error: "Unknown account." }, { status: 404 }); + + const signature = request.headers.get("x-revenuecat-webhook-signature"); + const authorization = request.headers.get("authorization"); + if (!signature && !authorization) { + return Response.json({ error: "Invalid signature." }, { status: 401 }); + } + + const payload = await readBody(request, MAX_PAYLOAD_BYTES); + if (payload === null) return Response.json({ error: "Payload too large." }, { status: 413 }); + + const outcome = await receiveRevenueCatWebhook(accountId.data, payload, { + signature, + authorization, + }); + if (outcome.status === "unknown_account") { + return Response.json({ error: "Unknown account." }, { status: 404 }); + } + if (outcome.status === "invalid_signature") { + return Response.json({ error: "Invalid signature." }, { status: 401 }); + } + if (outcome.status === "invalid_payload") { + return Response.json({ error: "Invalid payload." }, { status: 400 }); + } + + if (outcome.notify) { + const id = accountId.data; + after(() => + notifyPhones(id).catch((error: unknown) => { + console.warn("[push] Could not notify phones after RevenueCat webhook:", error); + }), + ); + } + if (outcome.sync) { + scheduleSync([accountId.data]); + } + return Response.json({ received: true }); +} + +async function readBody(request: Request, maxBytes: number): Promise { + if (Number(request.headers.get("content-length") ?? 0) > maxBytes) return null; + if (!request.body) return ""; + + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) { + size += chunk.value.byteLength; + if (size > maxBytes) { + await reader.cancel(); + return null; + } + chunks.push(chunk.value); + } + return Buffer.concat(chunks).toString("utf8"); +} diff --git a/src/components/app/accounts/account-actions.tsx b/src/components/app/accounts/account-actions.tsx index df5acbb..260c698 100644 --- a/src/components/app/accounts/account-actions.tsx +++ b/src/components/app/accounts/account-actions.tsx @@ -28,6 +28,7 @@ import { Field, FieldError, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { Spinner } from "@/components/ui/spinner"; import type { ActionResult } from "@/lib/action-result"; +import { providerLabel, type AccountProvider } from "@/lib/account-providers"; import { NAME_MAX_LENGTH } from "@/lib/names"; import { siteConfig } from "@/lib/site"; @@ -37,11 +38,12 @@ export function AccountActions({ account, canReimport, }: { - account: { id: string; name: string }; + account: { id: string; name: string; provider: AccountProvider }; canReimport: boolean; }) { const [dialog, setDialog] = useState(null); const close = (open: boolean) => open || setDialog(null); + const providerName = providerLabel(account.provider); return ( <> @@ -78,14 +80,17 @@ export function AccountActions({ description={ <>

- Everything imported from this account is deleted, then imported again from Stripe. - Screens show “Importing” until it’s done. Nothing changes in Stripe. -

-

- Stripe keeps no history of subscription changes: the upgrades and downgrades recorded - since you connected the account are lost, and past MRR is rebuilt from current - amounts. + Everything imported from this account is deleted, then imported again from{" "} + {providerName}. Screens show “Importing” until it’s done. Nothing changes in{" "} + {providerName}.

+ {account.provider === "stripe" && ( +

+ Stripe keeps no history of subscription changes: the upgrades and downgrades + recorded since you connected the account are lost, and past MRR is rebuilt from + current amounts. +

+ )} } confirmLabel="Re-import" @@ -103,8 +108,8 @@ export function AccountActions({ disappears from your screens.

- Nothing changes in Stripe: you can connect it again later. If you won’t, delete the - restricted key in Stripe too. + Nothing changes in {providerName}: you can connect it again later. If you won’t, + delete the API key in {providerName} too.

} diff --git a/src/components/app/accounts/account-card.tsx b/src/components/app/accounts/account-card.tsx index ae45e39..9ba9d18 100644 --- a/src/components/app/accounts/account-card.tsx +++ b/src/components/app/accounts/account-card.tsx @@ -1,10 +1,11 @@ import { CircleAlertIcon, KeyRoundIcon } from "lucide-react"; import Link from "next/link"; import { Button } from "@/components/ui/button"; +import { providerLabel, type AccountProvider } from "@/lib/account-providers"; import { formatRelativeTime } from "@/lib/format"; import type { StripeAccountSummary } from "@/server/stripe/accounts"; import { AccountActions } from "./account-actions"; -import { ModeBadge, MrrValue, SyncStatus } from "./account-status"; +import { ModeBadge, MrrValue, ProviderBadge, SyncStatus } from "./account-status"; import { ImportProgress } from "./import-progress"; import { InstantUpdates } from "./instant-updates"; @@ -13,7 +14,7 @@ export function AccountCard({ webhookInstructions, }: { account: StripeAccountSummary; - /** Only for accounts still polling: what to configure in Stripe for instant updates. */ + /** Only for accounts still polling: what to configure in the provider for instant updates. */ webhookInstructions: { url: string; events: string[] } | null; }) { const lastEventAt = account.updates.mode === "webhook" ? account.updates.lastEventAt : null; @@ -24,10 +25,11 @@ export function AccountCard({ >
-
+

{account.name}

+

{account.keyHint}

@@ -39,7 +41,7 @@ export function AccountCard({
)} @@ -48,15 +50,16 @@ export function AccountCard({
{account.status === "error" ? ( - + ) : ( )} - {account.status === "importing" && } + {account.status === "importing" && }

- The first import reads your whole Stripe history, a few minutes for large accounts. Screens - show “Importing” until it’s done. + {provider === "revenuecat" + ? "Importing your MRR, charts and revenue from RevenueCat. This usually takes a few seconds." + : "The first import reads your whole Stripe history, a few minutes for large accounts. Screens show “Importing” until it’s done."}

); @@ -93,7 +97,14 @@ function ImportingDetails() { * Accounts only fail when their key needs a fix (revoked, missing a permission, undecryptable): * connecting again with a new key replaces it and keeps the data, while a re-import would drop it. */ -function ErrorDetails({ message }: { message: string | null }) { +function ErrorDetails({ + provider, + message, +}: { + provider: AccountProvider; + message: string | null; +}) { + const providerName = providerLabel(provider); return (

@@ -102,13 +113,19 @@ function ErrorDetails({ message }: { message: string | null }) {

{message &&

{message}

}

- Most often the key was revoked or lost a permission. Fix the key in Stripe (it is checked - again every 30 minutes), or connect the account again with a new restricted key: your - imported data is kept. + Most often the key was revoked or lost a permission. Fix the key in {providerName} (it is + checked again every 30 minutes), or connect the account again with a new key: your imported + data is kept.

+ + + ); +} diff --git a/src/components/app/accounts/instant-updates.tsx b/src/components/app/accounts/instant-updates.tsx index d79d18f..24321d5 100644 --- a/src/components/app/accounts/instant-updates.tsx +++ b/src/components/app/accounts/instant-updates.tsx @@ -15,7 +15,9 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/component import { Field, FieldError, FieldLabel } from "@/components/ui/field"; import { Spinner } from "@/components/ui/spinner"; import type { ActionResult } from "@/lib/action-result"; +import { providerLabel, type AccountProvider } from "@/lib/account-providers"; import { formatApproximateDuration } from "@/lib/format"; +import { REVENUECAT_DASHBOARD_URL } from "@/lib/revenuecat-permissions"; import { siteConfig } from "@/lib/site"; import type { StripeAccountSummary } from "@/server/stripe/accounts"; @@ -25,17 +27,19 @@ interface WebhookInstructions { } /** - * How new Stripe activity reaches the app. Polling works everywhere but is slow; a webhook makes + * How new activity reaches the app. Polling works everywhere but is slow; a webhook makes * sales show up (and play their sound) within seconds. */ export function InstantUpdates({ accountId, + provider, livemode, updates, lastEventLabel, instructions, }: { accountId: string; + provider: AccountProvider; livemode: boolean; updates: StripeAccountSummary["updates"]; /** "3 minutes ago", computed on the server. */ @@ -45,6 +49,7 @@ export function InstantUpdates({ const [error, setError] = useState(null); const [manualOpen, setManualOpen] = useState(false); const [enabling, startEnabling] = useTransition(); + const providerName = providerLabel(provider); if (updates.mode === "webhook") { return ( @@ -54,7 +59,7 @@ export function InstantUpdates({ Instant updates are on

- Stripe notifies {siteConfig.name} of every change.{" "} + {providerName} notifies {siteConfig.name} of every change.{" "} {lastEventLabel ? `Last event ${lastEventLabel}.` : "No event received yet."}

@@ -80,10 +85,12 @@ export function InstantUpdates({

- Checks Stripe every {formatApproximateDuration(updates.intervalSeconds)} + Checks {providerName} every {formatApproximateDuration(updates.intervalSeconds)}

- Turn on instant updates to hear each sale the moment it happens. + {provider === "revenuecat" + ? "Turn on webhooks to see live purchases in the feed and hear each sale the moment it happens." + : "Turn on instant updates to hear each sale the moment it happens."}

    - + {account ? (
    -

    +

    {account.name} +

    @@ -55,15 +56,23 @@ export function SetupGuide({ ) : (

    - Create a read-only key in Stripe and paste it here. We import your subscriptions and - payments, then keep them in sync. + Connect Stripe or RevenueCat with a read-only API key. We import your MRR, + subscriptions and revenue, then keep them in sync.

    - +
    + + +
    )} @@ -100,7 +109,7 @@ export function SetupGuide({ ) : (

    - We set it up for you as soon as Stripe is connected. + We set it up for you as soon as an account is connected.

    )} diff --git a/src/components/app/screens/editor/account-picker.tsx b/src/components/app/screens/editor/account-picker.tsx index 0b1fada..f1b7fdc 100644 --- a/src/components/app/screens/editor/account-picker.tsx +++ b/src/components/app/screens/editor/account-picker.tsx @@ -3,7 +3,7 @@ import { CircleAlertIcon } from "lucide-react"; import Link from "next/link"; import { useId } from "react"; -import { ModeBadge } from "@/components/app/accounts/account-status"; +import { ModeBadge, ProviderBadge } from "@/components/app/accounts/account-status"; import { Checkbox } from "@/components/ui/checkbox"; import type { AccountOption } from "@/server/screens"; @@ -28,7 +28,7 @@ export function AccountPicker({ if (accounts.length === 0) { return (

    - No Stripe account yet.{" "} + No account yet.{" "}

    - Stripe accounts + Accounts

      {accounts.map((account) => ( @@ -71,6 +71,7 @@ export function AccountPicker({ onCheckedChange={(checked) => toggle(account.id, checked === true)} /> {account.name} + diff --git a/src/db/schema/app.ts b/src/db/schema/app.ts index a2e1557..f30a192 100644 --- a/src/db/schema/app.ts +++ b/src/db/schema/app.ts @@ -12,6 +12,7 @@ import { uniqueIndex, varchar, } from "drizzle-orm/mysql-core"; +import { ACCOUNT_PROVIDERS } from "@/lib/account-providers"; import type { ScreenEvent } from "@/lib/display/events"; import type { ChurnReason } from "@/lib/display/types"; import type { ScreenSettings } from "@/lib/screens/settings"; @@ -91,7 +92,7 @@ export interface ScanProgress extends ScanWindows { followUp?: ScanWindows; } -/** A Stripe account connected to a workspace with a (preferably restricted, read-only) API key. */ +/** A revenue source connected to a workspace (Stripe account or RevenueCat project). */ export const stripeAccounts = mysqlTable( "stripe_accounts", { @@ -99,10 +100,12 @@ export const stripeAccounts = mysqlTable( workspaceId: authId() .notNull() .references(() => organizations.id, { onDelete: "cascade" }), + provider: mysqlEnum(ACCOUNT_PROVIDERS).notNull().default("stripe"), name: text().notNull(), /** - * `acct_…` identifier, used to prevent connecting the same account twice. Test mode shares it - * with live mode, although their data is separate: both may be connected. + * External identifier (`acct_…` for Stripe, `proj…` for RevenueCat), used to prevent + * connecting the same account twice. Stripe test mode shares it with live mode, although their + * data is separate: both may be connected. */ stripeAccountId: stripeId(), livemode: boolean().notNull(), @@ -148,12 +151,74 @@ export const stripeAccounts = mysqlTable( index("stripe_accounts_workspace_id_index").on(table.workspaceId), uniqueIndex("stripe_accounts_workspace_id_stripe_account_id_livemode_index").on( table.workspaceId, + table.provider, table.stripeAccountId, table.livemode, ), ], ); +/** Cached product metadata for a RevenueCat project, used to enrich webhook feed items. */ +export interface RevenueCatProductEntry { + displayName: string; + /** ISO 8601 subscription duration (`P1M`, `P1Y`, `P1W`, …) or `null` for non-subscriptions. */ + duration: string | null; +} + +/** + * Latest overview metrics snapshot for a RevenueCat project, refreshed from RevenueCat REST API v2. + * Live webhook events that arrive after `overviewUpdatedAt` are added on top until the next sync. + */ +export const revenuecatMetrics = mysqlTable("revenuecat_metrics", { + accountId: uuid() + .primaryKey() + .references(() => stripeAccounts.id, { onDelete: "cascade" }), + currency: currency().notNull(), + /** Current MRR in minor units of `currency`. */ + mrr: money().notNull(), + /** Active paying subscriptions (used for active customers & ARPU). */ + activeSubscriptions: int().notNull().default(0), + /** Active free trials. */ + activeTrials: int().notNull().default(0), + /** When RevenueCat last computed the overview snapshot; live webhooks after this add on top. */ + overviewUpdatedAt: instant().notNull(), + /** Product catalog keyed by `store_identifier` (or product id), for webhook plan names. */ + products: json().$type>().notNull().default({}), + ...timestamps, +}); + +/** + * Daily time-series metrics for a RevenueCat project, synced from RevenueCat Charts API v2 + * (`mrr_movement`, `revenue`, `actives_new`, `customers_new`). + */ +export const revenuecatDailyMetrics = mysqlTable( + "revenuecat_daily_metrics", + { + accountId: uuid() + .notNull() + .references(() => stripeAccounts.id, { onDelete: "cascade" }), + /** Calendar day (`YYYY-MM-DD`, UTC as bucketed by RevenueCat). */ + day: identifier({ length: 10 }).notNull(), + currency: currency().notNull(), + /** Daily gross revenue in minor units of `currency`. */ + revenue: money().notNull().default(0), + /** Daily MRR movements in minor units (`contraction` and `churn` are <= 0). */ + mrrNew: money().notNull().default(0), + mrrExpansion: money().notNull().default(0), + mrrReactivation: money().notNull().default(0), + mrrContraction: money().notNull().default(0), + mrrChurn: money().notNull().default(0), + /** New paying subscriptions on this day (`actives_new` chart). */ + newPayingCustomers: int().notNull().default(0), + /** New customers first seen on this day (`customers_new` chart). */ + newCustomers: int().notNull().default(0), + }, + (table) => [ + primaryKey({ columns: [table.accountId, table.day] }), + index("revenuecat_daily_metrics_account_id_day_index").on(table.accountId, table.day), + ], +); + /** Local mirror of every Stripe subscription, with its current contribution to MRR. */ export const subscriptions = mysqlTable( "subscriptions", diff --git a/src/lib/account-providers.ts b/src/lib/account-providers.ts new file mode 100644 index 0000000..584ef68 --- /dev/null +++ b/src/lib/account-providers.ts @@ -0,0 +1,7 @@ +export const ACCOUNT_PROVIDERS = ["stripe", "revenuecat"] as const; + +export type AccountProvider = (typeof ACCOUNT_PROVIDERS)[number]; + +export function providerLabel(provider: AccountProvider): string { + return provider === "revenuecat" ? "RevenueCat" : "Stripe"; +} diff --git a/src/lib/revenuecat-permissions.ts b/src/lib/revenuecat-permissions.ts new file mode 100644 index 0000000..9879e89 --- /dev/null +++ b/src/lib/revenuecat-permissions.ts @@ -0,0 +1,61 @@ +/** + * Permissions of the RevenueCat API v2 secret key users create for the app. Read access is enough + * to compute every metric; the only write permission lets the app register its own webhook + * integration for instant updates. `id` is RevenueCat's scope identifier, `label` what the + * dashboard shows. + */ +export const REVENUECAT_KEY_PERMISSIONS = [ + { + id: "project_configuration:projects:read", + label: "Projects", + section: "Project configuration", + access: "Read", + }, + { + id: "charts_metrics:overview:read", + label: "Overview", + section: "Charts & metrics", + access: "Read", + }, + { + id: "charts_metrics:charts:read", + label: "Charts", + section: "Charts & metrics", + access: "Read", + }, + { + id: "project_configuration:products:read", + label: "Products", + section: "Project configuration", + access: "Read", + optional: true, + purpose: "Show product names and billing intervals on live sales", + }, + { + id: "project_configuration:integrations:read_write", + label: "Integrations", + section: "Project configuration", + access: "Write", + optional: true, + purpose: "Instant updates instead of periodic checks", + }, +] as const satisfies readonly RevenueCatKeyPermission[]; + +export interface RevenueCatKeyPermission { + id: string; + label: string; + section: string; + access: "Read" | "Write"; + optional?: boolean; + purpose?: string; +} + +export type RevenueCatPermissionId = (typeof REVENUECAT_KEY_PERMISSIONS)[number]["id"]; + +/** How the RevenueCat dashboard names a permission, e.g. `Charts (Read)`. */ +export function revenueCatPermissionLabel(id: string): string { + const permission = REVENUECAT_KEY_PERMISSIONS.find((candidate) => candidate.id === id); + return permission ? `${permission.label} (${permission.access})` : id; +} + +export const REVENUECAT_DASHBOARD_URL = "https://app.revenuecat.com/"; diff --git a/src/server/display/previews.test.ts b/src/server/display/previews.test.ts index e6b4067..b8f2c15 100644 --- a/src/server/display/previews.test.ts +++ b/src/server/display/previews.test.ts @@ -13,7 +13,7 @@ vi.mock("./recent-state", () => ({ })), })); -const account = { id: "a1", name: "Acme", livemode: true }; +const account = { id: "a1", provider: "stripe" as const, name: "Acme", livemode: true }; describe("display states of the dashboard's previews", () => { it("load the screens that show accounts, side by side", async () => { diff --git a/src/server/display/queries.ts b/src/server/display/queries.ts index 00733d7..8c079f9 100644 --- a/src/server/display/queries.ts +++ b/src/server/display/queries.ts @@ -23,6 +23,8 @@ import { customers, mrrMovements, payments, + revenuecatDailyMetrics, + revenuecatMetrics, screenAccounts, screens, stripeAccounts, @@ -30,7 +32,7 @@ import { } from "@/db/schema"; import { dayToUtcDate } from "@/lib/display/calendar"; import type { FeedEvent } from "@/lib/display/events"; -import type { ChurnReason, FeedItemKind } from "@/lib/display/types"; +import type { ChurnReason, FeedItemKind, MrrMovementKind } from "@/lib/display/types"; import { DAY_MS } from "@/lib/durations"; /* @@ -83,31 +85,129 @@ function countsByAccount(rows: readonly { accountId: string; count: number }[]) return new Map(rows.map((row) => [row.accountId, row.count])); } +/** Splits account ids by provider so Stripe and RevenueCat metrics never double-count. */ +async function partitionByProvider( + accountIds: readonly string[], +): Promise<{ stripeIds: string[]; revenuecatIds: string[] }> { + if (!accountIds.length) return { stripeIds: [], revenuecatIds: [] }; + const rows = await db() + .select({ id: stripeAccounts.id, provider: stripeAccounts.provider }) + .from(stripeAccounts) + .where(inArray(stripeAccounts.id, [...accountIds])); + const stripeIds: string[] = []; + const revenuecatIds: string[] = []; + for (const row of rows) { + if (row.provider === "revenuecat") revenuecatIds.push(row.id); + else stripeIds.push(row.id); + } + return { stripeIds, revenuecatIds }; +} + /** Current MRR and trials per account and currency. */ -export function subscriptionTotals(accountIds: string[]) { - return db() - .select({ - accountId: subscriptions.accountId, - currency: subscriptions.currency, - mrr: sum(subscriptions.mrr).mapWith(Number), - trialing: count(sql`case when ${subscriptions.status} = 'trialing' then 1 end`), - }) - .from(subscriptions) - .where(inArray(subscriptions.accountId, accountIds)) - .groupBy(subscriptions.accountId, subscriptions.currency); +export async function subscriptionTotals(accountIds: string[]) { + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + const [stripeRows, rcSnapshots] = await Promise.all([ + stripeIds.length + ? db() + .select({ + accountId: subscriptions.accountId, + currency: subscriptions.currency, + mrr: sum(subscriptions.mrr).mapWith(Number), + trialing: count(sql`case when ${subscriptions.status} = 'trialing' then 1 end`), + }) + .from(subscriptions) + .where(inArray(subscriptions.accountId, stripeIds)) + .groupBy(subscriptions.accountId, subscriptions.currency) + : Promise.resolve([]), + revenuecatIds.length + ? db() + .select({ + accountId: revenuecatMetrics.accountId, + currency: revenuecatMetrics.currency, + mrr: revenuecatMetrics.mrr, + trialing: revenuecatMetrics.activeTrials, + overviewUpdatedAt: revenuecatMetrics.overviewUpdatedAt, + }) + .from(revenuecatMetrics) + .where(inArray(revenuecatMetrics.accountId, revenuecatIds)) + : Promise.resolve([]), + ]); + + if (!rcSnapshots.length) return stripeRows; + + // Include live webhook movements recorded after RevenueCat last computed its overview snapshot. + const rcRows = [...stripeRows]; + const liveDeltas = await Promise.all( + rcSnapshots.map((snapshot) => + db() + .select({ + accountId: mrrMovements.accountId, + currency: mrrMovements.currency, + amount: sum(mrrMovements.amount).mapWith(Number), + }) + .from(mrrMovements) + .where( + and( + eq(mrrMovements.accountId, snapshot.accountId), + eq(mrrMovements.origin, "live"), + gt(mrrMovements.occurredAt, snapshot.overviewUpdatedAt), + ), + ) + .groupBy(mrrMovements.accountId, mrrMovements.currency), + ), + ); + + for (let i = 0; i < rcSnapshots.length; i += 1) { + const snapshot = rcSnapshots[i]; + const deltas = liveDeltas[i]; + let sameCurrencyDelta = 0; + for (const delta of deltas) { + if (delta.currency === snapshot.currency) { + sameCurrencyDelta += delta.amount; + } else if (delta.amount !== 0) { + rcRows.push({ + accountId: snapshot.accountId, + currency: delta.currency, + mrr: delta.amount, + trialing: 0, + }); + } + } + rcRows.push({ + accountId: snapshot.accountId, + currency: snapshot.currency, + mrr: Math.max(0, snapshot.mrr + sameCurrencyDelta), + trialing: snapshot.trialing, + }); + } + return rcRows; } /** Customers with at least one paying subscription, per account. */ export async function payingCustomerCounts(accountIds: string[]): Promise> { - const rows = await db() - .select({ - accountId: subscriptions.accountId, - count: countDistinct(subscriptions.stripeCustomerId), - }) - .from(subscriptions) - .where(and(inArray(subscriptions.accountId, accountIds), gt(subscriptions.mrr, 0))) - .groupBy(subscriptions.accountId); - return countsByAccount(rows); + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + const [stripeRows, rcRows] = await Promise.all([ + stripeIds.length + ? db() + .select({ + accountId: subscriptions.accountId, + count: countDistinct(subscriptions.stripeCustomerId), + }) + .from(subscriptions) + .where(and(inArray(subscriptions.accountId, stripeIds), gt(subscriptions.mrr, 0))) + .groupBy(subscriptions.accountId) + : Promise.resolve([]), + revenuecatIds.length + ? db() + .select({ + accountId: revenuecatMetrics.accountId, + count: revenuecatMetrics.activeSubscriptions, + }) + .from(revenuecatMetrics) + .where(inArray(revenuecatMetrics.accountId, revenuecatIds)) + : Promise.resolve([]), + ]); + return countsByAccount([...stripeRows, ...rcRows]); } /** The calendar day of an instant (stored in UTC) in the screen's time zone. */ @@ -124,80 +224,256 @@ function dayText(day: SQL.Aliased) { * Net MRR change per account, currency, kind and local day, from `from` on, or since the first * movement when `from` is `null`: all time, whose chart starts with it. */ -export function movementsByDay(accountIds: string[], timeZone: string, from: string | null) { - const local = db() - .$with("local_movements") - .as( - db() +export async function movementsByDay(accountIds: string[], timeZone: string, from: string | null) { + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + + const stripePromise = stripeIds.length + ? (() => { + const local = db() + .$with("local_movements") + .as( + db() + .select({ + accountId: mrrMovements.accountId, + currency: mrrMovements.currency, + kind: mrrMovements.kind, + amount: mrrMovements.amount, + day: localDay(mrrMovements.occurredAt, timeZone).as("day"), + }) + .from(mrrMovements) + .where( + and( + inArray(mrrMovements.accountId, stripeIds), + from === null ? undefined : gte(mrrMovements.occurredAt, instantBefore(from)), + ), + ), + ); + return db() + .with(local) + .select({ + accountId: local.accountId, + currency: local.currency, + kind: local.kind, + day: dayText(local.day), + amount: sql`sum(${local.amount})`.mapWith(Number), + }) + .from(local) + .where(from === null ? undefined : gte(local.day, from)) + .groupBy(local.accountId, local.currency, local.kind, local.day); + })() + : Promise.resolve([]); + + if (!revenuecatIds.length) return stripePromise; + + const [stripeRows, rcDaily, rcSnapshots] = await Promise.all([ + stripePromise, + db() + .select({ + accountId: revenuecatDailyMetrics.accountId, + day: revenuecatDailyMetrics.day, + currency: revenuecatDailyMetrics.currency, + mrrNew: revenuecatDailyMetrics.mrrNew, + mrrExpansion: revenuecatDailyMetrics.mrrExpansion, + mrrReactivation: revenuecatDailyMetrics.mrrReactivation, + mrrContraction: revenuecatDailyMetrics.mrrContraction, + mrrChurn: revenuecatDailyMetrics.mrrChurn, + }) + .from(revenuecatDailyMetrics) + .where( + and( + inArray(revenuecatDailyMetrics.accountId, revenuecatIds), + from === null ? undefined : gte(revenuecatDailyMetrics.day, from), + ), + ), + db() + .select({ + accountId: revenuecatMetrics.accountId, + overviewUpdatedAt: revenuecatMetrics.overviewUpdatedAt, + }) + .from(revenuecatMetrics) + .where(inArray(revenuecatMetrics.accountId, revenuecatIds)), + ]); + + const rcRows: { + accountId: string; + currency: string; + kind: MrrMovementKind; + day: string; + amount: number; + }[] = []; + + for (const row of rcDaily) { + const entries: [MrrMovementKind, number][] = [ + ["new", row.mrrNew], + ["expansion", row.mrrExpansion], + ["reactivation", row.mrrReactivation], + ["contraction", row.mrrContraction], + ["churn", row.mrrChurn], + ]; + for (const [kind, amount] of entries) { + if (amount !== 0) { + rcRows.push({ + accountId: row.accountId, + currency: row.currency, + kind, + day: row.day, + amount, + }); + } + } + } + + // Add live webhook movements that arrived after each RevenueCat snapshot. + const liveRows = await Promise.all( + rcSnapshots.map((snapshot) => { + const local = db() + .$with("rc_live_movements") + .as( + db() + .select({ + accountId: mrrMovements.accountId, + currency: mrrMovements.currency, + kind: mrrMovements.kind, + amount: mrrMovements.amount, + day: localDay(mrrMovements.occurredAt, timeZone).as("day"), + }) + .from(mrrMovements) + .where( + and( + eq(mrrMovements.accountId, snapshot.accountId), + eq(mrrMovements.origin, "live"), + gt(mrrMovements.occurredAt, snapshot.overviewUpdatedAt), + ), + ), + ); + return db() + .with(local) .select({ - accountId: mrrMovements.accountId, - currency: mrrMovements.currency, - kind: mrrMovements.kind, - amount: mrrMovements.amount, - day: localDay(mrrMovements.occurredAt, timeZone).as("day"), + accountId: local.accountId, + currency: local.currency, + kind: local.kind, + day: dayText(local.day), + amount: sql`sum(${local.amount})`.mapWith(Number), }) - .from(mrrMovements) - .where( - and( - inArray(mrrMovements.accountId, accountIds), - from === null ? undefined : gte(mrrMovements.occurredAt, instantBefore(from)), - ), - ), - ); - return db() - .with(local) - .select({ - accountId: local.accountId, - currency: local.currency, - kind: local.kind, - day: dayText(local.day), - amount: sql`sum(${local.amount})`.mapWith(Number), - }) - .from(local) - .where(from === null ? undefined : gte(local.day, from)) - .groupBy(local.accountId, local.currency, local.kind, local.day); + .from(local) + .where(from === null ? undefined : gte(local.day, from)) + .groupBy(local.accountId, local.currency, local.kind, local.day); + }), + ); + + return [...stripeRows, ...rcRows, ...liveRows.flat()]; } /** * Net revenue (payments minus refunds, and the fees of those made for Stripe Connect accounts) * per account, currency and local day, from `from` on. */ -export function revenueByDay(accountIds: string[], timeZone: string, from: string) { - const local = db() - .$with("local_payments") - .as( - db() +export async function revenueByDay(accountIds: string[], timeZone: string, from: string) { + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + + const stripePromise = stripeIds.length + ? (() => { + const local = db() + .$with("local_payments") + .as( + db() + .select({ + accountId: payments.accountId, + currency: payments.currency, + // A payment made for a Stripe Connect account is theirs: the account earns its fee, + // unless the payment was refunded in full. + net: sql`case + when ${payments.connectedAccountId} is null then ${payments.amount} - ${payments.amountRefunded} + when ${payments.amountRefunded} < ${payments.amount} then coalesce(${payments.applicationFee}, 0) + else 0 + end`.as("net"), + day: localDay(payments.occurredAt, timeZone).as("day"), + }) + .from(payments) + .where( + and( + inArray(payments.accountId, stripeIds), + gte(payments.occurredAt, instantBefore(from)), + ), + ), + ); + return db() + .with(local) + .select({ + accountId: local.accountId, + currency: local.currency, + day: dayText(local.day), + amount: sql`sum(${local.net})`.mapWith(Number), + }) + .from(local) + .where(gte(local.day, from)) + .groupBy(local.accountId, local.currency, local.day); + })() + : Promise.resolve([]); + + if (!revenuecatIds.length) return stripePromise; + + const [stripeRows, rcDaily, rcSnapshots] = await Promise.all([ + stripePromise, + db() + .select({ + accountId: revenuecatDailyMetrics.accountId, + currency: revenuecatDailyMetrics.currency, + day: revenuecatDailyMetrics.day, + amount: revenuecatDailyMetrics.revenue, + }) + .from(revenuecatDailyMetrics) + .where( + and( + inArray(revenuecatDailyMetrics.accountId, revenuecatIds), + gte(revenuecatDailyMetrics.day, from), + ), + ), + db() + .select({ + accountId: revenuecatMetrics.accountId, + overviewUpdatedAt: revenuecatMetrics.overviewUpdatedAt, + }) + .from(revenuecatMetrics) + .where(inArray(revenuecatMetrics.accountId, revenuecatIds)), + ]); + + const liveRows = await Promise.all( + rcSnapshots.map((snapshot) => { + const local = db() + .$with("rc_live_payments") + .as( + db() + .select({ + accountId: payments.accountId, + currency: payments.currency, + net: sql`${payments.amount} - ${payments.amountRefunded}`.as("net"), + day: localDay(payments.occurredAt, timeZone).as("day"), + }) + .from(payments) + .where( + and( + eq(payments.accountId, snapshot.accountId), + eq(payments.origin, "live"), + gt(payments.occurredAt, snapshot.overviewUpdatedAt), + ), + ), + ); + return db() + .with(local) .select({ - accountId: payments.accountId, - currency: payments.currency, - // A payment made for a Stripe Connect account is theirs: the account earns its fee, - // unless the payment was refunded in full. - net: sql`case - when ${payments.connectedAccountId} is null then ${payments.amount} - ${payments.amountRefunded} - when ${payments.amountRefunded} < ${payments.amount} then coalesce(${payments.applicationFee}, 0) - else 0 - end`.as("net"), - day: localDay(payments.occurredAt, timeZone).as("day"), + accountId: local.accountId, + currency: local.currency, + day: dayText(local.day), + amount: sql`sum(${local.net})`.mapWith(Number), }) - .from(payments) - .where( - and( - inArray(payments.accountId, accountIds), - gte(payments.occurredAt, instantBefore(from)), - ), - ), - ); - return db() - .with(local) - .select({ - accountId: local.accountId, - currency: local.currency, - day: dayText(local.day), - amount: sql`sum(${local.net})`.mapWith(Number), - }) - .from(local) - .where(gte(local.day, from)) - .groupBy(local.accountId, local.currency, local.day); + .from(local) + .where(gte(local.day, from)) + .groupBy(local.accountId, local.currency, local.day); + }), + ); + + return [...stripeRows, ...rcDaily.filter((row) => row.amount !== 0), ...liveRows.flat()]; } /** @@ -209,53 +485,76 @@ export async function newCustomerCounts( timeZone: string, monthStart: string, ): Promise> { - const { accountId, stripeCustomerId, amount, kind, occurredAt } = mrrMovements; - const thisMonth = gte(localDay(occurredAt, timeZone), monthStart); + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + const stripePromise = stripeIds.length + ? (() => { + const { accountId, stripeCustomerId, amount, kind, occurredAt } = mrrMovements; + const thisMonth = gte(localDay(occurredAt, timeZone), monthStart); - // Customers with movements this month, under new names since they are joined with the ledger. - const touched = db() - .$with("touched_customers") - .as( - db() - .selectDistinct({ - accountId: sql`${accountId}`.as("touched_account_id"), - customerId: sql`${stripeCustomerId}`.as("touched_customer_id"), + // Customers with movements this month, under new names since they are joined with the ledger. + const touched = db() + .$with("touched_customers") + .as( + db() + .selectDistinct({ + accountId: sql`${accountId}`.as("touched_account_id"), + customerId: sql`${stripeCustomerId}`.as("touched_customer_id"), + }) + .from(mrrMovements) + .where( + and( + inArray(accountId, stripeIds), + gte(occurredAt, instantBefore(monthStart)), + thisMonth, + ), + ), + ); + // Their MRR when the month began, and whether they started a subscription since. + const months = db() + .$with("customer_months") + .as( + db() + .select({ + accountId, + mrrBefore: sql`sum(if(${thisMonth}, 0, ${amount}))`.as("mrr_before"), + // Conditions are 0 or 1 in MySQL: the largest says whether any of them holds. + started: sql`max(${kind} = 'new' and ${thisMonth})`.as("started"), + }) + .from(mrrMovements) + .innerJoin( + touched, + and(eq(accountId, touched.accountId), eq(stripeCustomerId, touched.customerId)), + ) + .groupBy(accountId, stripeCustomerId), + ); + + return db() + .with(touched, months) + .select({ accountId: months.accountId, count: count() }) + .from(months) + .where(sql`${months.started} and ${months.mrrBefore} = 0`) + .groupBy(months.accountId); + })() + : Promise.resolve([]); + + const rcPromise = revenuecatIds.length + ? db() + .select({ + accountId: revenuecatDailyMetrics.accountId, + count: sum(revenuecatDailyMetrics.newPayingCustomers).mapWith(Number), }) - .from(mrrMovements) + .from(revenuecatDailyMetrics) .where( and( - inArray(accountId, accountIds), - gte(occurredAt, instantBefore(monthStart)), - thisMonth, + inArray(revenuecatDailyMetrics.accountId, revenuecatIds), + gte(revenuecatDailyMetrics.day, monthStart), ), - ), - ); - // Their MRR when the month began, and whether they started a subscription since. - const months = db() - .$with("customer_months") - .as( - db() - .select({ - accountId, - mrrBefore: sql`sum(if(${thisMonth}, 0, ${amount}))`.as("mrr_before"), - // Conditions are 0 or 1 in MySQL: the largest says whether any of them holds. - started: sql`max(${kind} = 'new' and ${thisMonth})`.as("started"), - }) - .from(mrrMovements) - .innerJoin( - touched, - and(eq(accountId, touched.accountId), eq(stripeCustomerId, touched.customerId)), ) - .groupBy(accountId, stripeCustomerId), - ); + .groupBy(revenuecatDailyMetrics.accountId) + : Promise.resolve([]); - const rows = await db() - .with(touched, months) - .select({ accountId: months.accountId, count: count() }) - .from(months) - .where(sql`${months.started} and ${months.mrrBefore} = 0`) - .groupBy(months.accountId); - return countsByAccount(rows); + const [stripeRows, rcRows] = await Promise.all([stripePromise, rcPromise]); + return countsByAccount([...stripeRows, ...rcRows]); } /** @@ -267,18 +566,38 @@ export async function customersCreatedSince( timeZone: string, day: string, ): Promise> { - const rows = await db() - .select({ accountId: customers.accountId, count: count() }) - .from(customers) - .where( - and( - inArray(customers.accountId, accountIds), - gte(customers.occurredAt, instantBefore(day)), - gte(localDay(customers.occurredAt, timeZone), day), - ), - ) - .groupBy(customers.accountId); - return countsByAccount(rows); + const { stripeIds, revenuecatIds } = await partitionByProvider(accountIds); + const [stripeRows, rcRows] = await Promise.all([ + stripeIds.length + ? db() + .select({ accountId: customers.accountId, count: count() }) + .from(customers) + .where( + and( + inArray(customers.accountId, stripeIds), + gte(customers.occurredAt, instantBefore(day)), + gte(localDay(customers.occurredAt, timeZone), day), + ), + ) + .groupBy(customers.accountId) + : Promise.resolve([]), + revenuecatIds.length + ? db() + .select({ + accountId: revenuecatDailyMetrics.accountId, + count: sum(revenuecatDailyMetrics.newCustomers).mapWith(Number), + }) + .from(revenuecatDailyMetrics) + .where( + and( + inArray(revenuecatDailyMetrics.accountId, revenuecatIds), + gte(revenuecatDailyMetrics.day, day), + ), + ) + .groupBy(revenuecatDailyMetrics.accountId) + : Promise.resolve([]), + ]); + return countsByAccount([...stripeRows, ...rcRows]); } /** A movement, payment or new customer of the feed, before conversion to the screen's currency. */ diff --git a/src/server/revenuecat/accounts.ts b/src/server/revenuecat/accounts.ts new file mode 100644 index 0000000..358cf98 --- /dev/null +++ b/src/server/revenuecat/accounts.ts @@ -0,0 +1,221 @@ +import "server-only"; +import { and, eq } from "drizzle-orm"; +import { z } from "zod"; +import { db } from "@/db"; +import { isDuplicateEntry } from "@/db/errors"; +import { stripeAccounts } from "@/db/schema"; +import type { ActionResult } from "@/lib/action-result"; +import { nameSchema } from "@/lib/names"; +import { encryptSecret } from "@/server/crypto"; +import type { MissingPermissions } from "@/server/stripe/accounts"; +import { scheduleSync } from "@/server/sync"; +import { workingStatus } from "@/server/sync/state"; +import { RevenueCatAccessError } from "./errors"; +import { + createRevenueCatGateway, + type RevenueCatAccessOptions, + type RevenueCatGateway, +} from "./gateway"; +import { revenueCatProjectIdSchema, revenueCatSecretKeySchema } from "./keys"; +import { newRevenueCatBackfill } from "./sync"; +import type { RevenueCatOverview, RevenueCatProject } from "./types"; +import { registerRevenueCatWebhook } from "./webhooks"; + +const accountNameSchema = nameSchema("Name the account, for example after your app."); + +export const connectRevenueCatSchema = z.object({ + name: accountNameSchema, + secretKey: revenueCatSecretKeySchema, + projectId: revenueCatProjectIdSchema, +}); + +const REVENUECAT_UNREACHABLE = "RevenueCat could not be reached. Try again in a moment."; + +/** + * Checks a RevenueCat API v2 secret key, resolves its project, verifies read permissions for + * overview & charts, stores it encrypted in `workspaceId`, attempts to register a webhook + * integration for instant updates, and starts the initial import. + */ +export async function connectRevenueCatAccount( + input: { workspaceId: string } & z.infer, + options: RevenueCatAccessOptions = {}, +): Promise> { + const key = input.secretKey; + const gateway = (options.createGateway ?? createRevenueCatGateway)(key.key); + + const projectResult = await resolveProject(gateway, input.projectId); + if (!projectResult.ok) return projectResult; + const { project } = projectResult; + + const probeResult = await probeReadAccess(gateway, project.id); + if (!probeResult.ok) return probeResult; + const { overview } = probeResult; + + const [existing] = await db() + .select({ id: stripeAccounts.id, status: stripeAccounts.status }) + .from(stripeAccounts) + .where( + and( + eq(stripeAccounts.workspaceId, input.workspaceId), + eq(stripeAccounts.provider, "revenuecat"), + eq(stripeAccounts.stripeAccountId, project.id), + eq(stripeAccounts.livemode, true), + ), + ); + if (existing?.status === "error") { + await db() + .update(stripeAccounts) + .set({ + encryptedSecretKey: encryptSecret(key.key), + secretKeyHint: key.hint, + status: workingStatus(), + lastError: null, + syncFailures: 0, + syncLockedUntil: null, + }) + .where(eq(stripeAccounts.id, existing.id)); + scheduleSync([existing.id]); + return { ok: true, accountId: existing.id }; + } + if (existing) { + return { ok: false, error: "This RevenueCat project is already connected." }; + } + + const now = new Date(); + let account: { id: string }; + try { + [account] = await db() + .insert(stripeAccounts) + .values({ + workspaceId: input.workspaceId, + provider: "revenuecat", + name: input.name, + stripeAccountId: project.id, + livemode: true, + encryptedSecretKey: encryptSecret(key.key), + secretKeyHint: key.hint, + defaultCurrency: overview.currency, + status: "importing", + backfill: newRevenueCatBackfill(now), + }) + .$returningId(); + } catch (error) { + if (!isDuplicateEntry(error)) throw error; + return { ok: false, error: "This RevenueCat project is already connected." }; + } + + await registerRevenueCatWebhook(account.id, project.id, gateway, true); + scheduleSync([account.id]); + return { ok: true, accountId: account.id }; +} + +async function resolveProject( + gateway: RevenueCatGateway, + requestedProjectId?: string, +): Promise> { + let projects: RevenueCatProject[]; + try { + projects = await gateway.listProjects(); + } catch (error) { + if (!(error instanceof RevenueCatAccessError)) throw error; + if (error.kind === "authentication") { + return { + ok: false, + error: + "This key is not valid. Create an API v2 secret key in RevenueCat under Project Settings › API keys.", + }; + } + if (error.kind === "permission") { + // If the user explicitly supplied a project ID, we can still proceed to probe overview & charts. + if (requestedProjectId) { + return { ok: true, project: { id: requestedProjectId, name: requestedProjectId } }; + } + return { + ok: false, + error: "This key is missing a permission.", + missingPermissions: ["project_configuration:projects:read"], + }; + } + return { ok: false, error: REVENUECAT_UNREACHABLE }; + } + + if (requestedProjectId) { + const match = projects.find((candidate) => candidate.id === requestedProjectId); + if (!match) { + return { + ok: false, + error: `This key does not have access to project “${requestedProjectId}”.`, + }; + } + return { ok: true, project: match }; + } + + if (projects.length === 0) { + return { ok: false, error: "No RevenueCat project was found for this API key." }; + } + if (projects.length > 1) { + const list = projects.map((p) => `${p.name} (${p.id})`).join(", "); + return { + ok: false, + error: `This key can access several projects. Enter the Project ID to connect: ${list}.`, + }; + } + return { ok: true, project: projects[0] }; +} + +async function probeReadAccess( + gateway: RevenueCatGateway, + projectId: string, +): Promise> { + const today = new Date().toISOString().slice(0, 10); + const [overviewRes, chartRes] = await Promise.allSettled([ + gateway.getOverviewMetrics(projectId), + gateway.getChartData(projectId, "mrr", { + startDate: today, + endDate: today, + resolution: "0", + }), + ]); + + const failures: { error: RevenueCatAccessError; permission: string }[] = []; + if (overviewRes.status === "rejected") { + if (!(overviewRes.reason instanceof RevenueCatAccessError)) throw overviewRes.reason; + failures.push({ error: overviewRes.reason, permission: "charts_metrics:overview:read" }); + } + if (chartRes.status === "rejected") { + if (!(chartRes.reason instanceof RevenueCatAccessError)) throw chartRes.reason; + failures.push({ error: chartRes.reason, permission: "charts_metrics:charts:read" }); + } + + if (!failures.length && overviewRes.status === "fulfilled") { + return { ok: true, overview: overviewRes.value }; + } + + if (failures.some(({ error }) => error.kind === "authentication")) { + return { + ok: false, + error: + "This key is not valid. Create an API v2 secret key in RevenueCat under Project Settings › API keys.", + }; + } + if (failures.some(({ error }) => error.kind === "not_found")) { + return { ok: false, error: `Project “${projectId}” was not found in RevenueCat.` }; + } + + const missing = failures.filter(({ error }) => error.kind === "permission"); + if (missing.length) { + const missingPermissions = missing.map( + ({ error, permission }) => error.permission ?? permission, + ); + return { + ok: false, + error: + missingPermissions.length === 1 + ? "This key is missing a permission." + : `This key is missing ${missingPermissions.length} permissions.`, + missingPermissions, + }; + } + + return { ok: false, error: REVENUECAT_UNREACHABLE }; +} diff --git a/src/server/revenuecat/charts.test.ts b/src/server/revenuecat/charts.test.ts new file mode 100644 index 0000000..df7c4a3 --- /dev/null +++ b/src/server/revenuecat/charts.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, it } from "vitest"; +import { DAY_MS } from "@/lib/durations"; +import { + billingIntervalOf, + buildDailyMetricRows, + normalizeMonthlyMrr, + parseOverviewMetrics, + toUtcDay, +} from "./charts"; + +describe("toUtcDay", () => { + it("normalizes unix seconds, unix ms, and ISO strings to UTC YYYY-MM-DD", () => { + expect(toUtcDay(1735689600)).toBe("2025-01-01"); + expect(toUtcDay(1735689600000)).toBe("2025-01-01"); + expect(toUtcDay("2025-03-15")).toBe("2025-03-15"); + expect(toUtcDay("2025-03-15T12:30:00Z")).toBe("2025-03-15"); + expect(toUtcDay(null)).toBeNull(); + }); +}); + +describe("parseOverviewMetrics", () => { + it("converts overview MRR to minor units and reads active counts", () => { + const fallback = new Date("2026-01-01T00:00:00Z"); + const parsed = parseOverviewMetrics( + { + currency: "EUR", + metrics: [ + { id: "mrr", value: 4270.55, last_updated_at: 1767225600000 }, + { id: "active_subscriptions", value: 184, last_updated_at: 1767225500000 }, + { id: "active_trials", value: 23, last_updated_at: 1767225400000 }, + ], + }, + fallback, + ); + + expect(parsed).toEqual({ + currency: "eur", + mrr: 427055, + activeSubscriptions: 184, + activeTrials: 23, + updatedAt: new Date(1767225600000), + }); + }); + + it("handles zero-decimal currencies such as JPY", () => { + const parsed = parseOverviewMetrics( + { currency: "JPY", metrics: [{ id: "mrr", value: 125000 }] }, + new Date("2026-01-01T00:00:00Z"), + ); + expect(parsed.currency).toBe("jpy"); + expect(parsed.mrr).toBe(125000); + }); +}); + +describe("buildDailyMetricRows", () => { + it("merges Charts v3 object points across mrr_movement, revenue, actives_new, and customers_new", () => { + const day1 = Date.UTC(2026, 10, 20) / 1000; + const day2 = Date.UTC(2026, 10, 21) / 1000; + + const rows = buildDailyMetricRows({ + currency: "usd", + mrrMovement: { + currency: "usd", + resolution: "day", + measures: [ + { displayName: "New MRR", unit: "$", chartable: true }, + { displayName: "Resubscription MRR", unit: "$", chartable: true }, + { displayName: "Expansion MRR", unit: "$", chartable: true }, + { displayName: "Contraction MRR", unit: "$", chartable: true }, + { displayName: "Churned MRR", unit: "$", chartable: true }, + ], + values: [ + { cohort: day1, measure: 0, value: 120.5 }, + { cohort: day1, measure: 1, value: 15 }, + { cohort: day1, measure: 2, value: 10 }, + { cohort: day1, measure: 3, value: 5 }, + { cohort: day1, measure: 4, value: 40.25 }, + { cohort: day2, measure: 0, value: 50 }, + ], + }, + revenue: { + currency: "usd", + resolution: "day", + measures: [ + { displayName: "Revenue", unit: "$", chartable: true }, + { displayName: "Transactions", unit: "#", chartable: false }, + ], + values: [ + { cohort: day1, measure: 0, value: 300.1 }, + { cohort: day1, measure: 1, value: 12 }, + { cohort: day2, measure: 0, value: 99.99 }, + ], + }, + activesNew: { + currency: "usd", + resolution: "day", + measures: [{ displayName: "New Paid Subscriptions", unit: "#", chartable: true }], + values: [ + [day1, 6], + [day2, 2], + ], + }, + customersNew: { + currency: "usd", + resolution: "day", + measures: [{ displayName: "New Customers", unit: "#", chartable: true }], + values: [[day2, 42]], + }, + }); + + expect(rows).toEqual([ + { + day: "2026-11-20", + currency: "usd", + revenue: 30010, + mrrNew: 12050, + mrrReactivation: 1500, + mrrExpansion: 1000, + mrrContraction: -500, + mrrChurn: -4025, + newPayingCustomers: 6, + newCustomers: 0, + }, + { + day: "2026-11-21", + currency: "usd", + revenue: 9999, + mrrNew: 5000, + mrrReactivation: 0, + mrrExpansion: 0, + mrrContraction: -0, + mrrChurn: -0, + newPayingCustomers: 2, + newCustomers: 42, + }, + ]); + }); +}); + +describe("normalizeMonthlyMrr", () => { + it("normalizes ISO 8601 durations to monthly MRR", () => { + expect(normalizeMonthlyMrr(12000, "P1Y")).toBe(1000); + expect(normalizeMonthlyMrr(1000, "P1M")).toBe(1000); + expect(normalizeMonthlyMrr(3000, "P3M")).toBe(1000); + expect(normalizeMonthlyMrr(6000, "P6M")).toBe(1000); + expect(normalizeMonthlyMrr(1000, "P1W")).toBe(Math.round((1000 * 52) / 12)); + }); + + it("falls back to period length in ms when product duration is missing", () => { + expect(normalizeMonthlyMrr(12000, null, 365 * DAY_MS)).toBe(1000); + expect(normalizeMonthlyMrr(1000, null, 30 * DAY_MS)).toBe(1000); + expect(billingIntervalOf(null, 7 * DAY_MS)).toBe("week"); + expect(billingIntervalOf("P1Y")).toBe("year"); + }); +}); diff --git a/src/server/revenuecat/charts.ts b/src/server/revenuecat/charts.ts new file mode 100644 index 0000000..065187a --- /dev/null +++ b/src/server/revenuecat/charts.ts @@ -0,0 +1,388 @@ +import "server-only"; +import { DAY_MS } from "@/lib/durations"; +import { toMinorUnits } from "@/lib/money"; +import type { BillingInterval } from "@/server/stripe/mrr"; +import type { + RevenueCatChartData, + RevenueCatChartMeasure, + RevenueCatDailyRow, + RevenueCatOverview, +} from "./types"; + +const ISO_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}/; + +/** Converts a RevenueCat timestamp (seconds, ms, or ISO date) to a UTC `YYYY-MM-DD` day string. */ +export function toUtcDay(input: unknown): string | null { + if (typeof input === "string") { + if (ISO_DAY_PATTERN.test(input)) return input.slice(0, 10); + const parsed = Number(input); + if (Number.isFinite(parsed)) return unixToUtcDay(parsed); + const date = new Date(input); + return Number.isNaN(date.getTime()) ? null : date.toISOString().slice(0, 10); + } + if (typeof input === "number" && Number.isFinite(input)) { + return unixToUtcDay(input); + } + return null; +} + +function unixToUtcDay(value: number): string { + // Timestamps >= 1e12 are milliseconds (year ~2001+); smaller values are Unix seconds. + const ms = Math.abs(value) >= 1e12 ? value : value * 1000; + return new Date(ms).toISOString().slice(0, 10); +} + +/** Parses `GET /v2/projects/{project_id}/metrics/overview` into integer minor units. */ +export function parseOverviewMetrics( + raw: { + currency?: string | null; + metrics?: readonly { + id?: string; + value?: number; + last_updated_at?: number | null; + }[]; + }, + fallbackNow: Date, +): RevenueCatOverview { + const currency = (raw.currency ?? "USD").toLowerCase(); + const byId = new Map(); + let latestMs: number | null = null; + + for (const metric of raw.metrics ?? []) { + if (!metric.id || typeof metric.value !== "number" || !Number.isFinite(metric.value)) continue; + const updated = + typeof metric.last_updated_at === "number" && Number.isFinite(metric.last_updated_at) + ? metric.last_updated_at + : null; + byId.set(metric.id, { value: metric.value, lastUpdatedAt: updated }); + if (updated !== null && (latestMs === null || updated > latestMs)) { + latestMs = updated; + } + } + + const mrrMajor = byId.get("mrr")?.value ?? 0; + const activeSubscriptions = Math.max(0, Math.round(byId.get("active_subscriptions")?.value ?? 0)); + const activeTrials = Math.max(0, Math.round(byId.get("active_trials")?.value ?? 0)); + + return { + currency, + mrr: toMinorUnits(mrrMajor, currency), + activeSubscriptions, + activeTrials, + updatedAt: latestMs !== null ? new Date(latestMs) : fallbackNow, + }; +} + +export interface ParsedDayPoint { + /** Measure values keyed by index (0-based into `chart.measures`, or 0 for single-series). */ + byIndex: Map; + /** Measure values keyed by lowercase name when provided directly as an object. */ + byName: Map; +} + +/** + * Extracts daily points from a RevenueCat Charts API v2/v3 response. + * Supports: + * - Charts v3 object points: `{ cohort, measure, value, incomplete? }` + * - Standard object points: `{ timestamp | date, value }` or `{ timestamp | date, measures: { ... } }` + * - Tuple array points: `[unixSeconds, value0, value1, ...]` + */ +export function parseChartValues(chart: RevenueCatChartData): Map { + const days = new Map(); + const ensure = (day: string): ParsedDayPoint => { + let entry = days.get(day); + if (!entry) { + entry = { byIndex: new Map(), byName: new Map() }; + days.set(day, entry); + } + return entry; + }; + + for (const item of chart.values) { + if (Array.isArray(item)) { + const day = toUtcDay(item[0]); + if (!day) continue; + const entry = ensure(day); + for (let i = 1; i < item.length; i += 1) { + const value = item[i]; + if (typeof value === "number" && Number.isFinite(value)) { + entry.byIndex.set(i - 1, value); + } + } + continue; + } + + if (item && typeof item === "object") { + const record = item as Record; + const day = toUtcDay(record.cohort ?? record.date ?? record.timestamp); + if (!day) continue; + const entry = ensure(day); + + if ( + record.measures && + typeof record.measures === "object" && + !Array.isArray(record.measures) + ) { + for (const [key, value] of Object.entries(record.measures as Record)) { + if (typeof value === "number" && Number.isFinite(value)) { + entry.byName.set(key.toLowerCase(), value); + } + } + continue; + } + + if (typeof record.value === "number" && Number.isFinite(record.value)) { + const measureIndex = + typeof record.measure === "number" && Number.isInteger(record.measure) + ? record.measure + : 0; + entry.byIndex.set(measureIndex, record.value); + } + } + } + + return days; +} + +function measureIndexMatching( + measures: readonly RevenueCatChartMeasure[], + predicate: (measure: RevenueCatChartMeasure, name: string) => boolean, +): number | null { + for (let i = 0; i < measures.length; i += 1) { + if (predicate(measures[i], measures[i].displayName.toLowerCase())) return i; + } + return null; +} + +function pointMeasureValue( + point: ParsedDayPoint, + index: number | null, + nameKeys: readonly string[], +): number { + if (index !== null) { + const value = point.byIndex.get(index); + if (value !== undefined) return value; + } + for (const key of nameKeys) { + const value = point.byName.get(key); + if (value !== undefined) return value; + } + return 0; +} + +function primaryAmountValue( + point: ParsedDayPoint, + measures: readonly RevenueCatChartMeasure[], +): number { + const moneyIndex = + measureIndexMatching( + measures, + (m, name) => m.unit !== "#" && (name.includes("revenue") || name.includes("proceeds")), + ) ?? + measureIndexMatching(measures, (m) => m.unit !== "#" && m.chartable) ?? + measureIndexMatching(measures, (m) => m.unit !== "#") ?? + 0; + return point.byIndex.get(moneyIndex) ?? point.byName.get("revenue") ?? point.byIndex.get(0) ?? 0; +} + +function primaryCountValue( + point: ParsedDayPoint, + measures: readonly RevenueCatChartMeasure[], +): number { + const countIndex = + measureIndexMatching(measures, (m) => m.unit === "#" && m.chartable) ?? + measureIndexMatching(measures, (m) => m.unit === "#") ?? + 0; + return point.byIndex.get(countIndex) ?? point.byIndex.get(0) ?? 0; +} + +/** + * Combines RevenueCat daily charts (`mrr_movement`, `revenue`, `actives_new`, `customers_new`) + * into normalized daily rows in `currency`'s minor unit. + */ +export function buildDailyMetricRows(input: { + currency: string; + mrrMovement: RevenueCatChartData | null; + revenue: RevenueCatChartData | null; + activesNew: RevenueCatChartData | null; + customersNew: RevenueCatChartData | null; +}): RevenueCatDailyRow[] { + const currency = input.currency.toLowerCase(); + const rows = new Map(); + const ensure = (day: string): RevenueCatDailyRow => { + let row = rows.get(day); + if (!row) { + row = { + day, + currency, + revenue: 0, + mrrNew: 0, + mrrExpansion: 0, + mrrReactivation: 0, + mrrContraction: 0, + mrrChurn: 0, + newPayingCustomers: 0, + newCustomers: 0, + }; + rows.set(day, row); + } + return row; + }; + + if (input.mrrMovement) { + const measures = input.mrrMovement.measures; + const movementCurrency = (input.mrrMovement.currency || currency).toLowerCase(); + const idxNew = measureIndexMatching( + measures, + (_, n) => n.includes("new") && !n.includes("net"), + ); + const idxResub = measureIndexMatching( + measures, + (_, n) => n.includes("resub") || n.includes("reactivat"), + ); + const idxExpansion = measureIndexMatching(measures, (_, n) => n.includes("expansion")); + const idxContraction = measureIndexMatching(measures, (_, n) => n.includes("contraction")); + const idxChurn = measureIndexMatching(measures, (_, n) => n.includes("churn")); + + for (const [day, point] of parseChartValues(input.mrrMovement)) { + const row = ensure(day); + row.mrrNew = Math.max( + 0, + toMinorUnits(pointMeasureValue(point, idxNew, ["new_mrr", "new"]), movementCurrency), + ); + row.mrrReactivation = Math.max( + 0, + toMinorUnits( + pointMeasureValue(point, idxResub, [ + "resubscription_mrr", + "reactivation_mrr", + "resubscription", + ]), + movementCurrency, + ), + ); + row.mrrExpansion = Math.max( + 0, + toMinorUnits( + pointMeasureValue(point, idxExpansion, ["expansion_mrr", "expansion"]), + movementCurrency, + ), + ); + // SaaS Monitor stores contraction and churn as negative integers (<= 0). + row.mrrContraction = -Math.abs( + toMinorUnits( + pointMeasureValue(point, idxContraction, ["contraction_mrr", "contraction"]), + movementCurrency, + ), + ); + row.mrrChurn = -Math.abs( + toMinorUnits( + pointMeasureValue(point, idxChurn, ["churned_mrr", "churn_mrr", "churn"]), + movementCurrency, + ), + ); + } + } + + if (input.revenue) { + const revCurrency = (input.revenue.currency || currency).toLowerCase(); + for (const [day, point] of parseChartValues(input.revenue)) { + const row = ensure(day); + row.revenue = toMinorUnits(primaryAmountValue(point, input.revenue.measures), revCurrency); + } + } + + if (input.activesNew) { + for (const [day, point] of parseChartValues(input.activesNew)) { + const row = ensure(day); + row.newPayingCustomers = Math.max( + 0, + Math.round(primaryCountValue(point, input.activesNew.measures)), + ); + } + } + + if (input.customersNew) { + for (const [day, point] of parseChartValues(input.customersNew)) { + const row = ensure(day); + row.newCustomers = Math.max( + 0, + Math.round(primaryCountValue(point, input.customersNew.measures)), + ); + } + } + + return [...rows.values()].sort((a, b) => a.day.localeCompare(b.day)); +} + +const ISO_DURATION_PATTERN = /^P(\d+)([DWMY])$/i; + +const PERIODS_PER_MONTH: Record = { + day: { numerator: 365, denominator: 12 }, + week: { numerator: 52, denominator: 12 }, + month: { numerator: 1, denominator: 1 }, + year: { numerator: 1, denominator: 12 }, +}; + +const UNIT_TO_INTERVAL: Record = { + D: "day", + W: "week", + M: "month", + Y: "year", +}; + +/** Parses an ISO 8601 RevenueCat product duration (e.g. `P1M`, `P1Y`, `P1W`). */ +export function parseIsoDuration( + duration: string | null | undefined, +): { interval: BillingInterval; count: number } | null { + if (!duration) return null; + const match = ISO_DURATION_PATTERN.exec(duration.trim()); + if (!match) return null; + const count = Number(match[1]); + const interval = UNIT_TO_INTERVAL[match[2].toUpperCase()]; + if (!interval || !Number.isFinite(count) || count <= 0) return null; + return { interval, count }; +} + +/** Infers billing interval & count from period length in ms when product metadata is unavailable. */ +export function inferDurationFromPeriodMs( + periodMs: number | null | undefined, +): { interval: BillingInterval; count: number } | null { + if (!periodMs || !Number.isFinite(periodMs) || periodMs <= 0) return null; + const days = periodMs / DAY_MS; + if (days >= 350 && days <= 380) return { interval: "year", count: 1 }; + if (days >= 175 && days <= 190) return { interval: "month", count: 6 }; + if (days >= 84 && days <= 96) return { interval: "month", count: 3 }; + if (days >= 55 && days <= 65) return { interval: "month", count: 2 }; + if (days >= 26 && days <= 33) return { interval: "month", count: 1 }; + if (days >= 12 && days <= 16) return { interval: "week", count: 2 }; + if (days >= 6 && days <= 8) return { interval: "week", count: 1 }; + if (days >= 1 && days < 6) return { interval: "day", count: Math.max(1, Math.round(days)) }; + return null; +} + +/** Normalizes a subscription price (in minor units) to monthly recurring revenue. */ +export function normalizeMonthlyMrr( + amountMinor: number, + duration: string | null | undefined, + periodMs?: number | null, +): number { + if (amountMinor <= 0) return 0; + const parsed = parseIsoDuration(duration) ?? inferDurationFromPeriodMs(periodMs); + if (parsed) { + const { numerator, denominator } = PERIODS_PER_MONTH[parsed.interval]; + return Math.round((amountMinor * numerator) / (denominator * parsed.count)); + } + if (periodMs && periodMs > 0) { + const days = periodMs / DAY_MS; + return Math.round((amountMinor * 365) / (12 * days)); + } + return amountMinor; +} + +export function billingIntervalOf( + duration: string | null | undefined, + periodMs?: number | null, +): BillingInterval | null { + return (parseIsoDuration(duration) ?? inferDurationFromPeriodMs(periodMs))?.interval ?? null; +} diff --git a/src/server/revenuecat/errors.test.ts b/src/server/revenuecat/errors.test.ts new file mode 100644 index 0000000..38085e5 --- /dev/null +++ b/src/server/revenuecat/errors.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { revenueCatPermissionLabel } from "@/lib/revenuecat-permissions"; +import { + describeRevenueCatAccessError, + redactRevenueCatSecrets, + RevenueCatAccessError, +} from "./errors"; + +describe("redactRevenueCatSecrets", () => { + it("masks RevenueCat secret keys in error text", () => { + expect(redactRevenueCatSecrets("Invalid key sk_AbCdEfGh1234567890 received")).toBe( + "Invalid key sk_… received", + ); + }); +}); + +describe("RevenueCatAccessError", () => { + it("marks rate_limited and unavailable errors as transient", () => { + expect(new RevenueCatAccessError("rate_limited", "Too many requests").isTransient).toBe(true); + expect(new RevenueCatAccessError("unavailable", "Timeout").isTransient).toBe(true); + expect(new RevenueCatAccessError("authentication", "Unauthorized").isTransient).toBe(false); + expect(new RevenueCatAccessError("permission", "Forbidden").isTransient).toBe(false); + }); + + it("describes missing permissions using dashboard labels", () => { + const error = new RevenueCatAccessError("permission", "Forbidden", { + permission: "charts_metrics:charts:read", + }); + expect(describeRevenueCatAccessError(error)).toContain( + revenueCatPermissionLabel("charts_metrics:charts:read"), + ); + }); +}); diff --git a/src/server/revenuecat/errors.ts b/src/server/revenuecat/errors.ts new file mode 100644 index 0000000..9357230 --- /dev/null +++ b/src/server/revenuecat/errors.ts @@ -0,0 +1,57 @@ +import "server-only"; +import { revenueCatPermissionLabel } from "@/lib/revenuecat-permissions"; + +export type RevenueCatErrorKind = + /** 401: the key is invalid, revoked or is a v1 key. */ + | "authentication" + /** 403: the v2 key lacks a required permission or project access. */ + | "permission" + | "not_found" + /** 429: rate limit exceeded for the endpoint's domain; retry later. */ + | "rate_limited" + /** Network failure, timeout or RevenueCat outage; retry later. */ + | "unavailable" + /** Any other rejected request (400/422). */ + | "invalid_request"; + +export class RevenueCatAccessError extends Error { + readonly kind: RevenueCatErrorKind; + readonly permission: string | null; + readonly retryAfterSeconds: number | null; + + constructor( + kind: RevenueCatErrorKind, + message: string, + details: { permission?: string | null; retryAfterSeconds?: number | null } = {}, + ) { + super(message); + this.name = "RevenueCatAccessError"; + this.kind = kind; + this.permission = details.permission ?? null; + this.retryAfterSeconds = details.retryAfterSeconds ?? null; + } + + get isTransient(): boolean { + return this.kind === "rate_limited" || this.kind === "unavailable"; + } +} + +/** Strips anything that looks like a RevenueCat secret key before logs or database writes. */ +export function redactRevenueCatSecrets(text: string): string { + return text.replace(/\b(sk_)[A-Za-z0-9_-]{8,}/g, "$1…"); +} + +export const REVENUECAT_UNREADABLE_KEY_ERROR = + "The saved RevenueCat key can no longer be decrypted (was ENCRYPTION_KEY changed?). Connect the account again."; + +export function describeRevenueCatAccessError(error: RevenueCatAccessError): string { + if (error.kind === "authentication") { + return "This RevenueCat key was revoked or is not a valid v2 secret key. Connect the account again with a new key."; + } + if (error.kind === "permission") { + return error.permission + ? `This RevenueCat key is missing the “${revenueCatPermissionLabel(error.permission)}” permission. Edit the key in RevenueCat to add it.` + : "This RevenueCat key is missing a permission. Edit the key in RevenueCat and allow the permissions listed in the setup guide."; + } + return "RevenueCat could not be reached. We will try again shortly."; +} diff --git a/src/server/revenuecat/gateway.ts b/src/server/revenuecat/gateway.ts new file mode 100644 index 0000000..e421dde --- /dev/null +++ b/src/server/revenuecat/gateway.ts @@ -0,0 +1,331 @@ +import "server-only"; +import { z } from "zod"; +import { parseOverviewMetrics } from "./charts"; +import { redactRevenueCatSecrets, RevenueCatAccessError } from "./errors"; +import type { + RevenueCatChartData, + RevenueCatOverview, + RevenueCatProduct, + RevenueCatProject, +} from "./types"; + +const DEFAULT_BASE_URL = "https://api.revenuecat.com/v2"; +const REQUEST_TIMEOUT_MS = 20_000; +const MAX_RETRIES = 2; +const MAX_RETRY_WAIT_MS = 2_000; + +export interface RevenueCatGateway { + readonly requestCount: number; + listProjects(): Promise; + getOverviewMetrics(projectId: string, currency?: string): Promise; + getChartData( + projectId: string, + chartName: string, + params: { startDate: string; endDate: string; resolution?: string; currency?: string }, + ): Promise; + listProducts(projectId: string): Promise; + createWebhookIntegration( + projectId: string, + input: { + name: string; + url: string; + authorizationHeader: string; + environment: "production" | "sandbox"; + eventTypes: readonly string[]; + }, + ): Promise<{ id: string; signingSecret: string | null }>; + deleteWebhookIntegration(projectId: string, webhookId: string): Promise; +} + +export type RevenueCatGatewayFactory = (secretKey: string) => RevenueCatGateway; + +export interface RevenueCatAccessOptions { + createGateway?: RevenueCatGatewayFactory; +} + +const projectSchema = z.object({ + id: z.string(), + name: z.string(), +}); + +const listProjectsSchema = z.object({ + items: z.array(projectSchema), + next_page: z.string().nullable().optional(), +}); + +const overviewSchema = z.object({ + currency: z.string().optional(), + metrics: z + .array( + z.object({ + id: z.string().optional(), + value: z.number().optional(), + last_updated_at: z.number().nullable().optional(), + }), + ) + .optional(), +}); + +const chartDataSchema = z.object({ + yaxis_currency: z.string().optional(), + resolution: z.string().optional(), + measures: z + .array( + z.object({ + display_name: z.string().optional(), + unit: z.string().nullable().optional(), + chartable: z.boolean().optional(), + }), + ) + .nullable() + .optional(), + values: z.array(z.unknown()).optional(), +}); + +const productSchema = z.object({ + id: z.string(), + store_identifier: z.string(), + display_name: z.string().nullable().optional(), + type: z.string(), + subscription: z + .object({ + duration: z.string().nullable().optional(), + }) + .nullable() + .optional(), +}); + +const listProductsSchema = z.object({ + items: z.array(productSchema), + next_page: z.string().nullable().optional(), +}); + +const webhookIntegrationSchema = z.object({ + id: z.string(), + signing_secret: z.string().nullable().optional(), +}); + +const errorBodySchema = z.object({ + type: z.string().optional(), + message: z.string().optional(), + backoff_ms: z.number().nullable().optional(), +}); + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export function createRevenueCatGateway( + secretKey: string, + baseUrl: string = DEFAULT_BASE_URL, +): RevenueCatGateway { + const root = baseUrl.replace(/\/+$/, ""); + let requestCount = 0; + + async function request( + path: string, + options: { + method?: "GET" | "POST" | "DELETE"; + body?: unknown; + permission?: string; + } = {}, + ): Promise { + const url = path.startsWith("http") + ? path + : `${root}${path.startsWith("/") ? path : `/${path}`}`; + const method = options.method ?? "GET"; + + for (let attempt = 0; ; attempt += 1) { + requestCount += 1; + let response: Response; + try { + response = await fetch(url, { + method, + headers: { + Authorization: `Bearer ${secretKey}`, + Accept: "application/json", + ...(options.body !== undefined && { "Content-Type": "application/json" }), + }, + body: options.body !== undefined ? JSON.stringify(options.body) : undefined, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (error) { + if (attempt < MAX_RETRIES) { + await sleep(Math.min(MAX_RETRY_WAIT_MS, 400 * 2 ** attempt)); + continue; + } + const message = redactRevenueCatSecrets( + error instanceof Error ? error.message : String(error), + ); + throw new RevenueCatAccessError("unavailable", message); + } + + if (response.ok) { + if (response.status === 204) return undefined as T; + return (await response.json()) as T; + } + + const rawText = await response.text().catch(() => ""); + let parsedError: z.infer | null = null; + try { + parsedError = errorBodySchema.parse(JSON.parse(rawText)); + } catch { + parsedError = null; + } + const message = redactRevenueCatSecrets( + parsedError?.message || `RevenueCat API returned ${response.status}`, + ); + const retryAfterHeader = Number(response.headers.get("retry-after")); + const retryAfterSeconds = + Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 + ? retryAfterHeader + : parsedError?.backoff_ms + ? Math.ceil(parsedError.backoff_ms / 1000) + : null; + + if ((response.status === 429 || response.status >= 500) && attempt < MAX_RETRIES) { + const waitMs = Math.min( + MAX_RETRY_WAIT_MS, + retryAfterSeconds ? retryAfterSeconds * 1000 : 500 * 2 ** attempt, + ); + await sleep(waitMs); + continue; + } + + switch (response.status) { + case 401: + throw new RevenueCatAccessError("authentication", message); + case 403: + throw new RevenueCatAccessError("permission", message, { + permission: options.permission ?? null, + }); + case 404: + throw new RevenueCatAccessError("not_found", message); + case 429: + throw new RevenueCatAccessError("rate_limited", message, { retryAfterSeconds }); + default: + throw new RevenueCatAccessError( + response.status >= 500 ? "unavailable" : "invalid_request", + message, + ); + } + } + } + + return { + get requestCount() { + return requestCount; + }, + + async listProjects() { + const items: RevenueCatProject[] = []; + let path: string | null = "/projects?limit=100"; + while (path) { + const raw = await request(path, { + permission: "project_configuration:projects:read", + }); + const page = listProjectsSchema.parse(raw); + items.push(...page.items); + path = page.next_page ? stripV2Prefix(page.next_page) : null; + } + return items; + }, + + async getOverviewMetrics(projectId, currency = "USD") { + const params = new URLSearchParams({ currency: currency.toUpperCase() }); + const raw = await request( + `/projects/${encodeURIComponent(projectId)}/metrics/overview?${params.toString()}`, + { permission: "charts_metrics:overview:read" }, + ); + return parseOverviewMetrics(overviewSchema.parse(raw), new Date()); + }, + + async getChartData(projectId, chartName, { startDate, endDate, resolution = "0", currency }) { + const params = new URLSearchParams({ + realtime: "true", + resolution, + start_date: startDate, + end_date: endDate, + }); + if (currency) params.set("currency", currency.toUpperCase()); + const raw = await request( + `/projects/${encodeURIComponent(projectId)}/charts/${encodeURIComponent(chartName)}?${params.toString()}`, + { permission: "charts_metrics:charts:read" }, + ); + const parsed = chartDataSchema.parse(raw); + return { + currency: (parsed.yaxis_currency ?? currency ?? "USD").toLowerCase(), + resolution: parsed.resolution ?? "day", + measures: (parsed.measures ?? []).map((m) => ({ + displayName: m.display_name ?? "", + unit: m.unit ?? null, + chartable: m.chartable ?? true, + })), + values: parsed.values ?? [], + }; + }, + + async listProducts(projectId) { + const items: RevenueCatProduct[] = []; + let path: string | null = `/projects/${encodeURIComponent(projectId)}/products?limit=100`; + // Cap pagination to keep sync bounded on unusually large catalogs. + for (let pageIndex = 0; path && pageIndex < 20; pageIndex += 1) { + const raw = await request(path, { + permission: "project_configuration:products:read", + }); + const page = listProductsSchema.parse(raw); + for (const product of page.items) { + items.push({ + id: product.id, + storeIdentifier: product.store_identifier, + displayName: product.display_name ?? null, + type: product.type, + duration: product.subscription?.duration ?? null, + }); + } + path = page.next_page ? stripV2Prefix(page.next_page) : null; + } + return items; + }, + + async createWebhookIntegration(projectId, input) { + const raw = await request( + `/projects/${encodeURIComponent(projectId)}/integrations/webhooks`, + { + method: "POST", + permission: "project_configuration:integrations:read_write", + body: { + name: input.name, + url: input.url, + authorization_header: input.authorizationHeader, + environment: input.environment, + event_types: [...input.eventTypes], + status: "active", + }, + }, + ); + const created = webhookIntegrationSchema.parse(raw); + return { id: created.id, signingSecret: created.signing_secret ?? null }; + }, + + async deleteWebhookIntegration(projectId, webhookId) { + try { + await request( + `/projects/${encodeURIComponent(projectId)}/integrations/webhooks/${encodeURIComponent(webhookId)}`, + { + method: "DELETE", + permission: "project_configuration:integrations:read_write", + }, + ); + } catch (error) { + if (error instanceof RevenueCatAccessError && error.kind === "not_found") return; + throw error; + } + }, + }; +} + +/** RevenueCat `next_page` starts with `/v2/...`; strip `/v2` because `baseUrl` already ends with it. */ +function stripV2Prefix(nextPage: string): string { + return nextPage.startsWith("/v2/") ? nextPage.slice(3) : nextPage; +} diff --git a/src/server/revenuecat/keys.test.ts b/src/server/revenuecat/keys.test.ts new file mode 100644 index 0000000..3d40d2d --- /dev/null +++ b/src/server/revenuecat/keys.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { + inspectRevenueCatSecretKey, + revenueCatProjectIdSchema, + revenueCatSecretKeySchema, +} from "./keys"; + +describe("inspectRevenueCatSecretKey", () => { + it("accepts a valid RevenueCat API v2 secret key and masks it", () => { + const result = inspectRevenueCatSecretKey(" sk_AbCdEfGhIjKlMnOpQrSt1234 "); + expect(result).toEqual({ + ok: true, + key: "sk_AbCdEfGhIjKlMnOpQrSt1234", + hint: "sk_…1234", + }); + }); + + it("rejects Stripe keys with a helpful message", () => { + const stripeKey = inspectRevenueCatSecretKey("sk_live_1234567890abcdef1234"); + expect(stripeKey.ok).toBe(false); + if (!stripeKey.ok) expect(stripeKey.error).toContain("Stripe"); + + const restrictedKey = inspectRevenueCatSecretKey("rk_test_1234567890abcdef1234"); + expect(restrictedKey.ok).toBe(false); + }); + + it("rejects public RevenueCat SDK keys", () => { + for (const prefix of ["appl_", "goog_", "amzn_", "strp_", "rcb_", "test_"]) { + const result = inspectRevenueCatSecretKey(`${prefix}1234567890abcdef1234`); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toContain("public SDK key"); + } + }); + + it("rejects malformed or short keys", () => { + expect(inspectRevenueCatSecretKey("sk_short").ok).toBe(false); + expect(inspectRevenueCatSecretKey("not_a_key_at_all_12345678").ok).toBe(false); + }); +}); + +describe("revenueCatSecretKeySchema", () => { + it("transforms valid strings into a key and hint", () => { + const parsed = revenueCatSecretKeySchema.parse("sk_9876543210abcdefWXYZ"); + expect(parsed).toEqual({ key: "sk_9876543210abcdefWXYZ", hint: "sk_…WXYZ" }); + }); +}); + +describe("revenueCatProjectIdSchema", () => { + it("normalizes blank input to undefined and trims valid ids", () => { + expect(revenueCatProjectIdSchema.parse("")).toBeUndefined(); + expect(revenueCatProjectIdSchema.parse(" ")).toBeUndefined(); + expect(revenueCatProjectIdSchema.parse(" proj1ab2c3d4 ")).toBe("proj1ab2c3d4"); + }); +}); diff --git a/src/server/revenuecat/keys.ts b/src/server/revenuecat/keys.ts new file mode 100644 index 0000000..a6a94a2 --- /dev/null +++ b/src/server/revenuecat/keys.ts @@ -0,0 +1,59 @@ +import "server-only"; +import { z } from "zod"; +import type { ActionResult } from "@/lib/action-result"; + +/** A RevenueCat API v2 secret key whose format was checked. */ +export interface RevenueCatSecretKey { + key: string; + /** Masked key, e.g. `sk_…4f2a`. */ + hint: string; +} + +const STRIPE_KEY_PREFIX = /^(?:sk|rk|pk)_(?:live|test)_/; +const PUBLIC_SDK_KEY_PREFIX = /^(?:appl|goog|amzn|strp|rcb|test)_/; +const SECRET_KEY_PATTERN = /^sk_[A-Za-z0-9_-]{16,}$/; + +/** Checks the format of a pasted RevenueCat API v2 secret key before sending it to RevenueCat. */ +export function inspectRevenueCatSecretKey(input: string): ActionResult { + const key = input.trim(); + if (STRIPE_KEY_PREFIX.test(key)) { + return { + ok: false, + error: "This looks like a Stripe key. Paste a RevenueCat API v2 secret key instead.", + }; + } + if (PUBLIC_SDK_KEY_PREFIX.test(key)) { + return { + ok: false, + error: "This is a public SDK key. Paste a secret API v2 key instead (it starts with sk_).", + }; + } + if (!SECRET_KEY_PATTERN.test(key)) { + return { + ok: false, + error: "This doesn’t look like a RevenueCat secret key. API v2 secret keys start with sk_.", + }; + } + return { ok: true, key, hint: `sk_…${key.slice(-4)}` }; +} + +/** A pasted API key, read into a `RevenueCatSecretKey`. */ +export const revenueCatSecretKeySchema = z + .string() + .max(500, "This doesn’t look like a RevenueCat secret key.") + .transform((input, context): RevenueCatSecretKey => { + const inspection = inspectRevenueCatSecretKey(input); + if (!inspection.ok) { + context.addIssue({ code: "custom", message: inspection.error }); + return z.NEVER; + } + return { key: inspection.key, hint: inspection.hint }; + }); + +/** Optional RevenueCat project id (`proj…`), needed only when a key can read multiple projects. */ +export const revenueCatProjectIdSchema = z + .string() + .trim() + .max(255) + .transform((value) => (value.length ? value : undefined)) + .optional(); diff --git a/src/server/revenuecat/sync.db.test.ts b/src/server/revenuecat/sync.db.test.ts new file mode 100644 index 0000000..97080d3 --- /dev/null +++ b/src/server/revenuecat/sync.db.test.ts @@ -0,0 +1,205 @@ +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it } from "vitest"; +import { db } from "@/db"; +import { stripeAccounts } from "@/db/schema"; +import { encryptSecret } from "@/server/crypto"; +import { getDisplayStateByToken } from "@/server/display/state"; +import { connectRevenueCatAccount } from "@/server/revenuecat/accounts"; +import type { RevenueCatGateway } from "@/server/revenuecat/gateway"; +import { revenueCatSecretKeySchema } from "@/server/revenuecat/keys"; +import { receiveRevenueCatWebhook } from "@/server/revenuecat/webhooks"; +import { createScreen } from "@/server/screens"; +import { listStripeAccountSummaries } from "@/server/stripe/accounts"; +import { syncAccount } from "@/server/sync/run"; +import { createUserWithWorkspace, resetDatabase } from "@/test/db"; + +const NOW = new Date("2026-11-25T12:00:00.000Z"); + +function fakeRevenueCatGateway(): RevenueCatGateway { + const dayToday = Date.UTC(2026, 10, 25) / 1000; + const dayYesterday = Date.UTC(2026, 10, 24) / 1000; + let requests = 0; + + return { + get requestCount() { + return requests; + }, + async listProjects() { + requests += 1; + return [{ id: "proj_rc_1", name: "Mobile App" }]; + }, + async getOverviewMetrics() { + requests += 1; + return { + currency: "usd", + mrr: 50000, + activeSubscriptions: 25, + activeTrials: 4, + updatedAt: new Date("2026-11-25T11:00:00.000Z"), + }; + }, + async getChartData(_projectId, chartName) { + requests += 1; + if (chartName === "mrr_movement") { + return { + currency: "usd", + resolution: "day", + measures: [ + { displayName: "New MRR", unit: "$", chartable: true }, + { displayName: "Churned MRR", unit: "$", chartable: true }, + ], + values: [ + { cohort: dayYesterday, measure: 0, value: 40 }, + { cohort: dayToday, measure: 0, value: 20 }, + { cohort: dayToday, measure: 1, value: 10 }, + ], + }; + } + if (chartName === "revenue") { + return { + currency: "usd", + resolution: "day", + measures: [{ displayName: "Revenue", unit: "$", chartable: true }], + values: [ + { cohort: dayYesterday, measure: 0, value: 120 }, + { cohort: dayToday, measure: 0, value: 80 }, + ], + }; + } + if (chartName === "actives_new") { + return { + currency: "usd", + resolution: "day", + measures: [{ displayName: "New Paid Subscriptions", unit: "#", chartable: true }], + values: [[dayToday, 3]], + }; + } + return { + currency: "usd", + resolution: "day", + measures: [{ displayName: "New Customers", unit: "#", chartable: true }], + values: [[dayToday, 11]], + }; + }, + async listProducts() { + requests += 1; + return [ + { + id: "prod_1", + storeIdentifier: "com.acme.pro_monthly", + displayName: "Pro Monthly", + type: "subscription", + duration: "P1M", + }, + ]; + }, + async createWebhookIntegration() { + requests += 1; + return { id: "wh_rc_1", signingSecret: "rc_hmac_secret" }; + }, + async deleteWebhookIntegration() { + requests += 1; + }, + }; +} + +describe("RevenueCat end-to-end sync, webhooks, and display state", () => { + beforeEach(resetDatabase); + + it("imports RevenueCat metrics, applies a live webhook, and computes display state", async () => { + const { workspaceId } = await createUserWithWorkspace(); + const gateway = fakeRevenueCatGateway(); + + const connected = await connectRevenueCatAccount( + { + workspaceId, + name: "Acme iOS", + secretKey: revenueCatSecretKeySchema.parse("sk_AbCdEfGhIjKlMnOp1234"), + }, + { createGateway: () => gateway }, + ); + expect(connected.ok).toBe(true); + if (!connected.ok) return; + + const report = await syncAccount(connected.accountId, { + createRevenueCatGateway: () => gateway, + now: () => NOW, + }); + expect(report?.ok).toBe(true); + + const summaries = await listStripeAccountSummaries(workspaceId); + expect(summaries).toHaveLength(1); + expect(summaries[0]).toMatchObject({ + provider: "revenuecat", + name: "Acme iOS", + status: "ready", + mrr: { amount: 50000, currency: "usd" }, + }); + + // Configure a manual webhook secret and send a live INITIAL_PURCHASE after overviewUpdatedAt. + await db() + .update(stripeAccounts) + .set({ encryptedWebhookSecret: encryptSecret("Bearer test-rc-webhook-token") }) + .where(eq(stripeAccounts.id, connected.accountId)); + + const payload = JSON.stringify({ + api_version: "1.0", + event: { + id: "rc_evt_live_1", + type: "INITIAL_PURCHASE", + environment: "PRODUCTION", + event_timestamp_ms: new Date("2026-11-25T11:30:00.000Z").getTime(), + purchased_at_ms: new Date("2026-11-25T11:30:00.000Z").getTime(), + expiration_at_ms: new Date("2026-12-25T11:30:00.000Z").getTime(), + app_user_id: "user_42", + original_app_user_id: "user_42", + product_id: "com.acme.pro_monthly", + period_type: "NORMAL", + transaction_id: "txn_live_1", + original_transaction_id: "txn_live_1", + currency: "USD", + price: 15, + price_in_purchased_currency: 15, + country_code: "FR", + subscriber_attributes: { + $displayName: { value: "Marie Curie" }, + }, + }, + }); + + const outcome = await receiveRevenueCatWebhook( + connected.accountId, + payload, + { signature: null, authorization: "Bearer test-rc-webhook-token" }, + { now: NOW }, + ); + expect(outcome).toEqual({ status: "accepted", notify: true, sync: true }); + + const createdScreen = await createScreen(workspaceId, { name: "Wall", timeZone: "UTC" }); + expect(createdScreen.ok).toBe(true); + if (!createdScreen.ok) return; + + const [{ publicToken }] = await db().query.screens.findMany({ + columns: { publicToken: true }, + }); + const state = await getDisplayStateByToken(publicToken, { now: NOW }); + expect(state).not.toBeNull(); + if (!state) return; + + expect(state.status).toBe("ready"); + // Overview $500 MRR + live $15 MRR webhook after overviewUpdatedAt = $515 MRR. + expect(state.metrics.mrr).toBe(51500); + expect(state.metrics.activeCustomers).toBe(25); + expect(state.metrics.trialingSubscriptions).toBe(4); + // Today revenue: $80 from chart + $15 live webhook = $95; yesterday $120. + expect(state.metrics.revenue.today).toBe(9500); + expect(state.metrics.revenue.yesterday).toBe(12000); + expect(state.metrics.thisMonth.newCustomers).toBe(3); + expect(state.metrics.customersCreatedToday).toBe(11); + expect( + state.feed.some( + (item) => item.kind === "new" && item.live && item.planName === "Pro Monthly", + ), + ).toBe(true); + }); +}); diff --git a/src/server/revenuecat/sync.ts b/src/server/revenuecat/sync.ts new file mode 100644 index 0000000..b3bf409 --- /dev/null +++ b/src/server/revenuecat/sync.ts @@ -0,0 +1,318 @@ +import "server-only"; +import { eq, sql } from "drizzle-orm"; +import { db } from "@/db"; +import { + revenuecatDailyMetrics, + revenuecatMetrics, + stripeAccounts, + type RevenueCatProductEntry, + type ScanProgress, +} from "@/db/schema"; +import { DAY_MS } from "@/lib/durations"; +import { decryptSecret } from "@/server/crypto"; +import { + releaseSyncLease, + type AccountUpdate, + type StripeAccountRow, + type SyncLease, +} from "@/server/sync/lease"; +import { retryDelaySeconds, SAFETY_NET_INTERVAL_SECONDS } from "@/server/sync/policy"; +import type { SyncMode, SyncReport } from "@/server/sync/run"; +import { buildDailyMetricRows } from "./charts"; +import { + describeRevenueCatAccessError, + redactRevenueCatSecrets, + REVENUECAT_UNREADABLE_KEY_ERROR, + RevenueCatAccessError, +} from "./errors"; +import { + createRevenueCatGateway, + type RevenueCatGateway, + type RevenueCatGatewayFactory, +} from "./gateway"; + +/** Historical chart lookbacks, matching SaaS Monitor's 12m chart, 2-month revenue, and today's sign-ups. */ +const MRR_MOVEMENT_DAYS = 365; +const REVENUE_DAYS = 65; +const ACTIVES_NEW_DAYS = 35; +const CUSTOMERS_NEW_DAYS = 7; + +export interface RevenueCatSyncOptions { + createGateway?: RevenueCatGatewayFactory; + now?: () => Date; +} + +class UnreadableRevenueCatKeyError extends Error {} + +export function newRevenueCatBackfill(now: Date): ScanProgress { + return { + phase: "subscriptions", + cursor: null, + startedAt: now.toISOString(), + paymentsSince: null, + customersSince: null, + subscriptions: 0, + payments: 0, + customers: 0, + }; +} + +function utcDayOffset(now: Date, daysAgo: number): string { + return new Date(now.getTime() - daysAgo * DAY_MS).toISOString().slice(0, 10); +} + +/** + * Syncs a RevenueCat project from RevenueCat REST API v2: + * - Overview metrics (`mrr`, `active_subscriptions`, `active_trials`) + * - Daily charts (`mrr_movement`, `revenue`, `actives_new`, `customers_new`) + * - Product catalog (best effort, for webhook display names and durations) + */ +export async function syncRevenueCatAccount( + lease: SyncLease, + options: RevenueCatSyncOptions = {}, +): Promise { + const startedAt = performance.now(); + const { account } = lease; + const now = options.now?.() ?? new Date(); + const mode: SyncMode = account.backfill ? "import" : "incremental"; + let gateway: RevenueCatGateway | null = null; + let changes = 0; + + const report = (ok: boolean): SyncReport => ({ + accountId: account.id, + mode, + ok, + changes, + requests: gateway?.requestCount ?? 0, + durationMs: Math.round(performance.now() - startedAt), + }); + + try { + const projectId = account.stripeAccountId; + if (!projectId) { + throw new RevenueCatAccessError("invalid_request", "Missing RevenueCat project identifier."); + } + gateway = (options.createGateway ?? createRevenueCatGateway)(readSecretKey(account)); + + const currency = (account.defaultCurrency ?? "usd").toUpperCase(); + const today = utcDayOffset(now, 0); + + const overview = await gateway.getOverviewMetrics(projectId, currency); + const chartCurrency = overview.currency.toUpperCase(); + + const [mrrMovement, revenue, activesNew, customersNew, products] = await Promise.all([ + gateway.getChartData(projectId, "mrr_movement", { + startDate: utcDayOffset(now, MRR_MOVEMENT_DAYS), + endDate: today, + resolution: "0", + currency: chartCurrency, + }), + gateway.getChartData(projectId, "revenue", { + startDate: utcDayOffset(now, REVENUE_DAYS), + endDate: today, + resolution: "0", + currency: chartCurrency, + }), + optionalChart(() => + gateway!.getChartData(projectId, "actives_new", { + startDate: utcDayOffset(now, ACTIVES_NEW_DAYS), + endDate: today, + resolution: "0", + }), + ), + optionalChart(() => + gateway!.getChartData(projectId, "customers_new", { + startDate: utcDayOffset(now, CUSTOMERS_NEW_DAYS), + endDate: today, + resolution: "0", + }), + ), + optionalProducts(() => gateway!.listProducts(projectId)), + ]); + + const dailyRows = buildDailyMetricRows({ + currency: overview.currency, + mrrMovement, + revenue, + activesNew, + customersNew, + }); + const productMap: Record = {}; + for (const product of products) { + const displayName = product.displayName || product.storeIdentifier; + const entry = { displayName, duration: product.duration }; + productMap[product.storeIdentifier] = entry; + productMap[product.id] = entry; + } + + await db().transaction(async (tx) => { + await tx + .insert(revenuecatMetrics) + .values({ + accountId: account.id, + currency: overview.currency, + mrr: overview.mrr, + activeSubscriptions: overview.activeSubscriptions, + activeTrials: overview.activeTrials, + overviewUpdatedAt: overview.updatedAt, + products: productMap, + }) + .onDuplicateKeyUpdate({ + set: { + currency: overview.currency, + mrr: overview.mrr, + activeSubscriptions: overview.activeSubscriptions, + activeTrials: overview.activeTrials, + overviewUpdatedAt: overview.updatedAt, + ...(products.length > 0 ? { products: productMap } : {}), + }, + }); + + const chunkSize = 100; + for (let i = 0; i < dailyRows.length; i += chunkSize) { + const chunk = dailyRows.slice(i, i + chunkSize).map((row) => ({ + accountId: account.id, + ...row, + })); + await tx + .insert(revenuecatDailyMetrics) + .values(chunk) + .onDuplicateKeyUpdate({ + set: { + currency: sql`values(${revenuecatDailyMetrics.currency})`, + revenue: sql`values(${revenuecatDailyMetrics.revenue})`, + mrrNew: sql`values(${revenuecatDailyMetrics.mrrNew})`, + mrrExpansion: sql`values(${revenuecatDailyMetrics.mrrExpansion})`, + mrrReactivation: sql`values(${revenuecatDailyMetrics.mrrReactivation})`, + mrrContraction: sql`values(${revenuecatDailyMetrics.mrrContraction})`, + mrrChurn: sql`values(${revenuecatDailyMetrics.mrrChurn})`, + newPayingCustomers: sql`values(${revenuecatDailyMetrics.newPayingCustomers})`, + newCustomers: sql`values(${revenuecatDailyMetrics.newCustomers})`, + }, + }); + } + + await tx + .update(stripeAccounts) + .set({ + defaultCurrency: overview.currency, + backfill: null, + reconcile: null, + status: "ready", + lastError: null, + lastReconciledAt: now, + }) + .where(eq(stripeAccounts.id, account.id)); + }); + + changes = dailyRows.length; + + await releaseSyncLease(lease, { + lastSyncedAt: now, + syncFailures: 0, + lastError: null, + status: "ready", + }); + + const result = report(true); + console.info( + `[sync:revenuecat] account=${account.id} mode=${mode} days=${result.changes} requests=${result.requests} duration=${result.durationMs}ms`, + ); + return result; + } catch (error) { + const failure = describeFailure(account, error, now); + await releaseSyncLease(lease, failure.values); + const result = report(false); + const line = `[sync:revenuecat] account=${account.id} mode=${mode} failed after ${result.durationMs}ms (requests=${result.requests}): ${failure.reason}; next attempt in ${failure.retryInSeconds}s`; + if (failure.expected) console.warn(line); + else console.error(line, error); + return result; + } +} + +async function optionalChart(load: () => Promise): Promise { + try { + return await load(); + } catch (error) { + if ( + error instanceof RevenueCatAccessError && + (error.kind === "authentication" || error.kind === "permission") + ) { + throw error; + } + return null; + } +} + +async function optionalProducts(load: () => Promise): Promise { + try { + return await load(); + } catch (error) { + // `project_configuration:products:read` is optional; skip silently if absent. + if (error instanceof RevenueCatAccessError && error.kind === "permission") return []; + if (error instanceof RevenueCatAccessError && error.kind === "authentication") throw error; + return []; + } +} + +function readSecretKey(account: StripeAccountRow): string { + try { + return decryptSecret(account.encryptedSecretKey); + } catch { + throw new UnreadableRevenueCatKeyError("The stored RevenueCat key cannot be decrypted."); + } +} + +function actionFor(error: unknown): string | null { + if (error instanceof UnreadableRevenueCatKeyError) return REVENUECAT_UNREADABLE_KEY_ERROR; + if ( + error instanceof RevenueCatAccessError && + (error.kind === "authentication" || error.kind === "permission") + ) { + return describeRevenueCatAccessError(error); + } + return null; +} + +function describeFailure( + account: StripeAccountRow, + error: unknown, + now: Date, +): { + values: AccountUpdate; + reason: string; + retryInSeconds: number; + expected: boolean; +} { + const syncFailures = account.syncFailures + 1; + const retryAt = (seconds: number) => new Date(now.getTime() + seconds * 1000); + + const userMessage = actionFor(error); + if (userMessage) { + return { + values: { + status: "error", + lastError: userMessage, + syncFailures, + syncLockedUntil: retryAt(SAFETY_NET_INTERVAL_SECONDS), + }, + reason: userMessage, + retryInSeconds: SAFETY_NET_INTERVAL_SECONDS, + expected: true, + }; + } + + const isRcError = error instanceof RevenueCatAccessError; + const retryInSeconds = Math.max( + retryDelaySeconds(syncFailures), + isRcError && error.retryAfterSeconds ? error.retryAfterSeconds : 0, + ); + return { + values: { syncFailures, syncLockedUntil: retryAt(retryInSeconds) }, + reason: isRcError + ? `${error.kind}: ${error.message}` + : redactRevenueCatSecrets(error instanceof Error ? error.message : String(error)), + retryInSeconds, + expected: isRcError && error.isTransient, + }; +} diff --git a/src/server/revenuecat/types.ts b/src/server/revenuecat/types.ts new file mode 100644 index 0000000..dc37c35 --- /dev/null +++ b/src/server/revenuecat/types.ts @@ -0,0 +1,70 @@ +/** + * Small views of the RevenueCat REST API v2 and webhook objects the app reads. + * Amounts in `RevenueCatOverview` and chart parsers are normalized to integer minor units + * (e.g. cents) at the boundary, matching the rest of the app. + */ + +export interface RevenueCatProject { + id: string; + name: string; +} + +export interface RevenueCatOverviewMetric { + id: string; + name: string; + unit: string; + period: string; + value: number; + lastUpdatedAt: Date | null; +} + +export interface RevenueCatOverview { + /** ISO 4217 code, lowercase (e.g. `usd`). */ + currency: string; + /** Current MRR in minor units of `currency`. */ + mrr: number; + /** Active paying subscriptions. */ + activeSubscriptions: number; + /** Active free trials. */ + activeTrials: number; + /** Most recent update timestamp reported by RevenueCat. */ + updatedAt: Date; +} + +export interface RevenueCatChartMeasure { + displayName: string; + unit: string | null; + chartable: boolean; +} + +export interface RevenueCatChartData { + currency: string; + resolution: string; + measures: RevenueCatChartMeasure[]; + values: unknown[]; +} + +export interface RevenueCatProduct { + id: string; + storeIdentifier: string; + displayName: string | null; + type: string; + /** ISO 8601 duration (`P1W`, `P1M`, `P2M`, `P3M`, `P6M`, `P1Y`) or `null`. */ + duration: string | null; +} + +export interface RevenueCatDailyRow { + /** `YYYY-MM-DD` UTC calendar day. */ + day: string; + currency: string; + revenue: number; + mrrNew: number; + mrrExpansion: number; + mrrReactivation: number; + /** Stored <= 0, matching `mrrMovements`. */ + mrrContraction: number; + /** Stored <= 0, matching `mrrMovements`. */ + mrrChurn: number; + newPayingCustomers: number; + newCustomers: number; +} diff --git a/src/server/revenuecat/webhooks.test.ts b/src/server/revenuecat/webhooks.test.ts new file mode 100644 index 0000000..bb5e1e2 --- /dev/null +++ b/src/server/revenuecat/webhooks.test.ts @@ -0,0 +1,114 @@ +import { createHmac } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { formatProductId, verifyRevenueCatWebhook } from "./webhooks"; + +describe("verifyRevenueCatWebhook", () => { + const payload = JSON.stringify({ api_version: "1.0", event: { id: "evt_1", type: "RENEWAL" } }); + const nowSeconds = 1_700_000_000; + + it("verifies a valid X-RevenueCat-Webhook-Signature HMAC header", () => { + const secret = "rc_signing_secret_1234567890"; + const sig = createHmac("sha256", secret).update(`${nowSeconds}.${payload}`).digest("hex"); + const header = `t=${nowSeconds},v1=${sig}`; + + expect( + verifyRevenueCatWebhook( + payload, + { signature: header, authorization: null }, + secret, + nowSeconds, + ), + ).toBe(true); + }); + + it("rejects an expired or tampered HMAC signature", () => { + const secret = "rc_signing_secret_1234567890"; + const staleTs = nowSeconds - 600; + const staleSig = createHmac("sha256", secret).update(`${staleTs}.${payload}`).digest("hex"); + + expect( + verifyRevenueCatWebhook( + payload, + { signature: `t=${staleTs},v1=${staleSig}`, authorization: null }, + secret, + nowSeconds, + ), + ).toBe(false); + + expect( + verifyRevenueCatWebhook( + `${payload} `, + { + signature: `t=${nowSeconds},v1=${createHmac("sha256", secret).update(`${nowSeconds}.${payload}`).digest("hex")}`, + authorization: null, + }, + secret, + nowSeconds, + ), + ).toBe(false); + }); + + it("verifies an Authorization header (with or without Bearer prefix)", () => { + expect( + verifyRevenueCatWebhook( + payload, + { signature: null, authorization: "Bearer my-webhook-token" }, + "Bearer my-webhook-token", + nowSeconds, + ), + ).toBe(true); + + expect( + verifyRevenueCatWebhook( + payload, + { signature: null, authorization: "Bearer my-webhook-token" }, + "my-webhook-token", + nowSeconds, + ), + ).toBe(true); + + expect( + verifyRevenueCatWebhook( + payload, + { signature: null, authorization: "Bearer wrong-token" }, + "Bearer my-webhook-token", + nowSeconds, + ), + ).toBe(false); + }); + + it("verifies JSON-encoded stored secrets created via API v2", () => { + const stored = JSON.stringify({ + authHeader: "Bearer rcwh_secret_abc", + signingSecret: "hmac_secret_xyz", + }); + + expect( + verifyRevenueCatWebhook( + payload, + { signature: null, authorization: "Bearer rcwh_secret_abc" }, + stored, + nowSeconds, + ), + ).toBe(true); + + const sig = createHmac("sha256", "hmac_secret_xyz") + .update(`${nowSeconds}.${payload}`) + .digest("hex"); + expect( + verifyRevenueCatWebhook( + payload, + { signature: `t=${nowSeconds},v1=${sig}`, authorization: null }, + stored, + nowSeconds, + ), + ).toBe(true); + }); +}); + +describe("formatProductId", () => { + it("turns store product identifiers into readable plan names", () => { + expect(formatProductId("com.acme.pro_monthly")).toBe("Pro Monthly"); + expect(formatProductId("premium_yearly:p1y")).toBe("Premium Yearly"); + }); +}); diff --git a/src/server/revenuecat/webhooks.ts b/src/server/revenuecat/webhooks.ts new file mode 100644 index 0000000..8160367 --- /dev/null +++ b/src/server/revenuecat/webhooks.ts @@ -0,0 +1,901 @@ +import "server-only"; +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { and, desc, eq } from "drizzle-orm"; +import { z } from "zod"; +import { db } from "@/db"; +import { + mrrMovements, + payments, + revenuecatMetrics, + stripeAccounts, + subscriptions, + type RevenueCatProductEntry, +} from "@/db/schema"; +import { env } from "@/env"; +import type { ActionResult } from "@/lib/action-result"; +import type { ChurnReason, MrrMovementKind } from "@/lib/display/types"; +import { toMinorUnits } from "@/lib/money"; +import { revenueCatPermissionLabel } from "@/lib/revenuecat-permissions"; +import { siteConfig } from "@/lib/site"; +import { decryptSecret, encryptSecret } from "@/server/crypto"; +import { ACCOUNT_NOT_FOUND } from "@/server/stripe/errors"; +import { isPublicHttpsUrl } from "@/server/stripe/webhooks"; +import { billingIntervalOf, normalizeMonthlyMrr } from "./charts"; +import { RevenueCatAccessError } from "./errors"; +import { + createRevenueCatGateway, + type RevenueCatAccessOptions, + type RevenueCatGateway, +} from "./gateway"; + +/** Event types requested when creating a RevenueCat webhook integration via API v2. */ +export const REVENUECAT_WEBHOOK_EVENT_TYPES = [ + "initial_purchase", + "renewal", + "cancellation", + "uncancellation", + "non_renewing_purchase", + "subscription_paused", + "expiration", + "billing_issue", + "product_change", + "subscription_extended", + "refund_reversed", +] as const; + +const MAX_RECENT_EVENT_IDS = 200; +const SIGNATURE_TOLERANCE_SECONDS = 300; + +function webhookEndpointUrl(accountId: string): string { + return `${env().APP_URL}/api/webhooks/revenuecat/${accountId}`; +} + +const INVALID_WEBHOOK_SECRET = + "Paste the Authorization header value or HMAC signing secret configured in RevenueCat (at least 8 characters)."; + +export const revenueCatWebhookSecretSchema = z + .string() + .trim() + .min(8, INVALID_WEBHOOK_SECRET) + .max(500, INVALID_WEBHOOK_SECRET); + +export interface StoredRevenueCatWebhookSecret { + authHeader?: string | null; + signingSecret?: string | null; +} + +function parseStoredSecret(raw: string): StoredRevenueCatWebhookSecret { + if (raw.startsWith("{")) { + try { + const parsed = JSON.parse(raw) as StoredRevenueCatWebhookSecret; + if (parsed && typeof parsed === "object") { + return { + authHeader: typeof parsed.authHeader === "string" ? parsed.authHeader : null, + signingSecret: typeof parsed.signingSecret === "string" ? parsed.signingSecret : null, + }; + } + } catch { + // Fall through to raw secret. + } + } + return { authHeader: raw, signingSecret: raw }; +} + +function safeEqual(a: string, b: string): boolean { + const bufA = Buffer.from(a); + const bufB = Buffer.from(b); + if (bufA.length !== bufB.length) return false; + return timingSafeEqual(bufA, bufB); +} + +/** + * Verifies an incoming RevenueCat webhook using either: + * 1. `X-RevenueCat-Webhook-Signature: t=,v1=` (HMAC signing) + * 2. `Authorization` header (shared token, matching raw or `Bearer `) + */ +export function verifyRevenueCatWebhook( + payload: string, + headers: { signature: string | null; authorization: string | null }, + storedSecretRaw: string, + nowSeconds: number = Math.floor(Date.now() / 1000), +): boolean { + const stored = parseStoredSecret(storedSecretRaw); + + if (headers.signature && stored.signingSecret) { + if (verifyHmacSignature(payload, headers.signature, stored.signingSecret, nowSeconds)) { + return true; + } + } + + if (headers.authorization && stored.authHeader) { + const incoming = headers.authorization.trim(); + const expected = stored.authHeader.trim(); + if (safeEqual(incoming, expected)) return true; + if ( + !expected.toLowerCase().startsWith("bearer ") && + safeEqual(incoming, `Bearer ${expected}`) + ) { + return true; + } + if (expected.toLowerCase().startsWith("bearer ") && safeEqual(incoming, expected.slice(7))) { + return true; + } + } + + return false; +} + +function verifyHmacSignature( + payload: string, + header: string, + secret: string, + nowSeconds: number, +): boolean { + const parts = new Map(); + for (const segment of header.split(",")) { + const index = segment.indexOf("="); + if (index === -1) continue; + parts.set(segment.slice(0, index).trim(), segment.slice(index + 1).trim()); + } + const timestamp = parts.get("t"); + const expectedSig = parts.get("v1"); + if (!timestamp || !expectedSig) return false; + const ts = Number(timestamp); + if (!Number.isFinite(ts) || Math.abs(nowSeconds - ts) > SIGNATURE_TOLERANCE_SECONDS) { + return false; + } + + const computed = createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex"); + return safeEqual(computed, expectedSig); +} + +export type RevenueCatWebhookRegistration = + { ok: true } | { ok: false; reason: "private_url" | "refused" | "unavailable" }; + +/** + * Registers a webhook integration on RevenueCat via API v2. Needs a public HTTPS `APP_URL` and + * the optional `project_configuration:integrations:read_write` permission. + */ +export async function registerRevenueCatWebhook( + accountId: string, + projectId: string, + gateway: RevenueCatGateway, + livemode: boolean = true, +): Promise { + const url = webhookEndpointUrl(accountId); + if (!isPublicHttpsUrl(url)) return { ok: false, reason: "private_url" }; + + const authHeader = `Bearer rcwh_${randomBytes(24).toString("base64url")}`; + let integration: { id: string; signingSecret: string | null }; + try { + integration = await gateway.createWebhookIntegration(projectId, { + name: `${siteConfig.name} instant updates`, + url, + authorizationHeader: authHeader, + environment: livemode ? "production" : "sandbox", + eventTypes: REVENUECAT_WEBHOOK_EVENT_TYPES, + }); + } catch (error) { + if (!(error instanceof RevenueCatAccessError)) throw error; + return { ok: false, reason: error.isTransient ? "unavailable" : "refused" }; + } + + const secretPayload: StoredRevenueCatWebhookSecret = { + authHeader, + signingSecret: integration.signingSecret, + }; + await db() + .update(stripeAccounts) + .set({ + webhookEndpointId: integration.id, + encryptedWebhookSecret: encryptSecret(JSON.stringify(secretPayload)), + }) + .where(eq(stripeAccounts.id, accountId)); + return { ok: true }; +} + +export async function enableRevenueCatInstantUpdates( + workspaceId: string, + accountId: string, + options: RevenueCatAccessOptions = {}, +): Promise { + const [account] = await db() + .select({ + encryptedSecretKey: stripeAccounts.encryptedSecretKey, + stripeAccountId: stripeAccounts.stripeAccountId, + webhookEndpointId: stripeAccounts.webhookEndpointId, + livemode: stripeAccounts.livemode, + }) + .from(stripeAccounts) + .where( + and( + eq(stripeAccounts.workspaceId, workspaceId), + eq(stripeAccounts.id, accountId), + eq(stripeAccounts.provider, "revenuecat"), + ), + ); + if (!account || !account.stripeAccountId) return ACCOUNT_NOT_FOUND; + if (account.webhookEndpointId) return { ok: true }; + + const gateway = (options.createGateway ?? createRevenueCatGateway)( + decryptSecret(account.encryptedSecretKey), + ); + const registration = await registerRevenueCatWebhook( + accountId, + account.stripeAccountId, + gateway, + account.livemode, + ); + if (registration.ok) return { ok: true }; + const errors = { + private_url: + "RevenueCat can only send updates to a public HTTPS address. Set APP_URL to the public URL of this app.", + refused: `RevenueCat refused to create the webhook. Give the key the “${revenueCatPermissionLabel("project_configuration:integrations:read_write")}” permission, or add the webhook manually.`, + unavailable: "RevenueCat could not be reached. Try again in a moment.", + }; + return { ok: false, error: errors[registration.reason] }; +} + +export async function setRevenueCatWebhookSecret( + workspaceId: string, + accountId: string, + secret: string, +): Promise { + const [{ affectedRows }] = await db() + .update(stripeAccounts) + .set({ encryptedWebhookSecret: encryptSecret(secret.trim()) }) + .where( + and( + eq(stripeAccounts.workspaceId, workspaceId), + eq(stripeAccounts.id, accountId), + eq(stripeAccounts.provider, "revenuecat"), + ), + ); + return affectedRows ? { ok: true } : ACCOUNT_NOT_FOUND; +} + +export function revenueCatWebhookSetupInstructions(accountId: string): { + url: string; + events: string[]; +} { + return { + url: webhookEndpointUrl(accountId), + events: REVENUECAT_WEBHOOK_EVENT_TYPES.map((type) => type.toUpperCase()), + }; +} + +const subscriberAttributeSchema = z.object({ + value: z.string().nullable().optional(), +}); + +const webhookEventSchema = z.object({ + id: z.string().min(1).max(255), + type: z.string().min(1), + environment: z.string().nullable().optional(), + event_timestamp_ms: z.number().nullable().optional(), + purchased_at_ms: z.number().nullable().optional(), + expiration_at_ms: z.number().nullable().optional(), + app_user_id: z.string().nullable().optional(), + original_app_user_id: z.string().nullable().optional(), + product_id: z.string().nullable().optional(), + new_product_id: z.string().nullable().optional(), + period_type: z.string().nullable().optional(), + transaction_id: z.string().nullable().optional(), + original_transaction_id: z.string().nullable().optional(), + currency: z.string().nullable().optional(), + price: z.number().nullable().optional(), + price_in_purchased_currency: z.number().nullable().optional(), + country_code: z.string().nullable().optional(), + store: z.string().nullable().optional(), + cancel_reason: z.string().nullable().optional(), + expiration_reason: z.string().nullable().optional(), + is_trial_conversion: z.boolean().nullable().optional(), + subscriber_attributes: z.record(z.string(), subscriberAttributeSchema).nullable().optional(), +}); + +const webhookPayloadSchema = z.object({ + api_version: z.string().optional(), + event: webhookEventSchema, +}); + +export type RevenueCatWebhookEvent = z.infer; + +export type RevenueCatWebhookOutcome = + | { status: "unknown_account" } + | { status: "invalid_signature" } + | { status: "invalid_payload" } + | { status: "accepted"; notify: boolean; sync: boolean }; + +/** + * Verifies and ingests a RevenueCat webhook event. Live purchases, renewals and churns are written + * immediately so wall screens and phones celebrate within seconds, while the periodic sync keeps + * aggregate overview & chart metrics aligned with RevenueCat. + */ +export async function receiveRevenueCatWebhook( + accountId: string, + payload: string, + headers: { signature: string | null; authorization: string | null }, + options: { now?: Date } = {}, +): Promise { + const now = options.now ?? new Date(); + const [account] = await db() + .select({ + id: stripeAccounts.id, + livemode: stripeAccounts.livemode, + encryptedWebhookSecret: stripeAccounts.encryptedWebhookSecret, + }) + .from(stripeAccounts) + .where(and(eq(stripeAccounts.id, accountId), eq(stripeAccounts.provider, "revenuecat"))); + if (!account) return { status: "unknown_account" }; + if (!account.encryptedWebhookSecret) return { status: "invalid_signature" }; + + let storedSecret: string; + try { + storedSecret = decryptSecret(account.encryptedWebhookSecret); + } catch { + return { status: "invalid_signature" }; + } + if (!verifyRevenueCatWebhook(payload, headers, storedSecret, Math.floor(now.getTime() / 1000))) { + return { status: "invalid_signature" }; + } + + let parsed: z.infer; + try { + parsed = webhookPayloadSchema.parse(JSON.parse(payload)); + } catch { + return { status: "invalid_payload" }; + } + const { event } = parsed; + + // Dashboard "Send test event": acknowledge and record webhook health without creating fake sales. + if (event.type === "TEST") { + await db() + .update(stripeAccounts) + .set({ lastWebhookAt: now }) + .where(eq(stripeAccounts.id, accountId)); + return { status: "accepted", notify: false, sync: false }; + } + + // Filter out sandbox events on production accounts (and vice versa). + const expectedEnv = account.livemode ? "PRODUCTION" : "SANDBOX"; + if (event.environment && event.environment.toUpperCase() !== expectedEnv) { + await db() + .update(stripeAccounts) + .set({ lastWebhookAt: now }) + .where(eq(stripeAccounts.id, accountId)); + return { status: "accepted", notify: false, sync: false }; + } + + const [metricsRow] = await db() + .select({ products: revenuecatMetrics.products }) + .from(revenuecatMetrics) + .where(eq(revenuecatMetrics.accountId, accountId)); + const products = metricsRow?.products ?? {}; + + const written = await db().transaction(async (tx) => { + const [locked] = await tx + .select({ recentEventIds: stripeAccounts.recentEventIds }) + .from(stripeAccounts) + .where(eq(stripeAccounts.id, accountId)) + .for("update"); + if (!locked) return false; + + if (locked.recentEventIds.includes(event.id)) { + await tx + .update(stripeAccounts) + .set({ lastWebhookAt: now }) + .where(eq(stripeAccounts.id, accountId)); + return false; + } + + const occurredAt = new Date(event.event_timestamp_ms ?? event.purchased_at_ms ?? now.getTime()); + const recentEventIds = [...locked.recentEventIds, event.id].slice(-MAX_RECENT_EVENT_IDS); + + const didWrite = await applyRevenueCatEvent(tx, accountId, event, products, occurredAt, now); + + await tx + .update(stripeAccounts) + .set({ + recentEventIds, + lastWebhookAt: now, + lastEventAt: occurredAt, + syncRequestedAt: now, + }) + .where(eq(stripeAccounts.id, accountId)); + + return didWrite; + }); + + return { status: "accepted", notify: written, sync: true }; +} + +function resolveProduct( + productId: string | null | undefined, + products: Record, +): { planName: string | null; duration: string | null } { + if (!productId) return { planName: null, duration: null }; + const exact = products[productId]; + if (exact) return { planName: exact.displayName, duration: exact.duration }; + // Google Play product ids may have `:` format. + const baseId = productId.split(":")[0]; + const base = products[baseId]; + if (base) return { planName: base.displayName, duration: base.duration }; + return { planName: formatProductId(productId), duration: null }; +} + +/** Turns a raw store product id like `com.app.pro_monthly:p1m` into a readable fallback label. */ +export function formatProductId(productId: string): string { + const withoutPlan = productId.split(":")[0]; + const tail = withoutPlan.split(".").at(-1) ?? withoutPlan; + return tail + .replace(/[_-]+/g, " ") + .trim() + .replace(/\b\w/g, (char) => char.toUpperCase()); +} + +function eventMoney(event: RevenueCatWebhookEvent): { amountMinor: number; currency: string } { + if ( + event.currency && + typeof event.price_in_purchased_currency === "number" && + Number.isFinite(event.price_in_purchased_currency) + ) { + const currency = event.currency.toLowerCase(); + return { amountMinor: toMinorUnits(event.price_in_purchased_currency, currency), currency }; + } + if (typeof event.price === "number" && Number.isFinite(event.price)) { + return { amountMinor: toMinorUnits(event.price, "usd"), currency: "usd" }; + } + return { amountMinor: 0, currency: (event.currency ?? "USD").toLowerCase() }; +} + +function eventCustomerInfo(event: RevenueCatWebhookEvent) { + const attrs = event.subscriber_attributes ?? {}; + const customerId = event.original_app_user_id ?? event.app_user_id ?? `rc:${event.id}`; + const name = attrs["$displayName"]?.value?.trim() || null; + const email = attrs["$email"]?.value?.trim() || null; + const country = event.country_code?.trim().toUpperCase() || null; + return { customerId, name, email, country }; +} + +function mapCancelReason(reason: string | null | undefined, scheduled: boolean): ChurnReason { + switch (reason?.toUpperCase()) { + case "BILLING_ERROR": + return "unpaid"; + case "SUBSCRIPTION_PAUSED": + return "paused"; + case "CUSTOMER_SUPPORT": + return "canceled"; + default: + return scheduled ? "scheduled" : "canceled"; + } +} + +async function applyRevenueCatEvent( + tx: Parameters["transaction"]>[0]>[0], + accountId: string, + event: RevenueCatWebhookEvent, + products: Record, + occurredAt: Date, + now: Date, +): Promise { + const customer = eventCustomerInfo(event); + const { amountMinor, currency } = eventMoney(event); + const product = resolveProduct(event.product_id, products); + const periodMs = + event.expiration_at_ms && + event.purchased_at_ms && + event.expiration_at_ms > event.purchased_at_ms + ? event.expiration_at_ms - event.purchased_at_ms + : null; + const subId = + event.original_transaction_id ?? + event.transaction_id ?? + `${customer.customerId}:${event.product_id ?? "subscription"}`; + const chargeId = event.transaction_id ?? event.id; + const startedAt = event.purchased_at_ms ? new Date(event.purchased_at_ms) : occurredAt; + const expiresAt = event.expiration_at_ms ? new Date(event.expiration_at_ms) : null; + + const findSub = async () => { + const [row] = await tx + .select() + .from(subscriptions) + .where( + and(eq(subscriptions.accountId, accountId), eq(subscriptions.stripeSubscriptionId, subId)), + ) + .for("update"); + return row ?? null; + }; + + const hasSubHistory = async () => { + const [row] = await tx + .select({ id: mrrMovements.id }) + .from(mrrMovements) + .where( + and(eq(mrrMovements.accountId, accountId), eq(mrrMovements.stripeSubscriptionId, subId)), + ) + .limit(1); + return Boolean(row); + }; + + const insertPaymentIfNew = async (amount: number, description: string | null) => { + if (amount <= 0) return false; + const [existing] = await tx + .select({ id: payments.id }) + .from(payments) + .where(and(eq(payments.accountId, accountId), eq(payments.stripeChargeId, chargeId))) + .limit(1); + if (existing) return false; + await tx.insert(payments).values({ + accountId, + stripeChargeId: chargeId, + stripeCustomerId: customer.customerId, + customerName: customer.name, + customerEmail: customer.email, + customerCountry: customer.country, + description, + amount, + amountRefunded: 0, + currency, + occurredAt, + origin: "live", + }); + return true; + }; + + let wrote = false; + + switch (event.type) { + case "INITIAL_PURCHASE": { + const isTrial = event.period_type?.toUpperCase() === "TRIAL"; + const mrr = isTrial ? 0 : normalizeMonthlyMrr(amountMinor, product.duration, periodMs); + const previous = await findSub(); + const values = { + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous?.customerName ?? null, + customerEmail: customer.email ?? previous?.customerEmail ?? null, + customerCountry: customer.country ?? previous?.customerCountry ?? null, + status: isTrial ? "trialing" : "active", + currency, + mrr, + planName: product.planName ?? previous?.planName ?? null, + billingInterval: billingIntervalOf(product.duration, periodMs), + startedAt: previous?.startedAt ?? startedAt, + trialEndsAt: isTrial ? expiresAt : null, + canceledAt: null, + endedAt: null, + cancelAtPeriodEnd: false, + lastSeenAt: now, + }; + if (previous) { + await tx.update(subscriptions).set(values).where(eq(subscriptions.id, previous.id)); + } else { + await tx.insert(subscriptions).values(values); + } + + if (!isTrial && mrr > 0) { + const previousMrr = previous?.mrr ?? 0; + if (mrr !== previousMrr) { + const kind: MrrMovementKind = + previousMrr === 0 + ? (await hasSubHistory()) + ? "reactivation" + : "new" + : mrr > previousMrr + ? "expansion" + : "contraction"; + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: values.customerName, + customerCountry: values.customerCountry, + planName: values.planName, + kind, + amount: mrr - previousMrr, + currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + } + if (!isTrial && amountMinor > 0) { + wrote = (await insertPaymentIfNew(amountMinor, product.planName)) || wrote; + } + return wrote; + } + + case "RENEWAL": { + if (amountMinor > 0) { + wrote = (await insertPaymentIfNew(amountMinor, product.planName)) || wrote; + } + const mrr = normalizeMonthlyMrr(amountMinor, product.duration, periodMs); + const previous = await findSub(); + const previousMrr = previous?.mrr ?? 0; + const values = { + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous?.customerName ?? null, + customerEmail: customer.email ?? previous?.customerEmail ?? null, + customerCountry: customer.country ?? previous?.customerCountry ?? null, + status: "active", + currency, + mrr, + planName: product.planName ?? previous?.planName ?? null, + billingInterval: + billingIntervalOf(product.duration, periodMs) ?? previous?.billingInterval ?? null, + startedAt: previous?.startedAt ?? startedAt, + trialEndsAt: previous?.trialEndsAt ?? null, + canceledAt: null, + endedAt: null, + cancelAtPeriodEnd: false, + lastSeenAt: now, + }; + if (previous) { + await tx.update(subscriptions).set(values).where(eq(subscriptions.id, previous.id)); + } else { + await tx.insert(subscriptions).values(values); + } + + // Only record an MRR movement on renewal when it's a trial conversion, reactivation, or price change. + const shouldRecordNew = + Boolean(event.is_trial_conversion) || (previous !== null && previousMrr === 0); + if (mrr > 0 && (shouldRecordNew || (previous !== null && mrr !== previousMrr))) { + const delta = shouldRecordNew ? mrr : mrr - previousMrr; + if (delta !== 0) { + const kind: MrrMovementKind = shouldRecordNew + ? event.is_trial_conversion + ? "new" + : (await hasSubHistory()) + ? "reactivation" + : "new" + : delta > 0 + ? "expansion" + : "contraction"; + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: values.customerName, + customerCountry: values.customerCountry, + planName: values.planName, + kind, + amount: delta, + currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + } + return wrote; + } + + case "NON_RENEWING_PURCHASE": { + if (amountMinor > 0) { + return insertPaymentIfNew(amountMinor, product.planName); + } + return false; + } + + case "CANCELLATION": { + const isRefund = event.cancel_reason?.toUpperCase() === "CUSTOMER_SUPPORT"; + if (isRefund && event.transaction_id) { + const [existingPayment] = await tx + .select({ id: payments.id, amount: payments.amount }) + .from(payments) + .where( + and( + eq(payments.accountId, accountId), + eq(payments.stripeChargeId, event.transaction_id), + ), + ) + .limit(1); + if (existingPayment) { + const refunded = + amountMinor < 0 + ? Math.min(existingPayment.amount, -amountMinor) + : existingPayment.amount; + await tx + .update(payments) + .set({ amountRefunded: refunded }) + .where(eq(payments.id, existingPayment.id)); + } + } + + const previous = await findSub(); + const scheduled = + !isRefund && expiresAt !== null && expiresAt.getTime() > occurredAt.getTime(); + const reason = mapCancelReason(event.cancel_reason, scheduled); + const lostMrr = + previous && previous.mrr > 0 + ? previous.mrr + : !previous && Math.abs(amountMinor) > 0 + ? normalizeMonthlyMrr(Math.abs(amountMinor), product.duration, periodMs) + : 0; + + if (previous) { + await tx + .update(subscriptions) + .set({ + status: scheduled ? previous.status : reason === "unpaid" ? "unpaid" : "canceled", + mrr: 0, + cancelAtPeriodEnd: scheduled, + canceledAt: occurredAt, + endedAt: scheduled ? previous.endedAt : occurredAt, + lastSeenAt: now, + }) + .where(eq(subscriptions.id, previous.id)); + } else if (lostMrr > 0) { + await tx.insert(subscriptions).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name, + customerEmail: customer.email, + customerCountry: customer.country, + status: scheduled ? "active" : "canceled", + currency, + mrr: 0, + planName: product.planName, + billingInterval: billingIntervalOf(product.duration, periodMs), + startedAt, + canceledAt: occurredAt, + endedAt: scheduled ? null : occurredAt, + cancelAtPeriodEnd: scheduled, + lastSeenAt: now, + }); + } + + if (lostMrr > 0) { + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous?.customerName ?? null, + customerCountry: customer.country ?? previous?.customerCountry ?? null, + planName: product.planName ?? previous?.planName ?? null, + kind: "churn", + churnReason: reason, + endsAt: reason === "scheduled" ? expiresAt : null, + amount: -lostMrr, + currency: previous?.currency ?? currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + return wrote; + } + + case "UNCANCELLATION": { + const previous = await findSub(); + const restoredMrr = + amountMinor > 0 + ? normalizeMonthlyMrr(amountMinor, product.duration, periodMs) + : await lastChurnedMrr(tx, accountId, subId); + if (previous) { + await tx + .update(subscriptions) + .set({ + status: "active", + mrr: restoredMrr || previous.mrr, + cancelAtPeriodEnd: false, + canceledAt: null, + endedAt: null, + lastSeenAt: now, + }) + .where(eq(subscriptions.id, previous.id)); + } + if (restoredMrr > 0 && (previous?.mrr ?? 0) === 0) { + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous?.customerName ?? null, + customerCountry: customer.country ?? previous?.customerCountry ?? null, + planName: product.planName ?? previous?.planName ?? null, + kind: "reactivation", + amount: restoredMrr, + currency: previous?.currency ?? currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + return wrote; + } + + case "EXPIRATION": { + const previous = await findSub(); + if (!previous) return false; + const reason = mapCancelReason(event.expiration_reason, false); + await tx + .update(subscriptions) + .set({ + status: reason === "paused" ? "paused" : reason === "unpaid" ? "unpaid" : "canceled", + mrr: 0, + endedAt: previous.endedAt ?? occurredAt, + lastSeenAt: now, + }) + .where(eq(subscriptions.id, previous.id)); + if (previous.mrr > 0) { + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous.customerName, + customerCountry: customer.country ?? previous.customerCountry, + planName: product.planName ?? previous.planName, + kind: "churn", + churnReason: reason, + amount: -previous.mrr, + currency: previous.currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + return wrote; + } + + case "SUBSCRIPTION_PAUSED": { + const previous = await findSub(); + if (!previous) return false; + await tx + .update(subscriptions) + .set({ status: "paused", mrr: 0, lastSeenAt: now }) + .where(eq(subscriptions.id, previous.id)); + if (previous.mrr > 0) { + await tx.insert(mrrMovements).values({ + accountId, + stripeSubscriptionId: subId, + stripeCustomerId: customer.customerId, + customerName: customer.name ?? previous.customerName, + customerCountry: customer.country ?? previous.customerCountry, + planName: product.planName ?? previous.planName, + kind: "churn", + churnReason: "paused", + amount: -previous.mrr, + currency: previous.currency, + occurredAt, + origin: "live", + stripeEventId: event.id, + }); + wrote = true; + } + return wrote; + } + + default: + return false; + } +} + +async function lastChurnedMrr( + tx: Parameters["transaction"]>[0]>[0], + accountId: string, + subId: string, +): Promise { + const [row] = await tx + .select({ amount: mrrMovements.amount }) + .from(mrrMovements) + .where( + and( + eq(mrrMovements.accountId, accountId), + eq(mrrMovements.stripeSubscriptionId, subId), + eq(mrrMovements.kind, "churn"), + ), + ) + .orderBy(desc(mrrMovements.occurredAt)) + .limit(1); + return row ? Math.abs(row.amount) : 0; +} diff --git a/src/server/screens.ts b/src/server/screens.ts index 77d4cee..2b2b01f 100644 --- a/src/server/screens.ts +++ b/src/server/screens.ts @@ -4,6 +4,7 @@ import { and, asc, eq, inArray, sql, type SQL } from "drizzle-orm"; import { z } from "zod"; import { db, type Transaction } from "@/db"; import { screenAccounts, screens, stripeAccounts } from "@/db/schema"; +import type { AccountProvider } from "@/lib/account-providers"; import type { ActionResult } from "@/lib/action-result"; import { NAME_MAX_LENGTH, nameSchema } from "@/lib/names"; import { @@ -22,6 +23,7 @@ import { hashScreenPassword } from "@/server/screen-access"; export interface LinkedAccount { id: string; + provider: AccountProvider; name: string; livemode: boolean; } @@ -94,7 +96,7 @@ async function findScreens(where: SQL | undefined): Promise { orderBy: [asc(screens.createdAt)], with: { screenAccounts: { - with: { account: { columns: { id: true, name: true, livemode: true } } }, + with: { account: { columns: { id: true, provider: true, name: true, livemode: true } } }, }, }, }); @@ -126,6 +128,7 @@ export async function listAccountOptions(workspaceId: string): Promise account.id); - const [mrrRows, paymentCounts] = await Promise.all([ - db() - .select({ - accountId: subscriptions.accountId, - currency: subscriptions.currency, - mrr: sum(subscriptions.mrr).mapWith(Number), - }) - .from(subscriptions) - .where(inArray(subscriptions.accountId, ids)) - .groupBy(subscriptions.accountId, subscriptions.currency), + const rcIds = accounts + .filter((account) => account.provider === "revenuecat") + .map((account) => account.id); + const stripeIds = accounts + .filter((account) => account.provider === "stripe") + .map((account) => account.id); + const [mrrRows, rcRows, paymentCounts] = await Promise.all([ + stripeIds.length + ? db() + .select({ + accountId: subscriptions.accountId, + currency: subscriptions.currency, + mrr: sum(subscriptions.mrr).mapWith(Number), + }) + .from(subscriptions) + .where(inArray(subscriptions.accountId, stripeIds)) + .groupBy(subscriptions.accountId, subscriptions.currency) + : Promise.resolve([]), + rcIds.length + ? db() + .select({ + accountId: revenuecatMetrics.accountId, + currency: revenuecatMetrics.currency, + mrr: revenuecatMetrics.mrr, + }) + .from(revenuecatMetrics) + .where(inArray(revenuecatMetrics.accountId, rcIds)) + : Promise.resolve([]), recentPaymentCounts(ids, now), ]); + const allMrrRows = [...mrrRows, ...rcRows]; return Promise.all( accounts.map(async (account) => ({ id: account.id, + provider: account.provider, name: account.name, livemode: account.livemode, keyHint: account.secretKeyHint, @@ -251,7 +288,7 @@ export async function listStripeAccountSummaries( ? null : await accountMrr( account.defaultCurrency, - mrrRows.filter((row) => row.accountId === account.id), + allMrrRows.filter((row) => row.accountId === account.id), ), })), ); @@ -295,6 +332,8 @@ export async function disconnectStripeAccount( ): Promise { const [account] = await db() .select({ + provider: stripeAccounts.provider, + stripeAccountId: stripeAccounts.stripeAccountId, encryptedSecretKey: stripeAccounts.encryptedSecretKey, webhookEndpointId: stripeAccounts.webhookEndpointId, }) @@ -304,14 +343,22 @@ export async function disconnectStripeAccount( if (account.webhookEndpointId) { try { - const gateway = (options.createGateway ?? createStripeGateway)( - decryptSecret(account.encryptedSecretKey), - ); - await gateway.deleteWebhookEndpoint(account.webhookEndpointId); + const secretKey = decryptSecret(account.encryptedSecretKey); + if (account.provider === "revenuecat") { + if (account.stripeAccountId) { + await createRevenueCatGateway(secretKey).deleteWebhookIntegration( + account.stripeAccountId, + account.webhookEndpointId, + ); + } + } else { + const gateway = (options.createGateway ?? createStripeGateway)(secretKey); + await gateway.deleteWebhookEndpoint(account.webhookEndpointId); + } } catch (error) { - // A revoked key cannot remove the endpoint; Stripe disables it once deliveries keep failing. + // A revoked key cannot remove the endpoint; providers disable it once deliveries keep failing. console.warn( - `[stripe] Could not delete webhook endpoint of account ${accountId}:`, + `[${account.provider}] Could not delete webhook endpoint of account ${accountId}:`, error instanceof Error ? error.message : error, ); } @@ -334,11 +381,18 @@ export async function reimportStripeAccount( options: StripeAccessOptions = {}, ): Promise { const [account] = await db() - .select({ encryptedSecretKey: stripeAccounts.encryptedSecretKey }) + .select({ + provider: stripeAccounts.provider, + stripeAccountId: stripeAccounts.stripeAccountId, + encryptedSecretKey: stripeAccounts.encryptedSecretKey, + }) .from(stripeAccounts) .where(and(eq(stripeAccounts.workspaceId, workspaceId), eq(stripeAccounts.id, accountId))); if (!account) return ACCOUNT_NOT_FOUND; - const access = await checkStoredKey(account.encryptedSecretKey, options); + const access = + account.provider === "revenuecat" + ? await checkStoredRevenueCatKey(account.encryptedSecretKey, account.stripeAccountId) + : await checkStoredKey(account.encryptedSecretKey, options); if (!access.ok) return access; const now = new Date(); @@ -348,9 +402,9 @@ export async function reimportStripeAccount( .set({ status: "importing", lastError: null, - backfill: newBackfill(now), + backfill: account.provider === "revenuecat" ? newRevenueCatBackfill(now) : newBackfill(now), reconcile: null, - eventsCursor: toUnixTime(now), + eventsCursor: account.provider === "revenuecat" ? null : toUnixTime(now), recentEventIds: [], lastEventAt: null, lastSyncedAt: null, @@ -365,6 +419,12 @@ export async function reimportStripeAccount( await tx.delete(subscriptions).where(eq(subscriptions.accountId, accountId)); await tx.delete(payments).where(eq(payments.accountId, accountId)); await tx.delete(customers).where(eq(customers.accountId, accountId)); + if (account.provider === "revenuecat") { + await tx.delete(revenuecatMetrics).where(eq(revenuecatMetrics.accountId, accountId)); + await tx + .delete(revenuecatDailyMetrics) + .where(eq(revenuecatDailyMetrics.accountId, accountId)); + } return true; }); if (!reset) return ACCOUNT_NOT_FOUND; @@ -372,6 +432,30 @@ export async function reimportStripeAccount( return { ok: true }; } +async function checkStoredRevenueCatKey( + encryptedSecretKey: string, + projectId: string | null, +): Promise { + if (!projectId) { + return { ok: false, error: "This RevenueCat account is missing its project id." }; + } + let key: string; + try { + key = decryptSecret(encryptedSecretKey); + } catch { + return { ok: false, error: REVENUECAT_UNREADABLE_KEY_ERROR }; + } + try { + await createRevenueCatGateway(key).getOverviewMetrics(projectId); + return { ok: true }; + } catch (error) { + if (error instanceof RevenueCatAccessError) { + return { ok: false, error: describeRevenueCatAccessError(error) }; + } + throw error; + } +} + /** Whether the stored key can still read everything an import needs. */ async function checkStoredKey( encryptedSecretKey: string, diff --git a/src/server/sync/index.ts b/src/server/sync/index.ts index 6d18c83..e4c3557 100644 --- a/src/server/sync/index.ts +++ b/src/server/sync/index.ts @@ -33,6 +33,7 @@ export async function syncDueAccounts( const accounts = await db() .select({ id: stripeAccounts.id, + provider: stripeAccounts.provider, status: stripeAccounts.status, lastSyncedAt: stripeAccounts.lastSyncedAt, syncRequestedAt: stripeAccounts.syncRequestedAt, diff --git a/src/server/sync/policy.ts b/src/server/sync/policy.ts index 7899f79..dd0d96d 100644 --- a/src/server/sync/policy.ts +++ b/src/server/sync/policy.ts @@ -1,9 +1,12 @@ import "server-only"; +import type { AccountProvider } from "@/lib/account-providers"; import { DAY_SECONDS, MINUTE_MS, MINUTE_SECONDS } from "@/lib/durations"; /** With a healthy webhook, polling is only a safety net. Also the slowest polling pace. */ export const SAFETY_NET_INTERVAL_SECONDS = 30 * MINUTE_SECONDS; const FASTEST_POLL_INTERVAL_SECONDS = MINUTE_SECONDS; +/** RevenueCat Charts & Metrics allows 25 req/min; checking every 10 min stays well under that. */ +const REVENUECAT_POLL_INTERVAL_SECONDS = 10 * MINUTE_SECONDS; const RECONCILE_INTERVAL_SECONDS = DAY_SECONDS; /** Webhooks may arrive shortly after a sync has already seen their event. */ const WEBHOOK_DELIVERY_GRACE_MS = 5 * MINUTE_MS; @@ -25,6 +28,7 @@ export function pollIntervalSeconds(paymentsLast30Days: number): number { } export interface UpdatesState { + provider?: AccountProvider; hasWebhookSecret: boolean; lastWebhookAt: Date | null; /** Creation time of the newest event the sync applied. */ @@ -64,8 +68,11 @@ type CheckedAccount = UpdatesState & Pick; * again now and then, like an account whose webhook announces everything. */ function checkIntervalSeconds(account: CheckedAccount): number { - return account.status === "error" || isWebhookHealthy(account) - ? SAFETY_NET_INTERVAL_SECONDS + if (account.status === "error" || isWebhookHealthy(account)) { + return SAFETY_NET_INTERVAL_SECONDS; + } + return account.provider === "revenuecat" + ? REVENUECAT_POLL_INTERVAL_SECONDS : pollIntervalSeconds(account.paymentsLast30Days); } diff --git a/src/server/sync/run.ts b/src/server/sync/run.ts index 63c582d..0875f73 100644 --- a/src/server/sync/run.ts +++ b/src/server/sync/run.ts @@ -1,6 +1,8 @@ import "server-only"; import { decryptSecret } from "@/server/crypto"; import { notifyPhones, type PushOptions } from "@/server/push/notify"; +import type { RevenueCatGatewayFactory } from "@/server/revenuecat/gateway"; +import { syncRevenueCatAccount } from "@/server/revenuecat/sync"; import { describeAccessError, redactSecrets, @@ -27,6 +29,8 @@ import { workingStatus } from "./state"; export interface SyncOptions { /** Creates the Stripe gateway from the account's key; tests pass a fake. */ createGateway?: GatewayFactory; + /** Creates the RevenueCat gateway from the account's key; tests pass a fake. */ + createRevenueCatGateway?: RevenueCatGatewayFactory; /** Current time, for tests. */ now?: () => Date; /** How long a scan may take new pages before saving its cursor. */ @@ -67,6 +71,13 @@ export async function syncAccount( const lease = await acquireSyncLease(accountId, now); if (!lease) return null; + if (lease.account.provider === "revenuecat") { + return syncRevenueCatAccount(lease, { + createGateway: options.createRevenueCatGateway, + now: options.now, + }); + } + const startedAt = performance.now(); const { account } = lease; let mode: SyncMode = account.backfill ? "import" : "incremental"; diff --git a/src/server/sync/state.ts b/src/server/sync/state.ts index 2d26fc2..11f603a 100644 --- a/src/server/sync/state.ts +++ b/src/server/sync/state.ts @@ -32,6 +32,7 @@ export async function recentPaymentCounts( type SyncColumns = Pick< StripeAccountRow, + | "provider" | "status" | "lastSyncedAt" | "syncRequestedAt" @@ -43,6 +44,7 @@ type SyncColumns = Pick< export function toSyncState(account: SyncColumns, paymentsLast30Days: number): SyncState { return { + provider: account.provider, status: account.status, lastSyncedAt: account.lastSyncedAt, syncRequestedAt: account.syncRequestedAt, From 46a712ba0bdc928c53a40a9e0abd1b61d6554ce8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=A9o=20Goulois?= Date: Wed, 25 Nov 2026 09:34:15 +0100 Subject: [PATCH 2/2] test: align db test expectations with account provider field --- src/server/revenuecat/sync.db.test.ts | 4 +++- src/server/screens.db.test.ts | 2 +- src/server/stripe/accounts.db.test.ts | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/server/revenuecat/sync.db.test.ts b/src/server/revenuecat/sync.db.test.ts index 97080d3..e971633 100644 --- a/src/server/revenuecat/sync.db.test.ts +++ b/src/server/revenuecat/sync.db.test.ts @@ -1,5 +1,5 @@ import { eq } from "drizzle-orm"; -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "@/db"; import { stripeAccounts } from "@/db/schema"; import { encryptSecret } from "@/server/crypto"; @@ -13,6 +13,8 @@ import { listStripeAccountSummaries } from "@/server/stripe/accounts"; import { syncAccount } from "@/server/sync/run"; import { createUserWithWorkspace, resetDatabase } from "@/test/db"; +vi.mock("next/server", () => ({ after: vi.fn() })); + const NOW = new Date("2026-11-25T12:00:00.000Z"); function fakeRevenueCatGateway(): RevenueCatGateway { diff --git a/src/server/screens.db.test.ts b/src/server/screens.db.test.ts index 5b5f43f..64bfb34 100644 --- a/src/server/screens.db.test.ts +++ b/src/server/screens.db.test.ts @@ -130,7 +130,7 @@ describe("screens", () => { expect(result.ok).toBe(false); expect((await getScreen(owner.workspaceId, screenId))?.accounts).toEqual([ - { id: ownAccount, name: "Acme", livemode: true }, + { id: ownAccount, provider: "stripe", name: "Acme", livemode: true }, ]); }); diff --git a/src/server/stripe/accounts.db.test.ts b/src/server/stripe/accounts.db.test.ts index 59fefd6..f975a6b 100644 --- a/src/server/stripe/accounts.db.test.ts +++ b/src/server/stripe/accounts.db.test.ts @@ -203,6 +203,7 @@ describe("Stripe accounts", () => { expect(summaries).toEqual([ { id: importing.id, + provider: "stripe", name: "New", livemode: false, keyHint: "rk_test_…4f2a",