Refactor API code and simplify billing display
The code in the webhook API has been refactored to move the DatabaseWebhookHandlerService instance out of the POST function scope. Furthermore, the display of renewal plan details on the billing page has been simplified and certain parts deemed superfluous have been removed. Numerous types and interfaces in the database.types.ts file have also been corrected and formatted for consistency and improved readability.
This commit is contained in:
@@ -20,7 +20,7 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzd
|
|||||||
NEXT_PUBLIC_REQUIRE_EMAIL_CONFIRMATION=true
|
NEXT_PUBLIC_REQUIRE_EMAIL_CONFIRMATION=true
|
||||||
|
|
||||||
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
## THIS IS FOR DEVELOPMENT ONLY - DO NOT USE IN PRODUCTION
|
||||||
SUPABASE_WEBHOOK_SECRET=WEBHOOKSECRET
|
SUPABASE_DB_WEBHOOK_SECRET=WEBHOOKSECRET
|
||||||
|
|
||||||
EMAIL_SENDER=test@makerkit.dev
|
EMAIL_SENDER=test@makerkit.dev
|
||||||
EMAIL_PORT=54325
|
EMAIL_PORT=54325
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ const webhooksSecret = z
|
|||||||
.min(1)
|
.min(1)
|
||||||
.parse(process.env.SUPABASE_DB_WEBHOOK_SECRET);
|
.parse(process.env.SUPABASE_DB_WEBHOOK_SECRET);
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
const service = new DatabaseWebhookHandlerService();
|
||||||
const service = new DatabaseWebhookHandlerService();
|
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
await service.handleWebhook(request, webhooksSecret);
|
await service.handleWebhook(request, webhooksSecret);
|
||||||
|
|
||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
|
|||||||
@@ -34,8 +34,7 @@ export function CurrentPlanCard({
|
|||||||
subscription: Database['public']['Tables']['subscriptions']['Row'];
|
subscription: Database['public']['Tables']['subscriptions']['Row'];
|
||||||
config: BillingConfig;
|
config: BillingConfig;
|
||||||
}>) {
|
}>) {
|
||||||
const { plan, product } = getProductPlanPair(config, subscription.variant_id);
|
const { plan, product } = getProductPlanPair(config, subscription);
|
||||||
const baseLineItem = getBaseLineItem(config, plan.id);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
@@ -61,16 +60,6 @@ export function CurrentPlanCard({
|
|||||||
<span>{product.name}</span>
|
<span>{product.name}</span>
|
||||||
<CurrentPlanBadge status={subscription.status} />
|
<CurrentPlanBadge status={subscription.status} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={'text-muted-foreground'}>
|
|
||||||
<Trans
|
|
||||||
i18nKey="billing:planRenewal"
|
|
||||||
values={{
|
|
||||||
interval: subscription.interval,
|
|
||||||
price: formatCurrency(product.currency, baseLineItem.cost),
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -53,19 +53,21 @@ export class BillingEventHandlerService {
|
|||||||
|
|
||||||
const ctx = {
|
const ctx = {
|
||||||
namespace: 'billing',
|
namespace: 'billing',
|
||||||
subscriptionId: subscription.id,
|
subscriptionId: subscription.subscription_id,
|
||||||
provider: subscription.billing_provider,
|
provider: subscription.billing_provider,
|
||||||
accountId: subscription.account_id,
|
accountId: subscription.account_id,
|
||||||
|
customerId: subscription.customer_id,
|
||||||
};
|
};
|
||||||
|
|
||||||
Logger.info(ctx, 'Processing subscription updated event');
|
Logger.info(ctx, 'Processing subscription updated event');
|
||||||
|
|
||||||
// Handle the subscription updated event
|
// Handle the subscription updated event
|
||||||
// here we update the subscription in the database
|
// here we update the subscription in the database
|
||||||
const { error } = await client
|
const { error } = await client.rpc('upsert_subscription', {
|
||||||
.from('subscriptions')
|
...subscription,
|
||||||
.update(subscription)
|
customer_id: subscription.customer_id,
|
||||||
.match({ id: subscription.id });
|
account_id: subscription.account_id,
|
||||||
|
});
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
Logger.error(
|
Logger.error(
|
||||||
@@ -88,24 +90,16 @@ export class BillingEventHandlerService {
|
|||||||
|
|
||||||
const ctx = {
|
const ctx = {
|
||||||
namespace: 'billing',
|
namespace: 'billing',
|
||||||
subscriptionId: subscription.id,
|
subscriptionId: subscription.subscription_id,
|
||||||
provider: subscription.billing_provider,
|
provider: subscription.billing_provider,
|
||||||
accountId: subscription.account_id,
|
accountId: subscription.account_id,
|
||||||
};
|
};
|
||||||
|
|
||||||
Logger.info(ctx, 'Processing checkout session completed event...');
|
Logger.info(ctx, 'Processing checkout session completed event...');
|
||||||
|
|
||||||
const { id: _, ...data } = subscription;
|
const { error } = await client.rpc('upsert_subscription', {
|
||||||
|
...subscription,
|
||||||
const { error } = await client.rpc('add_subscription', {
|
|
||||||
...data,
|
|
||||||
subscription_id: subscription.id,
|
|
||||||
customer_id: customerId,
|
customer_id: customerId,
|
||||||
price_amount: subscription.price_amount ?? 0,
|
|
||||||
period_starts_at: subscription.period_starts_at!,
|
|
||||||
period_ends_at: subscription.period_ends_at!,
|
|
||||||
trial_starts_at: subscription.trial_starts_at!,
|
|
||||||
trial_ends_at: subscription.trial_ends_at!,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { Database } from '@kit/supabase/database';
|
import { Database } from '@kit/supabase/database';
|
||||||
|
|
||||||
type SubscriptionObject = Database['public']['Tables']['subscriptions'];
|
type UpsertSubscriptionParams =
|
||||||
|
Database['public']['Functions']['upsert_subscription']['Args'];
|
||||||
type SubscriptionUpdateParams = SubscriptionObject['Update'];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an abstract class for handling billing webhook events.
|
* Represents an abstract class for handling billing webhook events.
|
||||||
@@ -14,12 +13,13 @@ export abstract class BillingWebhookHandlerService {
|
|||||||
event: unknown,
|
event: unknown,
|
||||||
params: {
|
params: {
|
||||||
onCheckoutSessionCompleted: (
|
onCheckoutSessionCompleted: (
|
||||||
subscription: SubscriptionObject['Row'],
|
subscription: UpsertSubscriptionParams,
|
||||||
customerId: string,
|
customerId: string,
|
||||||
) => Promise<unknown>;
|
) => Promise<unknown>;
|
||||||
|
|
||||||
onSubscriptionUpdated: (
|
onSubscriptionUpdated: (
|
||||||
subscription: SubscriptionUpdateParams,
|
subscription: UpsertSubscriptionParams,
|
||||||
|
customerId: string,
|
||||||
) => Promise<unknown>;
|
) => Promise<unknown>;
|
||||||
|
|
||||||
onSubscriptionDeleted: (subscriptionId: string) => Promise<unknown>;
|
onSubscriptionDeleted: (subscriptionId: string) => Promise<unknown>;
|
||||||
|
|||||||
@@ -10,9 +10,14 @@ export class DatabaseWebhookHandlerService {
|
|||||||
private readonly namespace = 'database-webhook-handler';
|
private readonly namespace = 'database-webhook-handler';
|
||||||
|
|
||||||
async handleWebhook(request: Request, webhooksSecret: string) {
|
async handleWebhook(request: Request, webhooksSecret: string) {
|
||||||
|
const json = await request.clone().json();
|
||||||
|
const { table, type } = json as RecordChange<keyof Tables>;
|
||||||
|
|
||||||
Logger.info(
|
Logger.info(
|
||||||
{
|
{
|
||||||
name: this.namespace,
|
name: this.namespace,
|
||||||
|
table,
|
||||||
|
type,
|
||||||
},
|
},
|
||||||
'Received webhook from DB. Processing...',
|
'Received webhook from DB. Processing...',
|
||||||
);
|
);
|
||||||
@@ -21,11 +26,17 @@ export class DatabaseWebhookHandlerService {
|
|||||||
this.assertSignatureIsAuthentic(request, webhooksSecret);
|
this.assertSignatureIsAuthentic(request, webhooksSecret);
|
||||||
|
|
||||||
// all good, handle the webhook
|
// all good, handle the webhook
|
||||||
const json = await request.json();
|
|
||||||
|
|
||||||
await this.handleWebhookBody(json);
|
// create a client with admin access since we are handling webhooks
|
||||||
|
// and no user is authenticated
|
||||||
|
const client = getSupabaseRouteHandlerClient({
|
||||||
|
admin: true,
|
||||||
|
});
|
||||||
|
|
||||||
const { table, type } = json as RecordChange<keyof Tables>;
|
// handle the webhook
|
||||||
|
const service = new DatabaseWebhookRouterService(client);
|
||||||
|
|
||||||
|
await service.handleWebhook(json);
|
||||||
|
|
||||||
Logger.info(
|
Logger.info(
|
||||||
{
|
{
|
||||||
@@ -37,16 +48,6 @@ export class DatabaseWebhookHandlerService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleWebhookBody(body: RecordChange<keyof Tables>) {
|
|
||||||
const client = getSupabaseRouteHandlerClient({
|
|
||||||
admin: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new DatabaseWebhookRouterService(client);
|
|
||||||
|
|
||||||
return service.handleWebhook(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
private assertSignatureIsAuthentic(request: Request, webhooksSecret: string) {
|
private assertSignatureIsAuthentic(request: Request, webhooksSecret: string) {
|
||||||
const header = request.headers.get('X-Supabase-Event-Signature');
|
const header = request.headers.get('X-Supabase-Event-Signature');
|
||||||
|
|
||||||
|
|||||||
@@ -7,12 +7,8 @@ import { Database } from '@kit/supabase/database';
|
|||||||
import { StripeServerEnvSchema } from '../schema/stripe-server-env.schema';
|
import { StripeServerEnvSchema } from '../schema/stripe-server-env.schema';
|
||||||
import { createStripeClient } from './stripe-sdk';
|
import { createStripeClient } from './stripe-sdk';
|
||||||
|
|
||||||
type Subscription = Database['public']['Tables']['subscriptions'];
|
type UpsertSubscriptionParams =
|
||||||
|
Database['public']['Functions']['upsert_subscription']['Args'];
|
||||||
type InsertSubscriptionParams = Omit<
|
|
||||||
Subscription['Insert'],
|
|
||||||
'billing_customer_id'
|
|
||||||
>;
|
|
||||||
|
|
||||||
export class StripeWebhookHandlerService
|
export class StripeWebhookHandlerService
|
||||||
implements BillingWebhookHandlerService
|
implements BillingWebhookHandlerService
|
||||||
@@ -64,11 +60,12 @@ export class StripeWebhookHandlerService
|
|||||||
event: Stripe.Event,
|
event: Stripe.Event,
|
||||||
params: {
|
params: {
|
||||||
onCheckoutSessionCompleted: (
|
onCheckoutSessionCompleted: (
|
||||||
data: InsertSubscriptionParams,
|
data: UpsertSubscriptionParams,
|
||||||
customerId: string,
|
|
||||||
) => Promise<unknown>;
|
) => Promise<unknown>;
|
||||||
|
|
||||||
onSubscriptionUpdated: (data: Subscription['Update']) => Promise<unknown>;
|
onSubscriptionUpdated: (
|
||||||
|
data: UpsertSubscriptionParams,
|
||||||
|
) => Promise<unknown>;
|
||||||
onSubscriptionDeleted: (subscriptionId: string) => Promise<unknown>;
|
onSubscriptionDeleted: (subscriptionId: string) => Promise<unknown>;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
@@ -111,8 +108,7 @@ export class StripeWebhookHandlerService
|
|||||||
private async handleCheckoutSessionCompleted(
|
private async handleCheckoutSessionCompleted(
|
||||||
event: Stripe.CheckoutSessionCompletedEvent,
|
event: Stripe.CheckoutSessionCompletedEvent,
|
||||||
onCheckoutCompletedCallback: (
|
onCheckoutCompletedCallback: (
|
||||||
data: Omit<Subscription['Insert'], 'billing_customer_id'>,
|
data: UpsertSubscriptionParams,
|
||||||
customerId: string,
|
|
||||||
) => Promise<unknown>,
|
) => Promise<unknown>,
|
||||||
) {
|
) {
|
||||||
const stripe = await this.loadStripe();
|
const stripe = await this.loadStripe();
|
||||||
@@ -134,20 +130,23 @@ export class StripeWebhookHandlerService
|
|||||||
|
|
||||||
const payload = this.buildSubscriptionPayload({
|
const payload = this.buildSubscriptionPayload({
|
||||||
subscription,
|
subscription,
|
||||||
accountId,
|
|
||||||
amount,
|
amount,
|
||||||
}) as InsertSubscriptionParams;
|
accountId,
|
||||||
|
customerId,
|
||||||
|
});
|
||||||
|
|
||||||
return onCheckoutCompletedCallback(payload, customerId);
|
return onCheckoutCompletedCallback(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleSubscriptionUpdatedEvent(
|
private async handleSubscriptionUpdatedEvent(
|
||||||
event: Stripe.CustomerSubscriptionUpdatedEvent,
|
event: Stripe.CustomerSubscriptionUpdatedEvent,
|
||||||
onSubscriptionUpdatedCallback: (
|
onSubscriptionUpdatedCallback: (
|
||||||
data: Subscription['Update'],
|
data: UpsertSubscriptionParams,
|
||||||
) => Promise<unknown>,
|
) => Promise<unknown>,
|
||||||
) {
|
) {
|
||||||
const subscription = event.data.object;
|
const subscription = event.data.object;
|
||||||
|
const accountId = subscription.metadata.account_id as string;
|
||||||
|
const customerId = subscription.customer as string;
|
||||||
|
|
||||||
const amount = subscription.items.data.reduce((acc, item) => {
|
const amount = subscription.items.data.reduce((acc, item) => {
|
||||||
return (acc + (item.plan.amount ?? 0)) * (item.quantity ?? 1);
|
return (acc + (item.plan.amount ?? 0)) * (item.quantity ?? 1);
|
||||||
@@ -156,6 +155,8 @@ export class StripeWebhookHandlerService
|
|||||||
const payload = this.buildSubscriptionPayload({
|
const payload = this.buildSubscriptionPayload({
|
||||||
subscription,
|
subscription,
|
||||||
amount,
|
amount,
|
||||||
|
accountId,
|
||||||
|
customerId,
|
||||||
});
|
});
|
||||||
|
|
||||||
return onSubscriptionUpdatedCallback(payload);
|
return onSubscriptionUpdatedCallback(payload);
|
||||||
@@ -173,52 +174,53 @@ export class StripeWebhookHandlerService
|
|||||||
private buildSubscriptionPayload(params: {
|
private buildSubscriptionPayload(params: {
|
||||||
subscription: Stripe.Subscription;
|
subscription: Stripe.Subscription;
|
||||||
amount: number;
|
amount: number;
|
||||||
// we only need the account id if we
|
accountId: string;
|
||||||
// are creating a subscription for an account
|
customerId: string;
|
||||||
accountId?: string;
|
}): UpsertSubscriptionParams {
|
||||||
}) {
|
|
||||||
const { subscription } = params;
|
const { subscription } = params;
|
||||||
const lineItem = subscription.items.data[0];
|
const currency = subscription.currency;
|
||||||
const price = lineItem?.price;
|
|
||||||
const priceId = price?.id as string;
|
|
||||||
const interval = price?.recurring?.interval ?? null;
|
|
||||||
|
|
||||||
const active =
|
const active =
|
||||||
subscription.status === 'active' || subscription.status === 'trialing';
|
subscription.status === 'active' || subscription.status === 'trialing';
|
||||||
|
|
||||||
const data = {
|
const lineItems = subscription.items.data.map((item) => {
|
||||||
billing_provider: this.provider,
|
const quantity = item.quantity ?? 1;
|
||||||
id: subscription.id,
|
|
||||||
status: subscription.status,
|
|
||||||
active,
|
|
||||||
price_amount: params.amount,
|
|
||||||
cancel_at_period_end: subscription.cancel_at_period_end ?? false,
|
|
||||||
interval: interval as string,
|
|
||||||
currency: (price as Stripe.Price).currency,
|
|
||||||
product_id: (price as Stripe.Price).product as string,
|
|
||||||
variant_id: priceId,
|
|
||||||
interval_count: price?.recurring?.interval_count ?? 1,
|
|
||||||
period_starts_at: getISOString(subscription.current_period_start),
|
|
||||||
period_ends_at: getISOString(subscription.current_period_end),
|
|
||||||
trial_starts_at: getISOString(subscription.trial_start),
|
|
||||||
trial_ends_at: getISOString(subscription.trial_end),
|
|
||||||
} satisfies Omit<InsertSubscriptionParams, 'account_id'>;
|
|
||||||
|
|
||||||
// when we are creating a subscription for an account
|
|
||||||
// we need to include the account id
|
|
||||||
if (params.accountId !== undefined) {
|
|
||||||
return {
|
return {
|
||||||
...data,
|
id: item.id,
|
||||||
account_id: params.accountId,
|
subscription_id: subscription.id,
|
||||||
|
product_id: item.price.product as string,
|
||||||
|
variant_id: item.price.id,
|
||||||
|
price_amount: item.price.unit_amount,
|
||||||
|
quantity,
|
||||||
|
interval: item.price.recurring?.interval as string,
|
||||||
|
interval_count: item.price.recurring?.interval_count as number,
|
||||||
};
|
};
|
||||||
}
|
});
|
||||||
|
|
||||||
// otherwise we are updating a subscription
|
// otherwise we are updating a subscription
|
||||||
// and we only need to return the update payload
|
// and we only need to return the update payload
|
||||||
return data;
|
return {
|
||||||
|
line_items: lineItems,
|
||||||
|
billing_provider: this.provider,
|
||||||
|
subscription_id: subscription.id,
|
||||||
|
status: subscription.status,
|
||||||
|
total_amount: params.amount,
|
||||||
|
active,
|
||||||
|
currency,
|
||||||
|
cancel_at_period_end: subscription.cancel_at_period_end ?? false,
|
||||||
|
period_starts_at: getISOString(
|
||||||
|
subscription.current_period_start,
|
||||||
|
) as string,
|
||||||
|
period_ends_at: getISOString(subscription.current_period_end) as string,
|
||||||
|
trial_starts_at: getISOString(subscription.trial_start),
|
||||||
|
trial_ends_at: getISOString(subscription.trial_end),
|
||||||
|
account_id: params.accountId,
|
||||||
|
customer_id: params.customerId,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getISOString(date: number | null) {
|
function getISOString(date: number | null) {
|
||||||
return date ? new Date(date * 1000).toISOString() : null;
|
return date ? new Date(date * 1000).toISOString() : undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -118,6 +118,16 @@ create type public.subscription_status as ENUM(
|
|||||||
'paused'
|
'paused'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/* Subscription Type
|
||||||
|
- We create the subscription type for the Supabase MakerKit. These types are used to manage the type of the subscriptions
|
||||||
|
- The types are 'ONE_OFF' and 'RECURRING'.
|
||||||
|
- You can add more types as needed.
|
||||||
|
*/
|
||||||
|
create type public.subscription_type as enum (
|
||||||
|
'one-off',
|
||||||
|
'recurring'
|
||||||
|
);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Billing Provider
|
* Billing Provider
|
||||||
- We create the billing provider for the Supabase MakerKit. These providers are used to manage the billing provider for the accounts and organizations
|
- We create the billing provider for the Supabase MakerKit. These providers are used to manage the billing provider for the accounts and organizations
|
||||||
@@ -944,28 +954,24 @@ select
|
|||||||
* -------------------------------------------------------
|
* -------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
-- Subscriptions table
|
-- Subscriptions table
|
||||||
create table if not exists
|
create table if not exists public.subscriptions (
|
||||||
public.subscriptions (
|
id text not null primary key,
|
||||||
account_id uuid references public.accounts (id) on delete cascade not null,
|
account_id uuid references public.accounts (id) on delete cascade not null,
|
||||||
billing_customer_id int references public.billing_customers on delete cascade not null,
|
billing_customer_id int references public.billing_customers on delete cascade not null,
|
||||||
id text not null primary key,
|
status public.subscription_status not null,
|
||||||
status public.subscription_status not null,
|
type public.subscription_type not null default 'recurring',
|
||||||
active bool not null,
|
total_amount numeric not null,
|
||||||
billing_provider public.billing_provider not null,
|
active bool not null,
|
||||||
product_id varchar(255) not null,
|
billing_provider public.billing_provider not null,
|
||||||
variant_id varchar(255) not null,
|
cancel_at_period_end bool not null,
|
||||||
price_amount numeric,
|
currency varchar(3) not null,
|
||||||
cancel_at_period_end bool not null,
|
created_at timestamptz not null default current_timestamp,
|
||||||
currency varchar(3) not null,
|
updated_at timestamptz not null default current_timestamp,
|
||||||
interval varchar(255) not null,
|
period_starts_at timestamptz not null,
|
||||||
interval_count integer not null check (interval_count > 0),
|
period_ends_at timestamptz not null,
|
||||||
created_at timestamptz not null default current_timestamp,
|
trial_starts_at timestamptz,
|
||||||
updated_at timestamptz not null default current_timestamp,
|
trial_ends_at timestamptz
|
||||||
period_starts_at timestamptz,
|
);
|
||||||
period_ends_at timestamptz,
|
|
||||||
trial_starts_at timestamptz,
|
|
||||||
trial_ends_at timestamptz
|
|
||||||
);
|
|
||||||
|
|
||||||
comment on table public.subscriptions is 'The subscriptions for an account';
|
comment on table public.subscriptions is 'The subscriptions for an account';
|
||||||
|
|
||||||
@@ -973,22 +979,16 @@ comment on column public.subscriptions.account_id is 'The account the subscripti
|
|||||||
|
|
||||||
comment on column public.subscriptions.billing_provider is 'The provider of the subscription';
|
comment on column public.subscriptions.billing_provider is 'The provider of the subscription';
|
||||||
|
|
||||||
comment on column public.subscriptions.product_id is 'The product ID for the subscription';
|
comment on column public.subscriptions.total_amount is 'The total price amount for the subscription';
|
||||||
|
|
||||||
comment on column public.subscriptions.variant_id is 'The variant ID for the subscription';
|
|
||||||
|
|
||||||
comment on column public.subscriptions.price_amount is 'The price amount for the subscription';
|
|
||||||
|
|
||||||
comment on column public.subscriptions.cancel_at_period_end is 'Whether the subscription will be canceled at the end of the period';
|
comment on column public.subscriptions.cancel_at_period_end is 'Whether the subscription will be canceled at the end of the period';
|
||||||
|
|
||||||
comment on column public.subscriptions.currency is 'The currency for the subscription';
|
comment on column public.subscriptions.currency is 'The currency for the subscription';
|
||||||
|
|
||||||
comment on column public.subscriptions.interval is 'The interval for the subscription';
|
|
||||||
|
|
||||||
comment on column public.subscriptions.interval_count is 'The interval count for the subscription';
|
|
||||||
|
|
||||||
comment on column public.subscriptions.status is 'The status of the subscription';
|
comment on column public.subscriptions.status is 'The status of the subscription';
|
||||||
|
|
||||||
|
comment on column public.subscriptions.type is 'The type of the subscription, either one-off or recurring';
|
||||||
|
|
||||||
comment on column public.subscriptions.period_starts_at is 'The start of the current period for the subscription';
|
comment on column public.subscriptions.period_starts_at is 'The start of the current period for the subscription';
|
||||||
|
|
||||||
comment on column public.subscriptions.period_ends_at is 'The end of the current period for the subscription';
|
comment on column public.subscriptions.period_ends_at is 'The end of the current period for the subscription';
|
||||||
@@ -1017,103 +1017,177 @@ select
|
|||||||
to authenticated using (has_role_on_account (account_id) or account_id = auth.uid ());
|
to authenticated using (has_role_on_account (account_id) or account_id = auth.uid ());
|
||||||
|
|
||||||
-- Functions
|
-- Functions
|
||||||
|
create or replace function public.upsert_subscription (
|
||||||
create or replace function public.add_subscription (
|
|
||||||
account_id uuid,
|
account_id uuid,
|
||||||
subscription_id text,
|
subscription_id text,
|
||||||
active bool,
|
active bool,
|
||||||
|
total_amount numeric,
|
||||||
status public.subscription_status,
|
status public.subscription_status,
|
||||||
billing_provider public.billing_provider,
|
billing_provider public.billing_provider,
|
||||||
product_id varchar(255),
|
|
||||||
variant_id varchar(255),
|
|
||||||
price_amount numeric,
|
|
||||||
cancel_at_period_end bool,
|
cancel_at_period_end bool,
|
||||||
currency varchar(3),
|
currency varchar(3),
|
||||||
"interval" varchar(255),
|
|
||||||
interval_count integer,
|
|
||||||
period_starts_at timestamptz,
|
period_starts_at timestamptz,
|
||||||
period_ends_at timestamptz,
|
period_ends_at timestamptz,
|
||||||
trial_starts_at timestamptz,
|
customer_id varchar(255),
|
||||||
trial_ends_at timestamptz,
|
line_items jsonb,
|
||||||
customer_id varchar(255)
|
trial_starts_at timestamptz default null,
|
||||||
|
trial_ends_at timestamptz default null,
|
||||||
|
type public.subscription_type default 'recurring'
|
||||||
) returns public.subscriptions as $$
|
) returns public.subscriptions as $$
|
||||||
declare
|
declare
|
||||||
new_subscription public.subscriptions;
|
new_subscription public.subscriptions;
|
||||||
new_billing_customer_id int;
|
new_billing_customer_id int;
|
||||||
begin
|
begin
|
||||||
insert into public.billing_customers(
|
insert into public.billing_customers(account_id, provider, customer_id)
|
||||||
account_id,
|
values (account_id, billing_provider, customer_id)
|
||||||
provider,
|
on conflict (account_id, provider, customer_id) do update
|
||||||
customer_id)
|
set provider = excluded.provider
|
||||||
values (
|
returning id into new_billing_customer_id;
|
||||||
account_id,
|
|
||||||
billing_provider,
|
|
||||||
customer_id)
|
|
||||||
returning
|
|
||||||
id into new_billing_customer_id;
|
|
||||||
|
|
||||||
insert into public.subscriptions(
|
insert into public.subscriptions(
|
||||||
account_id,
|
account_id,
|
||||||
billing_customer_id,
|
billing_customer_id,
|
||||||
id,
|
id,
|
||||||
active,
|
active,
|
||||||
status,
|
total_amount,
|
||||||
billing_provider,
|
status,
|
||||||
product_id,
|
type,
|
||||||
variant_id,
|
billing_provider,
|
||||||
price_amount,
|
cancel_at_period_end,
|
||||||
cancel_at_period_end,
|
currency,
|
||||||
currency,
|
period_starts_at,
|
||||||
interval,
|
period_ends_at,
|
||||||
interval_count,
|
trial_starts_at,
|
||||||
period_starts_at,
|
trial_ends_at)
|
||||||
period_ends_at,
|
values (
|
||||||
trial_starts_at,
|
account_id,
|
||||||
trial_ends_at)
|
new_billing_customer_id,
|
||||||
values (
|
subscription_id,
|
||||||
account_id,
|
active,
|
||||||
new_billing_customer_id,
|
total_amount,
|
||||||
subscription_id,
|
status,
|
||||||
active,
|
type,
|
||||||
status,
|
billing_provider,
|
||||||
billing_provider,
|
cancel_at_period_end,
|
||||||
product_id,
|
currency,
|
||||||
variant_id,
|
period_starts_at,
|
||||||
price_amount,
|
period_ends_at,
|
||||||
cancel_at_period_end,
|
trial_starts_at,
|
||||||
currency,
|
trial_ends_at)
|
||||||
interval,
|
on conflict (id) do update
|
||||||
interval_count,
|
set active = excluded.active,
|
||||||
period_starts_at,
|
status = excluded.status,
|
||||||
period_ends_at,
|
cancel_at_period_end = excluded.cancel_at_period_end,
|
||||||
trial_starts_at,
|
currency = excluded.currency,
|
||||||
trial_ends_at)
|
period_starts_at = excluded.period_starts_at,
|
||||||
returning
|
period_ends_at = excluded.period_ends_at,
|
||||||
* into new_subscription;
|
trial_starts_at = excluded.trial_starts_at,
|
||||||
return new_subscription;
|
trial_ends_at = excluded.trial_ends_at
|
||||||
end;
|
returning * into new_subscription;
|
||||||
|
|
||||||
|
-- Upsert subscription items
|
||||||
|
with item_data as (
|
||||||
|
select
|
||||||
|
(line_item ->> 'product_id')::varchar as prod_id,
|
||||||
|
(line_item ->> 'variant_id')::varchar as var_id,
|
||||||
|
(line_item ->> 'price_amount')::numeric as price_amt,
|
||||||
|
(line_item ->> 'quantity')::integer as qty,
|
||||||
|
(line_item ->> 'interval')::varchar as intv,
|
||||||
|
(line_item ->> 'interval_count')::integer as intv_count
|
||||||
|
from jsonb_array_elements(line_items) as line_item
|
||||||
|
)
|
||||||
|
insert into public.subscription_items(
|
||||||
|
subscription_id,
|
||||||
|
product_id,
|
||||||
|
variant_id,
|
||||||
|
price_amount,
|
||||||
|
quantity,
|
||||||
|
interval,
|
||||||
|
interval_count)
|
||||||
|
select
|
||||||
|
subscription_id,
|
||||||
|
prod_id,
|
||||||
|
var_id,
|
||||||
|
price_amt,
|
||||||
|
qty,
|
||||||
|
intv,
|
||||||
|
intv_count
|
||||||
|
from item_data
|
||||||
|
on conflict (subscription_id, product_id, variant_id) do update
|
||||||
|
set price_amount = excluded.price_amount,
|
||||||
|
quantity = excluded.quantity,
|
||||||
|
interval = excluded.interval,
|
||||||
|
interval_count = excluded.interval_count;
|
||||||
|
|
||||||
|
return new_subscription;
|
||||||
|
end;
|
||||||
$$ language plpgsql;
|
$$ language plpgsql;
|
||||||
|
|
||||||
grant execute on function public.add_subscription (
|
grant execute on function public.upsert_subscription (
|
||||||
uuid,
|
uuid,
|
||||||
text,
|
text,
|
||||||
boolean,
|
bool,
|
||||||
public.subscription_status,
|
numeric,
|
||||||
public.billing_provider,
|
public.subscription_status,
|
||||||
varchar,
|
public.billing_provider,
|
||||||
varchar,
|
bool,
|
||||||
numeric,
|
varchar,
|
||||||
boolean,
|
timestamptz,
|
||||||
varchar,
|
timestamptz,
|
||||||
varchar,
|
varchar,
|
||||||
integer,
|
jsonb,
|
||||||
timestamptz,
|
timestamptz,
|
||||||
timestamptz,
|
timestamptz,
|
||||||
timestamptz,
|
public.subscription_type
|
||||||
timestamptz,
|
|
||||||
varchar
|
|
||||||
) to service_role;
|
) to service_role;
|
||||||
|
|
||||||
|
|
||||||
|
/* -------------------------------------------------------
|
||||||
|
* Section: Subscription Items
|
||||||
|
* We create the schema for the subscription items. Subscription items are the items in a subscription.
|
||||||
|
* For example, a subscription might have a subscription item with the product ID 'prod_123' and the variant ID 'var_123'.
|
||||||
|
* -------------------------------------------------------
|
||||||
|
*/
|
||||||
|
create table if not exists public.subscription_items (
|
||||||
|
id text not null primary key,
|
||||||
|
subscription_id text references public.subscriptions (id) on delete cascade not null,
|
||||||
|
product_id varchar(255) not null,
|
||||||
|
variant_id varchar(255) not null,
|
||||||
|
price_amount numeric,
|
||||||
|
quantity integer not null default 1,
|
||||||
|
interval varchar(255) not null,
|
||||||
|
interval_count integer not null check (interval_count > 0),
|
||||||
|
created_at timestamptz not null default current_timestamp,
|
||||||
|
updated_at timestamptz not null default current_timestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
comment on table public.subscription_items is 'The items in a subscription';
|
||||||
|
comment on column public.subscription_items.subscription_id is 'The subscription the item is for';
|
||||||
|
comment on column public.subscription_items.product_id is 'The product ID for the item';
|
||||||
|
comment on column public.subscription_items.variant_id is 'The variant ID for the item';
|
||||||
|
comment on column public.subscription_items.price_amount is 'The price amount for the item';
|
||||||
|
comment on column public.subscription_items.quantity is 'The quantity of the item';
|
||||||
|
comment on column public.subscription_items.interval is 'The interval for the item';
|
||||||
|
comment on column public.subscription_items.interval_count is 'The interval count for the item';
|
||||||
|
comment on column public.subscription_items.created_at is 'The creation date of the item';
|
||||||
|
comment on column public.subscription_items.updated_at is 'The last update date of the item';
|
||||||
|
|
||||||
|
-- Open up access to subscription_items table for authenticated users and service_role
|
||||||
|
grant select on table public.subscription_items to authenticated, service_role;
|
||||||
|
grant insert, update, delete on table public.subscription_items to service_role;
|
||||||
|
|
||||||
|
-- RLS
|
||||||
|
alter table public.subscription_items enable row level security;
|
||||||
|
|
||||||
|
-- SELECT: Users can read subscription items on a subscription they are a member of
|
||||||
|
create policy subscription_items_read_self on public.subscription_items for
|
||||||
|
select
|
||||||
|
to authenticated using (
|
||||||
|
exists (
|
||||||
|
select 1 from public.subscriptions where id = subscription_id and (account_id = auth.uid () or has_role_on_account (account_id))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* -------------------------------------------------------
|
* -------------------------------------------------------
|
||||||
* Section: Functions
|
* Section: Functions
|
||||||
|
|||||||
@@ -6,18 +6,18 @@
|
|||||||
create trigger "accounts_memberships_insert" after insert
|
create trigger "accounts_memberships_insert" after insert
|
||||||
on "public"."accounts_memberships" for each row
|
on "public"."accounts_memberships" for each row
|
||||||
execute function "supabase_functions"."http_request"(
|
execute function "supabase_functions"."http_request"(
|
||||||
'http://localhost:3000/api/database/webhook',
|
'http://host.docker.internal:3000/api/database/webhook',
|
||||||
'POST',
|
'POST',
|
||||||
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
||||||
'{}',
|
'{}',
|
||||||
'1000'
|
'1000'
|
||||||
);
|
);
|
||||||
|
|
||||||
-- this webhook will be triggered after every insert on the accounts_memberships table
|
-- this webhook will be triggered after every delete on the accounts_memberships table
|
||||||
create trigger "account_membership_delete" after insert
|
create trigger "account_membership_delete" after delete
|
||||||
on "public"."accounts_memberships" for each row
|
on "public"."accounts_memberships" for each row
|
||||||
execute function "supabase_functions"."http_request"(
|
execute function "supabase_functions"."http_request"(
|
||||||
'http://localhost:3000/api/database/webhook',
|
'http://host.docker.internal:3000/api/database/webhook',
|
||||||
'POST',
|
'POST',
|
||||||
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
||||||
'{}',
|
'{}',
|
||||||
@@ -29,7 +29,19 @@ execute function "supabase_functions"."http_request"(
|
|||||||
create trigger "account_delete" after delete
|
create trigger "account_delete" after delete
|
||||||
on "public"."subscriptions" for each row
|
on "public"."subscriptions" for each row
|
||||||
execute function "supabase_functions"."http_request"(
|
execute function "supabase_functions"."http_request"(
|
||||||
'http://localhost:3000/api/database/webhook',
|
'http://host.docker.internal:3000/api/database/webhook',
|
||||||
|
'POST',
|
||||||
|
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
||||||
|
'{}',
|
||||||
|
'1000'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- this webhook will be triggered after every insert on the invitations table
|
||||||
|
-- which should happen when a user invites someone to their account
|
||||||
|
create trigger "invitations_insert" after insert
|
||||||
|
on "public"."invitations" for each row
|
||||||
|
execute function "supabase_functions"."http_request"(
|
||||||
|
'http://host.docker.internal:3000/api/database/webhook',
|
||||||
'POST',
|
'POST',
|
||||||
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
'{"Content-Type":"application/json", "X-Supabase-Event-Signature":"WEBHOOKSECRET"}',
|
||||||
'{}',
|
'{}',
|
||||||
|
|||||||
Reference in New Issue
Block a user