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
NEXT_PUBLIC_SUPABASE_URL=http://127.0.0.1:54321
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
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
SIGN_IN_PATH=/auth/sign-in
SIGN_UP_PATH=/auth/sign-up
ORGANIZATION_ACCOUNTS_PATH=/home
TEAM_ACCOUNTS_HOME_PATH=/home
INVITATION_PAGE_PATH=/join

View File

@@ -2,7 +2,10 @@
import { useState, useTransition } from 'react';
import { ExclamationTriangleIcon } from '@radix-ui/react-icons';
import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components';
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import {
Card,
CardContent,
@@ -10,6 +13,7 @@ import {
CardHeader,
CardTitle,
} from '@kit/ui/card';
import { If } from '@kit/ui/if';
import billingConfig from '~/config/billing.config';
@@ -17,7 +21,8 @@ import { createPersonalAccountCheckoutSession } from '../server-actions';
export function PersonalAccountCheckoutForm() {
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 (checkoutToken) {
@@ -41,18 +46,26 @@ export function PersonalAccountCheckoutForm() {
</CardDescription>
</CardHeader>
<CardContent>
<CardContent className={'space-y-4'}>
<If condition={error}>
<ErrorAlert />
</If>
<PlanPicker
pending={pending}
config={billingConfig}
onSubmit={({ planId }) => {
startTransition(async () => {
const { checkoutToken } =
await createPersonalAccountCheckoutSession({
planId,
});
try {
const { checkoutToken } =
await createPersonalAccountCheckoutSession({
planId,
});
setCheckoutToken(checkoutToken);
setCheckoutToken(checkoutToken);
} catch (e) {
setError(true);
}
});
}}
/>
@@ -61,3 +74,17 @@ export function PersonalAccountCheckoutForm() {
</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 { 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';
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 (
<>
<PageHeader
@@ -13,10 +40,48 @@ function PersonalAccountBillingPage() {
/>
<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>
</>
);
}
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
// 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';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { getProductPlanPairFromId } from '@kit/billing';
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 appConfig from '~/config/app.config';
import billingConfig from '~/config/billing.config';
import pathsConfig from '~/config/paths.config';
@@ -22,13 +24,21 @@ export async function createPersonalAccountCheckoutSession(params: {
planId: string;
}) {
const client = getSupabaseServerActionClient();
const { data, error } = await client.auth.getUser();
const { data, error } = await requireAuth(client);
if (error ?? !data.user) {
throw new Error('Authentication required');
}
const planId = z.string().min(1).parse(params.planId);
Logger.info(
{
planId,
},
`Creating checkout session for plan ID`,
);
const service = await getBillingGatewayProvider(client);
const productPlanPairFromId = getProductPlanPairFromId(billingConfig, planId);
@@ -61,6 +71,13 @@ export async function createPersonalAccountCheckoutSession(params: {
customerId,
});
Logger.info(
{
userId: data.user.id,
},
`Checkout session created. Returning checkout token to client...`,
);
// return the checkout token to the client
// so we can call the payment gateway to complete the checkout
return {
@@ -68,7 +85,7 @@ export async function createPersonalAccountCheckoutSession(params: {
};
}
export async function createBillingPortalSession() {
export async function createPersonalAccountBillingPortalSession() {
const client = getSupabaseServerActionClient();
const { data, error } = await client.auth.getUser();
@@ -95,18 +112,17 @@ export async function createBillingPortalSession() {
}
function getCheckoutSessionReturnUrl() {
const origin = headers().get('origin')!;
return new URL(
pathsConfig.app.personalAccountBillingReturn,
origin,
appConfig.url,
).toString();
}
function getBillingPortalReturnUrl() {
const origin = headers().get('origin')!;
return new URL(pathsConfig.app.accountBilling, origin).toString();
return new URL(
pathsConfig.app.personalAccountBilling,
appConfig.url,
).toString();
}
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 { withI18n } from '~/lib/i18n/with-i18n';
const features = {
enableAccountDeletion: featureFlagsConfig.enableAccountDeletion,
};
const paths = {
callback: pathsConfig.auth.callback,
};
function PersonalAccountSettingsPage() {
return (
<div
@@ -11,14 +19,7 @@ function PersonalAccountSettingsPage() {
'container mx-auto flex max-w-2xl flex-1 flex-col items-center'
}
>
<PersonalAccountSettingsContainer
features={{
enableAccountDeletion: featureFlagsConfig.enableAccountDeletion,
}}
paths={{
callback: pathsConfig.auth.callback,
}}
/>
<PersonalAccountSettingsContainer features={features} paths={paths} />
</div>
);
}

View File

@@ -4,7 +4,7 @@ import { useRouter } from 'next/navigation';
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 { Sidebar, SidebarContent } from '@kit/ui/sidebar';
@@ -138,13 +138,13 @@ function CollapsibleButton({
aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
onClick={() => onClick(!collapsed)}
>
<ArrowRightCircleIcon
<ArrowRightCircle
className={cn(iconClassName, {
hidden: !collapsed,
})}
/>
<ArrowLeftCircleIcon
<ArrowLeftCircle
className={cn(iconClassName, {
hidden: collapsed,
})}

View File

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

View File

@@ -3,7 +3,7 @@
import Link from 'next/link';
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 { useSignOut } from '@kit/supabase/hooks/use-sign-out';
@@ -67,7 +67,7 @@ export const MobileAppNavigation = (
return (
<DropdownMenu>
<DropdownMenuTrigger>
<MenuIcon className={'h-9'} />
<Menu className={'h-9'} />
</DropdownMenuTrigger>
<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'}
onClick={props.onSignOut}
>
<LogOutIcon className={'h-6'} />
<LogOut className={'h-6'} />
<span>
<Trans i18nKey={'common:signOut'} defaults={'Sign out'} />
@@ -135,7 +135,7 @@ function OrganizationsModal() {
onSelect={(e) => e.preventDefault()}
>
<button className={'flex items-center space-x-4'}>
<HomeIcon className={'h-6'} />
<Home className={'h-6'} />
<span>
<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 { useParams } from 'next/navigation';
import { EmbeddedCheckout, PlanPicker } from '@kit/billing-gateway/components';
import {
Card,
@@ -16,6 +18,7 @@ import billingConfig from '~/config/billing.config';
import { createTeamAccountCheckoutSession } from '../server-actions';
export function TeamAccountCheckoutForm(params: { accountId: string }) {
const routeParams = useParams();
const [pending, startTransition] = useTransition();
const [checkoutToken, setCheckoutToken] = useState<string | null>(null);
@@ -31,34 +34,32 @@ export function TeamAccountCheckoutForm(params: { accountId: string }) {
// Otherwise, render the plan picker component
return (
<div className={'mx-auto w-full max-w-2xl'}>
<Card>
<CardHeader>
<CardTitle>Manage your Team Plan</CardTitle>
<Card>
<CardHeader>
<CardTitle>Manage your Team Plan</CardTitle>
<CardDescription>
You can change your plan at any time.
</CardDescription>
</CardHeader>
<CardDescription>You can change your plan at any time.</CardDescription>
</CardHeader>
<CardContent>
<PlanPicker
pending={pending}
config={billingConfig}
onSubmit={({ planId }) => {
startTransition(async () => {
const { checkoutToken } =
await createTeamAccountCheckoutSession({
planId,
accountId: params.accountId,
});
<CardContent>
<PlanPicker
pending={pending}
config={billingConfig}
onSubmit={({ planId }) => {
startTransition(async () => {
const slug = routeParams.account as string;
setCheckoutToken(checkoutToken);
const { checkoutToken } = await createTeamAccountCheckoutSession({
planId,
accountId: params.accountId,
slug,
});
}}
/>
</CardContent>
</Card>
</div>
setCheckoutToken(checkoutToken);
});
}}
/>
</CardContent>
</Card>
);
}

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 { If } from '@kit/ui/if';
import { PageBody, PageHeader } from '@kit/ui/page';
import { Trans } from '@kit/ui/trans';
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 { TeamAccountCheckoutForm } from './_components/team-account-checkout-form';
@@ -18,7 +24,7 @@ interface Params {
async function OrganizationAccountBillingPage({ params }: Params) {
const workspace = await loadOrganizationWorkspace(params.account);
const accountId = workspace.account.id;
const customerId = await loadCustomerIdFromAccount(accountId);
const [subscription, customerId] = await loadAccountData(accountId);
return (
<>
@@ -28,11 +34,27 @@ async function OrganizationAccountBillingPage({ params }: Params) {
/>
<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}>
<BillingPortalForm accountId={accountId} />
</If>
<If condition={customerId}>
<form action={createBillingPortalSession}>
<input type="hidden" name={'accountId'} value={accountId} />
<input type="hidden" name={'slug'} value={params.account} />
<BillingPortalCard />
</form>
</If>
</div>
</div>
</PageBody>
</>
);
@@ -40,18 +62,21 @@ async function OrganizationAccountBillingPage({ params }: Params) {
export default withI18n(OrganizationAccountBillingPage);
async function loadCustomerIdFromAccount(accountId: string) {
async function loadAccountData(accountId: string) {
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')
.select('customer_id')
.eq('account_id', accountId)
.maybeSingle();
if (error) {
throw error;
}
return data?.customer_id;
return Promise.all([subscription, customerId]);
}

View File

@@ -1,6 +1,5 @@
'use server';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { z } from 'zod';
@@ -10,6 +9,7 @@ import { getBillingGatewayProvider } from '@kit/billing-gateway';
import { requireAuth } from '@kit/supabase/require-auth';
import { getSupabaseServerActionClient } from '@kit/supabase/server-actions-client';
import appConfig from '~/config/app.config';
import billingConfig from '~/config/billing.config';
import pathsConfig from '~/config/paths.config';
@@ -22,6 +22,7 @@ import pathsConfig from '~/config/paths.config';
export async function createTeamAccountCheckoutSession(params: {
planId: string;
accountId: string;
slug: string;
}) {
const client = getSupabaseServerActionClient();
@@ -57,7 +58,7 @@ export async function createTeamAccountCheckoutSession(params: {
}
// 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
// (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 accountId = z
const { accountId, slug } = z
.object({
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);
@@ -113,7 +115,7 @@ export async function createBillingPortalSession(data: FormData) {
const service = await getBillingGatewayProvider(client);
const customerId = await getCustomerIdFromAccountId(client, accountId);
const returnUrl = getBillingPortalReturnUrl();
const returnUrl = getBillingPortalReturnUrl(slug);
if (!customerId) {
throw new Error('Customer not found');
@@ -128,16 +130,16 @@ export async function createBillingPortalSession(data: FormData) {
return redirect(url);
}
function getCheckoutSessionReturnUrl() {
const origin = headers().get('origin')!;
return new URL(pathsConfig.app.accountBillingReturn, origin).toString();
function getCheckoutSessionReturnUrl(accountSlug: string) {
return new URL(pathsConfig.app.accountBillingReturn, appConfig.url)
.toString()
.replace('[account]', accountSlug);
}
function getBillingPortalReturnUrl() {
const origin = headers().get('origin')!;
return new URL(pathsConfig.app.accountBilling, origin).toString();
function getBillingPortalReturnUrl(accountSlug: string) {
return new URL(pathsConfig.app.accountBilling, appConfig.url)
.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 {
@@ -99,7 +99,7 @@ async function OrganizationAccountMembersPage({ params }: Params) {
<InviteMembersDialogContainer account={account.slug}>
<Button size={'sm'}>
<PlusCircleIcon className={'mr-2 w-4'} />
<PlusCircle className={'mr-2 w-4'} />
<span>Add Member</span>
</Button>
</InviteMembersDialogContainer>

View File

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

View File

@@ -2,19 +2,16 @@ import { use } from 'react';
import { cookies } from 'next/headers';
import { getSupabaseServerComponentClient } from '@kit/supabase/server-component-client';
import { Sidebar, SidebarContent, SidebarNavigation } from '@kit/ui/sidebar';
import { HomeSidebarAccountSelector } from '~/(dashboard)/home/_components/home-sidebar-account-selector';
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';
export function HomeSidebar() {
const collapsed = getSidebarCollapsed();
const [accounts, session] = use(
Promise.all([loadUserAccounts(), loadSession()]),
);
const { session, accounts } = use(loadUserWorkspace());
return (
<Sidebar collapsed={collapsed}>
@@ -38,38 +35,3 @@ export function HomeSidebar() {
function getSidebarCollapsed() {
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 { ChevronRightIcon } from 'lucide-react';
import { ChevronRight } from 'lucide-react';
import { PersonalAccountDropdown } from '@kit/accounts/personal-account-dropdown';
import { useSignOut } from '@kit/supabase/hooks/use-sign-out';
@@ -60,7 +60,7 @@ function AuthButtons() {
<Link href={pathsConfig.auth.signUp}>
<Button className={'rounded-full'}>
<Trans i18nKey={'auth:signUp'} />
<ChevronRightIcon className={'h-4'} />
<ChevronRight className={'h-4'} />
</Button>
</Link>
</div>

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,7 @@ import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { ChevronDownIcon, MenuIcon } from 'lucide-react';
import { ChevronDown, Menu } from 'lucide-react';
import { isBrowser } from '@kit/shared/utils';
import { Button } from '@kit/ui/button';
@@ -53,7 +53,7 @@ const DocsNavLink: React.FC<{
<span
className={`block w-2.5 ${collapsed ? '-rotate-90 transform' : ''}`}
>
<ChevronDownIcon className="h-4 w-4" />
<ChevronDown className="h-4 w-4" />
</span>
</button>
)}
@@ -218,7 +218,7 @@ function FloatingDocumentationNavigation({
className={'fixed bottom-5 right-5 z-10 h-16 w-16 rounded-full'}
onClick={onClick}
>
<MenuIcon className={'h-8'} />
<Menu className={'h-8'} />
</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 { withI18n } from '~/lib/i18n/with-i18n';
@@ -108,7 +108,7 @@ function FaqItem({
</h2>
<div>
<ChevronDownIcon
<ChevronDown
className={'h-5 transition duration-300 group-open:-rotate-180'}
/>
</div>

View File

@@ -1,7 +1,7 @@
import Image from 'next/image';
import Link from 'next/link';
import { ChevronRightIcon } from 'lucide-react';
import { ChevronRight } from 'lucide-react';
import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading';
@@ -135,7 +135,7 @@ function Home() {
<Button variant={'outline'}>
<span className={'flex items-center space-x-2'}>
<span>Get Started</span>
<ChevronRightIcon className={'h-3'} />
<ChevronRight className={'h-3'} />
</span>
</Button>
</div>
@@ -273,7 +273,7 @@ function MainCallToActionButton() {
<span className={'flex items-center space-x-2'}>
<span>Get Started</span>
<ChevronRightIcon
<ChevronRight
className={
'h-4 animate-in fade-in slide-in-from-left-8' +
' 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
*/
export async function POST(request: Request) {
const client = getSupabaseRouteHandlerClient();
// we can infer the provider from the billing config or the request
// for simplicity, we'll use the billing config for now
// TODO: use dynamic provider from request?
@@ -23,7 +21,9 @@ export async function POST(request: Request) {
`Received billing webhook. Processing...`,
);
const service = await getBillingEventHandlerService(client, provider);
const clientProvider = () => getSupabaseRouteHandlerClient({ admin: true });
const service = await getBillingEventHandlerService(clientProvider, provider);
try {
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 { ArrowLeftIcon } from 'lucide-react';
import { ArrowLeft } from 'lucide-react';
import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading';
@@ -41,7 +41,7 @@ const ErrorPage = () => {
<div>
<Link href={'/'}>
<Button variant={'outline'}>
<ArrowLeftIcon className={'mr-2 h-4'} />
<ArrowLeft className={'mr-2 h-4'} />
<Trans i18nKey={'common:backToHomePage'} />
</Button>

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,4 @@
import {
CreditCardIcon,
LayoutDashboardIcon,
SettingsIcon,
UsersIcon,
} from 'lucide-react';
import { CreditCard, LayoutDashboard, Settings, Users } from 'lucide-react';
import { SidebarConfigSchema } from '@kit/ui/sidebar-schema';
@@ -16,7 +11,7 @@ const routes = (account: string) => [
{
label: 'common:dashboardTabLabel',
path: pathsConfig.app.accountHome.replace('[account]', account),
Icon: <LayoutDashboardIcon className={iconClasses} />,
Icon: <LayoutDashboard className={iconClasses} />,
end: true,
},
{
@@ -26,18 +21,18 @@ const routes = (account: string) => [
{
label: 'common:settingsTabLabel',
path: createPath(pathsConfig.app.accountSettings, account),
Icon: <SettingsIcon className={iconClasses} />,
Icon: <Settings className={iconClasses} />,
},
{
label: 'common:accountMembers',
path: createPath(pathsConfig.app.accountMembers, account),
Icon: <UsersIcon className={iconClasses} />,
Icon: <Users className={iconClasses} />,
},
featureFlagsConfig.enableOrganizationBilling
? {
label: 'common:billingTabLabel',
path: createPath(pathsConfig.app.accountBilling, account),
Icon: <CreditCardIcon className={iconClasses} />,
Icon: <CreditCard className={iconClasses} />,
}
: undefined,
].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';
@@ -11,13 +11,13 @@ const routes = [
{
label: 'common:homeTabLabel',
path: pathsConfig.app.home,
Icon: <HomeIcon className={iconClasses} />,
Icon: <Home className={iconClasses} />,
end: true,
},
{
label: 'common:yourAccountTabLabel',
path: pathsConfig.app.personalAccountSettings,
Icon: <UserIcon className={iconClasses} />,
Icon: <User className={iconClasses} />,
},
];
@@ -25,7 +25,7 @@ if (featureFlagsConfig.enablePersonalAccountBilling) {
routes.push({
label: 'common:billingTabLabel',
path: pathsConfig.app.personalAccountBilling,
Icon: <CreditCardIcon className={iconClasses} />,
Icon: <CreditCard className={iconClasses} />,
});
}

View File

@@ -18,6 +18,7 @@ const config = {
'@kit/mailers',
'@kit/billing',
'@kit/billing-gateway',
'@kit/stripe',
],
pageExtensions: ['ts', 'tsx'],
images: {
@@ -25,6 +26,12 @@ const config = {
},
experimental: {
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 */
eslint: { ignoreDuringBuilds: true },

View File

@@ -6,7 +6,7 @@
"analyze": "ANALYZE=true pnpm run build",
"build": "pnpm with-env next build",
"clean": "git clean -xdf .next .turbo node_modules",
"dev": "pnpm with-env next dev --turbo",
"dev": "pnpm with-env next dev",
"lint": "next lint",
"format": "prettier --check \"**/*.{js,cjs,mjs,ts,tsx,md,json}\"",
"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:fix": "turbo lint --continue -- --fix --cache --cache-location 'node_modules/.cache/.eslintcache' && manypkg fix",
"typecheck": "turbo typecheck",
"stripe:listen": "pnpm --filter '@kit/stripe' start",
"supabase:start": "turbo dev --filter @kit/supabase-config",
"supabase:stop": "pnpm --filter '@kit/supabase-config' stop",
"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 { CheckIcon, ChevronRightIcon } from 'lucide-react';
import { Check, ChevronRight } from 'lucide-react';
import { Button } from '@kit/ui/button';
import { Heading } from '@kit/ui/heading';
@@ -55,9 +55,9 @@ function SuccessSessionStatus({
'flex flex-col items-center justify-center space-y-4 text-center'
}
>
<CheckIcon
<Check
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'
}
/>
@@ -87,7 +87,7 @@ function SuccessSessionStatus({
<Trans i18nKey={'subscription:checkoutSuccessBackButton'} />
</span>
<ChevronRightIcon className={'h-4'} />
<ChevronRight className={'h-4'} />
</span>
</Link>
</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 { LoadingOverlay } from '@kit/ui/loading-overlay';
type BillingProvider = Database['public']['Enums']['billing_provider'];
const Fallback = (
<LoadingOverlay fullPage={false}>Loading Checkout...</LoadingOverlay>
);
export function EmbeddedCheckout(
props: React.PropsWithChildren<{
checkoutToken: string;
@@ -11,7 +16,10 @@ export function EmbeddedCheckout(
onClose?: () => void;
}>,
) {
const CheckoutComponent = loadCheckoutComponent(props.provider);
const CheckoutComponent = useMemo(
() => memo(loadCheckoutComponent(props.provider)),
[],
);
return (
<CheckoutComponent
@@ -24,10 +32,12 @@ export function EmbeddedCheckout(
function loadCheckoutComponent(provider: BillingProvider) {
switch (provider) {
case 'stripe': {
return lazy(() => {
return import('@kit/stripe/components').then((c) => ({
default: c.StripeCheckout,
}));
return buildLazyComponent(() => {
return import('@kit/stripe/components').then(({ StripeCheckout }) => {
return {
default: StripeCheckout,
};
});
});
}
@@ -43,3 +53,33 @@ function loadCheckoutComponent(provider: BillingProvider) {
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 './embedded-checkout';
export * from './billing-session-status';
export * from './billing-portal-card';

View File

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

View File

@@ -6,7 +6,7 @@ import { Database } from '@kit/supabase/database';
export class BillingEventHandlerService {
constructor(
private readonly client: SupabaseClient<Database>,
private readonly clientProvider: () => SupabaseClient<Database>,
private readonly strategy: BillingWebhookHandlerService,
) {}
@@ -19,6 +19,8 @@ export class BillingEventHandlerService {
return this.strategy.handleWebhookEvent(event, {
onSubscriptionDeleted: async (subscriptionId: string) => {
const client = this.clientProvider();
// Handle the subscription deleted event
// here we delete the subscription from the database
Logger.info(
@@ -29,7 +31,7 @@ export class BillingEventHandlerService {
'Processing subscription deleted event',
);
const { error } = await this.client
const { error } = await client
.from('subscriptions')
.delete()
.match({ id: subscriptionId });
@@ -47,6 +49,8 @@ export class BillingEventHandlerService {
);
},
onSubscriptionUpdated: async (subscription) => {
const client = this.clientProvider();
const ctx = {
namespace: 'billing',
subscriptionId: subscription.id,
@@ -58,7 +62,7 @@ export class BillingEventHandlerService {
// Handle the subscription updated event
// here we update the subscription in the database
const { error } = await this.client
const { error } = await client
.from('subscriptions')
.update(subscription)
.match({ id: subscription.id });
@@ -77,9 +81,11 @@ export class BillingEventHandlerService {
Logger.info(ctx, 'Successfully updated subscription');
},
onCheckoutSessionCompleted: async (subscription) => {
onCheckoutSessionCompleted: async (subscription, customerId) => {
// Handle the checkout session completed event
// here we add the subscription to the database
const client = this.clientProvider();
const ctx = {
namespace: 'billing',
subscriptionId: subscription.id,
@@ -89,12 +95,21 @@ export class BillingEventHandlerService {
Logger.info(ctx, 'Processing checkout session completed event...');
const { error } = await this.client.rpc('add_subscription', {
subscription,
const { id, ...data } = 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) {
Logger.error(ctx, 'Failed to add subscription');
Logger.error({ ...ctx, 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.
*/
export async function getBillingEventHandlerService(
client: ReturnType<typeof getSupabaseServerActionClient>,
clientProvider: () => ReturnType<typeof getSupabaseServerActionClient>,
provider: Database['public']['Enums']['billing_provider'],
) {
const strategy =
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 { CheckCircleIcon, SparklesIcon } from 'lucide-react';
import { CheckCircle, Sparkles } from 'lucide-react';
import { z } from 'zod';
import { Button } from '@kit/ui/button';
@@ -147,7 +147,7 @@ function PricingItem(
)}
>
<If condition={highlighted}>
<SparklesIcon className={'mr-1 h-4 w-4'} />
<Sparkles className={'mr-1 h-4 w-4'} />
</If>
<span>{props.product.badge}</span>
@@ -238,7 +238,7 @@ function ListItem({ children }: React.PropsWithChildren) {
return (
<li className={'flex items-center space-x-3 font-medium'}>
<div>
<CheckCircleIcon className={'h-5 text-green-500'} />
<CheckCircle className={'h-5 text-green-500'} />
</div>
<span className={'text-muted-foreground text-sm'}>{children}</span>
@@ -275,7 +275,7 @@ function PlanIntervalSwitcher(
>
<span className={'flex items-center space-x-1'}>
<If condition={selected}>
<CheckCircleIcon className={'h-4 text-green-500'} />
<CheckCircle className={'h-4 text-green-500'} />
</If>
<span className={'capitalize'}>

View File

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

View File

@@ -3,7 +3,7 @@
import { useEffect, useState } from 'react';
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 { Button } from '@kit/ui/button';
@@ -19,7 +19,7 @@ import { If } from '@kit/ui/if';
import { Popover, PopoverContent, PopoverTrigger } from '@kit/ui/popover';
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 {
accounts: Array<{
@@ -64,7 +64,7 @@ export function AccountSelector({
const Icon = (props: { item: string }) => {
return (
<CheckIcon
<Check
className={cn(
'ml-auto h-4 w-4',
value === props.item ? 'opacity-100' : 'opacity-0',
@@ -196,7 +196,7 @@ export function AccountSelector({
setOpen(false);
}}
>
<PlusIcon className="mr-2 h-4 w-4" />
<Plus className="mr-2 h-4 w-4" />
<span>Create Organization</span>
</Button>
@@ -208,7 +208,7 @@ export function AccountSelector({
</Popover>
<If condition={features.enableOrganizationCreation}>
<CreateOrganizationAccountDialog
<CreateTeamAccountDialog
isOpen={isCreatingAccount}
setIsOpen={setIsCreatingAccount}
/>

View File

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

View File

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

View File

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

View File

@@ -15,7 +15,7 @@ export function UpdatePasswordFormContainer(
const { data: user, isPending } = useUser();
if (isPending) {
return <LoadingOverlay />;
return <LoadingOverlay fullPage={false} />;
}
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"
},
"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": {
".": "./src/index.ts"
},
"devDependencies": {
"@kit/prettier-config": "0.1.0"
"eslintConfig": {
"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 { PageHeader } from '@/components/app/Page';
import pathsConfig from '@/config/paths.config';
import { ArrowLeftIcon } from 'lucide-react';
import { ArrowLeft } from 'lucide-react';
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 (
<PageHeader
title={children}
description={`Manage your app from the admin dashboard.`}
>
<Link href={pathsConfig.appHome}>
<Link href={paths.appHome}>
<Button variant={'link'}>
<ArrowLeftIcon className={'h-4'} />
<ArrowLeft className={'h-4'} />
<span>Back to App</span>
</Button>
</Link>

View File

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

View File

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

View File

@@ -1,10 +1,12 @@
'use client';
import type { FormEventHandler } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
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 { Alert, AlertDescription } from '@kit/ui/alert';
import { Button } from '@kit/ui/button';

View File

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

View File

@@ -2,7 +2,7 @@
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 { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
@@ -66,7 +66,7 @@ export function EmailPasswordSignUpContainer({
<>
<If condition={showVerifyEmailAlert}>
<Alert variant={'success'}>
<CheckIcon className={'w-4'} />
<Check className={'w-4'} />
<AlertTitle>
<Trans i18nKey={'auth:emailConfirmationAlertHeading'} />

View File

@@ -11,15 +11,6 @@
"exports": {
"./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": {
"@kit/eslint-config": "0.2.0",
"@kit/prettier-config": "0.1.0",
@@ -28,7 +19,14 @@
},
"peerDependencies": {
"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",
"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 { Trans } from '@kit/ui/trans';
import { CreateOrganizationAccountSchema } from '../schema/create-organization.schema';
import { createOrganizationAccountAction } from '../server/accounts-server-actions';
import { createOrganizationAccountAction } from '../actions/create-team-account-server-actions';
import { CreateTeamSchema } from '../schema/create-team.schema';
export function CreateOrganizationAccountDialog(
export function CreateTeamAccountDialog(
props: React.PropsWithChildren<{
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
@@ -46,11 +46,11 @@ function CreateOrganizationAccountForm() {
const [error, setError] = useState<boolean>();
const [pending, startTransition] = useTransition();
const form = useForm<z.infer<typeof CreateOrganizationAccountSchema>>({
const form = useForm<z.infer<typeof CreateTeamSchema>>({
defaultValues: {
name: '',
},
resolver: zodResolver(CreateOrganizationAccountSchema),
resolver: zodResolver(CreateTeamSchema),
});
return (

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
import { z } from 'zod';
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",
"exports": {
"./mailer": "./src/mailer.ts",
"./logger": "./src/logger.ts",
"./logger": "./src/logger/index.ts",
"./hooks/*": "./src/hooks/*.ts",
"./contexts/*": "./src/contexts/*.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",
"format": "prettier --check \"**/*.{ts,tsx}\"",
"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",
"exports": {

View File

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

View File

@@ -4,20 +4,19 @@ import { StripeServerEnvSchema } from '../schema/stripe-server-env.schema';
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
*/
export async function createStripeClient() {
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,
});
}

View File

@@ -29,9 +29,11 @@ export class StripeWebhookHandlerService
*/
async verifyWebhookSignature(request: Request) {
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({
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
});
@@ -109,7 +111,7 @@ export class StripeWebhookHandlerService
private async handleCheckoutSessionCompleted(
event: Stripe.CheckoutSessionCompletedEvent,
onCheckoutCompletedCallback: (
data: InsertSubscriptionParams,
data: Omit<Subscription['Insert'], 'billing_customer_id'>,
customerId: string,
) => Promise<unknown>,
) {
@@ -128,11 +130,11 @@ export class StripeWebhookHandlerService
// TODO: convert or store the amount in cents?
const amount = session.amount_total ?? 0;
const payload = this.buildSubscriptionPayload<typeof accountId>({
const payload = this.buildSubscriptionPayload({
subscription,
accountId,
amount,
});
}) as InsertSubscriptionParams;
return onCheckoutCompletedCallback(payload, customerId);
}
@@ -149,7 +151,7 @@ export class StripeWebhookHandlerService
return (acc + (item.plan.amount ?? 0)) * (item.quantity ?? 1);
}, 0);
const payload = this.buildSubscriptionPayload<undefined>({
const payload = this.buildSubscriptionPayload({
subscription,
amount,
});
@@ -166,27 +168,27 @@ export class StripeWebhookHandlerService
return onSubscriptionDeletedCallback(subscription.id);
}
private buildSubscriptionPayload<
AccountId extends string | undefined,
>(params: {
private buildSubscriptionPayload(params: {
subscription: Stripe.Subscription;
amount: number;
// we only need the account id if we
// are creating a subscription for an account
accountId?: AccountId;
}): AccountId extends string
? InsertSubscriptionParams
: Subscription['Update'] {
accountId?: string;
}) {
const { subscription } = params;
const lineItem = subscription.items.data[0];
const price = lineItem?.price;
const priceId = price?.id!;
const interval = price?.recurring?.interval ?? null;
const active =
subscription.status === 'active' || subscription.status === 'trialing';
const data = {
billing_provider: this.provider,
id: subscription.id,
status: subscription.status,
active,
price_amount: params.amount,
cancel_at_period_end: subscription.cancel_at_period_end ?? false,
interval: interval as string,
@@ -194,15 +196,27 @@ export class StripeWebhookHandlerService
product_id: price?.product as string,
variant_id: priceId,
interval_count: price?.recurring?.interval_count ?? 1,
};
period_starts_at: getISOString(subscription.current_period_start),
period_ends_at: getISOString(subscription.current_period_end),
trial_starts_at: getISOString(subscription.trial_start),
trial_ends_at: getISOString(subscription.trial_end),
} satisfies Omit<InsertSubscriptionParams, 'account_id'>;
// when we are creating a subscription for an account
// we need to include the account id
if (params.accountId !== undefined) {
return {
...data,
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 { useSupabase } from './use-supabase';
export function useUser() {
const client = useSupabase();
const router = useRouter();
const queryKey = ['user'];
const queryFn = async () => {
const response = await client.auth.getUser();
// this is most likely a session error or the user is not logged in
if (response.error) {
return Promise.reject(response.error);
throw router.replace('/');
}
if (response.data?.user) {

View File

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

View File

@@ -18,12 +18,11 @@ import type {
SortingState,
VisibilityState,
} from '@tanstack/react-table';
import classNames from 'clsx';
import {
ChevronLeftIcon,
ChevronRightIcon,
ChevronsLeftIcon,
ChevronsRightIcon,
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react';
import { Button } from '../shadcn/button';
@@ -36,6 +35,7 @@ import {
TableHeader,
TableRow,
} from '../shadcn/table';
import { cn } from '../utils';
import Trans from './trans';
interface ReactTableProps<T extends object> {
@@ -148,7 +148,7 @@ export function DataTable<T extends object>({
{table.getRowModel().rows.map((row) => (
<Fragment key={row.id}>
<TableRow
className={classNames({
className={cn({
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted':
row.getIsExpanded(),
})}
@@ -200,7 +200,7 @@ function Pagination<T>({
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<ChevronsLeftIcon className={'h-4'} />
<ChevronsLeft className={'h-4'} />
</Button>
<Button
@@ -208,7 +208,7 @@ function Pagination<T>({
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<ChevronLeftIcon className={'h-4'} />
<ChevronLeft className={'h-4'} />
</Button>
<Button
@@ -216,7 +216,7 @@ function Pagination<T>({
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<ChevronRightIcon className={'h-4'} />
<ChevronRight className={'h-4'} />
</Button>
<Button
@@ -224,7 +224,7 @@ function Pagination<T>({
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<ChevronsRightIcon className={'h-4'} />
<ChevronsRight className={'h-4'} />
</Button>
<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 cn from 'clsx';
import { UploadCloud, XIcon } from 'lucide-react';
import { UploadCloud, X } from 'lucide-react';
import { Button } from '../shadcn/button';
import { Label } from '../shadcn/label';
import { cn } from '../utils';
import { If } from './if';
type Props = Omit<React.InputHTMLAttributes<unknown>, 'value'> & {
@@ -21,7 +21,7 @@ type Props = Omit<React.InputHTMLAttributes<unknown>, 'value'> & {
const IMAGE_SIZE = 22;
const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
export const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
function ImageUploadInputComponent(
{
children,
@@ -190,7 +190,7 @@ const ImageUploadInput = forwardRef<React.ElementRef<'input'>, Props>(
className={'!h-5 !w-5'}
onClick={imageRemoved}
>
<XIcon className="h-4" />
<X className="h-4" />
</Button>
</If>
</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 { ImageIcon } from 'lucide-react';
import { Image as ImageIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { Button } from '../shadcn/button';
import ImageUploadInput from './image-upload-input';
import { ImageUploadInput } from './image-upload-input';
import { Trans } from './trans';
function ImageUploader(

View File

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

View File

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

View File

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

9
pnpm-lock.yaml generated
View File

@@ -334,9 +334,18 @@ importers:
packages/features/admin:
devDependencies:
'@kit/eslint-config':
specifier: 0.2.0
version: link:../../../tooling/eslint
'@kit/prettier-config':
specifier: 0.1.0
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:
devDependencies:

View File

@@ -313,14 +313,6 @@ create policy accounts_read_self on public.accounts for
select
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
create policy accounts_self_update on public.accounts
for update
@@ -537,6 +529,14 @@ create policy accounts_memberships_team_read on public.accounts_memberships for
select
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
create policy accounts_memberships_delete_self on public.accounts_memberships for
delete
@@ -628,6 +628,29 @@ update,
delete on table public.role_permissions to authenticated,
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
alter table public.role_permissions enable row level security;
@@ -712,7 +735,6 @@ insert
has_role_on_account (account_id)
and public.has_permission (auth.uid (), account_id, 'invites.manage'::app_permissions));
/*
* -------------------------------------------------------
* Section: Billing Customers
@@ -756,7 +778,7 @@ select
-- 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
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,
id text not null primary key,
status public.subscription_status not null,
active bool not null,
billing_provider public.billing_provider not null,
product_id varchar(255) not null,
variant_id varchar(255) not null,
@@ -825,6 +848,8 @@ select
update,
delete on table public.subscriptions to service_role;
grant select on table public.subscriptions to authenticated;
-- Enable RLS on subscriptions table
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
create policy subscriptions_read_self on public.subscriptions for
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
create or replace function public.add_subscription (
account_id uuid,
id text,
subscription_id text,
active bool,
status public.subscription_status,
billing_provider public.billing_provider,
product_id varchar(255),
@@ -845,35 +872,34 @@ create or replace function public.add_subscription (
price_amount numeric,
cancel_at_period_end bool,
currency varchar(3),
interval varchar(255),
"interval" varchar(255),
interval_count integer,
period_starts_at timestamptz,
period_ends_at timestamptz,
trial_starts_at timestamptz,
trial_ends_at timestamptz,
customer_id text
customer_id varchar(255)
) returns public.subscriptions as $$
declare
new_subscription public.subscriptions;
billing_customer_id int;
new_billing_customer_id int;
begin
insert into public.billing_customers(
account_id,
id,
provider,
customer_id)
values (
account_id,
billing_customer_id,
billing_provider,
customer_id)
returning
id into billing_customer_id;
id into new_billing_customer_id;
insert into public.subscriptions(
account_id,
billing_customer_id,
id,
active,
status,
billing_provider,
product_id,
@@ -889,8 +915,9 @@ begin
trial_ends_at)
values (
account_id,
billing_customer_id,
id,
new_billing_customer_id,
subscription_id,
active,
status,
billing_provider,
product_id,
@@ -910,34 +937,31 @@ begin
end;
$$ 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
* -------------------------------------------------------
*/
-- 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
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;
create or replace function public.get_account_invitations(account_slug text) returns table (
id serial,
id integer,
email varchar(255),
account_id uuid,
invited_by uuid,
@@ -1293,6 +1317,7 @@ end;
$$ language plpgsql;
grant execute on function public.get_account_invitations (text) to authenticated, postgres;
CREATE TYPE kit.invitation AS (
email text,
role public.account_role
@@ -1334,7 +1359,7 @@ BEGIN
END;
$$ 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
-- Account Image
@@ -1364,4 +1389,4 @@ with
''
)::uuid
) = auth.uid ()
);
);

View File

@@ -7,11 +7,13 @@
},
"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": {
"persistent": true,
"cache": false
"cache": false,
"dotEnv": [".env.development.local", ".env.local", ".env.development", ".env"]
},
"format": {
"outputs": ["node_modules/.cache/.prettiercache"],
@@ -34,11 +36,7 @@
},
"globalEnv": [
"SKIP_ENV_VALIDATION",
"STRIPE_API_KEY",
"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"
"STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET"
]
}