Add tenant information fields to LocationEditForm

Added optional tenant fields (first name, last name, email) to billing locations
with a toggle to enable/disable 2D barcode generation for tenants.

Changes:
- Added generateTenantCode, tenantFirstName, tenantLastName, and tenantEmail
  fields to BillingLocation interface
- Updated LocationEditForm with toggle control and conditional tenant fields
- Implemented conditional validation: tenant names required when generateTenantCode is true
- Updated updateOrAddLocation action to persist tenant data across all update operations
- Added localization strings for tenant fields and validation messages (Croatian/English)

The generateTenantCode flag is persisted in the database and controls visibility
of tenant name fields. When enabled, both first and last names become mandatory.

🤖 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 08:23:08 +01:00
parent 365386febb
commit 9ae023cc94
5 changed files with 219 additions and 34 deletions

View File

@@ -14,7 +14,11 @@ import { getTranslations, getLocale } from "next-intl/server";
export type State = { export type State = {
errors?: { errors?: {
locationName?: string[]; locationName?: string[];
locationNotes?: string[], locationNotes?: string[];
generateTenantCode?: string[];
tenantFirstName?: string[];
tenantLastName?: string[];
tenantEmail?: string[];
}; };
message?:string | null; message?:string | null;
}; };
@@ -27,11 +31,34 @@ const FormSchema = (t:IntlTemplateFn) => z.object({
_id: z.string(), _id: z.string(),
locationName: z.coerce.string().min(1, t("location-name-required")), locationName: z.coerce.string().min(1, t("location-name-required")),
locationNotes: z.string(), locationNotes: z.string(),
generateTenantCode: z.boolean().optional().nullable(),
tenantFirstName: z.string().optional().nullable(),
tenantLastName: z.string().optional().nullable(),
tenantEmail: z.string().optional().nullable(),
addToSubsequentMonths: z.boolean().optional().nullable(), addToSubsequentMonths: z.boolean().optional().nullable(),
updateScope: z.enum(["current", "subsequent", "all"]).optional().nullable(), updateScope: z.enum(["current", "subsequent", "all"]).optional().nullable(),
}) })
// dont include the _id field in the response // dont include the _id field in the response
.omit({ _id: true }); .omit({ _id: true })
// Add conditional validation: if generateTenantCode is true, tenant names are required
.refine((data) => {
if (data.generateTenantCode) {
return !!data.tenantFirstName && data.tenantFirstName.trim().length > 0;
}
return true;
}, {
message: t("tenant-first-name-required"),
path: ["tenantFirstName"],
})
.refine((data) => {
if (data.generateTenantCode) {
return !!data.tenantLastName && data.tenantLastName.trim().length > 0;
}
return true;
}, {
message: t("tenant-last-name-required"),
path: ["tenantLastName"],
});
/** /**
* Server-side action which adds or updates a bill * Server-side action which adds or updates a bill
@@ -49,6 +76,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
const validatedFields = FormSchema(t).safeParse({ const validatedFields = FormSchema(t).safeParse({
locationName: formData.get('locationName'), locationName: formData.get('locationName'),
locationNotes: formData.get('locationNotes'), locationNotes: formData.get('locationNotes'),
generateTenantCode: formData.get('generateTenantCode') === 'on',
tenantFirstName: formData.get('tenantFirstName') || null,
tenantLastName: formData.get('tenantLastName') || null,
tenantEmail: formData.get('tenantEmail') || null,
addToSubsequentMonths: formData.get('addToSubsequentMonths') === 'on', addToSubsequentMonths: formData.get('addToSubsequentMonths') === 'on',
updateScope: formData.get('updateScope') as "current" | "subsequent" | "all" | undefined, updateScope: formData.get('updateScope') as "current" | "subsequent" | "all" | undefined,
}); });
@@ -57,13 +88,17 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
if(!validatedFields.success) { if(!validatedFields.success) {
return({ return({
errors: validatedFields.error.flatten().fieldErrors, errors: validatedFields.error.flatten().fieldErrors,
message: "Missing Fields", message: t("validation-failed"),
}); });
} }
const { const {
locationName, locationName,
locationNotes, locationNotes,
generateTenantCode,
tenantFirstName,
tenantLastName,
tenantEmail,
addToSubsequentMonths, addToSubsequentMonths,
updateScope, updateScope,
} = validatedFields.data; } = validatedFields.data;
@@ -97,6 +132,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
$set: { $set: {
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
generateTenantCode: generateTenantCode || false,
tenantFirstName: tenantFirstName || null,
tenantLastName: tenantLastName || null,
tenantEmail: tenantEmail || null,
} }
} }
); );
@@ -118,6 +157,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
$set: { $set: {
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
generateTenantCode: generateTenantCode || false,
tenantFirstName: tenantFirstName || null,
tenantLastName: tenantLastName || null,
tenantEmail: tenantEmail || null,
} }
} }
); );
@@ -132,6 +175,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
$set: { $set: {
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
generateTenantCode: generateTenantCode || false,
tenantFirstName: tenantFirstName || null,
tenantLastName: tenantLastName || null,
tenantEmail: tenantEmail || null,
} }
} }
); );
@@ -144,6 +191,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
userEmail, userEmail,
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
generateTenantCode: generateTenantCode || false,
tenantFirstName: tenantFirstName || null,
tenantLastName: tenantLastName || null,
tenantEmail: tenantEmail || null,
yearMonth: yearMonth, yearMonth: yearMonth,
bills: [], bills: [],
}); });
@@ -208,6 +259,10 @@ export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locat
userEmail, userEmail,
name: locationName, name: locationName,
notes: locationNotes, notes: locationNotes,
generateTenantCode: generateTenantCode || false,
tenantFirstName: tenantFirstName || null,
tenantLastName: tenantLastName || null,
tenantEmail: tenantEmail || null,
yearMonth: { year: monthData.year, month: monthData.month }, yearMonth: { year: monthData.year, month: monthData.month },
bills: [], bills: [],
}); });

View File

@@ -43,6 +43,14 @@ export interface BillingLocation {
bills: Bill[]; bills: Bill[];
/** (optional) notes */ /** (optional) notes */
notes: string|null; notes: string|null;
/** (optional) whether to generate 2D code for tenant */
generateTenantCode?: boolean | null;
/** (optional) tenant first name */
tenantFirstName?: string | null;
/** (optional) tenant last name */
tenantLastName?: string | null;
/** (optional) tenant email */
tenantEmail?: string | null;
}; };
export enum BilledTo { export enum BilledTo {

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import { TrashIcon } from "@heroicons/react/24/outline"; import { TrashIcon } from "@heroicons/react/24/outline";
import { FC } from "react"; import { FC, useState } from "react";
import { BillingLocation, YearMonth } from "../lib/db-types"; import { BillingLocation, YearMonth } from "../lib/db-types";
import { updateOrAddLocation } from "../lib/actions/locationActions"; import { updateOrAddLocation } from "../lib/actions/locationActions";
import { useFormState } from "react-dom"; import { useFormState } from "react-dom";
@@ -20,14 +20,29 @@ export type LocationEditFormProps = {
yearMonth: YearMonth yearMonth: YearMonth
} }
export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth }) => export const LocationEditForm: FC<LocationEditFormProps> = ({ location, yearMonth }) => {
{
const initialState = { message: null, errors: {} }; const initialState = { message: null, errors: {} };
const handleAction = updateOrAddLocation.bind(null, location?._id, location?.yearMonth ?? yearMonth); const handleAction = updateOrAddLocation.bind(null, location?._id, location?.yearMonth ?? yearMonth);
const [state, dispatch] = useFormState(handleAction, initialState); const [state, dispatch] = useFormState(handleAction, initialState);
const t = useTranslations("location-edit-form"); const t = useTranslations("location-edit-form");
const locale = useLocale(); const locale = useLocale();
// Track whether to generate 2D code for tenant (use persisted value from database)
const [generateTenantCode, setGenerateTenantCode] = useState(
location?.generateTenantCode ?? false
);
// Track tenant field values for real-time validation
const [tenantFields, setTenantFields] = useState({
tenantFirstName: location?.tenantFirstName ?? "",
tenantLastName: location?.tenantLastName ?? "",
tenantEmail: location?.tenantEmail ?? "",
});
const handleTenantFieldChange = (field: keyof typeof tenantFields, value: string) => {
setTenantFields(prev => ({ ...prev, [field]: value }));
};
let { year, month } = location ? location.yearMonth : yearMonth; let { year, month } = location ? location.yearMonth : yearMonth;
return ( return (
@@ -60,6 +75,92 @@ export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth
))} ))}
</div> </div>
<div className="form-control mt-4">
<label className="label cursor-pointer justify-start gap-3">
<input
type="checkbox"
name="generateTenantCode"
className="toggle toggle-primary"
checked={generateTenantCode}
onChange={(e) => setGenerateTenantCode(e.target.checked)}
/>
<span className="label-text">{t("generate-tenant-code")}</span>
</label>
</div>
{generateTenantCode && (
<>
<div className="form-control w-full">
<label className="label">
<span className="label-text">{t("tenant-first-name-label")}</span>
</label>
<input
id="tenantFirstName"
name="tenantFirstName"
type="text"
placeholder={t("tenant-first-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={location?.tenantFirstName ?? ""}
onChange={(e) => handleTenantFieldChange("tenantFirstName", e.target.value)}
/>
<div id="tenantFirstName-error" aria-live="polite" aria-atomic="true">
{state.errors?.tenantFirstName &&
state.errors.tenantFirstName.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("tenant-last-name-label")}</span>
</label>
<input
id="tenantLastName"
name="tenantLastName"
type="text"
placeholder={t("tenant-last-name-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={location?.tenantLastName ?? ""}
onChange={(e) => handleTenantFieldChange("tenantLastName", e.target.value)}
/>
<div id="tenantLastName-error" aria-live="polite" aria-atomic="true">
{state.errors?.tenantLastName &&
state.errors.tenantLastName.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("tenant-email-label")}</span>
</label>
<input
id="tenantEmail"
name="tenantEmail"
type="email"
placeholder={t("tenant-email-placeholder")}
className="input input-bordered w-full placeholder:text-gray-600"
defaultValue={location?.tenantEmail ?? ""}
onChange={(e) => handleTenantFieldChange("tenantEmail", e.target.value)}
/>
<div id="tenantEmail-error" aria-live="polite" aria-atomic="true">
{state.errors?.tenantEmail &&
state.errors.tenantEmail.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div>
{/* Show different options for add vs edit operations */} {/* Show different options for add vs edit operations */}
{!location ? ( {!location ? (
<div className="form-control"> <div className="form-control">
@@ -108,8 +209,7 @@ export const LocationEditForm:FC<LocationEditFormProps> = ({ location, yearMonth
) )
} }
export const LocationEditFormSkeleton:FC = () => export const LocationEditFormSkeleton: FC = () => {
{
return ( return (
<div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1"> <div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1">
<div className="card-body"> <div className="card-body">

View File

@@ -124,6 +124,14 @@
"location-edit-form": { "location-edit-form": {
"location-name-placeholder": "Realestate name", "location-name-placeholder": "Realestate name",
"notes-placeholder": "Notes", "notes-placeholder": "Notes",
"generate-tenant-code": "Generate 2D code for tenant",
"tenant-first-name-label": "Tenant First Name",
"tenant-first-name-placeholder": "Enter tenant's first name",
"tenant-last-name-label": "Tenant Last Name",
"tenant-last-name-placeholder": "Enter tenant's last name",
"tenant-email-label": "Tenant Email",
"tenant-email-placeholder": "Enter tenant's email",
"warning-missing-tenant-names": "Warning: Tenant first and last name are missing. The 2D barcode will not be displayed to the tenant when they open the shared link until both fields are filled in.",
"save-button": "Save", "save-button": "Save",
"cancel-button": "Cancel", "cancel-button": "Cancel",
"delete-tooltip": "Delete realestate", "delete-tooltip": "Delete realestate",
@@ -133,7 +141,10 @@
"update-subsequent-months": "current and all future months", "update-subsequent-months": "current and all future months",
"update-all-months": "all months", "update-all-months": "all months",
"validation": { "validation": {
"location-name-required": "Relaestate name is required" "location-name-required": "Relaestate name is required",
"tenant-first-name-required": "tenant first name is missing",
"tenant-last-name-required": "tenant last name is missing",
"validation-failed": "Validation failed. Please check the form and try again."
} }
}, },
"account-form": { "account-form": {

View File

@@ -123,6 +123,14 @@
"location-edit-form": { "location-edit-form": {
"location-name-placeholder": "Ime nekretnine", "location-name-placeholder": "Ime nekretnine",
"notes-placeholder": "Bilješke", "notes-placeholder": "Bilješke",
"generate-tenant-code": "Generiraj 2D barkod za podstanara",
"tenant-first-name-label": "Ime podstanara",
"tenant-first-name-placeholder": "Unesite ime podstanara",
"tenant-last-name-label": "Prezime podstanara",
"tenant-last-name-placeholder": "Unesite prezime podstanara",
"tenant-email-label": "Email podstanara",
"tenant-email-placeholder": "Unesite email podstanara",
"warning-missing-tenant-names": "Upozorenje: Ime i prezime podstanara nedostaju. 2D barkod neće biti prikazan podstanaru kada otvori podijeljenu poveznicu dok oba polja ne budu popunjena.",
"save-button": "Spremi", "save-button": "Spremi",
"cancel-button": "Odbaci", "cancel-button": "Odbaci",
"delete-tooltip": "Brisanje nekretnine", "delete-tooltip": "Brisanje nekretnine",
@@ -132,7 +140,10 @@
"update-subsequent-months": "trenutni i svi budući mjeseci", "update-subsequent-months": "trenutni i svi budući mjeseci",
"update-all-months": "svi mjeseci", "update-all-months": "svi mjeseci",
"validation": { "validation": {
"location-name-required": "Ime nekretnine je obavezno" "location-name-required": "Ime nekretnine je obavezno",
"tenant-first-name-required": "nedostaje ime podstanara",
"tenant-last-name-required": "nedostaje prezime podstanara",
"validation-failed": "Validacija nije uspjela. Molimo provjerite formu i pokušajte ponovno."
} }
}, },
"account-form": { "account-form": {