feat(forms): add PhoneInput and unify module form validation UX
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import type { ComponentProps } from 'react';
|
||||
import type { FieldErrors, UseFormRegister } from 'react-hook-form';
|
||||
import { useRef, type ComponentProps } from 'react';
|
||||
import {
|
||||
Controller,
|
||||
type Control,
|
||||
type FieldErrors,
|
||||
type UseFormRegister,
|
||||
} from 'react-hook-form';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import { FormField } from '@/components/form';
|
||||
import { FormField, PhoneInput } from '@/components/form';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -22,6 +27,7 @@ interface ClientSheetProps {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
clientId?: number;
|
||||
register: UseFormRegister<ClientFormValues>;
|
||||
control: Control<ClientFormValues>;
|
||||
errors: FieldErrors<ClientFormValues>;
|
||||
isSubmitted: boolean;
|
||||
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||
@@ -34,12 +40,14 @@ export function ClientSheet({
|
||||
onOpenChange,
|
||||
clientId,
|
||||
register,
|
||||
control,
|
||||
errors,
|
||||
isSubmitted,
|
||||
onSubmit,
|
||||
canSubmit,
|
||||
isSaving,
|
||||
}: ClientSheetProps) {
|
||||
const dropdownPortalRef = useRef<HTMLDivElement | null>(null);
|
||||
const firstNameErrorMessage = isSubmitted
|
||||
? errors.first_name?.message
|
||||
: undefined;
|
||||
@@ -201,11 +209,19 @@ export function ClientSheet({
|
||||
required
|
||||
error={contactPhoneErrorMessage}
|
||||
>
|
||||
<Input
|
||||
id="contact-phone-number"
|
||||
placeholder="Enter contact phone"
|
||||
aria-invalid={!!contactPhoneErrorMessage}
|
||||
{...register('contact_phone_number')}
|
||||
<Controller
|
||||
control={control}
|
||||
name="contact_phone_number"
|
||||
render={({ field }) => (
|
||||
<PhoneInput
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Enter contact phone"
|
||||
aria-invalid={!!contactPhoneErrorMessage}
|
||||
portalContainer={dropdownPortalRef}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
@@ -244,6 +260,8 @@ export function ClientSheet({
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
<div ref={dropdownPortalRef} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { isValidPhoneNumber } from 'libphonenumber-js';
|
||||
import { useCallback } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { Client } from '@/types';
|
||||
@@ -23,7 +23,10 @@ const clientFormSchema = z.object({
|
||||
pan: optionalTaxIdSchema,
|
||||
tan: optionalTaxIdSchema,
|
||||
contact_name: requiredText('Contact name is required'),
|
||||
contact_phone_number: requiredText('Contact phone number is required'),
|
||||
contact_phone_number: requiredText('Contact phone number is required').refine(
|
||||
(value) => isValidPhoneNumber(value),
|
||||
'Enter a valid phone number',
|
||||
),
|
||||
contact_email: requiredText('Contact email is required').email(
|
||||
'Invalid contact email',
|
||||
),
|
||||
@@ -87,18 +90,7 @@ export function useClientForm({ onSaved }: { onSaved: () => void }) {
|
||||
contactPhoneNumber.trim().length > 0 &&
|
||||
contactEmail.trim().length > 0;
|
||||
|
||||
const handleSubmit = submitForm(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
const firstError = Object.values(formErrors).find(
|
||||
(error) => error?.message,
|
||||
);
|
||||
|
||||
if (firstError?.message) {
|
||||
toast.error(firstError.message);
|
||||
}
|
||||
},
|
||||
);
|
||||
const handleSubmit = submitForm((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
@@ -127,6 +119,7 @@ export function useClientForm({ onSaved }: { onSaved: () => void }) {
|
||||
|
||||
return {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
openCreate,
|
||||
|
||||
@@ -48,6 +48,7 @@ export default function ClientsPage() {
|
||||
clientForm;
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
clientId,
|
||||
errors,
|
||||
@@ -134,6 +135,7 @@ export default function ClientsPage() {
|
||||
onOpenChange={setIsSheetOpen}
|
||||
clientId={clientId}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isSubmitted={isSubmitted}
|
||||
onSubmit={handleSubmit}
|
||||
|
||||
@@ -74,7 +74,7 @@ export function PackageDialog({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
|
||||
<section className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -103,18 +103,7 @@ export function usePackageForm({ onSaved }: { onSaved: () => void }) {
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
if (formErrors.project_id?.message) {
|
||||
toast.error(formErrors.project_id.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.name?.message) {
|
||||
toast.error(formErrors.name.message);
|
||||
}
|
||||
},
|
||||
);
|
||||
const onSubmit = handleSubmit((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
|
||||
@@ -77,7 +77,7 @@ export function PlanSheet({
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
import type { PermissionTreeItem, Plan } from '@/types';
|
||||
import { useCallback } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { useSavePlanMutation } from './usePlanMutations';
|
||||
@@ -104,31 +103,20 @@ export function usePlanForm({
|
||||
price.trim().length > 0 &&
|
||||
permissionIds.length > 0;
|
||||
|
||||
const onSubmit = handleSubmit(
|
||||
(values) => {
|
||||
saveMutation.mutate({
|
||||
...values,
|
||||
name: values.name.trim(),
|
||||
slug: values.slug.trim(),
|
||||
description: values.description.trim(),
|
||||
price: values.price.trim(),
|
||||
trial_days: toNumber(values.trial_days),
|
||||
max_projects: toNumber(values.max_projects),
|
||||
max_organizations: toNumber(values.max_organizations),
|
||||
max_users: toNumber(values.max_users),
|
||||
max_roles: toNumber(values.max_roles),
|
||||
});
|
||||
},
|
||||
(formErrors) => {
|
||||
const firstMessage = Object.values(formErrors).find(
|
||||
(error) => error?.message,
|
||||
)?.message;
|
||||
|
||||
if (firstMessage) {
|
||||
toast.error(String(firstMessage));
|
||||
}
|
||||
},
|
||||
);
|
||||
const onSubmit = handleSubmit((values) => {
|
||||
saveMutation.mutate({
|
||||
...values,
|
||||
name: values.name.trim(),
|
||||
slug: values.slug.trim(),
|
||||
description: values.description.trim(),
|
||||
price: values.price.trim(),
|
||||
trial_days: toNumber(values.trial_days),
|
||||
max_projects: toNumber(values.max_projects),
|
||||
max_organizations: toNumber(values.max_organizations),
|
||||
max_users: toNumber(values.max_users),
|
||||
max_roles: toNumber(values.max_roles),
|
||||
});
|
||||
});
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset({
|
||||
|
||||
@@ -66,7 +66,7 @@ export function ProjectDialog({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
|
||||
<section className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -106,14 +106,7 @@ export function useProjectForm({ onSaved }: { onSaved: () => void }) {
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
if (formErrors.name?.message) {
|
||||
toast.error(formErrors.name.message);
|
||||
}
|
||||
},
|
||||
);
|
||||
const onSubmit = handleSubmit((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
|
||||
@@ -73,7 +73,7 @@ export function RoleSheet({
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
|
||||
@@ -89,22 +89,7 @@ export function useRoleForm({
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
if (formErrors.name?.message) {
|
||||
toast.error(formErrors.name.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.display_name?.message) {
|
||||
toast.error(formErrors.display_name.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.permission_ids?.message) {
|
||||
toast.error(formErrors.permission_ids.message);
|
||||
}
|
||||
},
|
||||
);
|
||||
const onSubmit = handleSubmit((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset({
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import type { ComponentProps } from 'react';
|
||||
import type { FieldErrors, UseFormRegister } from 'react-hook-form';
|
||||
import { useMemo, useRef, type ComponentProps } from 'react';
|
||||
import {
|
||||
Controller,
|
||||
type Control,
|
||||
type FieldErrors,
|
||||
type UseFormRegister,
|
||||
} from 'react-hook-form';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import { FormField } from '@/components/form';
|
||||
import { FormField, PhoneInput, SelectPopover } from '@/components/form';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -15,16 +20,12 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { Client, Plan } from '@/types';
|
||||
|
||||
import type { TenantFormValues } from '../hooks/useTenantForm';
|
||||
import type {
|
||||
TenantAdminFieldLocks,
|
||||
TenantFormValues,
|
||||
} from '../hooks/useTenantForm';
|
||||
|
||||
interface TenantSheetProps {
|
||||
open: boolean;
|
||||
@@ -32,6 +33,7 @@ interface TenantSheetProps {
|
||||
tenantId?: number;
|
||||
isEditMode: boolean;
|
||||
register: UseFormRegister<TenantFormValues>;
|
||||
control: Control<TenantFormValues>;
|
||||
errors: FieldErrors<TenantFormValues>;
|
||||
isSubmitted: boolean;
|
||||
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||
@@ -46,6 +48,7 @@ interface TenantSheetProps {
|
||||
isLookupsLoading: boolean;
|
||||
isSaving: boolean;
|
||||
adminEmail?: string;
|
||||
adminFieldLocks: TenantAdminFieldLocks;
|
||||
}
|
||||
|
||||
export function TenantSheet({
|
||||
@@ -54,6 +57,7 @@ export function TenantSheet({
|
||||
tenantId,
|
||||
isEditMode,
|
||||
register,
|
||||
control,
|
||||
errors,
|
||||
isSubmitted,
|
||||
onSubmit,
|
||||
@@ -68,10 +72,30 @@ export function TenantSheet({
|
||||
isLookupsLoading,
|
||||
isSaving,
|
||||
adminEmail,
|
||||
adminFieldLocks,
|
||||
}: TenantSheetProps) {
|
||||
const dropdownPortalRef = useRef<HTMLDivElement | null>(null);
|
||||
const fieldError = (field: keyof TenantFormValues) =>
|
||||
isSubmitted ? errors[field]?.message : undefined;
|
||||
|
||||
const clientOptions = useMemo(
|
||||
() =>
|
||||
clients.map((client) => ({
|
||||
value: String(client.id),
|
||||
label: [client.first_name, client.last_name].filter(Boolean).join(' '),
|
||||
})),
|
||||
[clients],
|
||||
);
|
||||
|
||||
const planOptions = useMemo(
|
||||
() =>
|
||||
plans.map((plan) => ({
|
||||
value: String(plan.id),
|
||||
label: plan.name,
|
||||
})),
|
||||
[plans],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-3xl">
|
||||
@@ -85,7 +109,11 @@ export function TenantSheet({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
|
||||
<form
|
||||
noValidate
|
||||
onSubmit={onSubmit}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<div className="max-h-[50vh] space-y-5 overflow-y-auto px-6 py-4">
|
||||
<div className="space-y-1">
|
||||
<p>Basic Information</p>
|
||||
@@ -129,34 +157,23 @@ export function TenantSheet({
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormField
|
||||
id="tenant-client"
|
||||
label="Client"
|
||||
required
|
||||
error={fieldError('client_id')}
|
||||
>
|
||||
<Select
|
||||
<SelectPopover
|
||||
options={clientOptions}
|
||||
value={clientId}
|
||||
onValueChange={onClientChange}
|
||||
disabled={isLookupsLoading}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue
|
||||
placeholder={
|
||||
isLookupsLoading
|
||||
? 'Loading clients...'
|
||||
: 'Select client'
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{clients.map((client) => (
|
||||
<SelectItem key={client.id} value={String(client.id)}>
|
||||
{[client.first_name, client.last_name]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
portalContainer={dropdownPortalRef}
|
||||
placeholder={
|
||||
isLookupsLoading ? 'Loading clients...' : 'Select client'
|
||||
}
|
||||
searchPlaceholder="Search clients"
|
||||
emptyMessage="No clients found."
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
{...register('client_id')}
|
||||
@@ -166,30 +183,23 @@ export function TenantSheet({
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="tenant-plan"
|
||||
label="Subscription Plan"
|
||||
required
|
||||
error={fieldError('plan_id')}
|
||||
>
|
||||
<Select
|
||||
<SelectPopover
|
||||
options={planOptions}
|
||||
value={planId}
|
||||
onValueChange={onPlanChange}
|
||||
disabled={isLookupsLoading}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue
|
||||
placeholder={
|
||||
isLookupsLoading ? 'Loading plans...' : 'Select plan'
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{plans.map((plan) => (
|
||||
<SelectItem key={plan.id} value={String(plan.id)}>
|
||||
{plan.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
portalContainer={dropdownPortalRef}
|
||||
placeholder={
|
||||
isLookupsLoading ? 'Loading plans...' : 'Select plan'
|
||||
}
|
||||
searchPlaceholder="Search plans"
|
||||
emptyMessage="No plans found."
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
{...register('plan_id')}
|
||||
@@ -242,6 +252,7 @@ export function TenantSheet({
|
||||
id="admin-first-name"
|
||||
placeholder="Enter first name"
|
||||
aria-invalid={!!fieldError('admin_first_name')}
|
||||
readOnly={adminFieldLocks.admin_first_name}
|
||||
{...register('admin_first_name')}
|
||||
/>
|
||||
</FormField>
|
||||
@@ -256,6 +267,7 @@ export function TenantSheet({
|
||||
id="admin-last-name"
|
||||
placeholder="Enter last name"
|
||||
aria-invalid={!!fieldError('admin_last_name')}
|
||||
readOnly={adminFieldLocks.admin_last_name}
|
||||
{...register('admin_last_name')}
|
||||
/>
|
||||
</FormField>
|
||||
@@ -273,6 +285,7 @@ export function TenantSheet({
|
||||
type="email"
|
||||
placeholder="admin@example.com"
|
||||
aria-invalid={!!fieldError('admin_email')}
|
||||
readOnly={adminFieldLocks.admin_email}
|
||||
{...register('admin_email')}
|
||||
/>
|
||||
</FormField>
|
||||
@@ -282,11 +295,20 @@ export function TenantSheet({
|
||||
label="Phone Number"
|
||||
error={fieldError('admin_phone_number')}
|
||||
>
|
||||
<Input
|
||||
id="admin-phone"
|
||||
placeholder="+91-9000011111"
|
||||
aria-invalid={!!fieldError('admin_phone_number')}
|
||||
{...register('admin_phone_number')}
|
||||
<Controller
|
||||
control={control}
|
||||
name="admin_phone_number"
|
||||
render={({ field }) => (
|
||||
<PhoneInput
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Enter phone number"
|
||||
aria-invalid={!!fieldError('admin_phone_number')}
|
||||
disabled={adminFieldLocks.admin_phone_number}
|
||||
portalContainer={dropdownPortalRef}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
@@ -322,6 +344,8 @@ export function TenantSheet({
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
<div ref={dropdownPortalRef} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useCallback } from 'react';
|
||||
import { isValidPhoneNumber } from 'libphonenumber-js';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { Tenant } from '@/types';
|
||||
|
||||
import { useSaveTenantMutation } from './useTenantMutations';
|
||||
|
||||
const optionalPhoneSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((value) => value === '' || /^\+(?:[0-9] ?|-){6,18}[0-9]$/.test(value), {
|
||||
message: 'Please enter a valid phone number',
|
||||
});
|
||||
const requiredText = (message: string) => z.string().trim().min(1, message);
|
||||
|
||||
const tenantFormSchema = z
|
||||
.object({
|
||||
id: z.number().optional(),
|
||||
name: z.string().trim().min(1, 'Tenant name is required'),
|
||||
slug: z.string().trim().min(1, 'Slug is required'),
|
||||
client_id: z.string().trim().min(1, 'Client is required'),
|
||||
plan_id: z.string().trim().min(1, 'Plan is required'),
|
||||
name: requiredText('Tenant name is required'),
|
||||
slug: requiredText('Slug is required'),
|
||||
client_id: requiredText('Client is required'),
|
||||
plan_id: requiredText('Plan is required'),
|
||||
domain: z.string().trim(),
|
||||
description: z.string().trim(),
|
||||
admin_first_name: z.string().trim(),
|
||||
admin_last_name: z.string().trim(),
|
||||
admin_email: z.string().trim(),
|
||||
admin_phone_number: optionalPhoneSchema,
|
||||
admin_phone_number: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((value) => value === '' || isValidPhoneNumber(value), {
|
||||
message: 'Enter a valid phone number',
|
||||
}),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (values.id) return;
|
||||
@@ -38,7 +38,7 @@ const tenantFormSchema = z
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['admin_first_name'],
|
||||
message: 'Admin first name is required',
|
||||
message: 'First name is required',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ const tenantFormSchema = z
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['admin_last_name'],
|
||||
message: 'Admin last name is required',
|
||||
message: 'Last name is required',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -98,6 +98,20 @@ function splitContactName(contactName: string) {
|
||||
return { firstName: parts[0], lastName: parts.slice(1).join(' ') };
|
||||
}
|
||||
|
||||
export type TenantAdminFieldLocks = {
|
||||
admin_first_name: boolean;
|
||||
admin_last_name: boolean;
|
||||
admin_email: boolean;
|
||||
admin_phone_number: boolean;
|
||||
};
|
||||
|
||||
const defaultAdminFieldLocks: TenantAdminFieldLocks = {
|
||||
admin_first_name: false,
|
||||
admin_last_name: false,
|
||||
admin_email: false,
|
||||
admin_phone_number: false,
|
||||
};
|
||||
|
||||
export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
const {
|
||||
register,
|
||||
@@ -115,10 +129,15 @@ export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
const saveMutation = useSaveTenantMutation({
|
||||
onSaved: () => {
|
||||
reset(defaultValues);
|
||||
setAdminFieldLocks(defaultAdminFieldLocks);
|
||||
onSaved();
|
||||
},
|
||||
});
|
||||
|
||||
const [adminFieldLocks, setAdminFieldLocks] = useState<TenantAdminFieldLocks>(
|
||||
defaultAdminFieldLocks,
|
||||
);
|
||||
|
||||
const tenantId = useWatch({ control, name: 'id' });
|
||||
const clientId = useWatch({ control, name: 'client_id' }) || '';
|
||||
const planId = useWatch({ control, name: 'plan_id' }) || '';
|
||||
@@ -138,21 +157,11 @@ export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
adminLastName.trim().length > 0 &&
|
||||
adminEmail.trim().length > 0));
|
||||
|
||||
const handleSubmit = submitForm(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
const firstMessage = Object.values(formErrors).find(
|
||||
(error) => error?.message,
|
||||
)?.message;
|
||||
|
||||
if (firstMessage) {
|
||||
toast.error(String(firstMessage));
|
||||
}
|
||||
},
|
||||
);
|
||||
const handleSubmit = submitForm((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
setAdminFieldLocks(defaultAdminFieldLocks);
|
||||
}, [reset]);
|
||||
|
||||
const openEdit = useCallback(
|
||||
@@ -170,19 +179,37 @@ export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
admin_email: tenant.admin_email || '',
|
||||
admin_phone_number: '',
|
||||
});
|
||||
setAdminFieldLocks(defaultAdminFieldLocks);
|
||||
},
|
||||
[reset],
|
||||
);
|
||||
|
||||
const clearAdminFields = useCallback(() => {
|
||||
setValue('admin_first_name', '', { shouldDirty: true });
|
||||
setValue('admin_last_name', '', { shouldDirty: true });
|
||||
setValue('admin_email', '', { shouldDirty: true });
|
||||
setValue('admin_phone_number', '', { shouldDirty: true });
|
||||
setAdminFieldLocks(defaultAdminFieldLocks);
|
||||
}, [setValue]);
|
||||
|
||||
const applyClientAdminDefaults = useCallback(
|
||||
(contactName: string, contactEmail: string, contactPhone: string) => {
|
||||
if (isEditMode) return;
|
||||
|
||||
const { firstName, lastName } = splitContactName(contactName);
|
||||
const trimmedEmail = contactEmail.trim();
|
||||
const trimmedPhone = contactPhone.trim();
|
||||
|
||||
setValue('admin_first_name', firstName, { shouldDirty: true });
|
||||
setValue('admin_last_name', lastName, { shouldDirty: true });
|
||||
setValue('admin_email', contactEmail, { shouldDirty: true });
|
||||
setValue('admin_phone_number', contactPhone, { shouldDirty: true });
|
||||
setValue('admin_email', trimmedEmail, { shouldDirty: true });
|
||||
setValue('admin_phone_number', trimmedPhone, { shouldDirty: true });
|
||||
setAdminFieldLocks({
|
||||
admin_first_name: firstName.trim().length > 0,
|
||||
admin_last_name: lastName.trim().length > 0,
|
||||
admin_email: trimmedEmail.length > 0,
|
||||
admin_phone_number: trimmedPhone.length > 0,
|
||||
});
|
||||
},
|
||||
[isEditMode, setValue],
|
||||
);
|
||||
@@ -197,9 +224,9 @@ export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
|
||||
return {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
control,
|
||||
setValue,
|
||||
openCreate,
|
||||
openEdit,
|
||||
@@ -211,7 +238,9 @@ export function useTenantForm({ onSaved }: { onSaved: () => void }) {
|
||||
errors,
|
||||
isSubmitted,
|
||||
canSubmit,
|
||||
adminFieldLocks,
|
||||
applyClientAdminDefaults,
|
||||
clearAdminFields,
|
||||
syncSlugFromName,
|
||||
isSaving: isSubmitting || saveMutation.isPending,
|
||||
};
|
||||
|
||||
@@ -54,6 +54,7 @@ export default function TenantsPage() {
|
||||
});
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
openCreate: prepareCreateTenant,
|
||||
openEdit: prepareEditTenant,
|
||||
@@ -65,7 +66,9 @@ export default function TenantsPage() {
|
||||
errors,
|
||||
isSubmitted,
|
||||
canSubmit,
|
||||
adminFieldLocks,
|
||||
applyClientAdminDefaults,
|
||||
clearAdminFields,
|
||||
syncSlugFromName,
|
||||
setValue,
|
||||
isSaving,
|
||||
@@ -77,7 +80,11 @@ export default function TenantsPage() {
|
||||
(value: string) => {
|
||||
setValue('client_id', value, { shouldDirty: true, shouldValidate: true });
|
||||
|
||||
if (!value || isEditMode) return;
|
||||
if (isEditMode) return;
|
||||
|
||||
clearAdminFields();
|
||||
|
||||
if (!value) return;
|
||||
|
||||
clientService.getClientById(Number(value)).then((client) => {
|
||||
applyClientAdminDefaults(
|
||||
@@ -87,7 +94,7 @@ export default function TenantsPage() {
|
||||
);
|
||||
});
|
||||
},
|
||||
[applyClientAdminDefaults, isEditMode, setValue],
|
||||
[applyClientAdminDefaults, clearAdminFields, isEditMode, setValue],
|
||||
);
|
||||
|
||||
const handlePlanChange = useCallback(
|
||||
@@ -183,6 +190,7 @@ export default function TenantsPage() {
|
||||
tenantId={tenantId}
|
||||
isEditMode={isEditMode}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isSubmitted={isSubmitted}
|
||||
onSubmit={handleSubmit}
|
||||
@@ -197,6 +205,7 @@ export default function TenantsPage() {
|
||||
isLookupsLoading={isLookupsLoading}
|
||||
isSaving={isSaving}
|
||||
adminEmail={adminEmail}
|
||||
adminFieldLocks={adminFieldLocks}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { useRef, type ComponentProps } from 'react';
|
||||
import type { FieldErrors, UseFormRegister } from 'react-hook-form';
|
||||
import {
|
||||
Controller,
|
||||
type Control,
|
||||
type FieldErrors,
|
||||
type UseFormRegister,
|
||||
} from 'react-hook-form';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import { FormField } from '@/components/form';
|
||||
import { FormField, PhoneInput } from '@/components/form';
|
||||
import { RoleSelect } from '@/components/lookups/RoleSelect';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -23,6 +28,7 @@ interface UserSheetProps {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
userId?: number;
|
||||
register: UseFormRegister<UserFormValues>;
|
||||
control: Control<UserFormValues>;
|
||||
errors: FieldErrors<UserFormValues>;
|
||||
isSubmitted: boolean;
|
||||
onSubmit: ComponentProps<'form'>['onSubmit'];
|
||||
@@ -37,6 +43,7 @@ export function UserSheet({
|
||||
onOpenChange,
|
||||
userId,
|
||||
register,
|
||||
control,
|
||||
errors,
|
||||
isSubmitted,
|
||||
onSubmit,
|
||||
@@ -72,6 +79,7 @@ export function UserSheet({
|
||||
</DialogHeader>
|
||||
|
||||
<form
|
||||
noValidate
|
||||
onSubmit={onSubmit}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
@@ -126,16 +134,29 @@ export function UserSheet({
|
||||
label="Phone Number"
|
||||
error={phoneErrorMessage}
|
||||
>
|
||||
<Input
|
||||
id="phone-number"
|
||||
placeholder="+919876543210"
|
||||
aria-invalid={!!phoneErrorMessage}
|
||||
{...register('phone_number')}
|
||||
<Controller
|
||||
control={control}
|
||||
name="phone_number"
|
||||
render={({ field }) => (
|
||||
<PhoneInput
|
||||
value={field.value}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Enter phone number"
|
||||
aria-invalid={!!phoneErrorMessage}
|
||||
portalContainer={roleComboboxPortalRef}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
<FormField label="Role" required error={roleErrorMessage}>
|
||||
<FormField
|
||||
id="role"
|
||||
label="Role"
|
||||
required
|
||||
error={roleErrorMessage}
|
||||
>
|
||||
<RoleSelect
|
||||
value={roleId}
|
||||
onValueChange={onRoleChange}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { isValidPhoneNumber } from 'libphonenumber-js';
|
||||
import { useCallback } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { toast } from 'sonner';
|
||||
import { z } from 'zod';
|
||||
|
||||
import type { AdministrationUser } from '@/types';
|
||||
import { useSaveUserMutation } from './useUserMutations';
|
||||
|
||||
const optionalPhoneSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((value) => value === '' || /^\+(?:[0-9] ?){6,14}[0-9]$/.test(value), {
|
||||
message: 'Please enter a valid phone number',
|
||||
});
|
||||
const requiredText = (message: string) => z.string().trim().min(1, message);
|
||||
|
||||
const userFormSchema = z.object({
|
||||
id: z.number().optional(),
|
||||
first_name: z.string().trim().min(1, 'First name is required'),
|
||||
last_name: z.string().trim().min(1, 'Last name is required'),
|
||||
email: z.string().trim().min(1, 'Email is required').email('Invalid email'),
|
||||
phone_number: optionalPhoneSchema,
|
||||
role_id: z.string().trim().min(1, 'Role is required'),
|
||||
first_name: requiredText('First name is required'),
|
||||
last_name: requiredText('Last name is required'),
|
||||
email: requiredText('Email is required').email('Invalid email'),
|
||||
phone_number: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((value) => value === '' || isValidPhoneNumber(value), {
|
||||
message: 'Enter a valid phone number',
|
||||
}),
|
||||
role_id: requiredText('Role is required'),
|
||||
});
|
||||
|
||||
export type UserFormValues = z.infer<typeof userFormSchema>;
|
||||
@@ -61,41 +61,13 @@ export function useUserForm({ onSaved }: { onSaved: () => void }) {
|
||||
const firstName = useWatch({ control, name: 'first_name' }) || '';
|
||||
const lastName = useWatch({ control, name: 'last_name' }) || '';
|
||||
const email = useWatch({ control, name: 'email' }) || '';
|
||||
const phoneNumber = useWatch({ control, name: 'phone_number' }) || '';
|
||||
const isPhoneValid =
|
||||
phoneNumber.trim() === '' ||
|
||||
/^\+(?:[0-9] ?){6,14}[0-9]$/.test(phoneNumber.trim());
|
||||
const canSubmit =
|
||||
firstName.trim().length > 0 &&
|
||||
lastName.trim().length > 0 &&
|
||||
email.trim().length > 0 &&
|
||||
roleId.trim().length > 0 &&
|
||||
isPhoneValid;
|
||||
roleId.trim().length > 0;
|
||||
|
||||
const handleSubmit = submitForm(
|
||||
(values) => saveMutation.mutate(values),
|
||||
(formErrors) => {
|
||||
if (formErrors.first_name?.message) {
|
||||
toast.error(formErrors.first_name.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.last_name?.message) {
|
||||
toast.error(formErrors.last_name.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.email?.message) {
|
||||
toast.error(formErrors.email.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.phone_number?.message) {
|
||||
toast.error(formErrors.phone_number.message);
|
||||
return;
|
||||
}
|
||||
if (formErrors.role_id?.message) {
|
||||
toast.error(formErrors.role_id.message);
|
||||
}
|
||||
},
|
||||
);
|
||||
const handleSubmit = submitForm((values) => saveMutation.mutate(values));
|
||||
|
||||
const openCreate = useCallback(() => {
|
||||
reset(defaultValues);
|
||||
@@ -125,6 +97,7 @@ export function useUserForm({ onSaved }: { onSaved: () => void }) {
|
||||
|
||||
return {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
openCreate,
|
||||
|
||||
@@ -49,6 +49,7 @@ export default function UsersPage() {
|
||||
openCreate: prepareCreateUser,
|
||||
openEdit: prepareEditUser,
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
userId,
|
||||
roleId,
|
||||
@@ -144,6 +145,7 @@ export default function UsersPage() {
|
||||
onOpenChange={setIsSheetOpen}
|
||||
userId={userId}
|
||||
register={register}
|
||||
control={control}
|
||||
errors={errors}
|
||||
isSubmitted={isSubmitted}
|
||||
onSubmit={handleSubmit}
|
||||
|
||||
@@ -32,9 +32,10 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${poppins.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
<head>
|
||||
<link rel="stylesheet" href="/flags/flags.css" />
|
||||
</head>
|
||||
<body className={`${poppins.variable} ${geistMono.variable} antialiased`}>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
|
||||
Reference in New Issue
Block a user