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

@@ -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,
};
});
}