commit16
This commit is contained in:
@@ -0,0 +1,239 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
|
||||
type Match = {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
published_at?: string | null;
|
||||
};
|
||||
function publicationDate(value?: string | null): string | null {
|
||||
if (typeof value !== 'string' || !value.trim()) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? null
|
||||
: date.toLocaleDateString('pt-MZ');
|
||||
}
|
||||
type Classification = {
|
||||
target_type: string;
|
||||
target_id: string;
|
||||
label: string;
|
||||
purpose?: string;
|
||||
purpose_label?: string;
|
||||
source_reference?: string | null;
|
||||
};
|
||||
const classificationKey = (row: Classification) =>
|
||||
`${row.target_type}:${row.target_id}:${row.purpose ?? ''}`;
|
||||
type Props = {
|
||||
currentId: string;
|
||||
catalogueUrl: string;
|
||||
criteria: string[];
|
||||
classifications?: Classification[];
|
||||
};
|
||||
|
||||
export default function SimilarBusinesses({
|
||||
currentId,
|
||||
catalogueUrl,
|
||||
criteria,
|
||||
classifications = [],
|
||||
}: Props) {
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [selection, setSelection] = useState({
|
||||
recordId: currentId,
|
||||
value: '',
|
||||
});
|
||||
const selected =
|
||||
selection.recordId === currentId
|
||||
? classifications.find(
|
||||
(row) => classificationKey(row) === selection.value,
|
||||
)
|
||||
: undefined;
|
||||
const query = new URL(catalogueUrl, 'https://portal.invalid');
|
||||
if (selected) {
|
||||
query.searchParams.set('association_type', selected.target_type);
|
||||
query.searchParams.set('association_target', selected.target_id);
|
||||
if (selected.purpose)
|
||||
query.searchParams.set('association_purpose', selected.purpose);
|
||||
}
|
||||
const effectiveCatalogueUrl = query.pathname + query.search;
|
||||
const key = JSON.stringify([currentId, effectiveCatalogueUrl, attempt]);
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
rows: Match[];
|
||||
error: boolean;
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const params = new URL(effectiveCatalogueUrl, 'https://portal.invalid')
|
||||
.searchParams;
|
||||
params.set('per_page', '7');
|
||||
params.set('page', '1');
|
||||
void portalRequest<{ data: Match[] }>(
|
||||
`/api/v1/business-opportunities?${params}`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((response) => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (!Array.isArray(response.data))
|
||||
throw new Error('Invalid catalogue response');
|
||||
const seen = new Set([currentId]);
|
||||
if (
|
||||
response.data.some(
|
||||
(row) =>
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
!row.id.trim() ||
|
||||
typeof row.slug !== 'string' ||
|
||||
!row.slug.trim() ||
|
||||
typeof row.title !== 'string' ||
|
||||
!row.title.trim(),
|
||||
)
|
||||
) {
|
||||
throw new Error('Invalid catalogue record');
|
||||
}
|
||||
const rows = response.data
|
||||
.filter((row) => {
|
||||
if (
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
typeof row.slug !== 'string' ||
|
||||
typeof row.title !== 'string' ||
|
||||
seen.has(row.id)
|
||||
)
|
||||
return false;
|
||||
seen.add(row.id);
|
||||
return true;
|
||||
})
|
||||
.slice(0, 6);
|
||||
setResult({ key, rows, error: false });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, rows: [], error: true });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [currentId, effectiveCatalogueUrl, key]);
|
||||
const current = result?.key === key ? result : null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-xl border bg-white p-5"
|
||||
aria-label="Negócios com critérios semelhantes"
|
||||
aria-busy={!current}
|
||||
>
|
||||
<h2 className="text-xl font-bold">Explorar negócios semelhantes</h2>
|
||||
<p>
|
||||
Critérios:{' '}
|
||||
{[...criteria, ...(selected ? [selected.label] : [])].join(
|
||||
' · ',
|
||||
)}
|
||||
. A consulta compara os dados publicados; não avalia
|
||||
rentabilidade nem proximidade geográfica.
|
||||
</p>
|
||||
{!current ? (
|
||||
<p role="status">A consultar o catálogo…</p>
|
||||
) : current.error ? (
|
||||
<div role="alert">
|
||||
<p>Não foi possível consultar os negócios semelhantes.</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setAttempt((value) => value + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</div>
|
||||
) : current.rows.length ? (
|
||||
<ul className="space-y-2">
|
||||
{current.rows.map((row) => (
|
||||
<li key={row.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/negocios/${encodeURIComponent(row.slug)}${new URL(effectiveCatalogueUrl, 'https://portal.invalid').search}`}
|
||||
>
|
||||
{row.title}
|
||||
</Link>
|
||||
<p className="text-sm text-slate-600">
|
||||
Fonte: catálogo público do InvesteMoz.{' '}
|
||||
{publicationDate(row.published_at) ? (
|
||||
<>
|
||||
Publicado em{' '}
|
||||
<time
|
||||
dateTime={
|
||||
row.published_at ?? undefined
|
||||
}
|
||||
>
|
||||
{publicationDate(row.published_at)}
|
||||
</time>
|
||||
.
|
||||
</>
|
||||
) : (
|
||||
'Data de publicação não indicada.'
|
||||
)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>
|
||||
Não foram encontrados outros negócios públicos com estes
|
||||
critérios. Isto não demonstra ausência de negócios no
|
||||
mercado.
|
||||
</p>
|
||||
)}
|
||||
{classifications.length > 0 && (
|
||||
<label className="block space-y-1">
|
||||
Comparar também por uma classificação divulgada
|
||||
<select
|
||||
className="block w-full rounded border p-2"
|
||||
value={selected ? classificationKey(selected) : ''}
|
||||
onChange={(event) =>
|
||||
setSelection({
|
||||
recordId: currentId,
|
||||
value: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Sem classificação adicional</option>
|
||||
{classifications
|
||||
.filter(
|
||||
(row, index, all) =>
|
||||
all.findIndex(
|
||||
(other) =>
|
||||
classificationKey(other) ===
|
||||
classificationKey(row),
|
||||
) === index,
|
||||
)
|
||||
.map((row) => (
|
||||
<option
|
||||
key={classificationKey(row)}
|
||||
value={classificationKey(row)}
|
||||
>
|
||||
{row.label}
|
||||
{row.purpose_label
|
||||
? ` — ${row.purpose_label}`
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{selected && (
|
||||
<p className="text-sm">
|
||||
Fonte da classificação na ficha de origem:{' '}
|
||||
{selected.source_reference || 'não indicada'}. A relação
|
||||
documental não comprova implantação, propriedade ou
|
||||
capacidade.
|
||||
</p>
|
||||
)}
|
||||
<Link href={effectiveCatalogueUrl} className="underline">
|
||||
Consultar o catálogo com estes critérios
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
São apresentados até seis resultados. Pode ajustar os filtros no
|
||||
catálogo. A data de publicação não indica a data dos dados de
|
||||
origem.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user