@@ -1,6 +1,6 @@
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import { api } from "@/pages/investment/shared";
|
||||
import { replaceTerritoryPath } from "@/lib/territory-path.js";
|
||||
import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
|
||||
export type TerritoryOption = {
|
||||
id: string;
|
||||
@@ -11,18 +11,18 @@ export type TerritoryOption = {
|
||||
source_code?: string | null;
|
||||
};
|
||||
type Option = TerritoryOption;
|
||||
const levels = ["province", "district", "admin_post", "locality"];
|
||||
const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"];
|
||||
const control = "w-full rounded border bg-background p-2 text-foreground";
|
||||
const levels = ['province', 'district', 'admin_post', 'locality'];
|
||||
const labels = ['Província', 'Distrito', 'Posto administrativo', 'Localidade'];
|
||||
const control = 'w-full rounded border bg-background p-2 text-foreground';
|
||||
const emptyTerritoryPath: TerritoryOption[] = [];
|
||||
|
||||
export function ProvinceSelect({
|
||||
value,
|
||||
onChange,
|
||||
endpoint = "/api/v1/catalogs/jurisdictions",
|
||||
placeholder = "Seleccione uma província",
|
||||
endpoint = '/api/v1/catalogs/jurisdictions',
|
||||
placeholder = 'Seleccione uma província',
|
||||
className = control,
|
||||
label = "Província",
|
||||
label = 'Província',
|
||||
required = false,
|
||||
}: {
|
||||
value: string;
|
||||
@@ -36,25 +36,30 @@ export function ProvinceSelect({
|
||||
const id = useId();
|
||||
const [options, setOptions] = useState<Option[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setError('');
|
||||
fetch(`${endpoint}?type=province&page=1`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error("Não foi possível carregar as províncias.");
|
||||
if (!response.ok)
|
||||
throw new Error('Não foi possível carregar as províncias.');
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => setOptions(data.data))
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted)
|
||||
setError(cause instanceof Error ? cause.message : "Erro de ligação.");
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro de ligação.',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
@@ -69,11 +74,15 @@ export function ProvinceSelect({
|
||||
aria-label={label}
|
||||
className={className}
|
||||
required={required}
|
||||
value={options.some((option) => option.name === value) ? value : ""}
|
||||
value={
|
||||
options.some((option) => option.name === value) ? value : ''
|
||||
}
|
||||
disabled={loading || Boolean(error)}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">{loading ? "A carregar províncias…" : placeholder}</option>
|
||||
<option value="">
|
||||
{loading ? 'A carregar províncias…' : placeholder}
|
||||
</option>
|
||||
{options.map((option) => (
|
||||
<option key={option.id} value={option.name}>
|
||||
{option.name}
|
||||
@@ -82,8 +91,11 @@ export function ProvinceSelect({
|
||||
</select>
|
||||
{error && (
|
||||
<span role="alert" className="block text-sm">
|
||||
{error}{" "}
|
||||
<button type="button" onClick={() => setRetry((current) => current + 1)}>
|
||||
{error}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRetry((current) => current + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</span>
|
||||
@@ -95,7 +107,7 @@ export function ProvinceSelect({
|
||||
export function TerritoryFields({
|
||||
initial = emptyTerritoryPath,
|
||||
onChange,
|
||||
endpoint = "/api/v1/catalogs/jurisdictions",
|
||||
endpoint = '/api/v1/catalogs/jurisdictions',
|
||||
}: {
|
||||
initial?: TerritoryOption[];
|
||||
onChange?: (path: TerritoryOption[]) => void;
|
||||
@@ -105,24 +117,37 @@ export function TerritoryFields({
|
||||
useEffect(() => setPath(initial), [initial]);
|
||||
return (
|
||||
<div className="grid gap-4 md:col-span-full md:grid-cols-2">
|
||||
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
|
||||
(field, index) => (
|
||||
<div key={`${field}-${path[index - 1]?.id ?? ""}`}>
|
||||
<input type="hidden" name={field} value={path[index]?.id ?? ""} />
|
||||
<TerritoryLevel
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
selected={path[index]}
|
||||
endpoint={endpoint}
|
||||
onChange={(value) => {
|
||||
const next = replaceTerritoryPath(path, index, value);
|
||||
setPath(next);
|
||||
onChange?.(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((field, index) => (
|
||||
<div key={`${field}-${path[index - 1]?.id ?? ''}`}>
|
||||
<input
|
||||
type="hidden"
|
||||
name={field}
|
||||
value={path[index]?.id ?? ''}
|
||||
/>
|
||||
<TerritoryLevel
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={endpoint}
|
||||
onChange={(value) => {
|
||||
const next = replaceTerritoryPath(
|
||||
path,
|
||||
index,
|
||||
value,
|
||||
);
|
||||
setPath(next);
|
||||
onChange?.(next);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -132,7 +157,7 @@ export function TerritoryLevel({
|
||||
parent,
|
||||
selected,
|
||||
onChange,
|
||||
endpoint = "/management/territory-options",
|
||||
endpoint = '/management/territory-options',
|
||||
fieldError,
|
||||
}: {
|
||||
index: number;
|
||||
@@ -146,7 +171,7 @@ export function TerritoryLevel({
|
||||
const [page, setPage] = useState(1);
|
||||
const [options, setOptions] = useState<Option[]>([]);
|
||||
const [more, setMore] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const enabled = index === 0 || Boolean(parent);
|
||||
@@ -158,7 +183,7 @@ export function TerritoryLevel({
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setError('');
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
type: levels[index],
|
||||
@@ -167,16 +192,21 @@ export function TerritoryLevel({
|
||||
});
|
||||
const response = await fetch(`${endpoint}?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) throw new Error("Não foi possível carregar as localizações.");
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
'Não foi possível carregar as localizações.',
|
||||
);
|
||||
const data = await response.json();
|
||||
if (controller.signal.aborted) return;
|
||||
setOptions(data.data);
|
||||
setMore(Boolean(data.next_page_url));
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setError(e instanceof Error ? e.message : "Erro de ligação.");
|
||||
setError(
|
||||
e instanceof Error ? e.message : 'Erro de ligação.',
|
||||
);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
@@ -197,27 +227,33 @@ export function TerritoryLevel({
|
||||
aria-describedby={fieldError ? `${id}-error` : undefined}
|
||||
className={control}
|
||||
disabled={!enabled || loading}
|
||||
value={selected?.id ?? ""}
|
||||
onChange={(e) => onChange(options.find((o) => o.id === e.target.value))}
|
||||
value={selected?.id ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange(options.find((o) => o.id === e.target.value))
|
||||
}
|
||||
>
|
||||
<option value="">{enabled ? "Seleccione" : "Seleccione o nível anterior"}</option>
|
||||
<option value="">
|
||||
{enabled ? 'Seleccione' : 'Seleccione o nível anterior'}
|
||||
</option>
|
||||
{selected && !options.some((o) => o.id === selected.id) && (
|
||||
<option value={selected.id}>
|
||||
{selected.name}
|
||||
{selected.deleted_at ? " (arquivada)" : " (selecção actual)"}
|
||||
{selected.deleted_at
|
||||
? ' (arquivada)'
|
||||
: ' (selecção actual)'}
|
||||
</option>
|
||||
)}
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
{o.source_code ? ` (${o.source_code})` : ""}
|
||||
{o.source_code ? ` (${o.source_code})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{loading && <p role="status">A carregar…</p>}
|
||||
{error && (
|
||||
<div role="alert">
|
||||
{error}{" "}
|
||||
{error}{' '}
|
||||
<button type="button" onClick={() => setRetry(retry + 1)}>
|
||||
Tentar novamente
|
||||
</button>
|
||||
@@ -247,10 +283,16 @@ export function TerritoryLevel({
|
||||
);
|
||||
}
|
||||
|
||||
export default function InvestmentTerritory({ kind, id }: { kind: string; id: string | number }) {
|
||||
export default function InvestmentTerritory({
|
||||
kind,
|
||||
id,
|
||||
}: {
|
||||
kind: string;
|
||||
id: string | number;
|
||||
}) {
|
||||
const [path, setPath] = useState<Option[]>([]);
|
||||
const [version, setVersion] = useState<number | null>(null);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
@@ -259,7 +301,9 @@ export default function InvestmentTerritory({ kind, id }: { kind: string; id: st
|
||||
if (!active) return;
|
||||
setPath(
|
||||
levels.flatMap((level) =>
|
||||
data.path.filter((o: Option) => o.location_type === level),
|
||||
data.path.filter(
|
||||
(o: Option) => o.location_type === level,
|
||||
),
|
||||
),
|
||||
);
|
||||
setVersion(data.version);
|
||||
@@ -276,38 +320,48 @@ export default function InvestmentTerritory({ kind, id }: { kind: string; id: st
|
||||
className="my-6 space-y-4 rounded border p-4"
|
||||
aria-label="Localização do investimento"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Localização do investimento</h2>
|
||||
<p>Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes.</p>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Localização do investimento
|
||||
</h2>
|
||||
<p>
|
||||
Seleccione até ao nível conhecido. Alterar um nível limpa as
|
||||
selecções seguintes.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{levels.map((level, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${level}-${path[index - 1]?.id ?? ""}`}
|
||||
key={`${level}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
onChange={(value) => {
|
||||
setPath(replaceTerritoryPath(path, index, value));
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
|
||||
className="bg-primary text-primary-foreground rounded px-4 py-2 disabled:opacity-50"
|
||||
disabled={version === null || busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
const data = await api(`/management/territories/${kind}/${id}`, {
|
||||
version,
|
||||
path: path.map((o) => o.id),
|
||||
});
|
||||
const data = await api(
|
||||
`/management/territories/${kind}/${id}`,
|
||||
{
|
||||
version,
|
||||
path: path.map((o) => o.id),
|
||||
},
|
||||
);
|
||||
setVersion(data.version);
|
||||
setMessage("Localização associada e guardada.");
|
||||
setMessage('Localização associada e guardada.');
|
||||
} catch (e) {
|
||||
setMessage(e instanceof Error ? e.message : "Erro ao guardar.");
|
||||
setMessage(
|
||||
e instanceof Error ? e.message : 'Erro ao guardar.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user