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 add:*)",
"Bash(git commit:*)", "Bash(git commit:*)",
"mcp__serena__replace_regex", "mcp__serena__replace_regex",
"Bash(npm install:*)" "Bash(npm install:*)",
"mcp__ide__getDiagnostics"
] ]
}, },
"enableAllProjectMcpServers": true, "enableAllProjectMcpServers": true,

View File

@@ -18,6 +18,7 @@ export type State = {
lastName?: string[]; lastName?: string[];
address?: string[]; address?: string[];
iban?: string[]; iban?: string[];
show2dCodeInMonthlyStatement?: string[];
}; };
message?: string | null; message?: string | null;
success?: boolean; success?: boolean;
@@ -41,6 +42,48 @@ const FormSchema = (t: IntlTemplateFn) => z.object({
}, },
{ message: t("iban-invalid") } { 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, lastName: formData.get('lastName') || undefined,
address: formData.get('address') || undefined, address: formData.get('address') || undefined,
iban: formData.get('iban') || undefined, iban: formData.get('iban') || undefined,
show2dCodeInMonthlyStatement: formData.get('generateTenantCode') === 'on',
}); });
// If form validation fails, return errors early. Otherwise, continue... // 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 // Normalize IBAN: remove spaces and convert to uppercase
const normalizedIban = iban ? iban.replace(/\s/g, '').toUpperCase() : null; const normalizedIban = iban ? iban.replace(/\s/g, '').toUpperCase() : null;
@@ -97,6 +141,7 @@ export const updateUserProfile = withUser(async (user: AuthenticatedUser, prevSt
lastName: lastName || null, lastName: lastName || null,
address: address || null, address: address || null,
iban: normalizedIban, iban: normalizedIban,
show2dCodeInMonthlyStatement: show2dCodeInMonthlyStatement ?? false,
}; };
await dbClient.collection<UserProfile>("users") await dbClient.collection<UserProfile>("users")

View File

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

View File

@@ -41,9 +41,33 @@ const FormFields: FC<FormFieldsProps> = ({ profile, errors, message }) => {
const cleanedIban = formValues.iban.replace(/\s/g, ''); const cleanedIban = formValues.iban.replace(/\s/g, '');
const hasMissingData = !formValues.firstName || !formValues.lastName || !formValues.address || !cleanedIban; 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 ( return (
<> <>
<InfoBox>{t("info-box-message")}</InfoBox> <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>
<InfoBox className="p-1 mb-1">{t("info-box-message")}</InfoBox>
<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>
{show2dCodeInMonthlyStatement && (
<>
<div className="form-control w-full"> <div className="form-control w-full">
<label className="label"> <label className="label">
<span className="label-text">{t("first-name-label")}</span> <span className="label-text">{t("first-name-label")}</span>
@@ -138,15 +162,9 @@ const FormFields: FC<FormFieldsProps> = ({ profile, errors, message }) => {
))} ))}
</div> </div>
</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>
)} )}
</fieldset>
<div id="general-error" aria-live="polite" aria-atomic="true"> <div id="general-error" aria-live="polite" aria-atomic="true">
{message && ( {message && (

View File

@@ -166,8 +166,9 @@
}, },
"account-form": { "account-form": {
"title": "Profile Information", "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.", "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.",
"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.", "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-label": "First Name",
"first-name-placeholder": "Enter your first name", "first-name-placeholder": "Enter your first name",
"last-name-label": "Last Name", "last-name-label": "Last Name",
@@ -179,6 +180,10 @@
"save-button": "Save", "save-button": "Save",
"cancel-button": "Cancel", "cancel-button": "Cancel",
"validation": { "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", "iban-invalid": "Invalid IBAN format. Please enter a valid IBAN",
"validation-failed": "Validation failed. Please check the form and try again." "validation-failed": "Validation failed. Please check the form and try again."
} }

View File

@@ -165,8 +165,9 @@
}, },
"account-form": { "account-form": {
"title": "Podaci o profilu", "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.", "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.",
"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.", "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-label": "Ime",
"first-name-placeholder": "Unesite svoje ime", "first-name-placeholder": "Unesite svoje ime",
"last-name-label": "Prezime", "last-name-label": "Prezime",
@@ -178,6 +179,10 @@
"save-button": "Spremi", "save-button": "Spremi",
"cancel-button": "Odbaci", "cancel-button": "Odbaci",
"validation": { "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.", "iban-invalid": "Neispravan IBAN format. Molimo unesite ispravan IBAN.",
"validation-failed": "Validacija nije uspjela. Molimo provjerite formu i pokušajte ponovno." "validation-failed": "Validacija nije uspjela. Molimo provjerite formu i pokušajte ponovno."
} }