Refactor code and improve usage of package dependencies

This commit updates the naming convention of icons from Lucide-React, moving some package dependencies to "peerDependencies" in 'team-accounts', 'admin' and 'auth'. Additionally, it includes tweaks to the development server command in apps/web package.json and adds a logger reference to the shared package. Furthermore, cleanup work has been performed within the features and UI packages, and new scripts to interact with Stripe have been added to the root package.json.
This commit is contained in:
giancarlo
2024-03-26 01:34:19 +08:00
parent 95793c42b4
commit ee507e0816
92 changed files with 1691 additions and 1270 deletions

View File

@@ -4,7 +4,6 @@ NEXT_PUBLIC_PRODUCT_NAME=Makerkit
# SUPABASE # SUPABASE
NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321 NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0 NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
NEXT_PUBLIC_REQUIRE_EMAIL_CONFIRMATION=true NEXT_PUBLIC_REQUIRE_EMAIL_CONFIRMATION=true
@@ -32,5 +31,5 @@ NEXT_PUBLIC_LOCALES_PATH=apps/web/public/locales
# Please make sure to update these in the app's paths configuration as well # Please make sure to update these in the app's paths configuration as well
SIGN_IN_PATH=/auth/sign-in SIGN_IN_PATH=/auth/sign-in
SIGN_UP_PATH=/auth/sign-up SIGN_UP_PATH=/auth/sign-up
ORGANIZATION_ACCOUNTS_PATH=/home TEAM_ACCOUNTS_HOME_PATH=/home
INVITATION_PAGE_PATH=/join INVITATION_PAGE_PATH=/join

View File

