Refactor AccountForm with 2D code toggle and conditional validation

- Refactor AccountForm to use toggle for showing/hiding profile fields
- Add show2dCodeInMonthlyStatement field to UserProfile database schema
- Implement conditional validation: all fields mandatory when 2D code is enabled
- Update FormSchema with .refine() methods for firstName, lastName, address, and IBAN
- IBAN validation includes both presence check and format validation when required
- Add validation error messages to English and Croatian localization files
- Initialize toggle state from persisted database value
- Form fields conditionally displayed based on toggle state

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Knee Cola
2025-11-18 12:24:11 +01:00
parent 5d1b7fd6b4
commit 9e3d49c74f
6 changed files with 182 additions and 106 deletions

View File

@@ -9,7 +9,8 @@
"Bash(git add:*)",
"Bash(git commit:*)",
"mcp__serena__replace_regex",
"Bash(npm install:*)"
"Bash(npm install:*)",
"mcp__ide__getDiagnostics"
]
},
"enableAllProjectMcpServers": true,

View File

@@ -18,6 +18,7 @@ export type State = {
lastName?: string[];
address?: string[];
iban?: string[];
show2dCodeInMonthlyStatement?: string[];
};
message?: string | null;
success?: boolean;
@@ -41,6 +42,48 @@ const FormSchema = (t: IntlTemplateFn) => z.object({
},
{ message: t("iban-invalid") }
),
show2dCodeInMonthlyStatement: z.boolean().optional().nullable(),
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.firstName && data.firstName.trim().length > 0;
}
return true;
}, {
message: t("first-name-required"),
path: ["firstName"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.lastName && data.lastName.trim().length > 0;
}
return true;
}, {
message: t("last-name-required"),
path: ["lastName"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.address && data.address.trim().length > 0;
}
return true;
}, {
message: t("address-required"),
path: ["address"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
if (!data.iban || data.iban.trim().length === 0) {
return false;
}
// Validate IBAN format when required
const cleaned = data.iban.replace(/\s/g, '').toUpperCase();
return IBAN.isValid(cleaned);
}
return true;
}, {
message: t("iban-required"),
path: ["iban"],
});
/**
@@ -71,6 +114,7 @@ export const updateUserProfile = withUser(async (user: AuthenticatedUser, prevSt
lastName: formData.get('lastName') || undefined,
address: formData.get('address') || undefined,
iban: formData.get('iban') || undefined,
show2dCodeInMonthlyStatement: formData.get('generateTenantCode') === 'on',
});
// If form validation fails, return errors early. Otherwise, continue...
@@ -82,7 +126,7 @@ export const updateUserProfile = withUser(async (user: AuthenticatedUser, prevSt
};
}
const { firstName, lastName, address, iban } = validatedFields.data;
const { firstName, lastName, address, iban, show2dCodeInMonthlyStatement } = validatedFields.data;
// Normalize IBAN: remove spaces and convert to uppercase
const normalizedIban = iban ? iban.replace(/\s/g, '').toUpperCase() : null;
@@ -97,6 +141,7 @@ export const updateUserProfile = withUser(async (user: AuthenticatedUser, prevSt
lastName: lastName || null,
address: address || null,
iban: normalizedIban,
show2dCodeInMonthlyStatement: show2dCodeInMonthlyStatement ?? false,
};
await dbClient.collection<UserProfile>("users")

View File

@@ -26,6 +26,8 @@ export interface UserProfile {
address?: string | null;
/** IBAN */
iban?: string | null;
/** whether to show 2D code in monthly statement */
show2dCodeInMonthlyStatement?: boolean | null;
};
/** bill object in the form returned by MongoDB */

View File

