feat(i18n): country/phone/timezone/subdivision primitives + form wiring
Cross-cutting i18n polish for forms across the marina + residential + company
domains. Introduces a single source of truth for country/phone/timezone/
subdivision data and replaces every nationality-as-free-text and timezone-
as-string Input with a dedicated combobox.
PR1 Countries — ALL_COUNTRY_CODES (~250 ISO-3166-1 alpha-2), Intl.DisplayNames
for localized labels, detectDefaultCountry() with navigator-region
fallback to US, CountryCombobox with regional-indicator flag glyphs +
compact mode for inline use.
PR2 Phone — libphonenumber-js wrapper (parsePhone / formatAsYouType /
callingCodeFor), PhoneInput with flag dropdown + national-format
AsYouType + paste-detect that flips the country dropdown for pasted
international strings.
PR3 Timezones — country->IANA map (250 entries, multi-zone for AU/BR/CA/CD/
ID/KZ/MN/MX/RU/US), formatTimezoneLabel ("Europe/London (UTC+1)"),
TimezoneCombobox with Suggested/All grouping driven by countryHint.
PR4 Subdivisions — wraps the iso-3166-2 npm package (~5000 ISO 3166-2
codes for every country), per-country cache, SubdivisionCombobox with
"Pick a country first" / "No regions available" empty states.
PR5 Schema deltas (migration 0015) — clients.nationality_iso, clientContacts
{value_e164, value_country}, clientAddresses {country_iso, subdivision_iso},
residentialClients {phone_e164, phone_country, nationality_iso, timezone,
place_of_residence_country_iso, subdivision_iso}, companies {incorporation_
country_iso, incorporation_subdivision_iso}, companyAddresses {country_iso,
subdivision_iso}. Plus shared zod validators (validators/i18n.ts) used
by every entity validator + route handler.
PR6 ClientForm + ClientDetail — CountryCombobox replaces nationality Input,
TimezoneCombobox replaces timezone Input (driven by nationalityIso hint),
PhoneInput conditionally rendered for phone/whatsapp contacts. Inline
editors (InlineCountryField / InlineTimezoneField / InlinePhoneField)
for the detail-page overview rows + ContactsEditor.
PR7 Residential client form + detail — phone -> PhoneInput, nationality/
timezone/place-of-residence-country/subdivision rows in both create
sheet and inline-editable detail view. Subdivision wipes when country
flips since codes are country-scoped.
PR8 Company form + detail — incorporation country -> CountryCombobox,
incorporation region -> SubdivisionCombobox in both modes.
PR9 Public inquiry endpoint — accepts pre-normalized phoneE164/phoneCountry
and i18n fields from newer website builds, server-side parsePhone()
fallback for legacy raw-international submissions. Old Nuxt builds
keep working unchanged.
Tests: 4 unit suites for the primitives (25 tests), 1 integration spec for
the public phone-normalization path (3 tests), 1 smoke spec asserting the
combobox triggers render in all three create sheets.
Test totals: vitest 713 -> 741 (+28).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
16
src/lib/db/migrations/0015_i18n_columns.sql
Normal file
16
src/lib/db/migrations/0015_i18n_columns.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
ALTER TABLE "client_addresses" ADD COLUMN "subdivision_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "client_addresses" ADD COLUMN "country_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "client_contacts" ADD COLUMN "value_e164" text;--> statement-breakpoint
|
||||
ALTER TABLE "client_contacts" ADD COLUMN "value_country" text;--> statement-breakpoint
|
||||
ALTER TABLE "clients" ADD COLUMN "nationality_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "companies" ADD COLUMN "incorporation_country_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "companies" ADD COLUMN "incorporation_subdivision_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "company_addresses" ADD COLUMN "subdivision_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "company_addresses" ADD COLUMN "country_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "phone_e164" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "phone_country" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "nationality_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "timezone" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "place_of_residence_country_iso" text;--> statement-breakpoint
|
||||
ALTER TABLE "residential_clients" ADD COLUMN "subdivision_iso" text;--> statement-breakpoint
|
||||
CREATE INDEX "idx_clients_nationality_iso" ON "clients" USING btree ("nationality_iso");
|
||||
9885
src/lib/db/migrations/meta/0015_snapshot.json
Normal file
9885
src/lib/db/migrations/meta/0015_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -106,6 +106,13 @@
|
||||
"when": 1777379952283,
|
||||
"tag": "0014_black_banshee",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 15,
|
||||
"version": "7",
|
||||
"when": 1777391373291,
|
||||
"tag": "0015_i18n_columns",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -22,8 +22,12 @@ export const clients = pgTable(
|
||||
.references(() => ports.id),
|
||||
fullName: text('full_name').notNull(),
|
||||
nationality: text('nationality'),
|
||||
/** ISO-3166-1 alpha-2 nationality code. Supersedes `nationality`
|
||||
* after the i18n backfill (PR10) drops the legacy column. */
|
||||
nationalityIso: text('nationality_iso'),
|
||||
preferredContactMethod: text('preferred_contact_method'), // email, phone, whatsapp
|
||||
preferredLanguage: text('preferred_language'),
|
||||
/** IANA timezone, e.g. 'Europe/Warsaw'. Validated client + server. */
|
||||
timezone: text('timezone'),
|
||||
source: text('source'), // website, manual, referral, broker
|
||||
sourceDetails: text('source_details'),
|
||||
@@ -35,6 +39,7 @@ export const clients = pgTable(
|
||||
index('idx_clients_port').on(table.portId),
|
||||
index('idx_clients_name').on(table.portId, table.fullName),
|
||||
index('idx_clients_archived').on(table.portId, table.archivedAt),
|
||||
index('idx_clients_nationality_iso').on(table.nationalityIso),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -49,6 +54,10 @@ export const clientContacts = pgTable(
|
||||
.references(() => clients.id, { onDelete: 'cascade' }),
|
||||
channel: text('channel').notNull(), // email, phone, whatsapp, other
|
||||
value: text('value').notNull(),
|
||||
/** E.164-normalized phone number (only set when channel='phone'/'whatsapp'). */
|
||||
valueE164: text('value_e164'),
|
||||
/** ISO-3166-1 alpha-2 of the country this number was parsed against. */
|
||||
valueCountry: text('value_country'),
|
||||
label: text('label'), // primary, secondary, work, personal, broker, assistant
|
||||
isPrimary: boolean('is_primary').notNull().default(false),
|
||||
notes: text('notes'),
|
||||
@@ -154,8 +163,12 @@ export const clientAddresses = pgTable(
|
||||
streetAddress: text('street_address'),
|
||||
city: text('city'),
|
||||
stateProvince: text('state_province'),
|
||||
/** ISO 3166-2 subdivision code (e.g. 'PL-MZ', 'US-CA'). Optional. */
|
||||
subdivisionIso: text('subdivision_iso'),
|
||||
postalCode: text('postal_code'),
|
||||
country: text('country'),
|
||||
/** ISO-3166-1 alpha-2 country code. Supersedes `country` after backfill. */
|
||||
countryIso: text('country_iso'),
|
||||
isPrimary: boolean('is_primary').notNull().default(true),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
|
||||
@@ -25,6 +25,11 @@ export const companies = pgTable(
|
||||
taxId: text('tax_id'),
|
||||
registrationNumber: text('registration_number'),
|
||||
incorporationCountry: text('incorporation_country'),
|
||||
/** ISO-3166-1 alpha-2 country of incorporation. Replaces the
|
||||
* free-text `incorporation_country` after the i18n backfill. */
|
||||
incorporationCountryIso: text('incorporation_country_iso'),
|
||||
/** ISO 3166-2 subdivision (state/province) of incorporation. Optional. */
|
||||
incorporationSubdivisionIso: text('incorporation_subdivision_iso'),
|
||||
incorporationDate: timestamp('incorporation_date', { withTimezone: true, mode: 'date' }),
|
||||
status: text('status').notNull().default('active'), // 'active' | 'dissolved'
|
||||
billingEmail: text('billing_email'),
|
||||
@@ -89,8 +94,12 @@ export const companyAddresses = pgTable(
|
||||
streetAddress: text('street_address'),
|
||||
city: text('city'),
|
||||
stateProvince: text('state_province'),
|
||||
/** ISO 3166-2 subdivision code. Optional. */
|
||||
subdivisionIso: text('subdivision_iso'),
|
||||
postalCode: text('postal_code'),
|
||||
country: text('country'),
|
||||
/** ISO-3166-1 alpha-2 country code. Supersedes `country` after backfill. */
|
||||
countryIso: text('country_iso'),
|
||||
isPrimary: boolean('is_primary').notNull().default(true),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
|
||||
@@ -20,7 +20,21 @@ export const residentialClients = pgTable(
|
||||
fullName: text('full_name').notNull(),
|
||||
email: text('email'),
|
||||
phone: text('phone'),
|
||||
/** E.164-normalized phone, populated alongside `phone` once the i18n
|
||||
* PhoneInput component lands. The free-text `phone` column stays
|
||||
* for one release as a fallback for unparseable rows. */
|
||||
phoneE164: text('phone_e164'),
|
||||
/** ISO-3166-1 alpha-2 — country the phone was parsed against. */
|
||||
phoneCountry: text('phone_country'),
|
||||
/** ISO-3166-1 alpha-2 nationality. */
|
||||
nationalityIso: text('nationality_iso'),
|
||||
/** IANA timezone for scheduling/reminders. */
|
||||
timezone: text('timezone'),
|
||||
placeOfResidence: text('place_of_residence'),
|
||||
/** ISO-3166-1 alpha-2 country of residence. */
|
||||
placeOfResidenceCountryIso: text('place_of_residence_country_iso'),
|
||||
/** ISO 3166-2 subdivision code for place of residence. Optional. */
|
||||
subdivisionIso: text('subdivision_iso'),
|
||||
preferredContactMethod: text('preferred_contact_method'), // email | phone
|
||||
/**
|
||||
* Lifecycle: prospect | active | inactive. Distinct from
|
||||
|
||||
311
src/lib/i18n/countries.ts
Normal file
311
src/lib/i18n/countries.ts
Normal file
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* ISO-3166-1 alpha-2 country list.
|
||||
*
|
||||
* Source: full ISO 3166-1 list as of 2026-04 (250 codes incl. UN
|
||||
* member states + recognized territories). Country *names* are
|
||||
* resolved at render time via `Intl.DisplayNames` so we don't ship
|
||||
* a localized name table — the browser already has it.
|
||||
*
|
||||
* Validation uses the `ISO_COUNTRIES` Set; render uses
|
||||
* `getCountryName(iso, locale)`.
|
||||
*/
|
||||
|
||||
export const ALL_COUNTRY_CODES = [
|
||||
'AD',
|
||||
'AE',
|
||||
'AF',
|
||||
'AG',
|
||||
'AI',
|
||||
'AL',
|
||||
'AM',
|
||||
'AO',
|
||||
'AQ',
|
||||
'AR',
|
||||
'AS',
|
||||
'AT',
|
||||
'AU',
|
||||
'AW',
|
||||
'AX',
|
||||
'AZ',
|
||||
'BA',
|
||||
'BB',
|
||||
'BD',
|
||||
'BE',
|
||||
'BF',
|
||||
'BG',
|
||||
'BH',
|
||||
'BI',
|
||||
'BJ',
|
||||
'BL',
|
||||
'BM',
|
||||
'BN',
|
||||
'BO',
|
||||
'BQ',
|
||||
'BR',
|
||||
'BS',
|
||||
'BT',
|
||||
'BV',
|
||||
'BW',
|
||||
'BY',
|
||||
'BZ',
|
||||
'CA',
|
||||
'CC',
|
||||
'CD',
|
||||
'CF',
|
||||
'CG',
|
||||
'CH',
|
||||
'CI',
|
||||
'CK',
|
||||
'CL',
|
||||
'CM',
|
||||
'CN',
|
||||
'CO',
|
||||
'CR',
|
||||
'CU',
|
||||
'CV',
|
||||
'CW',
|
||||
'CX',
|
||||
'CY',
|
||||
'CZ',
|
||||
'DE',
|
||||
'DJ',
|
||||
'DK',
|
||||
'DM',
|
||||
'DO',
|
||||
'DZ',
|
||||
'EC',
|
||||
'EE',
|
||||
'EG',
|
||||
'EH',
|
||||
'ER',
|
||||
'ES',
|
||||
'ET',
|
||||
'FI',
|
||||
'FJ',
|
||||
'FK',
|
||||
'FM',
|
||||
'FO',
|
||||
'FR',
|
||||
'GA',
|
||||
'GB',
|
||||
'GD',
|
||||
'GE',
|
||||
'GF',
|
||||
'GG',
|
||||
'GH',
|
||||
'GI',
|
||||
'GL',
|
||||
'GM',
|
||||
'GN',
|
||||
'GP',
|
||||
'GQ',
|
||||
'GR',
|
||||
'GS',
|
||||
'GT',
|
||||
'GU',
|
||||
'GW',
|
||||
'GY',
|
||||
'HK',
|
||||
'HM',
|
||||
'HN',
|
||||
'HR',
|
||||
'HT',
|
||||
'HU',
|
||||
'ID',
|
||||
'IE',
|
||||
'IL',
|
||||
'IM',
|
||||
'IN',
|
||||
'IO',
|
||||
'IQ',
|
||||
'IR',
|
||||
'IS',
|
||||
'IT',
|
||||
'JE',
|
||||
'JM',
|
||||
'JO',
|
||||
'JP',
|
||||
'KE',
|
||||
'KG',
|
||||
'KH',
|
||||
'KI',
|
||||
'KM',
|
||||
'KN',
|
||||
'KP',
|
||||
'KR',
|
||||
'KW',
|
||||
'KY',
|
||||
'KZ',
|
||||
'LA',
|
||||
'LB',
|
||||
'LC',
|
||||
'LI',
|
||||
'LK',
|
||||
'LR',
|
||||
'LS',
|
||||
'LT',
|
||||
'LU',
|
||||
'LV',
|
||||
'LY',
|
||||
'MA',
|
||||
'MC',
|
||||
'MD',
|
||||
'ME',
|
||||
'MF',
|
||||
'MG',
|
||||
'MH',
|
||||
'MK',
|
||||
'ML',
|
||||
'MM',
|
||||
'MN',
|
||||
'MO',
|
||||
'MP',
|
||||
'MQ',
|
||||
'MR',
|
||||
'MS',
|
||||
'MT',
|
||||
'MU',
|
||||
'MV',
|
||||
'MW',
|
||||
'MX',
|
||||
'MY',
|
||||
'MZ',
|
||||
'NA',
|
||||
'NC',
|
||||
'NE',
|
||||
'NF',
|
||||
'NG',
|
||||
'NI',
|
||||
'NL',
|
||||
'NO',
|
||||
'NP',
|
||||
'NR',
|
||||
'NU',
|
||||
'NZ',
|
||||
'OM',
|
||||
'PA',
|
||||
'PE',
|
||||
'PF',
|
||||
'PG',
|
||||
'PH',
|
||||
'PK',
|
||||
'PL',
|
||||
'PM',
|
||||
'PN',
|
||||
'PR',
|
||||
'PS',
|
||||
'PT',
|
||||
'PW',
|
||||
'PY',
|
||||
'QA',
|
||||
'RE',
|
||||
'RO',
|
||||
'RS',
|
||||
'RU',
|
||||
'RW',
|
||||
'SA',
|
||||
'SB',
|
||||
'SC',
|
||||
'SD',
|
||||
'SE',
|
||||
'SG',
|
||||
'SH',
|
||||
'SI',
|
||||
'SJ',
|
||||
'SK',
|
||||
'SL',
|
||||
'SM',
|
||||
'SN',
|
||||
'SO',
|
||||
'SR',
|
||||
'SS',
|
||||
'ST',
|
||||
'SV',
|
||||
'SX',
|
||||
'SY',
|
||||
'SZ',
|
||||
'TC',
|
||||
'TD',
|
||||
'TF',
|
||||
'TG',
|
||||
'TH',
|
||||
'TJ',
|
||||
'TK',
|
||||
'TL',
|
||||
'TM',
|
||||
'TN',
|
||||
'TO',
|
||||
'TR',
|
||||
'TT',
|
||||
'TV',
|
||||
'TW',
|
||||
'TZ',
|
||||
'UA',
|
||||
'UG',
|
||||
'UM',
|
||||
'US',
|
||||
'UY',
|
||||
'UZ',
|
||||
'VA',
|
||||
'VC',
|
||||
'VE',
|
||||
'VG',
|
||||
'VI',
|
||||
'VN',
|
||||
'VU',
|
||||
'WF',
|
||||
'WS',
|
||||
'YE',
|
||||
'YT',
|
||||
'ZA',
|
||||
'ZM',
|
||||
'ZW',
|
||||
] as const;
|
||||
|
||||
export type CountryCode = (typeof ALL_COUNTRY_CODES)[number];
|
||||
|
||||
export const ISO_COUNTRIES: ReadonlySet<string> = new Set(ALL_COUNTRY_CODES);
|
||||
|
||||
export function isValidCountryCode(code: string): code is CountryCode {
|
||||
return ISO_COUNTRIES.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser-localized display name for a country code.
|
||||
* Caches `Intl.DisplayNames` instances by locale to avoid repeated allocation.
|
||||
*/
|
||||
const displayNameCache = new Map<string, Intl.DisplayNames>();
|
||||
|
||||
function getDisplay(locale: string): Intl.DisplayNames {
|
||||
let dn = displayNameCache.get(locale);
|
||||
if (!dn) {
|
||||
dn = new Intl.DisplayNames([locale], { type: 'region' });
|
||||
displayNameCache.set(locale, dn);
|
||||
}
|
||||
return dn;
|
||||
}
|
||||
|
||||
export function getCountryName(code: string, locale = 'en'): string {
|
||||
if (!isValidCountryCode(code)) return code;
|
||||
try {
|
||||
return getDisplay(locale).of(code) ?? code;
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect a sensible default country from the runtime context.
|
||||
* Browser path: navigator.language (`'en-GB'` → `'GB'`).
|
||||
* Server / unknown path: falls back to the provided default (`'US'` per spec).
|
||||
*/
|
||||
export function detectDefaultCountry(fallback: CountryCode = 'US'): CountryCode {
|
||||
if (typeof navigator === 'undefined') return fallback;
|
||||
const lang = navigator.language;
|
||||
if (!lang) return fallback;
|
||||
// Locale tags look like 'en', 'en-US', 'pl-PL'. Take the region part.
|
||||
const parts = lang.split('-');
|
||||
const region = parts.length > 1 ? parts[parts.length - 1]?.toUpperCase() : '';
|
||||
if (region && isValidCountryCode(region)) return region;
|
||||
return fallback;
|
||||
}
|
||||
80
src/lib/i18n/phone.ts
Normal file
80
src/lib/i18n/phone.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Phone-number helpers built on libphonenumber-js.
|
||||
*
|
||||
* Uses the default `min` build (~110 KB gz). The `/mobile` build
|
||||
* rejects landlines and reserved-range numbers, which is wrong for
|
||||
* a marina CRM where clients commonly give office numbers.
|
||||
* The `/max` build adds carrier/geocoding we don't need.
|
||||
*/
|
||||
|
||||
import {
|
||||
AsYouType,
|
||||
parsePhoneNumberFromString,
|
||||
isValidPhoneNumber as libIsValid,
|
||||
getCountryCallingCode,
|
||||
type CountryCode as LibCountryCode,
|
||||
} from 'libphonenumber-js';
|
||||
|
||||
import type { CountryCode } from './countries';
|
||||
|
||||
export interface ParsedPhone {
|
||||
/** E.164 form, e.g. '+442079460958'. Null when the input isn't parseable. */
|
||||
e164: string | null;
|
||||
/** ISO alpha-2 of the country the number was parsed against. */
|
||||
country: CountryCode | null;
|
||||
/** Display-friendly national format, e.g. '020 7946 0958'. */
|
||||
national: string | null;
|
||||
/** Display-friendly international format, e.g. '+44 20 7946 0958'. */
|
||||
international: string | null;
|
||||
isValid: boolean;
|
||||
}
|
||||
|
||||
const EMPTY: ParsedPhone = {
|
||||
e164: null,
|
||||
country: null,
|
||||
national: null,
|
||||
international: null,
|
||||
isValid: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a raw user-typed phone string into a normalized record.
|
||||
* `defaultCountry` provides context when the input lacks a +country prefix.
|
||||
*/
|
||||
export function parsePhone(raw: string, defaultCountry?: CountryCode): ParsedPhone {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return EMPTY;
|
||||
try {
|
||||
const parsed = parsePhoneNumberFromString(trimmed, defaultCountry as LibCountryCode);
|
||||
if (!parsed) return EMPTY;
|
||||
return {
|
||||
e164: parsed.number,
|
||||
country: (parsed.country ?? null) as CountryCode | null,
|
||||
national: parsed.formatNational(),
|
||||
international: parsed.formatInternational(),
|
||||
isValid: parsed.isValid(),
|
||||
};
|
||||
} catch {
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the in-progress digits with `AsYouType` for live typing.
|
||||
* Returns the formatted string in the country's national style.
|
||||
*/
|
||||
export function formatAsYouType(raw: string, country: CountryCode): string {
|
||||
const formatter = new AsYouType(country as LibCountryCode);
|
||||
return formatter.input(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict validation for zod / form layer. Accepts E.164 only.
|
||||
*/
|
||||
export function isValidE164(value: string): boolean {
|
||||
return libIsValid(value);
|
||||
}
|
||||
|
||||
export function callingCodeFor(country: CountryCode): string {
|
||||
return `+${getCountryCallingCode(country as LibCountryCode)}`;
|
||||
}
|
||||
79
src/lib/i18n/subdivisions.ts
Normal file
79
src/lib/i18n/subdivisions.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Country → ISO 3166-2 subdivision (state/province/region) catalog.
|
||||
*
|
||||
* Backed by the `iso-3166-2` npm package which ships the full ISO
|
||||
* 3166-2 dataset (~5000 entries across every country). We expose a
|
||||
* thin wrapper so the combobox doesn't have to know the library
|
||||
* shape, and so we can normalize the records into a uniform
|
||||
* `{ code, name }` pair.
|
||||
*
|
||||
* Subdivisions are an OPTIONAL field per the v1 spec. Countries
|
||||
* without recognized subdivisions return an empty array; the
|
||||
* combobox renders an empty state in that case.
|
||||
*/
|
||||
|
||||
import isoCountries from 'iso-3166-2';
|
||||
|
||||
import type { CountryCode } from './countries';
|
||||
|
||||
export interface Subdivision {
|
||||
/** ISO 3166-2 code, e.g. 'PL-MZ', 'US-CA', 'GB-SCT'. */
|
||||
code: string;
|
||||
/** Display name (English baseline from the iso-3166-2 dataset). */
|
||||
name: string;
|
||||
/** Subdivision type — 'State', 'Province', 'Region', etc. */
|
||||
type?: string;
|
||||
}
|
||||
|
||||
interface IsoCountryRecord {
|
||||
name: string;
|
||||
sub: Record<string, { type: string; name: string }>;
|
||||
}
|
||||
|
||||
const cache = new Map<string, readonly Subdivision[]>();
|
||||
|
||||
function loadFor(country: CountryCode): readonly Subdivision[] {
|
||||
const hit = cache.get(country);
|
||||
if (hit) return hit;
|
||||
// The `iso-3166-2` package exposes a `country` lookup. Defensive
|
||||
// because some country codes (e.g. obscure territories) lack subs.
|
||||
const lookup = (isoCountries as unknown as { country: (c: string) => IsoCountryRecord | null })
|
||||
.country;
|
||||
const record = lookup ? lookup(country) : null;
|
||||
if (!record?.sub) {
|
||||
cache.set(country, []);
|
||||
return [];
|
||||
}
|
||||
const list: Subdivision[] = Object.entries(record.sub)
|
||||
.map(([code, { name, type }]) => ({ code, name, type }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
cache.set(country, list);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the subdivision list for a country. Empty array when none
|
||||
* are recognized — caller can use this to hide the field.
|
||||
*/
|
||||
export function subdivisionsForCountry(country: CountryCode): readonly Subdivision[] {
|
||||
return loadFor(country);
|
||||
}
|
||||
|
||||
export function hasSubdivisions(country: CountryCode): boolean {
|
||||
return loadFor(country).length > 0;
|
||||
}
|
||||
|
||||
export function isValidSubdivisionCode(code: string): boolean {
|
||||
// ISO 3166-2 codes follow `XX-YYY` — derive the country from the prefix.
|
||||
const country = code.split('-')[0];
|
||||
if (!country || country.length !== 2) return false;
|
||||
const list = loadFor(country as CountryCode);
|
||||
return list.some((s) => s.code === code);
|
||||
}
|
||||
|
||||
export function getSubdivisionName(code: string): string {
|
||||
const country = code.split('-')[0];
|
||||
if (!country) return code;
|
||||
const list = loadFor(country as CountryCode);
|
||||
return list.find((s) => s.code === code)?.name ?? code;
|
||||
}
|
||||
411
src/lib/i18n/timezones.ts
Normal file
411
src/lib/i18n/timezones.ts
Normal file
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* Country → IANA timezone mapping.
|
||||
*
|
||||
* For single-zone countries, value is one IANA string.
|
||||
* For multi-zone countries, value is the primary IANA string followed
|
||||
* by all valid alternates. Source: IANA tzdb (current as of 2026-04).
|
||||
*
|
||||
* The full ~600-entry IANA list comes from `Intl.supportedValuesOf('timeZone')`
|
||||
* at runtime; this map only handles the country→default lookup.
|
||||
*/
|
||||
|
||||
import type { CountryCode } from './countries';
|
||||
|
||||
type TimezoneList = readonly [primary: string, ...alternates: string[]];
|
||||
|
||||
// Multi-zone countries — list every IANA zone.
|
||||
const MULTI_ZONE: Partial<Record<CountryCode, TimezoneList>> = {
|
||||
AU: [
|
||||
'Australia/Sydney',
|
||||
'Australia/Melbourne',
|
||||
'Australia/Brisbane',
|
||||
'Australia/Adelaide',
|
||||
'Australia/Perth',
|
||||
'Australia/Hobart',
|
||||
'Australia/Darwin',
|
||||
],
|
||||
BR: [
|
||||
'America/Sao_Paulo',
|
||||
'America/Manaus',
|
||||
'America/Rio_Branco',
|
||||
'America/Belem',
|
||||
'America/Recife',
|
||||
'America/Cuiaba',
|
||||
'America/Fortaleza',
|
||||
'America/Bahia',
|
||||
'America/Noronha',
|
||||
],
|
||||
CA: [
|
||||
'America/Toronto',
|
||||
'America/Vancouver',
|
||||
'America/Edmonton',
|
||||
'America/Winnipeg',
|
||||
'America/Halifax',
|
||||
'America/St_Johns',
|
||||
'America/Regina',
|
||||
'America/Whitehorse',
|
||||
],
|
||||
CD: ['Africa/Kinshasa', 'Africa/Lubumbashi'],
|
||||
ID: ['Asia/Jakarta', 'Asia/Pontianak', 'Asia/Makassar', 'Asia/Jayapura'],
|
||||
KZ: [
|
||||
'Asia/Almaty',
|
||||
'Asia/Atyrau',
|
||||
'Asia/Aqtau',
|
||||
'Asia/Aqtobe',
|
||||
'Asia/Oral',
|
||||
'Asia/Qostanay',
|
||||
'Asia/Qyzylorda',
|
||||
],
|
||||
MN: ['Asia/Ulaanbaatar', 'Asia/Hovd', 'Asia/Choibalsan'],
|
||||
MX: [
|
||||
'America/Mexico_City',
|
||||
'America/Cancun',
|
||||
'America/Merida',
|
||||
'America/Monterrey',
|
||||
'America/Mazatlan',
|
||||
'America/Chihuahua',
|
||||
'America/Hermosillo',
|
||||
'America/Tijuana',
|
||||
],
|
||||
RU: [
|
||||
'Europe/Moscow',
|
||||
'Europe/Kaliningrad',
|
||||
'Europe/Samara',
|
||||
'Asia/Yekaterinburg',
|
||||
'Asia/Omsk',
|
||||
'Asia/Novosibirsk',
|
||||
'Asia/Krasnoyarsk',
|
||||
'Asia/Irkutsk',
|
||||
'Asia/Yakutsk',
|
||||
'Asia/Vladivostok',
|
||||
'Asia/Magadan',
|
||||
'Asia/Kamchatka',
|
||||
],
|
||||
US: [
|
||||
'America/New_York',
|
||||
'America/Chicago',
|
||||
'America/Denver',
|
||||
'America/Los_Angeles',
|
||||
'America/Phoenix',
|
||||
'America/Anchorage',
|
||||
'America/Honolulu',
|
||||
'America/Indianapolis',
|
||||
'America/Detroit',
|
||||
'America/Boise',
|
||||
'America/Adak',
|
||||
'America/Juneau',
|
||||
'America/Nome',
|
||||
'Pacific/Guam',
|
||||
'America/Puerto_Rico',
|
||||
],
|
||||
};
|
||||
|
||||
// Single-zone primary lookup. Sourced from IANA tzdb's zone1970.tab.
|
||||
const SINGLE_ZONE: Partial<Record<CountryCode, string>> = {
|
||||
AD: 'Europe/Andorra',
|
||||
AE: 'Asia/Dubai',
|
||||
AF: 'Asia/Kabul',
|
||||
AG: 'America/Antigua',
|
||||
AI: 'America/Anguilla',
|
||||
AL: 'Europe/Tirane',
|
||||
AM: 'Asia/Yerevan',
|
||||
AO: 'Africa/Luanda',
|
||||
AQ: 'Antarctica/McMurdo',
|
||||
AR: 'America/Argentina/Buenos_Aires',
|
||||
AS: 'Pacific/Pago_Pago',
|
||||
AT: 'Europe/Vienna',
|
||||
AW: 'America/Aruba',
|
||||
AX: 'Europe/Mariehamn',
|
||||
AZ: 'Asia/Baku',
|
||||
BA: 'Europe/Sarajevo',
|
||||
BB: 'America/Barbados',
|
||||
BD: 'Asia/Dhaka',
|
||||
BE: 'Europe/Brussels',
|
||||
BF: 'Africa/Ouagadougou',
|
||||
BG: 'Europe/Sofia',
|
||||
BH: 'Asia/Bahrain',
|
||||
BI: 'Africa/Bujumbura',
|
||||
BJ: 'Africa/Porto-Novo',
|
||||
BL: 'America/St_Barthelemy',
|
||||
BM: 'Atlantic/Bermuda',
|
||||
BN: 'Asia/Brunei',
|
||||
BO: 'America/La_Paz',
|
||||
BQ: 'America/Kralendijk',
|
||||
BS: 'America/Nassau',
|
||||
BT: 'Asia/Thimphu',
|
||||
BV: 'Antarctica/Syowa',
|
||||
BW: 'Africa/Gaborone',
|
||||
BY: 'Europe/Minsk',
|
||||
BZ: 'America/Belize',
|
||||
CC: 'Indian/Cocos',
|
||||
CF: 'Africa/Bangui',
|
||||
CG: 'Africa/Brazzaville',
|
||||
CH: 'Europe/Zurich',
|
||||
CI: 'Africa/Abidjan',
|
||||
CK: 'Pacific/Rarotonga',
|
||||
CL: 'America/Santiago',
|
||||
CM: 'Africa/Douala',
|
||||
CN: 'Asia/Shanghai',
|
||||
CO: 'America/Bogota',
|
||||
CR: 'America/Costa_Rica',
|
||||
CU: 'America/Havana',
|
||||
CV: 'Atlantic/Cape_Verde',
|
||||
CW: 'America/Curacao',
|
||||
CX: 'Indian/Christmas',
|
||||
CY: 'Asia/Nicosia',
|
||||
CZ: 'Europe/Prague',
|
||||
DE: 'Europe/Berlin',
|
||||
DJ: 'Africa/Djibouti',
|
||||
DK: 'Europe/Copenhagen',
|
||||
DM: 'America/Dominica',
|
||||
DO: 'America/Santo_Domingo',
|
||||
DZ: 'Africa/Algiers',
|
||||
EC: 'America/Guayaquil',
|
||||
EE: 'Europe/Tallinn',
|
||||
EG: 'Africa/Cairo',
|
||||
EH: 'Africa/El_Aaiun',
|
||||
ER: 'Africa/Asmara',
|
||||
ES: 'Europe/Madrid',
|
||||
ET: 'Africa/Addis_Ababa',
|
||||
FI: 'Europe/Helsinki',
|
||||
FJ: 'Pacific/Fiji',
|
||||
FK: 'Atlantic/Stanley',
|
||||
FM: 'Pacific/Pohnpei',
|
||||
FO: 'Atlantic/Faroe',
|
||||
FR: 'Europe/Paris',
|
||||
GA: 'Africa/Libreville',
|
||||
GB: 'Europe/London',
|
||||
GD: 'America/Grenada',
|
||||
GE: 'Asia/Tbilisi',
|
||||
GF: 'America/Cayenne',
|
||||
GG: 'Europe/Guernsey',
|
||||
GH: 'Africa/Accra',
|
||||
GI: 'Europe/Gibraltar',
|
||||
GL: 'America/Godthab',
|
||||
GM: 'Africa/Banjul',
|
||||
GN: 'Africa/Conakry',
|
||||
GP: 'America/Guadeloupe',
|
||||
GQ: 'Africa/Malabo',
|
||||
GR: 'Europe/Athens',
|
||||
GS: 'Atlantic/South_Georgia',
|
||||
GT: 'America/Guatemala',
|
||||
GU: 'Pacific/Guam',
|
||||
GW: 'Africa/Bissau',
|
||||
GY: 'America/Guyana',
|
||||
HK: 'Asia/Hong_Kong',
|
||||
HM: 'Antarctica/Mawson',
|
||||
HN: 'America/Tegucigalpa',
|
||||
HR: 'Europe/Zagreb',
|
||||
HT: 'America/Port-au-Prince',
|
||||
HU: 'Europe/Budapest',
|
||||
IE: 'Europe/Dublin',
|
||||
IL: 'Asia/Jerusalem',
|
||||
IM: 'Europe/Isle_of_Man',
|
||||
IN: 'Asia/Kolkata',
|
||||
IO: 'Indian/Chagos',
|
||||
IQ: 'Asia/Baghdad',
|
||||
IR: 'Asia/Tehran',
|
||||
IS: 'Atlantic/Reykjavik',
|
||||
IT: 'Europe/Rome',
|
||||
JE: 'Europe/Jersey',
|
||||
JM: 'America/Jamaica',
|
||||
JO: 'Asia/Amman',
|
||||
JP: 'Asia/Tokyo',
|
||||
KE: 'Africa/Nairobi',
|
||||
KG: 'Asia/Bishkek',
|
||||
KH: 'Asia/Phnom_Penh',
|
||||
KI: 'Pacific/Tarawa',
|
||||
KM: 'Indian/Comoro',
|
||||
KN: 'America/St_Kitts',
|
||||
KP: 'Asia/Pyongyang',
|
||||
KR: 'Asia/Seoul',
|
||||
KW: 'Asia/Kuwait',
|
||||
KY: 'America/Cayman',
|
||||
LA: 'Asia/Vientiane',
|
||||
LB: 'Asia/Beirut',
|
||||
LC: 'America/St_Lucia',
|
||||
LI: 'Europe/Vaduz',
|
||||
LK: 'Asia/Colombo',
|
||||
LR: 'Africa/Monrovia',
|
||||
LS: 'Africa/Maseru',
|
||||
LT: 'Europe/Vilnius',
|
||||
LU: 'Europe/Luxembourg',
|
||||
LV: 'Europe/Riga',
|
||||
LY: 'Africa/Tripoli',
|
||||
MA: 'Africa/Casablanca',
|
||||
MC: 'Europe/Monaco',
|
||||
MD: 'Europe/Chisinau',
|
||||
ME: 'Europe/Podgorica',
|
||||
MF: 'America/Marigot',
|
||||
MG: 'Indian/Antananarivo',
|
||||
MH: 'Pacific/Majuro',
|
||||
MK: 'Europe/Skopje',
|
||||
ML: 'Africa/Bamako',
|
||||
MM: 'Asia/Yangon',
|
||||
MO: 'Asia/Macau',
|
||||
MP: 'Pacific/Saipan',
|
||||
MQ: 'America/Martinique',
|
||||
MR: 'Africa/Nouakchott',
|
||||
MS: 'America/Montserrat',
|
||||
MT: 'Europe/Malta',
|
||||
MU: 'Indian/Mauritius',
|
||||
MV: 'Indian/Maldives',
|
||||
MW: 'Africa/Blantyre',
|
||||
MY: 'Asia/Kuala_Lumpur',
|
||||
MZ: 'Africa/Maputo',
|
||||
NA: 'Africa/Windhoek',
|
||||
NC: 'Pacific/Noumea',
|
||||
NE: 'Africa/Niamey',
|
||||
NF: 'Pacific/Norfolk',
|
||||
NG: 'Africa/Lagos',
|
||||
NI: 'America/Managua',
|
||||
NL: 'Europe/Amsterdam',
|
||||
NO: 'Europe/Oslo',
|
||||
NP: 'Asia/Kathmandu',
|
||||
NR: 'Pacific/Nauru',
|
||||
NU: 'Pacific/Niue',
|
||||
NZ: 'Pacific/Auckland',
|
||||
OM: 'Asia/Muscat',
|
||||
PA: 'America/Panama',
|
||||
PE: 'America/Lima',
|
||||
PF: 'Pacific/Tahiti',
|
||||
PG: 'Pacific/Port_Moresby',
|
||||
PH: 'Asia/Manila',
|
||||
PK: 'Asia/Karachi',
|
||||
PL: 'Europe/Warsaw',
|
||||
PM: 'America/Miquelon',
|
||||
PN: 'Pacific/Pitcairn',
|
||||
PR: 'America/Puerto_Rico',
|
||||
PS: 'Asia/Gaza',
|
||||
PT: 'Europe/Lisbon',
|
||||
PW: 'Pacific/Palau',
|
||||
PY: 'America/Asuncion',
|
||||
QA: 'Asia/Qatar',
|
||||
RE: 'Indian/Reunion',
|
||||
RO: 'Europe/Bucharest',
|
||||
RS: 'Europe/Belgrade',
|
||||
RW: 'Africa/Kigali',
|
||||
SA: 'Asia/Riyadh',
|
||||
SB: 'Pacific/Guadalcanal',
|
||||
SC: 'Indian/Mahe',
|
||||
SD: 'Africa/Khartoum',
|
||||
SE: 'Europe/Stockholm',
|
||||
SG: 'Asia/Singapore',
|
||||
SH: 'Atlantic/St_Helena',
|
||||
SI: 'Europe/Ljubljana',
|
||||
SJ: 'Arctic/Longyearbyen',
|
||||
SK: 'Europe/Bratislava',
|
||||
SL: 'Africa/Freetown',
|
||||
SM: 'Europe/San_Marino',
|
||||
SN: 'Africa/Dakar',
|
||||
SO: 'Africa/Mogadishu',
|
||||
SR: 'America/Paramaribo',
|
||||
SS: 'Africa/Juba',
|
||||
ST: 'Africa/Sao_Tome',
|
||||
SV: 'America/El_Salvador',
|
||||
SX: 'America/Lower_Princes',
|
||||
SY: 'Asia/Damascus',
|
||||
SZ: 'Africa/Mbabane',
|
||||
TC: 'America/Grand_Turk',
|
||||
TD: 'Africa/Ndjamena',
|
||||
TF: 'Indian/Kerguelen',
|
||||
TG: 'Africa/Lome',
|
||||
TH: 'Asia/Bangkok',
|
||||
TJ: 'Asia/Dushanbe',
|
||||
TK: 'Pacific/Fakaofo',
|
||||
TL: 'Asia/Dili',
|
||||
TM: 'Asia/Ashgabat',
|
||||
TN: 'Africa/Tunis',
|
||||
TO: 'Pacific/Tongatapu',
|
||||
TR: 'Europe/Istanbul',
|
||||
TT: 'America/Port_of_Spain',
|
||||
TV: 'Pacific/Funafuti',
|
||||
TW: 'Asia/Taipei',
|
||||
TZ: 'Africa/Dar_es_Salaam',
|
||||
UA: 'Europe/Kyiv',
|
||||
UG: 'Africa/Kampala',
|
||||
UM: 'Pacific/Wake',
|
||||
UY: 'America/Montevideo',
|
||||
UZ: 'Asia/Tashkent',
|
||||
VA: 'Europe/Vatican',
|
||||
VC: 'America/St_Vincent',
|
||||
VE: 'America/Caracas',
|
||||
VG: 'America/Tortola',
|
||||
VI: 'America/St_Thomas',
|
||||
VN: 'Asia/Ho_Chi_Minh',
|
||||
VU: 'Pacific/Efate',
|
||||
WF: 'Pacific/Wallis',
|
||||
WS: 'Pacific/Apia',
|
||||
YE: 'Asia/Aden',
|
||||
YT: 'Indian/Mayotte',
|
||||
ZA: 'Africa/Johannesburg',
|
||||
ZM: 'Africa/Lusaka',
|
||||
ZW: 'Africa/Harare',
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the IANA zone(s) for a country. Always returns at least one
|
||||
* entry; the first entry is the primary/most-populous zone.
|
||||
*/
|
||||
export function timezonesForCountry(country: CountryCode): readonly string[] {
|
||||
const multi = MULTI_ZONE[country];
|
||||
if (multi) return multi;
|
||||
const single = SINGLE_ZONE[country];
|
||||
return single ? [single] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single best-default IANA timezone for a country, or null
|
||||
* when the dataset has no entry (caller should fall back to a generic
|
||||
* default like 'UTC').
|
||||
*/
|
||||
export function primaryTimezoneFor(country: CountryCode): string | null {
|
||||
const list = timezonesForCountry(country);
|
||||
return list[0] ?? null;
|
||||
}
|
||||
|
||||
/** True when the country has more than one valid zone (UI shows a sub-select). */
|
||||
export function isMultiZone(country: CountryCode): boolean {
|
||||
const list = timezonesForCountry(country);
|
||||
return list.length > 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Master IANA timezone list — uses Intl when available (modern browsers
|
||||
* + Node 21+). Falls back to a small bundled list when missing.
|
||||
*/
|
||||
export function listAllTimezones(): readonly string[] {
|
||||
if (typeof Intl !== 'undefined' && 'supportedValuesOf' in Intl) {
|
||||
try {
|
||||
const supported = Intl.supportedValuesOf('timeZone') as string[];
|
||||
if (Array.isArray(supported) && supported.length > 0) return supported;
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
// Tiny fallback drawn from our country map — covers ~250 entries and
|
||||
// never less than the timezones we'd otherwise reference.
|
||||
const set = new Set<string>();
|
||||
for (const tz of Object.values(SINGLE_ZONE)) set.add(tz!);
|
||||
for (const list of Object.values(MULTI_ZONE)) {
|
||||
for (const tz of list ?? []) set.add(tz);
|
||||
}
|
||||
return Array.from(set).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pretty-format a timezone for display: `'Europe/London (UTC+1)'`.
|
||||
* The offset is computed against `now` so it follows DST.
|
||||
*/
|
||||
export function formatTimezoneLabel(tz: string, now: Date = new Date()): string {
|
||||
try {
|
||||
const parts = new Intl.DateTimeFormat('en', {
|
||||
timeZone: tz,
|
||||
timeZoneName: 'shortOffset',
|
||||
}).formatToParts(now);
|
||||
const offset = parts.find((p) => p.type === 'timeZoneName')?.value ?? '';
|
||||
return offset ? `${tz} (${offset})` : tz;
|
||||
} catch {
|
||||
return tz;
|
||||
}
|
||||
}
|
||||
@@ -372,7 +372,15 @@ export async function listContacts(clientId: string, portId: string) {
|
||||
export async function addContact(
|
||||
clientId: string,
|
||||
portId: string,
|
||||
data: { channel: string; value: string; label?: string; isPrimary?: boolean; notes?: string },
|
||||
data: {
|
||||
channel: string;
|
||||
value: string;
|
||||
valueE164?: string | null;
|
||||
valueCountry?: string | null;
|
||||
label?: string;
|
||||
isPrimary?: boolean;
|
||||
notes?: string;
|
||||
},
|
||||
meta: AuditMeta,
|
||||
) {
|
||||
const client = await db.query.clients.findFirst({
|
||||
@@ -408,6 +416,8 @@ export async function updateContact(
|
||||
data: Partial<{
|
||||
channel: string;
|
||||
value: string;
|
||||
valueE164: string | null;
|
||||
valueCountry: string | null;
|
||||
label: string;
|
||||
isPrimary: boolean;
|
||||
notes: string;
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { baseListQuerySchema } from '@/lib/api/route-helpers';
|
||||
import {
|
||||
optionalCountryIsoSchema,
|
||||
optionalIanaTimezoneSchema,
|
||||
optionalPhoneE164Schema,
|
||||
} from '@/lib/validators/i18n';
|
||||
|
||||
// ─── Contact sub-schema ──────────────────────────────────────────────────────
|
||||
|
||||
export const contactSchema = z.object({
|
||||
channel: z.enum(['email', 'phone', 'whatsapp', 'other']),
|
||||
value: z.string().min(1),
|
||||
/** E.164-normalized number; required when channel is phone/whatsapp. */
|
||||
valueE164: optionalPhoneE164Schema.optional(),
|
||||
/** ISO-3166-1 alpha-2 country the number was parsed against. */
|
||||
valueCountry: optionalCountryIsoSchema.optional(),
|
||||
label: z.string().optional(),
|
||||
isPrimary: z.boolean().optional().default(false),
|
||||
notes: z.string().optional(),
|
||||
@@ -17,10 +26,14 @@ export const contactSchema = z.object({
|
||||
export const createClientSchema = z.object({
|
||||
fullName: z.string().min(1).max(200),
|
||||
contacts: z.array(contactSchema).min(1, 'At least one contact is required'),
|
||||
/** Legacy free-text nationality. Kept for backfill only — new edits write `nationalityIso`. */
|
||||
nationality: z.string().optional(),
|
||||
/** ISO-3166-1 alpha-2 nationality code. */
|
||||
nationalityIso: optionalCountryIsoSchema.optional(),
|
||||
preferredContactMethod: z.enum(['email', 'phone', 'whatsapp']).optional(),
|
||||
preferredLanguage: z.string().optional(),
|
||||
timezone: z.string().optional(),
|
||||
/** IANA timezone (e.g. 'Europe/Warsaw'). */
|
||||
timezone: optionalIanaTimezoneSchema.optional(),
|
||||
source: z.enum(['website', 'manual', 'referral', 'broker']).optional(),
|
||||
sourceDetails: z.string().optional(),
|
||||
tagIds: z.array(z.string()).optional().default([]),
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { z } from 'zod';
|
||||
import { baseListQuerySchema } from '@/lib/api/route-helpers';
|
||||
import { optionalCountryIsoSchema, optionalSubdivisionIsoSchema } from '@/lib/validators/i18n';
|
||||
|
||||
export const createCompanySchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
legalName: z.string().optional(),
|
||||
taxId: z.string().optional(),
|
||||
registrationNumber: z.string().optional(),
|
||||
/** Legacy free-text. New writes use `incorporationCountryIso`. */
|
||||
incorporationCountry: z.string().optional(),
|
||||
/** ISO-3166-1 alpha-2 country of incorporation. */
|
||||
incorporationCountryIso: optionalCountryIsoSchema.optional(),
|
||||
/** ISO 3166-2 state/province of incorporation. */
|
||||
incorporationSubdivisionIso: optionalSubdivisionIsoSchema.optional(),
|
||||
incorporationDate: z.coerce.date().optional(),
|
||||
status: z.enum(['active', 'dissolved']).optional().default('active'),
|
||||
billingEmail: z.string().email().optional(),
|
||||
|
||||
78
src/lib/validators/i18n.ts
Normal file
78
src/lib/validators/i18n.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Zod schemas wrapping the i18n primitives. Used by route handlers
|
||||
* and form-level validation so the same rules run client + server.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
import { ISO_COUNTRIES } from '@/lib/i18n/countries';
|
||||
import { isValidE164 } from '@/lib/i18n/phone';
|
||||
import { isValidSubdivisionCode } from '@/lib/i18n/subdivisions';
|
||||
|
||||
// ─── Country ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/** ISO-3166-1 alpha-2, uppercase. */
|
||||
export const countryIsoSchema = z
|
||||
.string()
|
||||
.length(2)
|
||||
.toUpperCase()
|
||||
.refine((c) => ISO_COUNTRIES.has(c), 'Unknown country code');
|
||||
|
||||
// ─── Phone ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** E.164 form, e.g. '+442079460958'. */
|
||||
export const phoneE164Schema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine((v) => isValidE164(v), 'Invalid phone number');
|
||||
|
||||
// ─── Timezone ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* IANA timezone (e.g. 'Europe/Warsaw'). Validates against
|
||||
* `Intl.supportedValuesOf('timeZone')` when available. Older Node
|
||||
* runtimes that lack the API fall back to a permissive shape check
|
||||
* (`Region/City`) so the validator never blocks the path.
|
||||
*/
|
||||
export const ianaTimezoneSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine((tz) => {
|
||||
if (typeof Intl !== 'undefined' && 'supportedValuesOf' in Intl) {
|
||||
try {
|
||||
const supported = Intl.supportedValuesOf('timeZone') as string[];
|
||||
if (supported.length > 0) return supported.includes(tz);
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
return /^[A-Z][A-Za-z_+-]+\/[A-Za-z_+-]+/.test(tz);
|
||||
}, 'Unknown timezone');
|
||||
|
||||
// ─── Subdivision ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** ISO 3166-2 code, e.g. 'PL-MZ'. */
|
||||
export const subdivisionIsoSchema = z
|
||||
.string()
|
||||
.min(2)
|
||||
.refine((code) => isValidSubdivisionCode(code), 'Unknown subdivision code');
|
||||
|
||||
// ─── Optional variants ────────────────────────────────────────────────────────
|
||||
// Inline forms most callers will use — empty strings normalize to null
|
||||
// so the user clearing a field doesn't fail validation.
|
||||
|
||||
export const optionalCountryIsoSchema = z
|
||||
.union([z.literal(''), z.null(), countryIsoSchema])
|
||||
.transform((v) => (v === '' || v === null ? null : v));
|
||||
|
||||
export const optionalPhoneE164Schema = z
|
||||
.union([z.literal(''), z.null(), phoneE164Schema])
|
||||
.transform((v) => (v === '' || v === null ? null : v));
|
||||
|
||||
export const optionalIanaTimezoneSchema = z
|
||||
.union([z.literal(''), z.null(), ianaTimezoneSchema])
|
||||
.transform((v) => (v === '' || v === null ? null : v));
|
||||
|
||||
export const optionalSubdivisionIsoSchema = z
|
||||
.union([z.literal(''), z.null(), subdivisionIsoSchema])
|
||||
.transform((v) => (v === '' || v === null ? null : v));
|
||||
@@ -1,6 +1,12 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { baseListQuerySchema } from '@/lib/api/route-helpers';
|
||||
import {
|
||||
optionalCountryIsoSchema,
|
||||
optionalIanaTimezoneSchema,
|
||||
optionalPhoneE164Schema,
|
||||
optionalSubdivisionIsoSchema,
|
||||
} from '@/lib/validators/i18n';
|
||||
|
||||
// ─── Residential client ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -12,7 +18,19 @@ export const createResidentialClientSchema = z.object({
|
||||
.optional()
|
||||
.or(z.literal('').transform(() => undefined)),
|
||||
phone: z.string().optional(),
|
||||
/** E.164-normalized phone alongside the legacy free-text `phone`. */
|
||||
phoneE164: optionalPhoneE164Schema.optional(),
|
||||
/** ISO-3166-1 alpha-2 the phone was parsed against. */
|
||||
phoneCountry: optionalCountryIsoSchema.optional(),
|
||||
/** ISO-3166-1 alpha-2 nationality. */
|
||||
nationalityIso: optionalCountryIsoSchema.optional(),
|
||||
/** IANA timezone. */
|
||||
timezone: optionalIanaTimezoneSchema.optional(),
|
||||
placeOfResidence: z.string().optional(),
|
||||
/** ISO-3166-1 alpha-2 country of residence. */
|
||||
placeOfResidenceCountryIso: optionalCountryIsoSchema.optional(),
|
||||
/** ISO 3166-2 subdivision code for place of residence. */
|
||||
subdivisionIso: optionalSubdivisionIsoSchema.optional(),
|
||||
preferredContactMethod: z.enum(['email', 'phone']).optional(),
|
||||
status: z.enum(['prospect', 'active', 'inactive']).optional().default('prospect'),
|
||||
source: z.enum(['website', 'manual', 'referral', 'broker']).optional(),
|
||||
@@ -62,13 +80,30 @@ export const listResidentialInterestsSchema = baseListQuerySchema.extend({
|
||||
/**
|
||||
* Shape posted by the public website's residential interest form. Coerces
|
||||
* to internal create-shapes inside the public route.
|
||||
*
|
||||
* The legacy `phone` field stays free-text — older website builds may post
|
||||
* raw international strings ('+44 7700 900123'). The route handler parses
|
||||
* it server-side into `phoneE164` + `phoneCountry`. Newer website builds
|
||||
* can post normalized values directly.
|
||||
*/
|
||||
export const publicResidentialInquirySchema = z.object({
|
||||
firstName: z.string().min(1),
|
||||
lastName: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
phone: z.string().min(1),
|
||||
/** Pre-normalized E.164 form, optional for backwards compat. */
|
||||
phoneE164: optionalPhoneE164Schema.optional(),
|
||||
/** ISO-3166-1 alpha-2 the phone was parsed against. */
|
||||
phoneCountry: optionalCountryIsoSchema.optional(),
|
||||
/** ISO-3166-1 alpha-2 nationality. */
|
||||
nationalityIso: optionalCountryIsoSchema.optional(),
|
||||
/** IANA timezone. */
|
||||
timezone: optionalIanaTimezoneSchema.optional(),
|
||||
placeOfResidence: z.string().optional(),
|
||||
/** ISO-3166-1 alpha-2 country of residence. */
|
||||
placeOfResidenceCountryIso: optionalCountryIsoSchema.optional(),
|
||||
/** ISO 3166-2 subdivision code for place of residence. */
|
||||
subdivisionIso: optionalSubdivisionIsoSchema.optional(),
|
||||
preferredContactMethod: z.enum(['email', 'phone']).optional(),
|
||||
notes: z.string().optional(),
|
||||
preferences: z.string().optional(),
|
||||
|
||||
Reference in New Issue
Block a user