B2B-88: add starter kit structure and elements

This commit is contained in:
devmc-ee
2025-06-08 16:18:30 +03:00
parent 657a36a298
commit e7b25600cb
1280 changed files with 77893 additions and 5688 deletions

View File

@@ -0,0 +1,413 @@
'use client';
import { useFormStatus } from 'react-dom';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm, useWatch } from 'react-hook-form';
import { z } from 'zod';
import { ErrorBoundary } from '@kit/monitoring/components';
import { VerifyOtpForm } from '@kit/otp/components';
import { useUser } from '@kit/supabase/hooks/use-user';
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@kit/ui/alert-dialog';
import { Button } from '@kit/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@kit/ui/form';
import { Input } from '@kit/ui/input';
import { LoadingOverlay } from '@kit/ui/loading-overlay';
import { Trans } from '@kit/ui/trans';
import { deleteTeamAccountAction } from '../../server/actions/delete-team-account-server-actions';
import { leaveTeamAccountAction } from '../../server/actions/leave-team-account-server-actions';
export function TeamAccountDangerZone({
account,
primaryOwnerUserId,
features,
}: React.PropsWithChildren<{
account: {
name: string;
id: string;
};
features: {
enableTeamDeletion: boolean;
};
primaryOwnerUserId: string;
}>) {
const { data: user } = useUser();
if (!user) {
return <LoadingOverlay fullPage={false} />;
}
// Only the primary owner can delete the team account
const userIsPrimaryOwner = user.id === primaryOwnerUserId;
if (userIsPrimaryOwner) {
if (features.enableTeamDeletion) {
return <DeleteTeamContainer account={account} />;
}
return;
}
// A primary owner can't leave the team account
// but other members can
return <LeaveTeamContainer account={account} />;
}
function DeleteTeamContainer(props: {
account: {
name: string;
id: string;
};
}) {
return (
<div className={'flex flex-col space-y-4'}>
<div className={'flex flex-col space-y-1'}>
<span className={'text-sm font-medium'}>
<Trans i18nKey={'teams:deleteTeam'} />
</span>
<p className={'text-muted-foreground text-sm'}>
<Trans
i18nKey={'teams:deleteTeamDescription'}
values={{
teamName: props.account.name,
}}
/>
</p>
</div>
<div>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
data-test={'delete-team-trigger'}
type={'button'}
variant={'destructive'}
>
<Trans i18nKey={'teams:deleteTeam'} />
</Button>
</AlertDialogTrigger>
<AlertDialogContent onEscapeKeyDown={(e) => e.preventDefault()}>
<AlertDialogHeader>
<AlertDialogTitle>
<Trans i18nKey={'teams:deletingTeam'} />
</AlertDialogTitle>
<AlertDialogDescription>
<Trans
i18nKey={'teams:deletingTeamDescription'}
values={{
teamName: props.account.name,
}}
/>
</AlertDialogDescription>
</AlertDialogHeader>
<DeleteTeamConfirmationForm
name={props.account.name}
id={props.account.id}
/>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
);
}
function DeleteTeamConfirmationForm({
name,
id,
}: {
name: string;
id: string;
}) {
const { data: user } = useUser();
const form = useForm({
mode: 'onChange',
reValidateMode: 'onChange',
resolver: zodResolver(
z.object({
otp: z.string().min(6).max(6),
}),
),
defaultValues: {
otp: '',
},
});
const { otp } = useWatch({ control: form.control });
if (!user?.email) {
return <LoadingOverlay fullPage={false} />;
}
if (!otp) {
return (
<VerifyOtpForm
purpose={`delete-team-account-${id}`}
email={user.email}
onSuccess={(otp) => form.setValue('otp', otp, { shouldValidate: true })}
CancelButton={
<AlertDialogCancel className={'m-0'}>
<Trans i18nKey={'common:cancel'} />
</AlertDialogCancel>
}
/>
);
}
return (
<ErrorBoundary fallback={<DeleteTeamErrorAlert />}>
<Form {...form}>
<form
data-test={'delete-team-form'}
className={'flex flex-col space-y-4'}
action={deleteTeamAccountAction}
>
<div className={'flex flex-col space-y-2'}>
<div
className={
'border-destructive text-destructive my-4 flex flex-col space-y-2 rounded-md border-2 p-4 text-sm'
}
>
<div>
<Trans
i18nKey={'teams:deleteTeamDisclaimer'}
values={{
teamName: name,
}}
/>
</div>
<div className={'text-sm'}>
<Trans i18nKey={'common:modalConfirmationQuestion'} />
</div>
</div>
<input type="hidden" value={id} name={'accountId'} />
<input type="hidden" value={otp} name={'otp'} />
</div>
<AlertDialogFooter>
<AlertDialogCancel>
<Trans i18nKey={'common:cancel'} />
</AlertDialogCancel>
<DeleteTeamSubmitButton />
</AlertDialogFooter>
</form>
</Form>
</ErrorBoundary>
);
}
function DeleteTeamSubmitButton() {
const { pending } = useFormStatus();
return (
<Button
data-test={'delete-team-form-confirm-button'}
disabled={pending}
variant={'destructive'}
>
<Trans i18nKey={'teams:deleteTeam'} />
</Button>
);
}
function LeaveTeamContainer(props: {
account: {
name: string;
id: string;
};
}) {
const form = useForm({
resolver: zodResolver(
z.object({
confirmation: z.string().refine((value) => value === 'LEAVE', {
message: 'Confirmation required to leave team',
path: ['confirmation'],
}),
}),
),
defaultValues: {
confirmation: '' as 'LEAVE',
},
});
return (
<div className={'flex flex-col space-y-4'}>
<p className={'text-muted-foreground text-sm'}>
<Trans
i18nKey={'teams:leaveTeamDescription'}
values={{
teamName: props.account.name,
}}
/>
</p>
<AlertDialog>
<AlertDialogTrigger asChild>
<div>
<Button
data-test={'leave-team-button'}
type={'button'}
variant={'destructive'}
>
<Trans i18nKey={'teams:leaveTeam'} />
</Button>
</div>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
<Trans i18nKey={'teams:leavingTeamModalHeading'} />
</AlertDialogTitle>
<AlertDialogDescription>
<Trans i18nKey={'teams:leavingTeamModalDescription'} />
</AlertDialogDescription>
</AlertDialogHeader>
<ErrorBoundary fallback={<LeaveTeamErrorAlert />}>
<Form {...form}>
<form
className={'flex flex-col space-y-4'}
action={leaveTeamAccountAction}
>
<input
type={'hidden'}
value={props.account.id}
name={'accountId'}
/>
<FormField
name={'confirmation'}
render={({ field }) => {
return (
<FormItem>
<FormLabel>
<Trans i18nKey={'teams:leaveTeamInputLabel'} />
</FormLabel>
<FormControl>
<Input
data-test="leave-team-input-field"
type="text"
className="w-full"
autoComplete={'off'}
placeholder=""
pattern="LEAVE"
required
{...field}
/>
</FormControl>
<FormDescription>
<Trans i18nKey={'teams:leaveTeamInputDescription'} />
</FormDescription>
<FormMessage />
</FormItem>
);
}}
/>
<AlertDialogFooter>
<AlertDialogCancel>
<Trans i18nKey={'common:cancel'} />
</AlertDialogCancel>
<LeaveTeamSubmitButton />
</AlertDialogFooter>
</form>
</Form>
</ErrorBoundary>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
function LeaveTeamSubmitButton() {
const { pending } = useFormStatus();
return (
<Button
data-test={'confirm-leave-organization-button'}
disabled={pending}
variant={'destructive'}
>
<Trans i18nKey={'teams:leaveTeam'} />
</Button>
);
}
function LeaveTeamErrorAlert() {
return (
<div className={'flex flex-col space-y-4'}>
<Alert variant={'destructive'}>
<AlertTitle>
<Trans i18nKey={'teams:leaveTeamErrorHeading'} />
</AlertTitle>
<AlertDescription>
<Trans i18nKey={'common:genericError'} />
</AlertDescription>
</Alert>
<AlertDialogFooter>
<AlertDialogCancel>
<Trans i18nKey={'common:cancel'} />
</AlertDialogCancel>
</AlertDialogFooter>
</div>
);
}
function DeleteTeamErrorAlert() {
return (
<div className={'flex flex-col space-y-4'}>
<Alert variant={'destructive'}>
<AlertTitle>
<Trans i18nKey={'teams:deleteTeamErrorHeading'} />
</AlertTitle>
<AlertDescription>
<Trans i18nKey={'common:genericError'} />
</AlertDescription>
</Alert>
<AlertDialogFooter>
<AlertDialogCancel>
<Trans i18nKey={'common:cancel'} />
</AlertDialogCancel>
</AlertDialogFooter>
</div>
);
}

View File

@@ -0,0 +1,91 @@
'use client';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@kit/ui/card';
import { Trans } from '@kit/ui/trans';
import { TeamAccountDangerZone } from './team-account-danger-zone';
import { UpdateTeamAccountImage } from './update-team-account-image-container';
import { UpdateTeamAccountNameForm } from './update-team-account-name-form';
export function TeamAccountSettingsContainer(props: {
account: {
name: string;
slug: string;
id: string;
pictureUrl: string | null;
primaryOwnerUserId: string;
};
paths: {
teamAccountSettings: string;
};
features: {
enableTeamDeletion: boolean;
};
}) {
return (
<div className={'flex w-full flex-col space-y-4'}>
<Card>
<CardHeader>
<CardTitle>
<Trans i18nKey={'teams:settings.teamLogo'} />
</CardTitle>
<CardDescription>
<Trans i18nKey={'teams:settings.teamLogoDescription'} />
</CardDescription>
</CardHeader>
<CardContent>
<UpdateTeamAccountImage account={props.account} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>
<Trans i18nKey={'teams:settings.teamName'} />
</CardTitle>
<CardDescription>
<Trans i18nKey={'teams:settings.teamNameDescription'} />
</CardDescription>
</CardHeader>
<CardContent>
<UpdateTeamAccountNameForm
path={props.paths.teamAccountSettings}
account={props.account}
/>
</CardContent>
</Card>
<Card className={'border-destructive border'}>
<CardHeader>
<CardTitle>
<Trans i18nKey={'teams:settings.dangerZone'} />
</CardTitle>
<CardDescription>
<Trans i18nKey={'teams:settings.dangerZoneDescription'} />
</CardDescription>
</CardHeader>
<CardContent>
<TeamAccountDangerZone
primaryOwnerUserId={props.account.primaryOwnerUserId}
account={props.account}
features={props.features}
/>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,141 @@
'use client';
import { useCallback } from 'react';
import type { SupabaseClient } from '@supabase/supabase-js';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
import { ImageUploader } from '@kit/ui/image-uploader';
import { Trans } from '@kit/ui/trans';
const AVATARS_BUCKET = 'account_image';
export function UpdateTeamAccountImage(props: {
account: {
id: string;
name: string;
pictureUrl: string | null;
};
}) {
const client = useSupabase();
const { t } = useTranslation('teams');
const createToaster = useCallback(
(promise: () => Promise<unknown>) => {
return toast.promise(promise, {
success: t(`updateTeamSuccessMessage`),
error: t(`updateTeamErrorMessage`),
loading: t(`updateTeamLoadingMessage`),
});
},
[t],
);
const onValueChange = useCallback(
(file: File | null) => {
const removeExistingStorageFile = () => {
if (props.account.pictureUrl) {
return (
deleteProfilePhoto(client, props.account.pictureUrl) ??
Promise.resolve()
);
}
return Promise.resolve();
};
if (file) {
const promise = () =>
removeExistingStorageFile().then(() =>
uploadUserProfilePhoto(client, file, props.account.id).then(
(pictureUrl) => {
return client
.from('accounts')
.update({
picture_url: pictureUrl,
})
.eq('id', props.account.id)
.throwOnError();
},
),
);
createToaster(promise);
} else {
const promise = () =>
removeExistingStorageFile().then(() => {
return client
.from('accounts')
.update({
picture_url: null,
})
.eq('id', props.account.id)
.throwOnError();
});
createToaster(promise);
}
},
[client, createToaster, props],
);
return (
<ImageUploader
value={props.account.pictureUrl}
onValueChange={onValueChange}
>
<div className={'flex flex-col space-y-1'}>
<span className={'text-sm'}>
<Trans i18nKey={'account:profilePictureHeading'} />
</span>
<span className={'text-xs'}>
<Trans i18nKey={'account:profilePictureSubheading'} />
</span>
</div>
</ImageUploader>
);
}
function deleteProfilePhoto(client: SupabaseClient, url: string) {
const bucket = client.storage.from(AVATARS_BUCKET);
const fileName = url.split('/').pop()?.split('?')[0];
if (!fileName) {
return;
}
return bucket.remove([fileName]);
}
async function uploadUserProfilePhoto(
client: SupabaseClient,
photoFile: File,
userId: string,
) {
const bytes = await photoFile.arrayBuffer();
const bucket = client.storage.from(AVATARS_BUCKET);
const extension = photoFile.name.split('.').pop();
const fileName = await getAvatarFileName(userId, extension);
const result = await bucket.upload(fileName, bytes);
if (!result.error) {
return bucket.getPublicUrl(fileName).data.publicUrl;
}
throw result.error;
}
async function getAvatarFileName(
userId: string,
extension: string | undefined,
) {
const { nanoid } = await import('nanoid');
const uniqueId = nanoid(16);
return `${userId}.${extension}?v=${uniqueId}`;
}

View File

@@ -0,0 +1,122 @@
'use client';
import { useTransition } from 'react';
import { isRedirectError } from 'next/dist/client/components/redirect-error';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@kit/ui/button';
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@kit/ui/form';
import { Input } from '@kit/ui/input';
import { Trans } from '@kit/ui/trans';
import { TeamNameFormSchema } from '../../schema/update-team-name.schema';
import { updateTeamAccountName } from '../../server/actions/team-details-server-actions';
export const UpdateTeamAccountNameForm = (props: {
account: {
name: string;
slug: string;
};
path: string;
}) => {
const [pending, startTransition] = useTransition();
const { t } = useTranslation('teams');
const form = useForm({
resolver: zodResolver(TeamNameFormSchema),
defaultValues: {
name: props.account.name,
},
});
return (
<div className={'space-y-8'}>
<Form {...form}>
<form
data-test={'update-team-account-name-form'}
className={'flex flex-col space-y-4'}
onSubmit={form.handleSubmit((data) => {
startTransition(async () => {
const toastId = toast.loading(t('updateTeamLoadingMessage'));
try {
const result = await updateTeamAccountName({
slug: props.account.slug,
name: data.name,
path: props.path,
});
if (result.success) {
toast.success(t('updateTeamSuccessMessage'), {
id: toastId,
});
} else {
toast.error(t('updateTeamErrorMessage'), {
id: toastId,
});
}
} catch (error) {
if (!isRedirectError(error)) {
toast.error(t('updateTeamErrorMessage'), {
id: toastId,
});
} else {
toast.success(t('updateTeamSuccessMessage'), {
id: toastId,
});
}
}
});
})}
>
<FormField
name={'name'}
render={({ field }) => {
return (
<FormItem>
<FormLabel>
<Trans i18nKey={'teams:teamNameInputLabel'} />
</FormLabel>
<FormControl>
<Input
data-test={'team-name-input'}
required
placeholder={''}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
);
}}
/>
<div>
<Button
className={'w-full md:w-auto'}
data-test={'update-team-submit-button'}
disabled={pending}
>
<Trans i18nKey={'teams:updateTeamSubmitLabel'} />
</Button>
</div>
</form>
</Form>
</div>
);
};