1import { assertCliScope } from "../cli/scope";2import { SUBSCRIPTION_SCAN_BYTES } from "./accessHistory";3import { REVENUE_COUNTERS } from "./revenueCounters";4import { query, type QueryCtx } from "../_generated/server";5import { ConvexError, v, type Infer } from "convex/values";6import type { Doc, Id } from "../_generated/dataModel";7 8import {9 canReadRawStoreEvidence,10 resolveOperatorProject,11 resolveProjectByApiKeyFromDb,12 resolveProjectByIdForCurrentUserFromDb,13} from "../projects/helpers";14import {15 isValidSubscriptionUserId,16 MAX_SUBSCRIPTION_USER_ID_LENGTH,17 SUBSCRIPTION_ENVIRONMENT_SCOPES,18 type SubscriptionEnvironmentScope,19} from "./limits";20import {21 loadStatsPeriods,22 statsAreCurrent,23 statsContributionFor,24} from "./stats";25import { subscriptionEnvironment } from "./analyticsFacts";26import { ROLLUP_DEFINITIONS_VERSION } from "./revenueMetrics";27import { entitlementActive, isMisrecordedApplePass } from "./stateMachine";28import { selectMostRecentlyUpdatedSubscription } from "./selectLatest";29import {30 DEFAULT_REPORTING_CURRENCY,31 normalizeReportingCurrencyOrDefault,32} from "../utils/currency";33import { storeOf } from "../commerce/internal";34import { purchaseStoreValidator } from "../schema";35import {36 purchaseIssueCauseValidator,37 receiptEnvironmentValidator,38 subscriptionStateValidator,39} from "../utils/validation";40 41const subscriptionFields = {42 id: v.id("subscriptions"),43 productId: v.string(),44 platform: v.union(v.literal("IOS"), v.literal("Android")),45 state: subscriptionStateValidator,46 expiresAt: v.optional(v.number()),47 renewsAt: v.optional(v.number()),48 willRenew: v.optional(v.boolean()),49 cancellationReason: v.optional(v.string()),50 currency: v.optional(v.string()),51 priceAmountMicros: v.optional(v.number()),52 startedAt: v.number(),53 updatedAt: v.number(),54 // Legacy server responses preserve this required MAUI field; v2 omits it.55 purchaseToken: v.string(),56 originalTransactionId: v.optional(v.string()),57 userId: v.optional(v.string()),58};59const subscriptionShape = v.object(subscriptionFields);60const subscriptionV2Shape = v.object({61 id: v.id("subscriptions"),62 productId: v.string(),63 platform: v.union(v.literal("IOS"), v.literal("Android")),64 store: v.optional(purchaseStoreValidator),65 state: subscriptionStateValidator,66 expiresAt: v.optional(v.number()),67 renewsAt: v.optional(v.number()),68 willRenew: v.optional(v.boolean()),69 cancellationReason: v.optional(v.string()),70 currency: v.optional(v.string()),71 priceAmountMicros: v.optional(v.number()),72 startedAt: v.number(),73 updatedAt: v.number(),74 userId: v.optional(v.string()),75});76const subscriptionEvaluationRowShape = v.object({77 ...subscriptionFields,78 createdAt: v.number(),79});80type SubscriptionRow = Infer<typeof subscriptionShape>;81type SubscriptionV2Row = Infer<typeof subscriptionV2Shape>;82type SubscriptionEvaluationRow = Infer<typeof subscriptionEvaluationRowShape>;83export const MAX_USER_SUBSCRIPTION_ROWS = 200;84 85const environmentScopeValidator = v.union(86 ...SUBSCRIPTION_ENVIRONMENT_SCOPES.map((scope) => v.literal(scope)),87);88 89function subscriptionInEnvironment(90 sub: Doc<"subscriptions">,91 scope: SubscriptionEnvironmentScope | undefined,92): boolean {93 if (scope === undefined) return true;94 const environment = sub.environment ?? sub.lastEventSource?.environment;95 if (environment === undefined) return false;96 return (97 scope === "all" ||98 (scope === "production"99 ? environment === "Production"100 : environment !== "Production")101 );102}103 104function isActive(sub: Doc<"subscriptions">, now: number): boolean {105 return entitlementActive(sub, now);106}107 108function isEntitledState(sub: Doc<"subscriptions">): boolean {109 return sub.state === "Active" || sub.state === "InGracePeriod";110}111 112export function assertUserSubscriptionRowLimit(113 rows: Array<Doc<"subscriptions">>,114): void {115 if (rows.length <= MAX_USER_SUBSCRIPTION_ROWS) return;116 throw new ConvexError({117 code: "ENTITLEMENT_SNAPSHOT_TOO_LARGE",118 message:119 "This user has more than 200 subscription rows. Contact IAPKit support before retrying.",120 });121}122 123async function userSubscriptionRows(124 ctx: QueryCtx,125 projectId: Id<"projects">,126 userId: string,127): Promise<Array<Doc<"subscriptions">>> {128 const rows = await ctx.db129 .query("subscriptions")130 .withIndex("by_project_and_user_and_updated", (q) =>131 q.eq("projectId", projectId).eq("userId", userId),132 )133 .order("desc")134 .take(MAX_USER_SUBSCRIPTION_ROWS + 1);135 assertUserSubscriptionRowLimit(rows);136 return rows;137}138 139export function shapeSubscriptionEvaluationSnapshot(140 rows: Array<Doc<"subscriptions">>,141): {142 candidates: SubscriptionEvaluationRow[];143 fallback: SubscriptionEvaluationRow | null;144} {145 const fallback = selectMostRecentlyUpdatedSubscription(rows);146 return {147 // The snapshot omits lastEventId, so the legacy-pass guard runs here.148 candidates: rows149 .filter((row) => isEntitledState(row) && !isMisrecordedApplePass(row))150 .map(shapeSubscriptionEvaluationRow),151 fallback: fallback ? shapeSubscriptionEvaluationRow(fallback) : null,152 };153}154 155function shapeSubscriptionEvaluationRow(156 sub: Doc<"subscriptions">,157): SubscriptionEvaluationRow {158 return {159 ...shapeSubscriptionRow(sub),160 createdAt: sub._creationTime,161 };162}163 164export function shapeSubscriptionRow(165 sub: Doc<"subscriptions">,166): SubscriptionRow {167 const row: SubscriptionRow = {168 id: sub._id,169 productId: sub.productId,170 platform: sub.platform,171 state: sub.state,172 expiresAt: sub.expiresAt,173 renewsAt: sub.renewsAt,174 willRenew: sub.willRenew,175 cancellationReason: sub.cancellationReason,176 currency: sub.currency,177 priceAmountMicros: sub.priceAmountMicros,178 startedAt: sub.startedAt,179 updatedAt: sub.updatedAt,180 purchaseToken: sub.purchaseToken,181 userId: sub.userId,182 };183 184 if (sub.platform === "IOS") {185 return {186 ...row,187 originalTransactionId: sub.purchaseToken,188 };189 }190 191 return row;192}193 194export function shapeSubscriptionV2Row(195 sub: Doc<"subscriptions">,196): SubscriptionV2Row {197 return {198 id: sub._id,199 productId: sub.productId,200 platform: sub.platform,201 ...(sub.store ? { store: sub.store } : {}),202 state: sub.state,203 expiresAt: sub.expiresAt,204 renewsAt: sub.renewsAt,205 willRenew: sub.willRenew,206 cancellationReason: sub.cancellationReason,207 currency: sub.currency,208 priceAmountMicros: sub.priceAmountMicros,209 startedAt: sub.startedAt,210 updatedAt: sub.updatedAt,211 userId: sub.userId,212 };213}214 215async function projectByApiKey(216 ctx: QueryCtx,217 apiKey: string | undefined,218 requiredAccess: "client" | "admin" = "client",219): Promise<Doc<"projects"> | null> {220 if (!apiKey) return null;221 const resolved = await resolveProjectByApiKeyFromDb(222 ctx,223 apiKey,224 requiredAccess,225 );226 return resolved?.project ?? null;227}228 229async function requireAdminProjectByApiKey(230 ctx: QueryCtx,231 apiKey: string,232): Promise<Doc<"projects">> {233 const project = await projectByApiKey(ctx, apiKey, "admin");234 if (!project) {235 throw new ConvexError({236 code: "INVALID_API_KEY",237 message: "API key is invalid or inactive",238 });239 }240 return project;241}242 243async function projectByIdForCurrentUser(244 ctx: QueryCtx,245 projectId: Id<"projects"> | undefined,246): Promise<Doc<"projects"> | null> {247 if (!projectId) return null;248 const resolved = await resolveProjectByIdForCurrentUserFromDb(ctx, projectId);249 return resolved?.project ?? null;250}251 252async function projectForReadArgs(253 ctx: QueryCtx,254 args: {255 apiKey?: string;256 projectId?: Id<"projects">;257 },258 apiKeyAccess: "client" | "admin" = "client",259): Promise<Doc<"projects"> | null> {260 if (args.projectId) {261 return projectByIdForCurrentUser(ctx, args.projectId);262 }263 264 if (args.apiKey !== undefined) {265 return projectByApiKey(ctx, args.apiKey, apiKeyAccess);266 }267 268 throw new Error("apiKey or projectId is required.");269}270 271// A dashboard member reads the list without store tokens; secret API keys272// keep them for reconciliation.273async function listReadAccess(274 ctx: QueryCtx,275 args: { apiKey?: string; projectId?: Id<"projects"> },276): Promise<{ project: Doc<"projects">; storeTokens: boolean } | null> {277 if (args.projectId) {278 const access = await resolveProjectByIdForCurrentUserFromDb(279 ctx,280 args.projectId,281 );282 return access283 ? {284 project: access.project,285 storeTokens: canReadRawStoreEvidence(access.role),286 }287 : null;288 }289 const project = await projectForReadArgs(ctx, args, "admin");290 return project ? { project, storeTokens: true } : null;291}292 293// purchaseToken stays present but empty: the field is required (see above).294function withoutStoreToken(row: SubscriptionRow): SubscriptionRow {295 const { originalTransactionId: _originalTransactionId, ...rest } = row;296 return { ...rest, purchaseToken: "" };297}298 299export interface MrrCurrencyEntry {300 currency: string;301 mrrMicros: number;302}303 304/**305 * Selects the headline MRR entry for a project's reporting currency.306 *307 * `reportingCurrency` is normalized via `normalizeReportingCurrencyOrDefault`,308 * so unknown or invalid input falls back to `DEFAULT_REPORTING_CURRENCY`.309 * If no entry matches the normalized currency, returned `mrrMicros` is `0`.310 * Returned `excludedMrrByCurrency` contains every non-reporting-currency entry.311 *312 * @param entries Per-currency MRR rows already summed for the project.313 * @param reportingCurrency Project-configured reporting currency, raw or normalized.314 * @returns The normalized `currency`, selected `mrrMicros`, and excluded rows.315 */316export function selectReportingMrr(317 entries: MrrCurrencyEntry[],318 reportingCurrency: string | null | undefined,319): {320 currency: string;321 mrrMicros: number;322 excludedMrrByCurrency: MrrCurrencyEntry[];323} {324 const normalizedReportingCurrency =325 normalizeReportingCurrencyOrDefault(reportingCurrency);326 const reportingEntry = entries.find(327 (entry) => entry.currency === normalizedReportingCurrency,328 );329 330 return {331 currency: normalizedReportingCurrency,332 mrrMicros: reportingEntry?.mrrMicros ?? 0,333 excludedMrrByCurrency: entries.filter(334 (entry) => entry.currency !== normalizedReportingCurrency,335 ),336 };337}338 339// Clock-free snapshot for the Fly HTTP layer, so Convex can cache it and340// invalidate it on row changes. Of the historical rows only the latest is kept,341// as the status fallback; Fly drops candidates whose expiresAt has passed using342// its own clock.343export const subscriptionEvaluationSnapshot = query({344 args: {345 apiKey: v.string(),346 userId: v.string(),347 },348 returns: v.object({349 projectId: v.union(v.id("projects"), v.null()),350 candidates: v.array(subscriptionEvaluationRowShape),351 fallback: v.union(subscriptionEvaluationRowShape, v.null()),352 }),353 handler: async (ctx, args) => {354 await assertCliScope(ctx, "read");355 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);356 357 const rows = await userSubscriptionRows(ctx, project._id, args.userId);358 return {359 projectId: project._id,360 ...shapeSubscriptionEvaluationSnapshot(rows),361 };362 },363});364 365// `/v2` account reads are server-to-server. Convex repeats the admin check and366// shapes the response without store credentials before it crosses the HTTP367// boundary.368export const subscriptionStatusV2 = query({369 args: {370 apiKey: v.string(),371 userId: v.string(),372 now: v.number(),373 environment: v.optional(environmentScopeValidator),374 },375 returns: v.object({376 active: v.boolean(),377 subscription: v.union(subscriptionV2Shape, v.null()),378 environmentScope: v.optional(environmentScopeValidator),379 }),380 handler: async (ctx, args) => {381 await assertCliScope(ctx, "read");382 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);383 384 const subs = (385 await userSubscriptionRows(ctx, project._id, args.userId)386 ).filter((sub) => subscriptionInEnvironment(sub, args.environment));387 const activeSubs = subs.filter((candidate) =>388 isActive(candidate, args.now),389 );390 const selected = selectMostRecentlyUpdatedSubscription(391 activeSubs.length > 0 ? activeSubs : subs,392 );393 394 return {395 active: activeSubs.length > 0,396 subscription: selected ? shapeSubscriptionV2Row(selected) : null,397 ...(args.environment === undefined398 ? {}399 : { environmentScope: args.environment }),400 };401 },402});403 404export const entitlementsV2 = query({405 args: {406 apiKey: v.string(),407 userId: v.string(),408 now: v.number(),409 environment: v.optional(environmentScopeValidator),410 },411 returns: v.object({412 userId: v.string(),413 productIds: v.array(v.string()),414 subscriptions: v.array(subscriptionV2Shape),415 environmentScope: v.optional(environmentScopeValidator),416 }),417 handler: async (ctx, args) => {418 await assertCliScope(ctx, "read");419 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);420 421 const all = await userSubscriptionRows(ctx, project._id, args.userId);422 const active = all.filter(423 (sub) =>424 subscriptionInEnvironment(sub, args.environment) &&425 isActive(sub, args.now),426 );427 return {428 userId: args.userId,429 productIds: Array.from(new Set(active.map((sub) => sub.productId))),430 subscriptions: active.map(shapeSubscriptionV2Row),431 ...(args.environment === undefined432 ? {}433 : { environmentScope: args.environment }),434 };435 },436});437 438// Authoritative server-credential gate with no side effect and no data. The439// commerce bindPurchase handler calls this before it parses store evidence, so440// an unknown or under-scoped key is rejected (UNAUTHORIZED / FORBIDDEN) before441// it can learn which stores bind or which evidence a store requires.442export const assertServerAccess = query({443 args: { apiKey: v.string() },444 returns: v.object({ ok: v.boolean() }),445 handler: async (ctx, args) => {446 await assertCliScope(ctx, "read");447 await requireAdminProjectByApiKey(ctx, args.apiKey);448 return { ok: true };449 },450});451 452export const userErasureStatusV2 = query({453 args: {454 apiKey: v.string(),455 // The id arrives from a URL path; a malformed one must read as "no such456 // job" (404), not fail argument validation into a 500.457 jobId: v.string(),458 },459 returns: v.union(460 v.null(),461 v.object({462 jobId: v.id("subscriptionUserErasureJobs"),463 status: v.union(464 v.literal("queued"),465 v.literal("running"),466 v.literal("completed"),467 ),468 subscriptionsErased: v.number(),469 commerceEventsErased: v.number(),470 createdAt: v.number(),471 updatedAt: v.number(),472 completedAt: v.optional(v.number()),473 }),474 ),475 handler: async (ctx, args) => {476 await assertCliScope(ctx, "read");477 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);478 const jobId = ctx.db.normalizeId("subscriptionUserErasureJobs", args.jobId);479 if (!jobId) return null;480 const job = await ctx.db.get(jobId);481 if (!job || job.projectId !== project._id) return null;482 return {483 jobId: job._id,484 status: job.status,485 subscriptionsErased: job.subscriptionsErased,486 commerceEventsErased: job.commerceEventsErased,487 createdAt: job.createdAt,488 updatedAt: job.updatedAt,489 completedAt: job.completedAt,490 };491 },492});493 494// Match onesub's `/onesub/status?userId=` — returns the most-recently-495// updated active subscription when the user is entitled, otherwise the496// most-recently-updated subscription overall, plus one `active` boolean497// for simple gating.498export const subscriptionStatus = query({499 args: { apiKey: v.string(), userId: v.string() },500 returns: v.object({501 active: v.boolean(),502 subscription: v.union(subscriptionShape, v.null()),503 }),504 handler: async (ctx, args) => {505 await assertCliScope(ctx, "read");506 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);507 508 const subs = await userSubscriptionRows(ctx, project._id, args.userId);509 510 const now = Date.now();511 const activeSubs = subs.filter((candidate) => isActive(candidate, now));512 const sub = selectMostRecentlyUpdatedSubscription(513 activeSubs.length > 0 ? activeSubs : subs,514 );515 if (!sub) return { active: false, subscription: null };516 517 return {518 active: activeSubs.length > 0,519 subscription: shapeSubscriptionRow(sub),520 };521 },522});523 524// Match onesub's entitlement evaluation — every productId the user525// currently has rights to. Aggregates across all subscription rows so526// a user with multiple offers (resub, family share, cross-grade) sees527// the union.528export const entitlements = query({529 args: { apiKey: v.string(), userId: v.string() },530 returns: v.object({531 userId: v.string(),532 productIds: v.array(v.string()),533 subscriptions: v.array(subscriptionShape),534 }),535 handler: async (ctx, args) => {536 await assertCliScope(ctx, "read");537 const project = await requireAdminProjectByApiKey(ctx, args.apiKey);538 539 const all = await userSubscriptionRows(ctx, project._id, args.userId);540 541 const now = Date.now();542 const active = all.filter((sub) => isActive(sub, now));543 return {544 userId: args.userId,545 productIds: Array.from(new Set(active.map((sub) => sub.productId))),546 subscriptions: active.map(shapeSubscriptionRow),547 };548 },549});550 551// Filtered list for the dashboard's subscriptions page. Mirrors552// onesub's `SubscriptionStore.listFiltered` API.553export const listSubscriptions = query({554 args: {555 apiKey: v.optional(v.string()),556 projectId: v.optional(v.id("projects")),557 state: v.optional(subscriptionStateValidator),558 productId: v.optional(v.string()),559 userId: v.optional(v.string()),560 limit: v.optional(v.number()),561 },562 returns: v.object({563 items: v.array(subscriptionShape),564 total: v.number(),565 }),566 handler: async (ctx, args) => {567 await assertCliScope(ctx, "read");568 const access = await listReadAccess(ctx, args);569 if (!access) return { items: [], total: 0 };570 const { project } = access;571 const shape = access.storeTokens572 ? shapeSubscriptionRow573 : (sub: Doc<"subscriptions">) =>574 withoutStoreToken(shapeSubscriptionRow(sub));575 576 const limit = Math.min(Math.max(args.limit ?? 50, 1), 200);577 578 // A user has few subscriptions, so load them all and filter by state and579 // productId in memory.580 if (args.userId) {581 const userRows = await ctx.db582 .query("subscriptions")583 .withIndex("by_project_and_user", (q) =>584 q.eq("projectId", project._id).eq("userId", args.userId),585 )586 .order("desc")587 .collect();588 const filtered = userRows.filter((sub) => {589 if (args.state && sub.state !== args.state) return false;590 if (args.productId && sub.productId !== args.productId) return false;591 return true;592 });593 return {594 items: filtered.slice(0, limit).map(shape),595 total: filtered.length,596 };597 }598 599 // Every filter combination has an index (state + productId is a composite),600 // so take() never cuts off rows a post-filter would need.601 let rows: Array<Doc<"subscriptions">>;602 if (args.state && args.productId) {603 rows = await ctx.db604 .query("subscriptions")605 .withIndex("by_project_and_state_and_product", (q) =>606 q607 .eq("projectId", project._id)608 .eq("state", args.state!)609 .eq("productId", args.productId!),610 )611 .order("desc")612 .take(limit);613 } else if (args.state) {614 rows = await ctx.db615 .query("subscriptions")616 .withIndex("by_project_and_state", (q) =>617 q.eq("projectId", project._id).eq("state", args.state!),618 )619 .order("desc")620 .take(limit);621 } else if (args.productId) {622 rows = await ctx.db623 .query("subscriptions")624 .withIndex("by_project_and_product", (q) =>625 q.eq("projectId", project._id).eq("productId", args.productId!),626 )627 .order("desc")628 .take(limit);629 } else {630 rows = await ctx.db631 .query("subscriptions")632 .withIndex("by_project_and_updated", (q) =>633 q.eq("projectId", project._id),634 )635 .order("desc")636 .take(limit);637 }638 639 // `total` counts the rows loaded, not every match; a true count would need640 // an unbounded scan.641 return {642 items: rows.slice(0, limit).map(shape),643 total: rows.length,644 };645 },646});647 648// Admin reads fail on an unknown key rather than answer with an empty project.649async function projectForAdminRead(650 ctx: QueryCtx,651 args: { apiKey?: string; projectId?: Id<"projects"> },652): Promise<Doc<"projects"> | null> {653 if (!args.projectId && args.apiKey !== undefined) {654 return requireAdminProjectByApiKey(ctx, args.apiKey);655 }656 return projectForReadArgs(ctx, args, "admin");657}658 659// Current caches avoid a subscription scan. Legacy or expired caches use a660// bounded fallback; an incomplete result is explicit, never a current total.661export const metricsSummary = query({662 args: {663 apiKey: v.optional(v.string()),664 projectId: v.optional(v.id("projects")),665 refreshAt: v.optional(v.number()),666 },667 returns: v.object({668 environment: v.literal("Production"),669 stats: v.object({670 state: v.union(671 v.literal("current"),672 v.literal("rebuilding"),673 v.literal("incomplete"),674 ),675 asOf: v.number(),676 validUntil: v.union(v.number(), v.null()),677 }),678 recentCountsTruncated: v.boolean(),679 activeSubs: v.number(),680 inGracePeriod: v.number(),681 inBillingRetry: v.number(),682 refunded30d: v.number(),683 canceled30d: v.number(),684 // Monthly MRR in the reporting currency only; the name predates685 // per-currency MRR and is kept for dashboard and MCP consumers.686 mrrMicros: v.number(),687 currency: v.optional(v.string()),688 reportingCurrency: v.string(),689 // Per-currency MRR, each normalized to monthly by the product's690 // billingPeriod.691 mrrByCurrency: v.array(692 v.object({ currency: v.string(), mrrMicros: v.number() }),693 ),694 excludedMrrByCurrency: v.array(695 v.object({ currency: v.string(), mrrMicros: v.number() }),696 ),697 }),698 handler: async (ctx, args) => {699 await assertCliScope(ctx, "read");700 const project = await projectForAdminRead(ctx, args);701 if (!project) {702 return {703 environment: "Production" as const,704 stats: {705 state: "incomplete" as const,706 asOf: Date.now(),707 validUntil: null,708 },709 recentCountsTruncated: false,710 activeSubs: 0,711 inGracePeriod: 0,712 inBillingRetry: 0,713 refunded30d: 0,714 canceled30d: 0,715 mrrMicros: 0,716 currency: DEFAULT_REPORTING_CURRENCY,717 reportingCurrency: DEFAULT_REPORTING_CURRENCY,718 mrrByCurrency: [],719 excludedMrrByCurrency: [],720 };721 }722 const now = Date.now();723 const cutoff = now - 30 * 24 * 60 * 60 * 1000;724 725 // Live state counters + MRR — read out of the incrementally726 // maintained `subscriptionStats` table.727 const statsRows = await ctx.db728 .query("subscriptionStats")729 .withIndex("by_project", (q) => q.eq("projectId", project._id))730 .collect();731 732 const status = await ctx.db733 .query("revenueMetricsRunStatus")734 .withIndex("by_project", (q) => q.eq("projectId", project._id))735 .unique();736 const cacheCurrent = statsRows.length > 0 && statsAreCurrent(status, now);737 // Reactive pagination retains a journal, so its indexed range stays fixed.738 const result = await ctx.db739 .query("subscriptions")740 .withIndex("by_project_and_updated", (q) =>741 q.eq("projectId", project._id),742 )743 .order("desc")744 .paginate({745 cursor: null,746 numItems: 10_000,747 maximumRowsRead: 10_000,748 maximumBytesRead: SUBSCRIPTION_SCAN_BYTES,749 });750 const pageComplete = result.isDone && result.pageStatus !== "SplitRequired";751 const recentlyChanged = result.page.filter(752 (sub) => sub.updatedAt >= cutoff,753 );754 const recentCountsTruncated =755 result.pageStatus === "SplitRequired" ||756 (!result.isDone && (result.page.at(-1)?.updatedAt ?? now) >= cutoff);757 let validUntil: number | null = cacheCurrent758 ? (status?.statsValidUntil ?? null)759 : null;760 let statsState: "current" | "rebuilding" | "incomplete" = "current";761 let activeSubs = 0;762 let inGracePeriod = 0;763 let inBillingRetry = 0;764 const mrrAccumulators = new Map<string, number>();765 766 if (cacheCurrent) {767 for (const row of statsRows) {768 activeSubs += row.activeSubs;769 inGracePeriod += row.inGracePeriod;770 inBillingRetry += row.inBillingRetry;771 if (row.currency && row.mrrMicros > 0) {772 mrrAccumulators.set(773 row.currency,774 (mrrAccumulators.get(row.currency) ?? 0) + row.mrrMicros,775 );776 }777 }778 } else {779 const periods = await loadStatsPeriods(ctx, project._id, result.page);780 if (!pageComplete || periods === null) {781 const rebuilding = await ctx.db782 .query("subscriptionStatsRebuilds")783 .withIndex("by_project", (q) => q.eq("projectId", project._id))784 .unique();785 statsState = rebuilding ? "rebuilding" : "incomplete";786 }787 for (const sub of result.page) {788 const contribution = statsContributionFor(789 sub,790 periods?.get(`${sub.platform}:${sub.productId}`),791 now,792 );793 if (contribution?.expiresAt !== undefined)794 validUntil =795 validUntil === null796 ? contribution.expiresAt797 : Math.min(validUntil, contribution.expiresAt);798 if (contribution?.state === "Active") {799 activeSubs += 1;800 if (contribution.mrrMicros > 0) {801 mrrAccumulators.set(802 contribution.currency,803 (mrrAccumulators.get(contribution.currency) ?? 0) +804 contribution.mrrMicros,805 );806 }807 } else if (contribution?.state === "InGracePeriod") {808 inGracePeriod += 1;809 } else if (contribution?.state === "InBillingRetry") {810 inBillingRetry += 1;811 }812 }813 }814 815 let refunded30d = 0;816 let canceled30d = 0;817 const CANCELED_STATES = new Set([818 "Active",819 "InGracePeriod",820 "InBillingRetry",821 "Expired",822 ]);823 for (const sub of recentlyChanged) {824 if (subscriptionEnvironment(sub) !== "Production") continue;825 if (sub.state === "Refunded") {826 refunded30d += 1;827 }828 if (829 sub.willRenew === false &&830 sub.cancellationReason === "UserCanceled" &&831 CANCELED_STATES.has(sub.state)832 ) {833 canceled30d += 1;834 }835 }836 837 // Sorted for stable rendering. Only the reporting currency feeds the838 // headline; the others stay in `excludedMrrByCurrency` instead of being839 // summed.840 const sorted = Array.from(mrrAccumulators.entries()).sort(841 ([a, av], [b, bv]) => (bv !== av ? bv - av : a.localeCompare(b)),842 );843 const mrrByCurrency = sorted.map(([currency, mrrMicros]) => ({844 currency,845 mrrMicros,846 }));847 const reportingMrr = selectReportingMrr(848 mrrByCurrency,849 project.reportingCurrency,850 );851 852 return {853 environment: "Production" as const,854 stats: {855 state: statsState,856 asOf: cacheCurrent ? status!.statsUpdatedAt! : now,857 validUntil,858 },859 recentCountsTruncated,860 activeSubs,861 inGracePeriod,862 inBillingRetry,863 refunded30d,864 canceled30d,865 mrrMicros: reportingMrr.mrrMicros,866 currency: reportingMrr.currency,867 reportingCurrency: reportingMrr.currency,868 mrrByCurrency,869 excludedMrrByCurrency: reportingMrr.excludedMrrByCurrency,870 };871 },872});873 874// Daily metrics for the Analytics dashboard from the `revenueMetricsDaily`875// rollups, so a render never scans `webhookEvents`. `fromDay` and `toDay` are876// inclusive UTC YYYY-MM-DD, compared as strings on the index. Returns one entry877// per (day, currency, productId, platform) of one environment, production by878// default; rows in different currencies need an FX rate to add. Definitions879// are in `revenueMetrics.ts`; the optional counters are absent on rows written880// before `definitionsFromDay`, and the trial split before `trialSplitFromDay`.881const platformValidator = v.union(v.literal("IOS"), v.literal("Android"));882 883// not_collected: no store notification has reached the environment.884// processing: notifications exist but the window is not rolled up yet.885// zero: the window was rolled up and nothing happened.886// ready: the window has rows.887const analyticsDataStateValidator = v.union(888 v.literal("not_collected"),889 v.literal("processing"),890 v.literal("zero"),891 v.literal("ready"),892);893 894const revenueCohortShape = v.object({895 month: v.string(),896 currency: v.string(),897 members: v.number(),898 revenueMicros: v.number(),899 refundedMicros: v.number(),900 // Gross revenue per member observed through `observedThrough`; never projected.901 realizedLtvMicros: v.number(),902 retained: v.array(v.number()),903 retentionObserved: v.optional(v.array(v.number())),904 trialStarts: v.number(),905 trialConversions: v.number(),906 trialsPending: v.number(),907 trialsUnobserved: v.optional(v.number()),908 observedThrough: v.string(),909});910 911const revenueMetricsResponse = v.object({912 days: v.array(913 v.object({914 day: v.string(),915 currency: v.string(),916 productId: v.string(),917 platform: platformValidator,918 activeSubs: v.number(),919 activeHistoryComplete: v.optional(v.boolean()),920 activeTrials: v.optional(v.number()),921 newSubs: v.number(),922 trialStarts: v.optional(v.number()),923 trialConversions: v.optional(v.number()),924 directPaidStarts: v.optional(v.number()),925 renewals: v.number(),926 cancellations: v.number(),927 expirations: v.optional(v.number()),928 refunds: v.number(),929 revenueMicros: v.number(),930 refundedMicros: v.optional(v.number()),931 }),932 ),933 // Every value in the window, for the dashboard's filter dropdowns.934 currencies: v.array(v.string()),935 productIds: v.array(v.string()),936 platforms: v.array(platformValidator),937 // The scan hit REVENUE_SCAN_CAP; the dashboard shows a banner.938 truncated: v.boolean(),939 environment: receiptEnvironmentValidator,940 dataState: analyticsDataStateValidator,941 lastRunAt: v.optional(v.number()),942 // Days from here on follow the current definitions; earlier rows mix943 // sandbox into production and have no trial split.944 definitionsFromDay: v.optional(v.string()),945 // Days from here on separate free trials, trial conversions, unpaid trial946 // expirations, refund reversals and Apple resubscribes. Earlier days omit947 // the counters that need them; unset when every day has them.948 trialSplitFromDay: v.optional(v.string()),949 // Notifications that arrived after their day's rollup and are waiting for950 // a catch-up recompute.951 pendingLateEvents: v.number(),952 oldestPendingLateDay: v.optional(v.string()),953 cohorts: v.optional(v.array(revenueCohortShape)),954 cohortsComputedAt: v.optional(v.number()),955});956 957// `days` returns every row, and a Convex array holds at most 8,192 items: about958// 92 days of 30 SKUs × 3 currencies on one platform. Hitting it sets959// `truncated`.960const REVENUE_SCAN_CAP = 8_192;961 962export const getRevenueMetrics = query({963 args: {964 apiKey: v.optional(v.string()),965 projectId: v.optional(v.id("projects")),966 fromDay: v.string(),967 toDay: v.string(),968 // No product, currency or platform args: the dashboard filters client-side969 // and fills its dropdowns from the unfiltered rows. Add a separate query if970 // another caller needs narrowing.971 environment: v.optional(receiptEnvironmentValidator),972 includeCohorts: v.optional(v.boolean()),973 },974 returns: revenueMetricsResponse,975 handler: async (ctx, args): Promise<Infer<typeof revenueMetricsResponse>> => {976 await assertCliScope(ctx, "read");977 const project = await projectForAdminRead(ctx, args);978 const environment = args.environment ?? "Production";979 if (!project) {980 return {981 days: [],982 currencies: [],983 productIds: [],984 platforms: [],985 truncated: false,986 environment,987 dataState: "not_collected" as const,988 pendingLateEvents: 0,989 };990 }991 992 // Cap at the dashboard's longest preset plus the day before it (`RANGES`993 // in analytics.tsx; change both together) so a client cannot load every994 // rollup row.995 const MAX_RANGE_DAYS = 92;996 if (args.fromDay > args.toDay) {997 throw new Error(998 `getRevenueMetrics: fromDay (${args.fromDay}) is after toDay (${args.toDay}).`,999 );1000 }1001 const fromMs = Date.parse(`${args.fromDay}T00:00:00.000Z`);1002 const toMs = Date.parse(`${args.toDay}T00:00:00.000Z`);1003 if (Number.isNaN(fromMs) || Number.isNaN(toMs)) {1004 throw new Error(1005 `getRevenueMetrics: invalid ISO date(s) fromDay=${args.fromDay} toDay=${args.toDay}.`,1006 );1007 }1008 const spanDays = Math.round((toMs - fromMs) / 86_400_000) + 1;1009 if (spanDays > MAX_RANGE_DAYS) {1010 throw new Error(1011 `getRevenueMetrics: span of ${spanDays} days exceeds MAX_RANGE_DAYS=${MAX_RANGE_DAYS}.`,1012 );1013 }1014 1015 // Rows from before the environment split have none and count as1016 // production.1017 const environmentKeys =1018 environment === "Production"1019 ? (["Production", undefined] as const)1020 : (["Sandbox"] as const);1021 // Newest first, so a full window drops its oldest days, and legacy rows,1022 // the oldest of all, go before any current one.1023 const rows: Doc<"revenueMetricsDaily">[] = [];1024 for (const key of environmentKeys) {1025 rows.push(1026 ...(await ctx.db1027 .query("revenueMetricsDaily")1028 .withIndex("by_project_and_environment_and_day", (q) =>1029 q1030 .eq("projectId", project._id)1031 .eq("environment", key)1032 .gte("day", args.fromDay)1033 .lte("day", args.toDay),1034 )1035 .order("desc")1036 .take(REVENUE_SCAN_CAP + 1 - rows.length)),1037 );1038 }1039 const truncated = rows.length > REVENUE_SCAN_CAP;1040 if (truncated) {1041 // The day the cap cut into is partial, which would skew its totals and1042 // churn base, so it goes whole unless it is the only day left.1043 const cutDay = rows[REVENUE_SCAN_CAP].day;1044 const keep = rows.findIndex((row) => row.day <= cutDay);1045 rows.splice(keep > 0 ? keep : REVENUE_SCAN_CAP);1046 }1047 // Return main's day order.1048 rows.sort(1049 (a, b) =>1050 a.day.localeCompare(b.day) ||1051 a.currency.localeCompare(b.currency) ||1052 a._creationTime - b._creationTime,1053 );1054 if (truncated) {1055 console.warn(1056 `[getRevenueMetrics] revenueMetricsDaily scan hit REVENUE_SCAN_CAP=${REVENUE_SCAN_CAP} for project=${project._id} environment=${environment} range=${args.fromDay}..${args.toDay}; the oldest days are missing.`,1057 );1058 }1059 1060 const currencies = new Set<string>();1061 const productIds = new Set<string>();1062 const platforms = new Set<"IOS" | "Android">();1063 for (const row of rows) {1064 if (row.currency) currencies.add(row.currency);1065 productIds.add(row.productId);1066 platforms.add(row.platform);1067 }1068 1069 const status = await ctx.db1070 .query("revenueMetricsRunStatus")1071 .withIndex("by_project", (q) => q.eq("projectId", project._id))1072 .unique();1073 const dataState = await revenueDataState(ctx, {1074 projectId: project._id,1075 environment,1076 hasRows: rows.some(1077 (row) =>1078 row.activeHistoryUnknown !== 0 ||1079 REVENUE_COUNTERS.some((key) => (row[key] ?? 0) !== 0),1080 ),1081 toDay: args.toDay,1082 status,1083 });1084 const cohorts = args.includeCohorts1085 ? await revenueCohorts(ctx, project._id, environment)1086 : undefined;1087 const trialSplitFromDay = status?.trialSplitFromDay;1088 1089 return {1090 days: rows.map((row) => ({1091 day: row.day,1092 currency: row.currency,1093 productId: row.productId,1094 platform: row.platform,1095 activeSubs: row.activeSubs,1096 activeHistoryComplete: row.activeHistoryUnknown === 0,1097 newSubs: row.newSubs,1098 renewals: row.renewals,1099 cancellations: row.cancellations,1100 refunds: row.refunds,1101 revenueMicros: row.revenueMicros,1102 refundedMicros: row.refundedMicros,1103 // These need the free-trial flags notifications carry from1104 // `trialSplitFromDay` on, so earlier days omit them.1105 ...(trialSplitFromDay === undefined || row.day >= trialSplitFromDay1106 ? {1107 activeTrials: row.activeTrials,1108 trialStarts: row.trialStarts,1109 trialConversions: row.trialConversions,1110 directPaidStarts: row.directPaidStarts,1111 expirations: row.expirations,1112 }1113 : {}),1114 })),1115 currencies: Array.from(currencies).sort(),1116 productIds: Array.from(productIds).sort(),1117 platforms: Array.from(platforms).sort(),1118 truncated,1119 environment,1120 dataState,1121 lastRunAt: status?.lastRunAt,1122 definitionsFromDay: status?.definitionsFromDay,1123 trialSplitFromDay,1124 pendingLateEvents: status?.pendingLateEvents ?? 0,1125 oldestPendingLateDay: status?.oldestPendingLateDay,1126 ...(cohorts1127 ? { cohorts, cohortsComputedAt: status?.cohortsComputedAt }1128 : {}),1129 };1130 },1131});1132 1133// Rows alone never mean collected: a project that only calls verify still gets1134// activeSubs rows, but its event counters would read as real zeros.1135async function revenueDataState(1136 ctx: QueryCtx,1137 args: {1138 projectId: Id<"projects">;1139 environment: Infer<typeof receiptEnvironmentValidator>;1140 hasRows: boolean;1141 toDay: string;1142 status: Doc<"revenueMetricsRunStatus"> | null;1143 },1144): Promise<Infer<typeof analyticsDataStateValidator>> {1145 const status = args.status;1146 if (1147 status?.lastRunAt === undefined ||1148 status.definitionsVersion !== ROLLUP_DEFINITIONS_VERSION1149 ) {1150 // No finished run has looked for store notifications yet. Oldest rows1151 // only, so new notifications never invalidate this query.1152 const anyEvent = await ctx.db1153 .query("webhookEvents")1154 .withIndex("by_project", (q) => q.eq("projectId", args.projectId))1155 .first();1156 return anyEvent ? "processing" : "not_collected";1157 }1158 if (status.lastNotificationAt?.[args.environment] === undefined) {1159 return "not_collected";1160 }1161 if (args.hasRows) return "ready";1162 if (args.toDay > new Date(status.lastRunAt).toISOString().slice(0, 10)) {1163 return "processing";1164 }1165 return "zero";1166}1167 1168async function revenueCohorts(1169 ctx: QueryCtx,1170 projectId: Id<"projects">,1171 environment: Infer<typeof receiptEnvironmentValidator>,1172): Promise<Array<Infer<typeof revenueCohortShape>>> {1173 // Rebuilt as a whole each day: at most COHORT_MONTHS × 2 × currencies rows.1174 const rows = await ctx.db1175 .query("revenueCohortsMonthly")1176 .withIndex("by_project", (q) => q.eq("projectId", projectId))1177 .collect();1178 return rows1179 .filter((row) => row.environment === environment)1180 .sort((a, b) =>1181 a.month !== b.month1182 ? a.month.localeCompare(b.month)1183 : a.currency.localeCompare(b.currency),1184 )1185 .map((row) => ({1186 month: row.month,1187 currency: row.currency,1188 members: row.members,1189 revenueMicros: row.revenueMicros,1190 refundedMicros: row.refundedMicros,1191 realizedLtvMicros:1192 row.members > 0 ? Math.round(row.revenueMicros / row.members) : 0,1193 retained: row.retained,1194 retentionObserved: row.retentionObserved,1195 trialStarts: row.trialStarts,1196 trialConversions: row.trialConversions,1197 trialsPending: row.trialsPending,1198 trialsUnobserved: row.trialsUnobserved,1199 observedThrough: row.observedThrough,1200 }));1201}1202 1203const TIMELINE_ROWS_PER_KIND = 50;1204 1205const timelineItemValidator = v.union(1206 v.object({1207 kind: v.literal("purchase"),1208 id: v.id("purchases"),1209 at: v.number(),1210 store: purchaseStoreValidator,1211 productId: v.optional(v.string()),1212 state: v.string(),1213 isValid: v.boolean(),1214 }),1215 v.object({1216 kind: v.literal("subscription"),1217 id: v.id("subscriptions"),1218 at: v.number(),1219 store: purchaseStoreValidator,1220 productId: v.string(),1221 state: subscriptionStateValidator,1222 expiresAt: v.optional(v.number()),1223 willRenew: v.optional(v.boolean()),1224 }),1225 v.object({1226 kind: v.literal("event"),1227 id: v.id("commerceEvents"),1228 at: v.number(),1229 store: purchaseStoreValidator,1230 eventType: v.string(),1231 productId: v.optional(v.string()),1232 }),1233 v.object({1234 kind: v.literal("issue"),1235 id: v.id("purchaseIssues"),1236 at: v.number(),1237 store: purchaseStoreValidator,1238 cause: purchaseIssueCauseValidator,1239 productId: v.optional(v.string()),1240 count: v.number(),1241 }),1242);1243export type TimelineItem = Infer<typeof timelineItemValidator>;1244 1245/**1246 * One app user's purchases, subscriptions, commerce events and purchase1247 * issues, newest first. Each kind is capped at 50 rows; `truncated` says a cap1248 * was reached.1249 */1250export const userTimeline = query({1251 args: {1252 projectId: v.optional(v.id("projects")),1253 apiKey: v.optional(v.string()),1254 appUserId: v.string(),1255 },1256 returns: v.object({1257 appUserId: v.string(),1258 items: v.array(timelineItemValidator),1259 truncated: v.boolean(),1260 }),1261 handler: async (ctx, args) => {1262 await assertCliScope(ctx, "read");1263 const project = await resolveOperatorProject(ctx, args, "read");1264 if (!isValidSubscriptionUserId(args.appUserId)) {1265 throw new ConvexError({1266 code: "INVALID_INPUT",1267 message: `appUserId must be 1 to ${MAX_SUBSCRIPTION_USER_ID_LENGTH} characters`,1268 });1269 }1270 const take = TIMELINE_ROWS_PER_KIND + 1;1271 const [updatedPurchases, legacyPurchases, subscriptions, events, issues] =1272 await Promise.all([1273 ctx.db1274 .query("purchases")1275 .withIndex("by_project_and_app_user_and_updated", (q) =>1276 q1277 .eq("projectId", project._id)1278 .eq("appUserId", args.appUserId)1279 .gt("updatedAt", undefined),1280 )1281 .order("desc")1282 .take(take),1283 ctx.db1284 .query("purchases")1285 .withIndex("by_project_and_app_user_and_updated", (q) =>1286 q1287 .eq("projectId", project._id)1288 .eq("appUserId", args.appUserId)1289 .eq("updatedAt", undefined),1290 )1291 .order("desc")1292 .take(take),1293 ctx.db1294 .query("subscriptions")1295 .withIndex("by_project_and_user_and_updated", (q) =>1296 q.eq("projectId", project._id).eq("userId", args.appUserId),1297 )1298 .order("desc")1299 .take(take),1300 ctx.db1301 .query("commerceEvents")1302 .withIndex("by_project_and_user_and_occurred", (q) =>1303 q.eq("projectId", project._id).eq("userId", args.appUserId),1304 )1305 .order("desc")1306 .take(take),1307 ctx.db1308 .query("purchaseIssues")1309 .withIndex("by_project_and_appUserId_and_lastSeenAt", (q) =>1310 q.eq("projectId", project._id).eq("appUserId", args.appUserId),1311 )1312 .order("desc")1313 .take(take),1314 ]);1315 const purchases = [...updatedPurchases, ...legacyPurchases]1316 .sort(1317 (a, b) =>1318 (b.updatedAt ?? b._creationTime) - (a.updatedAt ?? a._creationTime),1319 )1320 .slice(0, take);1321 const items: TimelineItem[] = [1322 ...purchases.slice(0, TIMELINE_ROWS_PER_KIND).map(1323 (purchase): TimelineItem => ({1324 kind: "purchase",1325 id: purchase._id,1326 at: purchase.updatedAt ?? purchase._creationTime,1327 store: purchase.store,1328 ...(purchase.productId ? { productId: purchase.productId } : {}),1329 state: purchase.state,1330 isValid: purchase.isValid ?? false,1331 }),1332 ),1333 ...subscriptions.slice(0, TIMELINE_ROWS_PER_KIND).map(1334 (subscription): TimelineItem => ({1335 kind: "subscription",1336 id: subscription._id,1337 at: subscription.updatedAt,1338 store: storeOf(subscription),1339 productId: subscription.productId,1340 state: subscription.state,1341 ...(subscription.expiresAt !== undefined1342 ? { expiresAt: subscription.expiresAt }1343 : {}),1344 ...(subscription.willRenew !== undefined1345 ? { willRenew: subscription.willRenew }1346 : {}),1347 }),1348 ),1349 ...events.slice(0, TIMELINE_ROWS_PER_KIND).map(1350 (event): TimelineItem => ({1351 kind: "event",1352 id: event._id,1353 at: event.occurredAt,1354 store: event.store,1355 eventType: event.eventType,1356 ...(event.productId ? { productId: event.productId } : {}),1357 }),1358 ),1359 ...issues.slice(0, TIMELINE_ROWS_PER_KIND).map(1360 (issue): TimelineItem => ({1361 kind: "issue",1362 id: issue._id,1363 at: issue.lastSeenAt,1364 store: issue.store,1365 cause: issue.cause,1366 ...(issue.productId ? { productId: issue.productId } : {}),1367 count: issue.count,1368 }),1369 ),1370 ].sort((a, b) => b.at - a.at);1371 return {1372 appUserId: args.appUserId,1373 items,1374 truncated: [purchases, subscriptions, events, issues].some(1375 (rows) => rows.length > TIMELINE_ROWS_PER_KIND,1376 ),1377 };1378 },1379});1380