Files
evidencija-rezija/app/lib/actions/userSettingsActions.ts
Knee Cola 387b7e0256 Rename 'street' to 'ownerStreet' in UserSettings with 25 character max length
Changes:
- Updated UserSettings interface: street -> ownerStreet
- Updated userSettingsActions.ts:
  - Changed State type to use ownerStreet
  - Added max length validation (25 characters) to FormSchema
  - Updated validation refinement to check ownerStreet
  - Updated form data parsing to read ownerStreet
  - Updated database write operations to use ownerStreet
- Updated UserSettingsForm.tsx:
  - Changed state tracking to use ownerStreet
  - Updated validation check to reference ownerStreet
  - Updated input field: id, name, maxLength={25}
- Updated ViewLocationCard.tsx to use ownerStreet instead of street
- Updated English translations:
  - street-label -> owner-street-label: "Your Street and House Number"
  - street-placeholder -> owner-street-placeholder
  - street-required -> owner-street-required
- Updated Croatian translations with corresponding ownerStreet keys

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-22 22:37:04 +01:00

195 lines
5.7 KiB
TypeScript

'use server';
import { z } from 'zod';
import { getDbClient } from '../dbClient';
import { UserSettings } from '../db-types';
import { withUser } from '@/app/lib/auth';
import { AuthenticatedUser } from '../types/next-auth';
import { unstable_noStore as noStore } from 'next/cache';
import { IntlTemplateFn } from '@/app/i18n';
import { getTranslations, getLocale } from "next-intl/server";
import { revalidatePath } from 'next/cache';
import { gotoHomeWithMessage } from './navigationActions';
import * as IBAN from 'iban';
export type State = {
errors?: {
ownerName?: string[];
ownerStreet?: string[];
town?: string[];
iban?: string[];
currency?: string[];
show2dCodeInMonthlyStatement?: string[];
};
message?: string | null;
success?: boolean;
};
/**
* Schema for validating user settings form fields
*/
const FormSchema = (t: IntlTemplateFn) => z.object({
ownerName: z.string().max(25).optional(),
ownerStreet: z.string().max(25).optional(),
town: z.string().optional(),
iban: z.string()
.optional()
.refine(
(val) => {
if (!val || val.trim() === '') return true;
// Remove spaces and validate using iban.js library
const cleaned = val.replace(/\s/g, '').toUpperCase();
return IBAN.isValid(cleaned);
},
{ message: t("iban-invalid") }
),
currency: z.string().optional(),
show2dCodeInMonthlyStatement: z.boolean().optional().nullable(),
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.ownerName && data.ownerName.trim().length > 0;
}
return true;
}, {
message: t("owner-name-required"),
path: ["ownerName"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.ownerStreet && data.ownerStreet.trim().length > 0;
}
return true;
}, {
message: t("owner-street-required"),
path: ["ownerStreet"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.town && data.town.trim().length > 0;
}
return true;
}, {
message: t("town-required"),
path: ["town"],
})
.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"],
})
.refine((data) => {
if (data.show2dCodeInMonthlyStatement) {
return !!data.currency && data.currency.trim().length > 0;
}
return true;
}, {
message: t("currency-required"),
path: ["currency"],
});
/**
* Get user settings
*/
export const getUserSettings = withUser(async (user: AuthenticatedUser) => {
noStore();
const dbClient = await getDbClient();
const { id: userId } = user;
const userSettings = await dbClient.collection<UserSettings>("userSettings")
.findOne({ userId });
return userSettings;
});
/**
* Get user settings by userId (without authentication)
* Used for public/shared pages where we need to display owner's payment information
*/
export const getUserSettingsByUserId = async (userId: string): Promise<UserSettings | null> => {
noStore();
const dbClient = await getDbClient();
const userSettings = await dbClient.collection<UserSettings>("userSettings")
.findOne({ userId });
return userSettings;
};
/**
* Update user settings
*/
export const updateUserSettings = withUser(async (user: AuthenticatedUser, prevState: State, formData: FormData) => {
noStore();
const t = await getTranslations("user-settings-form.validation");
const validatedFields = FormSchema(t).safeParse({
ownerName: formData.get('ownerName') || undefined,
ownerStreet: formData.get('ownerStreet') || undefined,
town: formData.get('town') || undefined,
iban: formData.get('iban') || undefined,
currency: formData.get('currency') || undefined,
show2dCodeInMonthlyStatement: formData.get('generateTenantCode') === 'on',
});
// If form validation fails, return errors early. Otherwise, continue...
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: t("validation-failed"),
success: false,
};
}
const { ownerName, ownerStreet, town, iban, currency, show2dCodeInMonthlyStatement } = validatedFields.data;
// Normalize IBAN: remove spaces and convert to uppercase
const normalizedIban = iban ? iban.replace(/\s/g, '').toUpperCase() : null;
// Update the user settings in MongoDB
const dbClient = await getDbClient();
const { id: userId } = user;
const userSettings: UserSettings = {
userId,
ownerName: ownerName || null,
ownerStreet: ownerStreet || null,
town: town || null,
iban: normalizedIban,
currency: currency || null,
show2dCodeInMonthlyStatement: show2dCodeInMonthlyStatement ?? false,
};
await dbClient.collection<UserSettings>("userSettings")
.updateOne(
{ userId },
{ $set: userSettings },
{ upsert: true }
);
revalidatePath('/settings');
// Get current locale and redirect to home with success message
const locale = await getLocale();
await gotoHomeWithMessage(locale, 'userSettingsSaved');
// This return is needed for TypeScript, but won't be reached due to redirect
return {
message: null,
errors: {},
success: true,
};
});