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

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