@@ -41,112 +41,130 @@ const FormFields: FC<FormFieldsProps> = ({ profile, errors, message }) => {
const cleanedIban = formValues.iban.replace(/\s/g, '');
const hasMissingData = !formValues.firstName || !formValues.lastName || !formValues.address || !cleanedIban;
// Track whether to generate 2D code for tenant (use persisted value from database)
const [show2dCodeInMonthlyStatement, setShow2dCodeInMonthlyStatement] = useState(
profile?.show2dCodeInMonthlyStatement ?? false
);
return (
<>
<InfoBox>{t("info-box-message")}</InfoBox>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("first-name-label")}</span>
</label>
<input
id="firstName"
name="firstName"
type="text"
placeholder={t("first-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={profile?.firstName ?? ""}
onChange={(e) => handleInputChange("firstName", e.target.value)}
disabled={pending}
/>
<div id="firstName-error" aria-live="polite" aria-atomic="true">
{errors?.firstName &&
errors.firstName.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
<fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
<legend className="fieldset-legend font-semibold uppercase">{t("tenant-2d-code-legend")}</legend>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("last-name-label")}</span>
</label>
<input
id="lastName"
name="lastName"
type="text"
placeholder={t("last-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={profile?.lastName ?? ""}
onChange={(e) => handleInputChange("lastName", e.target.value)}
disabled={pending}
/>
<div id="lastName-error" aria-live="polite" aria-atomic="true">
{errors?.lastName &&
errors.lastName.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
<InfoBox className="p-1 mb-1">{t("info-box-message")}</InfoBox>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("address-label")}</span>
</label>
<textarea
id="address"
name="address"
className="textarea textarea-bordered w-full placeholder:text-gray-600"
placeholder={t("address-placeholder")}
defaultValue={profile?.address ?? ""}
onChange={(e) => handleInputChange("address", e.target.value)}
disabled={pending}
></textarea>
<div id="address-error" aria-live="polite" aria-atomic="true">
{errors?.address &&
errors.address.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
<fieldset className="fieldset">
<label className="label cursor-pointer justify-start gap-3">
<input
type="checkbox"
name="generateTenantCode"
className="toggle toggle-primary"
checked={show2dCodeInMonthlyStatement}
onChange={(e) => setShow2dCodeInMonthlyStatement(e.target.checked)}
/>
<legend className="fieldset-legend">{t("tenant-2d-code-toggle-label")}</legend>
</label>
</fieldset>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("iban-label")}</span>
</label>
<input
id="iban"
name="iban"
type="text"
placeholder={t("iban-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={formatIban(profile?.iban)}
onChange={(e) => handleInputChange("iban", e.target.value)}
disabled={pending}
/>
<div id="iban-error" aria-live="polite" aria-atomic="true">
{errors?.iban &&
errors.iban.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
{show2dCodeInMonthlyStatement && (
<>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("first-name-label")}</span>
</label>
<input
id="firstName"
name="firstName"
type="text"
placeholder={t("first-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={profile?.firstName ?? ""}
onChange={(e) => handleInputChange("firstName", e.target.value)}
disabled={pending}
/>
<div id="firstName-error" aria-live="polite" aria-atomic="true">
{errors?.firstName &&
errors.firstName.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
{hasMissingData && (
<div className="alert mt-4 max-w-md flex flex-row items-start">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" className="stroke-current shrink-0 w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<span className="text-left">{t("warning-missing-data")}</span>
</div>
)}
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("last-name-label")}</span>
</label>
<input
id="lastName"
name="lastName"
type="text"
placeholder={t("last-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={profile?.lastName ?? ""}
onChange={(e) => handleInputChange("lastName", e.target.value)}
disabled={pending}
/>
<div id="lastName-error" aria-live="polite" aria-atomic="true">
{errors?.lastName &&
errors.lastName.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("address-label")}</span>
</label>
<textarea
id="address"
name="address"
className="textarea textarea-bordered w-full placeholder:text-gray-600"
placeholder={t("address-placeholder")}
defaultValue={profile?.address ?? ""}
onChange={(e) => handleInputChange("address", e.target.value)}
disabled={pending}
></textarea>
<div id="address-error" aria-live="polite" aria-atomic="true">
{errors?.address &&
errors.address.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("iban-label")}</span>
</label>
<input
id="iban"
name="iban"
type="text"
placeholder={t("iban-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={formatIban(profile?.iban)}
onChange={(e) => handleInputChange("iban", e.target.value)}
disabled={pending}
/>
<div id="iban-error" aria-live="polite" aria-atomic="true">
{errors?.iban &&
errors.iban.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
</>
)}
</fieldset>
<div id="general-error" aria-live="polite" aria-atomic="true">
{message && (

View File

@@ -166,8 +166,9 @@
},
"account-form": {
"title": "Profile Information",
"info-box-message": "This information will be used to generate a 2D barcode displayed in the bill view, allowing tenants to scan it and refund the money you have spent on paying utility bills in their name.",
"warning-missing-data": "Warning: Some profile fields are missing. The 2D barcode will not be displayed to tenants on the shared bill view until all fields are filled in.",
"info-box-message": "By activating this option, a 2D barcode will be included in the monthly statement sent to the tenant, allowing them to make a direct payment to your bank account.",
"tenant-2d-code-legend": "TENANT 2D CODE",
"tenant-2d-code-toggle-label": "include 2D code in monthly statements",
"first-name-label": "First Name",
"first-name-placeholder": "Enter your first name",
"last-name-label": "Last Name",
@@ -179,6 +180,10 @@
"save-button": "Save",
"cancel-button": "Cancel",
"validation": {
"first-name-required": "First name is mandatory",
"last-name-required": "Last name is mandatory",
"address-required": "Address is mandatory",
"iban-required": "Valid IBAN is mandatory",
"iban-invalid": "Invalid IBAN format. Please enter a valid IBAN",
"validation-failed": "Validation failed. Please check the form and try again."
}

View File

@@ -165,8 +165,9 @@
},
"account-form": {
"title": "Podaci o profilu",
"info-box-message": "Ovi podaci će se koristiti za generiranje 2D barkoda koji će biti prikazan u pregledu računa, omogućujući podstanarima da ga skeniraju i vrate novac koji ste potrošili na plaćanje režija u njihovo ime.",
"warning-missing-data": "Upozorenje: Neki podaci profila nedostaju. 2D barkod neće biti prikazan podstanarima u podijeljenom pregledu računa dok sva polja ne budu popunjena.",
"info-box-message": "Ako uključite ovu opciji na mjesečnom obračunu koji se šalje podstanaru biti će prikazan 2D bar kod, putem kojeg će moći izvršiti izravnu uplatu na vaš bankovni račun.",
"tenant-2d-code-legend": "2D BARKOD ZA PODSTANARA",
"tenant-2d-code-toggle-label": "prikazuj 2D barkod u mjesečnom obračunu",
"first-name-label": "Ime",
"first-name-placeholder": "Unesite svoje ime",
"last-name-label": "Prezime",
@@ -178,6 +179,10 @@
"save-button": "Spremi",
"cancel-button": "Odbaci",
"validation": {
"first-name-required": "Ime je obavezno",
"last-name-required": "Prezime je obavezno",
"address-required": "Adresa je obavezna",
"iban-required": "Ispravan IBAN je obavezan",
"iban-invalid": "Neispravan IBAN format. Molimo unesite ispravan IBAN.",
"validation-failed": "Validacija nije uspjela. Molimo provjerite formu i pokušajte ponovno."
}