464 lines
18 KiB
TypeScript
464 lines
18 KiB
TypeScript
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;
|
|
distance_km?: number | null;
|
|
location_recorded_at?: string | null;
|
|
location_source_reference?: string | null;
|
|
location_source_date?: 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',
|
|
/^\d{4}-\d{2}-\d{2}$/.test(value)
|
|
? { timeZone: 'UTC' }
|
|
: undefined,
|
|
);
|
|
}
|
|
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[];
|
|
radiusAvailable?: boolean;
|
|
areaLabel?: string;
|
|
};
|
|
|
|
export type BusinessGeographicCoverage = {
|
|
origin_id: string;
|
|
origin_title: string;
|
|
radius_km: number;
|
|
origin_recorded_at: string | null;
|
|
origin_source_reference?: string | null;
|
|
origin_source_date?: string | null;
|
|
with_public_point: number;
|
|
without_public_point: number;
|
|
source: string;
|
|
method: string;
|
|
};
|
|
|
|
export function GeographicCoverage({
|
|
coverage,
|
|
}: {
|
|
coverage: BusinessGeographicCoverage;
|
|
}) {
|
|
return (
|
|
<div className="space-y-1 rounded border p-3 text-sm">
|
|
<p>
|
|
Raio de {coverage.radius_km} km a partir de{' '}
|
|
{coverage.origin_title}.
|
|
</p>
|
|
<p>
|
|
Fonte: {coverage.source}. {coverage.method}
|
|
</p>
|
|
<p>
|
|
Cobertura entre as fichas públicas que cumprem os restantes
|
|
filtros, antes de aplicar o raio: {coverage.with_public_point}{' '}
|
|
com ponto utilizável; {coverage.without_public_point} sem ponto
|
|
público exacto utilizável, excluídas da pesquisa por distância.
|
|
Esta contagem pode incluir a ficha de referência.
|
|
</p>
|
|
<p>
|
|
Localização da referência registada em:{' '}
|
|
{publicationDate(coverage.origin_recorded_at) ??
|
|
'data não indicada'}
|
|
. A data de registo não confirma a actualidade dos dados de
|
|
origem. Cobertura incompleta não demonstra ausência de negócios.
|
|
</p>
|
|
<p>
|
|
Fonte de origem da localização:{' '}
|
|
{coverage.origin_source_reference ||
|
|
'referência não divulgada ou não indicada'}
|
|
. Data da fonte:{' '}
|
|
{publicationDate(coverage.origin_source_date) ?? 'desconhecida'}
|
|
.
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function BusinessDistance({
|
|
record,
|
|
}: {
|
|
record: Pick<
|
|
Match,
|
|
| 'distance_km'
|
|
| 'location_recorded_at'
|
|
| 'location_source_reference'
|
|
| 'location_source_date'
|
|
>;
|
|
}) {
|
|
if (
|
|
typeof record.distance_km !== 'number' ||
|
|
!Number.isFinite(record.distance_km) ||
|
|
record.distance_km < 0
|
|
)
|
|
return null;
|
|
return (
|
|
<div className="text-sm">
|
|
<p>
|
|
Distância aproximada em linha recta:{' '}
|
|
{record.distance_km.toLocaleString('pt-MZ')} km. Localização
|
|
registada em:{' '}
|
|
{publicationDate(record.location_recorded_at) ??
|
|
'data não indicada'}
|
|
.
|
|
</p>
|
|
<BusinessLocationSource record={record} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export function BusinessLocationSource({
|
|
record,
|
|
showRecorded = false,
|
|
}: {
|
|
record: Pick<
|
|
Match,
|
|
| 'location_recorded_at'
|
|
| 'location_source_reference'
|
|
| 'location_source_date'
|
|
>;
|
|
showRecorded?: boolean;
|
|
}) {
|
|
if (
|
|
!record.location_recorded_at &&
|
|
!record.location_source_reference &&
|
|
!record.location_source_date
|
|
)
|
|
return null;
|
|
return (
|
|
<p className="text-sm">
|
|
Fonte de origem da localização:{' '}
|
|
{record.location_source_reference ||
|
|
'referência não divulgada ou não indicada'}
|
|
. Data da fonte:{' '}
|
|
{publicationDate(record.location_source_date) ?? 'desconhecida'}.
|
|
{showRecorded && (
|
|
<>
|
|
{' '}
|
|
Registada em:{' '}
|
|
{publicationDate(record.location_recorded_at) ??
|
|
'data não indicada'}
|
|
. A data de registo não confirma a actualidade da origem.
|
|
</>
|
|
)}
|
|
</p>
|
|
);
|
|
}
|
|
|
|
export default function SimilarBusinesses({
|
|
currentId,
|
|
catalogueUrl,
|
|
criteria,
|
|
classifications = [],
|
|
radiusAvailable = false,
|
|
areaLabel,
|
|
}: 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 [radiusSelection, setRadiusSelection] = useState({
|
|
recordId: currentId,
|
|
value: '',
|
|
});
|
|
const radius =
|
|
radiusAvailable && radiusSelection.recordId === currentId
|
|
? radiusSelection.value
|
|
: '';
|
|
const query = new URL(catalogueUrl, 'https://portal.invalid');
|
|
if (radius) {
|
|
for (const field of [
|
|
'province_id',
|
|
'district_id',
|
|
'admin_post_id',
|
|
'locality_id',
|
|
])
|
|
query.searchParams.delete(field);
|
|
query.searchParams.set('near_business', currentId);
|
|
query.searchParams.set('radius_km', radius);
|
|
}
|
|
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;
|
|
coverage: BusinessGeographicCoverage | null;
|
|
} | 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[];
|
|
geographicCoverage?: BusinessGeographicCoverage | null;
|
|
}>(`/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 coverage = response.geographicCoverage ?? null;
|
|
if (
|
|
radius &&
|
|
(!coverage ||
|
|
coverage.origin_id !== currentId ||
|
|
coverage.radius_km !== Number(radius) ||
|
|
!Number.isInteger(coverage.with_public_point) ||
|
|
coverage.with_public_point < 0 ||
|
|
!Number.isInteger(coverage.without_public_point) ||
|
|
coverage.without_public_point < 0 ||
|
|
typeof coverage.origin_title !== 'string' ||
|
|
typeof coverage.source !== 'string' ||
|
|
typeof coverage.method !== 'string')
|
|
)
|
|
throw new Error('Invalid radius coverage');
|
|
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() ||
|
|
(radius &&
|
|
(typeof row.distance_km !== 'number' ||
|
|
!Number.isFinite(row.distance_km) ||
|
|
row.distance_km < 0)),
|
|
)
|
|
) {
|
|
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, coverage });
|
|
})
|
|
.catch(() => {
|
|
if (!controller.signal.aborted)
|
|
setResult({ key, rows: [], error: true, coverage: null });
|
|
});
|
|
return () => controller.abort();
|
|
}, [currentId, effectiveCatalogueUrl, key, radius]);
|
|
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,
|
|
...(!radius && areaLabel ? [areaLabel] : []),
|
|
...(radius ? [`Raio de ${radius} km`] : []),
|
|
...(selected ? [selected.label] : []),
|
|
].join(' · ')}
|
|
. A consulta compara os dados publicados; não avalia
|
|
rentabilidade.{' '}
|
|
{radius
|
|
? 'O raio substitui o filtro por área e pode atravessar limites administrativos.'
|
|
: 'Sem raio seleccionado, não é calculada 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>
|
|
<BusinessDistance record={row} />
|
|
</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>
|
|
)}
|
|
{current && !current.error && current.coverage && (
|
|
<GeographicCoverage coverage={current.coverage} />
|
|
)}
|
|
{radiusAvailable ? (
|
|
<fieldset className="rounded border p-3">
|
|
<legend>Âmbito geográfico</legend>
|
|
<label>
|
|
Pesquisar por área ou distância
|
|
<select
|
|
className="block w-full rounded border p-2"
|
|
value={radius}
|
|
onChange={(event) =>
|
|
setRadiusSelection({
|
|
recordId: currentId,
|
|
value: event.target.value,
|
|
})
|
|
}
|
|
>
|
|
<option value="">
|
|
{areaLabel
|
|
? `Área: ${areaLabel}`
|
|
: 'Sem limite por distância'}
|
|
</option>
|
|
{[1, 5, 10, 25, 50, 100, 250, 500, 1000, 2000].map(
|
|
(value) => (
|
|
<option key={value} value={String(value)}>
|
|
Até {value} km desta ficha
|
|
</option>
|
|
),
|
|
)}
|
|
</select>
|
|
</label>
|
|
</fieldset>
|
|
) : (
|
|
<p className="text-sm">
|
|
A pesquisa por raio requer um ponto primário público exacto
|
|
na ficha de referência. Pode continuar por área, sector e
|
|
classificação.
|
|
</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>
|
|
);
|
|
}
|