@@ -2,7 +2,10 @@
import { useState, useTransition } from 'react'; import { useState, useTransition } from 'react';
import { ExclamationTriangleIcon } from '@radix-ui/react-icons';
import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components'; import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components';
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import { import {
Card, Card,
CardContent, CardContent,
@@ -10,6 +13,7 @@ import {
CardHeader, CardHeader,
CardTitle, CardTitle,
} from '@kit/ui/card'; } from '@kit/ui/card';
import { If } from '@kit/ui/if';
import billingConfig from '~/config/billing.config'; import billingConfig from '~/config/billing.config';
@@ -17,7 +21,8 @@ import { createPersonalAccountCheckoutSession } from '../server-actions';
export function PersonalAccountCheckoutForm() { export function PersonalAccountCheckoutForm() {
const [pending, startTransition] = useTransition(); const [pending, startTransition] = useTransition();
const [checkoutToken, setCheckoutToken] = useState<string | null>(null); const [error, setError] = useState(false);
const [checkoutToken, setCheckoutToken] = useState<string>();
// If the checkout token is set, render the embedded checkout component // If the checkout token is set, render the embedded checkout component
if (checkoutToken) { if (checkoutToken) {
@@ -41,18 +46,26 @@ export function PersonalAccountCheckoutForm() {
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent className={'space-y-4'}>
<If condition={error}>
<ErrorAlert />
</If>
<PlanPicker <PlanPicker
pending={pending} pending={pending}
config={billingConfig} config={billingConfig}
onSubmit={({ planId }) => { onSubmit={({ planId }) => {
startTransition(async () => { startTransition(async () => {
try {
const { checkoutToken } = const { checkoutToken } =
await createPersonalAccountCheckoutSession({ await createPersonalAccountCheckoutSession({
planId, planId,
}); });
setCheckoutToken(checkoutToken); setCheckoutToken(checkoutToken);
} catch (e) {
setError(true);
}
}); });
}} }}
/> />
@@ -61,3 +74,17 @@ export function PersonalAccountCheckoutForm() {
</div> </div>
); );
} }
function ErrorAlert() {
return (
<Alert variant={'destructive'}>
<ExclamationTriangleIcon />
<AlertTitle>Sorry, we encountered an error.</AlertTitle>
<AlertDescription>
We couldn't process your request. Please try again.
</AlertDescription>
</Alert>
);
}

View File

@@ -1,10 +1,37 @@
import { redirect } from 'next/navigation';
import { SupabaseClient } from '@supabase/supabase-js';
import {
BillingPortalCard,
CurrentPlanCard,
} from '@kit/billing-gateway/components';
import { Database } from '@kit/supabase/database';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { If } from '@kit/ui/if';
import { PageBody, PageHeader } from '@kit/ui/page'; import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
import { PersonalAccountCheckoutForm } from '~/(dashboard)/home/(user)/billing/_components/personal-account-checkout-form'; import { createPersonalAccountBillingPortalSession } from '~/(dashboard)/home/(user)/billing/server-actions';
import billingConfig from '~/config/billing.config';
import pathsConfig from '~/config/paths.config';
import { withI18n } from '~/lib/i18n/with-i18n'; import { withI18n } from '~/lib/i18n/with-i18n';
function PersonalAccountBillingPage() { import { loadUserWorkspace } from '../../_lib/load-user-workspace';
import { PersonalAccountCheckoutForm } from './_components/personal-account-checkout-form';
type Subscription = Database['public']['Tables']['subscriptions']['Row'];
async function PersonalAccountBillingPage() {
const client = getSupabaseServerComponentClient();
const { session } = await loadUserWorkspace();
if (!session?.user) {
redirect(pathsConfig.auth.signIn);
}
const [subscription, customerId] = await loadData(client, session.user.id);
return ( return (
<> <>
<PageHeader <PageHeader
@@ -13,10 +40,48 @@ function PersonalAccountBillingPage() {
/> />
<PageBody> <PageBody>
<PersonalAccountCheckoutForm /> <div className={'mx-auto w-full max-w-2xl'}>
<div className={'flex flex-col space-y-8'}>
<If
condition={subscription}
fallback={<PersonalAccountCheckoutForm />}
>
{(subscription) => (
<CurrentPlanCard
subscription={subscription}
config={billingConfig}
/>
)}
</If>
<If condition={customerId}>
<form action={createPersonalAccountBillingPortalSession}>
<BillingPortalCard />
</form>
</If>
</div>
</div>
</PageBody> </PageBody>
</> </>
); );
} }
export default withI18n(PersonalAccountBillingPage); export default withI18n(PersonalAccountBillingPage);
function loadData(client: SupabaseClient<Database>, userId: string) {
const subscription = client
.from('subscriptions')
.select<string, Subscription>('*')
.eq('account_id', userId)
.maybeSingle()
.then(({ data }) => data);
const customer = client
.from('billing_customers')
.select('customer_id')
.eq('account_id', userId)
.maybeSingle()
.then(({ data }) => data?.customer_id);
return Promise.all([subscription, customer]);
}

View File

@@ -1,3 +1,5 @@
// We reuse the page from the billing module // We reuse the page from the billing module
// as there is no need to create a new one. // as there is no need to create a new one.
export * from '../return/page'; import ReturnStripeSessionPage from '../../../[account]/billing/return/page';
export default ReturnStripeSessionPage;

View File

@@ -1,14 +1,16 @@
'use server'; 'use server';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { z } from 'zod'; import { z } from 'zod';
import { getProductPlanPairFromId } from '@kit/billing'; import { getProductPlanPairFromId } from '@kit/billing';
import { getBillingGatewayProvider } from '@kit/billing-gateway'; import { getBillingGatewayProvider } from '@kit/billing-gateway';
import { Logger } from '@kit/shared/logger';
import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client'; import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import appConfig from '~/config/app.config';
import billingConfig from '~/config/billing.config'; import billingConfig from '~/config/billing.config';
import pathsConfig from '~/config/paths.config'; import pathsConfig from '~/config/paths.config';
@@ -22,13 +24,21 @@ export async function createPersonalAccountCheckoutSession(params: {
planId: string; planId: string;
}) { }) {
const client = getSupabaseServerActionClient(); const client = getSupabaseServerActionClient();
const { data, error } = await client.auth.getUser(); const { data, error } = await requireAuth(client);
if (error ?? !data.user) { if (error ?? !data.user) {
throw new Error('Authentication required'); throw new Error('Authentication required');
} }
const planId = z.string().min(1).parse(params.planId); const planId = z.string().min(1).parse(params.planId);
Logger.info(
{
planId,
},
`Creating checkout session for plan ID`,
);
const service = await getBillingGatewayProvider(client); const service = await getBillingGatewayProvider(client);
const productPlanPairFromId = getProductPlanPairFromId(billingConfig, planId); const productPlanPairFromId = getProductPlanPairFromId(billingConfig, planId);
@@ -61,6 +71,13 @@ export async function createPersonalAccountCheckoutSession(params: {
customerId, customerId,
}); });
Logger.info(
{
userId: data.user.id,
},
`Checkout session created. Returning checkout token to client...`,
);
// return the checkout token to the client // return the checkout token to the client
// so we can call the payment gateway to complete the checkout // so we can call the payment gateway to complete the checkout
return { return {
@@ -68,7 +85,7 @@ export async function createPersonalAccountCheckoutSession(params: {
}; };
} }
export async function createBillingPortalSession() { export async function createPersonalAccountBillingPortalSession() {
const client = getSupabaseServerActionClient(); const client = getSupabaseServerActionClient();
const { data, error } = await client.auth.getUser(); const { data, error } = await client.auth.getUser();
@@ -95,18 +112,17 @@ export async function createBillingPortalSession() {
} }
function getCheckoutSessionReturnUrl() { function getCheckoutSessionReturnUrl() {
const origin = headers().get('origin')!;
return new URL( return new URL(
pathsConfig.app.personalAccountBillingReturn, pathsConfig.app.personalAccountBillingReturn,
origin, appConfig.url,
).toString(); ).toString();
} }
function getBillingPortalReturnUrl() { function getBillingPortalReturnUrl() {
const origin = headers().get('origin')!; return new URL(
pathsConfig.app.personalAccountBilling,
return new URL(pathsConfig.app.accountBilling, origin).toString(); appConfig.url,
).toString();
} }
async function getCustomerIdFromAccountId(accountId: string) { async function getCustomerIdFromAccountId(accountId: string) {

View File

@@ -1,3 +0,0 @@
import { GlobalLoader } from '@kit/ui/global-loader';
export default GlobalLoader;

View File

@@ -4,6 +4,14 @@ import featureFlagsConfig from '~/config/feature-flags.config';
import pathsConfig from '~/config/paths.config'; import pathsConfig from '~/config/paths.config';
import { withI18n } from '~/lib/i18n/with-i18n'; import { withI18n } from '~/lib/i18n/with-i18n';
const features = {
enableAccountDeletion: featureFlagsConfig.enableAccountDeletion,
};
const paths = {
callback: pathsConfig.auth.callback,
};
function PersonalAccountSettingsPage() { function PersonalAccountSettingsPage() {
return ( return (
<div <div
@@ -11,14 +19,7 @@ function PersonalAccountSettingsPage() {
'container mx-auto flex max-w-2xl flex-1 flex-col items-center' 'container mx-auto flex max-w-2xl flex-1 flex-col items-center'
} }
> >
<PersonalAccountSettingsContainer <PersonalAccountSettingsContainer features={features} paths={paths} />
features={{
enableAccountDeletion: featureFlagsConfig.enableAccountDeletion,
}}
paths={{
callback: pathsConfig.auth.callback,
}}
/>
</div> </div>
); );
} }

View File

@@ -4,7 +4,7 @@ import { useRouter } from 'next/navigation';
import type { Session } from '@supabase/supabase-js'; import type { Session } from '@supabase/supabase-js';
import { ArrowLeftCircleIcon, ArrowRightCircleIcon } from 'lucide-react'; import { ArrowLeftCircle, ArrowRightCircle } from 'lucide-react';
import { AccountSelector } from '@kit/accounts/account-selector'; import { AccountSelector } from '@kit/accounts/account-selector';
import { Sidebar, SidebarContent } from '@kit/ui/sidebar'; import { Sidebar, SidebarContent } from '@kit/ui/sidebar';
@@ -138,13 +138,13 @@ function CollapsibleButton({
aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'} aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
onClick={() => onClick(!collapsed)} onClick={() => onClick(!collapsed)}
> >
<ArrowRightCircleIcon <ArrowRightCircle
className={cn(iconClassName, { className={cn(iconClassName, {
hidden: !collapsed, hidden: !collapsed,
})} })}
/> />
<ArrowLeftCircleIcon <ArrowLeftCircle
className={cn(iconClassName, { className={cn(iconClassName, {
hidden: collapsed, hidden: collapsed,
})} })}

View File

@@ -2,7 +2,7 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { ArrowDownIcon, ArrowUpIcon, MenuIcon } from 'lucide-react'; import { ArrowDown, ArrowUp, Menu } from 'lucide-react';
import { Line, LineChart, ResponsiveContainer, XAxis } from 'recharts'; import { Line, LineChart, ResponsiveContainer, XAxis } from 'recharts';
import { Badge } from '@kit/ui/badge'; import { Badge } from '@kit/ui/badge';
@@ -328,11 +328,11 @@ function Trend(
const Icon = useMemo(() => { const Icon = useMemo(() => {
switch (props.trend) { switch (props.trend) {
case 'up': case 'up':
return <ArrowUpIcon className={'h-4 text-green-500'} />; return <ArrowUp className={'h-4 text-green-500'} />;
case 'down': case 'down':
return <ArrowDownIcon className={'h-4 text-destructive'} />; return <ArrowDown className={'h-4 text-destructive'} />;
case 'stale': case 'stale':
return <MenuIcon className={'h-4 text-orange-500'} />; return <Menu className={'h-4 text-orange-500'} />;
} }
}, [props.trend]); }, [props.trend]);

View File

@@ -3,7 +3,7 @@
import Link from 'next/link'; import Link from 'next/link';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { HomeIcon, LogOutIcon, MenuIcon } from 'lucide-react'; import { Home, LogOut, Menu } from 'lucide-react';
import { AccountSelector } from '@kit/accounts/account-selector'; import { AccountSelector } from '@kit/accounts/account-selector';
import { useSignOut } from '@kit/supabase/hooks/use-sign-out'; import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
@@ -67,7 +67,7 @@ export const MobileAppNavigation = (
return ( return (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger> <DropdownMenuTrigger>
<MenuIcon className={'h-9'} /> <Menu className={'h-9'} />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent sideOffset={10} className={'w-screen rounded-none'}> <DropdownMenuContent sideOffset={10} className={'w-screen rounded-none'}>
@@ -115,7 +115,7 @@ function SignOutDropdownItem(
className={'flex h-12 w-full items-center space-x-4'} className={'flex h-12 w-full items-center space-x-4'}
onClick={props.onSignOut} onClick={props.onSignOut}
> >
<LogOutIcon className={'h-6'} /> <LogOut className={'h-6'} />
<span> <span>
<Trans i18nKey={'common:signOut'} defaults={'Sign out'} /> <Trans i18nKey={'common:signOut'} defaults={'Sign out'} />
@@ -135,7 +135,7 @@ function OrganizationsModal() {
onSelect={(e) => e.preventDefault()} onSelect={(e) => e.preventDefault()}
> >
<button className={'flex items-center space-x-4'}> <button className={'flex items-center space-x-4'}>
<HomeIcon className={'h-6'} /> <Home className={'h-6'} />
<span> <span>
<Trans i18nKey={'common:yourOrganizations'} /> <Trans i18nKey={'common:yourOrganizations'} />

View File

@@ -1,39 +0,0 @@
import { Button } from '@kit/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@kit/ui/card';
import { createBillingPortalSession } from '../server-actions';
export function BillingPortalForm(props: { accountId: string }) {
return (
<div className={'mx-auto w-full max-w-2xl'}>
<Card>
<CardHeader>
<CardTitle>Manage your Team Plan</CardTitle>
<CardDescription>
You can change your plan at any time.
</CardDescription>
</CardHeader>
<CardContent>
<form action={createBillingPortalSession}>
<input type={'hidden'} name={'accountId'} value={props.accountId} />
<Button>Manage your Billing Settings</Button>
<span>
Visit the billing portal to manage your subscription (update
payment method, cancel subscription, etc.)
</span>
</form>
</CardContent>
</Card>
</div>
);
}

View File

@@ -2,6 +2,8 @@
import { useState, useTransition } from 'react'; import { useState, useTransition } from 'react';
import { useParams } from 'next/navigation';
import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components'; import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components';
import { import {
Card, Card,
@@ -16,6 +18,7 @@ import billingConfig from '~/config/billing.config';
import { createTeamAccountCheckoutSession } from '../server-actions'; import { createTeamAccountCheckoutSession } from '../server-actions';
export function TeamAccountCheckoutForm(params: { accountId: string }) { export function TeamAccountCheckoutForm(params: { accountId: string }) {
const routeParams = useParams();
const [pending, startTransition] = useTransition(); const [pending, startTransition] = useTransition();
const [checkoutToken, setCheckoutToken] = useState<string | null>(null); const [checkoutToken, setCheckoutToken] = useState<string | null>(null);
@@ -31,14 +34,11 @@ export function TeamAccountCheckoutForm(params: { accountId: string }) {
// Otherwise, render the plan picker component // Otherwise, render the plan picker component
return ( return (
<div className={'mx-auto w-full max-w-2xl'}>
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>Manage your Team Plan</CardTitle> <CardTitle>Manage your Team Plan</CardTitle>
<CardDescription> <CardDescription>You can change your plan at any time.</CardDescription>
You can change your plan at any time.
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
@@ -47,10 +47,12 @@ export function TeamAccountCheckoutForm(params: { accountId: string }) {
config={billingConfig} config={billingConfig}
onSubmit={({ planId }) => { onSubmit={({ planId }) => {
startTransition(async () => { startTransition(async () => {
const { checkoutToken } = const slug = routeParams.account as string;
await createTeamAccountCheckoutSession({
const { checkoutToken } = await createTeamAccountCheckoutSession({
planId, planId,
accountId: params.accountId, accountId: params.accountId,
slug,
}); });
setCheckoutToken(checkoutToken); setCheckoutToken(checkoutToken);
@@ -59,6 +61,5 @@ export function TeamAccountCheckoutForm(params: { accountId: string }) {
/> />
</CardContent> </CardContent>
</Card> </Card>
</div>
); );
} }

View File

@@ -1,10 +1,16 @@
import {
BillingPortalCard,
CurrentPlanCard,
} from '@kit/billing-gateway/components';
import { Database } from '@kit/supabase/database';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client'; import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { If } from '@kit/ui/if'; import { If } from '@kit/ui/if';
import { PageBody, PageHeader } from '@kit/ui/page'; import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
import { loadOrganizationWorkspace } from '~/(dashboard)/home/[account]/_lib/load-workspace'; import { loadOrganizationWorkspace } from '~/(dashboard)/home/[account]/_lib/load-workspace';
import { BillingPortalForm } from '~/(dashboard)/home/[account]/billing/_components/billing-portal-form'; import { createBillingPortalSession } from '~/(dashboard)/home/[account]/billing/server-actions';
import billingConfig from '~/config/billing.config';
import { withI18n } from '~/lib/i18n/with-i18n'; import { withI18n } from '~/lib/i18n/with-i18n';
import { TeamAccountCheckoutForm } from './_components/team-account-checkout-form'; import { TeamAccountCheckoutForm } from './_components/team-account-checkout-form';
@@ -18,7 +24,7 @@ interface Params {
async function OrganizationAccountBillingPage({ params }: Params) { async function OrganizationAccountBillingPage({ params }: Params) {
const workspace = await loadOrganizationWorkspace(params.account); const workspace = await loadOrganizationWorkspace(params.account);
const accountId = workspace.account.id; const accountId = workspace.account.id;
const customerId = await loadCustomerIdFromAccount(accountId); const [subscription, customerId] = await loadAccountData(accountId);
return ( return (
<> <>
@@ -28,11 +34,27 @@ async function OrganizationAccountBillingPage({ params }: Params) {
/> />
<PageBody> <PageBody>
<TeamAccountCheckoutForm accountId={accountId} /> <div className={'mx-auto w-full max-w-2xl'}>
<div className={'flex flex-col space-y-4'}>
<If
condition={subscription}
fallback={<TeamAccountCheckoutForm accountId={accountId} />}
>
{(data) => (
<CurrentPlanCard subscription={data} config={billingConfig} />
)}
</If>
<If condition={customerId}> <If condition={customerId}>
<BillingPortalForm accountId={accountId} /> <form action={createBillingPortalSession}>
<input type="hidden" name={'accountId'} value={accountId} />
<input type="hidden" name={'slug'} value={params.account} />
<BillingPortalCard />
</form>
</If> </If>
</div>
</div>
</PageBody> </PageBody>
</> </>
); );
@@ -40,18 +62,21 @@ async function OrganizationAccountBillingPage({ params }: Params) {
export default withI18n(OrganizationAccountBillingPage); export default withI18n(OrganizationAccountBillingPage);
async function loadCustomerIdFromAccount(accountId: string) { async function loadAccountData(accountId: string) {
const client = getSupabaseServerComponentClient(); const client = getSupabaseServerComponentClient();
const { data, error } = await client const subscription = client
.from('subscriptions')
.select<string, Database['public']['Tables']['subscriptions']['Row']>('*')
.eq('account_id', accountId)
.maybeSingle()
.then(({ data }) => data);
const customerId = client
.from('billing_customers') .from('billing_customers')
.select('customer_id') .select('customer_id')
.eq('account_id', accountId) .eq('account_id', accountId)
.maybeSingle(); .maybeSingle();
if (error) { return Promise.all([subscription, customerId]);
throw error;
}
return data?.customer_id;
} }

View File

@@ -1,6 +1,5 @@
'use server'; 'use server';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { z } from 'zod'; import { z } from 'zod';
@@ -10,6 +9,7 @@ import { getBillingGatewayProvider } from '@kit/billing-gateway';
import { requireAuth } from '@kit/supabase/require-auth'; import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client'; import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import appConfig from '~/config/app.config';
import billingConfig from '~/config/billing.config'; import billingConfig from '~/config/billing.config';
import pathsConfig from '~/config/paths.config'; import pathsConfig from '~/config/paths.config';
@@ -22,6 +22,7 @@ import pathsConfig from '~/config/paths.config';
export async function createTeamAccountCheckoutSession(params: { export async function createTeamAccountCheckoutSession(params: {
planId: string; planId: string;
accountId: string; accountId: string;
slug: string;
}) { }) {
const client = getSupabaseServerActionClient(); const client = getSupabaseServerActionClient();
@@ -57,7 +58,7 @@ export async function createTeamAccountCheckoutSession(params: {
} }
// the return URL for the checkout session // the return URL for the checkout session
const returnUrl = getCheckoutSessionReturnUrl(); const returnUrl = getCheckoutSessionReturnUrl(params.slug);
// find the customer ID for the account if it exists // find the customer ID for the account if it exists
// (eg. if the account has been billed before) // (eg. if the account has been billed before)
@@ -85,14 +86,15 @@ export async function createTeamAccountCheckoutSession(params: {
}; };
} }
export async function createBillingPortalSession(data: FormData) { export async function createBillingPortalSession(formData: FormData) {
const client = getSupabaseServerActionClient(); const client = getSupabaseServerActionClient();
const accountId = z const { accountId, slug } = z
.object({ .object({
accountId: z.string().min(1), accountId: z.string().min(1),
slug: z.string().min(1),
}) })
.parse(Object.fromEntries(data)).accountId; .parse(Object.fromEntries(formData));
const { data: session, error } = await requireAuth(client); const { data: session, error } = await requireAuth(client);
@@ -113,7 +115,7 @@ export async function createBillingPortalSession(data: FormData) {
const service = await getBillingGatewayProvider(client); const service = await getBillingGatewayProvider(client);
const customerId = await getCustomerIdFromAccountId(client, accountId); const customerId = await getCustomerIdFromAccountId(client, accountId);
const returnUrl = getBillingPortalReturnUrl(); const returnUrl = getBillingPortalReturnUrl(slug);
if (!customerId) { if (!customerId) {
throw new Error('Customer not found'); throw new Error('Customer not found');
@@ -128,16 +130,16 @@ export async function createBillingPortalSession(data: FormData) {
return redirect(url); return redirect(url);
} }
function getCheckoutSessionReturnUrl() { function getCheckoutSessionReturnUrl(accountSlug: string) {
const origin = headers().get('origin')!; return new URL(pathsConfig.app.accountBillingReturn, appConfig.url)
.toString()
return new URL(pathsConfig.app.accountBillingReturn, origin).toString(); .replace('[account]', accountSlug);
} }
function getBillingPortalReturnUrl() { function getBillingPortalReturnUrl(accountSlug: string) {
const origin = headers().get('origin')!; return new URL(pathsConfig.app.accountBilling, appConfig.url)
.toString()
return new URL(pathsConfig.app.accountBilling, origin).toString(); .replace('[account]', accountSlug);
} }
/** /**

View File

@@ -1,4 +1,4 @@
import { PlusCircleIcon } from 'lucide-react'; import { PlusCircle } from 'lucide-react';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client'; import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { import {
@@ -99,7 +99,7 @@ async function OrganizationAccountMembersPage({ params }: Params) {
<InviteMembersDialogContainer account={account.slug}> <InviteMembersDialogContainer account={account.slug}>
<Button size={'sm'}> <Button size={'sm'}>
<PlusCircleIcon className={'mr-2 w-4'} /> <PlusCircle className={'mr-2 w-4'} />
<span>Add Member</span> <span>Add Member</span>
</Button> </Button>
</InviteMembersDialogContainer> </InviteMembersDialogContainer>

View File

@@ -1,6 +1,6 @@
import loadDynamic from 'next/dynamic'; import loadDynamic from 'next/dynamic';
import { PlusIcon } from 'lucide-react'; import { Plus } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { PageBody } from '@kit/ui/page'; import { PageBody } from '@kit/ui/page';
@@ -11,7 +11,7 @@ import { AppHeader } from '~/(dashboard)/home/[account]/_components/app-header';
import { withI18n } from '~/lib/i18n/with-i18n'; import { withI18n } from '~/lib/i18n/with-i18n';
const DashboardDemo = loadDynamic( const DashboardDemo = loadDynamic(
() => import('~/(dashboard)/home/[account]/_components/dashboard-demo'), () => import('./_components/dashboard-demo'),
{ {
ssr: false, ssr: false,
loading: () => ( loading: () => (
@@ -50,7 +50,7 @@ function OrganizationAccountHomePage({
account={params.account} account={params.account}
> >
<Button> <Button>
<PlusIcon className={'mr-2 h-4'} /> <Plus className={'mr-2 h-4'} />
<span>Add Widget</span> <span>Add Widget</span>
</Button> </Button>
</AppHeader> </AppHeader>

View File

@@ -2,19 +2,16 @@ import { use } from 'react';
import { cookies } from 'next/headers'; import { cookies } from 'next/headers';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { Sidebar, SidebarContent, SidebarNavigation } from '@kit/ui/sidebar'; import { Sidebar, SidebarContent, SidebarNavigation } from '@kit/ui/sidebar';
import { HomeSidebarAccountSelector } from '~/(dashboard)/home/_components/home-sidebar-account-selector'; import { HomeSidebarAccountSelector } from '~/(dashboard)/home/_components/home-sidebar-account-selector';
import { ProfileDropdownContainer } from '~/(dashboard)/home/_components/personal-account-dropdown'; import { ProfileDropdownContainer } from '~/(dashboard)/home/_components/personal-account-dropdown';
import { loadUserWorkspace } from '~/(dashboard)/home/_lib/load-user-workspace';
import { personalAccountSidebarConfig } from '~/config/personal-account-sidebar.config'; import { personalAccountSidebarConfig } from '~/config/personal-account-sidebar.config';
export function HomeSidebar() { export function HomeSidebar() {
const collapsed = getSidebarCollapsed(); const collapsed = getSidebarCollapsed();
const { session, accounts } = use(loadUserWorkspace());
const [accounts, session] = use(
Promise.all([loadUserAccounts(), loadSession()]),
);
return ( return (
<Sidebar collapsed={collapsed}> <Sidebar collapsed={collapsed}>
@@ -38,38 +35,3 @@ export function HomeSidebar() {
function getSidebarCollapsed() { function getSidebarCollapsed() {
return cookies().get('sidebar-collapsed')?.value === 'true'; return cookies().get('sidebar-collapsed')?.value === 'true';
} }
async function loadSession() {
const client = getSupabaseServerComponentClient();
const {
data: { session },
error,
} = await client.auth.getSession();
if (error) {
throw error;
}
return session;
}
async function loadUserAccounts() {
const client = getSupabaseServerComponentClient();
const { data: accounts, error } = await client
.from('user_accounts')
.select(`name, slug, picture_url`);
if (error) {
throw error;
}
return accounts.map(({ name, slug, picture_url }) => {
return {
label: name,
value: slug,
image: picture_url,
};
});
}

View File

@@ -0,0 +1,50 @@
import { cache } from 'react';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
export const loadUserWorkspace = cache(async () => {
const [accounts, session] = await Promise.all([
loadUserAccounts(),
loadSession(),
]);
return {
accounts,
session,
};
});
async function loadSession() {
const client = getSupabaseServerComponentClient();
const {
data: { session },
error,
} = await client.auth.getSession();
if (error) {
throw error;
}
return session;
}
async function loadUserAccounts() {
const client = getSupabaseServerComponentClient();
const { data: accounts, error } = await client
.from('user_accounts')
.select(`name, slug, picture_url`);
if (error) {
throw error;
}
return accounts.map(({ name, slug, picture_url }) => {
return {
label: name,
value: slug,
image: picture_url,
};
});
}

View File

@@ -6,7 +6,7 @@ import Link from 'next/link';
import type { Session } from '@supabase/supabase-js'; import type { Session } from '@supabase/supabase-js';
import { ChevronRightIcon } from 'lucide-react'; import { ChevronRight } from 'lucide-react';
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown'; import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
import { useSignOut } from '@kit/supabase/hooks/use-sign-out'; import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
@@ -60,7 +60,7 @@ function AuthButtons() {
<Link href={pathsConfig.auth.signUp}> <Link href={pathsConfig.auth.signUp}>
<Button className={'rounded-full'}> <Button className={'rounded-full'}>
<Trans i18nKey={'auth:signUp'} /> <Trans i18nKey={'auth:signUp'} />
<ChevronRightIcon className={'h-4'} /> <ChevronRight className={'h-4'} />
</Button> </Button>
</Link> </Link>
</div> </div>

View File

@@ -4,7 +4,7 @@ import { SiteHeaderAccountSection } from '~/(marketing)/_components/site-header-
import { SiteNavigation } from '~/(marketing)/_components/site-navigation'; import { SiteNavigation } from '~/(marketing)/_components/site-navigation';
import { AppLogo } from '~/components/app-logo'; import { AppLogo } from '~/components/app-logo';
export async function SiteHeader(props: { session: Session | null }) { export async function SiteHeader(props: { session?: Session | null }) {
return ( return (
<div className={'container mx-auto'}> <div className={'container mx-auto'}>
<div className="flex h-16 items-center justify-between"> <div className="flex h-16 items-center justify-between">
@@ -19,7 +19,7 @@ export async function SiteHeader(props: { session: Session | null }) {
<div className={'flex flex-1 items-center justify-end space-x-4'}> <div className={'flex flex-1 items-center justify-end space-x-4'}>
<div className={'flex items-center'}></div> <div className={'flex items-center'}></div>
<SiteHeaderAccountSection session={props.session} /> <SiteHeaderAccountSection session={props.session ?? null} />
<div className={'flex lg:hidden'}> <div className={'flex lg:hidden'}>
<SiteNavigation /> <SiteNavigation />

View File

@@ -1,6 +1,6 @@
import Link from 'next/link'; import Link from 'next/link';
import { MenuIcon } from 'lucide-react'; import { Menu } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
@@ -81,7 +81,7 @@ function MobileDropdown() {
return ( return (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger aria-label={'Open Menu'}> <DropdownMenuTrigger aria-label={'Open Menu'}>
<MenuIcon className={'h-9'} /> <Menu className={'h-9'} />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent> <DropdownMenuContent>

View File

@@ -3,7 +3,7 @@ import { cache } from 'react';
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { allDocumentationPages } from 'contentlayer/generated'; import { allDocumentationPages } from 'contentlayer/generated';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'; import { ChevronLeft, ChevronRight } from 'lucide-react';
import { If } from '@kit/ui/if'; import { If } from '@kit/ui/if';
import { Mdx } from '@kit/ui/mdx'; import { Mdx } from '@kit/ui/mdx';
@@ -77,7 +77,7 @@ function DocumentationPage({ params }: PageParams) {
{(page) => ( {(page) => (
<DocumentationPageLink <DocumentationPageLink
page={page} page={page}
before={<ChevronLeftIcon className={'w-4'} />} before={<ChevronLeft className={'w-4'} />}
/> />
)} )}
</If> </If>
@@ -88,7 +88,7 @@ function DocumentationPage({ params }: PageParams) {
{(page) => ( {(page) => (
<DocumentationPageLink <DocumentationPageLink
page={page} page={page}
after={<ChevronRightIcon className={'w-4'} />} after={<ChevronRight className={'w-4'} />}
/> />
)} )}
</If> </If>

View File

@@ -1,6 +1,6 @@
import Link from 'next/link'; import Link from 'next/link';
import { ChevronRightIcon } from 'lucide-react'; import { ChevronRight } from 'lucide-react';
export const DocsCard: React.FC< export const DocsCard: React.FC<
React.PropsWithChildren<{ React.PropsWithChildren<{
@@ -36,7 +36,7 @@ export const DocsCard: React.FC<
{link.label} {link.label}
</Link> </Link>
<ChevronRightIcon className={'h-4'} /> <ChevronRight className={'h-4'} />
</span> </span>
</div> </div>
)} )}

View File

@@ -5,7 +5,7 @@ import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { ChevronDownIcon, MenuIcon } from 'lucide-react'; import { ChevronDown, Menu } from 'lucide-react';
import { isBrowser } from '@kit/shared/utils'; import { isBrowser } from '@kit/shared/utils';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
@@ -53,7 +53,7 @@ const DocsNavLink: React.FC<{
<span <span
className={`block w-2.5 ${collapsed ? '-rotate-90 transform' : ''}`} className={`block w-2.5 ${collapsed ? '-rotate-90 transform' : ''}`}
> >
<ChevronDownIcon className="h-4 w-4" /> <ChevronDown className="h-4 w-4" />
</span> </span>
</button> </button>
)} )}
@@ -218,7 +218,7 @@ function FloatingDocumentationNavigation({
className={'fixed bottom-5 right-5 z-10 h-16 w-16 rounded-full'} className={'fixed bottom-5 right-5 z-10 h-16 w-16 rounded-full'}
onClick={onClick} onClick={onClick}
> >
<MenuIcon className={'h-8'} /> <Menu className={'h-8'} />
</Button> </Button>
</> </>
); );

View File

@@ -1,4 +1,4 @@
import { ChevronDownIcon } from 'lucide-react'; import { ChevronDown } from 'lucide-react';
import { SitePageHeader } from '~/(marketing)/_components/site-page-header'; import { SitePageHeader } from '~/(marketing)/_components/site-page-header';
import { withI18n } from '~/lib/i18n/with-i18n'; import { withI18n } from '~/lib/i18n/with-i18n';
@@ -108,7 +108,7 @@ function FaqItem({
</h2> </h2>
<div> <div>
<ChevronDownIcon <ChevronDown
className={'h-5 transition duration-300 group-open:-rotate-180'} className={'h-5 transition duration-300 group-open:-rotate-180'}
/> />
</div> </div>

View File

@@ -1,7 +1,7 @@
import Image from 'next/image'; import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { ChevronRightIcon } from 'lucide-react'; import { ChevronRight } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading'; import { Heading } from '@kit/ui/heading';
@@ -135,7 +135,7 @@ function Home() {
<Button variant={'outline'}> <Button variant={'outline'}>
<span className={'flex items-center space-x-2'}> <span className={'flex items-center space-x-2'}>
<span>Get Started</span> <span>Get Started</span>
<ChevronRightIcon className={'h-3'} /> <ChevronRight className={'h-3'} />
</span> </span>
</Button> </Button>
</div> </div>
@@ -273,7 +273,7 @@ function MainCallToActionButton() {
<span className={'flex items-center space-x-2'}> <span className={'flex items-center space-x-2'}>
<span>Get Started</span> <span>Get Started</span>
<ChevronRightIcon <ChevronRight
className={ className={
'h-4 animate-in fade-in slide-in-from-left-8' + 'h-4 animate-in fade-in slide-in-from-left-8' +
' delay-1000 duration-1000 zoom-in fill-mode-both' ' delay-1000 duration-1000 zoom-in fill-mode-both'

View File

@@ -8,8 +8,6 @@ import billingConfig from '~/config/billing.config';
* @description Handle the webhooks from Stripe related to checkouts * @description Handle the webhooks from Stripe related to checkouts
*/ */
export async function POST(request: Request) { export async function POST(request: Request) {
const client = getSupabaseRouteHandlerClient();
// we can infer the provider from the billing config or the request // we can infer the provider from the billing config or the request
// for simplicity, we'll use the billing config for now // for simplicity, we'll use the billing config for now
// TODO: use dynamic provider from request? // TODO: use dynamic provider from request?
@@ -23,7 +21,9 @@ export async function POST(request: Request) {
`Received billing webhook. Processing...`, `Received billing webhook. Processing...`,
); );
const service = await getBillingEventHandlerService(client, provider); const clientProvider = () => getSupabaseRouteHandlerClient({ admin: true });
const service = await getBillingEventHandlerService(clientProvider, provider);
try { try {
await service.handleWebhookEvent(request); await service.handleWebhookEvent(request);

View File

@@ -0,0 +1,3 @@
export function POST(request: Request) {
console.log(request);
}

View File

@@ -2,7 +2,7 @@
import Link from 'next/link'; import Link from 'next/link';
import { ArrowLeftIcon } from 'lucide-react'; import { ArrowLeft } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading'; import { Heading } from '@kit/ui/heading';
@@ -41,7 +41,7 @@ const ErrorPage = () => {
<div> <div>
<Link href={'/'}> <Link href={'/'}>
<Button variant={'outline'}> <Button variant={'outline'}>
<ArrowLeftIcon className={'mr-2 h-4'} /> <ArrowLeft className={'mr-2 h-4'} />
<Trans i18nKey={'common:backToHomePage'} /> <Trans i18nKey={'common:backToHomePage'} />
</Button> </Button>

View File

@@ -1,6 +1,6 @@
import Link from 'next/link'; import Link from 'next/link';
import { ArrowLeftIcon } from 'lucide-react'; import { ArrowLeft } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading'; import { Heading } from '@kit/ui/heading';
@@ -44,7 +44,7 @@ const NotFoundPage = () => {
<Link href={'/'}> <Link href={'/'}>
<Button variant={'outline'}> <Button variant={'outline'}>
<ArrowLeftIcon className={'mr-2 h-4'} /> <ArrowLeft className={'mr-2 h-4'} />
<Trans i18nKey={'common:backToHomePage'} /> <Trans i18nKey={'common:backToHomePage'} />
</Button> </Button>

View File

@@ -4,7 +4,7 @@ import { getServerSideSitemap } from 'next-sitemap';
import appConfig from '~/config/app.config'; import appConfig from '~/config/app.config';
const siteUrl = appConfig.url; invariant(appConfig.url, 'No NEXT_PUBLIC_SITE_URL environment variable found');
export async function GET() { export async function GET() {
const urls = getSiteUrls(); const urls = getSiteUrls();
@@ -15,35 +15,29 @@ export async function GET() {
} }
function getSiteUrls() { function getSiteUrls() {
invariant(siteUrl, 'No NEXT_PUBLIC_SITE_URL found'); const urls = ['/', 'faq', 'pricing'];
const urls = ['', 'faq', 'pricing'];
return urls.map((url) => { return urls.map((url) => {
return { return {
loc: new URL(siteUrl, url).href, loc: new URL(url, appConfig.url).href,
lastmod: new Date().toISOString(), lastmod: new Date().toISOString(),
}; };
}); });
} }
function getPostsSitemap() { function getPostsSitemap() {
invariant(siteUrl, 'No NEXT_PUBLIC_SITE_URL found');
return allPosts.map((post) => { return allPosts.map((post) => {
return { return {
loc: new URL(siteUrl, post.url).href, loc: new URL(post.url, appConfig.url).href,
lastmod: new Date().toISOString(), lastmod: new Date().toISOString(),
}; };
}); });
} }
function getDocsSitemap() { function getDocsSitemap() {
invariant(siteUrl, 'No NEXT_PUBLIC_SITE_URL found');
return allDocumentationPages.map((page) => { return allDocumentationPages.map((page) => {
return { return {
loc: new URL(siteUrl, page.url).href, loc: new URL(page.url, appConfig.url).href,
lastmod: new Date().toISOString(), lastmod: new Date().toISOString(),
}; };
}); });

View File

@@ -12,7 +12,7 @@ export default createBillingSchema({
badge: `Value`, badge: `Value`,
plans: [ plans: [
{ {
id: 'starter-monthly', id: 'price_1NNwYHI1i3VnbZTqI2UzaHIe',
name: 'Starter Monthly', name: 'Starter Monthly',
price: '9.99', price: '9.99',
interval: 'month', interval: 'month',

View File

@@ -1,9 +1,4 @@
import { import { CreditCard, LayoutDashboard, Settings, Users } from 'lucide-react';
CreditCardIcon,
LayoutDashboardIcon,
SettingsIcon,
UsersIcon,
} from 'lucide-react';
import { SidebarConfigSchema } from '@kit/ui/sidebar-schema'; import { SidebarConfigSchema } from '@kit/ui/sidebar-schema';
@@ -16,7 +11,7 @@ const routes = (account: string) => [
{ {
label: 'common:dashboardTabLabel', label: 'common:dashboardTabLabel',
path: pathsConfig.app.accountHome.replace('[account]', account), path: pathsConfig.app.accountHome.replace('[account]', account),
Icon: <LayoutDashboardIcon className={iconClasses} />, Icon: <LayoutDashboard className={iconClasses} />,
end: true, end: true,
}, },
{ {
@@ -26,18 +21,18 @@ const routes = (account: string) => [
{ {
label: 'common:settingsTabLabel', label: 'common:settingsTabLabel',
path: createPath(pathsConfig.app.accountSettings, account), path: createPath(pathsConfig.app.accountSettings, account),
Icon: <SettingsIcon className={iconClasses} />, Icon: <Settings className={iconClasses} />,
}, },
{ {
label: 'common:accountMembers', label: 'common:accountMembers',
path: createPath(pathsConfig.app.accountMembers, account), path: createPath(pathsConfig.app.accountMembers, account),
Icon: <UsersIcon className={iconClasses} />, Icon: <Users className={iconClasses} />,
}, },
featureFlagsConfig.enableOrganizationBilling featureFlagsConfig.enableOrganizationBilling
? { ? {
label: 'common:billingTabLabel', label: 'common:billingTabLabel',
path: createPath(pathsConfig.app.accountBilling, account), path: createPath(pathsConfig.app.accountBilling, account),
Icon: <CreditCardIcon className={iconClasses} />, Icon: <CreditCard className={iconClasses} />,
} }
: undefined, : undefined,
].filter(Boolean), ].filter(Boolean),

View File

@@ -1,4 +1,4 @@
import { CreditCardIcon, HomeIcon, UserIcon } from 'lucide-react'; import { CreditCard, Home, User } from 'lucide-react';
import { SidebarConfigSchema } from '@kit/ui/sidebar-schema'; import { SidebarConfigSchema } from '@kit/ui/sidebar-schema';
@@ -11,13 +11,13 @@ const routes = [
{ {
label: 'common:homeTabLabel', label: 'common:homeTabLabel',
path: pathsConfig.app.home, path: pathsConfig.app.home,
Icon: <HomeIcon className={iconClasses} />, Icon: <Home className={iconClasses} />,
end: true, end: true,
}, },
{ {
label: 'common:yourAccountTabLabel', label: 'common:yourAccountTabLabel',
path: pathsConfig.app.personalAccountSettings, path: pathsConfig.app.personalAccountSettings,
Icon: <UserIcon className={iconClasses} />, Icon: <User className={iconClasses} />,
}, },
]; ];
@@ -25,7 +25,7 @@ if (featureFlagsConfig.enablePersonalAccountBilling) {
routes.push({ routes.push({
label: 'common:billingTabLabel', label: 'common:billingTabLabel',
path: pathsConfig.app.personalAccountBilling, path: pathsConfig.app.personalAccountBilling,
Icon: <CreditCardIcon className={iconClasses} />, Icon: <CreditCard className={iconClasses} />,
}); });
} }

View File

@@ -18,6 +18,7 @@ const config = {
'@kit/mailers', '@kit/mailers',
'@kit/billing', '@kit/billing',
'@kit/billing-gateway', '@kit/billing-gateway',
'@kit/stripe',
], ],
pageExtensions: ['ts', 'tsx'], pageExtensions: ['ts', 'tsx'],
images: { images: {
@@ -25,6 +26,12 @@ const config = {
}, },
experimental: { experimental: {
mdxRs: true, mdxRs: true,
optimizePackageImports: []
},
modularizeImports: {
"lucide-react": {
transform: "lucide-react/dist/esm/icons/{{ kebabCase member }}",
}
}, },
/** We already do linting and typechecking as separate tasks in CI */ /** We already do linting and typechecking as separate tasks in CI */
eslint: { ignoreDuringBuilds: true }, eslint: { ignoreDuringBuilds: true },

View File

@@ -6,7 +6,7 @@
"analyze": "ANALYZE=true pnpm run build", "analyze": "ANALYZE=true pnpm run build",
"build": "pnpm with-env next build", "build": "pnpm with-env next build",
"clean": "git clean -xdf .next .turbo node_modules", "clean": "git clean -xdf .next .turbo node_modules",
"dev": "pnpm with-env next dev --turbo", "dev": "pnpm with-env next dev",
"lint": "next lint", "lint": "next lint",
"format": "prettier --check \"**/*.{js,cjs,mjs,ts,tsx,md,json}\"", "format": "prettier --check \"**/*.{js,cjs,mjs,ts,tsx,md,json}\"",
"start": "pnpm with-env next start", "start": "pnpm with-env next start",

View File

@@ -18,6 +18,7 @@
"lint": "turbo lint --continue -- --cache --cache-location 'node_modules/.cache/.eslintcache' && manypkg check", "lint": "turbo lint --continue -- --cache --cache-location 'node_modules/.cache/.eslintcache' && manypkg check",
"lint:fix": "turbo lint --continue -- --fix --cache --cache-location 'node_modules/.cache/.eslintcache' && manypkg fix", "lint:fix": "turbo lint --continue -- --fix --cache --cache-location 'node_modules/.cache/.eslintcache' && manypkg fix",
"typecheck": "turbo typecheck", "typecheck": "turbo typecheck",
"stripe:listen": "pnpm --filter '@kit/stripe' start",
"supabase:start": "turbo dev --filter @kit/supabase-config", "supabase:start": "turbo dev --filter @kit/supabase-config",
"supabase:stop": "pnpm --filter '@kit/supabase-config' stop", "supabase:stop": "pnpm --filter '@kit/supabase-config' stop",
"supabase:reset": "pnpm --filter '@kit/supabase-config' reset", "supabase:reset": "pnpm --filter '@kit/supabase-config' reset",

View File

@@ -0,0 +1,38 @@
'use client';
import { ArrowRightIcon } from '@radix-ui/react-icons';
import { Button } from '@kit/ui/button';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@kit/ui/card';
export function BillingPortalCard() {
return (
<Card>
<CardHeader>
<CardTitle>Manage your Subscription</CardTitle>
<CardDescription>
You can change your plan or cancel your subscription at any time.
</CardDescription>
</CardHeader>
<CardContent className={'space-y-2'}>
<Button className={'w-full'}>
<span>Manage your Billing Settings</span>
<ArrowRightIcon className={'ml-2 h-4'} />
</Button>
<p className={'text-sm'}>
Visit the billing portal to manage your subscription (update payment
method, cancel subscription, etc.)
</p>
</CardContent>
</Card>
);
}

View File

@@ -2,7 +2,7 @@
import Link from 'next/link'; import Link from 'next/link';
import { CheckIcon, ChevronRightIcon } from 'lucide-react'; import { Check, ChevronRight } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading'; import { Heading } from '@kit/ui/heading';
@@ -55,9 +55,9 @@ function SuccessSessionStatus({
'flex flex-col items-center justify-center space-y-4 text-center' 'flex flex-col items-center justify-center space-y-4 text-center'
} }
> >
<CheckIcon <Check
className={ className={
'w-16 rounded-full bg-green-500 p-1 text-white ring-8' + 'h-16 w-16 rounded-full bg-green-500 p-1 text-white ring-8' +
' ring-green-500/30 dark:ring-green-500/50' ' ring-green-500/30 dark:ring-green-500/50'
} }
/> />
@@ -87,7 +87,7 @@ function SuccessSessionStatus({
<Trans i18nKey={'subscription:checkoutSuccessBackButton'} /> <Trans i18nKey={'subscription:checkoutSuccessBackButton'} />
</span> </span>
<ChevronRightIcon className={'h-4'} /> <ChevronRight className={'h-4'} />
</span> </span>
</Link> </Link>
</Button> </Button>

View File

@@ -1 +1,68 @@
export function CurrentPlanCard(props: React.PropsWithChildren<{}>) {} import { formatDate } from 'date-fns';
import { z } from 'zod';
import { BillingSchema, getProductPlanPairFromId } from '@kit/billing';
import { Database } from '@kit/supabase/database';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@kit/ui/card';
import { If } from '@kit/ui/if';
export function CurrentPlanCard({
subscription,
config,
}: React.PropsWithChildren<{
subscription: Database['public']['Tables']['subscriptions']['Row'];
config: z.infer<typeof BillingSchema>;
}>) {
const { plan, product } = getProductPlanPairFromId(
config,
subscription.variant_id,
);
return (
<Card>
<CardHeader>
<CardTitle>{product.name}</CardTitle>
<CardDescription>{product.description}</CardDescription>
</CardHeader>
<CardContent className={'space-y-4 text-sm'}>
<div>
<div className={'font-semibold'}>
Your Current Plan: <span>{plan.name}</span>
</div>
</div>
<div>
<div className={'font-semibold'}>
Your Subscription is currently <span>{subscription.status}</span>
</div>
</div>
<If condition={subscription.cancel_at_period_end}>
<div>
<div className={'font-semibold'}>
Cancellation Date:{' '}
<span>{formatDate(subscription.period_ends_at, 'P')}</span>
</div>
</div>
</If>
<If condition={!subscription.cancel_at_period_end}>
<div>
<div className={'font-semibold'}>
Next Billing Date:{' '}
<span>{formatDate(subscription.period_ends_at, 'P')}</span>{' '}
</div>
</div>
</If>
</CardContent>
</Card>
);
}

View File

@@ -1,9 +1,14 @@
import { lazy } from 'react'; import { Suspense, forwardRef, lazy, memo, useMemo } from 'react';
import { Database } from '@kit/supabase/database'; import { Database } from '@kit/supabase/database';
import { LoadingOverlay } from '@kit/ui/loading-overlay';
type BillingProvider = Database['public']['Enums']['billing_provider']; type BillingProvider = Database['public']['Enums']['billing_provider'];
const Fallback = (
<LoadingOverlay fullPage={false}>Loading Checkout...</LoadingOverlay>
);
export function EmbeddedCheckout( export function EmbeddedCheckout(
props: React.PropsWithChildren<{ props: React.PropsWithChildren<{
checkoutToken: string; checkoutToken: string;
@@ -11,7 +16,10 @@ export function EmbeddedCheckout(
onClose?: () => void; onClose?: () => void;
}>, }>,
) { ) {
const CheckoutComponent = loadCheckoutComponent(props.provider); const CheckoutComponent = useMemo(
() => memo(loadCheckoutComponent(props.provider)),
[],
);
return ( return (
<CheckoutComponent <CheckoutComponent
@@ -24,10 +32,12 @@ export function EmbeddedCheckout(
function loadCheckoutComponent(provider: BillingProvider) { function loadCheckoutComponent(provider: BillingProvider) {
switch (provider) { switch (provider) {
case 'stripe': { case 'stripe': {
return lazy(() => { return buildLazyComponent(() => {
return import('@kit/stripe/components').then((c) => ({ return import('@kit/stripe/components').then(({ StripeCheckout }) => {
default: c.StripeCheckout, return {
})); default: StripeCheckout,
};
});
}); });
} }
@@ -43,3 +53,33 @@ function loadCheckoutComponent(provider: BillingProvider) {
throw new Error(`Unsupported provider: ${provider as string}`); throw new Error(`Unsupported provider: ${provider as string}`);
} }
} }
function buildLazyComponent<
Cmp extends React.ComponentType<
React.PropsWithChildren<{
onClose?: (() => unknown) | undefined;
checkoutToken: string;
}>
>,
>(
load: () => Promise<{
default: Cmp;
}>,
fallback = Fallback,
) {
let LoadedComponent: ReturnType<typeof lazy> | null = null;
const LazyComponent = forwardRef((props, ref) => {
if (!LoadedComponent) {
LoadedComponent = lazy(load);
}
return (
<Suspense fallback={fallback}>
<LoadedComponent {...props} ref={ref} />
</Suspense>
);
});
return memo(LazyComponent);
}

View File

@@ -2,3 +2,4 @@ export * from './plan-picker';
export * from './current-plan-card'; export * from './current-plan-card';
export * from './embedded-checkout'; export * from './embedded-checkout';
export * from './billing-session-status'; export * from './billing-session-status';
export * from './billing-portal-card';

View File

@@ -1,7 +1,7 @@
'use client'; 'use client';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { ArrowRightIcon } from 'lucide-react'; import { ArrowRight } from 'lucide-react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { z } from 'zod'; import { z } from 'zod';
@@ -212,7 +212,7 @@ export function PlanPicker(
) : ( ) : (
<> <>
<span>Proceed to payment</span> <span>Proceed to payment</span>
<ArrowRightIcon className={'ml-2 h-4 w-4'} /> <ArrowRight className={'ml-2 h-4 w-4'} />
</> </>
)} )}
</Button> </Button>

View File

@@ -6,7 +6,7 @@ import { Database } from '@kit/supabase/database';
export class BillingEventHandlerService { export class BillingEventHandlerService {
constructor( constructor(
private readonly client: SupabaseClient<Database>, private readonly clientProvider: () => SupabaseClient<Database>,
private readonly strategy: BillingWebhookHandlerService, private readonly strategy: BillingWebhookHandlerService,
) {} ) {}
@@ -19,6 +19,8 @@ export class BillingEventHandlerService {
return this.strategy.handleWebhookEvent(event, { return this.strategy.handleWebhookEvent(event, {
onSubscriptionDeleted: async (subscriptionId: string) => { onSubscriptionDeleted: async (subscriptionId: string) => {
const client = this.clientProvider();
// Handle the subscription deleted event // Handle the subscription deleted event
// here we delete the subscription from the database // here we delete the subscription from the database
Logger.info( Logger.info(
@@ -29,7 +31,7 @@ export class BillingEventHandlerService {
'Processing subscription deleted event', 'Processing subscription deleted event',
); );
const { error } = await this.client const { error } = await client
.from('subscriptions') .from('subscriptions')
.delete() .delete()
.match({ id: subscriptionId }); .match({ id: subscriptionId });
@@ -47,6 +49,8 @@ export class BillingEventHandlerService {
); );
}, },
onSubscriptionUpdated: async (subscription) => { onSubscriptionUpdated: async (subscription) => {
const client = this.clientProvider();
const ctx = { const ctx = {
namespace: 'billing', namespace: 'billing',
subscriptionId: subscription.id, subscriptionId: subscription.id,
@@ -58,7 +62,7 @@ export class BillingEventHandlerService {
// 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 this.client const { error } = await client
.from('subscriptions') .from('subscriptions')
.update(subscription) .update(subscription)
.match({ id: subscription.id }); .match({ id: subscription.id });
@@ -77,9 +81,11 @@ export class BillingEventHandlerService {
Logger.info(ctx, 'Successfully updated subscription'); Logger.info(ctx, 'Successfully updated subscription');
}, },
onCheckoutSessionCompleted: async (subscription) => { onCheckoutSessionCompleted: async (subscription, customerId) => {
// Handle the checkout session completed event // Handle the checkout session completed event
// here we add the subscription to the database // here we add the subscription to the database
const client = this.clientProvider();
const ctx = { const ctx = {
namespace: 'billing', namespace: 'billing',
subscriptionId: subscription.id, subscriptionId: subscription.id,
@@ -89,12 +95,21 @@ export class BillingEventHandlerService {
Logger.info(ctx, 'Processing checkout session completed event...'); Logger.info(ctx, 'Processing checkout session completed event...');
const { error } = await this.client.rpc('add_subscription', { const { id, ...data } = subscription;
subscription,
const { error } = await client.rpc('add_subscription', {
...data,
subscription_id: subscription.id,
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) {
Logger.error(ctx, 'Failed to add subscription'); Logger.error({ ...ctx, error }, 'Failed to add subscription');
throw new Error('Failed to add subscription'); throw new Error('Failed to add subscription');
} }

View File

@@ -10,11 +10,11 @@ import { BillingEventHandlerFactoryService } from './billing-gateway-factory.ser
* defined in the host application. * defined in the host application.
*/ */
export async function getBillingEventHandlerService( export async function getBillingEventHandlerService(
client: ReturnType<typeof getSupabaseServerActionClient>, clientProvider: () => ReturnType<typeof getSupabaseServerActionClient>,
provider: Database['public']['Enums']['billing_provider'], provider: Database['public']['Enums']['billing_provider'],
) { ) {
const strategy = const strategy =
await BillingEventHandlerFactoryService.GetProviderStrategy(provider); await BillingEventHandlerFactoryService.GetProviderStrategy(provider);
return new BillingEventHandlerService(client, strategy); return new BillingEventHandlerService(clientProvider, strategy);
} }

View File

@@ -4,7 +4,7 @@ import { useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { CheckCircleIcon, SparklesIcon } from 'lucide-react'; import { CheckCircle, Sparkles } from 'lucide-react';
import { z } from 'zod'; import { z } from 'zod';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
@@ -147,7 +147,7 @@ function PricingItem(
)} )}
> >
<If condition={highlighted}> <If condition={highlighted}>
<SparklesIcon className={'mr-1 h-4 w-4'} /> <Sparkles className={'mr-1 h-4 w-4'} />
</If> </If>
<span>{props.product.badge}</span> <span>{props.product.badge}</span>
@@ -238,7 +238,7 @@ function ListItem({ children }: React.PropsWithChildren) {
return ( return (
<li className={'flex items-center space-x-3 font-medium'}> <li className={'flex items-center space-x-3 font-medium'}>
<div> <div>
<CheckCircleIcon className={'h-5 text-green-500'} /> <CheckCircle className={'h-5 text-green-500'} />
</div> </div>
<span className={'text-muted-foreground text-sm'}>{children}</span> <span className={'text-muted-foreground text-sm'}>{children}</span>
@@ -275,7 +275,7 @@ function PlanIntervalSwitcher(
> >
<span className={'flex items-center space-x-1'}> <span className={'flex items-center space-x-1'}>
<If condition={selected}> <If condition={selected}>
<CheckCircleIcon className={'h-4 text-green-500'} /> <CheckCircle className={'h-4 text-green-500'} />
</If> </If>
<span className={'capitalize'}> <span className={'capitalize'}>

View File

@@ -2,11 +2,6 @@ import { Database } from '@kit/supabase/database';
type SubscriptionObject = Database['public']['Tables']['subscriptions']; type SubscriptionObject = Database['public']['Tables']['subscriptions'];
type SubscriptionInsertParams = Omit<
SubscriptionObject['Insert'],
'billing_customer_id'
>;
type SubscriptionUpdateParams = SubscriptionObject['Update']; type SubscriptionUpdateParams = SubscriptionObject['Update'];
/** /**
@@ -19,7 +14,8 @@ export abstract class BillingWebhookHandlerService {
event: unknown, event: unknown,
params: { params: {
onCheckoutSessionCompleted: ( onCheckoutSessionCompleted: (
subscription: SubscriptionInsertParams, subscription: SubscriptionObject['Row'],
customerId: string,
) => Promise<unknown>; ) => Promise<unknown>;
onSubscriptionUpdated: ( onSubscriptionUpdated: (

View File

@@ -3,7 +3,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { CaretSortIcon, PersonIcon } from '@radix-ui/react-icons'; import { CaretSortIcon, PersonIcon } from '@radix-ui/react-icons';
import { CheckIcon, PlusIcon } from 'lucide-react'; import { Check, Plus } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@kit/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from '@kit/ui/avatar';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
@@ -19,7 +19,7 @@ import { If } from '@kit/ui/if';
import { Popover, PopoverContent, PopoverTrigger } from '@kit/ui/popover'; import { Popover, PopoverContent, PopoverTrigger } from '@kit/ui/popover';
import { cn } from '@kit/ui/utils'; import { cn } from '@kit/ui/utils';
import { CreateOrganizationAccountDialog } from './create-organization-account-dialog'; import { CreateTeamAccountDialog } from '../../../team-accounts/src/components/create-team-account-dialog';
interface AccountSelectorProps { interface AccountSelectorProps {
accounts: Array<{ accounts: Array<{
@@ -64,7 +64,7 @@ export function AccountSelector({
const Icon = (props: { item: string }) => { const Icon = (props: { item: string }) => {
return ( return (
<CheckIcon <Check
className={cn( className={cn(
'ml-auto h-4 w-4', 'ml-auto h-4 w-4',
value === props.item ? 'opacity-100' : 'opacity-0', value === props.item ? 'opacity-100' : 'opacity-0',
@@ -196,7 +196,7 @@ export function AccountSelector({
setOpen(false); setOpen(false);
}} }}
> >
<PlusIcon className="mr-2 h-4 w-4" /> <Plus className="mr-2 h-4 w-4" />
<span>Create Organization</span> <span>Create Organization</span>
</Button> </Button>
@@ -208,7 +208,7 @@ export function AccountSelector({
</Popover> </Popover>
<If condition={features.enableOrganizationCreation}> <If condition={features.enableOrganizationCreation}>
<CreateOrganizationAccountDialog <CreateTeamAccountDialog
isOpen={isCreatingAccount} isOpen={isCreatingAccount}
setIsOpen={setIsCreatingAccount} setIsOpen={setIsCreatingAccount}
/> />

View File

@@ -7,11 +7,11 @@ import Link from 'next/link';
import type { Session } from '@supabase/gotrue-js'; import type { Session } from '@supabase/gotrue-js';
import { import {
EllipsisVerticalIcon, EllipsisVertical,
HomeIcon, Home,
LogOutIcon, LogOut,
MessageCircleQuestionIcon, MessageCircleQuestion,
ShieldIcon, Shield,
} from 'lucide-react'; } from 'lucide-react';
import { import {
@@ -87,7 +87,7 @@ export function PersonalAccountDropdown({
</span> </span>
</div> </div>
<EllipsisVerticalIcon <EllipsisVertical
className={'text-muted-foreground hidden h-8 group-hover:flex'} className={'text-muted-foreground hidden h-8 group-hover:flex'}
/> />
</If> </If>
@@ -119,7 +119,7 @@ export function PersonalAccountDropdown({
className={'s-full flex items-center space-x-2'} className={'s-full flex items-center space-x-2'}
href={paths.home} href={paths.home}
> >
<HomeIcon className={'h-5'} /> <Home className={'h-5'} />
<span> <span>
<Trans i18nKey={'common:homeTabLabel'} /> <Trans i18nKey={'common:homeTabLabel'} />
@@ -131,7 +131,7 @@ export function PersonalAccountDropdown({
<DropdownMenuItem asChild> <DropdownMenuItem asChild>
<Link className={'s-full flex items-center space-x-2'} href={'/docs'}> <Link className={'s-full flex items-center space-x-2'} href={'/docs'}>
<MessageCircleQuestionIcon className={'h-5'} /> <MessageCircleQuestion className={'h-5'} />
<span> <span>
<Trans i18nKey={'common:documentation'} /> <Trans i18nKey={'common:documentation'} />
@@ -147,7 +147,7 @@ export function PersonalAccountDropdown({
className={'s-full flex items-center space-x-2'} className={'s-full flex items-center space-x-2'}
href={'/admin'} href={'/admin'}
> >
<ShieldIcon className={'h-5'} /> <Shield className={'h-5'} />
<span>Admin</span> <span>Admin</span>
</Link> </Link>
@@ -162,7 +162,7 @@ export function PersonalAccountDropdown({
onClick={signOutRequested} onClick={signOutRequested}
> >
<span className={'flex w-full items-center space-x-2'}> <span className={'flex w-full items-center space-x-2'}>
<LogOutIcon className={'h-5'} /> <LogOut className={'h-5'} />
<span> <span>
<Trans i18nKey={'auth:signOut'} /> <Trans i18nKey={'auth:signOut'} />

View File

@@ -18,6 +18,8 @@ import { Heading } from '@kit/ui/heading';
import { Input } from '@kit/ui/input'; import { Input } from '@kit/ui/input';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
import { deletePersonalAccountAction } from '../../server/personal-accounts-server-actions';
export function AccountDangerZone() { export function AccountDangerZone() {
return <DeleteAccountContainer />; return <DeleteAccountContainer />;
} }
@@ -72,7 +74,7 @@ function DeleteAccountForm() {
return ( return (
<Form {...form}> <Form {...form}>
<form <form
action={deleteUserAccountAction} action={deletePersonalAccountAction}
className={'flex flex-col space-y-4'} className={'flex flex-col space-y-4'}
> >
<div className={'flex flex-col space-y-6'}> <div className={'flex flex-col space-y-6'}>
@@ -99,6 +101,7 @@ function DeleteAccountForm() {
<Input <Input
data-test={'delete-account-input-field'} data-test={'delete-account-input-field'}
required required
name={'confirmation'}
type={'text'} type={'text'}
className={'w-full'} className={'w-full'}
placeholder={''} placeholder={''}

View File

@@ -9,7 +9,7 @@ export function UpdateEmailFormContainer(props: { callbackPath: string }) {
const { data: user, isPending } = useUser(); const { data: user, isPending } = useUser();
if (isPending) { if (isPending) {
return <LoadingOverlay />; return <LoadingOverlay fullPage={false} />;
} }
if (!user) { if (!user) {

View File

@@ -15,7 +15,7 @@ export function UpdatePasswordFormContainer(
const { data: user, isPending } = useUser(); const { data: user, isPending } = useUser();
if (isPending) { if (isPending) {
return <LoadingOverlay />; return <LoadingOverlay fullPage={false} />;
} }
const canUpdatePassword = user.identities?.some( const canUpdatePassword = user.identities?.some(

View File

@@ -1,69 +0,0 @@
'use server';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { Logger } from '@kit/shared/logger';
import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { CreateOrganizationAccountSchema } from '../schema/create-organization.schema';
import { AccountsService } from './services/accounts.service';
const ORGANIZATION_ACCOUNTS_PATH = z
.string({
required_error: 'Organization accounts path is required',
})
.min(1)
.parse(process.env.ORGANIZATION_ACCOUNTS_PATH);
export async function createOrganizationAccountAction(
params: z.infer<typeof CreateOrganizationAccountSchema>,
) {
const { name: accountName } = CreateOrganizationAccountSchema.parse(params);
const client = getSupabaseServerActionClient();
const accountsService = new AccountsService(client);
const session = await requireAuth(client);
if (session.error) {
redirect(session.redirectTo);
}
const createAccountResponse =
await accountsService.createNewOrganizationAccount({
name: accountName,
userId: session.data.user.id,
});
if (createAccountResponse.error) {
return handleError(
createAccountResponse.error,
`Error creating organization`,
);
}
const accountHomePath =
ORGANIZATION_ACCOUNTS_PATH + createAccountResponse.data.slug;
redirect(accountHomePath);
}
function handleError<Error = unknown>(
error: Error,
message: string,
organizationId?: string,
) {
const exception = error instanceof Error ? error.message : undefined;
Logger.error(
{
exception,
organizationId,
},
message,
);
throw new Error(message);
}

View File

@@ -0,0 +1,63 @@
'use server';
import { redirect } from 'next/navigation';
import { Logger } from '@kit/shared/logger';
import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { PersonalAccountsService } from './services/personal-accounts.service';
export async function deletePersonalAccountAction(formData: FormData) {
const confirmation = formData.get('confirmation');
if (confirmation !== 'DELETE') {
throw new Error('Confirmation required to delete account');
}
const session = await requireAuth(getSupabaseServerActionClient());
if (session.error) {
redirect(session.redirectTo);
}
const client = getSupabaseServerActionClient();
const service = new PersonalAccountsService(client);
const userId = session.data.user.id;
Logger.info(
{
userId,
name: 'accounts',
},
`Deleting personal account...`,
);
const deleteAccountResponse = await service.deletePersonalAccount({
userId,
});
if (deleteAccountResponse.error) {
Logger.error(
{
error: deleteAccountResponse.error,
name: 'accounts',
},
`Error deleting personal account`,
);
throw new Error('Error deleting personal account');
}
Logger.info(
{
userId,
name: 'accounts',
},
`Personal account deleted successfully.`,
);
await client.auth.signOut();
redirect('/');
}

View File

@@ -1,46 +0,0 @@
import { SupabaseClient } from '@supabase/supabase-js';
import { Logger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
/**
* @name AccountsService
* @description Service for managing accounts in the application
* @param Database - The Supabase database type to use
* @example
* const client = getSupabaseClient();
* const accountsService = new AccountsService(client);
*
* accountsService.createNewOrganizationAccount({
* name: 'My Organization',
* userId: '123',
* });
*/
export class AccountsService {
private readonly logger = new AccountsServiceLogger();
constructor(private readonly client: SupabaseClient<Database>) {}
createNewOrganizationAccount(params: { name: string; userId: string }) {
this.logger.logCreateNewOrganizationAccount(params);
return this.client.rpc('create_account', {
account_name: params.name,
});
}
}
class AccountsServiceLogger {
private namespace = 'accounts';
logCreateNewOrganizationAccount(params: { name: string; userId: string }) {
Logger.info(
this.withNamespace(params),
`Creating new organization account...`,
);
}
private withNamespace(params: object) {
return { ...params, name: this.namespace };
}
}

View File

@@ -0,0 +1,17 @@
import { SupabaseClient } from '@supabase/supabase-js';
import { Database } from '@kit/supabase/database';
/**
* @name PersonalAccountsService
* @description Service for managing accounts in the application
* @param Database - The Supabase database type to use
* @example
* const client = getSupabaseClient();
* const accountsService = new AccountsService(client);
*/
export class PersonalAccountsService {
constructor(private readonly client: SupabaseClient<Database>) {}
async deletePersonalAccount(param: { userId: string }) {}
}

View File

@@ -9,10 +9,30 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"prettier": "@kit/prettier-config", "prettier": "@kit/prettier-config",
"peerDependencies": {
"@kit/ui": "0.1.0"
},
"devDependencies": {
"@kit/eslint-config": "0.2.0",
"@kit/prettier-config": "0.1.0",
"@kit/tailwind-config": "0.1.0",
"@kit/tsconfig": "0.1.0"
},
"exports": { "exports": {
".": "./src/index.ts" ".": "./src/index.ts"
}, },
"devDependencies": { "eslintConfig": {
"@kit/prettier-config": "0.1.0" "root": true,
"extends": [
"@kit/eslint-config/base",
"@kit/eslint-config/react"
]
},
"typesVersions": {
"*": {
"*": [
"src/*"
]
}
} }
} }

View File

@@ -1,20 +1,27 @@
import Link from 'next/link'; import Link from 'next/link';
import { PageHeader } from '@/components/app/Page'; import { ArrowLeft } from 'lucide-react';
import pathsConfig from '@/config/paths.config';
import { ArrowLeftIcon } from 'lucide-react';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
import { PageHeader } from '@kit/ui/page';
function AdminHeader({ children }: React.PropsWithChildren) { function AdminHeader({
children,
paths,
}: React.PropsWithChildren<{
appHome: string;
paths: {
appHome: string;
};
}>) {
return ( return (
<PageHeader <PageHeader
title={children} title={children}
description={`Manage your app from the admin dashboard.`} description={`Manage your app from the admin dashboard.`}
> >
<Link href={pathsConfig.appHome}> <Link href={paths.appHome}>
<Button variant={'link'}> <Button variant={'link'}>
<ArrowLeftIcon className={'h-4'} /> <ArrowLeft className={'h-4'} />
<span>Back to App</span> <span>Back to App</span>
</Button> </Button>
</Link> </Link>

View File

@@ -1,31 +1,26 @@
'use client'; 'use client';
import Logo from '@/components/app/Logo'; import { Home, User, Users } from 'lucide-react';
import { Sidebar, SidebarContent, SidebarItem } from '@/components/app/Sidebar';
import { HomeIcon, UserIcon, UsersIcon } from 'lucide-react';
function AdminSidebar() { import { Sidebar, SidebarContent, SidebarItem } from '@kit/ui/sidebar';
function AdminSidebar(props: { Logo: React.ReactNode }) {
return ( return (
<Sidebar> <Sidebar>
<SidebarContent className={'mb-6 mt-4 pt-2'}> <SidebarContent className={'mb-6 mt-4 pt-2'}>{props.Logo}</SidebarContent>
<Logo href={'/admin'} />
</SidebarContent>
<SidebarContent> <SidebarContent>
<SidebarItem end path={'/admin'} Icon={<HomeIcon className={'h-4'} />}> <SidebarItem end path={'/admin'} Icon={<Home className={'h-4'} />}>
Admin Admin
</SidebarItem> </SidebarItem>
<SidebarItem <SidebarItem path={'/admin/users'} Icon={<User className={'h-4'} />}>
path={'/admin/users'}
Icon={<UserIcon className={'h-4'} />}
>
Users Users
</SidebarItem> </SidebarItem>
<SidebarItem <SidebarItem
path={'/admin/organizations'} path={'/admin/organizations'}
Icon={<UsersIcon className={'h-4'} />} Icon={<Users className={'h-4'} />}
> >
Organizations Organizations
</SidebarItem> </SidebarItem>

View File

@@ -15,7 +15,6 @@
"./shared": "./src/shared.ts", "./shared": "./src/shared.ts",
"./mfa": "./src/mfa.ts" "./mfa": "./src/mfa.ts"
}, },
"dependencies": {},
"devDependencies": { "devDependencies": {
"@kit/prettier-config": "0.1.0", "@kit/prettier-config": "0.1.0",
"@kit/eslint-config": "0.2.0", "@kit/eslint-config": "0.2.0",

View File

@@ -1,10 +1,12 @@
'use client';
import type { FormEventHandler } from 'react'; import type { FormEventHandler } from 'react';
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
import useFetchAuthFactors from '@kit/supabase/hooks/use-fetch-mfa-factors'; import useFetchAuthFactors from '@kit/supabase/hooks/use-fetch-mfa-factors';
import useSignOut from '@kit/supabase/hooks/use-sign-out'; import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
import { useSupabase } from '@kit/supabase/hooks/use-supabase'; import { useSupabase } from '@kit/supabase/hooks/use-supabase';
import { Alert, AlertDescription } from '@kit/ui/alert'; import { Alert, AlertDescription } from '@kit/ui/alert';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';

View File

@@ -1,6 +1,6 @@
import Image from 'next/image'; import Image from 'next/image';
import { AtSignIcon, PhoneIcon } from 'lucide-react'; import { AtSign, Phone } from 'lucide-react';
const DEFAULT_IMAGE_SIZE = 18; const DEFAULT_IMAGE_SIZE = 18;
@@ -29,8 +29,8 @@ export const OauthProviderLogoImage: React.FC<{
function getOAuthProviderLogos(): Record<string, string | React.ReactNode> { function getOAuthProviderLogos(): Record<string, string | React.ReactNode> {
return { return {
password: <AtSignIcon className={'s-[18px]'} />, password: <AtSign className={'s-[18px]'} />,
phone: <PhoneIcon className={'s-[18px]'} />, phone: <Phone className={'s-[18px]'} />,
google: '/assets/images/google.webp', google: '/assets/images/google.webp',
facebook: '/assets/images/facebook.webp', facebook: '/assets/images/facebook.webp',
twitter: '/assets/images/twitter.webp', twitter: '/assets/images/twitter.webp',

View File

@@ -2,7 +2,7 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { CheckIcon } from 'lucide-react'; import { Check } from 'lucide-react';
import { useSignUpWithEmailAndPassword } from '@kit/supabase/hooks/use-sign-up-with-email-password'; import { useSignUpWithEmailAndPassword } from '@kit/supabase/hooks/use-sign-up-with-email-password';
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert'; import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
@@ -66,7 +66,7 @@ export function EmailPasswordSignUpContainer({
<> <>
<If condition={showVerifyEmailAlert}> <If condition={showVerifyEmailAlert}>
<Alert variant={'success'}> <Alert variant={'success'}>
<CheckIcon className={'w-4'} /> <Check className={'w-4'} />
<AlertTitle> <AlertTitle>
<Trans i18nKey={'auth:emailConfirmationAlertHeading'} /> <Trans i18nKey={'auth:emailConfirmationAlertHeading'} />

View File

@@ -11,15 +11,6 @@
"exports": { "exports": {
"./components": "./src/components/index.ts" "./components": "./src/components/index.ts"
}, },
"dependencies": {
"@kit/supabase": "0.1.0",
"@kit/ui": "0.1.0",
"@kit/shared": "0.1.0",
"@kit/accounts": "0.1.0",
"@kit/mailers": "0.1.0",
"@kit/emails": "0.1.0",
"lucide-react": "^0.360.0"
},
"devDependencies": { "devDependencies": {
"@kit/eslint-config": "0.2.0", "@kit/eslint-config": "0.2.0",
"@kit/prettier-config": "0.1.0", "@kit/prettier-config": "0.1.0",
@@ -28,7 +19,14 @@
}, },
"peerDependencies": { "peerDependencies": {
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0",
"@kit/supabase": "0.1.0",
"@kit/ui": "0.1.0",
"@kit/shared": "0.1.0",
"@kit/accounts": "0.1.0",
"@kit/mailers": "0.1.0",
"@kit/emails": "0.1.0",
"lucide-react": "^0.360.0"
}, },
"prettier": "@kit/prettier-config", "prettier": "@kit/prettier-config",
"eslintConfig": { "eslintConfig": {

View File

@@ -0,0 +1,58 @@
'use server';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { Logger } from '@kit/shared/logger';
import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import { CreateTeamSchema } from '../schema/create-team.schema';
import { CreateTeamAccountService } from '../services/create-team-account.service';
const TEAM_ACCOUNTS_HOME_PATH = z
.string({
required_error: 'variable TEAM_ACCOUNTS_HOME_PATH is required',
})
.min(1)
.parse(process.env.TEAM_ACCOUNTS_HOME_PATH);
export async function createOrganizationAccountAction(
params: z.infer<typeof CreateTeamSchema>,
) {
const { name: accountName } = CreateTeamSchema.parse(params);
const client = getSupabaseServerActionClient();
const service = new CreateTeamAccountService(client);
const session = await requireAuth(client);
if (session.error) {
redirect(session.redirectTo);
}
const userId = session.data.user.id;
const createAccountResponse = await service.createNewOrganizationAccount({
name: accountName,
userId,
});
if (createAccountResponse.error) {
Logger.error(
{
userId,
error: createAccountResponse.error,
name: 'accounts',
},
`Error creating organization account`,
);
throw new Error('Error creating organization account');
}
const accountHomePath =
TEAM_ACCOUNTS_HOME_PATH + '/' + createAccountResponse.data.slug;
redirect(accountHomePath);
}

View File

@@ -20,10 +20,10 @@ import { If } from '@kit/ui/if';
import { Input } from '@kit/ui/input'; import { Input } from '@kit/ui/input';
import { Trans } from '@kit/ui/trans'; import { Trans } from '@kit/ui/trans';
import { CreateOrganizationAccountSchema } from '../schema/create-organization.schema'; import { createOrganizationAccountAction } from '../actions/create-team-account-server-actions';
import { createOrganizationAccountAction } from '../server/accounts-server-actions'; import { CreateTeamSchema } from '../schema/create-team.schema';
export function CreateOrganizationAccountDialog( export function CreateTeamAccountDialog(
props: React.PropsWithChildren<{ props: React.PropsWithChildren<{
isOpen: boolean; isOpen: boolean;
setIsOpen: (isOpen: boolean) => void; setIsOpen: (isOpen: boolean) => void;
@@ -46,11 +46,11 @@ function CreateOrganizationAccountForm() {
const [error, setError] = useState<boolean>(); const [error, setError] = useState<boolean>();
const [pending, startTransition] = useTransition(); const [pending, startTransition] = useTransition();
const form = useForm<z.infer<typeof CreateOrganizationAccountSchema>>({ const form = useForm<z.infer<typeof CreateTeamSchema>>({
defaultValues: { defaultValues: {
name: '', name: '',
}, },
resolver: zodResolver(CreateOrganizationAccountSchema), resolver: zodResolver(CreateTeamSchema),
}); });
return ( return (

View File

@@ -3,7 +3,7 @@
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef } from '@tanstack/react-table';
import { EllipsisIcon } from 'lucide-react'; import { Ellipsis } from 'lucide-react';
import { Database } from '@kit/supabase/database'; import { Database } from '@kit/supabase/database';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
@@ -126,7 +126,7 @@ function ActionsDropdown({
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant={'ghost'} size={'icon'}> <Button variant={'ghost'} size={'icon'}>
<EllipsisIcon className={'h-5 w-5'} /> <Ellipsis className={'h-5 w-5'} />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>

View File

@@ -17,7 +17,7 @@ import { deleteInvitationAction } from '../../actions/account-invitations-server
export const DeleteInvitationDialog: React.FC<{ export const DeleteInvitationDialog: React.FC<{
isOpen: boolean; isOpen: boolean;
setIsOpen: (isOpen: boolean) => void; setIsOpen: (isOpen: boolean) => void;
invitationId: string; invitationId: number;
}> = ({ isOpen, setIsOpen, invitationId }) => { }> = ({ isOpen, setIsOpen, invitationId }) => {
return ( return (
<Dialog open={isOpen} onOpenChange={setIsOpen}> <Dialog open={isOpen} onOpenChange={setIsOpen}>
@@ -45,7 +45,7 @@ function DeleteInvitationForm({
invitationId, invitationId,
setIsOpen, setIsOpen,
}: { }: {
invitationId: string; invitationId: number;
setIsOpen: (isOpen: boolean) => void; setIsOpen: (isOpen: boolean) => void;
}) { }) {
const [isSubmitting, startTransition] = useTransition(); const [isSubmitting, startTransition] = useTransition();

View File

@@ -3,7 +3,7 @@
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { ColumnDef } from '@tanstack/react-table'; import { ColumnDef } from '@tanstack/react-table';
import { EllipsisIcon } from 'lucide-react'; import { Ellipsis } from 'lucide-react';
import { Database } from '@kit/supabase/database'; import { Database } from '@kit/supabase/database';
import { Button } from '@kit/ui/button'; import { Button } from '@kit/ui/button';
@@ -189,7 +189,7 @@ function ActionsDropdown({
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant={'ghost'} size={'icon'}> <Button variant={'ghost'} size={'icon'}>
<EllipsisIcon className={'h-5 w-5'} /> <Ellipsis className={'h-5 w-5'} />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>

View File

@@ -3,7 +3,7 @@
import { useState, useTransition } from 'react'; import { useState, useTransition } from 'react';
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from '@hookform/resolvers/zod';
import { PlusIcon, XIcon } from 'lucide-react'; import { Plus, X } from 'lucide-react';
import { useFieldArray, useForm } from 'react-hook-form'; import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -181,7 +181,7 @@ function InviteMembersForm({
form.clearErrors(emailInputName); form.clearErrors(emailInputName);
}} }}
> >
<XIcon className={'h-4 lg:h-5'} /> <X className={'h-4 lg:h-5'} />
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -208,7 +208,7 @@ function InviteMembersForm({
}} }}
> >
<span className={'flex items-center space-x-2'}> <span className={'flex items-center space-x-2'}>
<PlusIcon className={'h-4'} /> <Plus className={'h-4'} />
<span> <span>
<Trans i18nKey={'organization:addAnotherMemberButtonLabel'} /> <Trans i18nKey={'organization:addAnotherMemberButtonLabel'} />

View File

@@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
export const CreateOrganizationAccountSchema = z.object({ export const CreateTeamSchema = z.object({
name: z.string().min(2).max(50), name: z.string().min(2).max(50),
}); });

View File

@@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
export const DeleteInvitationSchema = z.object({ export const DeleteInvitationSchema = z.object({
invitationId: z.bigint(), invitationId: z.number().int(),
}); });

View File

@@ -0,0 +1,21 @@
import { SupabaseClient } from '@supabase/supabase-js';
import { Logger } from '@kit/shared/logger';
import { Database } from '@kit/supabase/database';
export class CreateTeamAccountService {
private readonly namespace = 'accounts.create-team-account';
constructor(private readonly client: SupabaseClient<Database>) {}
createNewOrganizationAccount(params: { name: string; userId: string }) {
Logger.info(
{ ...params, namespace: this.namespace },
`Creating new organization account...`,
);
return this.client.rpc('create_account', {
account_name: params.name,
});
}
}

View File

@@ -10,8 +10,7 @@
}, },
"prettier": "@kit/prettier-config", "prettier": "@kit/prettier-config",
"exports": { "exports": {
"./mailer": "./src/mailer.ts", "./logger": "./src/logger/index.ts",
"./logger": "./src/logger.ts",
"./hooks/*": "./src/hooks/*.ts", "./hooks/*": "./src/hooks/*.ts",
"./contexts/*": "./src/contexts/*.ts", "./contexts/*": "./src/contexts/*.ts",
"./cookies/*": "./src/cookies/*.ts", "./cookies/*": "./src/cookies/*.ts",

View File

@@ -0,0 +1,6 @@
/*
* Logger
* By default, the logger is set to use Pino. To change the logger, update the import statement below.
* to your desired logger implementation.
*/
export * from './impl/pino';

View File

@@ -7,7 +7,8 @@
"clean": "git clean -xdf .turbo node_modules", "clean": "git clean -xdf .turbo node_modules",
"format": "prettier --check \"**/*.{ts,tsx}\"", "format": "prettier --check \"**/*.{ts,tsx}\"",
"lint": "eslint .", "lint": "eslint .",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit",
"start": "docker run --rm -it --name=stripe -v ~/.config/stripe:/root/.config/stripe stripe/stripe-cli:latest listen --forward-to http://host.docker.internal:3000/api/billing/webhook"
}, },
"prettier": "@kit/prettier-config", "prettier": "@kit/prettier-config",
"exports": { "exports": {

View File

@@ -2,6 +2,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { invariant } from '@epic-web/invariant';
import { import {
EmbeddedCheckout, EmbeddedCheckout,
EmbeddedCheckoutProvider, EmbeddedCheckoutProvider,
@@ -14,15 +15,10 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@kit/ui/dialog'; } from '@kit/ui/dialog';
import { cn } from '@kit/ui/utils';
const STRIPE_PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY; const STRIPE_PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
if (!STRIPE_PUBLISHABLE_KEY) { invariant(STRIPE_PUBLISHABLE_KEY, 'Stripe publishable key is required');
throw new Error(
'Missing NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY environment variable. Did you forget to add it to your .env file?',
);
}
const stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY); const stripePromise = loadStripe(STRIPE_PUBLISHABLE_KEY);
@@ -52,11 +48,7 @@ function EmbeddedCheckoutPopup({
onClose?: () => void; onClose?: () => void;
}>) { }>) {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
const className = `bg-white p-4 max-h-[98vh] overflow-y-auto shadow-transparent border`;
const className = cn({
[`bg-white p-4 max-h-[98vh] overflow-y-auto shadow-transparent border border-gray-200 dark:border-dark-700`]:
true,
});
return ( return (
<Dialog <Dialog

View File

@@ -4,20 +4,19 @@ import { StripeServerEnvSchema } from '../schema/stripe-server-env.schema';
const STRIPE_API_VERSION = '2023-10-16'; const STRIPE_API_VERSION = '2023-10-16';
// Parse the environment variables and validate them
const stripeServerEnv = StripeServerEnvSchema.parse({
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
});
/** /**
* @description returns a Stripe instance * @description returns a Stripe instance
*/ */
export async function createStripeClient() { export async function createStripeClient() {
const { default: Stripe } = await import('stripe'); const { default: Stripe } = await import('stripe');
const key = stripeServerEnv.STRIPE_SECRET_KEY;
return new Stripe(key, { // Parse the environment variables and validate them
const stripeServerEnv = StripeServerEnvSchema.parse({
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
});
return new Stripe(stripeServerEnv.STRIPE_SECRET_KEY, {
apiVersion: STRIPE_API_VERSION, apiVersion: STRIPE_API_VERSION,
}); });
} }

View File

@@ -29,9 +29,11 @@ export class StripeWebhookHandlerService
*/ */
async verifyWebhookSignature(request: Request) { async verifyWebhookSignature(request: Request) {
const body = await request.clone().text(); const body = await request.clone().text();
const signature = `stripe-signature`; const signatureKey = `stripe-signature`;
const signature = request.headers.get(signatureKey) as string;
const { STRIPE_WEBHOOK_SECRET } = StripeServerEnvSchema.parse({ const { STRIPE_WEBHOOK_SECRET } = StripeServerEnvSchema.parse({
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET, STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
}); });
@@ -109,7 +111,7 @@ export class StripeWebhookHandlerService
private async handleCheckoutSessionCompleted( private async handleCheckoutSessionCompleted(
event: Stripe.CheckoutSessionCompletedEvent, event: Stripe.CheckoutSessionCompletedEvent,
onCheckoutCompletedCallback: ( onCheckoutCompletedCallback: (
data: InsertSubscriptionParams, data: Omit<Subscription['Insert'], 'billing_customer_id'>,
customerId: string, customerId: string,
) => Promise<unknown>, ) => Promise<unknown>,
) { ) {
@@ -128,11 +130,11 @@ export class StripeWebhookHandlerService
// TODO: convert or store the amount in cents? // TODO: convert or store the amount in cents?
const amount = session.amount_total ?? 0; const amount = session.amount_total ?? 0;
const payload = this.buildSubscriptionPayload<typeof accountId>({ const payload = this.buildSubscriptionPayload({
subscription, subscription,
accountId, accountId,
amount, amount,
}); }) as InsertSubscriptionParams;
return onCheckoutCompletedCallback(payload, customerId); return onCheckoutCompletedCallback(payload, customerId);
} }
@@ -149,7 +151,7 @@ export class StripeWebhookHandlerService
return (acc + (item.plan.amount ?? 0)) * (item.quantity ?? 1); return (acc + (item.plan.amount ?? 0)) * (item.quantity ?? 1);
}, 0); }, 0);
const payload = this.buildSubscriptionPayload<undefined>({ const payload = this.buildSubscriptionPayload({
subscription, subscription,
amount, amount,
}); });
@@ -166,27 +168,27 @@ export class StripeWebhookHandlerService
return onSubscriptionDeletedCallback(subscription.id); return onSubscriptionDeletedCallback(subscription.id);
} }
private buildSubscriptionPayload< private buildSubscriptionPayload(params: {
AccountId extends string | undefined,
>(params: {
subscription: Stripe.Subscription; subscription: Stripe.Subscription;
amount: number; amount: number;
// we only need the account id if we // we only need the account id if we
// are creating a subscription for an account // are creating a subscription for an account
accountId?: AccountId; accountId?: string;
}): AccountId extends string }) {
? InsertSubscriptionParams
: Subscription['Update'] {
const { subscription } = params; const { subscription } = params;
const lineItem = subscription.items.data[0]; const lineItem = subscription.items.data[0];
const price = lineItem?.price; const price = lineItem?.price;
const priceId = price?.id!; const priceId = price?.id!;
const interval = price?.recurring?.interval ?? null; const interval = price?.recurring?.interval ?? null;
const active =
subscription.status === 'active' || subscription.status === 'trialing';
const data = { const data = {
billing_provider: this.provider, billing_provider: this.provider,
id: subscription.id, id: subscription.id,
status: subscription.status, status: subscription.status,
active,
price_amount: params.amount, price_amount: params.amount,
cancel_at_period_end: subscription.cancel_at_period_end ?? false, cancel_at_period_end: subscription.cancel_at_period_end ?? false,
interval: interval as string, interval: interval as string,
@@ -194,15 +196,27 @@ export class StripeWebhookHandlerService
product_id: price?.product as string, product_id: price?.product as string,
variant_id: priceId, variant_id: priceId,
interval_count: price?.recurring?.interval_count ?? 1, 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) { if (params.accountId !== undefined) {
return { return {
...data, ...data,
account_id: params.accountId, account_id: params.accountId,
} satisfies InsertSubscriptionParams; };
} }
return data as Subscription['Update']; // otherwise we are updating a subscription
// and we only need to return the update payload
return data;
} }
} }
function getISOString(date: number | null) {
return date ? new Date(date * 1000).toISOString() : null;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,20 @@
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useSupabase } from './use-supabase'; import { useSupabase } from './use-supabase';
export function useUser() { export function useUser() {
const client = useSupabase(); const client = useSupabase();
const router = useRouter();
const queryKey = ['user']; const queryKey = ['user'];
const queryFn = async () => { const queryFn = async () => {
const response = await client.auth.getUser(); const response = await client.auth.getUser();
// this is most likely a session error or the user is not logged in
if (response.error) { if (response.error) {
return Promise.reject(response.error); throw router.replace('/');
} }
if (response.data?.user) { if (response.data?.user) {

View File

@@ -25,7 +25,6 @@
"@radix-ui/react-alert-dialog": "^1.0.5", "@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-navigation-menu": "^1.1.4", "@radix-ui/react-navigation-menu": "^1.1.4",
"@radix-ui/react-separator": "^1.0.3", "@radix-ui/react-separator": "^1.0.3",
"class-variance-authority": "^0.7.0",
"react-top-loading-bar": "2.3.1", "react-top-loading-bar": "2.3.1",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"cmdk": "^0.2.0", "cmdk": "^0.2.0",
@@ -37,7 +36,8 @@
"@radix-ui/react-icons": "1.3.0", "@radix-ui/react-icons": "1.3.0",
"zod": "^3.22.4", "zod": "^3.22.4",
"sonner": "^1.4.41", "sonner": "^1.4.41",
"lucide-react": "0.307.0" "lucide-react": "0.307.0",
"class-variance-authority": "^0.7.0"
}, },
"devDependencies": { "devDependencies": {
"@kit/eslint-config": "0.2.0", "@kit/eslint-config": "0.2.0",

View File

@@ -18,12 +18,11 @@ import type {
SortingState, SortingState,
VisibilityState, VisibilityState,
} from '@tanstack/react-table'; } from '@tanstack/react-table';
import classNames from 'clsx';
import { import {
ChevronLeftIcon, ChevronLeft,
ChevronRightIcon, ChevronRight,
ChevronsLeftIcon, ChevronsLeft,
ChevronsRightIcon, ChevronsRight,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '../shadcn/button'; import { Button } from '../shadcn/button';
@@ -36,6 +35,7 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from '../shadcn/table'; } from '../shadcn/table';
import { cn } from '../utils';
import Trans from './trans'; import Trans from './trans';
interface ReactTableProps<T extends object> { interface ReactTableProps<T extends object> {
@@ -148,7 +148,7 @@ export function DataTable<T extends object>({
{table.getRowModel().rows.map((row) => ( {table.getRowModel().rows.map((row) => (
<Fragment key={row.id}> <Fragment key={row.id}>
<TableRow <TableRow
className={classNames({ className={cn({
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted': 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted':
row.getIsExpanded(), row.getIsExpanded(),
})} })}
@@ -200,7 +200,7 @@ function Pagination<T>({
onClick={() => table.setPageIndex(0)} onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()} disabled={!table.getCanPreviousPage()}
> >
<ChevronsLeftIcon className={'h-4'} /> <ChevronsLeft className={'h-4'} />
</Button> </Button>
<Button <Button
@@ -208,7 +208,7 @@ function Pagination<T>({
onClick={() => table.previousPage()} onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()} disabled={!table.getCanPreviousPage()}
> >
<ChevronLeftIcon className={'h-4'} /> <ChevronLeft className={'h-4'} />
</Button> </Button>
<Button <Button
@@ -216,7 +216,7 @@ function Pagination<T>({
onClick={() => table.nextPage()} onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()} disabled={!table.getCanNextPage()}
> >
<ChevronRightIcon className={'h-4'} /> <ChevronRight className={'h-4'} />
</Button> </Button>
<Button <Button
@@ -224,7 +224,7 @@ function Pagination<T>({
onClick={() => table.setPageIndex(table.getPageCount() - 1)} onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()} disabled={!table.getCanNextPage()}
> >
<ChevronsRightIcon className={'h-4'} /> <ChevronsRight className={'h-4'} />
</Button> </Button>
<span className="flex items-center text-sm"> <span className="flex items-center text-sm">

View File

@@ -5,11 +5,11 @@ import { forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import Image from 'next/image'; import Image from 'next/image';
import cn from 'clsx'; import { UploadCloud, X } from 'lucide-react';
import { UploadCloud, XIcon } from 'lucide-react';
import { Button } from '../shadcn/button'; import { Button } from '../shadcn/button';
import { Label } from '../shadcn/label'; import { Label } from '../shadcn/label';
import { cn } from '../utils';
import { If } from './if'; import { If } from './if';
type Props = Omit<React.InputHTMLAttributes<unknown>, 'value'> & { type Props = Omit<React.InputHTMLAttributes<unknown>, 'value'> & {
@@ -21,7 +21,7 @@ type Props = Omit<React.InputHTMLAttributes<unknown>, 'value'> & {
const IMAGE_SIZE = 22; const IMAGE_SIZE = 22;
const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>( export const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
function ImageUploadInputComponent( function ImageUploadInputComponent(
{ {
children, children,
@@ -190,7 +190,7 @@ const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
className={'!h-5 !w-5'} className={'!h-5 !w-5'}
onClick={imageRemoved} onClick={imageRemoved}
> >
<XIcon className="h-4" /> <X className="h-4" />
</Button> </Button>
</If> </If>
</div> </div>
@@ -198,4 +198,3 @@ const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
); );
}, },
); );
export default ImageUploadInput;

View File

@@ -4,11 +4,11 @@ import { useCallback, useEffect, useState } from 'react';
import Image from 'next/image'; import Image from 'next/image';
import { ImageIcon } from 'lucide-react'; import { Image as ImageIcon } from 'lucide-react';
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { Button } from '../shadcn/button'; import { Button } from '../shadcn/button';
import ImageUploadInput from './image-upload-input'; import { ImageUploadInput } from './image-upload-input';
import { Trans } from './trans'; import { Trans } from './trans';
function ImageUploader( function ImageUploader(

View File

@@ -5,7 +5,7 @@ import { useMemo } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { ChevronDownIcon } from 'lucide-react'; import { ChevronDown } from 'lucide-react';
import { Button } from '../shadcn/button'; import { Button } from '../shadcn/button';
import { import {
@@ -14,7 +14,7 @@ import {
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
} from '../shadcn/dropdown-menu'; } from '../shadcn/dropdown-menu';
import { Trans } from '../shadcn/trans'; import { Trans } from './trans';
function MobileNavigationDropdown({ function MobileNavigationDropdown({
links, links,
@@ -41,7 +41,7 @@ function MobileNavigationDropdown({
<Trans i18nKey={currentPathName} defaults={currentPathName} /> <Trans i18nKey={currentPathName} defaults={currentPathName} />
</span> </span>
<ChevronDownIcon className={'h-5'} /> <ChevronDown className={'h-5'} />
</span> </span>
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>

View File

@@ -3,7 +3,7 @@ import { useMemo } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { ChevronDownIcon } from 'lucide-react'; import { ChevronDown } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
@@ -11,7 +11,7 @@ import {
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
} from '../shadcn/dropdown-menu'; } from '../shadcn/dropdown-menu';
import { Trans } from '../shadcn/trans'; import { Trans } from './trans';
const MobileNavigationDropdown: React.FC<{ const MobileNavigationDropdown: React.FC<{
links: { links: {
@@ -60,7 +60,7 @@ const MobileNavigationDropdown: React.FC<{
<Trans i18nKey={currentPathName} defaults={currentPathName} /> <Trans i18nKey={currentPathName} defaults={currentPathName} />
</span> </span>
<ChevronDownIcon className={'h-5'} /> <ChevronDown className={'h-5'} />
</span> </span>
</div> </div>
</DropdownMenuTrigger> </DropdownMenuTrigger>

View File

@@ -6,7 +6,7 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { cva } from 'class-variance-authority'; import { cva } from 'class-variance-authority';
import { ChevronDownIcon } from 'lucide-react'; import { ChevronDown } from 'lucide-react';
import { z } from 'zod'; import { z } from 'zod';
import { Button } from '../shadcn/button'; import { Button } from '../shadcn/button';
@@ -111,7 +111,7 @@ export function SidebarGroup({
<Title>{label}</Title> <Title>{label}</Title>
<If condition={collapsible}> <If condition={collapsible}>
<ChevronDownIcon <ChevronDown
className={cn(`h-3 transition duration-300`, { className={cn(`h-3 transition duration-300`, {
'rotate-180': !isGroupCollapsed, 'rotate-180': !isGroupCollapsed,
})} })}

9
pnpm-lock.yaml generated
View File

@@ -334,9 +334,18 @@ importers:
packages/features/admin: packages/features/admin:
devDependencies: devDependencies:
'@kit/eslint-config':
specifier: 0.2.0
version: link:../../../tooling/eslint
'@kit/prettier-config': '@kit/prettier-config':
specifier: 0.1.0 specifier: 0.1.0
version: link:../../../tooling/prettier version: link:../../../tooling/prettier
'@kit/tailwind-config':
specifier: 0.1.0
version: link:../../../tooling/tailwind
'@kit/tsconfig':
specifier: 0.1.0
version: link:../../../tooling/typescript
packages/features/auth: packages/features/auth:
devDependencies: devDependencies:

View File

@@ -313,14 +313,6 @@ create policy accounts_read_self on public.accounts for
select select
to authenticated using (auth.uid () = primary_owner_user_id); to authenticated using (auth.uid () = primary_owner_user_id);
-- RLS on the accounts table
-- SELECT: Users can read the team accounts they are a member of
create policy accounts_read_team on public.accounts for
select
to authenticated using (
has_role_on_account (id)
);
-- UPDATE: Team owners can update their accounts -- UPDATE: Team owners can update their accounts
create policy accounts_self_update on public.accounts create policy accounts_self_update on public.accounts
for update for update
@@ -537,6 +529,14 @@ create policy accounts_memberships_team_read on public.accounts_memberships for
select select
to authenticated using (is_team_member (account_id, user_id)); to authenticated using (is_team_member (account_id, user_id));
-- RLS on the accounts table
-- SELECT: Users can read the team accounts they are a member of
create policy accounts_read_team on public.accounts for
select
to authenticated using (
has_role_on_account (id)
);
-- DELETE: Users can remove themselves from an account -- DELETE: Users can remove themselves from an account
create policy accounts_memberships_delete_self on public.accounts_memberships for create policy accounts_memberships_delete_self on public.accounts_memberships for
delete delete
@@ -628,6 +628,29 @@ update,
delete on table public.role_permissions to authenticated, delete on table public.role_permissions to authenticated,
service_role; service_role;
-- Create a function to check if a user has a permission
create function public.has_permission (
user_id uuid,
account_id uuid,
permission_name app_permissions
) returns boolean as $$
begin
return exists(
select
1
from
public.accounts_memberships
join public.role_permissions on accounts_memberships.account_role = role_permissions.role
where
accounts_memberships.user_id = has_permission.user_id
and accounts_memberships.account_id = has_permission.account_id
and role_permissions.permission = has_permission.permission_name);
end;
$$ language plpgsql;
grant execute on function public.has_permission (uuid, uuid, public.app_permissions) to authenticated, postgres;
-- Enable RLS on the role_permissions table -- Enable RLS on the role_permissions table
alter table public.role_permissions enable row level security; alter table public.role_permissions enable row level security;
@@ -712,7 +735,6 @@ insert
has_role_on_account (account_id) has_role_on_account (account_id)
and public.has_permission (auth.uid (), account_id, 'invites.manage'::app_permissions)); and public.has_permission (auth.uid (), account_id, 'invites.manage'::app_permissions));
/* /*
* ------------------------------------------------------- * -------------------------------------------------------
* Section: Billing Customers * Section: Billing Customers
@@ -756,7 +778,7 @@ select
-- SELECT: Users can read account subscriptions on an account they are a member of -- SELECT: Users can read account subscriptions on an account they are a member of
create policy billing_customers_read_self on public.billing_customers for create policy billing_customers_read_self on public.billing_customers for
select select
to authenticated using (has_role_on_account (account_id)); to authenticated using (account_id = auth.uid() or has_role_on_account (account_id));
/* /*
* ------------------------------------------------------- * -------------------------------------------------------
@@ -771,6 +793,7 @@ create table if not exists
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, id text not null primary key,
status public.subscription_status not null, status public.subscription_status not null,
active bool not null,
billing_provider public.billing_provider not null, billing_provider public.billing_provider not null,
product_id varchar(255) not null, product_id varchar(255) not null,
variant_id varchar(255) not null, variant_id varchar(255) not null,
@@ -825,6 +848,8 @@ select
update, update,
delete on table public.subscriptions to service_role; delete on table public.subscriptions to service_role;
grant select on table public.subscriptions to authenticated;
-- Enable RLS on subscriptions table -- Enable RLS on subscriptions table
alter table public.subscriptions enable row level security; alter table public.subscriptions enable row level security;
@@ -832,12 +857,14 @@ alter table public.subscriptions enable row level security;
-- SELECT: Users can read account subscriptions on an account they are a member of -- SELECT: Users can read account subscriptions on an account they are a member of
create policy subscriptions_read_self on public.subscriptions for create policy subscriptions_read_self on public.subscriptions for
select select
to authenticated using (has_role_on_account (account_id)); to authenticated using (has_role_on_account (account_id) or account_id = auth.uid ());
-- Functions -- Functions
create or replace function public.add_subscription ( create or replace function public.add_subscription (
account_id uuid, account_id uuid,
id text, subscription_id text,
active bool,
status public.subscription_status, status public.subscription_status,
billing_provider public.billing_provider, billing_provider public.billing_provider,
product_id varchar(255), product_id varchar(255),
@@ -845,35 +872,34 @@ create or replace function public.add_subscription (
price_amount numeric, price_amount numeric,
cancel_at_period_end bool, cancel_at_period_end bool,
currency varchar(3), currency varchar(3),
interval varchar(255), "interval" varchar(255),
interval_count integer, interval_count integer,
period_starts_at timestamptz, period_starts_at timestamptz,
period_ends_at timestamptz, period_ends_at timestamptz,
trial_starts_at timestamptz, trial_starts_at timestamptz,
trial_ends_at timestamptz, trial_ends_at timestamptz,
customer_id text customer_id varchar(255)
) returns public.subscriptions as $$ ) returns public.subscriptions as $$
declare declare
new_subscription public.subscriptions; new_subscription public.subscriptions;
billing_customer_id int; new_billing_customer_id int;
begin begin
insert into public.billing_customers( insert into public.billing_customers(
account_id, account_id,
id,
provider, provider,
customer_id) customer_id)
values ( values (
account_id, account_id,
billing_customer_id,
billing_provider, billing_provider,
customer_id) customer_id)
returning returning
id into billing_customer_id; 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,
status, status,
billing_provider, billing_provider,
product_id, product_id,
@@ -889,8 +915,9 @@ begin
trial_ends_at) trial_ends_at)
values ( values (
account_id, account_id,
billing_customer_id, new_billing_customer_id,
id, subscription_id,
active,
status, status,
billing_provider, billing_provider,
product_id, product_id,
@@ -910,34 +937,31 @@ begin
end; end;
$$ language plpgsql; $$ language plpgsql;
grant execute on function public.add_subscription (
uuid,
text,
boolean,
public.subscription_status,
public.billing_provider,
varchar,
varchar,
numeric,
boolean,
varchar,
varchar,
integer,
timestamptz,
timestamptz,
timestamptz,
timestamptz,
varchar
) to service_role;
/* /*
* ------------------------------------------------------- * -------------------------------------------------------
* Section: Functions * Section: Functions
* ------------------------------------------------------- * -------------------------------------------------------
*/ */
-- Create a function to check if a user has a permission
create function public.has_permission (
user_id uuid,
account_id uuid,
permission_name app_permissions
) returns boolean as $$
begin
return exists(
select
1
from
public.accounts_memberships
join public.role_permissions on accounts_memberships.account_role = role_permissions.role
where
accounts_memberships.user_id = has_permission.user_id
and accounts_memberships.account_id = has_permission.account_id
and role_permissions.permission = has_permission.permission_name);
end;
$$ language plpgsql;
grant execute on function public.has_permission (uuid, uuid, public.app_permissions) to authenticated, postgres;
-- Create a function to slugify a string -- Create a function to slugify a string
create create
or replace function kit.slugify ("value" text) returns text as $$ or replace function kit.slugify ("value" text) returns text as $$
@@ -1262,7 +1286,7 @@ execute on function public.get_account_members (text) to authenticated,
postgres; postgres;
create or replace function public.get_account_invitations(account_slug text) returns table ( create or replace function public.get_account_invitations(account_slug text) returns table (
id serial, id integer,
email varchar(255), email varchar(255),
account_id uuid, account_id uuid,
invited_by uuid, invited_by uuid,
@@ -1293,6 +1317,7 @@ end;
$$ language plpgsql; $$ language plpgsql;
grant execute on function public.get_account_invitations (text) to authenticated, postgres; grant execute on function public.get_account_invitations (text) to authenticated, postgres;
CREATE TYPE kit.invitation AS ( CREATE TYPE kit.invitation AS (
email text, email text,
role public.account_role role public.account_role
@@ -1334,7 +1359,7 @@ BEGIN
END; END;
$$ LANGUAGE plpgsql; $$ LANGUAGE plpgsql;
grant execute on function public.add_invitations_to_account (text, array) to authenticated, postgres; grant execute on function public.add_invitations_to_account (text, kit.invitation[]) to authenticated, postgres;
-- Storage -- Storage
-- Account Image -- Account Image

View File

@@ -7,11 +7,13 @@
}, },
"build": { "build": {
"dependsOn": ["^build"], "dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**", "next-env.d.ts"] "outputs": [".next/**", "!.next/cache/**", "next-env.d.ts"],
"dotEnv": [".env.production.local", ".env.local", ".env.production", ".env"]
}, },
"dev": { "dev": {
"persistent": true, "persistent": true,
"cache": false "cache": false,
"dotEnv": [".env.development.local", ".env.local", ".env.development", ".env"]
}, },
"format": { "format": {
"outputs": ["node_modules/.cache/.prettiercache"], "outputs": ["node_modules/.cache/.prettiercache"],
@@ -34,11 +36,7 @@
}, },
"globalEnv": [ "globalEnv": [
"SKIP_ENV_VALIDATION", "SKIP_ENV_VALIDATION",
"STRIPE_API_KEY", "STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET", "STRIPE_WEBHOOK_SECRET"
"NEXT_PUBLIC_STRIPE_STD_PRODUCT_ID",
"NEXT_PUBLIC_STRIPE_STD_MONTHLY_PRICE_ID",
"NEXT_PUBLIC_STRIPE_PRO_PRODUCT_ID",
"NEXT_PUBLIC_STRIPE_PRO_MONTHLY_PRICE_ID"
] ]
} }