Files
CoHaiSe/frontend/crm/src/pages/Countries.tsx
T
Esiah 09cf07d79b feat: migrate showcase to Next.js and overhaul CRM UI
- rebuild the public site on the Next.js App Router with static export,
  per-section SEO pages, metadata, sitemap, robots and a generated OG image
- add full-screen scroll-snap regions, staged scroll reveals, a hash-free
  tab navigation with a sliding indicator and region-by-region menu scrolling
- replace the theme text toggle with animated sun/moon icons
- restructure the CRM API into config, middleware, models, routes, services
  and utils layers
- redesign the CRM shell with a single surface, tab rail, full-width blurred
  DataTable, record dialogs and mask-based icons
- update Docker/Nginx publishing, Makefile targets, shared UI polish and docs
2026-11-16 00:52:29 +01:00

256 lines
7.5 KiB
TypeScript

import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react";
import { Button, Input } from "@cohaise/ui";
import { ApiError, api, type Country } from "../lib/api.js";
import { DataTable, type DataTableColumn } from "../components/DataTable.js";
import { RecordDialog } from "../components/RecordDialog.js";
import { RowActionButton } from "../components/RowActionButton.js";
import { PenMaskIcon, TrashMaskIcon } from "../components/icons.js";
interface Form {
code: string;
name: string;
phoneCode: string;
}
const EMPTY: Form = { code: "", name: "", phoneCode: "" };
export const Countries = () => {
const [rows, setRows] = useState<Country[]>([]);
const [search, setSearch] = useState("");
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [formError, setFormError] = useState<string | null>(null);
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<Country | null>(null);
const [form, setForm] = useState<Form>(EMPTY);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const result = await api.countries();
setRows(result.countries);
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void load();
}, [load]);
// Le referentiel est court : le filtrage reste local, sans requete par frappe.
const filtered = useMemo(() => {
const query = search.trim().toLowerCase();
if (!query) return rows;
return rows.filter((country) =>
[country.code, country.name, country.phone_code ?? ""]
.join(" ")
.toLowerCase()
.includes(query),
);
}, [rows, search]);
const close = () => {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setOpen(false);
};
const openCreate = () => {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setOpen(true);
};
const openEdit = (country: Country) => {
setEditing(country);
setForm({
code: country.code,
name: country.name,
phoneCode: country.phone_code ?? "",
});
setFormError(null);
setOpen(true);
};
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const code = form.code.trim().toUpperCase();
const name = form.name.trim();
if (!/^[A-Z]{2}$/.test(code)) {
setFormError("Le code doit contenir exactement deux lettres.");
return;
}
if (!name) {
setFormError("Le nom est obligatoire.");
return;
}
setBusy(true);
setFormError(null);
try {
const payload = { code, name, phoneCode: form.phoneCode.trim() || null };
if (editing) await api.updateCountry(editing.id, payload);
else await api.createCountry(payload);
close();
await load();
} catch (caught) {
setFormError(caught instanceof ApiError ? caught.message : "Enregistrement impossible.");
} finally {
setBusy(false);
}
};
const remove = async (country: Country) => {
if (!window.confirm(`Supprimer « ${country.name} » ?`)) return;
setBusy(true);
setError(null);
try {
await api.deleteCountry(country.id);
await load();
} catch (caught) {
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
} finally {
setBusy(false);
}
};
const columns: DataTableColumn<Country>[] = [
{
id: "code",
header: "Code",
sortable: true,
sortValue: (row) => row.code,
cell: (row) => (
<span className="inline-flex rounded-sm border border-border bg-surface-muted px-1.5 py-0.5 font-mono text-xs font-semibold tracking-wide text-foreground">
{row.code}
</span>
),
},
{
id: "name",
header: "Nom",
sortable: true,
sortValue: (row) => row.name,
cell: (row) => <span className="font-medium text-foreground">{row.name}</span>,
},
{
id: "phone",
header: "Indicatif",
sortable: true,
sortValue: (row) => row.phone_code,
cell: (row) => (
<span className="font-mono text-sm text-muted-foreground">{row.phone_code ?? "—"}</span>
),
},
];
return (
<>
<DataTable
data={filtered}
columns={columns}
keyExtractor={(country) => country.id}
loading={loading}
error={error}
emptyMessage={search ? "Aucun pays correspondant" : "Aucun pays"}
emptyHint={
search
? "Essayez un autre code, un autre nom ou un indicatif."
: "Ajoutez le premier pays du référentiel."
}
search={{
value: search,
onChange: setSearch,
placeholder: "Code, nom, indicatif…",
}}
toolbarStart={
<p className="hidden max-w-lg text-sm text-muted-foreground lg:block">
Référentiel ISO 3166 utilisé par les entreprises et les prospects.
</p>
}
actions={<Button onClick={openCreate}>Nouveau pays</Button>}
rowActions={(country) => (
<div className="flex items-center justify-end gap-1.5">
<RowActionButton
label={`Modifier ${country.name}`}
onClick={() => openEdit(country)}
>
<PenMaskIcon />
</RowActionButton>
<RowActionButton
label={`Supprimer ${country.name}`}
tone="destructive"
onClick={() => void remove(country)}
>
<TrashMaskIcon />
</RowActionButton>
</div>
)}
footer={
<span>
{filtered.length === rows.length
? `${rows.length} pays`
: `${filtered.length} sur ${rows.length} pays`}
</span>
}
initialSort={{ column: "name", direction: "asc" }}
/>
<RecordDialog
open={open}
title={editing ? "Modifier le pays" : "Nouveau pays"}
onClose={close}
>
<form className="grid gap-4 sm:grid-cols-3" onSubmit={(event) => void submit(event)}>
<Input
label="Code *"
required
maxLength={2}
placeholder="FR"
value={form.code}
onChange={(event) =>
setForm((current) => ({ ...current, code: event.target.value.toUpperCase() }))
}
/>
<Input
label="Nom *"
required
value={form.name}
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
/>
<Input
label="Indicatif"
placeholder="+33"
value={form.phoneCode}
onChange={(event) =>
setForm((current) => ({ ...current, phoneCode: event.target.value }))
}
/>
{formError ? (
<p className="text-sm text-destructive sm:col-span-3" role="alert">
{formError}
</p>
) : null}
<div className="flex items-center justify-end gap-3 sm:col-span-3">
<Button type="button" variant="secondary" onClick={close}>
Annuler
</Button>
<Button type="submit" isLoading={busy}>
{editing ? "Enregistrer" : "Créer"}
</Button>
</div>
</form>
</RecordDialog>
</>
);
};