189 lines · 7.0 KB
import { first, run } from "../db";
import { badRequest, forbidden } from "../errors";
import { publicUrl } from "../events/emit";
import type { BillingAccount } from "../metering/access";
import type { Viewer } from "~/lib/types";
import { billingNotConfigured, proPriceVerified, stripe, stripeEnabled, verifiedPacks } from "./config";
import type { TopupPack } from "./config";
import { env } from "cloudflare:workers";

export type CustomerRow = {
  account_id: string;
  stripe_customer_id: string;
  subscription_id: string | null;
  subscription_status: string | null;
  price_id: string | null;
  current_period_end: number | null;
  cancel_at_period_end: number;
  subscription_event_at: number;
};

/** Subscription states that keep the Pro plan. past_due keeps it while Stripe retries the card. */
export const ACTIVE_STATUSES = new Set(["active", "trialing", "past_due"]);

export async function customerFor(accountId: string): Promise<CustomerRow | null> {
  return first<CustomerRow>("SELECT * FROM billing_customers WHERE account_id = ?", accountId);
}

export async function accountForCustomer(customerId: string): Promise<string | null> {
  const row = await first<{ account_id: string }>(
    "SELECT account_id FROM billing_customers WHERE stripe_customer_id = ?",
    customerId,
  );
  return row?.account_id ?? null;
}

export async function linkCustomer(accountId: string, customerId: string): Promise<void> {
  await run(
    `INSERT INTO billing_customers (account_id, stripe_customer_id, updated_at) VALUES (?, ?, ?)
     ON CONFLICT DO NOTHING`,
    accountId,