caelum0x c724bf1700 feat: conversion, per-link, churn and LTV metrics (G14, part 1)
GET /v1/analytics/metrics computes, from live sessions, payments,
subscriptions and catalog: checkout conversion, per-payment-link opened /
paid / conversion / revenue, repeat customers, average revenue per
customer, subscription churn, ARPU and an estimated lifetime value, with
exact bigint money. Checkout repositories gain listCreatedSince
(in-memory and Postgres). The dashboard Analytics page shows the new
cards and a payment-link table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:37:57 +03:00

540 lines
19 KiB
TypeScript

// Real HTTP client for the SettleKit API.
//
// SERVER-ONLY. Every request is authenticated with the signed-in merchant's
// session token (the httpOnly `sk_session` cookie), which the API resolves to
// the merchant's organization so all data is tenant-scoped. Because it reads
// the cookie via `next/headers`, this module must run on the server — client
// components route mutations through server actions (e.g. products/new) instead
// of importing it. Failures and empty payloads degrade to empty arrays / nulls
// so pages render graceful empty states instead of crashing.
import "server-only";
import { cookies } from "next/headers";
import { API_URL } from "./config";
import type {
SentInvoice,
GrowthMetrics,
TeamInvitation,
TeamMember,
WebhookDelivery,
AgentService,
AnalyticsSummary,
ApiKey,
Bundle,
Coupon,
CreateProductInput,
Customer,
DeliveryLog,
DeliveryRun,
DiscordAccessGrant,
DiscordRole,
DiscordServer,
Dispute,
DisputeReason,
DunningState,
Entitlement,
EscrowTask,
FileAsset,
GithubAccessGrant,
GithubInstallation,
GithubRepository,
GithubTeam,
Invoice,
CreditBalance,
LicenseKey,
MarketplaceListing,
Money,
OnboardingStatus,
OrgSettings,
UsageMeter,
Payment,
Payout,
Product,
Refund,
RefundReason,
SaasFeature,
SaasPlan,
Seat,
Subscription,
PayoutBalance,
WebhookEndpoint,
} from "./types";
export { API_URL };
/** Name of the cookie holding the merchant's opaque session token. */
const SESSION_COOKIE = "sk_session";
/**
* Authorization header for the current request, derived from the signed-in
* merchant's session cookie. Absent when there is no session — the API then
* rejects the call (401), which pages surface as an error/empty state rather
* than leaking another tenant's data.
*/
function authHeader(): Record<string, string> {
const token = cookies().get(SESSION_COOKIE)?.value;
return token ? { authorization: `Bearer ${token}` } : {};
}
/**
* Discount payload accepted by `POST /v1/coupons`. A fixed-amount discount's
* `amountOff` is sent as a decimal string (e.g. "25.00"), matching the API.
*/
export type CreateCouponDiscount =
| { type: "percent"; percentOff: number }
| { type: "amount"; amountOff: string }
| { type: "free-trial-days"; days: number };
/** Webhook endpoint as the API stores it. */
interface ApiKeyRecord {
id: string;
customerId: string;
keyPrefix: string;
scopes: string[];
status: "active" | "revoked";
lastUsedAt?: string;
createdAt: string;
kind?: "platform" | "customer";
}
function toApiKey(k: ApiKeyRecord): ApiKey {
return {
id: k.id,
name: k.kind === "platform" ? k.customerId : `Buyer key (${k.customerId})`,
prefix: k.keyPrefix,
scopes: k.scopes,
lastUsedAt: k.lastUsedAt ?? null,
createdAt: k.createdAt,
kind: k.kind ?? "customer",
status: k.status,
};
}
interface ApiWebhookEndpoint {
id: string;
url: string;
enabledEvents?: string[];
active?: boolean;
signingSecret?: string;
disabledReason?: string;
consecutiveFailures?: number;
}
export interface ApiList<T> {
data: T[];
total: number;
empty: boolean;
error: string | null;
}
export interface ApiItem<T> {
data: T | null;
error: string | null;
}
function listResult<T>(data: T[], error: string | null): ApiList<T> {
return { data, total: data.length, empty: data.length === 0, error };
}
async function request<T>(path: string, init?: RequestInit): Promise<{ data: T | null; error: string | null }> {
try {
const res = await fetch(`${API_URL}${path}`, {
...init,
headers: {
"content-type": "application/json",
...authHeader(),
...(init?.headers ?? {}),
},
// Server components: always fetch fresh dashboard data.
cache: "no-store",
});
if (!res.ok) {
const failure = (await res.json().catch(() => null)) as { error?: { message?: string } } | null;
const detail = failure?.error?.message;
return { data: null, error: detail ? `${detail} (API ${res.status})` : `API ${res.status} ${res.statusText}` };
}
const body = (await res.json()) as { data?: T } | T;
const data =
body && typeof body === "object" && "data" in (body as object)
? ((body as { data: T }).data ?? null)
: (body as T);
return { data, error: null };
} catch (err) {
return {
data: null,
error: err instanceof Error ? err.message : "Network error",
};
}
}
/** Fetch a binary API resource (PDF, CSV) with the merchant's session. */
export async function fetchApiRaw(path: string): Promise<Response> {
return fetch(`${API_URL}${path}`, { headers: authHeader(), cache: "no-store" });
}
async function getList<T>(path: string): Promise<ApiList<T>> {
const { data, error } = await request<T[]>(path);
if (error) return listResult<T>([], error);
return listResult<T>(Array.isArray(data) ? data : [], null);
}
async function getItem<T>(path: string): Promise<ApiItem<T>> {
const { data, error } = await request<T>(path);
return { data, error };
}
async function post<T>(path: string, payload: unknown): Promise<ApiItem<T>> {
return request<T>(path, { method: "POST", body: JSON.stringify(payload) });
}
const ZERO: Money = { amount: 0, currency: "USDC" };
export const api = {
// ---- Overview / analytics ----
analytics: {
metrics: (days = 30) => getItem<GrowthMetrics>(`/v1/analytics/metrics?days=${days}`),
async summary(): Promise<AnalyticsSummary> {
const { data } = await getItem<AnalyticsSummary>("/v1/analytics/summary");
return (
data ?? {
revenue: ZERO,
customers: 0,
activeAccess: 0,
expiringSubscriptions: 0,
failedDeliveries: 0,
mrr: ZERO,
revenueSeries: [],
}
);
},
},
// ---- Onboarding / activation funnel ----
onboarding: {
async status(): Promise<OnboardingStatus | null> {
const { data } = await getItem<OnboardingStatus>("/v1/onboarding");
return data;
},
},
// ---- Products ----
products: {
list: () => getList<Product>("/v1/products"),
get: (id: string) => getItem<Product>(`/v1/products/${id}`),
create: (input: CreateProductInput) => post<Product>("/v1/products", input),
},
// ---- Customers / payments / subscriptions ----
customers: { list: () => getList<Customer>("/v1/customers") },
payments: { list: () => getList<Payment>("/v1/payments") },
subscriptions: { list: () => getList<Subscription>("/v1/subscriptions") },
entitlements: { list: () => getList<Entitlement>("/v1/entitlements") },
// ---- License keys / API keys / files ----
licenseKeys: { list: () => getList<LicenseKey>("/v1/license-keys") },
apiKeys: {
list: async (): Promise<ApiList<ApiKey>> => {
const raw = await getList<ApiKeyRecord>("/v1/api-keys");
return listResult(raw.data.map(toApiKey), raw.error);
},
/** Management key with restricted scopes; the plaintext is returned once. */
createPlatform: (label: string, scopes: string[]) =>
post<{ apiKey: ApiKeyRecord; plaintext: string }>("/v1/api-keys/platform", { label, scopes }),
revoke: (id: string) => post<ApiKeyRecord>(`/v1/api-keys/${encodeURIComponent(id)}/revoke`, {}),
},
team: {
get: () => getItem<{ members: TeamMember[]; invitations: TeamInvitation[]; roles: string[] }>("/v1/team"),
invite: (email: string, role: string) =>
post<{ inviteUrl: string; emailed: boolean }>("/v1/team/invitations", { email, role }),
revokeInvitation: (id: string) => post<TeamInvitation>(`/v1/team/invitations/${encodeURIComponent(id)}/revoke`, {}),
setRole: (accountId: string, role: string) =>
request<TeamMember>(`/v1/team/members/${encodeURIComponent(accountId)}`, { method: "PATCH", body: JSON.stringify({ role }) }),
remove: (accountId: string) =>
request<{ removed: string }>(`/v1/team/members/${encodeURIComponent(accountId)}`, { method: "DELETE" }),
},
files: { list: () => getList<FileAsset>("/v1/files") },
webhooks: {
list: async (): Promise<ApiList<WebhookEndpoint>> => {
const raw = await getList<ApiWebhookEndpoint>("/v1/webhooks/endpoints");
return listResult(
raw.data.map((e) => ({
id: e.id,
url: e.url,
events: e.enabledEvents ?? [],
status: e.active ? "enabled" : "disabled",
lastDeliveryAt: null,
signingSecret: e.signingSecret ?? "",
disabledReason: e.disabledReason ?? null,
consecutiveFailures: e.consecutiveFailures ?? 0,
})),
raw.error,
);
},
create: (url: string, events: string[]) =>
post<ApiWebhookEndpoint>("/v1/webhooks/endpoints", { url, enabledEvents: events }),
deliveries: (filter: { status?: string } = {}) =>
getList<WebhookDelivery>(`/v1/webhooks/deliveries${filter.status ? `?status=${encodeURIComponent(filter.status)}` : ""}`),
resend: (eventId: string, endpointId?: string) =>
post<WebhookDelivery[]>(`/v1/webhooks/events/${encodeURIComponent(eventId)}/resend`, endpointId ? { endpointId } : {}),
test: (endpointId: string) => post<WebhookDelivery>(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/test`, {}),
rotate: (endpointId: string, graceHours: number) =>
post<ApiWebhookEndpoint>(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/rotate-secret`, { graceHours }),
setActive: (endpointId: string, active: boolean) =>
post<ApiWebhookEndpoint>(`/v1/webhooks/endpoints/${encodeURIComponent(endpointId)}/${active ? "enable" : "disable"}`, {}),
},
// ---- Refunds ----
refunds: {
list: (filter?: { paymentId?: string; customerId?: string }) => {
const params = new URLSearchParams();
if (filter?.paymentId) params.set("paymentId", filter.paymentId);
if (filter?.customerId) params.set("customerId", filter.customerId);
const qs = params.toString();
return getList<Refund>(qs ? `/v1/refunds?${qs}` : "/v1/refunds");
},
create: (input: {
paymentId: string;
customerId: string;
amount: string;
reason: RefundReason;
}) => post<Refund>("/v1/refunds", input),
succeed: (id: string) => post<Refund>(`/v1/refunds/${encodeURIComponent(id)}/succeed`, {}),
fail: (id: string, reason?: string) =>
post<Refund>(`/v1/refunds/${encodeURIComponent(id)}/fail`, reason ? { reason } : {}),
},
// ---- Dunning ----
dunning: {
list: (due?: boolean) => getList<DunningState>(due ? "/v1/dunning?due=true" : "/v1/dunning"),
start: (subscriptionId: string) => post<DunningState>("/v1/dunning", { subscriptionId }),
attempt: (subscriptionId: string, outcome: "recovered" | "failed", failureReason?: string) =>
post<DunningState>(`/v1/dunning/${encodeURIComponent(subscriptionId)}/attempt`, {
outcome,
...(failureReason ? { failureReason } : {}),
}),
recover: (subscriptionId: string) =>
post<DunningState>(`/v1/dunning/${encodeURIComponent(subscriptionId)}/recover`, {}),
},
// ---- Disputes ----
disputes: {
list: (status?: string) =>
getList<Dispute>(status ? `/v1/disputes?status=${encodeURIComponent(status)}` : "/v1/disputes"),
get: (id: string) => getItem<Dispute>(`/v1/disputes/${encodeURIComponent(id)}`),
open: (input: { paymentId: string; customerId: string; reason: DisputeReason }) =>
post<Dispute>("/v1/disputes", input),
evidence: (
id: string,
input: {
kind: "text" | "receipt" | "shipping" | "communication" | "url" | "file";
description: string;
value: string;
},
) => post<Dispute>(`/v1/disputes/${encodeURIComponent(id)}/evidence`, input),
resolve: (id: string, outcome: "won" | "lost" | "refunded") =>
post<Dispute>(`/v1/disputes/${encodeURIComponent(id)}/resolve`, { outcome }),
},
// ---- Payouts ----
payouts: {
list: (organizationId?: string) =>
getList<Payout>(
organizationId ? `/v1/payouts?organizationId=${encodeURIComponent(organizationId)}` : "/v1/payouts",
),
// Tenant-scoped via the session; returns the full take-rate breakdown.
async balance(): Promise<PayoutBalance | null> {
const { data } = await getItem<PayoutBalance>("/v1/payouts/balance");
return data;
},
create: (input: {
organizationId: string;
walletAddress: string;
amount: string;
network: "arc" | "base" | "ethereum";
}) => post<Payout>("/v1/payouts", input),
paid: (id: string, txHash: string) =>
post<Payout>(`/v1/payouts/${encodeURIComponent(id)}/paid`, { txHash }),
fail: (id: string, reason?: string) =>
post<Payout>(`/v1/payouts/${encodeURIComponent(id)}/fail`, reason ? { reason } : {}),
},
// ---- GitHub ----
github: {
installations: () =>
getList<GithubInstallation>("/v1/integrations/github/installations"),
repositories: () =>
getList<GithubRepository>("/v1/integrations/github/repositories"),
teams: () => getList<GithubTeam>("/v1/integrations/github/teams"),
access: () => getList<GithubAccessGrant>("/v1/github/access"),
grant: (customerEmail: string, target: string, kind: "repo" | "team") =>
post<GithubAccessGrant>("/v1/github/access/grant", {
customerEmail,
target,
kind,
}),
},
// ---- Discord ----
discord: {
servers: () => getList<DiscordServer>("/v1/integrations/discord/guilds"),
roles: () => getList<DiscordRole>("/v1/integrations/discord/roles"),
access: () => getList<DiscordAccessGrant>("/v1/discord/access"),
grant: (customerEmail: string, roleId: string) =>
post<DiscordAccessGrant>("/v1/discord/access/grant", {
customerEmail,
roleId,
}),
},
// ---- SaaS ----
saas: {
plans: () => getList<SaasPlan>("/v1/saas/plans"),
features: () => getList<SaasFeature>("/v1/saas/features"),
seats: () => getList<Seat>("/v1/saas/seats"),
entitlements: () => getList<Entitlement>("/v1/saas/entitlements"),
createPlan: (name: string, amount: number, interval: "monthly" | "yearly") =>
post<SaasPlan>("/v1/saas/plans", { name, amount, interval }),
},
// ---- Bundles ----
bundles: {
list: () => getList<Bundle>("/v1/bundles"),
get: (id: string) => getItem<Bundle>(`/v1/bundles/${id}`),
create: (name: string, productIds: string[], amount: number) =>
post<Bundle>("/v1/bundles", { name, productIds, amount }),
},
// ---- Coupons ----
coupons: {
list: () => getList<Coupon>("/v1/coupons"),
get: (code: string) => getItem<Coupon>(`/v1/coupons/${encodeURIComponent(code)}`),
create: (input: {
code: string;
name?: string;
// The API encodes a fixed `amount` discount's amountOff as a decimal string.
discount: CreateCouponDiscount;
maxRedemptions?: number;
perCustomerLimit?: number;
expiresAt?: string;
}) => post<Coupon>("/v1/coupons", input),
},
// ---- Invoices ----
invoices: {
list: (customerId?: string) =>
getList<Invoice>(
customerId ? `/v1/invoices?customerId=${encodeURIComponent(customerId)}` : "/v1/invoices",
),
get: (id: string) => getItem<Invoice>(`/v1/invoices/${id}`),
htmlUrl: (id: string) => `${API_URL}/v1/invoices/${id}.html`,
create: (input: {
organizationId: string;
customerId: string;
lineItems?: { description: string; quantity: number; unitAmount: string }[];
}) => post<Invoice>("/v1/invoices", input),
/** Issue + email the pay link (idempotent: the link stays the same). */
send: (id: string, payerEmail?: string) =>
post<SentInvoice>(`/v1/invoices/${encodeURIComponent(id)}/send`, payerEmail ? { payerEmail } : {}),
/** Ad-hoc payment request: amount + memo, sent to an email. */
request: (input: { amount: string; description: string; payerEmail: string; dueAt?: string }) =>
post<SentInvoice>("/v1/invoices/requests", input),
},
// ---- Delivery ----
delivery: {
runs: () => getList<DeliveryRun>("/v1/delivery-runs"),
logs: () => getList<DeliveryLog>("/v1/delivery-runs/logs"),
retry: (id: string) => post<DeliveryRun>(`/v1/delivery-runs/${id}/retry`, {}),
},
// ---- Agent services ----
agentServices: {
list: () => getList<AgentService>("/v1/agent-services"),
get: (id: string) => getItem<AgentService>(`/v1/agent-services/${id}`),
create: (name: string, description: string, pricePerCall: number) =>
post<AgentService>("/v1/agent-services", {
name,
description,
pricePerCall,
}),
},
// ---- Escrow ----
escrow: {
tasks: () => getList<EscrowTask>("/v1/escrow/tasks"),
get: (id: string) => getItem<EscrowTask>(`/v1/escrow/tasks/${id}`),
create: (title: string, buyerEmail: string, amount: number) =>
post<EscrowTask>("/v1/escrow/tasks", { title, buyerEmail, amount }),
assign: (id: string, workerCustomerId: string) =>
post<EscrowTask>(`/v1/escrow/tasks/${id}/assign`, { workerCustomerId }),
fund: (id: string, fundingTxHash: string) =>
post<EscrowTask>(`/v1/escrow/tasks/${id}/fund`, { fundingTxHash }),
submit: (id: string, content: string) =>
post<EscrowTask>(`/v1/escrow/tasks/${id}/submit`, { content }),
approve: (id: string) => post<EscrowTask>(`/v1/escrow/tasks/${id}/approve`, {}),
release: (id: string, releaseTxHash: string) =>
post<EscrowTask>(`/v1/escrow/tasks/${id}/release`, { releaseTxHash }),
refund: (id: string, reason: string) =>
post<EscrowTask>(`/v1/escrow/tasks/${id}/refund`, { reason }),
},
// ---- Usage-based billing ----
usage: {
record: (input: {
organizationId: string;
customerId: string;
productId: string;
metric: string;
quantity: number;
}) => post<UsageMeter>("/v1/usage/record", input),
grantCredits: (input: {
organizationId: string;
customerId: string;
productId: string;
credits: number;
}) => post<CreditBalance>("/v1/usage/credits/grant", input),
consumeCredits: (input: {
organizationId: string;
customerId: string;
productId: string;
credits: number;
}) => post<CreditBalance>("/v1/usage/credits/consume", input),
credits: (organizationId: string, customerId: string, productId: string) =>
getItem<CreditBalance>(
`/v1/usage/credits?organizationId=${encodeURIComponent(organizationId)}&customerId=${encodeURIComponent(customerId)}&productId=${encodeURIComponent(productId)}`,
),
},
// ---- Marketplace ----
marketplace: {
listings: () => getList<MarketplaceListing>("/v1/marketplace/listings"),
create: (input: {
organizationId: string;
merchantId: string;
productId: string;
title: string;
summary: string;
tags: string[];
}) => post<MarketplaceListing>("/v1/marketplace/listings", input),
publish: (id: string) =>
post<MarketplaceListing>(`/v1/marketplace/listings/${encodeURIComponent(id)}/publish`, {}),
},
// ---- Settings ----
settings: {
async get(): Promise<OrgSettings> {
const { data } = await getItem<OrgSettings>("/v1/settings");
return (
data ?? {
orgName: "SettleKit Merchant",
supportEmail: "",
payoutCurrency: "USDC",
webhookSecret: "",
defaultRail: "circle",
}
);
},
update: (input: Partial<OrgSettings>) =>
post<OrgSettings>("/v1/settings", input),
},
};