Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5756c0282 | ||
|
|
bf2c054943 | ||
|
|
f3455432cf | ||
|
|
4b3c7e161f | ||
|
|
3a3aba5026 | ||
|
|
fde7343894 | ||
|
|
e0987afb0e | ||
|
|
bad05eb092 | ||
|
|
b2812e5925 | ||
|
|
fdadc8ace7 | ||
|
|
996b5b08cd |
@@ -119,3 +119,8 @@ INVESTMOZ_TAX_RULE_APPROVERS=
|
|||||||
INVESTMOZ_TAX_RULE_PUBLISHERS=
|
INVESTMOZ_TAX_RULE_PUBLISHERS=
|
||||||
|
|
||||||
INVESTMOZ_ZONE_TERRITORY_REVIEWERS=
|
INVESTMOZ_ZONE_TERRITORY_REVIEWERS=
|
||||||
|
|
||||||
|
# Local LibreTranslate service and installed language models.
|
||||||
|
LIBRETRANSLATE_URL=http://127.0.0.1:5000
|
||||||
|
LIBRETRANSLATE_TIMEOUT=60
|
||||||
|
LIBRETRANSLATE_API_KEY=
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Api;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class TranslationApiController extends Controller
|
||||||
|
{
|
||||||
|
public function languages(): JsonResponse
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->get($this->url().'/languages');
|
||||||
|
if ($response->successful() && is_array($response->json())) {
|
||||||
|
return response()->json($response->json())->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
} catch (Throwable) {
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function translate(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'text' => 'required|string|max:10000',
|
||||||
|
'source_lang' => 'required|string|max:20',
|
||||||
|
'target_lang' => 'required|string|max:20',
|
||||||
|
'is_html' => 'boolean',
|
||||||
|
]);
|
||||||
|
if ($data['source_lang'] === $data['target_lang']) {
|
||||||
|
return response()->json(['original_text' => $data['text'], 'translated_text' => $data['text'], 'source_lang' => $data['source_lang'], 'target_lang' => $data['target_lang']])->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = ['q' => $data['text'], 'source' => $data['source_lang'], 'target' => $data['target_lang'], 'format' => ($data['is_html'] ?? false) ? 'html' : 'text'];
|
||||||
|
if (config('services.translation.api_key')) {
|
||||||
|
$payload['api_key'] = config('services.translation.api_key');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->post($this->url().'/translate', $payload);
|
||||||
|
$translated = $response->json('translatedText');
|
||||||
|
if ($response->successful() && is_string($translated) && $translated !== '') {
|
||||||
|
return response()->json(['original_text' => $data['text'], 'translated_text' => $translated, 'source_lang' => $data['source_lang'], 'target_lang' => $data['target_lang']])->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
} catch (Throwable) {
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503)->header('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
|
||||||
|
private function url(): string
|
||||||
|
{
|
||||||
|
return rtrim((string) config('services.translation.url'), '/');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,9 @@ namespace App\Http\Controllers\Api\V1;
|
|||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\InvestmentCatalogue;
|
||||||
|
use App\Services\OpportunityMaturity;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
@@ -15,6 +18,11 @@ class OpportunityController extends Controller
|
|||||||
'q' => ['nullable', 'string', 'max:120'],
|
'q' => ['nullable', 'string', 'max:120'],
|
||||||
'sector' => ['nullable', 'string', 'max:80'],
|
'sector' => ['nullable', 'string', 'max:80'],
|
||||||
'province' => ['nullable', 'string', 'max:80'],
|
'province' => ['nullable', 'string', 'max:80'],
|
||||||
|
'province_id' => ['nullable', 'uuid'],
|
||||||
|
'district_id' => ['nullable', 'uuid'],
|
||||||
|
'admin_post_id' => ['nullable', 'uuid'],
|
||||||
|
'locality_id' => ['nullable', 'uuid'],
|
||||||
|
'geo_location_id' => ['nullable', 'uuid'],
|
||||||
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
|
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
|
||||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||||
@@ -47,22 +55,24 @@ class OpportunityController extends Controller
|
|||||||
|
|
||||||
if (! empty($validated['sector'])) {
|
if (! empty($validated['sector'])) {
|
||||||
$sector = $validated['sector'];
|
$sector = $validated['sector'];
|
||||||
\App\Services\SectorOrganization::constrain($query, $sector);
|
SectorOrganization::constrain($query, $sector);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! empty($validated['province'])) {
|
$territory = array_intersect_key($validated, array_flip(['province', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'geo_location_id']));
|
||||||
$query->where('province', $validated['province']);
|
if (array_filter($territory, fn ($value) => $value !== null && $value !== '') !== []) {
|
||||||
|
// Keep the legacy search's sorting and non-territorial filters while sharing the public territorial contract.
|
||||||
|
$query->whereIn('opportunities.id', app(InvestmentCatalogue::class)->query($territory)->reorder()->select('opportunities.id'));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! empty($validated['maturity_level'])) {
|
if (! empty($validated['maturity_level'])) {
|
||||||
\App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$results = $query->orderByDesc('is_featured')
|
$results = $query->orderByDesc('is_featured')
|
||||||
->orderByDesc('published_at')
|
->orderByDesc('published_at')
|
||||||
->paginate($validated['per_page'] ?? 12);
|
->paginate($validated['per_page'] ?? 12);
|
||||||
|
|
||||||
return response()->json($results);
|
return response()->json($results->withQueryString()->through(fn ($record) => app(InvestmentCatalogue::class)->presentLocation($record)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(string $slug): JsonResponse
|
public function show(string $slug): JsonResponse
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\ExistingBusiness;
|
||||||
|
use App\Models\Sector;
|
||||||
|
use App\Services\EditorialReading;
|
||||||
|
use App\Services\FederatedSearch;
|
||||||
|
use App\Services\InvestmentCatalogue;
|
||||||
|
use App\Services\InvestmentGeography;
|
||||||
|
use App\Services\InvestmentZones;
|
||||||
|
use App\Services\SearchTerms;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
class GlobalSearchController extends Controller
|
||||||
|
{
|
||||||
|
public function __invoke(Request $request, InvestmentCatalogue $catalogue, SearchTerms $search, FederatedSearch $federated): Response
|
||||||
|
{
|
||||||
|
$input = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||||
|
$term = trim($input['q'] ?? '');
|
||||||
|
$tokens = $search->tokens($term);
|
||||||
|
$results = ['data' => [], 'total' => 0, 'current_page' => 1, 'last_page' => 1, 'per_page' => 5, 'unavailable' => []];
|
||||||
|
if ($tokens !== []) {
|
||||||
|
$factories = [
|
||||||
|
'Páginas e serviços' => function () use ($search, $tokens, $term) {
|
||||||
|
$pages = array_values(array_filter($this->pages(), fn ($page) => $search->matches(implode(' ', $page), $tokens)));
|
||||||
|
usort($pages, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens)
|
||||||
|
?: strcmp($a['title'], $b['title']) ?: strcmp($a['url'], $b['url']));
|
||||||
|
|
||||||
|
return ['count' => count($pages), 'fetch' => fn ($offset, $limit) => array_slice($pages, $offset, $limit)];
|
||||||
|
},
|
||||||
|
'Oportunidades' => function () use ($catalogue, $search, $tokens, $term) {
|
||||||
|
$query = $catalogue->query(['include_national' => true]);
|
||||||
|
foreach ($tokens as $token) {
|
||||||
|
$query->where(function ($match) use ($catalogue, $search, $token) {
|
||||||
|
$search->orFields($match, ['opportunities.title', 'opportunities.summary', 'opportunities.description', 'opportunities.reference', 'opportunities.province'], $token);
|
||||||
|
$match->orWhereHas('sector', fn ($sector) => $search->constrain($sector, ['name'], [$token]));
|
||||||
|
$match->orWhereExists(fn ($location) => $location->selectRaw('1')->from('geo_locations as search_location')
|
||||||
|
->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
|
||||||
|
->where(fn ($name) => $search->orFields($name, ['search_location.name'], $token))
|
||||||
|
->where(fn ($direct) => $direct->whereColumn('search_location.id', 'opportunities.primary_territory_id')
|
||||||
|
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations as search_link')
|
||||||
|
->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereColumn('search_link.geo_location_id', 'search_location.id'))));
|
||||||
|
if (preg_match('/^[a-z0-9]+$/', $token)) {
|
||||||
|
$match->orWhereIn('opportunities.id', $catalogue->query(['q' => $token, 'include_national' => true])->reorder()->select('opportunities.id'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'opportunities.title', 'opportunities.id',
|
||||||
|
fn ($r) => ['title' => $r->title, 'description' => $r->summary, 'url' => '/oportunidades/'.rawurlencode($r->slug)]);
|
||||||
|
},
|
||||||
|
'Negócios' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = ExistingBusiness::query()->published();
|
||||||
|
$search->constrain($query, ['public_title', 'activity_code', 'objective'], $tokens);
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'public_title', 'existing_businesses.id',
|
||||||
|
fn ($r) => ['title' => $r->public_title, 'description' => $r->objective, 'url' => '/negocios/'.rawurlencode($r->public_slug)]);
|
||||||
|
},
|
||||||
|
'Carteira: projectos, clusters e corredores' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = InvestmentPortfolioController::visible();
|
||||||
|
$search->constrain($query, ['investment_dossiers.title', 'investment_dossiers.content'], $tokens);
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'investment_dossiers.title', 'investment_dossiers.id',
|
||||||
|
fn ($r) => ['title' => $r->title, 'description' => $r->corridor_id ? 'Corredor' : ($r->cluster_id ? 'Cluster' : 'Projecto âncora'), 'url' => '/carteira/'.$r->id]);
|
||||||
|
},
|
||||||
|
'Documentos e legislação' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||||
|
->where('r.published', true)->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
|
||||||
|
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
|
||||||
|
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256');
|
||||||
|
$search->constrain($query, ['r.title', 'r.description', 'r.document_number', 'd.issuer', 'r.source_reference', 'r.category', 'r.topic'], $tokens);
|
||||||
|
$query->select('r.id', 'r.title', 'r.description');
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
|
||||||
|
fn ($r) => ['title' => $r->title, 'description' => $r->description, 'url' => '/documentos/'.$r->id]);
|
||||||
|
},
|
||||||
|
'Artigos' => function () use ($search, $tokens, $term) {
|
||||||
|
if (! Schema::hasColumn('portal_resources', 'editorial_content')) {
|
||||||
|
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
|
||||||
|
}
|
||||||
|
$query = app(EditorialReading::class)->publicResources()
|
||||||
|
->whereRaw("nullif(btrim(r.editorial_content->>'body'), '') is not null");
|
||||||
|
$search->constrain($query, ['r.title', "(r.editorial_content->>'body')"], $tokens);
|
||||||
|
$query->select('r.id', 'r.title')->selectRaw("r.editorial_content->>'body' as body");
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
|
||||||
|
fn ($r) => ['title' => $r->title, 'description' => Str::limit(trim(strip_tags($r->body)), 220), 'url' => '/artigos/'.$r->id]);
|
||||||
|
},
|
||||||
|
'Sectores' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = Sector::query()->where('is_active', true)->whereNotNull('published_at');
|
||||||
|
$search->constrain($query, ['name', 'description', 'short_description'], $tokens);
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'name', 'sectors.id',
|
||||||
|
fn ($r) => ['title' => $r->name, 'description' => $r->short_description, 'url' => SectorOrganization::href($r->slug)]);
|
||||||
|
},
|
||||||
|
'Localizações' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = app(InvestmentGeography::class)->publicReferences()
|
||||||
|
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality']);
|
||||||
|
$search->constrain($query, ['geo_locations.name', 'geo_locations.source_code'], $tokens);
|
||||||
|
$query->select('geo_locations.id', 'geo_locations.name', 'geo_locations.location_type');
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'geo_locations.name', 'geo_locations.id',
|
||||||
|
fn ($r) => ['title' => $r->name, 'description' => ['province' => 'Província', 'district' => 'Distrito', 'admin_post' => 'Posto administrativo', 'locality' => 'Localidade'][$r->location_type],
|
||||||
|
'url' => '/oportunidades?'.http_build_query([$r->location_type.'_id' => $r->id])]);
|
||||||
|
},
|
||||||
|
'Zonas de investimento' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = app(InvestmentZones::class)->visible();
|
||||||
|
$search->constrain($query, ['name', 'code'], $tokens);
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'name', 'investment_zones.id',
|
||||||
|
fn ($r) => ['title' => $r->name, 'description' => $r->code, 'url' => '/zonas/'.$r->id]);
|
||||||
|
},
|
||||||
|
'Parcerias' => function () use ($search, $tokens, $term) {
|
||||||
|
$query = DB::table('portal_partnerships as p')->where('p.status', 'published');
|
||||||
|
$search->constrain($query, ['p.title', 'p.sector', 'p.province'], $tokens);
|
||||||
|
$query->select('p.id', 'p.title', 'p.sector', 'p.province');
|
||||||
|
|
||||||
|
return $this->source($query, $search, $term, $tokens, 'p.title', 'p.id',
|
||||||
|
fn ($r) => ['title' => $r->title, 'description' => implode(' · ', array_filter([$r->sector, $r->province])), 'url' => '/parcerias/'.$r->id]);
|
||||||
|
},
|
||||||
|
];
|
||||||
|
$results = $federated->page($factories, (int) ($input['page'] ?? 1), 5,
|
||||||
|
fn ($item) => $search->score($item['title'], $term, $tokens));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Inertia::render('portal/search', ['query' => $term, 'results' => $results]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function source($query, SearchTerms $search, string $term, array $tokens, string $title, string $id, callable $present): array
|
||||||
|
{
|
||||||
|
$count = (clone $query)->reorder()->count();
|
||||||
|
$query->reorder();
|
||||||
|
$search->orderByRelevance($query, $title, $term, $tokens, $id);
|
||||||
|
|
||||||
|
return ['count' => $count, 'fetch' => fn ($offset, $limit) => (clone $query)->offset($offset)->limit($limit)->get()->map($present)->all()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Public service entry points and terms used to find them. */
|
||||||
|
private function pages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
['title' => 'Como investir em Moçambique', 'description' => 'Procedimentos e etapas para investir', 'url' => '/como-investir'],
|
||||||
|
['title' => 'Iniciar ou continuar investimento', 'description' => 'Preparar uma ideia e dossier de investimento', 'url' => '/investimentos/iniciar'],
|
||||||
|
['title' => 'Oportunidades de investimento', 'description' => 'Pesquisar por sector, localização e maturidade', 'url' => '/oportunidades'],
|
||||||
|
['title' => 'Carteira de investimento', 'description' => 'Projectos âncora, clusters e corredores', 'url' => '/carteira'],
|
||||||
|
['title' => 'Negócios existentes', 'description' => 'Compra, venda e participação em negócios', 'url' => '/negocios'],
|
||||||
|
['title' => 'Sectores de investimento', 'description' => 'Actividades económicas e sectores prioritários', 'url' => '/sectores'],
|
||||||
|
['title' => 'Zonas de investimento', 'description' => 'Zonas económicas especiais, ZEE, ZFI e parques industriais', 'url' => '/zonas'],
|
||||||
|
['title' => 'Contextos de investimento', 'description' => 'Formas de iniciar e preparar um investimento', 'url' => '/contextos-de-investimento'],
|
||||||
|
['title' => 'Documentos e formulários', 'description' => 'Acervo documental e formulários para investidores e empresas', 'url' => '/documentos'],
|
||||||
|
['title' => 'Formulário do investidor', 'description' => 'Dados e contacto para investir', 'url' => '/formularios/investidor'],
|
||||||
|
['title' => 'Formulário de empresa', 'description' => 'Dados e contacto para empresas', 'url' => '/formularios/empresa'],
|
||||||
|
['title' => 'Legislação e incentivos', 'description' => 'Leis, decretos, benefícios e enquadramento legal', 'url' => '/legislacao'],
|
||||||
|
['title' => 'Simulador fiscal', 'description' => 'Simular impostos e cenários fiscais de investimento', 'url' => '/simulador-fiscal'],
|
||||||
|
['title' => 'Formulários fiscais', 'description' => 'Preparação dos formulários IVA e IRPC', 'url' => '/formularios/fiscais'],
|
||||||
|
['title' => 'Terra e DUAT', 'description' => 'Apoio ao uso e aproveitamento da terra', 'url' => '/terra-duat'],
|
||||||
|
['title' => 'Bolsa de parcerias', 'description' => 'Encontrar parceiros e propostas', 'url' => '/parcerias'],
|
||||||
|
['title' => 'Apoio ao investidor', 'description' => 'Contactos e pedido de apoio', 'url' => '/apoio'],
|
||||||
|
['title' => 'Educação para investimento', 'description' => 'Conteúdos educativos e orientação', 'url' => '/educacao'],
|
||||||
|
['title' => 'Sobre o InvesteMoz', 'description' => 'Informação institucional do portal', 'url' => '/sobre'],
|
||||||
|
['title' => 'Contacto', 'description' => 'Contactar o portal InvesteMoz', 'url' => '/contacto'],
|
||||||
|
['title' => 'Política de privacidade', 'description' => 'Privacidade e tratamento de dados pessoais', 'url' => '/politica-de-privacidade'],
|
||||||
|
['title' => 'Termos de uso', 'description' => 'Condições de utilização do portal', 'url' => '/termos-de-uso'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
|
||||||
|
/** Combines independent, already-authorised sources without loading complete catalogues. */
|
||||||
|
final class FederatedSearch
|
||||||
|
{
|
||||||
|
/** @param array<string, callable(): array{count:int, fetch:callable(int,int): iterable}> $factories */
|
||||||
|
public function page(array $factories, int $requestedPage, int $size = 5, ?callable $score = null): array
|
||||||
|
{
|
||||||
|
$sources = [];
|
||||||
|
$unavailable = [];
|
||||||
|
foreach ($factories as $label => $factory) {
|
||||||
|
try {
|
||||||
|
$sources[$label] = $factory();
|
||||||
|
} catch (QueryException $exception) {
|
||||||
|
report($exception);
|
||||||
|
$unavailable[] = $label;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a source fails after its count, remove it and recompute the page offsets.
|
||||||
|
do {
|
||||||
|
$failed = false;
|
||||||
|
$total = array_sum(array_column($sources, 'count'));
|
||||||
|
$last = max(1, (int) ceil($total / $size));
|
||||||
|
$page = min(max(1, $requestedPage), $last);
|
||||||
|
$first = ($page - 1) * $size;
|
||||||
|
$items = [];
|
||||||
|
$positions = array_fill_keys(array_keys($sources), 0);
|
||||||
|
$buffers = array_fill_keys(array_keys($sources), []);
|
||||||
|
for ($position = 0; $position < min($total, $first + $size); $position++) {
|
||||||
|
$best = null;
|
||||||
|
$bestScore = PHP_INT_MIN;
|
||||||
|
foreach ($sources as $label => $source) {
|
||||||
|
if ($buffers[$label] === [] && $positions[$label] < $source['count']) {
|
||||||
|
try {
|
||||||
|
$batch = iterator_to_array((function () use ($source, $positions, $label, $size) {
|
||||||
|
yield from ($source['fetch'])($positions[$label], $size);
|
||||||
|
})(), false);
|
||||||
|
$positions[$label] += count($batch);
|
||||||
|
$buffers[$label] = $batch;
|
||||||
|
if ($batch === []) {
|
||||||
|
$positions[$label] = $source['count'];
|
||||||
|
}
|
||||||
|
} catch (QueryException $exception) {
|
||||||
|
report($exception);
|
||||||
|
$unavailable[] = $label;
|
||||||
|
unset($sources[$label]);
|
||||||
|
$failed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($buffers[$label] === []) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$candidateScore = $score ? $score($buffers[$label][0]) : 0;
|
||||||
|
if ($best === null || $candidateScore > $bestScore) {
|
||||||
|
$best = $label;
|
||||||
|
$bestScore = $candidateScore;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($failed || $best === null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$item = array_shift($buffers[$best]);
|
||||||
|
if ($position >= $first) {
|
||||||
|
$items[] = [...$item, 'category' => $best];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while ($failed);
|
||||||
|
|
||||||
|
return ['data' => $items, 'total' => $total, 'current_page' => $page, 'last_page' => $last,
|
||||||
|
'per_page' => $size, 'unavailable' => $unavailable];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,14 @@ namespace App\Services;
|
|||||||
use App\Http\Controllers\InvestmentPortfolioController;
|
use App\Http\Controllers\InvestmentPortfolioController;
|
||||||
use App\Models\InvestmentDossier;
|
use App\Models\InvestmentDossier;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Models\Sector;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class InvestmentCatalogue
|
class InvestmentCatalogue
|
||||||
{
|
{
|
||||||
@@ -17,8 +22,8 @@ class InvestmentCatalogue
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
public function filters(Request $request): array
|
public function filters(Request $request): array
|
||||||
{
|
{
|
||||||
$filters = $request->validate(['perspective' => ['nullable', 'in:exists,needs,ideas,opportunities'],'q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
$filters = $request->validate(['perspective' => ['nullable', 'in:exists,needs,ideas,opportunities'], 'q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||||
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
'preparation' => ['nullable', Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||||
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
|
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
|
||||||
@@ -40,14 +45,15 @@ class InvestmentCatalogue
|
|||||||
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
||||||
'publication_state' => ['nullable', 'in:published'],
|
'publication_state' => ['nullable', 'in:published'],
|
||||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||||
|
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||||
app(InvestmentGeography::class)->selection($filters);
|
app(InvestmentGeography::class)->selection($filters);
|
||||||
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
||||||
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
||||||
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
||||||
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
|
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
|
||||||
throw \Illuminate\Validation\ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
|
throw ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
|
||||||
}
|
}
|
||||||
if (\Illuminate\Support\Str::isUuid($filters['association_target'])) {
|
if (Str::isUuid($filters['association_target'])) {
|
||||||
$filters[$alias] = $filters['association_target'];
|
$filters[$alias] = $filters['association_target'];
|
||||||
unset($filters['association_type'], $filters['association_target']);
|
unset($filters['association_type'], $filters['association_target']);
|
||||||
}
|
}
|
||||||
@@ -62,9 +68,13 @@ class InvestmentCatalogue
|
|||||||
*/
|
*/
|
||||||
public function query(array $filters): Builder
|
public function query(array $filters): Builder
|
||||||
{
|
{
|
||||||
|
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||||
$query = Opportunity::published()->with('sector:id,name,slug');
|
$query = Opportunity::published()->with('sector:id,name,slug');
|
||||||
if (in_array($filters['perspective'] ?? '', ['exists','needs','ideas'], true)) $query->where('workflow_context->promotional_summary->projection->proactive->group', $filters['perspective']);
|
if (in_array($filters['perspective'] ?? '', ['exists', 'needs', 'ideas'], true)) {
|
||||||
elseif (($filters['perspective'] ?? '') === 'opportunities') $query->whereNull('workflow_context->promotional_summary->projection->proactive');
|
$query->where('workflow_context->promotional_summary->projection->proactive->group', $filters['perspective']);
|
||||||
|
} elseif (($filters['perspective'] ?? '') === 'opportunities') {
|
||||||
|
$query->whereNull('workflow_context->promotional_summary->projection->proactive');
|
||||||
|
}
|
||||||
$associated = $this->publicAssociatedIds($filters);
|
$associated = $this->publicAssociatedIds($filters);
|
||||||
if (($filters['territory_basis'] ?? 'all') === 'direct') {
|
if (($filters['territory_basis'] ?? 'all') === 'direct') {
|
||||||
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
|
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
|
||||||
@@ -86,9 +96,14 @@ class InvestmentCatalogue
|
|||||||
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
||||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
|
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
|
||||||
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
|
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
|
||||||
|
if (count($path) === 1) {
|
||||||
|
$this->declaredProvince($territory, $path[0]->name);
|
||||||
|
}
|
||||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||||
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
||||||
if (count($path) === 1) $this->approvedCorridorProvince($territory, $path[0]->id);
|
if (count($path) === 1) {
|
||||||
|
$this->approvedCorridorProvince($territory, $path[0]->id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ($includeNational) {
|
if ($includeNational) {
|
||||||
$territory->orWhere('opportunities.geography_scope', 'national');
|
$territory->orWhere('opportunities.geography_scope', 'national');
|
||||||
@@ -163,6 +178,10 @@ class InvestmentCatalogue
|
|||||||
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
||||||
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
||||||
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
|
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
|
||||||
|
$province = app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->first(['name']);
|
||||||
|
if ($province) {
|
||||||
|
$this->declaredProvince($matches, $province->name);
|
||||||
|
}
|
||||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||||
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
|
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
|
||||||
if (app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->exists()) {
|
if (app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->exists()) {
|
||||||
@@ -206,7 +225,9 @@ class InvestmentCatalogue
|
|||||||
if (! empty($filters['before'])) {
|
if (! empty($filters['before'])) {
|
||||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
|
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
|
||||||
}
|
}
|
||||||
if (! empty($filters['category'])) $query->where('opportunity_category', $filters['category']);
|
if (! empty($filters['category'])) {
|
||||||
|
$query->where('opportunity_category', $filters['category']);
|
||||||
|
}
|
||||||
app(OpportunityClassification::class)->constrain($query, $filters);
|
app(OpportunityClassification::class)->constrain($query, $filters);
|
||||||
$sort = $filters['sort'] ?? 'recent';
|
$sort = $filters['sort'] ?? 'recent';
|
||||||
|
|
||||||
@@ -218,14 +239,28 @@ class InvestmentCatalogue
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function declaredProvince($query, string $name): void
|
||||||
|
{
|
||||||
|
// Read the published province declaration only when no more precise territory contradicts it.
|
||||||
|
// This does not assign any canonical ID, district, post, locality or coordinates to the record.
|
||||||
|
$query->orWhere(fn ($declared) => $declared->whereNull('opportunities.primary_territory_id')
|
||||||
|
->whereNotExists(fn ($links) => $links->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))
|
||||||
|
->where('opportunities.geography_scope', '!=', 'national')
|
||||||
|
->whereRaw('lower(btrim(opportunities.province)) = ?', [mb_strtolower(trim($name))]));
|
||||||
|
}
|
||||||
|
|
||||||
private function approvedCorridorProvince($query, string $provinceId): void
|
private function approvedCorridorProvince($query, string $provinceId): void
|
||||||
{
|
{
|
||||||
$code = app(InvestmentGeography::class)->publicReferences()->where('id', $provinceId)->value('source_code');
|
$code = app(InvestmentGeography::class)->publicReferences()->where('id', $provinceId)->value('source_code');
|
||||||
$names = [];
|
$names = [];
|
||||||
foreach (config('investment_corridors', []) as $entry) {
|
foreach (config('investment_corridors', []) as $entry) {
|
||||||
if (in_array($code, $entry['provinces'], true)) $names[] = $entry['name'];
|
if (in_array($code, $entry['provinces'], true)) {
|
||||||
|
$names[] = $entry['name'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! $names) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (!$names) return;
|
|
||||||
$query->orWhere(fn ($context) => $context->whereNull('opportunities.primary_territory_id')
|
$query->orWhere(fn ($context) => $context->whereNull('opportunities.primary_territory_id')
|
||||||
->whereNotExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))
|
->whereNotExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))
|
||||||
->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||||
@@ -240,13 +275,19 @@ class InvestmentCatalogue
|
|||||||
$ids = array_filter([$record->primary_territory_id, ...$record->additionalTerritories()->pluck('geo_locations.id')->all()]);
|
$ids = array_filter([$record->primary_territory_id, ...$record->additionalTerritories()->pluck('geo_locations.id')->all()]);
|
||||||
foreach (array_unique($ids) as $id) {
|
foreach (array_unique($ids) as $id) {
|
||||||
$path = $geo->path($id);
|
$path = $geo->path($id);
|
||||||
if ($path) $paths[] = implode(' / ', array_column($path, 'name'));
|
if ($path) {
|
||||||
|
$paths[] = implode(' / ', array_column($path, 'name'));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ($paths) $label = implode('; ', array_unique($paths));
|
if ($paths) {
|
||||||
elseif ($provinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record)) {
|
$label = implode('; ', array_unique($paths));
|
||||||
|
} elseif ($provinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record)) {
|
||||||
$label = implode(' / ', array_column($provinces, 'name')).' — contexto provincial do corredor; distrito e posto administrativo não indicados';
|
$label = implode(' / ', array_column($provinces, 'name')).' — contexto provincial do corredor; distrito e posto administrativo não indicados';
|
||||||
} else $label = implode(' / ', array_filter([$record->province, $record->district])) ?: 'Localização não indicada';
|
} else {
|
||||||
|
$label = implode(' / ', array_filter([$record->province, $record->district])) ?: 'Localização não indicada';
|
||||||
|
}
|
||||||
$record->setAttribute('territorial_summary', $label);
|
$record->setAttribute('territorial_summary', $label);
|
||||||
|
|
||||||
return $record;
|
return $record;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,9 +301,9 @@ class InvestmentCatalogue
|
|||||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||||
'categories' => OpportunityManagement::CATEGORIES,
|
'categories' => OpportunityManagement::CATEGORIES,
|
||||||
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||||
'sectors' => \App\Models\Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
||||||
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
|
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES,
|
||||||
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
|
'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS]];
|
||||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||||
$query = DB::table($table)->whereNull('deleted_at');
|
$query = DB::table($table)->whereNull('deleted_at');
|
||||||
if (! $management) {
|
if (! $management) {
|
||||||
@@ -295,7 +336,7 @@ class InvestmentCatalogue
|
|||||||
$zones = app(InvestmentZones::class)->visible();
|
$zones = app(InvestmentZones::class)->visible();
|
||||||
if (! $management && $territoryFilters !== []) {
|
if (! $management && $territoryFilters !== []) {
|
||||||
// Opportunity words/modalities are not names/categories of zones.
|
// Opportunity words/modalities are not names/categories of zones.
|
||||||
$zones = app(InvestmentZones::class)->search(\Illuminate\Support\Arr::only($territoryFilters,
|
$zones = app(InvestmentZones::class)->search(Arr::only($territoryFilters,
|
||||||
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
||||||
}
|
}
|
||||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||||
@@ -318,24 +359,35 @@ class InvestmentCatalogue
|
|||||||
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
||||||
$selected = array_filter(array_intersect_key($filters, $kinds));
|
$selected = array_filter(array_intersect_key($filters, $kinds));
|
||||||
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
|
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
|
||||||
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) unset($selected[$key]);
|
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) {
|
||||||
|
unset($selected[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($selected === []) {
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
if ($selected === []) return [];
|
|
||||||
$ids = [];
|
$ids = [];
|
||||||
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
||||||
foreach ($records as $record) {
|
foreach ($records as $record) {
|
||||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
||||||
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') continue;
|
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
foreach ($selected as $field => $target) {
|
foreach ($selected as $field => $target) {
|
||||||
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) $ids[$field][] = $record->id;
|
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) {
|
||||||
|
$ids[$field][] = $record->id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (!empty($selected['corridor_id'])) {
|
if (! empty($selected['corridor_id'])) {
|
||||||
$dossier = InvestmentPortfolioController::visible()->where('corridor_id', $selected['corridor_id'])->first();
|
$dossier = InvestmentPortfolioController::visible()->where('corridor_id', $selected['corridor_id'])->first();
|
||||||
if ($dossier) $ids['corridor_id'] = array_values(array_unique([...($ids['corridor_id'] ?? []), ...app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($dossier)]));
|
if ($dossier) {
|
||||||
|
$ids['corridor_id'] = array_values(array_unique([...($ids['corridor_id'] ?? []), ...app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($dossier)]));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $ids;
|
return $ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,9 +411,12 @@ class InvestmentCatalogue
|
|||||||
$public = ['profile' => null, 'facets' => collect(), 'zones' => collect(), 'classification' => [], 'source_evidence' => [],
|
$public = ['profile' => null, 'facets' => collect(), 'zones' => collect(), 'classification' => [], 'source_evidence' => [],
|
||||||
'primary_territory_path' => app(InvestmentGeography::class)->path($opportunity->primary_territory_id, true),
|
'primary_territory_path' => app(InvestmentGeography::class)->path($opportunity->primary_territory_id, true),
|
||||||
'opportunity_locations' => app(InvestmentRelations::class)->opportunityLocations($id)];
|
'opportunity_locations' => app(InvestmentRelations::class)->opportunityLocations($id)];
|
||||||
foreach (self::RELATIONS as $relation => $_) $public[$relation] = collect();
|
foreach (self::RELATIONS as $relation => $_) {
|
||||||
|
$public[$relation] = collect();
|
||||||
|
}
|
||||||
$public['locations'] = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
|
$public['locations'] = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
|
||||||
->where('l.opportunity_id', $id)->where('g.data_classification', 'public')->whereNull('g.deleted_at')->get(['g.id', 'g.name']);
|
->where('l.opportunity_id', $id)->where('g.data_classification', 'public')->whereNull('g.deleted_at')->get(['g.id', 'g.name']);
|
||||||
|
|
||||||
return $public;
|
return $public;
|
||||||
}
|
}
|
||||||
$result = ['profile' => DB::table('opportunity_profiles')->where('opportunity_id', $id)->first(),
|
$result = ['profile' => DB::table('opportunity_profiles')->where('opportunity_id', $id)->first(),
|
||||||
|
|||||||
@@ -12,6 +12,21 @@ final class InvestmentGeography
|
|||||||
{
|
{
|
||||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||||
|
|
||||||
|
/** Resolve an old province-name search only when the public register has exactly one match. */
|
||||||
|
public function provinceSearch(array $filters): array
|
||||||
|
{
|
||||||
|
if (empty($filters['province_id']) && is_string($filters['province'] ?? null) && trim($filters['province']) !== '') {
|
||||||
|
$matches = $this->publicReferences()->where('location_type', 'province')
|
||||||
|
->whereRaw('lower(btrim(name)) = ?', [mb_strtolower(trim($filters['province']))])->limit(2)->get(['id']);
|
||||||
|
if ($matches->count() === 1) {
|
||||||
|
$filters['province_id'] = $matches[0]->id;
|
||||||
|
unset($filters['province']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $filters;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict published dossier searches using direct territories and public, validated structure links.
|
* Restrict published dossier searches using direct territories and public, validated structure links.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
/** Text matching shared by the database and the built-in page catalogue. */
|
||||||
|
final class SearchTerms
|
||||||
|
{
|
||||||
|
/** @return list<string> */
|
||||||
|
public function tokens(string $query): array
|
||||||
|
{
|
||||||
|
$normalized = mb_strtolower(Str::ascii($query));
|
||||||
|
$tokens = array_values(array_filter(array_unique(array_map(
|
||||||
|
fn ($word) => trim($word, ".,;:!?\"'()[]{}"),
|
||||||
|
preg_split('/\s+/u', trim($normalized), -1, PREG_SPLIT_NO_EMPTY) ?: []
|
||||||
|
)), fn ($word) => $word !== ''));
|
||||||
|
if (count($tokens) > 1) {
|
||||||
|
$meaningful = array_values(array_diff($tokens, ['a', 'as', 'o', 'os', 'de', 'do', 'da', 'dos', 'das', 'em', 'no', 'na', 'nos', 'nas', 'para', 'por', 'e', 'como', 'qual', 'quais', 'um', 'uma']));
|
||||||
|
|
||||||
|
return $meaningful === [] ? $tokens : $meaningful;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Known Portuguese spelling and number variants; do not infer semantic equivalence. */
|
||||||
|
public function variants(string $token): array
|
||||||
|
{
|
||||||
|
foreach ([['sector', 'sectores', 'setor', 'setores'], ['projecto', 'projectos', 'projeto', 'projetos'],
|
||||||
|
['investir', 'investimento', 'investimentos'], ['investidor', 'investidores'], ['oportunidade', 'oportunidades'], ['documento', 'documentos'],
|
||||||
|
['empresa', 'empresas'], ['parceria', 'parcerias'], ['zona', 'zonas'], ['formulario', 'formularios'],
|
||||||
|
['provincia', 'provincias'], ['corredor', 'corredores'], ['cluster', 'clusters'], ['imposto', 'impostos'], ['licenca', 'licencas']] as $group) {
|
||||||
|
if (in_array($token, $group, true)) {
|
||||||
|
return $group;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$token];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pattern(string $token): string
|
||||||
|
{
|
||||||
|
return '%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $token).'%';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Columns are trusted application constants, never user input. */
|
||||||
|
public function orFields($query, array $columns, string $token): void
|
||||||
|
{
|
||||||
|
foreach ($columns as $column) {
|
||||||
|
foreach ($this->variants($token) as $variant) {
|
||||||
|
$query->orWhereRaw($this->normalizedColumn($column)." LIKE ? ESCAPE '!'", [$this->pattern($variant)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function constrain($query, array $columns, array $tokens): void
|
||||||
|
{
|
||||||
|
foreach ($tokens as $token) {
|
||||||
|
$query->where(fn ($match) => $this->orFields($match, $columns, $token));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function matches(string $text, array $tokens): bool
|
||||||
|
{
|
||||||
|
$text = mb_strtolower(Str::ascii($text));
|
||||||
|
foreach ($tokens as $token) {
|
||||||
|
if (! array_filter($this->variants($token), fn ($variant) => str_contains($text, $variant))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function normalizedColumn(string $column): string
|
||||||
|
{
|
||||||
|
return "translate(lower(coalesce({$column}::text, '')), 'áàâãäéèêëíìîïóòôõöúùûüçñ', 'aaaaaeeeeiiiiooooouuuucn')";
|
||||||
|
}
|
||||||
|
|
||||||
|
public function score(string $title, string $phrase, array $tokens): int
|
||||||
|
{
|
||||||
|
$title = mb_strtolower(Str::ascii($title));
|
||||||
|
$phrase = mb_strtolower(Str::ascii(trim($phrase)));
|
||||||
|
$score = $title === $phrase ? 1000 : (str_contains($title, $phrase) ? 400 : 0);
|
||||||
|
foreach ($tokens as $token) {
|
||||||
|
if ($this->matches($title, [$token])) {
|
||||||
|
$score += 20;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $score;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same title score used for in-memory pages, with bound search terms. */
|
||||||
|
public function orderByRelevance($query, string $titleColumn, string $phrase, array $tokens, string $tieColumn): void
|
||||||
|
{
|
||||||
|
$column = $this->normalizedColumn($titleColumn);
|
||||||
|
$phrase = mb_strtolower(Str::ascii(trim($phrase)));
|
||||||
|
$sql = "CASE WHEN {$column} = ? THEN 1000 WHEN {$column} LIKE ? ESCAPE '!' THEN 400 ELSE 0 END";
|
||||||
|
$bindings = [$phrase, $this->pattern($phrase)];
|
||||||
|
foreach ($tokens as $token) {
|
||||||
|
$conditions = [];
|
||||||
|
foreach ($this->variants($token) as $variant) {
|
||||||
|
$conditions[] = "{$column} LIKE ? ESCAPE '!'";
|
||||||
|
$bindings[] = $this->pattern($variant);
|
||||||
|
}
|
||||||
|
$sql .= ' + CASE WHEN ('.implode(' OR ', $conditions).') THEN 20 ELSE 0 END';
|
||||||
|
}
|
||||||
|
$query->orderByRaw('('.$sql.') DESC', $bindings)->orderBy($titleColumn)->orderBy($tieColumn);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,12 @@ return [
|
|||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
'translation' => [
|
||||||
|
'url' => env('LIBRETRANSLATE_URL', 'http://127.0.0.1:5000'),
|
||||||
|
'timeout' => (int) env('LIBRETRANSLATE_TIMEOUT', 60),
|
||||||
|
'api_key' => env('LIBRETRANSLATE_API_KEY'),
|
||||||
|
],
|
||||||
|
|
||||||
'postmark' => [
|
'postmark' => [
|
||||||
'key' => env('POSTMARK_API_KEY'),
|
'key' => env('POSTMARK_API_KEY'),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1863,4 +1863,28 @@ Instalado pelo avanço normal de main e pipeline existente, preservando 23ecccfa
|
|||||||
|
|
||||||
**Filtros provinciais: separado e aberto.** Esta entrega não alterou a lógica dos filtros nem demonstra a correcção relatada de Agronegócio/Maputo Província no portal. Preservam-se as provas e os estados históricos; não encerrar V2-07/V2-10 ou ACT-02 por causa da persistência de Competitividade. Restantes alterações permanecem na sequência posterior.
|
**Filtros provinciais: separado e aberto.** Esta entrega não alterou a lógica dos filtros nem demonstra a correcção relatada de Agronegócio/Maputo Província no portal. Preservam-se as provas e os estados históricos; não encerrar V2-07/V2-10 ou ACT-02 por causa da persistência de Competitividade. Restantes alterações permanecem na sequência posterior.
|
||||||
|
|
||||||
Origem de continuidade: C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-persistence-20261029, instalado b81f477b. A pasta principal anterior não deve substituir esta versão sem reconciliação do delta.
|
Origem de continuidade: C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-persistence-20261029, instalado b81f477b. A pasta principal anterior não deve substituir esta versão sem reconciliação do delta.
|
||||||
|
### 29/10/2026 — V2-07/V2-10 / ACT-02, diagnóstico dos filtros provinciais em curso
|
||||||
|
|
||||||
|
Separação confirmada pela Tempo: a equipa executará e registará a conferência visual autenticada de Competitividade (continua pendente); o Codex prossegue no código/API dos filtros. Provas aceites preservadas, sem repetição das suites fiscais ou de Competitividade. Nenhuma perda de dados confirmada nesta passagem.
|
||||||
|
|
||||||
|
Reprodução pública em b81f477b: Agronegócio/Maputo Província por province_id na API /api/v1/investment/search devolve5 oportunidades (IDs60–64). O mesmo nome em province devolve0, tanto nessa API como em /api/v1/opportunities/search. A API antiga ignora province_id e devolve34, incluindo outras províncias. São lacunas de normalização/compatibilidade entre entradas, não prova de eliminação nem falha demonstrada da expansão hierárquica já existente. Corrigir apenas os deltas: resolver nomes provinciais públicos inequívocos para a mesma hierarquia e aplicar o filtro territorial na API antiga, preservando outros filtros, versões públicas, localização real e dados. Demonstrar todos os níveis inferiores por pedidos HTTP em QA isolada; província apenas contextual ou declarada não deve ganhar distrito. O problema permanece aberto até às provas específicas e à conferência da API instalada; não encerrar a conferência visual da equipa por testes técnicos.
|
||||||
|
### 29/10/2026 — duas frentes e diagnóstico local Edge
|
||||||
|
|
||||||
|
A equipa executa directamente e regista a conferência visual autenticada de Competitividade (editar → guardar → reabrir → conferir versão aprovada); estado pendente até execução. O Codex prossegue com código/API dos filtros provinciais, independentemente do navegador. Provas aceites preservadas.
|
||||||
|
|
||||||
|
Ligação identificada: com.openai.codexextension, manifesto stdio válido, extensão Edge instalada e activa no perfil detectado, host executado como filho do Edge; named pipes do browser-use presentes e servidor registado nos logs do cliente. Inspeccionados os listeners/processos sem libertar portas. Não foi identificado conflito TCP nem um serviço de extensão parado. Não foi encontrado erro de permissões no recorte de logs consultado, sem excluir outros pontos. A descoberta desta sessão continua a indicar access host indisponível; o runtime exige caminho do pipe e identidade verificadora, ausentes na shell. Falha de passagem de contexto é uma hipótese delimitada, não conclusão de porta ocupada. O registo de erros do service worker não ficou acessível pela ligação de navegador indisponível. A recuperação suportada, limitada à abertura do perfil Edge detectado, não restabeleceu a leitura do URL. Não foram terminados processos, reinstalados hosts nem alteradas permissões/políticas. InvesteMoz e SGF continuam em execução. Relatório local: outputs/edge-bridge-diagnostic-20261029/report.json. Não declarar recuperada a ligação nem concluída a conferência visual.
|
||||||
|
|
||||||
|
Correcção provincial preparada no ramo codex/province-search-20261029; validação QA/instalação pendentes. A sessão SSH anterior expirou. O lançamento automático de nova consola foi recusado pela revisão automática com indicação genérica blocked by policy, sem razão adicional; foi pedido arranque/autenticação manual no helper existente. Nenhuma escrita no activo ou novo ensaio remoto ocorreu por essa tentativa.
|
||||||
|
### 29/10/2026 — filtros provinciais: correcção candidata, pendente de QA
|
||||||
|
|
||||||
|
Reproduzido no portal instalado b81f477b: /api/v1/investment/search por province_id de Maputo Província devolve5; por province textual devolve0 nas duas APIs; a API antiga com province_id ignora o parâmetro e devolve34 de Agronegócio. Preparada correcção no ramo codex/province-search-20261029, preservando a expansão de descendentes existente e aplicando a mesma selecção territorial à API antiga. Nomes provinciais só são resolvidos quando a correspondência pública exacta é inequívoca. Declarações provinciais antigas são consideradas sem atribuir distrito, posto, localidade ou coordenadas, e não prevalecem sobre territórios explícitos contraditórios. Nenhum dado cadastral é actualizado por esta correcção.
|
||||||
|
|
||||||
|
Quatro testes HTTP preparados para província/distrito/posto/localidade e localizações adicionais, onze províncias e exclusão de vizinhas/privados/eliminados, preservação das localizações e consistência de catálogo/mapa/exportação. Sintaxe PHP e diff conferidos; testes ainda não executados e candidato ainda não instalado. Recibo: docs/investmoz/unification/province-search-qa-20261029.json. A sessão SSH expirou e a nova consola automática foi recusada pela revisão de aprovação com blocked by policy (sem razão específica adicional); pedida autenticação manual no helper outputs/province-search-20261029/ssh-session.py. Não substituir ausência de ensaio por declaração de correcção concluída.
|
||||||
|
|
||||||
|
A conferência visual de Competitividade fica a cargo da equipa e permanece pendente até execução/registo; provas técnicas aceites preservadas. Ligação Edge diagnosticada separadamente: extensão/manifesto/host activos, stdio/named pipes, leitura do URL não restabelecida pela recuperação suportada do perfil. Nenhum processo terminado nem porta libertada/reconfigurada. InvesteMoz e SGF preservados. Relatório local: outputs/edge-bridge-diagnostic-20261029/report.json. Os filtros mantêm-se abertos até QA e confirmação da API instalada.
|
||||||
|
### 29/10/2026 — filtros provinciais, prova HTTP específica em QA
|
||||||
|
|
||||||
|
Quatro testes Feature/364 asserções passaram na base restaurada province_search_20261029_test, porta55441, candidato e0987afb. Seleccionar só a província, por nome público inequívoco ou ID, inclui registos provinciais, distritais, de posto e localidade e localizações adicionais, nas duas APIs; confirmada cobertura das11 províncias e exclusão de vizinhas. Privados/eliminados não entram; distrito seleccionado não recebe oportunidades apenas provinciais. Declaração provincial antiga não supera localização explícita noutro território. Maputo Província por nome/ID, página do catálogo, mapa e exportação concordam nas5 oportunidades do contexto aprovado; sem coordenadas ou distrito inventados. Campos e relações guardados permanecem inalterados. Zero escritas no activo; nenhuma migração nem alteração de permissões. O conjunto inclui provas novas da hierarquia HTTP, sem reabrir as provas aceites de Competitividade/fiscalidade.
|
||||||
|
|
||||||
|
Recibo: docs/investmoz/unification/province-search-qa-20261029.json. Instalação e confirmação da API no portal continuam pendentes; não declarar encerrado o problema por QA isolada. A conferência visual autenticada de Competitividade permanece separada, pendente de execução e registo pela equipa. A sessão SSH foi reaberta a pedido expresso da Tempo e ficou autenticada; a recusa anterior da abertura automática não constitui bloqueio actual.
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-10-29",
|
||||||
|
"scope": "Reorganização visual local do catálogo autorizada pela Tempo; sem instalação no portal.",
|
||||||
|
"base": "838ad941a24ae76ec4bf91ccc3f92012668fe8cf",
|
||||||
|
"design": {
|
||||||
|
"desktop": "Painel lateral de filtros e resultados em duas colunas; lista com acções na coluna lateral do cartão.",
|
||||||
|
"mobile": "Filtros expansíveis; cartões numa coluna; áreas de toque e foco visível.",
|
||||||
|
"content": "Todos os campos, descrições, avisos e acções conservados; 29 fichas agrupadas por tipo. Aviso provincial e título dos resultados recuperados do pedido fornecido."
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"types": {
|
||||||
|
"command": "npm run types:check",
|
||||||
|
"exit": 0
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"command": "INVESTMOZ_QA_BUILD=1 npm run build",
|
||||||
|
"exit": 0,
|
||||||
|
"target": "public/build-qa-opportunities",
|
||||||
|
"limitations": "Avisos existentes de fontaine opcional e chunks grandes. Compilação anterior à formatação final, apenas cosmética."
|
||||||
|
},
|
||||||
|
"browser": {
|
||||||
|
"result": "passed",
|
||||||
|
"scope": "Local compiled React application with public document-based preview fixtures and mocked HTTP, no database or external requests. Does not prove backend or live availability.",
|
||||||
|
"layouts": [
|
||||||
|
{
|
||||||
|
"width": 1440,
|
||||||
|
"scrollWidth": 1440,
|
||||||
|
"count": 12,
|
||||||
|
"headingY": 296.65625,
|
||||||
|
"sidebarVisible": true,
|
||||||
|
"groups": [
|
||||||
|
"Corredores6",
|
||||||
|
"Clusters8",
|
||||||
|
"Projectos âncora15"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 1024,
|
||||||
|
"scrollWidth": 1024,
|
||||||
|
"count": 12,
|
||||||
|
"headingY": 292.234375,
|
||||||
|
"sidebarVisible": true,
|
||||||
|
"groups": [
|
||||||
|
"Corredores6",
|
||||||
|
"Clusters8",
|
||||||
|
"Projectos âncora15"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 768,
|
||||||
|
"scrollWidth": 768,
|
||||||
|
"count": 12,
|
||||||
|
"headingY": 368.078125,
|
||||||
|
"sidebarVisible": false,
|
||||||
|
"groups": [
|
||||||
|
"Corredores6",
|
||||||
|
"Clusters8",
|
||||||
|
"Projectos âncora15"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 390,
|
||||||
|
"scrollWidth": 390,
|
||||||
|
"count": 12,
|
||||||
|
"headingY": 395.265625,
|
||||||
|
"sidebarVisible": false,
|
||||||
|
"groups": [
|
||||||
|
"Corredores6",
|
||||||
|
"Clusters8",
|
||||||
|
"Projectos âncora15"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 320,
|
||||||
|
"scrollWidth": 320,
|
||||||
|
"count": 12,
|
||||||
|
"headingY": 425.96875,
|
||||||
|
"sidebarVisible": false,
|
||||||
|
"groups": [
|
||||||
|
"Corredores6",
|
||||||
|
"Clusters8",
|
||||||
|
"Projectos âncora15"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"checks": [
|
||||||
|
"All 12 sample titles, full descriptions and territorial caveats preserved at every width; expanded filter controls fit 320/390/1024px.",
|
||||||
|
"Missing currency error remains visible on mobile.",
|
||||||
|
"Keyboard opens mobile filters; search preserved through collapse, reopen and reload.",
|
||||||
|
"Hierarchical territory selector still loads and updates filter context (synthetic QA territory).",
|
||||||
|
"Investment selection and dossier link survive reload.",
|
||||||
|
"Comparison still limits four selections and renders the existing comparison table.",
|
||||||
|
"All 29 territorial reference cards remain accessible in three expandable groups.",
|
||||||
|
"All five views activate and fit mobile width; map uses explicit no-coordinates preview data."
|
||||||
|
],
|
||||||
|
"pageErrors": 0
|
||||||
|
},
|
||||||
|
"logic": [
|
||||||
|
{
|
||||||
|
"file": "resources/js/pages/investment/catalogue.tsx",
|
||||||
|
"existingNonPresentationLogicBlocks": 33,
|
||||||
|
"missing": 0,
|
||||||
|
"excludes": "JSX and its inline handlers; those reviewed in source diff and directed browser checks."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "resources/js/components/opportunity-search-filters.tsx",
|
||||||
|
"existingNonPresentationLogicBlocks": 5,
|
||||||
|
"missing": 0,
|
||||||
|
"excludes": "JSX and its inline handlers; those reviewed in source diff and directed browser checks."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"preservation": {
|
||||||
|
"schema": "Sem alterações.",
|
||||||
|
"data": "Sem acesso à base de dados; prévia baseada nos documentos locais e referências públicas já guardadas.",
|
||||||
|
"configuration": "Sem alterações.",
|
||||||
|
"permissions": "Sem alterações.",
|
||||||
|
"queries": "Filtros, endpoints e regras preservados; testes de backend anteriores reutilizados, sem nova prova de backend ou autenticação.",
|
||||||
|
"sourceFiles": [
|
||||||
|
{
|
||||||
|
"file": "resources/js/pages/investment/catalogue.tsx",
|
||||||
|
"sha256": "d4697cb83c2f92a786108286c7743401b44d61c5b367e9ff322b05d0424b0d70"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "resources/js/components/opportunity-search-filters.tsx",
|
||||||
|
"sha256": "d5b75fc78f7dc272b745117d37e040f1bb921cec2783c3f50ddaaafff7e2df66"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "resources/js/components/catalogue-filter-group.tsx",
|
||||||
|
"sha256": "f2728dfc2393de7d4f4338d3ea1057ed84317603980a2dc44f8a208d225cda45"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "resources/css/investment-catalogue.css",
|
||||||
|
"sha256": "034a79a62ba13220f814027afd62e43c49e2947afd1d9e25a87ba37d3648fd93"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"evidence": {
|
||||||
|
"directory": "outputs/catalogue-layout-20261029/",
|
||||||
|
"screenshots": [
|
||||||
|
"catalogue-1440.png",
|
||||||
|
"catalogue-1024.png",
|
||||||
|
"catalogue-768.png",
|
||||||
|
"catalogue-390.png",
|
||||||
|
"catalogue-320.png",
|
||||||
|
"filters-expanded-390.png",
|
||||||
|
"territorial-expanded.png",
|
||||||
|
"list-1440.png"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"matrix": [
|
||||||
|
"RF-MN-010",
|
||||||
|
"RF-PII-003",
|
||||||
|
"RNF-EDU-008",
|
||||||
|
"MASTER-471012ab-0124"
|
||||||
|
],
|
||||||
|
"deployment": "Não realizada; alteração activa fora desta entrega local.",
|
||||||
|
"dynamicMoreFilters": {
|
||||||
|
"origin": "Pedido expresso da Tempo, 29/10/2026",
|
||||||
|
"collapsed": "Mais filtros",
|
||||||
|
"expanded": "Menos filtros",
|
||||||
|
"verification": {
|
||||||
|
"result": "passed",
|
||||||
|
"checks": [
|
||||||
|
"Mais filtros quando recolhido",
|
||||||
|
"Menos filtros quando aberto",
|
||||||
|
"Alternância por clique e teclado",
|
||||||
|
"Escolhas e contagem conservadas"
|
||||||
|
],
|
||||||
|
"scope": "Componente React real, compilado e exercitado em Chromium; sem backend ou base de dados."
|
||||||
|
},
|
||||||
|
"deployment": "Alteração local; sem instalação."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"public_baseline": [
|
||||||
|
{
|
||||||
|
"first_page_ids": [
|
||||||
|
64,
|
||||||
|
63,
|
||||||
|
62,
|
||||||
|
61,
|
||||||
|
60
|
||||||
|
],
|
||||||
|
"path": "/api/v1/investment/search?sector=agronegocio\u0026province_id=bfde2651-2b46-5d9c-a500-733fa55a8c5c",
|
||||||
|
"total": 5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"first_page_ids": [
|
||||||
|
|
||||||
|
],
|
||||||
|
"path": "/api/v1/investment/search?sector=agronegocio\u0026province=Maputo%20Prov%C3%ADncia",
|
||||||
|
"total": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"first_page_ids": [
|
||||||
|
|
||||||
|
],
|
||||||
|
"path": "/api/v1/opportunities/search?sector=agronegocio\u0026province=Maputo%20Prov%C3%ADncia",
|
||||||
|
"total": 0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"first_page_ids": [
|
||||||
|
62,
|
||||||
|
63,
|
||||||
|
64,
|
||||||
|
60,
|
||||||
|
61,
|
||||||
|
49,
|
||||||
|
50,
|
||||||
|
55,
|
||||||
|
58,
|
||||||
|
56,
|
||||||
|
52,
|
||||||
|
48
|
||||||
|
],
|
||||||
|
"path": "/api/v1/opportunities/search?sector=agronegocio\u0026province_id=bfde2651-2b46-5d9c-a500-733fa55a8c5c",
|
||||||
|
"total": 34
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"branch": "codex/province-search-20261029",
|
||||||
|
"data_writes": 0,
|
||||||
|
"authentication": {
|
||||||
|
"automatic_console_launch": "rejected by automatic approval review: blocked by policy; no specific reason supplied",
|
||||||
|
"manual_helper": "outputs/province-search-20261029/ssh-session.py",
|
||||||
|
"session": "closed"
|
||||||
|
},
|
||||||
|
"installed": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||||
|
"cause": "Legacy text province uses exact opportunity field comparison; legacy search ignores canonical province_id; canonical province filtering already expands descendants",
|
||||||
|
"remaining": [
|
||||||
|
"fresh backup and isolated restore",
|
||||||
|
"existing Git installation pipeline",
|
||||||
|
"installed public API confirmation"
|
||||||
|
],
|
||||||
|
"visual_competitiveness": "pending direct execution and record by team; accepted proofs preserved",
|
||||||
|
"schema_changes": 0,
|
||||||
|
"status": "specific_HTTP_QA_passed_not_installed",
|
||||||
|
"change": "Resolve a public, unique exact province name to the existing hierarchy; constrain legacy API by the same published catalogue territorial query; include declared province-only legacy records only without contradictory primary/additional territories",
|
||||||
|
"candidate": "b2812e5925d27f46cf97f94da17fd64d41747c6f",
|
||||||
|
"browser_bridge": "diagnosed separately; URL read not restored; outputs/edge-bridge-diagnostic-20261029/report.json",
|
||||||
|
"checks": {
|
||||||
|
"specific_HTTP_tests_run": 4,
|
||||||
|
"diff": "passed",
|
||||||
|
"specific_HTTP_tests_planned": 4,
|
||||||
|
"PHP_syntax": "passed",
|
||||||
|
"specific_HTTP_assertions": 364
|
||||||
|
},
|
||||||
|
"source_sha256": {
|
||||||
|
"app/Services/InvestmentCatalogue.php": "731091c7c754aaf40a7235c405869134523de1fef431e686a94a1d1b3d1e9fd9",
|
||||||
|
"app/Services/InvestmentGeography.php": "9815835078fe625031d795e3fda83b4af0fc1a0d18af6e8ce9fd2d3f8e535c72",
|
||||||
|
"tests/Feature/ProvinceSearchCompatibilityTest.php": "b0164154b6f08c624dcd81425f145c2fc2770a595f04c7917858c30b26049279",
|
||||||
|
"app/Http/Controllers/Api/V1/OpportunityController.php": "69a873a429e3510d5fd6691b58d825cf877274f6cd7d1303aa8029555680bb92"
|
||||||
|
},
|
||||||
|
"tested_candidate": "e0987afb0e2722300eeb0d50e8797b07fb53853a",
|
||||||
|
"QA": {
|
||||||
|
"candidate": "e0987afb0e2722300eeb0d50e8797b07fb53853a",
|
||||||
|
"status": "passed",
|
||||||
|
"database": "province_search_20261029_test",
|
||||||
|
"port": 55441,
|
||||||
|
"snapshot_restored": true,
|
||||||
|
"active_database_writes": 0,
|
||||||
|
"schema_changes": 0,
|
||||||
|
"log": "/var/lib/investmoz-deploy/province-search-qa-20261029/qa-e0987afb0e2722300eeb0d50e8797b07fb53853a.log",
|
||||||
|
"summary": "PHPUnit 12.5.34 by Sebastian Bergmann and contributors.\n\nRuntime: PHP 8.4.27\nConfiguration: /var/lib/investmoz-deploy/province-search-qa-20261029/e0987afb0e2722300eeb0d50e8797b07fb53853a-1793279039249452598/phpunit.xml\n\n.... 4 / 4 (100%)\n\nTime: 00:10.928, Memory: 60.50 MB\n\n\u001b[30;42mOK (4 tests, 364 assertions)\u001b[0m\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7386,39 +7386,18 @@ Pedido expresso da Tempo: preencher formulário de IVA ou IRPC, em vez de abrir
|
|||||||
Incremento em preparação QA: entrada directa em Documentos e Formulários, preenchimento manual dos campos correspondidos de IVA e subconjunto M22, identificação/período, revisão, impressão e ficheiro privado para recuperação mediante confirmação. Escolha técnica: sem persistência no servidor nem ligação automática ao dossier neste incremento; não altera schema, dados, permissões ou cálculos. Ficheiro não publicado. IRPC ajustamentos completos, outros regimes, anexos, assinatura e submissão à AT fora da cobertura; L8 permanece parcial. Ainda sem instalação deste incremento. Próximas provas apenas do delta: fidelidade da recuperação, rejeição de ficheiros incompatíveis sem perda, formatos/valores desconhecidos, acesso público e compilação.
|
Incremento em preparação QA: entrada directa em Documentos e Formulários, preenchimento manual dos campos correspondidos de IVA e subconjunto M22, identificação/período, revisão, impressão e ficheiro privado para recuperação mediante confirmação. Escolha técnica: sem persistência no servidor nem ligação automática ao dossier neste incremento; não altera schema, dados, permissões ou cálculos. Ficheiro não publicado. IRPC ajustamentos completos, outros regimes, anexos, assinatura e submissão à AT fora da cobertura; L8 permanece parcial. Ainda sem instalação deste incremento. Próximas provas apenas do delta: fidelidade da recuperação, rejeição de ficheiros incompatíveis sem perda, formatos/valores desconhecidos, acesso público e compilação.
|
||||||
|
|
||||||
|
|
||||||
## 29/10/2026 — ACT-20261029-01, inventário antes da verificação do incremento
|
### 03/11/2026 — pesquisa rápida, incremento local em preparação
|
||||||
|
|
||||||
Continuação sequencial solicitada pela Tempo. Correspondência: ACT-20261029-01 reutiliza D-02 §8, clusters/cadeias e a orientação metodológica documentada em 23/10. Concluído previamente e preservado: gestão de clusters, etapas, ligações, lacunas e relações auditadas; disponibilidade instalada de carteira/âncoras e formulários fiscais conforme recibos de 28/10. Nenhuma perda nova confirmada nesta inspecção de código; não foi feita nova comparação de dados ou alegada prova do servidor. A pasta principal está em fde644af, enquanto o último recibo identifica 332c16eb instalado; reconciliar o delta sobre essa origem antes de instalar, sem substituir o destino pela pasta principal.
|
Inventário reutilizado: a pesquisa da página inicial encaminhava ao catálogo de oportunidades; continuam disponíveis os catálogos de oportunidades, carteira, documentos, sectores, zonas e negócios, com regras próprias de publicação. Nenhuma perda foi demonstrada nesta comparação de código. A alteração local encaminha para uma página agrupada com estes seis domínios e paginação por grupo, reutilizando os filtros públicos dos destinos; não altera dados nem permissões. O incremento ainda não comprova pesquisa integral: faltam outros módulos, pesquisa de conteúdo dos ficheiros, correspondência mais flexível e prova funcional com dados na base QA isolada. A pesquisa vazia e a validação de comprimento passaram; a prova com dados ficou pendente por falta de credenciais da base QA. Não instalado no activo. A referência ao pedido de pesquisa na matriz existente (MASTER-9dee08d0-0016 e MASTER-471012ab-0124) não altera a aceitação anterior nem encerra estes requisitos.
|
||||||
|
|
||||||
Incremento em preparação: diagnóstico qualitativo das cinco forças na edição do cluster, sector/região editáveis, fonte/período/evidência/justificação/limites/oportunidade por força; indeterminação explícita, ficheiro privado transferível e recuperação com confirmação. Sem alteração de schema, dados, permissões, publicações ou motores fiscais. Persistência no servidor, ligação territorial canónica, dados sectoriais fundamentados e consulta pública permanecem por implementar; ACT-01 não está concluída. Verificação dirigida e instalação ainda pendentes neste registo inicial. Restantes ACT-02 a 16 mantêm o estado anterior e a sequência, sem trabalho SGF nesta passagem.
|
|
||||||
### ACT-20261029-01 — candidato sequencial preparado, 29/10/2026
|
|
||||||
|
|
||||||
Primeiro incremento implementado, **parcial e ainda não instalado**: gestão → clusters → editar → Competitividade. As cinco forças conservam fonte, período, evidência, apreciação, limites e oportunidade; sector e região explícitos, sem inferências automáticas. Transferência de rascunhos JSON e recuperação restrita ao mesmo cluster, com confirmação antes de substituir. Quatro testes frontend dirigidos, TypeScript e compilação QA passaram tanto na pasta de trabalho como no candidato baseado em 332c16eb. Guarda C132 local passou; não foram efectuados testes nem escritas na base activa. A edição existente recebe apenas a inclusão do componente; contratos e permissões existentes preservados.
|
### 03/11/2026 — pesquisa sem acesso à base
|
||||||
|
|
||||||
Origem reconciliada: main remoto e revisão pública conferidos em 332c16eb em 29/10. Candidato em C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-sequential-20261029. Consulta do estado remoto não equivale a inventário novo da base. Sessão SSH anterior encerrada; autenticação por chave recusada. Instalação requer autenticação SSH, backup fresco, restauro isolado, guarda de versão, pipeline existente e conferência posterior. Não instalar a pasta principal sobre o destino. A sequência solicitada mantém ACT-02 a 16 por iniciar após a instalação e o saldo de ACT-01; persistência no servidor, cobertura factual e consulta pública continuam pendentes. Sem declaração de conferência visual autenticada.
|
A pedido da Tempo, continuação por análise do código e testes isolados, sem ligar à base. A pesquisa local passou a combinar palavras em qualquer ordem, ignorar maiúsculas e acentos portugueses nos campos pesquisados e tratar % e _ literalmente. Agrupa páginas/serviços, oportunidades, negócios, carteira, documentos/legislação, sectores, zonas e parcerias públicas; preserva os filtros de visibilidade dos percursos e sinaliza fontes indisponíveis. O catálogo estático de serviços pode ser pesquisado sem consultar tabelas; o acesso HTTP ao portal continua dependente da sua configuração. Documentos são pesquisados pelos metadados, não pelo conteúdo dos ficheiros; outros módulos e dados privados não estão cobertos. Testes isolados não demonstram resultados nem desempenho contra dados reais ou o funcionamento de toda a aplicação sem base. Sem instalação, migração, publicação ou alteração de dados no activo. Referência na matriz existente: MASTER-9dee08d0-0016, com aceitação anterior preservada.
|
||||||
### 29/10/2026 — ACT-20261029-01, primeiro incremento instalado: 23ecccfa
|
|
||||||
|
|
||||||
Estado corrente de ACT-01: **parcial — primeiro incremento instalado**, substituindo apenas o estado planeado/preparado deste recorte; ACT-02 a 16 não foram implementadas nesta entrega. Instalado por avanço normal de main e pipeline existente em https://teste-investidor.tempo.co.mz/. Entrada: Gestão → Clusters → Editar → Competitividade — cinco forças de Porter. Preparação qualitativa por sector/região, evidências/fontes/períodos/limites e oportunidades, transferência JSON e recuperação confirmada do mesmo cluster. Sem gravação no servidor nem publicação da análise. Persistência, cobertura factual, território canónico e consulta pública continuam pendentes; esta instalação não encerra o critério amplo ACT-01.
|
|
||||||
|
|
||||||
Provas: backup fresco, restauro isolado sem rede das 176 tabelas; pipeline com lifecycle de schema (3.106 asserções), 59 testes Unit/320 asserções e 1.180 testes frontend sem falhas, tipos e compilação; quatro ficheiros do incremento conferidos por SHA-256 no instalado; C132 no destino passou. Comparação após instalação: todas as 176 tabelas de domínio preservadas, diferenças operacionais apenas em cache/sessões; 369 ficheiros/configuração idênticos. Acesso anónimo ao catálogo privado recusado HTTP401. Zero migrações/importações, nenhuma nova divulgação nem mudança de permissões; versão anterior 332c16eb preservada. Conferência visual autenticada permanece pendente. Recibo: `docs/investmoz/unification/competitiveness-sequential-qa-20261029.json`, em docs/investmoz/unification. As provas aceites anteriores foram reutilizadas; não foram reabertas por esta entrega.
|
### 04/11/2026 — pesquisa unificada, candidata local
|
||||||
### 29/10/2026 — ACT-01, persistência e aprovação: execução em curso
|
|
||||||
|
|
||||||
Ordem confirmada pela Tempo: 1) gravar/validar/recuperar na gestão com permissões e histórico, 2) consultar publicamente apenas conteúdo aprovado, 3) restantes alterações. A instalação da interface 23ecccfa e os 1.180 testes anteriores são provas desse incremento, não prova de persistência. Sem perda nova confirmada; preservar a versão pública anterior e os recibos de backup/restauro. O problema dos filtros provinciais permanece **separado e aberto**, sem declaração de correcção por estes trabalhos.
|
A pedido da Tempo, mantida a execução sem acesso à base e preservados os catálogos e provas anteriores. A pesquisa passa a apresentar uma sequência global de cinco resultados por página, números de página e a expressão efectiva, com cores vermelho, preto e branco; as fontes públicas são combinadas por relevância do título e identificadas por tipo. Aceita algumas variantes portuguesas de escrita, singular/plural e termos de ligação; acrescenta páginas públicas, localizações públicas e o corpo de edições editoriais publicadas e autorizadas. Contagens e blocos são obtidos por fonte, sem carregar integralmente os catálogos; uma fonte indisponível é identificada e as restantes mantidas. Escolhas técnicas de pesquisa, não novas regras organizacionais.
|
||||||
|
|
||||||
Escolha técnica: reutilizar snapshots cifrados nos eventos append-only de auditoria, já usados pelo portal; bloqueio transaccional do cluster, controlo de versão e histórico imutável. Sem alteração de schema/permissões. Guardar rascunho e recuperar histórico não publica; aprovação explícita fixa a versão consultável, edições seguintes preservam a aprovação anterior até nova decisão. Rascunhos parciais são guardáveis; aprovação exige os fundamentos das cinco forças. Recuperação/conflito não deve sobrescrever edições inadvertidamente. Acesso público continua limitado às fichas publicadas. Implementação e provas específicas de persistência/consulta ainda em preparação; restantes ACT mantêm o estado anterior.
|
Foram efectuados testes isolados de correspondência, sequência e paginação entre fontes, indisponibilidade, renderização e compilação; não há demonstração com dados reais ou de desempenho com volumes de produção. A pesquisa não indexa o texto dos ficheiros originais nem cobre todos os módulos e dados privados autorizados; não declarar pesquisa universal. Sem alteração de dados, permissões, ficheiros originais ou instalação no activo. Cobertura e limites registados em MASTER-9dee08d0-0016 na matriz existente, sem alterar aceitações anteriores.
|
||||||
### ACT-01 — prova específica antes da instalação, 29/10/2026
|
|
||||||
|
|
||||||
Sete testes Feature/93 asserções passaram na base restaurada competitiveness_persistence_20261029_test, porta 55441: gravação e leitura HTTP entre pedidos, retorno pela edição da gestão, histórico cifrado, validação de campos/cluster/forças, normalização do formato recuperável, conflitos sem sobrescrita, aprovação fixa, rascunhos posteriores sem divulgação, recuperação histórica como nova versão, retirada e exclusão do conteúdo não aprovado na consulta pública. Utilizadores sem permissão e pedidos anónimos foram recusados na gestão. O teste público percorreu a ficha publicada e confirmou 404 da ficha não publicada. Zero escritas na base activa. Esta prova não afirma conferência visual autenticada nem correcção dos filtros provinciais, que permanecem abertos. Recibo: docs/investmoz/unification/competitiveness-persistence-qa-20261029.json. Compilação QA, tipos e quatro testes frontend dirigidos passaram; instalação ainda pendente.
|
|
||||||
### 29/10/2026 — ACT-01, gravação/recuperação e consulta aprovada instaladas: b81f477b
|
|
||||||
|
|
||||||
Instalado pelo avanço normal de main e pipeline existente, preservando 23ecccfa para retorno. Gestão → Clusters → Editar → Competitividade agora recupera o rascunho do servidor e permite gravar, consultar a versão actual, confirmar recuperação e recuperar uma versão histórica como nova gravação. Versões cifradas e imutáveis na auditoria existente, com bloqueio transaccional do cluster e controlo de versão; conflitos conservam a versão guardada e os campos do editor. Reutilizada a permissão existente de gestão, sem novos papéis ou aprovadores. Rascunhos incompletos podem ser guardados; a aprovação exige âmbito e fundamentos das cinco forças.
|
|
||||||
|
|
||||||
**Percurso da gestão:** preencher → Guardar rascunho no servidor → voltar à edição para recuperar → consultar histórico quando necessário. Para comparar com outra gravação, usar Consultar versão actual do servidor e confirmar antes de substituir os campos; transferir primeiro edições que se queira conservar. Recuperar o histórico cria nova versão e mantém o histórico e a aprovação pública existente. A aprovação ou retirada é expressa, com evidência/motivo registado. A ficha pública de um cluster publicado mostra exclusivamente a análise aprovada; novas gravações privadas não alteram essa versão. Uma ficha não publicada continua indisponível ao público. Não houve aprovação nem divulgação automática de análises.
|
|
||||||
|
|
||||||
**Prova específica:** sete testes Feature/93 asserções na base restaurada e isolada competitiveness_persistence_20261029_test, porta55441. Abrange gravação/recuperação HTTP, retorno na gestão, validação e formato, histórico cifrado, conflito, acesso recusado, aprovação fixa, rascunho posterior privado, recuperação, retirada e consulta pública/404 de ficha não publicada. Os 1.180 testes frontend não são apresentados como prova substituta de persistência. Pipeline: tipos, compilação, lifecycle de schema1/3106, Unit59/320 e frontend1180 sem falhas. Dez ficheiros de código/testes do instalado conferidos por SHA-256 com os da QA; C132 no destino passou.
|
|
||||||
|
|
||||||
**Preservação e limites:** backup fresco/restauro isolado176; comparação posterior de176 tabelas sem alterações de domínio, apenas diferenças operacionais de cache/sessões; 369 ficheiros/configuração idênticos. Ligação real teste_investidor_app conferida em leitura, com privilégios existentes de SELECT/INSERT em auditoria e bloqueio do cluster; endpoint de gestão anónimo HTTP401. Nenhuma escrita sintética na base activa, migração, importação, mudança de permissões ou nova publicação. A conferência visual autenticada no instalado permanece pendente; não foi simulada uma decisão real de conteúdo no activo. ACT-01 tem agora persistência e consulta aprovada implementadas/instaladas, mantendo parcial a cobertura factual por sector/região. Recibo: docs/investmoz/unification/competitiveness-persistence-qa-20261029.json.
|
|
||||||
|
|
||||||
**Filtros provinciais: separado e aberto.** Esta entrega não alterou a lógica dos filtros nem demonstra a correcção relatada de Agronegócio/Maputo Província no portal. Preservam-se as provas e os estados históricos; não encerrar V2-07/V2-10 ou ACT-02 por causa da persistência de Competitividade. Restantes alterações permanecem na sequência posterior.
|
|
||||||
|
|
||||||
Origem de continuidade: C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-persistence-20261029, instalado b81f477b. A pasta principal anterior não deve substituir esta versão sem reconciliação do delta.
|
|
||||||
|
|||||||
@@ -3043,4 +3043,28 @@ Instalado pelo avanço normal de main e pipeline existente, preservando 23ecccfa
|
|||||||
|
|
||||||
**Filtros provinciais: separado e aberto.** Esta entrega não alterou a lógica dos filtros nem demonstra a correcção relatada de Agronegócio/Maputo Província no portal. Preservam-se as provas e os estados históricos; não encerrar V2-07/V2-10 ou ACT-02 por causa da persistência de Competitividade. Restantes alterações permanecem na sequência posterior.
|
**Filtros provinciais: separado e aberto.** Esta entrega não alterou a lógica dos filtros nem demonstra a correcção relatada de Agronegócio/Maputo Província no portal. Preservam-se as provas e os estados históricos; não encerrar V2-07/V2-10 ou ACT-02 por causa da persistência de Competitividade. Restantes alterações permanecem na sequência posterior.
|
||||||
|
|
||||||
Origem de continuidade: C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-persistence-20261029, instalado b81f477b. A pasta principal anterior não deve substituir esta versão sem reconciliação do delta.
|
Origem de continuidade: C:/laragon/www/portal-investidor-competitiveness-qa-20261029, ramo codex/competitiveness-persistence-20261029, instalado b81f477b. A pasta principal anterior não deve substituir esta versão sem reconciliação do delta.
|
||||||
|
### 29/10/2026 — V2-07/V2-10 / ACT-02, diagnóstico dos filtros provinciais em curso
|
||||||
|
|
||||||
|
Separação confirmada pela Tempo: a equipa executará e registará a conferência visual autenticada de Competitividade (continua pendente); o Codex prossegue no código/API dos filtros. Provas aceites preservadas, sem repetição das suites fiscais ou de Competitividade. Nenhuma perda de dados confirmada nesta passagem.
|
||||||
|
|
||||||
|
Reprodução pública em b81f477b: Agronegócio/Maputo Província por province_id na API /api/v1/investment/search devolve5 oportunidades (IDs60–64). O mesmo nome em province devolve0, tanto nessa API como em /api/v1/opportunities/search. A API antiga ignora province_id e devolve34, incluindo outras províncias. São lacunas de normalização/compatibilidade entre entradas, não prova de eliminação nem falha demonstrada da expansão hierárquica já existente. Corrigir apenas os deltas: resolver nomes provinciais públicos inequívocos para a mesma hierarquia e aplicar o filtro territorial na API antiga, preservando outros filtros, versões públicas, localização real e dados. Demonstrar todos os níveis inferiores por pedidos HTTP em QA isolada; província apenas contextual ou declarada não deve ganhar distrito. O problema permanece aberto até às provas específicas e à conferência da API instalada; não encerrar a conferência visual da equipa por testes técnicos.
|
||||||
|
### 29/10/2026 — duas frentes e diagnóstico local Edge
|
||||||
|
|
||||||
|
A equipa executa directamente e regista a conferência visual autenticada de Competitividade (editar → guardar → reabrir → conferir versão aprovada); estado pendente até execução. O Codex prossegue com código/API dos filtros provinciais, independentemente do navegador. Provas aceites preservadas.
|
||||||
|
|
||||||
|
Ligação identificada: com.openai.codexextension, manifesto stdio válido, extensão Edge instalada e activa no perfil detectado, host executado como filho do Edge; named pipes do browser-use presentes e servidor registado nos logs do cliente. Inspeccionados os listeners/processos sem libertar portas. Não foi identificado conflito TCP nem um serviço de extensão parado. Não foi encontrado erro de permissões no recorte de logs consultado, sem excluir outros pontos. A descoberta desta sessão continua a indicar access host indisponível; o runtime exige caminho do pipe e identidade verificadora, ausentes na shell. Falha de passagem de contexto é uma hipótese delimitada, não conclusão de porta ocupada. O registo de erros do service worker não ficou acessível pela ligação de navegador indisponível. A recuperação suportada, limitada à abertura do perfil Edge detectado, não restabeleceu a leitura do URL. Não foram terminados processos, reinstalados hosts nem alteradas permissões/políticas. InvesteMoz e SGF continuam em execução. Relatório local: outputs/edge-bridge-diagnostic-20261029/report.json. Não declarar recuperada a ligação nem concluída a conferência visual.
|
||||||
|
|
||||||
|
Correcção provincial preparada no ramo codex/province-search-20261029; validação QA/instalação pendentes. A sessão SSH anterior expirou. O lançamento automático de nova consola foi recusado pela revisão automática com indicação genérica blocked by policy, sem razão adicional; foi pedido arranque/autenticação manual no helper existente. Nenhuma escrita no activo ou novo ensaio remoto ocorreu por essa tentativa.
|
||||||
|
### 29/10/2026 — filtros provinciais: correcção candidata, pendente de QA
|
||||||
|
|
||||||
|
Reproduzido no portal instalado b81f477b: /api/v1/investment/search por province_id de Maputo Província devolve5; por province textual devolve0 nas duas APIs; a API antiga com province_id ignora o parâmetro e devolve34 de Agronegócio. Preparada correcção no ramo codex/province-search-20261029, preservando a expansão de descendentes existente e aplicando a mesma selecção territorial à API antiga. Nomes provinciais só são resolvidos quando a correspondência pública exacta é inequívoca. Declarações provinciais antigas são consideradas sem atribuir distrito, posto, localidade ou coordenadas, e não prevalecem sobre territórios explícitos contraditórios. Nenhum dado cadastral é actualizado por esta correcção.
|
||||||
|
|
||||||
|
Quatro testes HTTP preparados para província/distrito/posto/localidade e localizações adicionais, onze províncias e exclusão de vizinhas/privados/eliminados, preservação das localizações e consistência de catálogo/mapa/exportação. Sintaxe PHP e diff conferidos; testes ainda não executados e candidato ainda não instalado. Recibo: docs/investmoz/unification/province-search-qa-20261029.json. A sessão SSH expirou e a nova consola automática foi recusada pela revisão de aprovação com blocked by policy (sem razão específica adicional); pedida autenticação manual no helper outputs/province-search-20261029/ssh-session.py. Não substituir ausência de ensaio por declaração de correcção concluída.
|
||||||
|
|
||||||
|
A conferência visual de Competitividade fica a cargo da equipa e permanece pendente até execução/registo; provas técnicas aceites preservadas. Ligação Edge diagnosticada separadamente: extensão/manifesto/host activos, stdio/named pipes, leitura do URL não restabelecida pela recuperação suportada do perfil. Nenhum processo terminado nem porta libertada/reconfigurada. InvesteMoz e SGF preservados. Relatório local: outputs/edge-bridge-diagnostic-20261029/report.json. Os filtros mantêm-se abertos até QA e confirmação da API instalada.
|
||||||
|
### 29/10/2026 — filtros provinciais, prova HTTP específica em QA
|
||||||
|
|
||||||
|
Quatro testes Feature/364 asserções passaram na base restaurada province_search_20261029_test, porta55441, candidato e0987afb. Seleccionar só a província, por nome público inequívoco ou ID, inclui registos provinciais, distritais, de posto e localidade e localizações adicionais, nas duas APIs; confirmada cobertura das11 províncias e exclusão de vizinhas. Privados/eliminados não entram; distrito seleccionado não recebe oportunidades apenas provinciais. Declaração provincial antiga não supera localização explícita noutro território. Maputo Província por nome/ID, página do catálogo, mapa e exportação concordam nas5 oportunidades do contexto aprovado; sem coordenadas ou distrito inventados. Campos e relações guardados permanecem inalterados. Zero escritas no activo; nenhuma migração nem alteração de permissões. O conjunto inclui provas novas da hierarquia HTTP, sem reabrir as provas aceites de Competitividade/fiscalidade.
|
||||||
|
|
||||||
|
Recibo: docs/investmoz/unification/province-search-qa-20261029.json. Instalação e confirmação da API no portal continuam pendentes; não declarar encerrado o problema por QA isolada. A conferência visual autenticada de Competitividade permanece separada, pendente de execução e registo pela equipa. A sessão SSH foi reaberta a pedido expresso da Tempo e ficou autenticada; a recusa anterior da abertura automática não constitui bloqueio actual.
|
||||||
File diff suppressed because one or more lines are too long
@@ -1,5 +1,17 @@
|
|||||||
# Roteiro executável de interface — I0–I3 QA
|
# Roteiro executável de interface — I0–I3 QA
|
||||||
|
|
||||||
|
## Tradução transversal — levantamento e plano, 02/11/2026
|
||||||
|
|
||||||
|
O pedido actual determina a tradução nas quatro línguas já apresentadas no selector: português, inglês, francês e espanhol. A referência anterior MASTER-9dee08d0-0008 prevê pelo menos português e inglês; o pedido actual explicita as quatro línguas já expostas. O levantamento é de código, não comprova a situação no ambiente activo nem substitui os recibos de reposição ou a comparação com o último estado demonstrado.
|
||||||
|
|
||||||
|
- Existe um contexto de idioma persistido no navegador e um dicionário em `tempo-brand.tsx`; a sua cobertura anterior concentrava-se no menu e rodapé. A tradução devolve o original quando não encontra uma chave. Os componentes institucionais `Trans` recorrem ao mesmo dicionário, mas várias das suas frases não têm entrada.
|
||||||
|
- Há 125 ficheiros em `resources/js/pages` (incluindo ficheiros auxiliares): páginas públicas, autenticação, gestão, oportunidades, carteira, percurso, dossier, simulador, terra, parcerias e outras áreas contêm textos portugueses directos. Formulários e componentes partilhados em `resources/js/lib` e `resources/js/components` também contêm rótulos e mensagens directos. A IA possui selector e textos próprios em português/inglês, sem integração completa com o idioma global. Catálogos e questionários de API têm pontos fixados em `pt-MZ`; mensagens de validação Laravel estão em português. Documentos, dados cadastrados, fontes e exportações precisam de tratamento distinto da interface e preservação do original.
|
||||||
|
- Incremento de código preparado: idioma do documento HTML acompanha o selector; textos comuns do acesso ao conteúdo, caminho de navegação, aviso de homologação, contacto de apoio e selector passam pelo contexto; algumas etiquetas institucionais passam a ter entradas nas três línguas. Os títulos sem entrada continuam no original. Esta cobertura é parcial, não representa conclusão do requisito nem publicação no activo.
|
||||||
|
- Continuação: etiquetas e placeholders de acesso e registo, apresentação do respectivo título, controlo acessível de visualização da palavra-passe e duas mensagens exactas de autenticação usam o mesmo contexto. Mensagens variáveis, restantes validações, outros ecrãs de autenticação e conteúdos de QA continuam por traduzir. Valores submetidos e comportamento de autenticação não foram alterados. O `types:check` e o build do primeiro incremento passaram; este acréscimo requer nova verificação.
|
||||||
|
- Comparação com `D:\Projects\revistatempo` e `D:\Projects\Tempo_Investidor\tempo-api`: a Revista usa componentes/hooks explicitamente marcados, POST `/api/translate`, protecção de tokens e cache; a API chama LibreTranslate e devolve o original em caso de falha, inclusive com HTTP 200. Não se demonstrou cobertura integral automática na Revista. Adaptado o cliente para os textos institucionais públicos já marcados com `Trans`, com URL configurável por `VITE_TRANSLATION_API_URL`, preservação de tokens, deduplicação e cache em memória apenas para respostas diferentes do original. Este incremento não envia dados de formulários, dossiers ou outras informações privadas para o serviço. A conectividade real, cobertura restante, resultados e exportações continuam pendentes de verificação e implementação; não declarar a plataforma traduzida.
|
||||||
|
|
||||||
|
Sequência restante: (1) inventariar por rota e componente, comparando com o último estado demonstrado e reutilizando provas e recibos existentes; (2) consolidar catálogo versionado e detecção de chaves ausentes para as quatro línguas; (3) migrar navegação e páginas públicas, autenticação e formulários; (4) migrar oportunidades, carteira, percurso adaptativo, dossier, simulador e áreas privadas/gestão sem alterar regras nem dados; (5) tratar mensagens do servidor, catálogos, conteúdos cadastrados e relatórios, preservando origens e indicando quando não existe versão traduzida; (6) verificar alternância, persistência, regressão dos fluxos, acessibilidade e exportações em QA isolado e registar cobertura por requisito nesta matriz e neste manual. Traduções de documentos oficiais não substituem os originais.
|
||||||
|
|
||||||
## C37 — causa confirmada; seleção de conta QA corrigida — P0, visual pendente
|
## C37 — causa confirmada; seleção de conta QA corrigida — P0, visual pendente
|
||||||
|
|
||||||
O pedido de reabertura referia a conta esperada18. A captura manual21:22–21:24UTC demonstra que foi selecionada a conta13 restaurada. O MFA foi alcançado, mas a autenticação nunca se completou. Causa concreta: credenciais MFA da conta13 cifradas pela chave de origem, incompatíveis com a chave estávelQA; a conta18 sintética não foi desafiada nessa tentativa. Nenhuma chave, MFA ou conta13 foi alterada para contornar o problema.
|
O pedido de reabertura referia a conta esperada18. A captura manual21:22–21:24UTC demonstra que foi selecionada a conta13 restaurada. O MFA foi alcançado, mas a autenticação nunca se completou. Causa concreta: credenciais MFA da conta13 cifradas pela chave de origem, incompatíveis com a chave estávelQA; a conta18 sintética não foi desafiada nessa tentativa. Nenhuma chave, MFA ou conta13 foi alterada para contornar o problema.
|
||||||
|
|||||||
@@ -0,0 +1,445 @@
|
|||||||
|
/* Presentation only: catalogue queries, records and permissions retain their contracts. */
|
||||||
|
.investment-catalogue {
|
||||||
|
--catalogue-accent: #c9141b;
|
||||||
|
--catalogue-ink: #17324d;
|
||||||
|
max-width: 1440px;
|
||||||
|
color: var(--catalogue-ink);
|
||||||
|
}
|
||||||
|
.investment-catalogue > h1 {
|
||||||
|
font-size: clamp(1.6rem, 3vw, 2.15rem);
|
||||||
|
letter-spacing: -0.035em;
|
||||||
|
}
|
||||||
|
.investment-catalogue .catalogue-intro {
|
||||||
|
margin-top: 0.65rem;
|
||||||
|
max-width: 76ch;
|
||||||
|
color: #526477;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
.catalogue-workspace {
|
||||||
|
display: grid;
|
||||||
|
gap: 1.5rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.catalogue-workspace > *,
|
||||||
|
.catalogue-results > *,
|
||||||
|
.catalogue-opportunity > * {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.catalogue-filters {
|
||||||
|
border: 1px solid #dce3eb;
|
||||||
|
border-radius: 1rem;
|
||||||
|
background: #fff;
|
||||||
|
overflow: clip;
|
||||||
|
}
|
||||||
|
.catalogue-filters-toggle,
|
||||||
|
.catalogue-filters-heading {
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.65rem;
|
||||||
|
padding: 1rem 1.15rem;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.catalogue-filters-toggle {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
min-height: 52px;
|
||||||
|
}
|
||||||
|
.catalogue-filters-toggle > svg:last-child {
|
||||||
|
margin-left: auto;
|
||||||
|
transition: transform 0.15s;
|
||||||
|
}
|
||||||
|
.catalogue-filters-toggle[aria-expanded='true'] > svg:last-child {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
.catalogue-filters-heading {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
#catalogue-filter-fields {
|
||||||
|
padding: 0 1.15rem 1.15rem;
|
||||||
|
}
|
||||||
|
.catalogue-filters input:not([type='checkbox']),
|
||||||
|
.catalogue-filters select {
|
||||||
|
min-height: 44px;
|
||||||
|
max-width: 100%;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
.catalogue-filter-group {
|
||||||
|
border-top: 1px solid #e5eaf0;
|
||||||
|
}
|
||||||
|
.catalogue-filter-group > summary {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
min-height: 52px;
|
||||||
|
padding: 0.65rem 0;
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.catalogue-filter-group > summary::-webkit-details-marker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.catalogue-filter-group > summary > svg {
|
||||||
|
margin-left: auto;
|
||||||
|
flex-shrink: 0;
|
||||||
|
transition: transform 0.15s;
|
||||||
|
}
|
||||||
|
.catalogue-filter-group[open] > summary > svg {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
.catalogue-filter-group-content {
|
||||||
|
padding: 0.4rem 0 1rem;
|
||||||
|
display: grid;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.catalogue-count {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 1.5rem;
|
||||||
|
padding: 0.15rem 0.45rem;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: #f0f3f7;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-filters .catalogue-filter-group {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
.catalogue-active-filters:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.catalogue-active-filters button {
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: #f5f7fa;
|
||||||
|
border-color: #dce3eb;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.catalogue-filter-submit > button:first-of-type {
|
||||||
|
gap: 0.5rem;
|
||||||
|
background: var(--catalogue-accent);
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
.catalogue-filter-submit > button:last-child {
|
||||||
|
min-height: 44px;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
border: 0;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.catalogue-results {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.25rem;
|
||||||
|
scroll-margin-top: 2rem;
|
||||||
|
}
|
||||||
|
.catalogue-results-heading {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem 1rem;
|
||||||
|
}
|
||||||
|
.catalogue-results-heading > h2 {
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
.catalogue-results-heading > [role] {
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
.catalogue-results-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.8rem 1.25rem;
|
||||||
|
padding-bottom: 1.1rem;
|
||||||
|
border-bottom: 1px solid #dce3eb;
|
||||||
|
}
|
||||||
|
.catalogue-view-options {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.2rem;
|
||||||
|
padding: 0.25rem;
|
||||||
|
border: 1px solid #dce3eb;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.catalogue-view-button {
|
||||||
|
display: inline-flex;
|
||||||
|
gap: 0.4rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 42px;
|
||||||
|
padding: 0.5rem 0.7rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.catalogue-view-button[aria-pressed='true'] {
|
||||||
|
background: #17324d;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.catalogue-view-button:not(:disabled):hover {
|
||||||
|
color: var(--catalogue-accent);
|
||||||
|
}
|
||||||
|
.catalogue-view-button[aria-pressed='true']:not(:disabled):hover {
|
||||||
|
background: var(--catalogue-accent);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.catalogue-view-button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
.catalogue-utility-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.25rem 1.25rem;
|
||||||
|
}
|
||||||
|
.catalogue-utility-link {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: #526477;
|
||||||
|
}
|
||||||
|
.catalogue-utility-link[aria-disabled='true'] {
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
.catalogue-cards {
|
||||||
|
display: grid;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
border: 1px solid #dce3eb;
|
||||||
|
border-radius: 1rem;
|
||||||
|
background: white;
|
||||||
|
overflow: clip;
|
||||||
|
transition:
|
||||||
|
border-color 0.15s,
|
||||||
|
box-shadow 0.15s;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity:hover,
|
||||||
|
.catalogue-opportunity:focus-within {
|
||||||
|
border-color: #9cabbc;
|
||||||
|
box-shadow: 0 5px 18px #17324d0a;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-body {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: start;
|
||||||
|
gap: 0.85rem;
|
||||||
|
padding: 1.25rem;
|
||||||
|
}
|
||||||
|
.catalogue-sector {
|
||||||
|
padding: 0.25rem 0.6rem;
|
||||||
|
background: #f0f4f8;
|
||||||
|
color: #3d5268;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.catalogue-location {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.4rem;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
.catalogue-location svg {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-top: 0.2rem;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity h2 {
|
||||||
|
font-size: 1.125rem;
|
||||||
|
line-height: 1.45;
|
||||||
|
letter-spacing: -0.015em;
|
||||||
|
color: var(--catalogue-ink);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.catalogue-summary {
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-facts {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.65rem;
|
||||||
|
width: 100%;
|
||||||
|
margin-top: auto;
|
||||||
|
padding-top: 0.5rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
.catalogue-maturity {
|
||||||
|
padding: 0.25rem 0.6rem;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: #f5f6f8;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-actions {
|
||||||
|
padding: 0.45rem 1.25rem 0.75rem;
|
||||||
|
border-top: 1px solid #e5eaf0;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-links {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.25rem 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-detail-link,
|
||||||
|
.catalogue-favourite {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.catalogue-detail-link {
|
||||||
|
color: var(--catalogue-accent);
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.catalogue-favourite {
|
||||||
|
color: #526477;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.catalogue-favourite[aria-pressed='true'] {
|
||||||
|
color: var(--catalogue-accent);
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-choices {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.15rem;
|
||||||
|
padding-top: 0.35rem;
|
||||||
|
border-top: 1px solid #eef1f5;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-choices label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
min-height: 44px;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.catalogue-opportunity-choices input {
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
accent-color: var(--catalogue-accent);
|
||||||
|
}
|
||||||
|
.catalogue-pagination {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-pagination a {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 44px;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: 1px solid #dce3eb;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background: #fff;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
.catalogue-territorial {
|
||||||
|
padding-top: 1.5rem;
|
||||||
|
border-top: 1px solid #dce3eb;
|
||||||
|
}
|
||||||
|
.catalogue-territorial > h2 {
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.catalogue-territorial > p {
|
||||||
|
margin: 0.5rem 0 1.2rem;
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
.catalogue-territorial-links {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-territorial-link {
|
||||||
|
border: 1px solid #e5eaf0;
|
||||||
|
border-radius: 0.65rem;
|
||||||
|
padding: 0.85rem 1rem;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.catalogue-territorial-link > span {
|
||||||
|
color: #526477;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.catalogue-territorial-link h3 {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
/* Headings and emphasized catalogue content use Tempo's red. */
|
||||||
|
.investment-catalogue :is(h1, h2, h3, h4, h5, h6, caption, th, strong),
|
||||||
|
.investment-catalogue :is(p.font-bold, p.font-semibold),
|
||||||
|
.investment-catalogue .catalogue-sector,
|
||||||
|
.investment-catalogue .catalogue-filters-toggle,
|
||||||
|
.investment-catalogue .catalogue-territorial .catalogue-filter-group > summary {
|
||||||
|
color: var(--catalogue-accent);
|
||||||
|
}
|
||||||
|
.investment-catalogue :is(a, button, summary, input, select):focus-visible {
|
||||||
|
outline: 2px solid #17324d;
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
|
.investment-catalogue :is(a, button, summary):hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
text-underline-offset: 3px;
|
||||||
|
}
|
||||||
|
@media (min-width: 640px) {
|
||||||
|
.catalogue-cards-grid,
|
||||||
|
.catalogue-territorial-links {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.catalogue-workspace {
|
||||||
|
grid-template-columns: 290px minmax(0, 1fr);
|
||||||
|
gap: 2rem;
|
||||||
|
}
|
||||||
|
.catalogue-filters-toggle {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.catalogue-filters-heading {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
.catalogue-results-heading {
|
||||||
|
min-height: 48px;
|
||||||
|
}
|
||||||
|
.catalogue-cards-list .catalogue-opportunity {
|
||||||
|
flex-direction: row;
|
||||||
|
}
|
||||||
|
.catalogue-cards-list .catalogue-opportunity-actions {
|
||||||
|
flex: 0 0 235px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
border-top: 0;
|
||||||
|
border-left: 1px solid #e5eaf0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.investment-catalogue * {
|
||||||
|
transition: none;
|
||||||
|
scroll-behavior: auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ChevronDown } from 'lucide-react';
|
||||||
|
import { useState, type ReactNode } from 'react';
|
||||||
|
|
||||||
|
export default function CatalogueFilterGroup({
|
||||||
|
title,
|
||||||
|
expandedTitle,
|
||||||
|
count = 0,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
expandedTitle?: string;
|
||||||
|
count?: number;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<details
|
||||||
|
className="catalogue-filter-group"
|
||||||
|
onToggle={(event) => setOpen(event.currentTarget.open)}
|
||||||
|
>
|
||||||
|
<summary>
|
||||||
|
<span>{open && expandedTitle ? expandedTitle : title}</span>
|
||||||
|
{count > 0 && <span className="catalogue-count">{count}</span>}
|
||||||
|
<ChevronDown size={16} aria-hidden="true" />
|
||||||
|
</summary>
|
||||||
|
<div className="catalogue-filter-group-content">{children}</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,17 +1,19 @@
|
|||||||
import type { HTMLAttributes } from 'react';
|
import type { HTMLAttributes } from 'react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
|
||||||
export default function InputError({
|
export default function InputError({
|
||||||
message,
|
message,
|
||||||
className = '',
|
className = '',
|
||||||
...props
|
...props
|
||||||
}: HTMLAttributes<HTMLParagraphElement> & { message?: string }) {
|
}: HTMLAttributes<HTMLParagraphElement> & { message?: string }) {
|
||||||
|
const { t } = useTempoUi();
|
||||||
return message ? (
|
return message ? (
|
||||||
<p
|
<p
|
||||||
{...props}
|
{...props}
|
||||||
className={cn('text-sm text-red-600 dark:text-red-400', className)}
|
className={cn('text-sm text-red-600 dark:text-red-400', className)}
|
||||||
>
|
>
|
||||||
{message}
|
{t(message)}
|
||||||
</p>
|
</p>
|
||||||
) : null;
|
) : null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,54 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
import { useTempoUi } from '@/components/tempo-brand';
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
import { translateText } from '@/translation/service';
|
||||||
|
import { protectTranslationTokens, restoreTranslationTokens } from '@/translation/utils';
|
||||||
|
|
||||||
// Bridge the original Trans calls to this platform's existing language context.
|
// Only the fixed public institutional texts using this component are sent to Tempo.
|
||||||
export function Trans({ children }: { children: string }) {
|
const cache = new Map<string, string>();
|
||||||
const { t } = useTempoUi();
|
const pending = new Map<string, Promise<string>>();
|
||||||
return <span>{t(children)}</span>;
|
|
||||||
|
function translateInstitutionalText(text: string, language: string): Promise<string> {
|
||||||
|
const key = JSON.stringify([language, text]);
|
||||||
|
const cached = cache.get(key);
|
||||||
|
if (cached) return Promise.resolve(cached);
|
||||||
|
const existing = pending.get(key);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
const protectedText = protectTranslationTokens(text);
|
||||||
|
const request = translateText({
|
||||||
|
text: protectedText.text,
|
||||||
|
sourceLanguage: 'pt',
|
||||||
|
targetLanguage: language,
|
||||||
|
}).then(({ translatedText }) => {
|
||||||
|
// Do not accept a response that lost an identifier, URL or protected term.
|
||||||
|
for (const token of protectedText.replacements.keys()) {
|
||||||
|
if (!translatedText.includes(token)) throw new Error('Translation lost a protected token');
|
||||||
|
}
|
||||||
|
const result = restoreTranslationTokens(translatedText, protectedText.replacements);
|
||||||
|
// Tempo's API returns the input on upstream failure: do not cache it as success.
|
||||||
|
if (result !== text) cache.set(key, result);
|
||||||
|
return result;
|
||||||
|
}).finally(() => pending.delete(key));
|
||||||
|
pending.set(key, request);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Trans({ children }: { children: string }) {
|
||||||
|
const { language, t } = useTempoUi();
|
||||||
|
const localText = t(children);
|
||||||
|
const [result, setResult] = useState<{ key: string; text: string } | null>(null);
|
||||||
|
const key = JSON.stringify([language, children]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (language === 'pt' || localText !== children || !children.trim()) return;
|
||||||
|
let active = true;
|
||||||
|
translateInstitutionalText(children, language).then((text) => {
|
||||||
|
if (active) setResult({ key, text });
|
||||||
|
}).catch(() => {
|
||||||
|
if (active) setResult(null);
|
||||||
|
});
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [children, key, language, localText]);
|
||||||
|
|
||||||
|
return <span data-no-translate>{result?.key === key ? result.text : localText}</span>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
|
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
|
||||||
import type { References } from '@/pages/investment/shared';
|
import type { References } from '@/pages/investment/shared';
|
||||||
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
|
import { TerritoryLevel, type TerritoryOption } from './investment-territory';
|
||||||
|
import CatalogueFilterGroup from './catalogue-filter-group';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { ChevronDown, Search, SlidersHorizontal } from 'lucide-react';
|
||||||
|
|
||||||
export const modalityLabels: Record<string, string> = {
|
export const modalityLabels: Record<string, string> = {
|
||||||
investment_project: 'Projecto de investimento',
|
investment_project: 'Projecto de investimento',
|
||||||
@@ -50,14 +53,19 @@ const labels: Record<string, string> = {
|
|||||||
publication_state: 'Critério herdado',
|
publication_state: 'Critério herdado',
|
||||||
};
|
};
|
||||||
const specialisedEmpty: Record<string, string> = {
|
const specialisedEmpty: Record<string, string> = {
|
||||||
corridor_id: 'Não existem corredores públicos cadastrados para esta localização.',
|
corridor_id:
|
||||||
cluster_id: 'Não existem clusters públicos cadastrados para esta localização.',
|
'Não existem corredores públicos cadastrados para esta localização.',
|
||||||
|
cluster_id:
|
||||||
|
'Não existem clusters públicos cadastrados para esta localização.',
|
||||||
zee_id: 'Não existem ZEE públicas cadastradas para esta localização.',
|
zee_id: 'Não existem ZEE públicas cadastradas para esta localização.',
|
||||||
zfi_id: 'Não existem ZFI públicas cadastradas para esta localização.',
|
zfi_id: 'Não existem ZFI públicas cadastradas para esta localização.',
|
||||||
park_id: 'Não existem parques industriais públicos cadastrados para esta localização.',
|
park_id:
|
||||||
project_id: 'Não existem projectos âncora públicos cadastrados para esta localização.',
|
'Não existem parques industriais públicos cadastrados para esta localização.',
|
||||||
|
project_id:
|
||||||
|
'Não existem projectos âncora públicos cadastrados para esta localização.',
|
||||||
subsector_id: 'Não existem actividades disponíveis no catálogo público.',
|
subsector_id: 'Não existem actividades disponíveis no catálogo público.',
|
||||||
chain_id: 'Não existem cadeias de valor públicas cadastradas para esta localização.',
|
chain_id:
|
||||||
|
'Não existem cadeias de valor públicas cadastradas para esta localização.',
|
||||||
};
|
};
|
||||||
export default function OpportunitySearchFilters({
|
export default function OpportunitySearchFilters({
|
||||||
data,
|
data,
|
||||||
@@ -78,6 +86,10 @@ export default function OpportunitySearchFilters({
|
|||||||
clear: () => void;
|
clear: () => void;
|
||||||
errors: Record<string, string>;
|
errors: Record<string, string>;
|
||||||
}) {
|
}) {
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (Object.keys(errors).length) setExpanded(true);
|
||||||
|
}, [errors]);
|
||||||
const select = (
|
const select = (
|
||||||
key: string,
|
key: string,
|
||||||
choices: { value: string; label: string }[],
|
choices: { value: string; label: string }[],
|
||||||
@@ -87,8 +99,14 @@ export default function OpportunitySearchFilters({
|
|||||||
<select
|
<select
|
||||||
className={input}
|
className={input}
|
||||||
aria-label={labels[key]}
|
aria-label={labels[key]}
|
||||||
aria-describedby={specialisedEmpty[key] ? `filter-help-${key}` : undefined}
|
aria-describedby={
|
||||||
disabled={Boolean(specialisedEmpty[key]) && choices.length === 0 && !data[key]}
|
specialisedEmpty[key] ? `filter-help-${key}` : undefined
|
||||||
|
}
|
||||||
|
disabled={
|
||||||
|
Boolean(specialisedEmpty[key]) &&
|
||||||
|
choices.length === 0 &&
|
||||||
|
!data[key]
|
||||||
|
}
|
||||||
value={String(data[key] ?? '')}
|
value={String(data[key] ?? '')}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
change({
|
change({
|
||||||
@@ -100,9 +118,13 @@ export default function OpportunitySearchFilters({
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<option value="">Todos</option>
|
<option value="">Todos</option>
|
||||||
{data[key] && !choices.some((o) => o.value === String(data[key])) && (
|
{data[key] &&
|
||||||
<option value={String(data[key])}>Selecção indisponível neste contexto — remova o filtro</option>
|
!choices.some((o) => o.value === String(data[key])) && (
|
||||||
)}
|
<option value={String(data[key])}>
|
||||||
|
Selecção indisponível neste contexto — remova o
|
||||||
|
filtro
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
{choices.map((o) => (
|
{choices.map((o) => (
|
||||||
<option key={o.value} value={o.value}>
|
<option key={o.value} value={o.value}>
|
||||||
{o.label}
|
{o.label}
|
||||||
@@ -114,7 +136,9 @@ export default function OpportunitySearchFilters({
|
|||||||
{choices.length === 0
|
{choices.length === 0
|
||||||
? specialisedEmpty[key]
|
? specialisedEmpty[key]
|
||||||
: `${choices.length} opções públicas disponíveis, mesmo sem oportunidades associadas.`}
|
: `${choices.length} opções públicas disponíveis, mesmo sem oportunidades associadas.`}
|
||||||
{key === 'subsector_id' && choices.length > 0 && ' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
|
{key === 'subsector_id' &&
|
||||||
|
choices.length > 0 &&
|
||||||
|
' Classificação de actividades; não confirma a existência de investimentos nesta localização.'}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{hint && <p className="text-sm text-slate-600">{hint}</p>}
|
{hint && <p className="text-sm text-slate-600">{hint}</p>}
|
||||||
@@ -200,311 +224,399 @@ export default function OpportunitySearchFilters({
|
|||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
<form
|
<form
|
||||||
className="space-y-5 rounded-xl border bg-white p-4 sm:p-6"
|
className="catalogue-filters"
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
submit();
|
submit();
|
||||||
}}
|
}}
|
||||||
aria-label="Pesquisar oportunidades"
|
aria-label="Pesquisar oportunidades"
|
||||||
>
|
>
|
||||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
<button
|
||||||
<Field label="O que procura">
|
type="button"
|
||||||
<input
|
className="catalogue-filters-toggle"
|
||||||
className={input}
|
aria-expanded={expanded}
|
||||||
value={String(data.q)}
|
aria-controls="catalogue-filter-fields"
|
||||||
placeholder="Palavras do título ou da descrição"
|
onClick={() => setExpanded((value) => !value)}
|
||||||
onChange={(e) => change({ q: e.target.value })}
|
>
|
||||||
/>
|
<SlidersHorizontal size={18} aria-hidden="true" />
|
||||||
</Field>
|
<span>Filtros</span>
|
||||||
{select('perspective', [{value:'exists',label:'O que existe'},{value:'needs',label:'Necessidades identificadas'},{value:'ideas',label:'Ideias de investimento'},{value:'opportunities',label:'Oportunidades cadastradas — disponibilidade na ficha'}])}
|
{active.length + path.length > 0 && (
|
||||||
{select('sector', choicesFor('sector'))}
|
<span className="catalogue-count">
|
||||||
{select('category', choicesFor('category'))}
|
{active.length + path.length}
|
||||||
</div>
|
</span>
|
||||||
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
|
||||||
<legend className="mb-2 font-semibold">Localização</legend>
|
|
||||||
<p className="text-sm sm:col-span-2 lg:col-span-4">
|
|
||||||
A província inclui as oportunidades dos seus distritos, postos administrativos e localidades.
|
|
||||||
Não é necessário escolher todos os níveis. O contexto provincial de um corredor é identificado nos resultados; não confirma uma implantação distrital.
|
|
||||||
{path.length > 1 && <button type="button" className="ml-2 underline" onClick={() => territory(path.slice(0, 1))}>Ver toda a província de {path[0].name}</button>}
|
|
||||||
</p>
|
|
||||||
{(
|
|
||||||
[
|
|
||||||
'province_id',
|
|
||||||
'district_id',
|
|
||||||
'admin_post_id',
|
|
||||||
'locality_id',
|
|
||||||
] as const
|
|
||||||
).map((key, index) => (
|
|
||||||
<TerritoryLevel
|
|
||||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
|
||||||
index={index}
|
|
||||||
parent={path[index - 1]?.id ?? ''}
|
|
||||||
selected={path[index]}
|
|
||||||
endpoint="/api/v1/investment/territory-options"
|
|
||||||
onChange={(value) =>
|
|
||||||
territory([
|
|
||||||
...path.slice(0, index),
|
|
||||||
...(value ? [value] : []),
|
|
||||||
])
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</fieldset>
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
|
||||||
<Field label="Estado de preparação">
|
|
||||||
<select
|
|
||||||
className={input}
|
|
||||||
value={String(data.preparation ?? '')}
|
|
||||||
onChange={(e) =>
|
|
||||||
change({
|
|
||||||
preparation: e.target.value,
|
|
||||||
maturity_level: '',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<option value="">Todos os estados</option>
|
|
||||||
{[
|
|
||||||
'Etapas de preparação',
|
|
||||||
'Classificações históricas',
|
|
||||||
].map((group) => (
|
|
||||||
<optgroup key={group} label={group}>
|
|
||||||
{(references.preparationOptions ?? [])
|
|
||||||
.filter((o) => o.group === group)
|
|
||||||
.map((o) => (
|
|
||||||
<option key={o.value} value={o.value}>
|
|
||||||
{o.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</optgroup>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<p className="text-sm text-slate-600">
|
|
||||||
Os registos históricos são apresentados separadamente e
|
|
||||||
conservam a classificação indicada na ficha.
|
|
||||||
</p>
|
|
||||||
</Field>
|
|
||||||
{(['min_amount', 'max_amount'] as const).map((key) => (
|
|
||||||
<Field key={key} label={labels[key]}>
|
|
||||||
<input
|
|
||||||
className={input}
|
|
||||||
type="number"
|
|
||||||
min="0"
|
|
||||||
step="0.01"
|
|
||||||
value={String(data[key])}
|
|
||||||
onChange={(e) => change({ [key]: e.target.value })}
|
|
||||||
/>
|
|
||||||
</Field>
|
|
||||||
))}
|
|
||||||
{select(
|
|
||||||
'currency',
|
|
||||||
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
|
|
||||||
value: c,
|
|
||||||
label: c,
|
|
||||||
})),
|
|
||||||
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
|
|
||||||
)}
|
)}
|
||||||
</div>
|
<ChevronDown size={18} aria-hidden="true" />
|
||||||
<details>
|
</button>
|
||||||
<summary className="cursor-pointer rounded border p-3 font-semibold focus-visible:outline-2">
|
<h2 className="catalogue-filters-heading">
|
||||||
Mais filtros
|
<SlidersHorizontal size={17} aria-hidden="true" />
|
||||||
</summary>
|
Filtros
|
||||||
<div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
</h2>
|
||||||
{[
|
<div
|
||||||
'corridor_id',
|
id="catalogue-filter-fields"
|
||||||
'cluster_id',
|
className={`${expanded ? 'block' : 'hidden'} space-y-5 lg:block`}
|
||||||
'zee_id',
|
>
|
||||||
'zfi_id',
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
|
||||||
'park_id',
|
<Field label="O que procura">
|
||||||
'project_id',
|
|
||||||
'subsector_id',
|
|
||||||
'chain_id',
|
|
||||||
].map((key) => select(key, choicesFor(key)))}
|
|
||||||
<Field label="Data-alvo até">
|
|
||||||
<input
|
<input
|
||||||
className={input}
|
className={input}
|
||||||
type="date"
|
value={String(data.q)}
|
||||||
value={String(data.before)}
|
placeholder="Palavras do título ou da descrição"
|
||||||
onChange={(e) => change({ before: e.target.value })}
|
onChange={(e) => change({ q: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
|
{select('perspective', [
|
||||||
|
{ value: 'exists', label: 'O que existe' },
|
||||||
|
{ value: 'needs', label: 'Necessidades identificadas' },
|
||||||
|
{ value: 'ideas', label: 'Ideias de investimento' },
|
||||||
|
{
|
||||||
|
value: 'opportunities',
|
||||||
|
label: 'Oportunidades cadastradas — disponibilidade na ficha',
|
||||||
|
},
|
||||||
|
])}
|
||||||
|
{select('sector', choicesFor('sector'))}
|
||||||
|
{select('category', choicesFor('category'))}
|
||||||
</div>
|
</div>
|
||||||
<p className="my-3 text-sm">
|
<CatalogueFilterGroup title="Localização" count={path.length}>
|
||||||
Estes filtros procuram associações documentadas. Estar perto
|
<p className="text-sm leading-relaxed text-slate-600">
|
||||||
de um parque ou no mesmo distrito não constitui associação,
|
A província inclui as oportunidades dos seus distritos,
|
||||||
nem confirma incentivos ou disponibilidade.
|
postos administrativos e localidades. Não é necessário
|
||||||
</p>
|
escolher todos os níveis. O contexto provincial de um
|
||||||
<label className="flex gap-2">
|
corredor é identificado nos resultados; não confirma uma
|
||||||
<input
|
implantação distrital.
|
||||||
type="checkbox"
|
{path.length > 1 && (
|
||||||
checked={Boolean(data.include_national)}
|
<button type="button" className="ml-2 underline" onClick={() => territory(path.slice(0, 1))}>
|
||||||
onChange={(e) =>
|
Ver toda a província de {path[0].name}
|
||||||
change({ include_national: e.target.checked })
|
</button>
|
||||||
}
|
)}
|
||||||
/>
|
</p>
|
||||||
Incluir oportunidades de âmbito nacional
|
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
|
||||||
</label>
|
<legend className="sr-only">Localização</legend>
|
||||||
<details className="mt-3">
|
{(
|
||||||
<summary className="cursor-pointer font-medium">
|
[
|
||||||
Outras características
|
'province_id',
|
||||||
</summary>
|
'district_id',
|
||||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
'admin_post_id',
|
||||||
|
'locality_id',
|
||||||
|
] as const
|
||||||
|
).map((key, index) => (
|
||||||
|
<TerritoryLevel
|
||||||
|
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||||
|
index={index}
|
||||||
|
parent={path[index - 1]?.id ?? ''}
|
||||||
|
selected={path[index]}
|
||||||
|
endpoint="/api/v1/investment/territory-options"
|
||||||
|
onChange={(value) =>
|
||||||
|
territory([
|
||||||
|
...path.slice(0, index),
|
||||||
|
...(value ? [value] : []),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
</CatalogueFilterGroup>
|
||||||
|
<CatalogueFilterGroup
|
||||||
|
title="Preparação e investimento"
|
||||||
|
count={
|
||||||
|
[
|
||||||
|
'preparation',
|
||||||
|
'min_amount',
|
||||||
|
'max_amount',
|
||||||
|
'currency',
|
||||||
|
].filter((key) => data[key]).length
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
|
||||||
|
<Field label="Estado de preparação">
|
||||||
|
<select
|
||||||
|
className={input}
|
||||||
|
value={String(data.preparation ?? '')}
|
||||||
|
onChange={(e) =>
|
||||||
|
change({
|
||||||
|
preparation: e.target.value,
|
||||||
|
maturity_level: '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">Todos os estados</option>
|
||||||
|
{[
|
||||||
|
'Etapas de preparação',
|
||||||
|
'Classificações históricas',
|
||||||
|
].map((group) => (
|
||||||
|
<optgroup key={group} label={group}>
|
||||||
|
{(references.preparationOptions ?? [])
|
||||||
|
.filter((o) => o.group === group)
|
||||||
|
.map((o) => (
|
||||||
|
<option
|
||||||
|
key={o.value}
|
||||||
|
value={o.value}
|
||||||
|
>
|
||||||
|
{o.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</optgroup>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="text-sm text-slate-600">
|
||||||
|
Os registos históricos são apresentados
|
||||||
|
separadamente e conservam a classificação
|
||||||
|
indicada na ficha.
|
||||||
|
</p>
|
||||||
|
</Field>
|
||||||
|
{(['min_amount', 'max_amount'] as const).map((key) => (
|
||||||
|
<Field key={key} label={labels[key]}>
|
||||||
|
<input
|
||||||
|
className={input}
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
value={String(data[key])}
|
||||||
|
onChange={(e) =>
|
||||||
|
change({ [key]: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
))}
|
||||||
|
{select(
|
||||||
|
'currency',
|
||||||
|
['MZN', 'USD', 'EUR', 'ZAR'].map((c) => ({
|
||||||
|
value: c,
|
||||||
|
label: c,
|
||||||
|
})),
|
||||||
|
'Seleccione uma moeda para comparar montantes. Não se efectuam conversões cambiais.',
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CatalogueFilterGroup>
|
||||||
|
<CatalogueFilterGroup
|
||||||
|
title="Mais filtros"
|
||||||
|
expandedTitle="Menos filtros"
|
||||||
|
count={
|
||||||
|
active.filter(([key]) =>
|
||||||
|
[
|
||||||
|
'corridor_id',
|
||||||
|
'cluster_id',
|
||||||
|
'zee_id',
|
||||||
|
'zfi_id',
|
||||||
|
'park_id',
|
||||||
|
'project_id',
|
||||||
|
'subsector_id',
|
||||||
|
'chain_id',
|
||||||
|
'before',
|
||||||
|
'include_national',
|
||||||
|
'facets',
|
||||||
|
].includes(key),
|
||||||
|
).length
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
|
||||||
{[
|
{[
|
||||||
'education',
|
'corridor_id',
|
||||||
'infrastructure',
|
'cluster_id',
|
||||||
'labour',
|
'zee_id',
|
||||||
'qualification',
|
'zfi_id',
|
||||||
'support',
|
'park_id',
|
||||||
'impact',
|
'project_id',
|
||||||
'partnership',
|
'subsector_id',
|
||||||
]
|
'chain_id',
|
||||||
.filter((group) =>
|
].map((key) => select(key, choicesFor(key)))}
|
||||||
references.options.some(
|
<Field label="Data-alvo até">
|
||||||
(o) => o.group === group,
|
<input
|
||||||
),
|
className={input}
|
||||||
)
|
type="date"
|
||||||
.map((group) => (
|
value={String(data.before)}
|
||||||
<fieldset
|
onChange={(e) =>
|
||||||
key={group}
|
change({ before: e.target.value })
|
||||||
className="rounded border p-3"
|
}
|
||||||
>
|
/>
|
||||||
<legend>{groupLabels[group]}</legend>
|
</Field>
|
||||||
{references.options
|
</div>
|
||||||
.filter((o) => o.group === group)
|
<p className="my-3 text-sm">
|
||||||
.map((option) => (
|
Estes filtros procuram associações documentadas. Estar
|
||||||
<label
|
perto de um parque ou no mesmo distrito não constitui
|
||||||
key={option.id}
|
associação, nem confirma incentivos ou disponibilidade.
|
||||||
className="flex gap-2 py-1"
|
</p>
|
||||||
>
|
<label className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
checked={
|
checked={Boolean(data.include_national)}
|
||||||
Array.isArray(
|
onChange={(e) =>
|
||||||
data.facets,
|
change({ include_national: e.target.checked })
|
||||||
) &&
|
}
|
||||||
data.facets.includes(
|
/>
|
||||||
option.id,
|
Incluir oportunidades de âmbito nacional
|
||||||
)
|
</label>
|
||||||
}
|
<details className="mt-3">
|
||||||
onChange={(e) => {
|
<summary className="cursor-pointer font-medium">
|
||||||
const selected =
|
Outras características
|
||||||
|
</summary>
|
||||||
|
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
|
||||||
|
{[
|
||||||
|
'education',
|
||||||
|
'infrastructure',
|
||||||
|
'labour',
|
||||||
|
'qualification',
|
||||||
|
'support',
|
||||||
|
'impact',
|
||||||
|
'partnership',
|
||||||
|
]
|
||||||
|
.filter((group) =>
|
||||||
|
references.options.some(
|
||||||
|
(o) => o.group === group,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.map((group) => (
|
||||||
|
<fieldset
|
||||||
|
key={group}
|
||||||
|
className="rounded border p-3"
|
||||||
|
>
|
||||||
|
<legend>{groupLabels[group]}</legend>
|
||||||
|
{references.options
|
||||||
|
.filter((o) => o.group === group)
|
||||||
|
.map((option) => (
|
||||||
|
<label
|
||||||
|
key={option.id}
|
||||||
|
className="flex gap-2 py-1"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={
|
||||||
Array.isArray(
|
Array.isArray(
|
||||||
data.facets,
|
data.facets,
|
||||||
|
) &&
|
||||||
|
data.facets.includes(
|
||||||
|
option.id,
|
||||||
)
|
)
|
||||||
? data.facets
|
}
|
||||||
: [];
|
onChange={(e) => {
|
||||||
change({
|
const selected =
|
||||||
facets: e.target
|
Array.isArray(
|
||||||
.checked
|
data.facets,
|
||||||
? [
|
)
|
||||||
...selected,
|
? data.facets
|
||||||
option.id,
|
: [];
|
||||||
]
|
change({
|
||||||
: selected.filter(
|
facets: e.target
|
||||||
(id) =>
|
.checked
|
||||||
id !==
|
? [
|
||||||
|
...selected,
|
||||||
option.id,
|
option.id,
|
||||||
),
|
]
|
||||||
});
|
: selected.filter(
|
||||||
}}
|
(
|
||||||
/>
|
id,
|
||||||
{option.label}
|
) =>
|
||||||
</label>
|
id !==
|
||||||
))}
|
option.id,
|
||||||
</fieldset>
|
),
|
||||||
))}
|
});
|
||||||
</div>
|
}}
|
||||||
</details>
|
/>
|
||||||
</details>
|
{option.label}
|
||||||
<section
|
</label>
|
||||||
aria-label="Filtros activos"
|
))}
|
||||||
className="flex flex-wrap gap-2"
|
</fieldset>
|
||||||
>
|
))}
|
||||||
{path.map((node, index) => (
|
</div>
|
||||||
<button
|
</details>
|
||||||
className="rounded border px-3 py-2"
|
</CatalogueFilterGroup>
|
||||||
type="button"
|
<section
|
||||||
key={node.id}
|
aria-label="Filtros activos"
|
||||||
aria-label={`Remover localização ${node.name}`}
|
className="catalogue-active-filters flex flex-wrap gap-2"
|
||||||
onClick={() => territory(path.slice(0, index))}
|
|
||||||
>
|
|
||||||
{node.name} ×
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
{active.flatMap(([key, value]) =>
|
|
||||||
key === 'facets' && Array.isArray(value)
|
|
||||||
? value.map((id) => (
|
|
||||||
<button
|
|
||||||
key={`facet-${id}`}
|
|
||||||
type="button"
|
|
||||||
className="rounded border px-3 py-2"
|
|
||||||
onClick={() =>
|
|
||||||
change({
|
|
||||||
facets: value.filter((x) => x !== id),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{' '}
|
|
||||||
{references.options.find((o) => o.id === id)
|
|
||||||
?.label ?? 'Critério adicional'}{' '}
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
))
|
|
||||||
: [
|
|
||||||
<button
|
|
||||||
key={key}
|
|
||||||
type="button"
|
|
||||||
className="rounded border px-3 py-2 text-left"
|
|
||||||
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
|
|
||||||
onClick={() => remove(key)}
|
|
||||||
>
|
|
||||||
{labels[key] ?? 'Critério adicional'}:{' '}
|
|
||||||
{typeof value === 'boolean'
|
|
||||||
? 'Sim'
|
|
||||||
: (choicesFor(key).find(
|
|
||||||
(o) => o.value === String(value),
|
|
||||||
)?.label ??
|
|
||||||
([
|
|
||||||
'q',
|
|
||||||
'min_amount',
|
|
||||||
'max_amount',
|
|
||||||
'currency',
|
|
||||||
'before',
|
|
||||||
'province',
|
|
||||||
'district',
|
|
||||||
].includes(key)
|
|
||||||
? String(value)
|
|
||||||
: 'seleccionado'))}{' '}
|
|
||||||
×
|
|
||||||
</button>,
|
|
||||||
],
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
{Object.entries(errors).map(([key, value]) => (
|
|
||||||
<p key={key} role="alert">
|
|
||||||
{value}
|
|
||||||
</p>
|
|
||||||
))}
|
|
||||||
<div className="flex flex-wrap items-end gap-4">
|
|
||||||
{select('sort', [
|
|
||||||
{ value: 'recent', label: 'Mais recentes' },
|
|
||||||
{ value: 'title', label: 'Título' },
|
|
||||||
{
|
|
||||||
value: 'amount_asc',
|
|
||||||
label: 'Montante crescente, por moeda',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: 'amount_desc',
|
|
||||||
label: 'Montante decrescente, por moeda',
|
|
||||||
},
|
|
||||||
])}
|
|
||||||
<button className={button}>Pesquisar</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="rounded border px-4 py-2 underline"
|
|
||||||
onClick={clear}
|
|
||||||
>
|
>
|
||||||
Limpar filtros
|
{path.map((node, index) => (
|
||||||
</button>
|
<button
|
||||||
|
className="rounded border px-3 py-2"
|
||||||
|
type="button"
|
||||||
|
key={node.id}
|
||||||
|
aria-label={`Remover localização ${node.name}`}
|
||||||
|
onClick={() => territory(path.slice(0, index))}
|
||||||
|
>
|
||||||
|
{node.name} ×
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{active.flatMap(([key, value]) =>
|
||||||
|
key === 'facets' && Array.isArray(value)
|
||||||
|
? value.map((id) => (
|
||||||
|
<button
|
||||||
|
key={`facet-${id}`}
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-3 py-2"
|
||||||
|
onClick={() =>
|
||||||
|
change({
|
||||||
|
facets: value.filter(
|
||||||
|
(x) => x !== id,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{' '}
|
||||||
|
{references.options.find(
|
||||||
|
(o) => o.id === id,
|
||||||
|
)?.label ?? 'Critério adicional'}{' '}
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
: [
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-3 py-2 text-left"
|
||||||
|
aria-label={`Remover ${labels[key] ?? 'critério adicional'}`}
|
||||||
|
onClick={() => remove(key)}
|
||||||
|
>
|
||||||
|
{labels[key] ?? 'Critério adicional'}:{' '}
|
||||||
|
{typeof value === 'boolean'
|
||||||
|
? 'Sim'
|
||||||
|
: (choicesFor(key).find(
|
||||||
|
(o) =>
|
||||||
|
o.value === String(value),
|
||||||
|
)?.label ??
|
||||||
|
([
|
||||||
|
'q',
|
||||||
|
'min_amount',
|
||||||
|
'max_amount',
|
||||||
|
'currency',
|
||||||
|
'before',
|
||||||
|
'province',
|
||||||
|
'district',
|
||||||
|
].includes(key)
|
||||||
|
? String(value)
|
||||||
|
: 'seleccionado'))}{' '}
|
||||||
|
×
|
||||||
|
</button>,
|
||||||
|
],
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
{Object.entries(errors).map(([key, value]) => (
|
||||||
|
<p key={key} role="alert">
|
||||||
|
{value}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
<div className="catalogue-filter-submit grid gap-3">
|
||||||
|
{select('sort', [
|
||||||
|
{ value: 'recent', label: 'Mais recentes' },
|
||||||
|
{ value: 'title', label: 'Título' },
|
||||||
|
{
|
||||||
|
value: 'amount_asc',
|
||||||
|
label: 'Montante crescente, por moeda',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: 'amount_desc',
|
||||||
|
label: 'Montante decrescente, por moeda',
|
||||||
|
},
|
||||||
|
])}
|
||||||
|
<button className={button}>
|
||||||
|
<Search size={16} aria-hidden="true" />
|
||||||
|
Pesquisar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-4 py-2 underline"
|
||||||
|
onClick={clear}
|
||||||
|
>
|
||||||
|
Limpar filtros
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { ComponentProps, Ref } from 'react';
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
|
||||||
export default function PasswordInput({
|
export default function PasswordInput({
|
||||||
className,
|
className,
|
||||||
@@ -10,6 +11,7 @@ export default function PasswordInput({
|
|||||||
...props
|
...props
|
||||||
}: Omit<ComponentProps<'input'>, 'type'> & { ref?: Ref<HTMLInputElement> }) {
|
}: Omit<ComponentProps<'input'>, 'type'> & { ref?: Ref<HTMLInputElement> }) {
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
const { t } = useTempoUi();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
@@ -23,7 +25,7 @@ export default function PasswordInput({
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => setShowPassword((prev) => !prev)}
|
onClick={() => setShowPassword((prev) => !prev)}
|
||||||
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute inset-y-0 right-0 flex items-center rounded-r-md px-3 focus-visible:ring-[3px] focus-visible:outline-none"
|
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute inset-y-0 right-0 flex items-center rounded-r-md px-3 focus-visible:ring-[3px] focus-visible:outline-none"
|
||||||
aria-label={showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe'}
|
aria-label={t(showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe')}
|
||||||
tabIndex={-1}
|
tabIndex={-1}
|
||||||
>
|
>
|
||||||
{showPassword ? (
|
{showPassword ? (
|
||||||
|
|||||||
@@ -231,14 +231,14 @@ export default function PortalHero({
|
|||||||
<form
|
<form
|
||||||
onSubmit={onSearch}
|
onSubmit={onSearch}
|
||||||
role="search"
|
role="search"
|
||||||
aria-label="Pesquisar oportunidades"
|
aria-label="Pesquisar no InvesteMoz"
|
||||||
className="mt-7 w-full max-w-4xl"
|
className="mt-7 w-full max-w-4xl"
|
||||||
>
|
>
|
||||||
<label
|
<label
|
||||||
htmlFor="portal-opportunity-search"
|
htmlFor="portal-opportunity-search"
|
||||||
className="mb-2 block text-left text-sm font-medium text-white/90"
|
className="mb-2 block text-left text-sm font-medium text-white/90"
|
||||||
>
|
>
|
||||||
Pesquisa rápida de oportunidades
|
Pesquisa rápida no InvesteMoz
|
||||||
</label>
|
</label>
|
||||||
<div className="flex min-w-0 flex-col gap-2 rounded-2xl border border-white/30 bg-white p-1.5 shadow-2xl shadow-black/20 focus-within:ring-2 focus-within:ring-white focus-within:ring-offset-4 focus-within:ring-offset-[#101820] min-[400px]:flex-row">
|
<div className="flex min-w-0 flex-col gap-2 rounded-2xl border border-white/30 bg-white p-1.5 shadow-2xl shadow-black/20 focus-within:ring-2 focus-within:ring-white focus-within:ring-offset-4 focus-within:ring-offset-[#101820] min-[400px]:flex-row">
|
||||||
<input
|
<input
|
||||||
@@ -247,7 +247,7 @@ export default function PortalHero({
|
|||||||
name="q"
|
name="q"
|
||||||
value={query}
|
value={query}
|
||||||
onChange={(event) => setQuery(event.target.value)}
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
placeholder="Ex.: agronegócio, Nampula, energia..."
|
placeholder="Ex.: agronegócio, Nampula, legislação..."
|
||||||
className="h-12 w-full min-w-0 flex-1 rounded-xl border-0 bg-white px-4 text-base text-slate-900 outline-none placeholder:text-slate-500"
|
className="h-12 w-full min-w-0 flex-1 rounded-xl border-0 bg-white px-4 text-base text-slate-900 outline-none placeholder:text-slate-500"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { createContext, useContext } from 'react';
|
||||||
|
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
||||||
|
|
||||||
|
export const MenuPlacement = createContext(false);
|
||||||
|
|
||||||
|
export function PortalMenu({ primary = false }: { primary?: boolean }) {
|
||||||
|
const placed = useContext(MenuPlacement);
|
||||||
|
return placed && !primary ? null : <PortalGroupedMenu />;
|
||||||
|
}
|
||||||
@@ -241,6 +241,48 @@ const translations: Record<string, Record<string, string>> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sharedTranslations: Record<string, [string, string, string]> = {
|
||||||
|
'Criar conta': ['Create account', 'Créer un compte', 'Crear cuenta'],
|
||||||
|
'Entrar na sua conta': ['Sign in to your account', 'Connectez-vous à votre compte', 'Inicie sesión en su cuenta'],
|
||||||
|
'Crie uma conta simples para continuar e acompanhar a sua operação. Não é necessário configurar MFA para participar.': ['Create an account to continue and follow your operation. You do not need to set up MFA to participate.', 'Créez un compte pour poursuivre et suivre votre opération. La configuration de l’authentification multifacteur n’est pas nécessaire pour participer.', 'Cree una cuenta para continuar y seguir su operación. No necesita configurar la autenticación multifactor para participar.'],
|
||||||
|
'Entre para continuar a operação que escolheu. Os dados preenchidos permanecem guardados neste navegador.': ['Sign in to continue the operation you chose. Your entered data remains saved in this browser.', 'Connectez-vous pour poursuivre l’opération choisie. Les données saisies restent enregistrées dans ce navigateur.', 'Inicie sesión para continuar la operación elegida. Los datos introducidos permanecen guardados en este navegador.'],
|
||||||
|
'Palavra-passe': ['Password', 'Mot de passe', 'Contraseña'],
|
||||||
|
'Mostrar palavra-passe': ['Show password', 'Afficher le mot de passe', 'Mostrar contraseña'],
|
||||||
|
'Ocultar palavra-passe': ['Hide password', 'Masquer le mot de passe', 'Ocultar contraseña'],
|
||||||
|
'Confirmar palavra-passe': ['Confirm password', 'Confirmer le mot de passe', 'Confirmar contraseña'],
|
||||||
|
'Nome': ['Name', 'Nom', 'Nombre'],
|
||||||
|
'Nome completo': ['Full name', 'Nom complet', 'Nombre completo'],
|
||||||
|
'Esqueceu a palavra-passe?': ['Forgot your password?', 'Mot de passe oublié ?', '¿Olvidó su contraseña?'],
|
||||||
|
'Manter sessão iniciada': ['Keep me signed in', 'Rester connecté', 'Mantener la sesión iniciada'],
|
||||||
|
'Ainda não tem conta?': ['Don’t have an account?', 'Vous n’avez pas de compte ?', '¿Aún no tiene cuenta?'],
|
||||||
|
'Já tem conta?': ['Already have an account?', 'Vous avez déjà un compte ?', '¿Ya tiene cuenta?'],
|
||||||
|
'Entrar com chave de acesso': ['Sign in with a passkey', 'Se connecter avec une clé d’accès', 'Iniciar sesión con clave de acceso'],
|
||||||
|
'A autenticar…': ['Signing in…', 'Connexion en cours…', 'Iniciando sesión…'],
|
||||||
|
'Ou continuar com email': ['Or continue with email', 'Ou continuer avec l’e-mail', 'O continuar con correo electrónico'],
|
||||||
|
'O email ou a palavra-passe não correspondem aos nossos registos.': ['The email or password does not match our records.', 'L’adresse e-mail ou le mot de passe ne correspond pas à nos informations.', 'El correo electrónico o la contraseña no coinciden con nuestros registros.'],
|
||||||
|
'A palavra-passe está incorrecta.': ['The password is incorrect.', 'Le mot de passe est incorrect.', 'La contraseña es incorrecta.'],
|
||||||
|
'Atalho para o conteúdo': ['Skip link', 'Lien d’accès rapide', 'Enlace de acceso rápido'],
|
||||||
|
'Saltar para o conteúdo': ['Skip to content', 'Aller au contenu', 'Ir al contenido'],
|
||||||
|
'Caminho de navegação': ['Breadcrumb', 'Fil d’Ariane', 'Ruta de navegación'],
|
||||||
|
'Contacto de apoio ao investidor': ['Investor support contact', 'Contact de l’assistance aux investisseurs', 'Contacto de apoyo al inversor'],
|
||||||
|
'Contactar Apoio ao Investidor': ['Contact investor support', 'Contacter l’assistance aux investisseurs', 'Contactar con apoyo al inversor'],
|
||||||
|
'Ambiente de homologação': ['Review environment', 'Environnement de validation', 'Entorno de validación'],
|
||||||
|
'Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.': ['This review environment is reserved for Tempo. Browse public content; sign in when starting an operation.', 'Cet environnement de validation est réservé à Tempo. Consultez le contenu public ; connectez-vous pour commencer une opération.', 'Este entorno de validación está reservado para Tempo. Consulte el contenido público; inicie sesión al comenzar una operación.'],
|
||||||
|
'Idioma da navegação': ['Navigation language', 'Langue de navigation', 'Idioma de navegación'],
|
||||||
|
'Navegação institucional': ['Language', 'Langue', 'Idioma'],
|
||||||
|
'Valores': ['Values', 'Valeurs', 'Valores'],
|
||||||
|
'Ver menos': ['Show less', 'Voir moins', 'Ver menos'],
|
||||||
|
'Ver mais': ['Show more', 'Voir plus', 'Ver más'],
|
||||||
|
'Voltar': ['Back', 'Retour', 'Volver'],
|
||||||
|
'Anos de Experiência': ['Years of experience', 'Années d’expérience', 'Años de experiencia'],
|
||||||
|
'Projetos Realizados': ['Projects completed', 'Projets réalisés', 'Proyectos realizados'],
|
||||||
|
};
|
||||||
|
for (const [source, values] of Object.entries(sharedTranslations)) {
|
||||||
|
(['en', 'fr', 'es'] as const).forEach((locale, index) => {
|
||||||
|
translations[locale][source] = values[index];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const TempoUi = createContext({
|
const TempoUi = createContext({
|
||||||
language: 'pt',
|
language: 'pt',
|
||||||
setLanguage: (_language: string) => {},
|
setLanguage: (_language: string) => {},
|
||||||
@@ -255,13 +297,17 @@ export function TempoUiProvider({ children }: { children: ReactNode }) {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
try {
|
||||||
const saved = localStorage.getItem('tempo-navigation-language');
|
const saved = localStorage.getItem('tempo-navigation-language');
|
||||||
if (saved && ['pt', 'en', 'fr', 'es'].includes(saved))
|
if (saved && /^[a-zA-Z][a-zA-Z0-9-]{0,19}$/.test(saved))
|
||||||
setCurrentLanguage(saved);
|
setCurrentLanguage(saved);
|
||||||
} catch {
|
} catch {
|
||||||
/* Navigation remains usable without browser storage. */
|
/* Navigation remains usable without browser storage. */
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.lang = language;
|
||||||
|
}, [language]);
|
||||||
const setLanguage = (next: string) => {
|
const setLanguage = (next: string) => {
|
||||||
|
if (!/^[a-zA-Z][a-zA-Z0-9-]{0,19}$/.test(next)) return;
|
||||||
setCurrentLanguage(next);
|
setCurrentLanguage(next);
|
||||||
try {
|
try {
|
||||||
localStorage.setItem('tempo-navigation-language', next);
|
localStorage.setItem('tempo-navigation-language', next);
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { useTempoUi } from '@/components/tempo-brand';
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
import { getLanguages } from '@/translation/service';
|
||||||
|
import { withPortugueseFirst } from '@/translation/utils';
|
||||||
|
import type { TranslationLanguage } from '@/translation/types';
|
||||||
|
|
||||||
type Weather = { temp: number; description: string; humidity?: number };
|
type Weather = { temp: number; description: string; humidity?: number };
|
||||||
|
|
||||||
@@ -97,12 +100,28 @@ export function TempoWeather() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function TempoLanguageSelector() {
|
export function TempoLanguageSelector() {
|
||||||
const { language, setLanguage } = useTempoUi();
|
const { language, setLanguage, t } = useTempoUi();
|
||||||
|
const [languages, setLanguages] = useState<TranslationLanguage[]>([
|
||||||
|
{ code: 'pt', name: 'Português' },
|
||||||
|
{ code: 'en', name: 'English' },
|
||||||
|
{ code: 'fr', name: 'Français' },
|
||||||
|
{ code: 'es', name: 'Español' },
|
||||||
|
]);
|
||||||
|
const [available, setAvailable] = useState(true);
|
||||||
|
useEffect(() => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
getLanguages(controller.signal).then((items) => {
|
||||||
|
const portuguese = items.find((item) => item.code === 'pt');
|
||||||
|
if (!portuguese) throw new Error('Portuguese model unavailable');
|
||||||
|
setLanguages(withPortugueseFirst(items.filter((item) => item.code === 'pt' || !portuguese.targets || portuguese.targets.includes(item.code))));
|
||||||
|
}).catch(() => { if (!controller.signal.aborted) setAvailable(false); });
|
||||||
|
return () => controller.abort();
|
||||||
|
}, []);
|
||||||
return (
|
return (
|
||||||
<DropdownMenu modal={false}>
|
<DropdownMenu modal={false}>
|
||||||
<DropdownMenuTrigger
|
<DropdownMenuTrigger
|
||||||
className="tempo-utility-button"
|
className="tempo-utility-button"
|
||||||
aria-label="Idioma da navegação"
|
aria-label={t('Idioma da navegação')}
|
||||||
>
|
>
|
||||||
<Globe size={16} aria-hidden="true" />
|
<Globe size={16} aria-hidden="true" />
|
||||||
<span className="text-xs font-semibold uppercase">
|
<span className="text-xs font-semibold uppercase">
|
||||||
@@ -116,14 +135,10 @@ export function TempoLanguageSelector() {
|
|||||||
className="tempo-dropdown min-w-44"
|
className="tempo-dropdown min-w-44"
|
||||||
>
|
>
|
||||||
<DropdownMenuLabel className="text-xs text-slate-500">
|
<DropdownMenuLabel className="text-xs text-slate-500">
|
||||||
Navegação institucional
|
{t('Navegação institucional')}
|
||||||
</DropdownMenuLabel>
|
</DropdownMenuLabel>
|
||||||
{[
|
{!available && <DropdownMenuLabel className="text-xs text-slate-500">Tradução temporariamente indisponível</DropdownMenuLabel>}
|
||||||
['pt', 'Português'],
|
{languages.map(({ code, name }) => (
|
||||||
['en', 'English'],
|
|
||||||
['fr', 'Français'],
|
|
||||||
['es', 'Español'],
|
|
||||||
].map(([code, name]) => (
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
key={code}
|
key={code}
|
||||||
onSelect={() => setLanguage(code)}
|
onSelect={() => setLanguage(code)}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { AppShell } from '@/components/app-shell';
|
|||||||
import { AppSidebar } from '@/components/app-sidebar';
|
import { AppSidebar } from '@/components/app-sidebar';
|
||||||
import { AppSidebarHeader } from '@/components/app-sidebar-header';
|
import { AppSidebarHeader } from '@/components/app-sidebar-header';
|
||||||
import { NavigationContextSummary } from '@/components/navigation-context';
|
import { NavigationContextSummary } from '@/components/navigation-context';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import type { AppLayoutProps } from '@/types';
|
import type { AppLayoutProps } from '@/types';
|
||||||
|
|
||||||
export default function AppSidebarLayout({
|
export default function AppSidebarLayout({
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout';
|
import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
|
||||||
export default function AuthLayout({
|
export default function AuthLayout({
|
||||||
title = '',
|
title = '',
|
||||||
@@ -9,8 +10,9 @@ export default function AuthLayout({
|
|||||||
description?: string;
|
description?: string;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
|
const { t } = useTempoUi();
|
||||||
return (
|
return (
|
||||||
<AuthLayoutTemplate title={title} description={description}>
|
<AuthLayoutTemplate title={t(title)} description={t(description)}>
|
||||||
{children}
|
{children}
|
||||||
</AuthLayoutTemplate>
|
</AuthLayoutTemplate>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import SearchFeedback from '@/components/search-feedback';
|
import SearchFeedback from '@/components/search-feedback';
|
||||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||||
import { Link, usePage } from '@inertiajs/react';
|
import { Link, usePage } from '@inertiajs/react';
|
||||||
import { createContext, useContext } from 'react';
|
import { MenuPlacement, PortalMenu } from '@/components/portal-menu';
|
||||||
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
import { TempoUiProvider, useTempoUi } from '@/components/tempo-brand';
|
||||||
import { TempoUiProvider } from '@/components/tempo-brand';
|
import { PageTranslator } from '@/translation/page-translator';
|
||||||
import { TempoFooter } from '@/components/tempo-footer';
|
import { TempoFooter } from '@/components/tempo-footer';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import {
|
import {
|
||||||
@@ -11,8 +11,6 @@ import {
|
|||||||
NavigationContextSummary,
|
NavigationContextSummary,
|
||||||
} from '@/components/navigation-context';
|
} from '@/components/navigation-context';
|
||||||
|
|
||||||
const MenuPlacement = createContext(false);
|
|
||||||
|
|
||||||
export const portalLinks = [
|
export const portalLinks = [
|
||||||
['/', 'Início'],
|
['/', 'Início'],
|
||||||
['/oportunidades', 'Oportunidades de Investimento'],
|
['/oportunidades', 'Oportunidades de Investimento'],
|
||||||
@@ -67,6 +65,11 @@ export default function PortalNavigation({
|
|||||||
}: {
|
}: {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
|
return <TempoUiProvider><PageTranslator /><PortalNavigationContent>{children}</PortalNavigationContent></TempoUiProvider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function PortalNavigationContent({ children }: { children: ReactNode }) {
|
||||||
|
const { t } = useTempoUi();
|
||||||
const { url, props, component } = usePage();
|
const { url, props, component } = usePage();
|
||||||
const printable = component === 'land-assistance/print';
|
const printable = component === 'land-assistance/print';
|
||||||
const portalShell =
|
const portalShell =
|
||||||
@@ -108,24 +111,23 @@ export default function PortalNavigation({
|
|||||||
? 'Definições da conta'
|
? 'Definições da conta'
|
||||||
: 'Detalhes');
|
: 'Detalhes');
|
||||||
return (
|
return (
|
||||||
<TempoUiProvider>
|
|
||||||
<NavigationContextProvider>
|
<NavigationContextProvider>
|
||||||
<MenuPlacement.Provider value={true}>
|
<MenuPlacement.Provider value={true}>
|
||||||
<div className="min-h-screen [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
|
<div className="min-h-screen [&_button]:scroll-mb-24 [&_input]:scroll-mb-24 [&_select]:scroll-mb-24 [&_textarea]:scroll-mb-24">
|
||||||
<nav
|
<nav
|
||||||
aria-label="Atalho para o conteúdo"
|
aria-label={t('Atalho para o conteúdo')}
|
||||||
className={printable ? 'print:hidden' : undefined}
|
className={printable ? 'print:hidden' : undefined}
|
||||||
>
|
>
|
||||||
<a
|
<a
|
||||||
href="#portal-content"
|
href="#portal-content"
|
||||||
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
className="sr-only focus:not-sr-only focus:block focus:bg-white focus:p-4 focus:text-emerald-900"
|
||||||
>
|
>
|
||||||
Saltar para o conteúdo
|
{t('Saltar para o conteúdo')}
|
||||||
</a>
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
{props.homologationReserved === true && (
|
{props.homologationReserved === true && (
|
||||||
<aside aria-label="Ambiente de homologação" className="border-b border-amber-200 bg-amber-50 px-5 py-2 text-sm text-amber-950 print:hidden">
|
<aside aria-label={t('Ambiente de homologação')} className="border-b border-amber-200 bg-amber-50 px-5 py-2 text-sm text-amber-950 print:hidden">
|
||||||
Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.
|
{t('Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.')}
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
{portalShell && (
|
{portalShell && (
|
||||||
@@ -139,12 +141,12 @@ export default function PortalNavigation({
|
|||||||
)}
|
)}
|
||||||
{path !== '/' && (
|
{path !== '/' && (
|
||||||
<nav
|
<nav
|
||||||
aria-label="Caminho de navegação"
|
aria-label={t('Caminho de navegação')}
|
||||||
className={`bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm ${printable ? 'print:hidden' : ''}`}
|
className={`bg-background text-foreground flex flex-wrap items-center gap-2 border-b px-5 py-3 text-sm ${printable ? 'print:hidden' : ''}`}
|
||||||
>
|
>
|
||||||
<>
|
<>
|
||||||
<Link href="/" className="underline">
|
<Link href="/" className="underline">
|
||||||
Início
|
{t('Início')}
|
||||||
</Link>
|
</Link>
|
||||||
<span aria-hidden="true">/</span>
|
<span aria-hidden="true">/</span>
|
||||||
{parent && (
|
{parent && (
|
||||||
@@ -153,12 +155,12 @@ export default function PortalNavigation({
|
|||||||
href={searchTerritoryHref(parent, url)}
|
href={searchTerritoryHref(parent, url)}
|
||||||
className="underline"
|
className="underline"
|
||||||
>
|
>
|
||||||
{names[parent]}
|
{t(names[parent])}
|
||||||
</Link>
|
</Link>
|
||||||
<span aria-hidden="true">/</span>
|
<span aria-hidden="true">/</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<span aria-current="page">{title}</span>
|
<span aria-current="page">{t(title)}</span>
|
||||||
</>
|
</>
|
||||||
</nav>
|
</nav>
|
||||||
)}
|
)}
|
||||||
@@ -176,14 +178,14 @@ export default function PortalNavigation({
|
|||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
<aside
|
<aside
|
||||||
aria-label="Contacto de apoio ao investidor"
|
aria-label={t('Contacto de apoio ao investidor')}
|
||||||
className={`mx-auto flex max-w-6xl justify-center px-5 pt-4 ${printable ? 'print:hidden' : ''}`}
|
className={`mx-auto flex max-w-6xl justify-center px-5 pt-4 ${printable ? 'print:hidden' : ''}`}
|
||||||
>
|
>
|
||||||
<a
|
<a
|
||||||
href="/apoio"
|
href="/apoio"
|
||||||
className="inline-flex min-h-11 max-w-full items-center justify-center rounded-lg bg-[#ed1c24] px-4 py-2 text-center text-sm font-semibold text-white shadow-sm transition-colors hover:bg-[#c9141b] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#ed1c24]"
|
className="inline-flex min-h-11 max-w-full items-center justify-center rounded-lg bg-[#ed1c24] px-4 py-2 text-center text-sm font-semibold text-white shadow-sm transition-colors hover:bg-[#c9141b] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#ed1c24]"
|
||||||
>
|
>
|
||||||
Contactar Apoio ao Investidor
|
{t('Contactar Apoio ao Investidor')}
|
||||||
</a>
|
</a>
|
||||||
</aside>
|
</aside>
|
||||||
<div className={printable ? 'print:hidden' : undefined}>
|
<div className={printable ? 'print:hidden' : undefined}>
|
||||||
@@ -192,11 +194,6 @@ export default function PortalNavigation({
|
|||||||
</div>
|
</div>
|
||||||
</MenuPlacement.Provider>
|
</MenuPlacement.Provider>
|
||||||
</NavigationContextProvider>
|
</NavigationContextProvider>
|
||||||
</TempoUiProvider>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function PortalMenu({ primary = false }: { primary?: boolean }) {
|
|
||||||
const placed = useContext(MenuPlacement);
|
|
||||||
return placed && !primary ? null : <PortalGroupedMenu />;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import SearchState from '@/components/search-state';
|
|||||||
import { useInterestDraft } from '@/hooks/use-interest-draft';
|
import { useInterestDraft } from '@/hooks/use-interest-draft';
|
||||||
import { createContext, useContext, useRef, useState } from 'react';
|
import { createContext, useContext, useRef, useState } from 'react';
|
||||||
import { router } from '@inertiajs/react';
|
import { router } from '@inertiajs/react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import { ProvinceSelect } from '@/components/investment-territory';
|
import { ProvinceSelect } from '@/components/investment-territory';
|
||||||
import { MATURITY_LEVELS } from '@/lib/investment-maturity';
|
import { MATURITY_LEVELS } from '@/lib/investment-maturity';
|
||||||
import CountrySelect, { type Country } from '@/components/country-select';
|
import CountrySelect, { type Country } from '@/components/country-select';
|
||||||
@@ -973,7 +973,7 @@ export default function PortalInvestidorApp({
|
|||||||
|
|
||||||
function handleHeroSearch(event: FormEvent<HTMLFormElement>) {
|
function handleHeroSearch(event: FormEvent<HTMLFormElement>) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
router.get('/oportunidades', { q: heroQuery.trim() });
|
router.get('/pesquisa', { q: heroQuery.trim() });
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleView(opportunity: Opportunity) {
|
function handleView(opportunity: Opportunity) {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { participationIdentity } from '@/lib/participation-identity';
|
import { participationIdentity } from '@/lib/participation-identity';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
import { Form, Head, usePage } from '@inertiajs/react';
|
import { Form, Head, usePage } from '@inertiajs/react';
|
||||||
import InputError from '@/components/input-error';
|
import InputError from '@/components/input-error';
|
||||||
import PasswordInput from '@/components/password-input';
|
import PasswordInput from '@/components/password-input';
|
||||||
@@ -24,11 +25,12 @@ type Props = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||||
|
const { t } = useTempoUi();
|
||||||
// A redirect from another page (e.g. MFA) creates a new Form with empty local errors.
|
// A redirect from another page (e.g. MFA) creates a new Form with empty local errors.
|
||||||
const pageErrors = usePage<{ errors: { email?: string } }>().props.errors;
|
const pageErrors = usePage<{ errors: { email?: string } }>().props.errors;
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head title="Entrar" />
|
<Head title={t('Entrar')} />
|
||||||
|
|
||||||
{qaAccount && (
|
{qaAccount && (
|
||||||
<aside
|
<aside
|
||||||
@@ -48,9 +50,9 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
|
|
||||||
{/* @chisel-passkeys */}
|
{/* @chisel-passkeys */}
|
||||||
<PasskeyVerify
|
<PasskeyVerify
|
||||||
label="Entrar com chave de acesso"
|
label={t('Entrar com chave de acesso')}
|
||||||
loadingLabel="A autenticar…"
|
loadingLabel={t('A autenticar…')}
|
||||||
separator="Ou continuar com email"
|
separator={t('Ou continuar com email')}
|
||||||
/>
|
/>
|
||||||
{/* @end-chisel-passkeys */}
|
{/* @end-chisel-passkeys */}
|
||||||
|
|
||||||
@@ -85,7 +87,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<div className="flex items-center">
|
<div className="flex items-center">
|
||||||
<Label htmlFor="password">
|
<Label htmlFor="password">
|
||||||
Palavra-passe
|
{t('Palavra-passe')}
|
||||||
</Label>
|
</Label>
|
||||||
{canResetPassword && (
|
{canResetPassword && (
|
||||||
<TextLink
|
<TextLink
|
||||||
@@ -93,7 +95,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
className="ml-auto text-sm"
|
className="ml-auto text-sm"
|
||||||
tabIndex={5}
|
tabIndex={5}
|
||||||
>
|
>
|
||||||
Esqueceu a palavra-passe?
|
{t('Esqueceu a palavra-passe?')}
|
||||||
</TextLink>
|
</TextLink>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -103,7 +105,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
required
|
required
|
||||||
tabIndex={2}
|
tabIndex={2}
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
placeholder="Palavra-passe"
|
placeholder={t('Palavra-passe')}
|
||||||
/>
|
/>
|
||||||
<InputError message={errors.password} />
|
<InputError message={errors.password} />
|
||||||
</div>
|
</div>
|
||||||
@@ -115,7 +117,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
tabIndex={3}
|
tabIndex={3}
|
||||||
/>
|
/>
|
||||||
<Label htmlFor="remember">
|
<Label htmlFor="remember">
|
||||||
Manter sessão iniciada
|
{t('Manter sessão iniciada')}
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -127,15 +129,15 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
|||||||
data-test="login-button"
|
data-test="login-button"
|
||||||
>
|
>
|
||||||
{processing && <Spinner />}
|
{processing && <Spinner />}
|
||||||
Entrar
|
{t('Entrar')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* @chisel-registration */}
|
{/* @chisel-registration */}
|
||||||
<div className="text-muted-foreground text-center text-sm">
|
<div className="text-muted-foreground text-center text-sm">
|
||||||
Ainda não tem conta?{' '}
|
{t('Ainda não tem conta?')}{' '}
|
||||||
<TextLink href={register()} tabIndex={5}>
|
<TextLink href={register()} tabIndex={5}>
|
||||||
Criar conta
|
{t('Criar conta')}
|
||||||
</TextLink>
|
</TextLink>
|
||||||
</div>
|
</div>
|
||||||
{/* @end-chisel-registration */}
|
{/* @end-chisel-registration */}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { participationIdentity } from '@/lib/participation-identity';
|
import { participationIdentity } from '@/lib/participation-identity';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
import { Form, Head } from '@inertiajs/react';
|
import { Form, Head } from '@inertiajs/react';
|
||||||
import InputError from '@/components/input-error';
|
import InputError from '@/components/input-error';
|
||||||
import PasswordInput from '@/components/password-input';
|
import PasswordInput from '@/components/password-input';
|
||||||
@@ -15,9 +16,10 @@ type Props = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function Register({ passwordRules }: Props) {
|
export default function Register({ passwordRules }: Props) {
|
||||||
|
const { t } = useTempoUi();
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head title="Criar conta" />
|
<Head title={t('Criar conta')} />
|
||||||
<Form
|
<Form
|
||||||
{...store.form()}
|
{...store.form()}
|
||||||
resetOnSuccess={['password', 'password_confirmation']}
|
resetOnSuccess={['password', 'password_confirmation']}
|
||||||
@@ -28,7 +30,7 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
<>
|
<>
|
||||||
<div className="grid gap-6">
|
<div className="grid gap-6">
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="name">Nome</Label>
|
<Label htmlFor="name">{t('Nome')}</Label>
|
||||||
<Input
|
<Input
|
||||||
id="name"
|
id="name"
|
||||||
defaultValue={participationIdentity().name}
|
defaultValue={participationIdentity().name}
|
||||||
@@ -37,7 +39,7 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
tabIndex={1}
|
tabIndex={1}
|
||||||
autoComplete="name"
|
autoComplete="name"
|
||||||
name="name"
|
name="name"
|
||||||
placeholder="Nome completo"
|
placeholder={t('Nome completo')}
|
||||||
/>
|
/>
|
||||||
<InputError
|
<InputError
|
||||||
message={errors.name}
|
message={errors.name}
|
||||||
@@ -61,14 +63,14 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="password">Palavra-passe</Label>
|
<Label htmlFor="password">{t('Palavra-passe')}</Label>
|
||||||
<PasswordInput
|
<PasswordInput
|
||||||
id="password"
|
id="password"
|
||||||
required
|
required
|
||||||
tabIndex={3}
|
tabIndex={3}
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
name="password"
|
name="password"
|
||||||
placeholder="Palavra-passe"
|
placeholder={t('Palavra-passe')}
|
||||||
passwordrules={passwordRules}
|
passwordrules={passwordRules}
|
||||||
/>
|
/>
|
||||||
<InputError message={errors.password} />
|
<InputError message={errors.password} />
|
||||||
@@ -76,7 +78,7 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
|
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="password_confirmation">
|
<Label htmlFor="password_confirmation">
|
||||||
Confirmar palavra-passe
|
{t('Confirmar palavra-passe')}
|
||||||
</Label>
|
</Label>
|
||||||
<PasswordInput
|
<PasswordInput
|
||||||
id="password_confirmation"
|
id="password_confirmation"
|
||||||
@@ -84,7 +86,7 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
tabIndex={4}
|
tabIndex={4}
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
name="password_confirmation"
|
name="password_confirmation"
|
||||||
placeholder="Confirmar palavra-passe"
|
placeholder={t('Confirmar palavra-passe')}
|
||||||
passwordrules={passwordRules}
|
passwordrules={passwordRules}
|
||||||
/>
|
/>
|
||||||
<InputError
|
<InputError
|
||||||
@@ -99,14 +101,14 @@ export default function Register({ passwordRules }: Props) {
|
|||||||
data-test="register-user-button"
|
data-test="register-user-button"
|
||||||
>
|
>
|
||||||
{processing && <Spinner />}
|
{processing && <Spinner />}
|
||||||
Criar conta
|
{t('Criar conta')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="text-muted-foreground text-center text-sm">
|
<div className="text-muted-foreground text-center text-sm">
|
||||||
Já tem conta?{' '}
|
{t('Já tem conta?')}{' '}
|
||||||
<TextLink href={login()} tabIndex={6}>
|
<TextLink href={login()} tabIndex={6}>
|
||||||
Entrar
|
{t('Entrar')}
|
||||||
</TextLink>
|
</TextLink>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
import { Head, Link, usePage } from '@inertiajs/react';
|
import { Head, Link, usePage } from '@inertiajs/react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import type { TerritorialSourceEvidence } from '@/components/territorial-source-evidence';
|
import type { TerritorialSourceEvidence } from '@/components/territorial-source-evidence';
|
||||||
import type {
|
import type {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Head, Link } from '@inertiajs/react';
|
import { Head, Link } from '@inertiajs/react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import EditorialReading, {
|
import EditorialReading, {
|
||||||
type EditorialArticle,
|
type EditorialArticle,
|
||||||
} from '@/components/editorial-reading';
|
} from '@/components/editorial-reading';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Head, Link } from '@inertiajs/react';
|
import { Head, Link } from '@inertiajs/react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import {
|
import {
|
||||||
PublicDocumentContent,
|
PublicDocumentContent,
|
||||||
type PublicDocument,
|
type PublicDocument,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Head, Link, router } from '@inertiajs/react';
|
import { Head, Link, router } from '@inertiajs/react';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import { fiscalForms, fiscalFormFields, fiscalPreparationIssues, newFiscalPreparation, readFiscalPreparation, type FiscalFormKind, type FiscalPreparation } from '@/lib/fiscal-form-preparation';
|
import { fiscalForms, fiscalFormFields, fiscalPreparationIssues, newFiscalPreparation, readFiscalPreparation, type FiscalFormKind, type FiscalPreparation } from '@/lib/fiscal-form-preparation';
|
||||||
|
|
||||||
const input = 'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
|
const input = 'mt-1 block w-full rounded border border-slate-400 bg-white p-3 text-slate-900';
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { Head, Link } from '@inertiajs/react';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Search as SearchIcon } from 'lucide-react';
|
||||||
|
|
||||||
|
type Result = { title: string; description: string | null; url: string; category: string };
|
||||||
|
type Results = { data: Result[]; total: number; current_page: number; last_page: number; per_page: number; unavailable: string[] };
|
||||||
|
|
||||||
|
function pageNumbers(current: number, last: number): (number | string)[] {
|
||||||
|
const pages = [...new Set([1, last, ...Array.from({ length: 5 }, (_, i) => current - 2 + i)])]
|
||||||
|
.filter((page) => page >= 1 && page <= last).sort((a, b) => a - b);
|
||||||
|
return pages.flatMap((page, i) => i > 0 && page - pages[i - 1] > 1 ? [`gap-${page}`, page] : [page]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Search({ query, results }: { query: string; results: Results }) {
|
||||||
|
const [input, setInput] = useState(query);
|
||||||
|
useEffect(() => setInput(query), [query]);
|
||||||
|
const { data, total, current_page: current, last_page: last, per_page: perPage, unavailable } = results;
|
||||||
|
const pageUrl = (page: number) => `/pesquisa?${new URLSearchParams({ q: query, page: String(page) })}`;
|
||||||
|
const start = total ? (current - 1) * perPage + 1 : 0;
|
||||||
|
const end = Math.min(start + data.length - 1, total);
|
||||||
|
|
||||||
|
return <main className="min-h-[65vh] bg-white text-[#101820]">
|
||||||
|
<Head title="Pesquisa" />
|
||||||
|
<div className="border-b border-slate-200 bg-[#101820] text-white">
|
||||||
|
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Pesquisa no InvesteMoz</h1>
|
||||||
|
<form action="/pesquisa" role="search" className="mt-5 flex max-w-3xl flex-col gap-2 sm:flex-row">
|
||||||
|
<label htmlFor="search-query" className="sr-only">Pesquisar no InvesteMoz</label>
|
||||||
|
<input id="search-query" type="search" name="q" value={input} onChange={(event) => setInput(event.target.value)} maxLength={120} className="min-h-12 min-w-0 flex-1 rounded-lg border border-slate-300 bg-white px-4 text-base text-[#101820] outline-none focus:ring-2 focus:ring-[#ed1c24]" placeholder="Oportunidades, documentos, sectores..." />
|
||||||
|
<button className="inline-flex min-h-12 items-center justify-center gap-2 rounded-lg bg-[#ed1c24] px-6 font-semibold text-white hover:bg-[#c9141b] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"><SearchIcon size={18} aria-hidden="true" />Pesquisar</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mx-auto max-w-5xl px-4 py-7 sm:px-6">
|
||||||
|
<p className="max-w-3xl text-sm leading-relaxed text-slate-600">Pesquise por palavras em qualquer ordem. Pode escrever com ou sem acentos. Os documentos são pesquisados pelos seus dados descritivos.</p>
|
||||||
|
{unavailable.length > 0 && <p role="alert" className="mt-4 rounded-lg border border-amber-400 bg-amber-50 p-3 text-sm">Não foi possível consultar: {unavailable.join(', ')}. Os restantes resultados continuam disponíveis; tente novamente mais tarde.</p>}
|
||||||
|
{query && <p className="mt-6 text-sm text-slate-600" aria-live="polite">{total > 0 ? `Resultados ${start}–${end} de ${total}` : 'Nenhum resultado nas fontes consultadas'} para “{query}”.</p>}
|
||||||
|
{query && total === 0 && <p className="mt-4 text-slate-600">Experimente outras palavras ou uma expressão mais curta.</p>}
|
||||||
|
<ol start={start || 1} className="mt-2 max-w-3xl divide-y divide-slate-200">
|
||||||
|
{data.map((item) => <li key={`${item.category}:${item.url}`} className="py-5">
|
||||||
|
<p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-600">{item.category}</p>
|
||||||
|
<Link href={item.url} className="text-lg font-semibold text-[#b5121b] underline-offset-4 hover:underline focus-visible:rounded focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#ed1c24]">{item.title}</Link>
|
||||||
|
{item.description && <p className="mt-1 line-clamp-3 text-sm leading-relaxed text-slate-600">{item.description}</p>}
|
||||||
|
</li>)}
|
||||||
|
</ol>
|
||||||
|
{last > 1 && <nav className="mt-8 flex flex-wrap items-center gap-2" aria-label="Páginas de resultados">
|
||||||
|
{current > 1 && <Link href={pageUrl(current - 1)} rel="prev" className="rounded-md px-3 py-2 text-sm font-semibold text-[#b5121b] hover:bg-red-50">Anterior</Link>}
|
||||||
|
{pageNumbers(current, last).map((page) => typeof page === 'string' ? <span key={page} className="px-1 text-slate-500" aria-hidden="true">…</span> :
|
||||||
|
<Link key={page} href={pageUrl(page)} aria-label={`Página ${page}`} aria-current={page === current ? 'page' : undefined} className={page === current ? 'rounded-md bg-[#101820] px-3 py-2 text-sm font-bold text-white' : 'rounded-md px-3 py-2 text-sm font-semibold text-[#b5121b] hover:bg-red-50'}>{page}</Link>)}
|
||||||
|
{current < last && <Link href={pageUrl(current + 1)} rel="next" className="rounded-md px-3 py-2 text-sm font-semibold text-[#b5121b] hover:bg-red-50">Seguinte</Link>}
|
||||||
|
</nav>}
|
||||||
|
</div>
|
||||||
|
</main>;
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
} from '@/components/public-document-content';
|
} from '@/components/public-document-content';
|
||||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
import { PortalMenu } from '@/components/portal-menu';
|
||||||
import { newSubmissionKey } from '@/lib/portal-api';
|
import { newSubmissionKey } from '@/lib/portal-api';
|
||||||
import { ProvinceSelect } from '@/components/investment-territory';
|
import { ProvinceSelect } from '@/components/investment-territory';
|
||||||
import { SimulationForm } from '@/components/simulation-form';
|
import { SimulationForm } from '@/components/simulation-form';
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useTempoUi } from '@/components/tempo-brand';
|
||||||
|
import { translateText } from '@/translation/service';
|
||||||
|
import { protectTranslationTokens, restoreTranslationTokens } from '@/translation/utils';
|
||||||
|
|
||||||
|
// Never change the structure of React's DOM or the value of a form control.
|
||||||
|
const excluded = 'script,style,noscript,code,pre,textarea,[contenteditable]:not([contenteditable="false"]),[translate="no"],[data-no-translate],.no-translate';
|
||||||
|
const attributes = ['placeholder', 'title', 'aria-label', 'alt'] as const;
|
||||||
|
type Target = { node: Text | Element; attribute?: string; original: string; translated?: string };
|
||||||
|
|
||||||
|
function read(target: Target): string | null {
|
||||||
|
return target.attribute ? (target.node as Element).getAttribute(target.attribute) : target.node.nodeValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
function write(target: Target, value: string): void {
|
||||||
|
if (target.attribute) (target.node as Element).setAttribute(target.attribute, value);
|
||||||
|
else target.node.nodeValue = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PageTranslator() {
|
||||||
|
const { language } = useTempoUi();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (language === 'pt') return;
|
||||||
|
let active = true;
|
||||||
|
const abort = new AbortController();
|
||||||
|
const targets = new Map<Node, Map<string, Target>>();
|
||||||
|
const cache = new Map<string, Promise<string>>();
|
||||||
|
const queue: Array<() => void> = [];
|
||||||
|
let running = 0;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let unavailable = false;
|
||||||
|
|
||||||
|
const run = () => {
|
||||||
|
if (!active || unavailable || timer || running >= 2 || !queue.length) return;
|
||||||
|
running++;
|
||||||
|
queue.shift()?.();
|
||||||
|
// Stay below the API's per-minute limit on large pages.
|
||||||
|
timer = setTimeout(() => { timer = undefined; run(); }, 650);
|
||||||
|
};
|
||||||
|
const translate = (value: string): Promise<string> => {
|
||||||
|
const previous = cache.get(value);
|
||||||
|
if (previous) return previous;
|
||||||
|
const promise = new Promise<string>((resolve, reject) => {
|
||||||
|
queue.push(() => {
|
||||||
|
const protectedText = protectTranslationTokens(value);
|
||||||
|
translateText({ text: protectedText.text, sourceLanguage: 'auto', targetLanguage: language }, abort.signal)
|
||||||
|
.then(({ translatedText }) => {
|
||||||
|
for (const token of protectedText.replacements.keys()) {
|
||||||
|
if (!translatedText.includes(token)) throw new Error('Translation lost a protected token');
|
||||||
|
}
|
||||||
|
resolve(restoreTranslationTokens(translatedText, protectedText.replacements));
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
if (!abort.signal.aborted && (error?.status === 503 || error?.status === null)) unavailable = true;
|
||||||
|
reject(error);
|
||||||
|
})
|
||||||
|
.finally(() => { running--; run(); });
|
||||||
|
});
|
||||||
|
run();
|
||||||
|
});
|
||||||
|
cache.set(value, promise);
|
||||||
|
promise.catch(() => cache.delete(value));
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
const consider = (node: Text | Element, attribute?: string) => {
|
||||||
|
const element = node instanceof Element ? node : node.parentElement;
|
||||||
|
if (!element || element.closest(excluded)) return;
|
||||||
|
// Without an explicit value, translating an option changes the submitted value.
|
||||||
|
if (element.closest('option:not([value])')) return;
|
||||||
|
const key = attribute ?? '';
|
||||||
|
const value = attribute ? (node as Element).getAttribute(attribute) : node.nodeValue;
|
||||||
|
if (!value || value.length > 10000 || !/\p{L}/u.test(value)) return;
|
||||||
|
let entries = targets.get(node);
|
||||||
|
if (!entries) { entries = new Map(); targets.set(node, entries); }
|
||||||
|
const old = entries.get(key);
|
||||||
|
if (old && (value === old.original || value === old.translated)) return;
|
||||||
|
const target: Target = { node, attribute, original: value };
|
||||||
|
entries.set(key, target);
|
||||||
|
translate(value).then((translated) => {
|
||||||
|
if (!active || !node.isConnected || entries?.get(key) !== target || read(target) !== value) return;
|
||||||
|
target.translated = translated;
|
||||||
|
write(target, translated);
|
||||||
|
}).catch(() => { /* Keep the original visible when translation fails. */ });
|
||||||
|
};
|
||||||
|
const scan = (root: Node) => {
|
||||||
|
if (root instanceof Text) { consider(root); return; }
|
||||||
|
if (!(root instanceof Element)) return;
|
||||||
|
if (root.closest(excluded)) return;
|
||||||
|
for (const name of attributes) if (root.hasAttribute(name)) consider(root, name);
|
||||||
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
|
||||||
|
while (walker.nextNode()) {
|
||||||
|
const node = walker.currentNode;
|
||||||
|
if (node instanceof Text) consider(node);
|
||||||
|
else if (node instanceof Element) for (const name of attributes) if (node.hasAttribute(name)) consider(node, name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const observer = new MutationObserver((mutations) => {
|
||||||
|
for (const mutation of mutations) {
|
||||||
|
if (mutation.type === 'characterData') scan(mutation.target);
|
||||||
|
else if (mutation.type === 'attributes' && mutation.target instanceof Element && mutation.attributeName) consider(mutation.target, mutation.attributeName);
|
||||||
|
else mutation.addedNodes.forEach(scan);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
observer.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: [...attributes] });
|
||||||
|
scan(document.body);
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
abort.abort();
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
observer.disconnect();
|
||||||
|
for (const entries of targets.values()) for (const target of entries.values()) {
|
||||||
|
if (target.translated !== undefined && read(target) === target.translated) write(target, target.original);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [language]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import type {
|
||||||
|
TranslateRequest,
|
||||||
|
TranslateResponse,
|
||||||
|
TranslationLanguage,
|
||||||
|
} from "./types";
|
||||||
|
import { readLanguageList } from "./utils";
|
||||||
|
|
||||||
|
const translationApiBaseUrl = "/api";
|
||||||
|
|
||||||
|
const REQUEST_TIMEOUT_MS = 65_000;
|
||||||
|
const MAX_ATTEMPTS = 3;
|
||||||
|
|
||||||
|
export class TranslationRequestError extends Error {
|
||||||
|
status: number | null;
|
||||||
|
retryable: boolean;
|
||||||
|
|
||||||
|
constructor(message: string, options?: { status?: number | null; retryable?: boolean }) {
|
||||||
|
super(message);
|
||||||
|
this.name = "TranslationRequestError";
|
||||||
|
this.status = options?.status ?? null;
|
||||||
|
this.retryable = options?.retryable ?? false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRetryableStatus(status: number): boolean {
|
||||||
|
return [429, 500, 502, 503, 504].includes(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function wait(ms: number): Promise<void> {
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJson<T>(
|
||||||
|
input: RequestInfo | URL,
|
||||||
|
init: RequestInit = {},
|
||||||
|
attempt = 1,
|
||||||
|
maxAttempts = MAX_ATTEMPTS,
|
||||||
|
): Promise<T> {
|
||||||
|
const parentSignal = init.signal;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeoutId = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||||
|
|
||||||
|
const forwardAbort = () => controller.abort();
|
||||||
|
parentSignal?.addEventListener("abort", forwardAbort, { once: true });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(input, {
|
||||||
|
...init,
|
||||||
|
signal: controller.signal,
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
...(init.headers ?? {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const retryable = isRetryableStatus(response.status);
|
||||||
|
if (retryable && attempt < maxAttempts) {
|
||||||
|
await wait(300 * attempt);
|
||||||
|
return fetchJson<T>(input, init, attempt + 1, maxAttempts);
|
||||||
|
}
|
||||||
|
|
||||||
|
let message = `Translation request failed with status ${response.status}`;
|
||||||
|
try {
|
||||||
|
const payload = (await response.json()) as { message?: string };
|
||||||
|
if (payload?.message) {
|
||||||
|
message = payload.message;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore JSON parse issues on error responses.
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new TranslationRequestError(message, {
|
||||||
|
status: response.status,
|
||||||
|
retryable,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (await response.json()) as T;
|
||||||
|
} catch (error) {
|
||||||
|
const aborted = controller.signal.aborted;
|
||||||
|
const isDomAbort = error instanceof DOMException && error.name === "AbortError";
|
||||||
|
const parentAborted = parentSignal?.aborted ?? false;
|
||||||
|
const timedOut = aborted && !parentAborted;
|
||||||
|
const retryable = timedOut || error instanceof TypeError;
|
||||||
|
|
||||||
|
if (retryable && attempt < maxAttempts) {
|
||||||
|
await wait(300 * attempt);
|
||||||
|
return fetchJson<T>(input, init, attempt + 1, maxAttempts);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof TranslationRequestError) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentAborted || isDomAbort) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (timedOut) {
|
||||||
|
throw new TranslationRequestError("Translation request timed out", {
|
||||||
|
status: null,
|
||||||
|
retryable,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new TranslationRequestError("Translation request failed", {
|
||||||
|
status: null,
|
||||||
|
retryable,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
window.clearTimeout(timeoutId);
|
||||||
|
parentSignal?.removeEventListener("abort", forwardAbort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLanguages(signal?: AbortSignal): Promise<TranslationLanguage[]> {
|
||||||
|
const payload = await fetchJson<unknown>(`${translationApiBaseUrl}/translate/languages`, {
|
||||||
|
method: "GET",
|
||||||
|
signal,
|
||||||
|
}, 1, 1);
|
||||||
|
|
||||||
|
return readLanguageList(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function translateText(
|
||||||
|
request: TranslateRequest,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): Promise<TranslateResponse> {
|
||||||
|
const payload = await fetchJson<{
|
||||||
|
original_text?: string;
|
||||||
|
translated_text?: string;
|
||||||
|
source_lang?: string;
|
||||||
|
target_lang?: string;
|
||||||
|
}>(`${translationApiBaseUrl}/translate`, {
|
||||||
|
method: "POST",
|
||||||
|
signal,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
text: request.text,
|
||||||
|
source_lang: request.sourceLanguage,
|
||||||
|
target_lang: request.targetLanguage,
|
||||||
|
is_html: request.isHtml ?? false,
|
||||||
|
}),
|
||||||
|
}, 1, 1);
|
||||||
|
|
||||||
|
if (typeof payload.translated_text !== "string" || payload.translated_text.trim() === "") {
|
||||||
|
throw new TranslationRequestError("Translation response is missing translated_text", {
|
||||||
|
status: 200,
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
originalText: payload.original_text ?? request.text,
|
||||||
|
translatedText: payload.translated_text,
|
||||||
|
sourceLanguage: payload.source_lang ?? request.sourceLanguage,
|
||||||
|
targetLanguage: payload.target_lang ?? request.targetLanguage,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
export interface TranslationLanguage {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
targets?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TranslateRequest {
|
||||||
|
text: string;
|
||||||
|
sourceLanguage: string;
|
||||||
|
targetLanguage: string;
|
||||||
|
isHtml?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TranslateResponse {
|
||||||
|
originalText: string;
|
||||||
|
translatedText: string;
|
||||||
|
sourceLanguage: string;
|
||||||
|
targetLanguage: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TranslationCacheEntry {
|
||||||
|
value: string;
|
||||||
|
createdAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProtectedTranslationTokens {
|
||||||
|
text: string;
|
||||||
|
replacements: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TranslationPayloadHealth {
|
||||||
|
shouldTranslate: boolean;
|
||||||
|
normalizedText: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TranslateOptions {
|
||||||
|
isHtml?: boolean;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
protectedTerms?: string[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,615 @@
|
|||||||
|
import type {
|
||||||
|
ProtectedTranslationTokens,
|
||||||
|
TranslationPayloadHealth,
|
||||||
|
TranslationCacheEntry,
|
||||||
|
TranslationLanguage,
|
||||||
|
} from "./types";
|
||||||
|
|
||||||
|
const CACHE_PREFIX = "tempo_translation_v1";
|
||||||
|
const CACHE_VERSION = "v1";
|
||||||
|
const CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
const CACHE_MAX_ENTRIES = 200;
|
||||||
|
const CACHE_CLEANUP_INTERVAL = 12 * 60 * 60 * 1000;
|
||||||
|
const CLEANUP_MARKER_KEY = `${CACHE_PREFIX}:cleanup`;
|
||||||
|
const memoryCache = new Map<string, TranslationCacheEntry>();
|
||||||
|
|
||||||
|
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||||
|
ar: "ar",
|
||||||
|
"ar-sa": "ar",
|
||||||
|
en: "en",
|
||||||
|
"en-gb": "en",
|
||||||
|
"en-us": "en",
|
||||||
|
es: "es",
|
||||||
|
"es-es": "es",
|
||||||
|
fr: "fr",
|
||||||
|
"fr-fr": "fr",
|
||||||
|
hi: "hi",
|
||||||
|
"hi-in": "hi",
|
||||||
|
pt: "pt",
|
||||||
|
"pt-mz": "pt",
|
||||||
|
"pt-pt": "pt",
|
||||||
|
zh: "zh-Hans",
|
||||||
|
"zh-cn": "zh-Hans",
|
||||||
|
"zh-hans": "zh-Hans",
|
||||||
|
};
|
||||||
|
|
||||||
|
const apiUnsafeNodes = "script, iframe, object, embed, link, meta";
|
||||||
|
const excludedTranslationNodes =
|
||||||
|
"code, pre, script, style, textarea, noscript, .no-translate, [data-no-translate], [translate='no']";
|
||||||
|
const INTERNAL_PLACEHOLDER_PREFIX = "¤TRX";
|
||||||
|
const BATCH_MAX_ITEMS = 8;
|
||||||
|
const BATCH_MAX_CHARS = 2200;
|
||||||
|
const TRANSLATION_PLACEHOLDER_PATTERN = /¤TRX[A-Z]+\d+¤/g;
|
||||||
|
const HTML_BATCH_ROOT_ATTR = "data-trx-batch-root";
|
||||||
|
const HTML_BATCH_NODE_ATTR = "data-trx-node";
|
||||||
|
|
||||||
|
export const fallbackTranslationLanguages: TranslationLanguage[] = [
|
||||||
|
{ code: "pt", name: "Português" },
|
||||||
|
{ code: "en", name: "English" },
|
||||||
|
{ code: "fr", name: "French" },
|
||||||
|
{ code: "es", name: "Spanish" },
|
||||||
|
{ code: "ar", name: "Arabic" },
|
||||||
|
{ code: "hi", name: "Hindi" },
|
||||||
|
{ code: "zh-Hans", name: "Chinese" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const DEFAULT_PROTECTED_TERMS = [
|
||||||
|
"Revista TEMPO",
|
||||||
|
"Grupo TEMPO",
|
||||||
|
"Tempo TV",
|
||||||
|
"Tempo Connect",
|
||||||
|
"Informação Pública",
|
||||||
|
"InvesteMoz",
|
||||||
|
"TEMPO",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function getStorage(): Storage | null {
|
||||||
|
if (typeof window === "undefined") return null;
|
||||||
|
return window.localStorage;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeAlias(code: string): string {
|
||||||
|
return LANGUAGE_ALIASES[code.trim().toLowerCase()] ?? code.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeLanguageCode(
|
||||||
|
code: string,
|
||||||
|
availableLanguages: TranslationLanguage[],
|
||||||
|
): string | null {
|
||||||
|
if (!code) return null;
|
||||||
|
|
||||||
|
const normalized = normalizeAlias(code);
|
||||||
|
const supportedCodes = new Set(
|
||||||
|
availableLanguages.map((language) => normalizeAlias(language.code)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return supportedCodes.has(normalized) ? normalized : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBrowserLanguageCode(code: string): string {
|
||||||
|
switch (code) {
|
||||||
|
case "zh-Hans":
|
||||||
|
return "zh-CN";
|
||||||
|
default:
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLocaleForLanguage(code: string): string {
|
||||||
|
switch (normalizeAlias(code)) {
|
||||||
|
case "pt":
|
||||||
|
return "pt-MZ";
|
||||||
|
case "zh-Hans":
|
||||||
|
return "zh-CN";
|
||||||
|
default:
|
||||||
|
return normalizeAlias(code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isRtlLanguage(code: string): boolean {
|
||||||
|
return normalizeAlias(code) === "ar";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readLanguageList(payload: unknown): TranslationLanguage[] {
|
||||||
|
const source = Array.isArray(payload)
|
||||||
|
? payload
|
||||||
|
: Array.isArray((payload as { value?: unknown[] })?.value)
|
||||||
|
? (payload as { value: unknown[] }).value
|
||||||
|
: Array.isArray((payload as { data?: unknown[] })?.data)
|
||||||
|
? (payload as { data: unknown[] }).data
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return source
|
||||||
|
.filter((item): item is TranslationLanguage => {
|
||||||
|
return (
|
||||||
|
Boolean(item) &&
|
||||||
|
typeof item === "object" &&
|
||||||
|
typeof item.code === "string" &&
|
||||||
|
typeof item.name === "string"
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.map((language) => ({
|
||||||
|
code: normalizeAlias(language.code),
|
||||||
|
name: language.name,
|
||||||
|
targets: Array.isArray(language.targets)
|
||||||
|
? language.targets.map((target) => normalizeAlias(target))
|
||||||
|
: undefined,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withPortugueseFirst(
|
||||||
|
languages: TranslationLanguage[],
|
||||||
|
): TranslationLanguage[] {
|
||||||
|
const unique = new Map<string, TranslationLanguage>();
|
||||||
|
|
||||||
|
for (const language of languages) {
|
||||||
|
const code = normalizeAlias(language.code);
|
||||||
|
if (!unique.has(code)) {
|
||||||
|
unique.set(code, {
|
||||||
|
...language,
|
||||||
|
code,
|
||||||
|
name: code === "pt" ? "Português" : language.name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = Array.from(unique.values()).sort((a, b) =>
|
||||||
|
a.name.localeCompare(b.name),
|
||||||
|
);
|
||||||
|
|
||||||
|
const portuguese =
|
||||||
|
items.find((language) => language.code === "pt") ?? fallbackTranslationLanguages[0];
|
||||||
|
|
||||||
|
return [portuguese, ...items.filter((language) => language.code !== "pt")];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hashTranslationText(value: string): string {
|
||||||
|
let hash = 2166136261;
|
||||||
|
|
||||||
|
for (let index = 0; index < value.length; index += 1) {
|
||||||
|
hash ^= value.charCodeAt(index);
|
||||||
|
hash = Math.imul(hash, 16777619);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (hash >>> 0).toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTranslationCacheKey(params: {
|
||||||
|
sourceLanguage: string;
|
||||||
|
targetLanguage: string;
|
||||||
|
isHtml: boolean;
|
||||||
|
text: string;
|
||||||
|
protectedTerms?: string[];
|
||||||
|
}): string {
|
||||||
|
return [
|
||||||
|
CACHE_PREFIX,
|
||||||
|
CACHE_VERSION,
|
||||||
|
params.sourceLanguage,
|
||||||
|
params.targetLanguage,
|
||||||
|
params.isHtml ? "html" : "text",
|
||||||
|
hashTranslationText(params.text),
|
||||||
|
hashTranslationText(
|
||||||
|
JSON.stringify(
|
||||||
|
collectProtectedTerms(params.protectedTerms).map((term) => term.toLowerCase()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
].join(":");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMemoryCacheEntry(key: string): TranslationCacheEntry | null {
|
||||||
|
const entry = memoryCache.get(key);
|
||||||
|
if (!entry) return null;
|
||||||
|
|
||||||
|
if (entry.expiresAt <= Date.now()) {
|
||||||
|
memoryCache.delete(key);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setMemoryCacheEntry(key: string, value: string): TranslationCacheEntry {
|
||||||
|
const entry: TranslationCacheEntry = {
|
||||||
|
value,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
expiresAt: Date.now() + CACHE_TTL,
|
||||||
|
};
|
||||||
|
|
||||||
|
memoryCache.set(key, entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPersistentCacheEntry(key: string): TranslationCacheEntry | null {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (!storage) return null;
|
||||||
|
|
||||||
|
const raw = storage.getItem(key);
|
||||||
|
if (!raw) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const entry = JSON.parse(raw) as TranslationCacheEntry;
|
||||||
|
if (entry.expiresAt <= Date.now()) {
|
||||||
|
storage.removeItem(key);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return entry;
|
||||||
|
} catch {
|
||||||
|
storage.removeItem(key);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPersistentCacheEntry(key: string, entry: TranslationCacheEntry): void {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (!storage) return;
|
||||||
|
|
||||||
|
storage.setItem(key, JSON.stringify(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cleanupTranslationCache(): void {
|
||||||
|
const storage = getStorage();
|
||||||
|
if (!storage) return;
|
||||||
|
|
||||||
|
const lastCleanup = Number(storage.getItem(CLEANUP_MARKER_KEY) ?? "0");
|
||||||
|
if (lastCleanup && Date.now() - lastCleanup < CACHE_CLEANUP_INTERVAL) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const translationKeys: string[] = [];
|
||||||
|
|
||||||
|
for (let index = 0; index < storage.length; index += 1) {
|
||||||
|
const key = storage.key(index);
|
||||||
|
if (key && key.startsWith(`${CACHE_PREFIX}:${CACHE_VERSION}:`)) {
|
||||||
|
translationKeys.push(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const validEntries: Array<{ key: string; entry: TranslationCacheEntry }> = [];
|
||||||
|
|
||||||
|
for (const key of translationKeys) {
|
||||||
|
const entry = getPersistentCacheEntry(key);
|
||||||
|
if (entry) {
|
||||||
|
validEntries.push({ key, entry });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validEntries
|
||||||
|
.sort((a, b) => a.entry.createdAt - b.entry.createdAt)
|
||||||
|
.slice(0, Math.max(0, validEntries.length - CACHE_MAX_ENTRIES))
|
||||||
|
.forEach(({ key }) => storage.removeItem(key));
|
||||||
|
|
||||||
|
storage.setItem(CLEANUP_MARKER_KEY, String(Date.now()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPlaceholder(prefix: string, index: number): string {
|
||||||
|
return `${INTERNAL_PLACEHOLDER_PREFIX}${prefix}${index}¤`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeRegExp(value: string): string {
|
||||||
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function collectProtectedTerms(terms?: Array<string | null | undefined>): string[] {
|
||||||
|
const combined = [...DEFAULT_PROTECTED_TERMS, ...(terms ?? [])]
|
||||||
|
.map((term) => String(term ?? "").trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
return Array.from(new Set(combined)).sort((a, b) => b.length - a.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
function protectMatches(
|
||||||
|
input: string,
|
||||||
|
pattern: RegExp,
|
||||||
|
replacements: Map<string, string>,
|
||||||
|
prefix: string,
|
||||||
|
): string {
|
||||||
|
return input.replace(pattern, (match) => {
|
||||||
|
const placeholder = createPlaceholder(prefix, replacements.size);
|
||||||
|
replacements.set(placeholder, match);
|
||||||
|
return placeholder;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function protectExcludedHtmlBlocks(
|
||||||
|
input: string,
|
||||||
|
replacements: Map<string, string>,
|
||||||
|
): string {
|
||||||
|
if (typeof window === "undefined") return input;
|
||||||
|
|
||||||
|
const documentFragment = new DOMParser().parseFromString(input, "text/html");
|
||||||
|
const nodes = Array.from(documentFragment.body.querySelectorAll(excludedTranslationNodes));
|
||||||
|
|
||||||
|
nodes.forEach((node) => {
|
||||||
|
const placeholder = createPlaceholder("HTML", replacements.size);
|
||||||
|
replacements.set(placeholder, node.outerHTML);
|
||||||
|
node.replaceWith(documentFragment.createTextNode(placeholder));
|
||||||
|
});
|
||||||
|
|
||||||
|
return documentFragment.body.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function protectTranslationTokens(
|
||||||
|
input: string,
|
||||||
|
options?: { isHtml?: boolean; protectedTerms?: string[] },
|
||||||
|
): ProtectedTranslationTokens {
|
||||||
|
const replacements = new Map<string, string>();
|
||||||
|
let output = String(input ?? "");
|
||||||
|
|
||||||
|
if (options?.isHtml) {
|
||||||
|
output = protectExcludedHtmlBlocks(output, replacements);
|
||||||
|
}
|
||||||
|
|
||||||
|
output = protectMatches(
|
||||||
|
output,
|
||||||
|
/https?:\/\/[^\s"'<>]+/gi,
|
||||||
|
replacements,
|
||||||
|
"URL",
|
||||||
|
);
|
||||||
|
output = protectMatches(
|
||||||
|
output,
|
||||||
|
/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,
|
||||||
|
replacements,
|
||||||
|
"EMAIL",
|
||||||
|
);
|
||||||
|
output = protectMatches(
|
||||||
|
output,
|
||||||
|
/\{\{[^{}]+\}\}|\{[a-zA-Z0-9_.-]+\}|%(\d+\$)?[sd]|:[a-zA-Z_][a-zA-Z0-9_]*/g,
|
||||||
|
replacements,
|
||||||
|
"TOKEN",
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const term of collectProtectedTerms(options?.protectedTerms)) {
|
||||||
|
const escapedTerm = escapeRegExp(term);
|
||||||
|
const pattern = new RegExp(`(^|[^\\p{L}\\p{N}])(${escapedTerm})(?=$|[^\\p{L}\\p{N}])`, "giu");
|
||||||
|
|
||||||
|
output = output.replace(pattern, (match, prefix, protectedValue) => {
|
||||||
|
const placeholder = createPlaceholder("TERM", replacements.size);
|
||||||
|
replacements.set(placeholder, protectedValue);
|
||||||
|
return `${prefix}${placeholder}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { text: output, replacements };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function restoreTranslationTokens(
|
||||||
|
input: string,
|
||||||
|
replacements: Map<string, string>,
|
||||||
|
): string {
|
||||||
|
let output = String(input ?? "");
|
||||||
|
|
||||||
|
for (const [placeholder, original] of replacements.entries()) {
|
||||||
|
output = output.split(placeholder).join(original);
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTranslationPayloadHealth(
|
||||||
|
input: string,
|
||||||
|
options?: { isHtml?: boolean; protectedTerms?: string[] },
|
||||||
|
): TranslationPayloadHealth {
|
||||||
|
const source = String(input ?? "");
|
||||||
|
if (!source.trim()) {
|
||||||
|
return {
|
||||||
|
shouldTranslate: false,
|
||||||
|
normalizedText: source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options?.isHtml && typeof window !== "undefined") {
|
||||||
|
const documentFragment = new DOMParser().parseFromString(source, "text/html");
|
||||||
|
const walker = document.createTreeWalker(
|
||||||
|
documentFragment.body,
|
||||||
|
NodeFilter.SHOW_TEXT,
|
||||||
|
{
|
||||||
|
acceptNode(node) {
|
||||||
|
return isSkippableTextNode(node as Text)
|
||||||
|
? NodeFilter.FILTER_REJECT
|
||||||
|
: NodeFilter.FILTER_ACCEPT;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!walker.nextNode()) {
|
||||||
|
return {
|
||||||
|
shouldTranslate: false,
|
||||||
|
normalizedText: source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const protectedPayload = protectTranslationTokens(source, options);
|
||||||
|
const remainder = protectedPayload.text
|
||||||
|
.replace(TRANSLATION_PLACEHOLDER_PATTERN, "")
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
if (!remainder) {
|
||||||
|
return {
|
||||||
|
shouldTranslate: false,
|
||||||
|
normalizedText: source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasLetters = /[\p{L}]/u.test(remainder);
|
||||||
|
if (!hasLetters) {
|
||||||
|
return {
|
||||||
|
shouldTranslate: false,
|
||||||
|
normalizedText: source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
shouldTranslate: true,
|
||||||
|
normalizedText: source,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sanitizeTranslatedHtml(html: string): string {
|
||||||
|
if (typeof window === "undefined" || !html) return "";
|
||||||
|
|
||||||
|
const documentFragment = new DOMParser().parseFromString(String(html), "text/html");
|
||||||
|
documentFragment.querySelectorAll(apiUnsafeNodes).forEach((node) => node.remove());
|
||||||
|
|
||||||
|
documentFragment.querySelectorAll("*").forEach((node) => {
|
||||||
|
for (const attribute of Array.from(node.attributes)) {
|
||||||
|
const name = attribute.name.toLowerCase();
|
||||||
|
const value = attribute.value.trim().toLowerCase();
|
||||||
|
|
||||||
|
if (
|
||||||
|
name.startsWith("on") ||
|
||||||
|
value.startsWith("javascript:") ||
|
||||||
|
value.startsWith("data:text/html") ||
|
||||||
|
value.startsWith("vbscript:")
|
||||||
|
) {
|
||||||
|
node.removeAttribute(attribute.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return documentFragment.body.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSkippableTextNode(node: Text): boolean {
|
||||||
|
const parent = node.parentElement;
|
||||||
|
const value = node.textContent ?? "";
|
||||||
|
|
||||||
|
if (!value.trim()) return true;
|
||||||
|
if (!parent) return true;
|
||||||
|
if (parent.closest(excludedTranslationNodes)) return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBatchPayload(values: string[]): {
|
||||||
|
payload: string;
|
||||||
|
} {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return {
|
||||||
|
payload: values.join(" "),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const documentFragment = document.implementation.createHTMLDocument("");
|
||||||
|
const root = documentFragment.createElement("div");
|
||||||
|
root.setAttribute(HTML_BATCH_ROOT_ATTR, "1");
|
||||||
|
|
||||||
|
values.forEach((value, index) => {
|
||||||
|
const node = documentFragment.createElement("span");
|
||||||
|
node.setAttribute(HTML_BATCH_NODE_ATTR, String(index));
|
||||||
|
node.textContent = value;
|
||||||
|
root.appendChild(node);
|
||||||
|
});
|
||||||
|
|
||||||
|
documentFragment.body.appendChild(root);
|
||||||
|
|
||||||
|
return { payload: root.outerHTML };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBatchResponse(
|
||||||
|
translated: string,
|
||||||
|
originalValues: string[],
|
||||||
|
): string[] {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return originalValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
const documentFragment = new DOMParser().parseFromString(translated, "text/html");
|
||||||
|
const root = documentFragment.body.querySelector(`[${HTML_BATCH_ROOT_ATTR}]`);
|
||||||
|
if (!root) {
|
||||||
|
return originalValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodes = Array.from(root.querySelectorAll(`[${HTML_BATCH_NODE_ATTR}]`));
|
||||||
|
if (nodes.length !== originalValues.length) {
|
||||||
|
return originalValues;
|
||||||
|
}
|
||||||
|
|
||||||
|
return originalValues.map((originalValue, index) => {
|
||||||
|
const node = nodes.find(
|
||||||
|
(candidate) => candidate.getAttribute(HTML_BATCH_NODE_ATTR) === String(index),
|
||||||
|
);
|
||||||
|
|
||||||
|
return node?.textContent?.trim() ? node.textContent : originalValue;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTextBatches(nodes: Text[]): Text[][] {
|
||||||
|
const batches: Text[][] = [];
|
||||||
|
let currentBatch: Text[] = [];
|
||||||
|
let currentLength = 0;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
const textLength = (node.textContent ?? "").length;
|
||||||
|
const shouldFlush =
|
||||||
|
currentBatch.length >= BATCH_MAX_ITEMS ||
|
||||||
|
currentLength + textLength > BATCH_MAX_CHARS;
|
||||||
|
|
||||||
|
if (shouldFlush && currentBatch.length > 0) {
|
||||||
|
batches.push(currentBatch);
|
||||||
|
currentBatch = [];
|
||||||
|
currentLength = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentBatch.push(node);
|
||||||
|
currentLength += textLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentBatch.length > 0) {
|
||||||
|
batches.push(currentBatch);
|
||||||
|
}
|
||||||
|
|
||||||
|
return batches;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function translateHtmlByTextNodes(params: {
|
||||||
|
html: string;
|
||||||
|
protectedTerms?: string[];
|
||||||
|
translateText: (text: string, options?: { protectedTerms?: string[]; isHtml?: boolean }) => Promise<string>;
|
||||||
|
}): Promise<string> {
|
||||||
|
if (typeof window === "undefined" || !params.html.trim()) {
|
||||||
|
return params.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
const documentFragment = new DOMParser().parseFromString(params.html, "text/html");
|
||||||
|
const walker = document.createTreeWalker(
|
||||||
|
documentFragment.body,
|
||||||
|
NodeFilter.SHOW_TEXT,
|
||||||
|
{
|
||||||
|
acceptNode(node) {
|
||||||
|
return isSkippableTextNode(node as Text)
|
||||||
|
? NodeFilter.FILTER_REJECT
|
||||||
|
: NodeFilter.FILTER_ACCEPT;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const textNodes: Text[] = [];
|
||||||
|
let currentNode = walker.nextNode();
|
||||||
|
while (currentNode) {
|
||||||
|
textNodes.push(currentNode as Text);
|
||||||
|
currentNode = walker.nextNode();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (textNodes.length === 0) {
|
||||||
|
return sanitizeTranslatedHtml(documentFragment.body.innerHTML);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const batch of buildTextBatches(textNodes)) {
|
||||||
|
const originalValues = batch.map((node) => node.textContent ?? "");
|
||||||
|
const { payload } = createBatchPayload(originalValues);
|
||||||
|
const translatedPayload = await params.translateText(payload, {
|
||||||
|
protectedTerms: params.protectedTerms,
|
||||||
|
isHtml: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const translatedValues = parseBatchResponse(translatedPayload, originalValues);
|
||||||
|
|
||||||
|
batch.forEach((node, index) => {
|
||||||
|
node.textContent = translatedValues[index];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return sanitizeTranslatedHtml(documentFragment.body.innerHTML);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use App\Http\Controllers\Api\TranslationApiController;
|
||||||
use App\Http\Controllers\Api\V1\HomeController;
|
use App\Http\Controllers\Api\V1\HomeController;
|
||||||
use App\Http\Controllers\Api\V1\InterestRequestController;
|
use App\Http\Controllers\Api\V1\InterestRequestController;
|
||||||
use App\Http\Controllers\Api\V1\LegislationSourceController;
|
use App\Http\Controllers\Api\V1\LegislationSourceController;
|
||||||
@@ -17,6 +18,9 @@ use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
|||||||
use App\Services\SimulationPublishedFiscal;
|
use App\Services\SimulationPublishedFiscal;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
Route::get('translate/languages', [TranslationApiController::class, 'languages'])->middleware('throttle:60,1');
|
||||||
|
Route::post('translate', [TranslationApiController::class, 'translate'])->middleware('throttle:120,1');
|
||||||
|
|
||||||
Route::prefix('v1')->middleware(['throttle:api', CorrelationId::class])->group(function () {
|
Route::prefix('v1')->middleware(['throttle:api', CorrelationId::class])->group(function () {
|
||||||
Route::get('/catalogs/{catalog}', [ReferenceCatalogController::class, 'index'])
|
Route::get('/catalogs/{catalog}', [ReferenceCatalogController::class, 'index'])
|
||||||
->whereIn('catalog', ['authorities', 'jurisdictions', 'economic-activities', 'countries']);
|
->whereIn('catalog', ['authorities', 'jurisdictions', 'economic-activities', 'countries']);
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ Route::get('/artigos/{id}', [\App\Http\Controllers\EditorialArticleController::c
|
|||||||
Route::get('/carteira', [InvestmentPortfolioController::class, 'index'])->name('portfolio.index');
|
Route::get('/carteira', [InvestmentPortfolioController::class, 'index'])->name('portfolio.index');
|
||||||
Route::get('/carteira/{id}', [InvestmentPortfolioController::class, 'show'])->whereUuid('id')->name('portfolio.show');
|
Route::get('/carteira/{id}', [InvestmentPortfolioController::class, 'show'])->whereUuid('id')->name('portfolio.show');
|
||||||
Route::get('/carteira/{id}/interesse', [InvestmentPortfolioController::class, 'resumeInterest'])->whereUuid('id')->middleware(['auth', \App\Http\Middleware\VerifiedOrSimpleParticipation::class])->name('portfolio.interest');
|
Route::get('/carteira/{id}/interesse', [InvestmentPortfolioController::class, 'resumeInterest'])->whereUuid('id')->middleware(['auth', \App\Http\Middleware\VerifiedOrSimpleParticipation::class])->name('portfolio.interest');
|
||||||
|
Route::get('/pesquisa', \App\Http\Controllers\GlobalSearchController::class)->name('portal.search');
|
||||||
Route::get('/oportunidades', [InvestmentDiscoveryController::class, 'index'])->name('portal.opportunities');
|
Route::get('/oportunidades', [InvestmentDiscoveryController::class, 'index'])->name('portal.opportunities');
|
||||||
Route::get('/oportunidades/{slug}', [InvestmentDiscoveryController::class, 'detail'])->name('portal.opportunity');
|
Route::get('/oportunidades/{slug}', [InvestmentDiscoveryController::class, 'detail'])->name('portal.opportunity');
|
||||||
Route::get('/negocios', [PublicBusinessOpportunityController::class, 'index'])->name('business-marketplace.index');
|
Route::get('/negocios', [PublicBusinessOpportunityController::class, 'index'])->name('business-marketplace.index');
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use App\Http\Controllers\InvestmentPortfolioController;
|
||||||
|
use App\Services\FederatedSearch;
|
||||||
|
use Illuminate\Database\QueryException;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
final class GlobalSearchTest extends TestCase
|
||||||
|
{
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->withoutVite();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_empty_and_overlong_queries(): void
|
||||||
|
{
|
||||||
|
$this->get('/pesquisa')->assertOk()->assertInertia(fn (Assert $page) => $page->component('portal/search')->where('results.total', 0));
|
||||||
|
$this->get('/pesquisa?q='.str_repeat('a', 121))->assertSessionHasErrors('q');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_source_failure_recalculates_the_page_without_hiding_the_other_results(): void
|
||||||
|
{
|
||||||
|
$sources = [
|
||||||
|
'Documentos' => fn () => ['count' => 1, 'fetch' => fn () => throw new QueryException('testing', 'select 1', [], new \RuntimeException('Source unavailable'))],
|
||||||
|
'Páginas' => fn () => ['count' => 1, 'fetch' => fn ($offset, $limit) => array_slice([['title' => 'Como investir', 'url' => '/como-investir']], $offset, $limit)],
|
||||||
|
];
|
||||||
|
$result = app(FederatedSearch::class)->page($sources, 1);
|
||||||
|
$this->assertSame(1, $result['total']);
|
||||||
|
$this->assertSame(['Documentos'], $result['unavailable']);
|
||||||
|
$this->assertSame('Como investir', $result['data'][0]['title']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_public_search_uses_the_existing_portfolio_visibility_scope(): void
|
||||||
|
{
|
||||||
|
if (getenv('GLOBAL_SEARCH_QA') !== '1') {
|
||||||
|
$this->markTestSkipped('A prova com dados exige a base QA explicitamente seleccionada.');
|
||||||
|
}
|
||||||
|
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||||
|
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
|
||||||
|
$this->assertSame(55441, (int) $identity->port);
|
||||||
|
$record = InvestmentPortfolioController::visible()->first();
|
||||||
|
if (! $record) {
|
||||||
|
$this->markTestSkipped('No published portfolio records in isolated QA.');
|
||||||
|
}
|
||||||
|
$term = mb_substr($record->title, 0, 15);
|
||||||
|
$this->get('/pesquisa?q='.urlencode($term))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||||
|
->component('portal/search')->where('query', $term)
|
||||||
|
->where('results.total', fn ($total) => $total >= 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\CorridorAgribusinessOpportunities;
|
||||||
|
use App\Services\InvestmentGeography;
|
||||||
|
use App\Support\IsolatedQaDatabase;
|
||||||
|
use Illuminate\Foundation\Application;
|
||||||
|
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Inertia\Testing\AssertableInertia;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class ProvinceSearchCompatibilityTest extends TestCase
|
||||||
|
{
|
||||||
|
use DatabaseTransactions;
|
||||||
|
|
||||||
|
public function createApplication(): Application
|
||||||
|
{
|
||||||
|
$app = parent::createApplication();
|
||||||
|
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||||
|
throw new \LogicException('Isolated QA required');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $app;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->withoutVite();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function createOpportunity(?string $territory, string $prefix, string $status = 'published', ?string $province = null): Opportunity
|
||||||
|
{
|
||||||
|
return Opportunity::create(['sector_id' => 1, 'reference' => 'SYNTHETIC-QA-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(),
|
||||||
|
'title' => $prefix.' synthetic provincial search', 'status' => $status, 'published_at' => now()->subMinute(),
|
||||||
|
'primary_territory_id' => $territory, 'province' => $province, 'district' => null, 'geography_scope' => 'specific']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function requests(array $filters): array
|
||||||
|
{
|
||||||
|
$query = http_build_query([...$filters, 'per_page' => 50]);
|
||||||
|
|
||||||
|
return ['/api/v1/investment/search?'.$query, '/api/v1/opportunities/search?'.$query];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_a_single_province_includes_all_lower_levels_and_linked_locations_in_both_apis(): void
|
||||||
|
{
|
||||||
|
$geo = app(InvestmentGeography::class);
|
||||||
|
$locality = $geo->publicReferences()->where('location_type', 'locality')->orderBy('id')->first();
|
||||||
|
$this->assertNotNull($locality, 'Public locality fixture required');
|
||||||
|
$path = $geo->path($locality->id);
|
||||||
|
$this->assertCount(4, $path);
|
||||||
|
$prefix = 'SYNTHETIC-'.Str::uuid();
|
||||||
|
$records = array_map(fn ($node) => $this->createOpportunity($node->id, $prefix, 'published', 'Legacy label differs from canonical hierarchy'), $path);
|
||||||
|
$linked = $this->createOpportunity(null, $prefix);
|
||||||
|
$linked->additionalTerritories()->attach($locality->id);
|
||||||
|
$records[] = $linked;
|
||||||
|
$private = $this->createOpportunity($locality->id, $prefix, 'draft');
|
||||||
|
$deleted = $this->createOpportunity($locality->id, $prefix);
|
||||||
|
$deleted->delete();
|
||||||
|
$otherProvince = $geo->publicReferences()->where('location_type', 'province')->where('id', '<>', $path[0]->id)->first();
|
||||||
|
$outside = $this->createOpportunity($otherProvince->id, $prefix);
|
||||||
|
foreach ([['province_id' => $path[0]->id], ['province' => $path[0]->name], ['geo_location_id' => $path[0]->id]] as $entry) {
|
||||||
|
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
|
||||||
|
$response = $this->getJson($url)->assertOk()->assertJsonPath('total', 5);
|
||||||
|
$this->assertEqualsCanonicalizing(array_map(fn ($row) => $row->id, $records), array_column($response->json('data'), 'id'), $url);
|
||||||
|
foreach ($response->json('data') as $row) {
|
||||||
|
$this->assertNull($row['district']);
|
||||||
|
}
|
||||||
|
foreach ([$private, $deleted, $outside] as $row) {
|
||||||
|
$this->assertNotContains($row->id, array_column($response->json('data'), 'id'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($records as $record) {
|
||||||
|
$this->assertNull($record->fresh()->district);
|
||||||
|
$this->assertSame($record->primary_territory_id, $record->fresh()->primary_territory_id);
|
||||||
|
}
|
||||||
|
$this->assertSame([$locality->id], $linked->additionalTerritories()->pluck('geo_locations.id')->all());
|
||||||
|
foreach ($this->requests(['province_id' => $path[0]->id, 'district_id' => $path[1]->id, 'q' => $prefix]) as $url) {
|
||||||
|
// Province-only records are not silently assigned to a district.
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('total', 4);
|
||||||
|
}
|
||||||
|
foreach ($this->requests(['district_id' => $path[1]->id]) as $url) {
|
||||||
|
$this->getJson($url)->assertUnprocessable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_published_province_declaration_is_found_without_inventing_a_district_or_overriding_an_explicit_other_territory(): void
|
||||||
|
{
|
||||||
|
$geo = app(InvestmentGeography::class);
|
||||||
|
$province = $geo->publicReferences()->where('location_type', 'province')->first();
|
||||||
|
$other = $geo->publicReferences()->where('location_type', 'province')->where('id', '<>', $province->id)->first();
|
||||||
|
$district = $geo->publicReferences()->where('parent_id', $province->id)->where('location_type', 'district')->first();
|
||||||
|
$prefix = 'SYNTHETIC-'.Str::uuid();
|
||||||
|
$legacy = $this->createOpportunity(null, $prefix, 'published', $province->name);
|
||||||
|
$contradictory = $this->createOpportunity($other->id, $prefix, 'published', $province->name);
|
||||||
|
$linkedOutside = $this->createOpportunity(null, $prefix, 'published', $province->name);
|
||||||
|
$linkedOutside->additionalTerritories()->attach($other->id);
|
||||||
|
foreach ([['province' => $province->name], ['province_id' => $province->id], ['geo_location_id' => $province->id]] as $entry) {
|
||||||
|
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $legacy->id)->assertJsonPath('data.0.district', null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($this->requests(['province_id' => $province->id, 'district_id' => $district->id, 'q' => $prefix]) as $url) {
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('total', 0);
|
||||||
|
}
|
||||||
|
$this->assertNull($legacy->fresh()->primary_territory_id);
|
||||||
|
$this->assertNull($legacy->fresh()->district);
|
||||||
|
$this->assertSame($other->id, $contradictory->fresh()->primary_territory_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_provincial_only_search_covers_the_eleven_provinces_without_including_neighbouring_provinces(): void
|
||||||
|
{
|
||||||
|
$geo = app(InvestmentGeography::class);
|
||||||
|
$provinces = $geo->publicReferences()->where('location_type', 'province')->get();
|
||||||
|
$this->assertCount(11, $provinces);
|
||||||
|
$prefix = 'SYNTHETIC-'.Str::uuid();
|
||||||
|
$records = [];
|
||||||
|
foreach ($provinces as $province) {
|
||||||
|
$district = $geo->publicReferences()->where('parent_id', $province->id)->where('location_type', 'district')->first();
|
||||||
|
$this->assertNotNull($district, $province->name);
|
||||||
|
$records[$province->id] = $this->createOpportunity($district->id, $prefix);
|
||||||
|
}
|
||||||
|
foreach ($provinces as $province) {
|
||||||
|
foreach ([['province_id' => $province->id], ['province' => $province->name]] as $entry) {
|
||||||
|
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
|
||||||
|
$this->getJson($url)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $records[$province->id]->id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_maputo_names_ids_page_map_and_export_share_the_existing_approved_corridor_coverage(): void
|
||||||
|
{
|
||||||
|
$provinceId = 'bfde2651-2b46-5d9c-a500-733fa55a8c5c';
|
||||||
|
$expected = Opportunity::published()->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||||
|
->where('workflow_context->corridor_agribusiness->corridor', 'Corredor de Maputo')->pluck('id')->all();
|
||||||
|
$this->assertCount(5, $expected);
|
||||||
|
foreach ([['province' => 'Maputo Província'], ['province' => ' mApUtO Província '], ['province_id' => $provinceId]] as $entry) {
|
||||||
|
foreach ($this->requests([...$entry, 'sector' => 'agronegocio']) as $url) {
|
||||||
|
$response = $this->getJson($url)->assertOk()->assertJsonPath('total', 5);
|
||||||
|
$this->assertEqualsCanonicalizing($expected, array_column($response->json('data'), 'id'));
|
||||||
|
foreach ($response->json('data') as $row) {
|
||||||
|
$this->assertNull($row['district']);
|
||||||
|
$this->assertStringContainsString('contexto provincial do corredor', $row['territorial_summary']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$query = http_build_query(['sector' => 'agronegocio', 'province' => 'Maputo Província']);
|
||||||
|
$this->get('/oportunidades?'.$query)->assertInertia(fn (AssertableInertia $page) => $page
|
||||||
|
->component('investment/catalogue')->where('filters.province_id', $provinceId)->missing('filters.province')
|
||||||
|
->has('territorySelection', 1)->where('results.total', 5));
|
||||||
|
$this->getJson('/api/v1/investment/map?'.$query)->assertOk()->assertJsonCount(0, 'features')->assertJsonCount(5, 'unlocated');
|
||||||
|
$csv = $this->get('/api/v1/investment/export?'.$query)->assertOk()->streamedContent();
|
||||||
|
foreach (Opportunity::whereIn('id', $expected)->get() as $row) {
|
||||||
|
$this->assertStringContainsString($row->title, $csv);
|
||||||
|
}
|
||||||
|
foreach ($this->requests(['sector' => 'turismo', 'province_id' => $provinceId]) as $url) {
|
||||||
|
$response = $this->getJson($url)->assertOk();
|
||||||
|
foreach ($response->json('data') as $row) {
|
||||||
|
$this->assertNotContains($row['id'], $expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class TranslationApiTest extends TestCase
|
||||||
|
{
|
||||||
|
public function test_it_lists_languages_from_the_configured_engine(): void
|
||||||
|
{
|
||||||
|
config(['services.translation.url' => 'http://translator.test']);
|
||||||
|
Http::fake(['translator.test/languages' => Http::response([['code' => 'pt', 'name' => 'Portuguese', 'targets' => ['en']]])]);
|
||||||
|
|
||||||
|
$this->getJson('/api/translate/languages')->assertOk()->assertJsonPath('0.targets.0', 'en');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_it_translates_and_reports_engine_failures(): void
|
||||||
|
{
|
||||||
|
config(['services.translation.url' => 'http://translator.test']);
|
||||||
|
Http::fake(['translator.test/translate' => Http::sequence()->push(['translatedText' => 'Hello'])->push([], 500)]);
|
||||||
|
$input = ['text' => 'Olá', 'source_lang' => 'pt', 'target_lang' => 'en'];
|
||||||
|
|
||||||
|
$this->postJson('/api/translate', $input)->assertOk()->assertJsonPath('translated_text', 'Hello');
|
||||||
|
$this->postJson('/api/translate', $input)->assertStatus(503);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit;
|
||||||
|
|
||||||
|
use App\Services\FederatedSearch;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class FederatedSearchTest extends TestCase
|
||||||
|
{
|
||||||
|
public function test_global_pagination_spans_sources_without_loading_the_complete_sets(): void
|
||||||
|
{
|
||||||
|
$calls = [];
|
||||||
|
$factory = function (string $prefix, int $count) use (&$calls) {
|
||||||
|
return function () use (&$calls, $prefix, $count) {
|
||||||
|
return ['count' => $count, 'fetch' => function ($offset, $limit) use (&$calls, $prefix, $count) {
|
||||||
|
$calls[] = [$prefix, $offset, $limit];
|
||||||
|
|
||||||
|
return array_map(fn ($i) => ['title' => $prefix.$i, 'url' => '/'.$prefix.$i], array_slice(range(1, $count), $offset, $limit));
|
||||||
|
}];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
$sources = ['Páginas' => $factory('p', 3), 'Oportunidades' => $factory('o', 7), 'Documentos' => $factory('d', 2)];
|
||||||
|
$service = new FederatedSearch;
|
||||||
|
$first = $service->page($sources, 1);
|
||||||
|
$this->assertSame(['p1', 'p2', 'p3', 'o1', 'o2'], array_column($first['data'], 'title'));
|
||||||
|
$this->assertSame(['Páginas', 'Páginas', 'Páginas', 'Oportunidades', 'Oportunidades'], array_column($first['data'], 'category'));
|
||||||
|
$this->assertSame(12, $first['total']);
|
||||||
|
$this->assertSame(3, $first['last_page']);
|
||||||
|
$calls = [];
|
||||||
|
$second = $service->page($sources, 2);
|
||||||
|
$this->assertSame(['o3', 'o4', 'o5', 'o6', 'o7'], array_column($second['data'], 'title'));
|
||||||
|
$this->assertSame([['p', 0, 5], ['o', 0, 5], ['d', 0, 5], ['o', 5, 5]], $calls);
|
||||||
|
$third = $service->page($sources, 99);
|
||||||
|
$this->assertSame(3, $third['current_page']);
|
||||||
|
$this->assertSame(['d1', 'd2'], array_column($third['data'], 'title'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_more_relevant_titles_appear_first_across_sources(): void
|
||||||
|
{
|
||||||
|
$factories = [
|
||||||
|
'Serviços' => fn () => ['count' => 1, 'fetch' => fn ($offset, $limit) => array_slice([['title' => 'Informação', 'url' => '/info', 'score' => 10]], $offset, $limit)],
|
||||||
|
'Sectores' => fn () => ['count' => 1, 'fetch' => fn ($offset, $limit) => array_slice([['title' => 'Sectores', 'url' => '/sectores', 'score' => 100]], $offset, $limit)],
|
||||||
|
];
|
||||||
|
$result = (new FederatedSearch)->page($factories, 1, 5, fn ($item) => $item['score']);
|
||||||
|
$this->assertSame(['Sectores', 'Informação'], array_column($result['data'], 'title'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Unit;
|
||||||
|
|
||||||
|
use App\Http\Controllers\GlobalSearchController;
|
||||||
|
use App\Services\SearchTerms;
|
||||||
|
use Illuminate\Database\PostgresConnection;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class SearchTermsTest extends TestCase
|
||||||
|
{
|
||||||
|
public function test_matches_all_words_in_any_order_without_case_or_accents(): void
|
||||||
|
{
|
||||||
|
$search = new SearchTerms;
|
||||||
|
$tokens = $search->tokens(' NAMPULA agronegócio Agronegócio ');
|
||||||
|
|
||||||
|
$this->assertSame(['nampula', 'agronegocio'], $tokens);
|
||||||
|
$this->assertTrue($search->matches('Agronegócio em Nampula', $tokens));
|
||||||
|
$this->assertFalse($search->matches('Agronegócio em Gaza', $tokens));
|
||||||
|
$this->assertSame([], $search->tokens(' '));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_sql_matches_each_word_across_fields_with_bound_literal_patterns(): void
|
||||||
|
{
|
||||||
|
$connection = new PostgresConnection(fn () => throw new \LogicException('A database must not be opened.'));
|
||||||
|
$query = $connection->table('records');
|
||||||
|
$search = new SearchTerms;
|
||||||
|
$search->constrain($query, ['title', 'description'], $search->tokens('100% a_b'));
|
||||||
|
|
||||||
|
$sql = $query->toSql();
|
||||||
|
$this->assertStringContainsString('translate(lower(coalesce(title::text', $sql);
|
||||||
|
$this->assertStringContainsString(' or ', $sql);
|
||||||
|
$this->assertStringContainsString(' and ', $sql);
|
||||||
|
$this->assertSame(['%100!%%', '%100!%%', '%a!_b%', '%a!_b%'], $query->getBindings());
|
||||||
|
$this->assertStringNotContainsString('100%', $sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_static_services_can_be_found_without_a_database(): void
|
||||||
|
{
|
||||||
|
$pages = (new \ReflectionMethod(GlobalSearchController::class, 'pages'))->invoke(new GlobalSearchController);
|
||||||
|
$search = new SearchTerms;
|
||||||
|
$matches = array_values(array_filter($pages, fn ($page) => $search->matches(implode(' ', $page), $search->tokens('FISCAL simulador'))));
|
||||||
|
|
||||||
|
$this->assertCount(1, $matches);
|
||||||
|
$this->assertSame('/simulador-fiscal', $matches[0]['url']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_spelling_variants_common_words_and_title_relevance(): void
|
||||||
|
{
|
||||||
|
$search = new SearchTerms;
|
||||||
|
$tokens = $search->tokens('setores de investimento');
|
||||||
|
$this->assertTrue($search->matches('Sectores de investimento', $tokens));
|
||||||
|
$this->assertFalse($search->matches('Sector de saúde', $tokens));
|
||||||
|
$this->assertTrue($search->matches('Projectos âncora', $search->tokens('projeto')));
|
||||||
|
$this->assertTrue($search->matches('Oportunidades de investimento em energia', $search->tokens('Como investir em energia?')));
|
||||||
|
$this->assertGreaterThan($search->score('Como investir', 'investir', ['investir']), $search->score('Investir', 'investir', ['investir']));
|
||||||
|
$this->assertSame(['de'], $search->tokens('de'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ const require=createRequire(import.meta.url);
|
|||||||
const source=fs.readFileSync(new URL('../../resources/js/pages/portal/fiscal-forms.tsx',import.meta.url),'utf8');
|
const source=fs.readFileSync(new URL('../../resources/js/pages/portal/fiscal-forms.tsx',import.meta.url),'utf8');
|
||||||
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
|
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
|
||||||
const module={exports:{}};
|
const module={exports:{}};
|
||||||
new Function('require','module','exports',compiled)(name=>name==='@inertiajs/react'?{Head:()=>null,Link:({href,children,...props})=>React.createElement('a',{href,...props},children),router:{on:()=>()=>{}}}:name==='@/layouts/portal-navigation'?{PortalMenu:()=>null}:name==='@/lib/fiscal-form-preparation'?forms:require(name),module,module.exports);
|
new Function('require','module','exports',compiled)(name=>name==='@inertiajs/react'?{Head:()=>null,Link:({href,children,...props})=>React.createElement('a',{href,...props},children),router:{on:()=>()=>{}}}:name==='@/components/portal-menu'?{PortalMenu:()=>null}:name==='@/lib/fiscal-form-preparation'?forms:require(name),module,module.exports);
|
||||||
test('fiscal entry renders labelled editable fields and a guided preparation rather than legislation',()=>{
|
test('fiscal entry renders labelled editable fields and a guided preparation rather than legislation',()=>{
|
||||||
const html=renderToStaticMarkup(React.createElement(module.exports.default));
|
const html=renderToStaticMarkup(React.createElement(module.exports.default));
|
||||||
for(const label of ['Identificação e período','Nome ou designação social','NUIT','Período — ano e mês','Conferir e guardar','Guardar ficheiro para continuar','Recuperar ficheiro guardado','Confirmar recuperação']) {
|
for(const label of ['Identificação e período','Nome ou designação social','NUIT','Período — ano e mês','Conferir e guardar','Guardar ficheiro para continuar','Recuperar ficheiro guardado','Confirmar recuperação']) {
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import ts from 'typescript';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const source = fs.readFileSync(new URL('../../resources/js/pages/portal/search.tsx', import.meta.url), 'utf8');
|
||||||
|
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX } }).outputText;
|
||||||
|
const module = { exports: {} };
|
||||||
|
new Function('require', 'module', 'exports', compiled)(name => name === '@inertiajs/react' ? {
|
||||||
|
Head: () => null,
|
||||||
|
Link: ({ href, children, ...props }) => React.createElement('a', { href, ...props }, children),
|
||||||
|
} : name === 'lucide-react' ? { Search: () => null } : require(name), module, module.exports);
|
||||||
|
const Search = module.exports.default;
|
||||||
|
|
||||||
|
test('shows five results in one sequence with numbered pagination and the query preserved', () => {
|
||||||
|
const results = { data: [{ title: 'Energia em Nampula', description: 'Projecto público', url: '/oportunidades/energia', category: 'Oportunidades' }], total: 12, current_page: 1, last_page: 3, per_page: 5, unavailable: [] };
|
||||||
|
const html = renderToStaticMarkup(React.createElement(Search, { query: 'energia', results }));
|
||||||
|
assert.match(html, /Oportunidades/);
|
||||||
|
assert.match(html, /Resultados 1–1 de 12/);
|
||||||
|
assert.match(html, /href="\/oportunidades\/energia"/);
|
||||||
|
assert.match(html, /q=energia&page=2/);
|
||||||
|
assert.match(html, /aria-current="page"/);
|
||||||
|
assert.doesNotMatch(html, /emerald/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('makes source failures explicit without hiding other results', () => {
|
||||||
|
const results = { data: [], total: 0, current_page: 1, last_page: 1, per_page: 5, unavailable: ['Documentos e legislação'] };
|
||||||
|
const html = renderToStaticMarkup(React.createElement(Search, { query: 'terra', results }));
|
||||||
|
assert.match(html, /role="alert"/);
|
||||||
|
assert.match(html, /Não foi possível consultar: Documentos e legislação/);
|
||||||
|
assert.match(html, /Nenhum resultado nas fontes consultadas/);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user