Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5756c0282 | ||
|
|
bf2c054943 | ||
|
|
f3455432cf | ||
|
|
4b3c7e161f | ||
|
|
3a3aba5026 | ||
|
|
fde7343894 | ||
|
|
e0987afb0e | ||
|
|
bad05eb092 | ||
|
|
b2812e5925 | ||
|
|
fdadc8ace7 | ||
|
|
979f3f850e | ||
|
|
b81f477bf2 | ||
|
|
568a488ae7 | ||
|
|
d96f9c6bf5 | ||
|
|
4875c4beb9 | ||
|
|
3f7082a3e6 | ||
|
|
23ecccfaad | ||
|
|
996b5b08cd | ||
|
|
332c16ebb5 | ||
|
|
17444aaaa5 | ||
|
|
789fffd098 | ||
|
|
502e3ec4d5 | ||
|
|
54d1b2a543 | ||
|
|
6520d303f7 | ||
|
|
47dae1b77e | ||
|
|
2c8eb95e10 | ||
|
|
1b2ede41e2 | ||
|
|
d7a9284d5f | ||
|
|
6e8de43ae7 |
@@ -119,3 +119,8 @@ INVESTMOZ_TAX_RULE_APPROVERS=
|
||||
INVESTMOZ_TAX_RULE_PUBLISHERS=
|
||||
|
||||
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\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\SectorOrganization;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -15,6 +18,11 @@ class OpportunityController extends Controller
|
||||
'q' => ['nullable', 'string', 'max:120'],
|
||||
'sector' => ['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'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||
@@ -47,22 +55,24 @@ class OpportunityController extends Controller
|
||||
|
||||
if (! empty($validated['sector'])) {
|
||||
$sector = $validated['sector'];
|
||||
\App\Services\SectorOrganization::constrain($query, $sector);
|
||||
SectorOrganization::constrain($query, $sector);
|
||||
}
|
||||
|
||||
if (! empty($validated['province'])) {
|
||||
$query->where('province', $validated['province']);
|
||||
$territory = array_intersect_key($validated, array_flip(['province', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'geo_location_id']));
|
||||
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'])) {
|
||||
\App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
||||
OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
||||
}
|
||||
|
||||
$results = $query->orderByDesc('is_featured')
|
||||
->orderByDesc('published_at')
|
||||
->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
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Services\ClusterCompetitiveness;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class ClusterCompetitivenessController extends Controller
|
||||
{
|
||||
public function show(EconomicCluster $cluster, ClusterCompetitiveness $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->management($cluster->id))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function change(Request $request, EconomicCluster $cluster, string $action, ClusterCompetitiveness $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['expected_version' => 'required|integer|min:0',
|
||||
'draft' => $action === 'saved' ? 'required|array:version,clusterId,sector,region,forces' : 'prohibited',
|
||||
'revision' => $action === 'restored' ? 'required|integer|min:1' : 'prohibited',
|
||||
'reason' => in_array($action, ['approved', 'withdrawn'], true) ? 'required|string|min:10|max:3000' : 'nullable|string|max:3000']);
|
||||
|
||||
return response()->json($service->change($cluster, $request->user()->id, (int) $data['expected_version'], $action, $data))
|
||||
->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
'corridorGroups' => ($filters['view'] ?? '') === 'corridors' ? app(\App\Services\OpportunityCorridorExplorer::class)->groups($filters) : [],
|
||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||
'guides' => app(\App\Services\SectorInvestment::class)->guides(\App\Models\Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)),
|
||||
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
|
||||
'territorial' => $this->territorial($filters)]);
|
||||
}
|
||||
@@ -74,7 +74,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
|
||||
public function search(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString());
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)));
|
||||
}
|
||||
|
||||
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
|
||||
@@ -140,6 +140,7 @@ class InvestmentPortfolioController extends Controller
|
||||
|
||||
return Inertia::render('portfolio/show', ['complements' => $management ? [] : app(\App\Services\InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
|
||||
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
|
||||
'competitiveness' => $record->cluster_id ? app(\App\Services\ClusterCompetitiveness::class)->publicData($record->cluster_id) : null,
|
||||
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
|
||||
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ class InvestmentStructureController extends Controller
|
||||
->whereNull('origins.deleted_at')->whereNull('destinations.deleted_at')->whereNull('value_chain_links.deleted_at')
|
||||
->orderBy('origins.code')->orderBy('destinations.code')
|
||||
->get(['value_chain_links.id', 'origins.name as origin', 'destinations.name as destination', 'link_type']) : [],
|
||||
'competitiveness' => $structure === 'clusters' && $id ? app(\App\Services\ClusterCompetitiveness::class)->management($id) : null,
|
||||
'viewerId' => $request->user()->id,
|
||||
'memberships' => $structure === 'clusters' && $id ? DB::table('cluster_projects')
|
||||
->join('projects', 'projects.id', '=', 'cluster_projects.project_id')
|
||||
|
||||
@@ -48,13 +48,15 @@ class HandleInertiaRequests extends Middleware
|
||||
*/
|
||||
public function share(Request $request): array
|
||||
{
|
||||
$contentManagementAccess=app(\App\Services\ContentManagement::class)->access($request->user());
|
||||
return [
|
||||
...parent::share($request),
|
||||
'name' => config('app.name'),
|
||||
'procurementEnabled' => app(\App\Services\Procurement::class)->available(),
|
||||
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||
'contentManagementHref' => app(\App\Services\ContentManagement::class)->access($request->user()) !== [] ? '/gestao-conteudos' : null,
|
||||
'contentManagementHref' => $contentManagementAccess !== [] ? '/gestao-conteudos' : null,
|
||||
'contentManagementAccess'=>$contentManagementAccess,
|
||||
'portalOperator' => config('portal.operator_name'),
|
||||
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
|
||||
'legacyContentEnabled' => app(LegacyContent::class)->available(),
|
||||
@@ -83,6 +85,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
|
||||
'legacyManagementAccess' => $request->user()?->hasVerifiedEmail() && app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
|
||||
],
|
||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class ClusterCompetitiveness
|
||||
{
|
||||
public const FORCES = ['rivalry', 'entrants', 'substitutes', 'suppliers', 'buyers'];
|
||||
|
||||
public const FIELDS = ['evidence', 'source', 'period', 'rationale', 'limitations', 'opportunity'];
|
||||
|
||||
private const SOURCE = 'cluster-competitiveness';
|
||||
|
||||
private function events(string $cluster): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)
|
||||
->where('entity_type', 'economic_clusters')->where('entity_id', $cluster);
|
||||
}
|
||||
|
||||
private function decode(?object $event): array
|
||||
{
|
||||
return $event ? json_decode(Crypt::decryptString(json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['snapshot']), true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['version' => 0, 'draft' => null, 'approved' => null];
|
||||
}
|
||||
|
||||
public function current(string $cluster): array
|
||||
{
|
||||
return $this->decode($this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->first());
|
||||
}
|
||||
|
||||
public function management(string $cluster): array
|
||||
{
|
||||
$state = $this->current($cluster);
|
||||
$state['history'] = $this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->limit(50)->get()
|
||||
->map(fn ($event) => ['version' => json_decode($event->after_data, true)['version'],
|
||||
'action' => $event->action, 'at' => $event->occurred_at, 'actor' => $event->actor_user_id])->all();
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
public function validateDraft(array $draft, string $cluster): array
|
||||
{
|
||||
$rules = ['version' => 'required|integer|in:1', 'clusterId' => 'required|string|in:'.$cluster,
|
||||
'sector' => 'present|nullable|string|max:200', 'region' => 'present|nullable|string|max:1000',
|
||||
'forces' => 'required|array:'.implode(',', self::FORCES)];
|
||||
foreach (self::FORCES as $force) {
|
||||
$rules["forces.$force"] = 'required|array:pressure,'.implode(',', self::FIELDS);
|
||||
$rules["forces.$force.pressure"] = 'present|nullable|in:low,medium,high';
|
||||
foreach (self::FIELDS as $field) {
|
||||
$rules["forces.$force.$field"] = 'present|nullable|string|max:5000';
|
||||
}
|
||||
}
|
||||
$clean = Validator::make($draft, $rules)->validate();
|
||||
$clean['version'] = 1;
|
||||
$clean['sector'] = trim($clean['sector'] ?? '');
|
||||
$clean['region'] = trim($clean['region'] ?? '');
|
||||
foreach (self::FORCES as $force) {
|
||||
foreach (['pressure', ...self::FIELDS] as $field) {
|
||||
$clean['forces'][$force][$field] = trim($clean['forces'][$force][$field] ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
private function assertComplete(?array $draft): void
|
||||
{
|
||||
$missing = ! $draft || ! $draft['sector'] || ! $draft['region'];
|
||||
foreach (self::FORCES as $force) {
|
||||
$row = $draft['forces'][$force] ?? [];
|
||||
$missing = $missing || ! in_array($row['pressure'] ?? '', ['low', 'medium', 'high'], true);
|
||||
foreach (self::FIELDS as $field) {
|
||||
$missing = $missing || trim($row[$field] ?? '') === '';
|
||||
}
|
||||
}
|
||||
if ($missing) {
|
||||
throw ValidationException::withMessages(['approval' => 'Complete o âmbito e as evidências, fontes, períodos, justificação, limitações e oportunidades das cinco forças antes de aprovar.']);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reuse the portal's encrypted, append-only audit snapshots; no new schema or mutable publication fields. */
|
||||
public function change(EconomicCluster $cluster, int $actor, int $expected, string $action, array $input = []): array
|
||||
{
|
||||
return DB::transaction(function () use ($cluster, $actor, $expected, $action, $input) {
|
||||
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
|
||||
$before = $this->current($cluster->id);
|
||||
abort_if($before['version'] !== $expected, 409, 'A análise foi alterada. Conserve os campos actuais e compare a versão do servidor antes de voltar a guardar.');
|
||||
$state = $before;
|
||||
if ($action === 'saved') {
|
||||
$state['draft'] = $this->validateDraft($input['draft'], $cluster->id);
|
||||
} elseif ($action === 'restored') {
|
||||
$event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first();
|
||||
abort_unless($event, 404);
|
||||
$state['draft'] = $this->decode($event)['draft'];
|
||||
} elseif ($action === 'approved') {
|
||||
$this->assertComplete($state['draft']);
|
||||
$state['approved'] = ['draft' => $state['draft'], 'at' => now()->toISOString(), 'actor' => $actor,
|
||||
'version' => $expected + 1, 'evidence' => $input['reason']];
|
||||
} elseif ($action === 'withdrawn') {
|
||||
$state['approved'] = null;
|
||||
} else {
|
||||
throw new \LogicException('Unsupported competitiveness action');
|
||||
}
|
||||
$state['version']++;
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'economic_clusters',
|
||||
'entity_id' => $cluster->id, 'external_id' => $cluster->id.':'.$state['version'], 'actor_user_id' => $actor,
|
||||
'action' => $action, 'data_classification' => 'restricted',
|
||||
'before_data' => json_encode(['version' => $before['version']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['version' => $state['version'], 'restored_from' => $input['revision'] ?? null,
|
||||
'reason' => Crypt::encryptString($input['reason'] ?? ''),
|
||||
'snapshot' => Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->management($cluster->id);
|
||||
});
|
||||
}
|
||||
|
||||
public function publicData(string $cluster): ?array
|
||||
{
|
||||
$approved = $this->current($cluster)['approved'];
|
||||
|
||||
// Explicit projection: never return editor identity, approval evidence, history or the unapproved draft.
|
||||
return $approved ? ['draft' => $approved['draft'], 'version' => $approved['version'], 'at' => $approved['at']] : null;
|
||||
}
|
||||
}
|
||||
@@ -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\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class InvestmentCatalogue
|
||||
{
|
||||
@@ -17,8 +22,8 @@ class InvestmentCatalogue
|
||||
/** @return array<string,mixed> */
|
||||
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'],
|
||||
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||
$filters = $request->validate(['perspective' => ['nullable', 'in:exists,needs,ideas,opportunities'], 'q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
'preparation' => ['nullable', Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||
'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'],
|
||||
@@ -40,14 +45,15 @@ class InvestmentCatalogue
|
||||
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
||||
'publication_state' => ['nullable', 'in:published'],
|
||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||
app(InvestmentGeography::class)->selection($filters);
|
||||
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
||||
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
||||
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
||||
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'];
|
||||
unset($filters['association_type'], $filters['association_target']);
|
||||
}
|
||||
@@ -62,16 +68,22 @@ class InvestmentCatalogue
|
||||
*/
|
||||
public function query(array $filters): Builder
|
||||
{
|
||||
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||
$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']);
|
||||
elseif (($filters['perspective'] ?? '') === 'opportunities') $query->whereNull('workflow_context->promotional_summary->projection->proactive');
|
||||
if (in_array($filters['perspective'] ?? '', ['exists', 'needs', 'ideas'], true)) {
|
||||
$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);
|
||||
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')));
|
||||
} elseif (($filters['territory_basis'] ?? 'all') === 'context') {
|
||||
$query->whereNull('opportunities.primary_territory_id')->whereNotExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'));
|
||||
$query->where(fn ($q) => $q->whereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_projects')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('project_id', app(InvestmentRelations::class)->projectIds()))
|
||||
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_clusters')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('cluster_id', $this->publicStructureIds('clusters', 'cluster_id'))));
|
||||
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_clusters')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('cluster_id', $this->publicStructureIds('clusters', 'cluster_id')))
|
||||
->orWhere(fn ($source) => $source->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||
->whereIn('workflow_context->corridor_agribusiness->corridor', array_column(config('investment_corridors', []), 'name'))));
|
||||
}
|
||||
if (! empty($filters['opportunity_id'])) {
|
||||
$query->whereKey($filters['opportunity_id']);
|
||||
@@ -80,12 +92,18 @@ class InvestmentCatalogue
|
||||
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
if ($path !== []) {
|
||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($territory) use ($ids, $includeNational, $filters): void {
|
||||
$query->where(function ($territory) use ($ids, $includeNational, $filters, $path): void {
|
||||
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
||||
->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));
|
||||
if (count($path) === 1) {
|
||||
$this->declaredProvince($territory, $path[0]->name);
|
||||
}
|
||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
||||
if (count($path) === 1) {
|
||||
$this->approvedCorridorProvince($territory, $path[0]->id);
|
||||
}
|
||||
}
|
||||
if ($includeNational) {
|
||||
$territory->orWhere('opportunities.geography_scope', 'national');
|
||||
@@ -160,8 +178,15 @@ class InvestmentCatalogue
|
||||
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
||||
->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') {
|
||||
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
|
||||
if (app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->exists()) {
|
||||
$this->approvedCorridorProvince($matches, $filters['geo_location_id']);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -200,7 +225,9 @@ class InvestmentCatalogue
|
||||
if (! empty($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);
|
||||
$sort = $filters['sort'] ?? 'recent';
|
||||
|
||||
@@ -212,6 +239,58 @@ 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
|
||||
{
|
||||
$code = app(InvestmentGeography::class)->publicReferences()->where('id', $provinceId)->value('source_code');
|
||||
$names = [];
|
||||
foreach (config('investment_corridors', []) as $entry) {
|
||||
if (in_array($code, $entry['provinces'], true)) {
|
||||
$names[] = $entry['name'];
|
||||
}
|
||||
}
|
||||
if (! $names) {
|
||||
return;
|
||||
}
|
||||
$query->orWhere(fn ($context) => $context->whereNull('opportunities.primary_territory_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)
|
||||
->whereIn('workflow_context->corridor_agribusiness->corridor', $names));
|
||||
}
|
||||
|
||||
/** Public result presentation only; no editorial or territorial data is saved. */
|
||||
public function presentLocation(Opportunity $record): Opportunity
|
||||
{
|
||||
$geo = app(InvestmentGeography::class);
|
||||
$paths = [];
|
||||
$ids = array_filter([$record->primary_territory_id, ...$record->additionalTerritories()->pluck('geo_locations.id')->all()]);
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$path = $geo->path($id);
|
||||
if ($path) {
|
||||
$paths[] = implode(' / ', array_column($path, 'name'));
|
||||
}
|
||||
}
|
||||
if ($paths) {
|
||||
$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';
|
||||
} else {
|
||||
$label = implode(' / ', array_filter([$record->province, $record->district])) ?: 'Localização não indicada';
|
||||
}
|
||||
$record->setAttribute('territorial_summary', $label);
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $territoryFilters
|
||||
* @return array<string,mixed> */
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
@@ -222,9 +301,9 @@ class InvestmentCatalogue
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||
'categories' => OpportunityManagement::CATEGORIES,
|
||||
'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']),
|
||||
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
|
||||
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
|
||||
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
||||
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES,
|
||||
'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS]];
|
||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||
$query = DB::table($table)->whereNull('deleted_at');
|
||||
if (! $management) {
|
||||
@@ -257,7 +336,7 @@ class InvestmentCatalogue
|
||||
$zones = app(InvestmentZones::class)->visible();
|
||||
if (! $management && $territoryFilters !== []) {
|
||||
// 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']));
|
||||
}
|
||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||
@@ -280,24 +359,35 @@ class InvestmentCatalogue
|
||||
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
||||
$selected = array_filter(array_intersect_key($filters, $kinds));
|
||||
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 = [];
|
||||
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
||||
foreach ($records as $record) {
|
||||
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) {
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -321,9 +411,12 @@ class InvestmentCatalogue
|
||||
$public = ['profile' => null, 'facets' => collect(), 'zones' => collect(), 'classification' => [], 'source_evidence' => [],
|
||||
'primary_territory_path' => app(InvestmentGeography::class)->path($opportunity->primary_territory_id, true),
|
||||
'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')
|
||||
->where('l.opportunity_id', $id)->where('g.data_classification', 'public')->whereNull('g.deleted_at')->get(['g.id', 'g.name']);
|
||||
|
||||
return $public;
|
||||
}
|
||||
$result = ['profile' => DB::table('opportunity_profiles')->where('opportunity_id', $id)->first(),
|
||||
@@ -429,7 +522,7 @@ class InvestmentCatalogue
|
||||
$located = 0;
|
||||
foreach ($records as $record) {
|
||||
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
|
||||
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
|
||||
'location' => $this->presentLocation($record)->getAttribute('territorial_summary'), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
|
||||
foreach ($relations as $relation => $groups) {
|
||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,15 @@ final class InvestmentCorridorContext
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Reuse Tempo's approved provincial context; never infer a district or master link. */
|
||||
public function catalogueProvinces(Opportunity $record): array
|
||||
{
|
||||
if (data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') !== CorridorAgribusinessOpportunities::SOURCE_HASH) return [];
|
||||
if ($record->primary_territory_id || $record->additionalTerritories()->exists()) return [];
|
||||
$key = $this->key($record);
|
||||
return $key ? $this->provinces($key) : [];
|
||||
}
|
||||
|
||||
public function provinces(string $key): array
|
||||
{
|
||||
$entry = config('investment_corridors.'.$key);
|
||||
|
||||
@@ -12,6 +12,21 @@ final class InvestmentGeography
|
||||
{
|
||||
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.
|
||||
*
|
||||
|
||||
@@ -63,10 +63,13 @@ class InvestmentZones
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($matches) use ($territoryIds, $management): void {
|
||||
$ancestorIds = array_column($path, 'id');
|
||||
$query->where(function ($matches) use ($territoryIds, $ancestorIds, $management): void {
|
||||
$matches->whereIn('primary_territory_id', $territoryIds)
|
||||
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('investment_zone_locations as zl')
|
||||
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.geo_location_id', $territoryIds)
|
||||
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.scope_type', ['site', 'administrative', 'legal_scope'])
|
||||
->where(fn ($area) => $area->whereIn('zl.geo_location_id', $territoryIds)
|
||||
->orWhere(fn ($coverage) => $coverage->where('zl.scope_type', 'legal_scope')->whereIn('zl.geo_location_id', $ancestorIds)))
|
||||
->where('zl.validation_status', 'validated')->where(fn ($valid) => $valid->whereNull('zl.valid_from')->orWhereDate('zl.valid_from', '<=', today()))
|
||||
->where(fn ($valid) => $valid->whereNull('zl.valid_until')->orWhereDate('zl.valid_until', '>=', today())));
|
||||
if (! $management) {
|
||||
|
||||
@@ -35,8 +35,11 @@ final class OpportunityCorridorExplorer
|
||||
$path = collect($context['primary_territory_path'] ?? []);
|
||||
$province = $path->firstWhere('location_type', 'province')->name ?? $record->province;
|
||||
$district = $path->firstWhere('location_type', 'district')->name ?? $record->district;
|
||||
$contextProvinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record);
|
||||
$provinceOptions = $province ? [$province] : array_column($contextProvinces, 'name');
|
||||
$item = ['id' => $record->id, 'title' => $record->title, 'slug' => $record->slug, 'summary' => $record->summary,
|
||||
'province' => $province, 'district' => $district, 'chains' => array_values(array_unique($chains)),
|
||||
'province' => $province, 'district' => $district, 'provinces' => $provinceOptions,
|
||||
'territorial_summary' => $catalogue->presentLocation($record)->getAttribute('territorial_summary'), 'chains' => array_values(array_unique($chains)),
|
||||
'stages' => $stages, 'maturity_label' => $record->maturity_label];
|
||||
foreach ($corridors ?: ['other' => 'Outras localizações'] as $key => $name) {
|
||||
$groups[$key] ??= ['id' => $key, 'name' => $name, 'opportunities' => []];
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ final class SectorInvestment
|
||||
|
||||
public function publicView(Sector $sector): array
|
||||
{
|
||||
$creation = app(ContentManagement::class)->access(request()->user())['opportunities']['create'] ?? null;
|
||||
$query = SectorOrganization::opportunities($sector);
|
||||
$articles = $this->guides($sector);
|
||||
$relations = [];
|
||||
@@ -67,7 +68,8 @@ final class SectorInvestment
|
||||
return ['articles' => $articles, 'relations' => collect($relations)->unique('id')->values()->all(), 'locations' => $locations,
|
||||
'start_href' => app(InvestorPath::class)->available() ? '/investimentos/a-partir-do-setor/'.$sector->slug : null,
|
||||
'start_notice' => app(InvestorPath::class)->available() ? null : 'O percurso para guardar a ideia está temporariamente indisponível. A consulta e o apoio continuam disponíveis.',
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/create?sector_id='.$sector->id : null,
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? ($creation ? $creation.'?sector_id='.$sector->id : '/perfil/promotor') : null,
|
||||
'register_label' => $creation ? 'Cadastrar oportunidade — escolher modalidade' : 'Pedir acesso para cadastrar oportunidades',
|
||||
'register_notice' => app(PortalProfileAccess::class)->available() ? null : 'O cadastro por perfis está temporariamente indisponível; pode preparar a ideia e contactar o apoio.',
|
||||
'specialization_href' => in_array($sector->slug, ['tecnologias-de-informacao', 'mercado-financeiro'], true) ? SectorOrganization::href('fintech') : null,
|
||||
'content_notice' => $sector->slug === 'mercado-financeiro' ? 'O artigo geral de Mercado Financeiro permanece vazio e não foi publicado. A preparação de negócios neste setor está disponível.' : null];
|
||||
|
||||
@@ -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' => [
|
||||
'key' => env('POSTMARK_API_KEY'),
|
||||
],
|
||||
|
||||
@@ -1702,3 +1702,189 @@ CI habitual do instalador: PostgreSQL1/3106asserções, Unit59/317, frontend1146
|
||||
`6d147693` está instalado, incluindo a base interna. A única pendência da conferência desta entrega é a validação visual autenticada: **Gurué → consultar oferta → comparar ideia → guardar → recuperar no mesmo dossier**, conservando fonte, data e incertezas. As435 observações de Gurué não são435 empresas únicas. Listas internas, cobertura nacional parcial e hipótese de investimento mantêm-se.
|
||||
|
||||
O erro actual, novamente observado, é **“The browser access host is unavailable”**: indisponibilidade do host do conector, distinta de deixar uma aba aberta. A orientação anterior para apenas manter a aba aberta era insuficiente. Restabelecer o conector por mecanismo suportado ou realizar a conferência pela equipa. Não reinstalar nem repetir as provas técnicas aceites; não declarar conferência visual concluída sem o seu resultado. O recibo remoto original e o historial do diagnóstico anterior ficam preservados; esta correcção é documental.
|
||||
|
||||
|
||||
## 28/10/2026 — revisão de menus: inventário antes da verificação do delta
|
||||
|
||||
Origem: recomendação expressa da Tempo após constatar que as entradas indicadas não aparecem ou ficam escondidas. Página relatada:https://teste-investidor.tempo.co.mz/. Preservados6d147693 e a base privada instalada,as provas QA do percurso e da navegação sectorial,os originais,dados,perfis,permissões e históricos. Não se declara uma funcionalidade anterior desaparecida apenas pela ausência de um novo teste.
|
||||
|
||||
Confirmado no código: barra lateral substitui cada grupo pelo seu primeiro destino,omitindo os restantes;menu principal esconde gestão/perfis dentro do menu do nome do utilizador;entrada de gestão de conteúdos existente não é incorporada nessa navegação principal. A conta e os props efectivos da sessão real permanecem por conferir,porque o conector está indisponível;não se presume falta de autorização.
|
||||
|
||||
Incremento em QA: área de trabalho explícita no menu principal,inclusive entrada neutra de acesso;destinos privados apenas segundo capacidades anteriores;mesmo catálogo completo na barra lateral,sem perda dos subdestinos;entrada directa na análise proactiva existente,sem substituir rascunhos editados;preservação de Descoberta/Realização/Suporte e todos os destinos anteriores aplicáveis. Sem alteração activa,schema,regras de negócio ou papéis. Escolhas de apresentação não são exigências organizacionais. Verificação dirigida do delta pendente nesta fotografia;nenhuma nova matriz ou backlog.
|
||||
|
||||
|
||||
## 28/10/2026 — reorganização dos menus implementada em QA, sem instalação
|
||||
|
||||
Recomendação expressa da Tempo após a página principal não apresentar as entradas sugeridas. Causa delimitada no código: a barra lateral omitia subdestinos ao seleccionar apenas o primeiro link de cada grupo; a navegação principal colocava gestão/perfis dentro do menu do nome do utilizador e não incorporava a entrada de gestão já calculada pelo servidor. Não se presume falta de permissões da sessão real, cujos props não foram observados. A entrega6d147693/base interna continua instalada e preservada; esta revisão não reinstala essa base nem repete as provas técnicas aceites.
|
||||
|
||||
**Proposta executável QA:** Área de trabalho visível ao lado de Descoberta,Realização,Suporte; entrada neutra Acesso à gestão explica o estado, mesmo sem acções privadas atribuídas. As acções autorizadas e Preparar análise e ideia vêm das capacidades existentes, sem criar papéis. A análise abre directamente no formulário existente; rascunhos guardados não são substituídos. A barra lateral põe trabalho primeiro e conserva todos os destinos e os filtros territoriais entre catálogos, em vez de reduzir grupos ao primeiro destino. O cabeçalho permite quebra de linha em largura intermédia; os controlos móveis e do teclado existentes são reutilizados.
|
||||
|
||||
**Verificação delimitada:**16 testes de navegação/renderização estrutural,0falhas;tipos,compilação QA e sintaxe PHP passaram. Quatro cenários de capacidades conservaram todos os destinos anteriores; não surgem operações privadas em cenário anónimo ou sem atribuições. SSR usa o componente real da barra lateral com wrappers semânticos de teste; não equivale a captura do navegador. A prévia HTML é um inventário interactivo de destinos, sem pedidos ao portal, identificado como proposta QA, não como sessão real.
|
||||
|
||||
**Pendente:** conferência visual desktop/móvel/teclado/toque e das capacidades efectivas da sessão relatada; o host do conector permanece indisponível no último diagnóstico. Não substituir essa conferência por alegação de acesso demonstrado. A instalação futura deve transportar só o delta de menus pelo processo Git/backup/restauro existente, preservando originais, dados, permissões, contexto,dossier e simulador.435 observações de Gurué não são435empresas únicas; listas internas/cobertura parcial/hipótese preservadas. L8 continua parcial.
|
||||
|
||||
Inventário anterior registado antes dos testes nesta matriz/manual. Actualização apenas nos requisitos existentesV2-01,V2-07,V2-10,MASTER-9dee08d0-0011,MASTER-9f6dd1d9-0001,MASTER-9f6dd1d9-0003,MASTER-02f44baf-0002;não há matriz ou backlog novos. Relatório:`navigation-reconciliation-qa-20261028.json`;prévia:`outputs/navigation-reconciliation-20261028/menu-proposta-qa.html`.
|
||||
|
||||
A apresentação da gestão antiga usa agora a decisão efectiva já existente (`legacyWriteAllowed`, com o requisito de email verificado das rotas), em vez de presumir que o indicador genérico de gestor basta. Não se alteraram regras, atribuições ou permissões. Preservada também a entrada de instalação de perfis anteriormente presente apenas na barra lateral autorizada. Os nomes longos quebram linha na barra lateral, sem reticências que escondam a função.
|
||||
|
||||
|
||||
## 28/10/2026 — menus 6e8de43a instalados pelo Git; conferência visual pendente
|
||||
|
||||
A Tempo aprovou a proposta QA e autenticou o transporte SSH existente. `main` avançou normalmente de `6d147693` para `6e8de43a`, sem force. A entrega usou o pipeline existente, sem alterar o seu contrato de schema, sem migrações, importações, atribuições de papéis ou permissões. Os 16 testes dirigidos e as provas QA aceites foram reutilizados; as verificações automáticas obrigatórias do pipeline não representam nova aceitação funcional.
|
||||
|
||||
Capacidade conferida antes da entrega: cerca de 78,5 GiB livres. Backup novo em `/var/backups/investmoz-navigation-delivery-20261028/backup`; restauro em base isolada, sem rede, confirmou as 176 tabelas por contagens/checksums. Os 369 ficheiros persistentes/configuração mantêm-se idênticos. As tabelas de domínio, incluindo base interna, relações e permissões, foram comparadas com o snapshot do backup; apenas alterações operacionais de cache/sessão são registadas separadamente. A versão anterior está preservada para retorno pelo mecanismo existente.
|
||||
|
||||
O delta instalado contém Área de trabalho no nível principal, destinos subordinados completos na barra lateral e continuidade para os destinos existentes de investimento, conteúdos e acompanhamento. A exposição das acções respeita a decisão efectiva do servidor; não se infere nova autorização pelo nome genérico de gestor. A presença dos assets e props instalados foi conferida tecnicamente, sem a apresentar como prova da sessão real.
|
||||
|
||||
Pendente: conferência visual autenticada desktop/móvel/teclado/toque e percurso Gurué → consultar oferta → comparar ideia → guardar → recuperar no mesmo dossier. Último bloqueio conhecido: `The browser access host is unavailable`; uma aba aberta não restabelece o host. Não repetir as provas QA aceites nem reinstalar a base interna para resolver essa pendência. As 435 observações de Gurué não equivalem a 435 empresas únicas; listas internas, cobertura parcial e hipótese de investimento mantêm-se explícitas. L8 permanece parcial.
|
||||
|
||||
Evidência: `docs/investmoz/unification/navigation-git-delivery-20261028.json`. O relatório QA anterior permanece como histórico do candidato antes da instalação. Actualizados os mesmos sete requisitos existentes, preservando o seu histórico; não foi criada outra matriz.
|
||||
# Inventário antes da verificação — catálogo territorial, 28/10/2026
|
||||
|
||||
Preservar menus `6e8de43a`, dados, base interna, aprovações, configuração de corredores e históricos já aceites. Caso Maputo Província / Agronegócio reproduzido por leitura QA: zero resultados apesar de cinco oportunidades públicas do Corredor de Maputo, cujo âmbito provincial está aprovado desde 23/10 em `corridor-adaptive-context-20261023.json`. A consulta não inclui esse contexto; os cartões também não mostram todos os níveis territoriais disponíveis. Correcção delimitada nos requisitos existentes V2-07/V2-10, sem inferir distrito/posto administrativo onde a fonte não os indica. Conferência visual autenticada continua pendente; não há nova matriz nem reabertura de provas aceites.
|
||||
|
||||
|
||||
## 28/10/2026 — correcção provincial do catálogo em QA, ainda sem instalação
|
||||
|
||||
Caso da Tempo: Agronegócio / Maputo Província. A leitura QA reproduziu zero resultados para cinco oportunidades públicas do Corredor de Maputo. Reutilizada a decisão expressa de 23/10 que abrange Maputo Província e Maputo Cidade, antes disponível no percurso mas omitida na consulta. O filtro provincial passa a incluir esse contexto aprovado, mantendo sector e estado público, sem duplicar oportunidades nem atribuir distrito/posto administrativo ou coordenadas inexistentes. Uma localização explícita posterior prevalece sobre o contexto antigo.
|
||||
|
||||
Os resultados apresentam a hierarquia territorial disponível; o contexto de corredor é identificado e os níveis não indicados continuam explícitos. Pesquisa/API, vista por corredores e lista sem coordenadas do mapa concordam. O atalho «Ver toda a província» elimina a necessidade de limpar vários níveis manualmente. Não foram criadas publicações, relações a mestres ou permissões. Provas QA: 4 testes/70 verificações, zero falhas, transacções revertidas; tipos, compilação QA e sintaxe PHP passaram. O inventário anterior foi registado antes dos testes. Menus 6e8de43a, base interna, históricos e aceitação anterior preservados; L8 permanece parcial.
|
||||
|
||||
Relatório: `catalogue-province-coverage-qa-20261028.json`. Instalação pelo processo Git e conferência visual autenticada continuam pendentes. Não declarar auditados todos os outros menus por este delta. Cobertura actualizada nos requisitos existentes V2-07/V2-10; sem nova matriz.
|
||||
|
||||
|
||||
28/10 — Âmbito nacional confirmado pela Tempo: antes da extensão dos testes, preservar a correcção QA 1b2ede41 e verificar os seis corredores aprovados nas onze unidades provinciais, hierarquia descendente e reutilização entre sectores/entradas de localização. Não presumir cobertura de corredor onde não está documentada. Nenhuma prova anterior é revogada.
|
||||
|
||||
|
||||
|
||||
28/10 - National coverage: 6 tests / 617 assertions passed across all 11 provincial units, 6 configured corridors and 2 sectors, including descendant hierarchy, sector separation and both province/location entry points. The runtime correction already used the common national hierarchy; Maputo was the reported reproduction, not a geographic limit. Existing publication decisions and unknown district/post/site information remain preserved. This is not a claim that every unrelated portal menu has been audited. No additional runtime change since 1b2ede41; types/build accepted evidence reused. Installation remains pending.
|
||||
|
||||
|
||||
28/10 - Before selector delta checks: accepted national catalogue QA 47dae1b7, 6 tests/617 assertions, remains uninstalled. Existing TerritoryLevel and ProvinceSelect required two separate fields (search then select). Tempo requests one dropdown on the search field. Consolidate the shared controls while retaining saved values, hierarchy, endpoints, paging and permission decisions;browser visual proof remains separate.
|
||||
|
||||
|
||||
|
||||
## 28/10/2026 — selecção territorial num único campo de pesquisa, QA
|
||||
|
||||
Pedido expresso da Tempo: o dropdown deve abrir em «Pesquisar província», sem um segundo controlo «Seleccione». `ProvinceSelect` e `TerritoryLevel` passam a usar o mesmo combobox, aplicado a província, distrito, posto administrativo e localidade. Pesquisar e escolher fica num único campo; a paginação permanece na lista. Escrever ou sair com Escape não substitui a selecção guardada; escolher e limpar são acções expressas. Mantêm-se a hierarquia, os endpoints existentes e os controlos de acesso, sem novos dados ou publicações.
|
||||
|
||||
Quatro testes do contrato de eventos/estado passaram: abertura/escolha, preservação ao escrever/Escape, teclado e bloqueio de resultado antigo durante carregamento, limpeza e dependência do nível anterior. Tipos e compilação QA passaram. As 6 provas nacionais/617 verificações são reutilizadas porque o PHP territorial não mudou. Este delta continua em QA e não comprova apresentação ou sessão real no navegador. Será agrupado com a correcção provincial; falta autenticação SSH antes da entrega, sem nova aprovação organizacional.
|
||||
|
||||
|
||||
28/10 - Before catalogue presentation checks: accepted province QA6/617 and unified selector QA4 remain preserved and uninstalled. Tempo reports Tourism/Cabo Delgado shows educational text and broad sector links. Read-only public API confirmed zero filtered records;unfiltered tourism returns16 records,all declared in Inhambane. This does not establish absence of tourism supply in Cabo Delgado. Correct presentation to retain filters and expose guides only as optional links;do not republish or reassign opportunities to manufacture results.
|
||||
|
||||
## 28/10/2026 — resultados do catálogo separados do apoio educativo, QA
|
||||
|
||||
A Tempo esclareceu que a combinação província/sector deve apresentar as oportunidades correspondentes, sem texto educativo ou atalhos que troquem a consulta por todas as oportunidades do sector. A consulta pública anónima conferiu Turismo/Cabo Delgado = zero oportunidades cadastradas; Turismo sem localização = 16, todas declaradas em Inhambane. Este snapshot não prova ausência de oferta turística em Cabo Delgado e não substitui inventário de fontes ou consulta autenticada.
|
||||
|
||||
Correcção de apresentação em QA: título dos resultados explicita sector e hierarquia escolhidos; removidos os cartões educativos e o botão sectorial sem localização da área de resultados. Os guias mantêm-se como títulos ligados em apoio opcional fechado por defeito. A remoção da localização é uma acção expressamente identificada como pesquisa noutras províncias. O estado vazio refere o cadastro consultado e a cobertura incompleta, sem fabricar oportunidades nem alargar automaticamente filtros.
|
||||
|
||||
Dois testes SSR do novo apoio opcional passaram, bem como tipos e compilação. As provas territoriais nacionais 6/617 e os quatro testes do selector são reutilizados; não mudou a consulta PHP ou o controlo territorial neste delta. Mantêm-se histórico, publicações, permissões, fontes e base interna. Este candidato continua sem instalação, dependente de autenticação SSH; a sessão real permanece sem prova visual. Relatório existente: `catalogue-province-coverage-qa-20261028.json`, campo `catalogue_result_presentation`. Requisitos V2-07/V2-10 actualizados na mesma matriz; L8 permanece parcial.
|
||||
|
||||
|
||||
28/10 - Before investor usability checks: accepted catalogue candidate54d1b2a5 remains in QA,not installed;active menus6e8de43a and earlier supply proofs preserved. Two Tempo attachments identify duplicate profile navigation,an exposed long canonical form and ZEE/ZFI/park searches that keep prior results until manual submit. Prepare presentation-only adaptive field groups and safe save-before-resource navigation;verify territorial search/count/paging and documented scope without republishing records or changing permissions. Reuse prior proofs;existing V2-07/V2-10 scope retained.
|
||||
|
||||
## 28/10/2026 — usabilidade do investidor e consulta territorial, QA
|
||||
|
||||
Pedidos da Tempo e exemplos recebidos: menu/ficha de oportunidade, zonas/parques, pedido de Promotor, Os meus investimentos, documentos/formulários e recusa autenticada em Turismo. Inventário anterior registado antes dos testes: menus 6e8de43a e base interna instalados; candidato territorial 54d1b2a5 ainda em QA; originais, dados, relações, histórico, aprovações e provas anteriores preservados.
|
||||
|
||||
Delta QA: acções do investidor em primeiro plano, administração em detalhe consultável; campos do contrato existente agrupados por tarefa e modalidade, com navegação livre e todos os campos montados para conservar edições. Os grupos mostram as pendências da última gravação e os erros existentes; não criam seis ou oito formulários obrigatórios. Guardar usa os mesmos endpoints/ETags; abrir recursos pela preparação guarda primeiro e regressa à mesma oportunidade/grupo. Contactos e detalhes de disponibilidade ficam opcionais; códigos técnicos de categorias e campos conhecidos têm nomes em português. Só um contexto único de promotor é escolhido automaticamente.
|
||||
|
||||
Zonas: selecção territorial aplica pesquisa sem esperar por outro clique; a lista anterior deixa de aparecer durante carregamento/erro. Totais, intervalo visível e páginas identificados, sem apresentar a primeira página como o conjunto completo. «Todo o território» remove expressamente a localização, preservando os restantes critérios visíveis. Abrangência jurídica documentada e validada inclui os níveis descendentes; influência não se torna implantação. Não são criadas localizações, direitos, publicações ou certificados.
|
||||
|
||||
Pedido de Promotor: representação/modalidades com nomes claros; pesquisa de ficheiros e selecção expressa dos comprovativos, preservando os escolhidos ao pesquisar. Mantidos propriedade, análise antimalware e verificações existentes; legislação/imagem/teste não se torna comprovativo por estar disponível. Os meus investimentos destaca a próxima acção e permite abrir fases/etapas; fontes, códigos e acompanhamento interno ficam preservados em detalhes.
|
||||
|
||||
Formulários: entradas directas para os campos já existentes da preparação do pedido de investimento e Terra/DUAT; pedido de apoio identificado separadamente. Originais oficiais e guias continuam consultáveis, sem os confundir com um formulário preenchível ou converter leis em campos/cálculos. Não se declara executada a totalidade dos formulários oficiais do acervo.
|
||||
|
||||
Provas delimitadas: 8 testes frontend de contrato/SSR e 3 testes isolados/12 verificações, zero falhas; tipos, compilação e sintaxe PHP passaram. Dados sintéticos revertidos em QA. Provas nacionais/selector/catálogo anteriores reutilizadas. Turismo: leitura anónima activa HTTP200 e QA visitante/conta sem Promotor HTTP200; a recusa da sessão real relatada não foi reproduzida, nem atribuída a uma permissão sem prova. A conferência autenticada e visual continua pendente. Este registo não instala o candidato nem encerra a implementação transversal. L8 permanece parcial.
|
||||
|
||||
Evidência: `investor-usability-qa-20261028.json`. Actualizados V2-01,V2-07,V2-10 na matriz existente; sem nova matriz ou backlog.
|
||||
|
||||
|
||||
### 28/10 — botão de cadastro e compatibilidade do pipeline
|
||||
|
||||
A Tempo esclareceu que a recusa em Turismo ocorreu depois de clicar num botão; não foi possível recuperar o nome. A rota pública continuou HTTP200. Conferência de forma pública/origem não identificou anexos privados nos documentos públicos de Turismo; não se atribui a recusa à perda de publicação. Encontrada uma falha delimitada no consumidor: o botão de cadastro dependia da disponibilidade do módulo, sem a capacidade efectiva da conta. Corrigido para reutilizar o destino autorizado de criação de ContentManagement; sem essa capacidade, mostra expressamente o pedido de acesso já existente. Não cria papéis nem restringe a consulta pública ou a preparação de ideias. A confirmação visual da acção real permanece pendente.
|
||||
|
||||
O candidato 502e3ec4 falhou na Unit de agrupamento de corredores antes da troca de release; 6e8de43a ficou servido. Causa: a simulação do catálogo não representava a nova apresentação de localização e uma consulta era feita antes de conferir se a fonte era aplicável. Correcção: conferir primeiro a fonte e simular a nova dependência no teste, conservando as verificações anteriores de identidade, grupos e contagens. Regressão Unit1/13 passou; não foi alterado o pipeline, o contrato de schema ou a exigência dos testes. Frontend9, Feature3/14, tipos e compilação passaram. Rótulos conhecidos de temas, categorias e idiomas do acervo traduzidos para apresentação; valores dos filtros preservados.
|
||||
|
||||
|
||||
## 28/10/2026 — entrega agrupada de usabilidade e filtros instalada, 789fffd0
|
||||
|
||||
Entrega autorizada pela Tempo e autenticada pelo mecanismo SSH existente. `main` avançou normalmente e o pipeline existente instalou `789fffd0`, preservando a release anterior `6e8de43a`. O candidato inicial `502e3ec4` foi recusado antes da troca por uma dependência não representada no teste Unit do agrupamento de corredores; o activo ficou preservado. A consulta desnecessária foi corrigida e a nova dependência simulada, conservando as provas anteriores. O pipeline e o seu contrato de schema não foram enfraquecidos.
|
||||
|
||||
Backup/restauro de 176 tabelas confirmado numa instância isolada, sem rede. Os 369 ficheiros persistentes/configuração mantêm-se idênticos. A comparação do snapshot com o instalado preserva as tabelas de domínio, incluindo papéis, publicações, originais e base interna; diferenças de cache/sessões são registadas separadamente. Sem migrações, importações ou activação fiscal. A versão anterior permanece disponível para o mecanismo de retorno.
|
||||
|
||||
Incluídos: consulta provincial nacional/corredores e detalhe territorial; pesquisa/selecção num único controlo; resultados do catálogo separados do apoio educativo; grupos adaptáveis de preenchimento, navegação livre e gravação antes de abrir recursos; pedido de Promotor legível com comprovativos escolhidos expressamente; zonas filtradas ao seleccionar, contagens/paginação visíveis; fases/etapas do dossier e fontes em detalhes; entradas para formulários de preparação já existentes; CTA sectorial conforme capacidade efectiva; rótulos do acervo legíveis. Não são novas permissões, publicações ou formulários fiscais oficiais inventados.
|
||||
|
||||
Conferidos o commit servido, APIs filtradas e assets instalados. Reutilizadas as provas QA aceites; a bateria obrigatória do pipeline não reabre a sua aceitação. Mantém-se pendente a conferência visual autenticada, incluindo navegação, ida/volta a recursos e Gurué no mesmo dossier. A recusa relatada em Turismo ocorreu após um botão; a falha concreta do CTA de cadastro foi corrigida, mas não se declara reproduzida e resolvida a acção original sem a sessão real. A escolha do formulário fiscal concreto ainda precisa de ser esclarecida; os diplomas IVA mostrados não são formulários preenchíveis.
|
||||
|
||||
Estado actual: `investor-usability-git-delivery-20261028.json`. Os relatórios QA anteriores conservam o estado histórico antes da instalação. As 435 observações de Gurué não são 435 empresas; as listas são internas, a cobertura nacional é parcial e a comparação sustenta hipóteses. L8 permanece parcial. Actualizados V2-01/V2-07/V2-10 na matriz e manual existentes.
|
||||
|
||||
|
||||
## 28/10/2026 — preparação de formulários fiscais, inventário antes das provas
|
||||
|
||||
Pedido expresso da Tempo: preencher formulário de IVA ou IRPC, em vez de abrir legislação. Base preservada: entrega instalada 789fffd0, Modelo A e aquisições/apuramento já aceites, L6 M20/M22 instalado em 5aaf1a56 e incrementos de L8. Nenhuma perda confirmada neste recorte; não se apagam as aceitações nem se repetem provas fiscais anteriores. Fontes reutilizadas do inventário de 20 exemplares acessíveis em outputs/irpc-l6-values-forms/accessible-source-inventory.json da QA anterior, incluindo temporários identificados; inventário do corpus e originais preservados. M22: três páginas conferidas visualmente nesta revisão, SHA256 4b61bd83d1fbcfd3b7b5c5523cea5923f7d0f65dc4c004eff58e5db38f763c88. Modelo A: correspondência e divergências aceites em modelo-a-reconciliacao-20261021.md; sem nova validação de proveniência.
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
### 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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
### 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,131 @@
|
||||
{
|
||||
"date": "2026-10-28",
|
||||
"status": "QA_corrected_and_verified_not_installed",
|
||||
"installed_baseline": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"user_case": "Agronegócio / Maputo Província",
|
||||
"reproduction": {
|
||||
"QA_public_agribusiness": 37,
|
||||
"Maputo_corridor_public_opportunities": 5,
|
||||
"province_results_before": 0,
|
||||
"province_results_after": 5
|
||||
},
|
||||
"cause": "The provincial catalogue ignored the corridor context already approved by Tempo; no records were deleted.",
|
||||
"reused_decision": [
|
||||
"config/investment_corridors.php",
|
||||
"docs/investmoz/unification/corridor-adaptive-context-20261023.json"
|
||||
],
|
||||
"correction": [
|
||||
"Reuse approved corridor province context only at province level, with the accepted source hash and existing public publication decisions",
|
||||
"Do not override an explicit primary/additional territory or infer district/post/coordinates",
|
||||
"Display available province,district,administrative post,locality directly in results",
|
||||
"Show both approved Maputo units as contextual coverage, not as two separate opportunities",
|
||||
"Keep catalogue,API,corridor view and unlocated map list consistent",
|
||||
"One action returns from district to whole province; no requirement to select every level"
|
||||
],
|
||||
"QA": {
|
||||
"tests": 6,
|
||||
"assertions": 617,
|
||||
"failures": 0,
|
||||
"database": "proactive_investment_20261027_test",
|
||||
"port": 55441,
|
||||
"transactions_rolled_back": true,
|
||||
"types": "passed",
|
||||
"build": "passed",
|
||||
"PHP_syntax": "passed"
|
||||
},
|
||||
"preserved": [
|
||||
"Installed menus and accepted supply proofs",
|
||||
"Originals,source data,territory IDs,publication states,permissions,private lists and histories",
|
||||
"L8 unchanged,partial"
|
||||
],
|
||||
"limitations": [
|
||||
"No active installation in this report",
|
||||
"Real authenticated visual conference remains pending;last connector error The browser access host is unavailable",
|
||||
"This fixes the shared investment catalogue and corridor view;it is not proof that every menu in the portal has been audited",
|
||||
"Provincial corridor coverage is not a documented district site;unknown levels stay unknown"
|
||||
],
|
||||
"existing_requirements": [
|
||||
"V2-07",
|
||||
"V2-10"
|
||||
],
|
||||
"restriction_origins": {
|
||||
"territorial_behaviour": "Tempo current request",
|
||||
"corridor_coverage": "Tempo express decision,23/10/2026",
|
||||
"no_new_publication_or_roles": "existing approved scope",
|
||||
"UI_summary_and_province_shortcut": "implementation choice"
|
||||
},
|
||||
"scope": "national;shared investment catalogue and similar location entry points",
|
||||
"national_verification": {
|
||||
"provincial_units": 11,
|
||||
"approved_corridors": 6,
|
||||
"sectors_for_descendant_fixtures": 2,
|
||||
"province_and_legacy_location_entry_points": true,
|
||||
"district_containment": true,
|
||||
"unrelated_provinces_excluded": true,
|
||||
"test_data": "synthetic fixtures rolled back;accepted published source reused"
|
||||
},
|
||||
"selector_delta": {
|
||||
"Tempo_request": "Dropdown belongs to Pesquisar província;remove separate Seleccione control",
|
||||
"scope": [
|
||||
"ProvinceSelect",
|
||||
"TerritoryLevel:province,district,administrative post,locality"
|
||||
],
|
||||
"behaviour": [
|
||||
"One combobox input opens the list and searches the existing endpoint",
|
||||
"Explicit choice commits the existing option;typing or Escape does not clear saved values",
|
||||
"Arrow keys and Enter select;clear is explicit;dependent levels remain disabled without parent",
|
||||
"Paging retained inside dropdown;loading cannot commit a stale option"
|
||||
],
|
||||
"QA": {
|
||||
"event_state_contract_tests": 4,
|
||||
"failures": 0,
|
||||
"types": "passed",
|
||||
"build": "passed",
|
||||
"limit": "Controlled React component contract;not browser visual/session evidence"
|
||||
},
|
||||
"publication_data_permissions_and_territory_rules": "unchanged",
|
||||
"national_province_evidence": "6 tests/617 assertions reused;unchanged PHP runtime",
|
||||
"status": "QA_not_installed"
|
||||
},
|
||||
"catalogue_result_presentation": {
|
||||
"Tempo_request": "Province+sector must show matching opportunities,not educational text and unfiltered national sector shortcuts",
|
||||
"public_read_snapshot": {
|
||||
"filtered": {
|
||||
"total": 0,
|
||||
"province": "Cabo Delgado",
|
||||
"sector": "turismo",
|
||||
"province_id": "059b02ca-7095-577a-8705-4d4c46896747"
|
||||
},
|
||||
"active_writes": 0,
|
||||
"sector_only": {
|
||||
"total": 16,
|
||||
"declared_provinces": [
|
||||
"Inhambane"
|
||||
],
|
||||
"sector": "turismo"
|
||||
},
|
||||
"method": "anonymous public API read; no authenticated session claimed",
|
||||
"meaning": "public catalogue snapshot;not evidence of absence of market supply",
|
||||
"checked_at": "2026-10-28T19:03:36.8285860Z",
|
||||
"target": "https://teste-investidor.tempo.co.mz/"
|
||||
},
|
||||
"UI_changes": [
|
||||
"Heading identifies applied sector and territorial path",
|
||||
"Educational cards and their broad sector opportunity button removed from catalogue results",
|
||||
"Guide titles remain available only inside closed optional support details",
|
||||
"Removing location is explicitly labelled as searching other provinces",
|
||||
"Empty state is limited to published records in the consulted catalogue;not absence of market supply"
|
||||
],
|
||||
"QA": {
|
||||
"new_component_SSR_tests": 2,
|
||||
"failures": 0,
|
||||
"types": "passed",
|
||||
"build": "passed",
|
||||
"accepted_national_and_selector_proofs": "reused;backend and selector unchanged"
|
||||
},
|
||||
"status": "QA_not_installed",
|
||||
"authenticated_visual_validation": "pending;public API read does not prove real session behaviour",
|
||||
"active_writes": 0,
|
||||
"new_publications": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
{
|
||||
"checks": {
|
||||
"feature_tests": 7,
|
||||
"isolated_build": "passed",
|
||||
"feature_assertions": 93,
|
||||
"frontend_tests": 4,
|
||||
"types": "passed"
|
||||
},
|
||||
"tested_candidate": "568a488ae76c631714547614f52ca6be7a121e2d",
|
||||
"schema_changes": 0,
|
||||
"active_writes": 0,
|
||||
"source_sha256": {
|
||||
"tests/Feature/ClusterCompetitivenessTest.php": "3c4b27fbc2c00210bd6be78057d88d03f54676c82907fafcbe57843ea7d726cb",
|
||||
"app/Http/Controllers/InvestmentPortfolioController.php": "0793d06bf94b679b301f4aedbd54d73184ed7b27d3100036dfc81f4621c101d6",
|
||||
"resources/js/pages/portfolio/show.tsx": "6562798defc1546466b1ed3c66e0d51b1c6c1b08f03c8d5acc915877792ce7da",
|
||||
"routes/web.php": "76501452ad4ce187ce234127ef160a5a458f629d583d9ccb3c67c1c9d4a1a561",
|
||||
"resources/js/components/cluster-competitiveness-public.tsx": "85ab2f59de4c63faf6ea699855bbcf0c9efaea0ff9c39421d5640286e9df5910",
|
||||
"app/Http/Controllers/ClusterCompetitivenessController.php": "12ab13860da1acda02dd77f38d0ddd0d1b8fca5856f7fa8823e9e6193143368e",
|
||||
"app/Services/ClusterCompetitiveness.php": "24cae918c14a84470b7fc2e1485eacd9c4e2306a54928ca9de6a56576f5227df",
|
||||
"resources/js/pages/structures/editor.tsx": "c6d50445de3c1f18b266afe5898cd31198fc5946606770ac74a5f01e6e67b712",
|
||||
"resources/js/pages/structures/competitiveness.tsx": "8c4253cef8450b47245a918712bb81fe0ff2a333f54726a38239264a398f4fde",
|
||||
"app/Http/Controllers/InvestmentStructureController.php": "b0d11991240fa5f6fa0d56a4c66b63f68665d0687b3772b4f8ca632460499930"
|
||||
},
|
||||
"baseline": "23ecccfaad1053f55bf0591fd242cb5fa3406c38",
|
||||
"provincial_filters": "separate_and_open_not_changed_or_verified",
|
||||
"remaining": [
|
||||
"authenticated visual conference of the installed management workflow",
|
||||
"factual sector and regional analysis and explicit content approvals",
|
||||
"provincial filter issue remains separate and open",
|
||||
"remaining planned ACT activities"
|
||||
],
|
||||
"status": "installed_specific_persistence_QA_and_preservation_verified_visual_pending",
|
||||
"proof": {
|
||||
"candidate": "568a488ae76c631714547614f52ca6be7a121e2d",
|
||||
"status": "passed",
|
||||
"database": "competitiveness_persistence_20261029_test",
|
||||
"port": 55441,
|
||||
"snapshot_restored": true,
|
||||
"active_database_writes": 0,
|
||||
"schema_changes": 0,
|
||||
"log": "/var/lib/investmoz-deploy/competitiveness-persistence-qa-20261029/qa-568a488ae76c631714547614f52ca6be7a121e2d.log",
|
||||
"summary": "PHPUnit 12.5.34 by Sebastian Bergmann and contributors.\n\nRuntime: PHP 8.4.27\nConfiguration: /var/lib/investmoz-deploy/competitiveness-persistence-qa-20261029/568a488ae76c631714547614f52ca6be7a121e2d-1793273608890561258/phpunit.xml\n\n....... 7 / 7 (100%)\n\nTime: 00:04.973, Memory: 58.50 MB\n\n\u001b[30;42mOK (7 tests, 93 assertions)\u001b[0m\n"
|
||||
},
|
||||
"installed_candidate": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||
"backup": {
|
||||
"stage": "/var/backups/investmoz-competitiveness-persistence-20261029/backup",
|
||||
"created_at": "2026-10-29T11:32:49Z",
|
||||
"target": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432
|
||||
},
|
||||
"tables": 176,
|
||||
"files_verified": 369,
|
||||
"dump_sha256": "e92123a3b986781de20367a04462ed7b92958c47f232326da18506a79a43717c",
|
||||
"files_sha256": "bb615875347f7b27da593f148af973fc825555524a261f8f68c50cd4ce26962c",
|
||||
"restore_verified": false
|
||||
},
|
||||
"restore": {
|
||||
"restore_verified": true,
|
||||
"tables_verified": 176,
|
||||
"container_network": "none",
|
||||
"database": "competitiveness_persistence_restore_20261029_test",
|
||||
"port": 55441,
|
||||
"source_dump_sha256": "e92123a3b986781de20367a04462ed7b92958c47f232326da18506a79a43717c",
|
||||
"active_database_writes": 0
|
||||
},
|
||||
"code": {
|
||||
"candidate": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||
"source_files_verified": 10,
|
||||
"diagnostics_C132": {
|
||||
"result": "passed",
|
||||
"case": "C132",
|
||||
"source_explicit_constant_OFF": true,
|
||||
"effective_configuration_OFF": true,
|
||||
"configuration_cached": false,
|
||||
"database_connections_used": 0,
|
||||
"active_writes": 0
|
||||
},
|
||||
"active_writes": 0
|
||||
},
|
||||
"runtime": {
|
||||
"identity": {
|
||||
"database": "teste_investidor",
|
||||
"role": "teste_investidor_app",
|
||||
"port": 5432,
|
||||
"audit_read": true,
|
||||
"audit_append": true,
|
||||
"cluster_lock": true
|
||||
},
|
||||
"management_read_from_database": true,
|
||||
"server_version": 0,
|
||||
"history_items": 0,
|
||||
"approved_projection_available": false,
|
||||
"actor_impersonation": false,
|
||||
"active_domain_writes": 0,
|
||||
"candidate": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||
"anonymous_management_status": 401,
|
||||
"persistence_actions_compiled": true,
|
||||
"specific_write_recovery_and_public_projection_QA": "7 tests / 93 assertions; no synthetic writes on active database",
|
||||
"provincial_filters": "separate and open; not changed or confirmed here",
|
||||
"authenticated_visual_conference": "pending"
|
||||
},
|
||||
"preservation": {
|
||||
"navigation_asset_and_shared_props_verified": true,
|
||||
"at": "2026-10-29T11:42:15.258836+00:00",
|
||||
"served_commit": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||
"backup_dump_sha256": "e92123a3b986781de20367a04462ed7b92958c47f232326da18506a79a43717c",
|
||||
"prior_public_tables_checked": 176,
|
||||
"prior_domain_rows_preserved": true,
|
||||
"new_migration_registry_rows": 0,
|
||||
"operational_delta": {
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 119,
|
||||
"checksum": "5ddea5ecf35f8dc04d275b189821b59a"
|
||||
},
|
||||
"after": {
|
||||
"rows": 119,
|
||||
"checksum": "8336a458d425e14c66b20c3da9aa01de"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 10,
|
||||
"checksum": "aa65128c0bafc9eab8419174754327d7"
|
||||
},
|
||||
"after": {
|
||||
"rows": 12,
|
||||
"checksum": "41f44e385b8a31b0af1f22e1a29680ce"
|
||||
}
|
||||
}
|
||||
},
|
||||
"persistent_files_and_configuration_identical": 369,
|
||||
"private_catalogue": {
|
||||
"observations": 361464,
|
||||
"distinct_administrative_observations": 214299,
|
||||
"preserved_repetitions": 147165,
|
||||
"unmapped_territory": 205608
|
||||
},
|
||||
"preservation_identity": "postgres, matching backup reader; no actor impersonation",
|
||||
"anonymous_query_status": 401,
|
||||
"public_revision_confirmed": true,
|
||||
"actual_team_UI_journey": "pending authenticated browser conference;accepted QA is not repeated",
|
||||
"unique_company_count": null,
|
||||
"publication": false,
|
||||
"national_coverage": "partial",
|
||||
"investment_conclusion": "hypothesis,not proved demand or viability",
|
||||
"L8": "unchanged,partial"
|
||||
},
|
||||
"pipeline": {
|
||||
"unit_tests": 59,
|
||||
"summaries": [
|
||||
"\u001b[30;42mOK (1 test, 3106 assertions)\u001b[0m",
|
||||
"✓ built in 33.96s",
|
||||
"\u001b[30;42mOK (59 tests, 320 assertions)\u001b[0m",
|
||||
"# tests 1180",
|
||||
"# pass 1180",
|
||||
"# fail 0"
|
||||
],
|
||||
"schema_assertions": 3106,
|
||||
"frontend_tests": 1180,
|
||||
"result": {
|
||||
"status": "installed",
|
||||
"commit": "b81f477bf2385227ed3099868e80b1e3c7bcb46b",
|
||||
"release": "/var/www/investmoz-homologacao/releases/b81f477bf2385227ed3099868e80b1e3c7bcb46b-5eed771e",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/23ecccfaad1053f55bf0591fd242cb5fa3406c38-0e0b8a65",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"b81f477bf2385227ed3099868e80b1e3c7bcb46b"
|
||||
],
|
||||
"finished_at": "2026-10-29T11:39:35.927983+00:00"
|
||||
},
|
||||
"frontend_failures": 0,
|
||||
"unit_assertions": 320
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
{
|
||||
"activity": "ACT-20261029-01",
|
||||
"status": "partial_increment_installed_preservation_verified_visual_pending",
|
||||
"baseline": "332c16ebb555e8d6b244fa519bc777d89c1a8b8f",
|
||||
"branch": "codex/competitiveness-sequential-20261029",
|
||||
"target": "https://teste-investidor.tempo.co.mz/",
|
||||
"checks": {
|
||||
"diff": "passed",
|
||||
"types": "passed",
|
||||
"diagnostics_C132": "passed_in_original_workspace",
|
||||
"frontend_tests": 4,
|
||||
"isolated_qa_build": "passed"
|
||||
},
|
||||
"active_database_writes": 0,
|
||||
"schema_changes": false,
|
||||
"permission_changes": false,
|
||||
"coverage": [
|
||||
"five qualitative forces in existing cluster management",
|
||||
"sector and regional scope",
|
||||
"evidence, source, period, rationale, limitations and investment opportunity",
|
||||
"explicit uncertainty",
|
||||
"JSON download and confirmed same-cluster recovery"
|
||||
],
|
||||
"remaining": [
|
||||
"authenticated visual verification",
|
||||
"server persistence and canonical territorial scope",
|
||||
"factual sector and regional data",
|
||||
"public consultation"
|
||||
],
|
||||
"source_sha256": {
|
||||
"resources/js/lib/cluster-competitiveness.ts": "1ed496f51f020da9f0c02ab0aa324b58a9dd17fa34a10d8c1a90d9915800fecb",
|
||||
"resources/js/pages/structures/competitiveness.tsx": "55338c144cefae4f91cef765b8e5e8b28ceb6c76375d46943c3c3430aeddc68e",
|
||||
"resources/js/pages/structures/editor.tsx": "080a90ab8607f05ec493e560ed8280a6f7eec743ed1954f0057a0ce6caa09208",
|
||||
"tests/frontend/cluster-competitiveness.test.mjs": "f48a9ed872f49ad900424daab4689cb0eeeb31cc93ebf1c608408c0a8c2b435b"
|
||||
},
|
||||
"candidate": "23ecccfaad1053f55bf0591fd242cb5fa3406c38",
|
||||
"backup": {
|
||||
"stage": "/var/backups/investmoz-competitiveness-delivery-20261029/backup",
|
||||
"created_at": "2026-10-29T11:04:46Z",
|
||||
"target": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432
|
||||
},
|
||||
"tables": 176,
|
||||
"files_verified": 369,
|
||||
"dump_sha256": "7979fa2b3fe1f69e62aad9fadf60a60d7b068e198cdc291a8fc79d409d67c7ca",
|
||||
"files_sha256": "8e0022b73cd0074e36f8efef0b7c803a386e24e6e4cf85f567757ff67e311369",
|
||||
"restore_verified": false
|
||||
},
|
||||
"restore": {
|
||||
"restore_verified": true,
|
||||
"tables_verified": 176,
|
||||
"container_network": "none",
|
||||
"database": "competitiveness_delivery_20261029_test",
|
||||
"port": 55441,
|
||||
"source_dump_sha256": "7979fa2b3fe1f69e62aad9fadf60a60d7b068e198cdc291a8fc79d409d67c7ca",
|
||||
"active_database_writes": 0
|
||||
},
|
||||
"preservation": {
|
||||
"navigation_asset_and_shared_props_verified": true,
|
||||
"at": "2026-10-29T11:10:44.303271+00:00",
|
||||
"served_commit": "23ecccfaad1053f55bf0591fd242cb5fa3406c38",
|
||||
"backup_dump_sha256": "7979fa2b3fe1f69e62aad9fadf60a60d7b068e198cdc291a8fc79d409d67c7ca",
|
||||
"prior_public_tables_checked": 176,
|
||||
"prior_domain_rows_preserved": true,
|
||||
"new_migration_registry_rows": 0,
|
||||
"operational_delta": {
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 119,
|
||||
"checksum": "5f3c36637fbf1e9dc4700066d4c45530"
|
||||
},
|
||||
"after": {
|
||||
"rows": 119,
|
||||
"checksum": "b1c9949cfacc34906c406e27e95cbd9b"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 37,
|
||||
"checksum": "b0e409c4c77c58b48252d9847c3c61ef"
|
||||
},
|
||||
"after": {
|
||||
"rows": 38,
|
||||
"checksum": "f4d94db55488bc0bcf6f727f222473c1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"persistent_files_and_configuration_identical": 369,
|
||||
"private_catalogue": {
|
||||
"observations": 361464,
|
||||
"distinct_administrative_observations": 214299,
|
||||
"preserved_repetitions": 147165,
|
||||
"unmapped_territory": 205608
|
||||
},
|
||||
"preservation_identity": "postgres, matching backup reader; no actor impersonation",
|
||||
"anonymous_query_status": 401,
|
||||
"public_revision_confirmed": true,
|
||||
"actual_team_UI_journey": "pending authenticated browser conference;accepted QA is not repeated",
|
||||
"unique_company_count": null,
|
||||
"publication": false,
|
||||
"national_coverage": "partial",
|
||||
"investment_conclusion": "hypothesis,not proved demand or viability",
|
||||
"L8": "unchanged,partial"
|
||||
},
|
||||
"installed_code": {
|
||||
"candidate": "23ecccfaad1053f55bf0591fd242cb5fa3406c38",
|
||||
"source_files_verified": 4,
|
||||
"diagnostics_C132": {
|
||||
"result": "passed",
|
||||
"case": "C132",
|
||||
"source_explicit_constant_OFF": true,
|
||||
"effective_configuration_OFF": true,
|
||||
"configuration_cached": false,
|
||||
"database_connections_used": 0,
|
||||
"active_writes": 0
|
||||
},
|
||||
"active_writes": 0
|
||||
},
|
||||
"pipeline": {
|
||||
"unit_tests": 59,
|
||||
"frontend_failures": 0,
|
||||
"schema_assertions": 3106,
|
||||
"checks": [
|
||||
"\u001b[30;42mOK (1 test, 3106 assertions)\u001b[0m",
|
||||
"✓ built in 34.50s",
|
||||
"\u001b[30;42mOK (59 tests, 320 assertions)\u001b[0m",
|
||||
"# tests 1180",
|
||||
"# pass 1180",
|
||||
"# fail 0"
|
||||
],
|
||||
"frontend_tests": 1180,
|
||||
"result": {
|
||||
"status": "installed",
|
||||
"commit": "23ecccfaad1053f55bf0591fd242cb5fa3406c38",
|
||||
"release": "/var/www/investmoz-homologacao/releases/23ecccfaad1053f55bf0591fd242cb5fa3406c38-0e0b8a65",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/332c16ebb555e8d6b244fa519bc777d89c1a8b8f-f0dfc218",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"23ecccfaad1053f55bf0591fd242cb5fa3406c38"
|
||||
],
|
||||
"finished_at": "2026-10-29T11:10:02.884033+00:00"
|
||||
},
|
||||
"unit_assertions": 320
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
{
|
||||
"date": "2026-10-28",
|
||||
"status": "installed_delta_verified_authenticated_visual_conference_pending",
|
||||
"served_commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"previous_runtime": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"target": "https://teste-investidor.tempo.co.mz/",
|
||||
"normal_Git_fast_forward": true,
|
||||
"force_used": false,
|
||||
"existing_pipeline_unchanged": true,
|
||||
"scope": [
|
||||
"National provincial catalogue/corridor coverage and territorial summaries",
|
||||
"One searchable territory control at all four levels",
|
||||
"Filtered catalogue results separate from optional educational support",
|
||||
"Adaptive opportunity preparation groups and save-before-resource navigation",
|
||||
"Readable promoter request with explicit searchable proof selection",
|
||||
"Immediate scoped zone search,total counts and complete pagination",
|
||||
"My investments next action and expandable stages/source details",
|
||||
"Direct entries to existing fillable investment/Terra-DUAT preparation;support form separately labelled",
|
||||
"Sector registration CTA uses effective account creation capability;no new permissions",
|
||||
"Readable known document topic/category/language labels"
|
||||
],
|
||||
"backup": {
|
||||
"stage": "/var/backups/investmoz-catalogue-territory-delivery-20261028/backup",
|
||||
"created_at": "2026-10-28T19:25:43Z",
|
||||
"target": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432
|
||||
},
|
||||
"tables": 176,
|
||||
"files_verified": 369,
|
||||
"dump_sha256": "597f73cda14dd47be440136f2e2242d8d7a4e4f3d5d69cabcd44f8fde58c136d",
|
||||
"files_sha256": "7fb639d8351e34ce220c5424c722c223512d139c82b7ff0a1a447136c62041ef",
|
||||
"restore_verified": false
|
||||
},
|
||||
"restore": {
|
||||
"restore_verified": true,
|
||||
"tables_verified": 176,
|
||||
"container_network": "none",
|
||||
"database": "catalogue_territory_delivery_20261028_test",
|
||||
"port": 55441,
|
||||
"source_dump_sha256": "597f73cda14dd47be440136f2e2242d8d7a4e4f3d5d69cabcd44f8fde58c136d",
|
||||
"active_database_writes": 0
|
||||
},
|
||||
"failed_candidate_preserved": {
|
||||
"commit": "502e3ec4",
|
||||
"reason": "Corridor explorer Unit mock missing the new public location presentation;unnecessary non-source relation read",
|
||||
"active_runtime_preserved": true,
|
||||
"resolution": "Short-circuit irrelevant source before relation access;represent new dependency and retain old assertions;Unit1/13 passed"
|
||||
},
|
||||
"pipeline": {
|
||||
"reports": [
|
||||
{
|
||||
"status": "already_installed",
|
||||
"commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"requested_commits": [
|
||||
"789fffd098fa222c85e1283de07f23ee6f42bd04"
|
||||
],
|
||||
"finished_at": "2026-10-28T19:39:46.948539+00:00"
|
||||
},
|
||||
{
|
||||
"status": "installed",
|
||||
"commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"release": "/var/www/investmoz-homologacao/releases/789fffd098fa222c85e1283de07f23ee6f42bd04-29ab1f0d",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/6e8de43ae7fec29b0766d95e209a8cb8baf0d88c-877dabd3",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"789fffd098fa222c85e1283de07f23ee6f42bd04"
|
||||
],
|
||||
"finished_at": "2026-10-28T19:39:45.796038+00:00"
|
||||
}
|
||||
],
|
||||
"build_logs": [
|
||||
{
|
||||
"file": "/var/lib/investmoz-deploy/logs/1793216167091522421.log",
|
||||
"sha256": "af1c3db072b2b354cfef13538a8cb69d07a37ec4b1ddef63d8d68e77ab5d7196",
|
||||
"summaries": [
|
||||
"\u001b[30;42mOK (1 test, 3106 assertions)\u001b[0m",
|
||||
"✓ built in 32.16s",
|
||||
"\u001b[30;42mOK (59 tests, 320 assertions)\u001b[0m",
|
||||
"# tests 1171",
|
||||
"# pass 1171",
|
||||
"# fail 0"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"installed_preservation_delta": {
|
||||
"navigation_asset_and_shared_props_verified": true,
|
||||
"at": "2026-10-28T19:40:32.494557+00:00",
|
||||
"served_commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"backup_dump_sha256": "597f73cda14dd47be440136f2e2242d8d7a4e4f3d5d69cabcd44f8fde58c136d",
|
||||
"prior_public_tables_checked": 176,
|
||||
"prior_domain_rows_preserved": true,
|
||||
"new_migration_registry_rows": 0,
|
||||
"operational_delta": {
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 111,
|
||||
"checksum": "1912b955cff09094395336c2137d5ce5"
|
||||
},
|
||||
"after": {
|
||||
"rows": 111,
|
||||
"checksum": "c158d3e941f896ca3997dfe02850d427"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 9,
|
||||
"checksum": "870b1c20d207a9db376633fc5514a3ed"
|
||||
},
|
||||
"after": {
|
||||
"rows": 8,
|
||||
"checksum": "f7737eac7d85ed501fb339d7faabbd8e"
|
||||
}
|
||||
}
|
||||
},
|
||||
"persistent_files_and_configuration_identical": 369,
|
||||
"private_catalogue": {
|
||||
"observations": 361464,
|
||||
"distinct_administrative_observations": 214299,
|
||||
"preserved_repetitions": 147165,
|
||||
"unmapped_territory": 205608
|
||||
},
|
||||
"RLS_without_actor_rows": 0,
|
||||
"anonymous_query_status": 401,
|
||||
"public_revision_confirmed": true,
|
||||
"actual_team_UI_journey": "pending authenticated browser conference;accepted QA is not repeated",
|
||||
"unique_company_count": null,
|
||||
"publication": false,
|
||||
"national_coverage": "partial",
|
||||
"investment_conclusion": "hypothesis,not proved demand or viability",
|
||||
"L8": "unchanged,partial"
|
||||
},
|
||||
"public_installed_delta": {
|
||||
"served_commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"public_Maputo_agribusiness_total": 5,
|
||||
"public_Tourism_Cabo_Delgado_total": 0,
|
||||
"Cabo_Delgado_zones_total": 2,
|
||||
"all_zones_total": 8,
|
||||
"all_zones_pages": 1,
|
||||
"filtered_scope_and_sector_confirmed": true,
|
||||
"installed_UI_assets_verified": [
|
||||
"Preencher formulários e preparar documentos",
|
||||
"Pesquisar nos meus ficheiros",
|
||||
"O meu acesso e administração",
|
||||
"Consultar situação, documentos e fundamentos"
|
||||
],
|
||||
"public_Tourism_HTTP": 200,
|
||||
"guest_Tourism_registration_action": "/perfil/promotor",
|
||||
"guest_Tourism_registration_label": "Pedir acesso para cadastrar oportunidades",
|
||||
"real_authenticated_Tourism_case": "pending;anonymous200 is not the real session",
|
||||
"pipeline_reports": [
|
||||
{
|
||||
"status": "already_installed",
|
||||
"commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"requested_commits": [
|
||||
"789fffd098fa222c85e1283de07f23ee6f42bd04"
|
||||
],
|
||||
"finished_at": "2026-10-28T19:39:46.948539+00:00"
|
||||
},
|
||||
{
|
||||
"status": "installed",
|
||||
"commit": "789fffd098fa222c85e1283de07f23ee6f42bd04",
|
||||
"release": "/var/www/investmoz-homologacao/releases/789fffd098fa222c85e1283de07f23ee6f42bd04-29ab1f0d",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/6e8de43ae7fec29b0766d95e209a8cb8baf0d88c-877dabd3",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"789fffd098fa222c85e1283de07f23ee6f42bd04"
|
||||
],
|
||||
"finished_at": "2026-10-28T19:39:45.796038+00:00"
|
||||
}
|
||||
],
|
||||
"no_schema_or_publication_changes": true,
|
||||
"source_files_preserved": true
|
||||
},
|
||||
"accepted_QA_reused": {
|
||||
"national_tests": 6,
|
||||
"national_assertions": 617,
|
||||
"selector_tests": 4,
|
||||
"guide_tests": 2,
|
||||
"usability_frontend_tests": 9,
|
||||
"usability_feature_tests": 3,
|
||||
"usability_feature_assertions": 14,
|
||||
"unit_regression_tests": 1,
|
||||
"unit_regression_assertions": 13,
|
||||
"types_build_PHP": "passed"
|
||||
},
|
||||
"remaining": [
|
||||
"Actual authenticated visual conference of responsive menus,free filling navigation,saved resource round-trip and Gurué same-dossier journey",
|
||||
"Tempo clarified Tourism denial followed a button;exact original button unavailable. Concrete creation CTA mismatch corrected and tested;real session still needs confirmation",
|
||||
"Clarify the particular official fiscal form sought;investment preparation adaptations are not a complete implementation of all IVA/IRPC official forms"
|
||||
],
|
||||
"preserved": {
|
||||
"old_release": "retained for existing rollback mechanism",
|
||||
"domain_data_permissions_publications": "unchanged",
|
||||
"persistent_files_and_configuration": 369,
|
||||
"private_supply_observations": 361464,
|
||||
"Gurue_observations": 435,
|
||||
"counts_are_not_unique_companies": true,
|
||||
"lists": "internal",
|
||||
"national_coverage": "partial",
|
||||
"investment_comparison": "hypothesis,not demand or viability proof",
|
||||
"L8": "partial,unchanged"
|
||||
},
|
||||
"proof_limits": "HTTP/API/asset checks do not prove the authenticated UI;prior QA/manual reports remain historical candidate evidence,not installation state",
|
||||
"source_QA_reports": [
|
||||
"catalogue-province-coverage-qa-20261028.json",
|
||||
"investor-usability-qa-20261028.json"
|
||||
],
|
||||
"authorisation": "Tempo requested corrections,authorised normal delivery,and authenticated the existing SSH mechanism;no repeated organisational approval required"
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"date": "2026-10-28",
|
||||
"status": "QA_implemented_and_delta_verified_not_installed",
|
||||
"runtime_baseline": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"prepared_catalogue_parent": "54d1b2a5",
|
||||
"Tempo_requests": [
|
||||
"Readable investor work menu and adaptive filling flow",
|
||||
"ZEE/ZFI/park results must match explicit territory selection;all means the available set",
|
||||
"Promoter request must use readable representation/modality labels and usable evidence selection",
|
||||
"Investigate authenticated denial of public Tourism sector",
|
||||
"Simplify My investments and present useful next actions",
|
||||
"Expose fillable forms rather than a guide or legislative catalogue"
|
||||
],
|
||||
"implemented": {
|
||||
"work_menu": "Investor actions remain primary;existing access/audit/profile setup destinations move into optional administration details;no permission change",
|
||||
"filling": "Schema fields grouped adaptively by task;free navigation,all fields stay mounted,unknown future keys retained;server missing paths and errors point to groups;not mandatory sequential forms",
|
||||
"preservation": "Deliberate values retained between groups;save uses existing endpoints and ETags;resource navigation saves first and returns to the same opportunity/group;only unique promoter context is auto-selected",
|
||||
"profile_request": "Portuguese visible representation/modality labels;owned clean-file criteria unchanged;file search and explicit selected proofs replace the unbounded list;availability does not prove evidentiary suitability",
|
||||
"zones": "Territory and other filter changes apply search;old records hidden while loading/error;all and filtered totals plus pagination explicit;existing public visibility preserved;validated legal coverage includes its child area,while influence is not treated as a site",
|
||||
"my_investments": "Next action remains prominent;other phases/stages expandable;source/code history and internal follow-up remain consultable rather than filling the main page",
|
||||
"forms": "Direct entries to existing private investment preparation fields and Terra/DUAT;support request separately labelled;originals/guides optional;no law is converted into a form or executable calculation",
|
||||
"document_taxonomy": "Known topic/category/language codes have Portuguese display labels;original query values preserved"
|
||||
},
|
||||
"QA": {
|
||||
"frontend_contract_and_SSR_tests": 9,
|
||||
"frontend_failures": 0,
|
||||
"isolated_feature_tests": 3,
|
||||
"feature_assertions": 14,
|
||||
"feature_failures": 0,
|
||||
"database": "proactive_investment_20261027_test",
|
||||
"port": 55441,
|
||||
"transactions_rolled_back": true,
|
||||
"types": "passed",
|
||||
"build": "passed",
|
||||
"PHP_syntax": "passed",
|
||||
"accepted_national_selector_and_catalogue_proofs": "reused",
|
||||
"unit_regression_tests": 1,
|
||||
"unit_regression_assertions": 13
|
||||
},
|
||||
"Tourism_incident": {
|
||||
"reported_by_Tempo": "authenticated session saw access denial at /sectores/turismo",
|
||||
"anonymous_live_HTTP": 200,
|
||||
"isolated_guest_and_no_promoter_account_HTTP": 200,
|
||||
"exact_real_session_cause": "not demonstrated;do not infer missing role or claim correction",
|
||||
"private_permissions_changed": false,
|
||||
"next": "Confer the actual authenticated session and related logs;public read is not real-session proof",
|
||||
"reported_action": "Tempo clarified denial followed a button click;exact label could not be recalled",
|
||||
"bounded_code_finding": "Sector registration action depended on module availability rather than effective account creation capability",
|
||||
"QA_correction": "Reuse ContentManagement effective create destination;otherwise explicitly link to existing promoter request with a readable label;public consultation and idea preparation remain separate",
|
||||
"real_session_reconference": "pending;the exact original button is not demonstrated"
|
||||
},
|
||||
"limits": [
|
||||
"Not installed in this QA report",
|
||||
"SSR and controlled event tests are not browser keyboard/touch/layout evidence",
|
||||
"Existing form adaptations are exposed;this does not implement every official form in the document collection",
|
||||
"No new roles,publications,source edits,schema changes or fiscal activation",
|
||||
"L8 remains partial"
|
||||
],
|
||||
"restriction_origins": {
|
||||
"UX_and_selected_scope": "Tempo current express instructions",
|
||||
"data_and_permissions_preservation": "permanent project instructions",
|
||||
"grouping_and_collapsed_details": "implementation choice,not new organisational requirement",
|
||||
"document_ownership_scan_and_existing_workflows": "prior contracts preserved"
|
||||
},
|
||||
"delivery_gate": {
|
||||
"candidate": "502e3ec4",
|
||||
"result": "failed before runtime switch;6e8de43a preserved",
|
||||
"reason": "Unit mock did not represent new public location presentation;unnecessary relation query on non-source records",
|
||||
"correction": "Short-circuit source applicability before reading relations;mock the new presentation dependency and retain prior identity/count assertions",
|
||||
"unit_regression": "1 test/13 assertions passed",
|
||||
"pipeline_guardrails": "unchanged;no schema migration or test-gate weakening"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
{
|
||||
"date": "2026-10-28",
|
||||
"status": "installed_technical_navigation_delta_verified_authenticated_visual_conference_pending",
|
||||
"served_commit": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"previous_runtime": "6d1476936920dc5715d4493b1f8b22a3d51935f4",
|
||||
"target": "https://teste-investidor.tempo.co.mz/",
|
||||
"authorisation": "Tempo approved the QA menu proposal and authenticated the existing SSH delivery mechanism",
|
||||
"normal_git_fast_forward": true,
|
||||
"force_used": false,
|
||||
"backup": {
|
||||
"stage": "/var/backups/investmoz-navigation-delivery-20261028/backup",
|
||||
"created_at": "2026-10-28T18:18:14Z",
|
||||
"target": {
|
||||
"database": "teste_investidor",
|
||||
"port": 5432
|
||||
},
|
||||
"tables": 176,
|
||||
"files_verified": 369,
|
||||
"dump_sha256": "748539aa92cf4a0e22698a3b7651faa7a4452db2517ddb811a924b761ea9dce5",
|
||||
"files_sha256": "946dd8d33903332557639103b8f5ad5bca955fd3ec79f112e3649128fea8c499",
|
||||
"restore_verified": false
|
||||
},
|
||||
"restore": {
|
||||
"restore_verified": true,
|
||||
"tables_verified": 176,
|
||||
"container_network": "none",
|
||||
"database": "navigation_delivery_20261028_test",
|
||||
"port": 55441,
|
||||
"source_dump_sha256": "748539aa92cf4a0e22698a3b7651faa7a4452db2517ddb811a924b761ea9dce5",
|
||||
"active_database_writes": 0
|
||||
},
|
||||
"guard": {
|
||||
"ready_for_normal_git_delivery": true,
|
||||
"restore_verified": true,
|
||||
"tables_verified": 176,
|
||||
"pipeline_and_schema_contract_unchanged": true,
|
||||
"candidate": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c"
|
||||
},
|
||||
"installed_delta": {
|
||||
"navigation_asset_and_shared_props_verified": true,
|
||||
"at": "2026-10-28T18:23:39.508498+00:00",
|
||||
"served_commit": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"backup_dump_sha256": "748539aa92cf4a0e22698a3b7651faa7a4452db2517ddb811a924b761ea9dce5",
|
||||
"prior_public_tables_checked": 176,
|
||||
"prior_domain_rows_preserved": true,
|
||||
"new_migration_registry_rows": 0,
|
||||
"operational_delta": {
|
||||
"cache": {
|
||||
"before": {
|
||||
"rows": 111,
|
||||
"checksum": "650ce50f1aa1af7e7025bcbaa7bcd6ba"
|
||||
},
|
||||
"after": {
|
||||
"rows": 111,
|
||||
"checksum": "ea8070b2c9a513485bfb27462e379703"
|
||||
}
|
||||
},
|
||||
"sessions": {
|
||||
"before": {
|
||||
"rows": 4,
|
||||
"checksum": "f0d8b267cdf55c86ba8223d9e1ff3c6a"
|
||||
},
|
||||
"after": {
|
||||
"rows": 5,
|
||||
"checksum": "99071034149a154c7e17acc47e058dae"
|
||||
}
|
||||
}
|
||||
},
|
||||
"persistent_files_and_configuration_identical": 369,
|
||||
"private_catalogue": {
|
||||
"observations": 361464,
|
||||
"distinct_administrative_observations": 214299,
|
||||
"preserved_repetitions": 147165,
|
||||
"unmapped_territory": 205608
|
||||
},
|
||||
"RLS_without_actor_rows": 0,
|
||||
"anonymous_query_status": 401,
|
||||
"public_revision_confirmed": true,
|
||||
"actual_team_UI_journey": "pending authenticated browser conference;accepted QA is not repeated",
|
||||
"unique_company_count": null,
|
||||
"publication": false,
|
||||
"national_coverage": "partial",
|
||||
"investment_conclusion": "hypothesis,not proved demand or viability",
|
||||
"L8": "unchanged,partial"
|
||||
},
|
||||
"existing_pipeline_receipt": {
|
||||
"reports": [
|
||||
{
|
||||
"status": "already_installed",
|
||||
"commit": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"requested_commits": [
|
||||
"6e8de43ae7fec29b0766d95e209a8cb8baf0d88c"
|
||||
],
|
||||
"finished_at": "2026-10-28T18:23:07.685587+00:00"
|
||||
},
|
||||
{
|
||||
"status": "installed",
|
||||
"commit": "6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"release": "/var/www/investmoz-homologacao/releases/6e8de43ae7fec29b0766d95e209a8cb8baf0d88c-877dabd3",
|
||||
"previous_release": "/var/www/investmoz-homologacao/releases/6d1476936920dc5715d4493b1f8b22a3d51935f4-c9ebfad4",
|
||||
"database_migrations": 0,
|
||||
"content_imports": 0,
|
||||
"requested_commits": [
|
||||
"6e8de43ae7fec29b0766d95e209a8cb8baf0d88c"
|
||||
],
|
||||
"finished_at": "2026-10-28T18:23:06.355940+00:00"
|
||||
}
|
||||
],
|
||||
"build_log": "/var/lib/investmoz-deploy/logs/1793211570315386207.log",
|
||||
"build_log_sha256": "7b1d78a066ed829cbdabc67549baf4835ab8f911b8c4b178be09539ed434ddde",
|
||||
"summaries": [
|
||||
"\u001b[30;42mOK (1 test, 3106 assertions)\u001b[0m",
|
||||
"✓ built in 31.30s",
|
||||
"\u001b[30;42mOK (59 tests, 317 assertions)\u001b[0m",
|
||||
"# tests 1156",
|
||||
"# pass 1156",
|
||||
"# fail 0"
|
||||
],
|
||||
"last_lines": [
|
||||
"ext-pcre 8.4.27 success ",
|
||||
"ext-session 8.4.27 success ",
|
||||
"ext-tokenizer 8.4.27 success ",
|
||||
"php 8.4.27 success ",
|
||||
"6e8de43ae7fec29b0766d95e209a8cb8baf0d88c",
|
||||
"",
|
||||
" INFO Broadcasting queue restart signal. ",
|
||||
""
|
||||
]
|
||||
},
|
||||
"accepted_QA_reused": {
|
||||
"directed_tests": 16,
|
||||
"types": "passed",
|
||||
"build": "passed",
|
||||
"PHP_syntax": "passed"
|
||||
},
|
||||
"UI_delta": [
|
||||
"Área de trabalho visible in principal navigation; operational entries follow existing effective capabilities",
|
||||
"Sidebar preserves every nested destination and territorial context instead of exposing only the first link",
|
||||
"Existing opportunity analysis form can be opened directly without replacing saved analysis",
|
||||
"Existing account, content, investment and follow-up destinations retained; no new roles or grants"
|
||||
],
|
||||
"remaining": [
|
||||
"Authenticated visual conference on the actual account, including responsive layout and keyboard/touch",
|
||||
"Confirm Gurué → offer consultation → idea comparison → save → recover in the same dossier; technical/QA proofs remain accepted"
|
||||
],
|
||||
"connector_last_known_error": "The browser access host is unavailable",
|
||||
"limitations": {
|
||||
"technical_delivery_is_not_visual_session_evidence": true,
|
||||
"435_Gurue_observations_are_not_435_unique_companies": true,
|
||||
"lists_remain_internal": true,
|
||||
"national_coverage": "partial",
|
||||
"absence_of_records": "insufficient information",
|
||||
"comparison": "investment hypothesis; does not establish demand or viability",
|
||||
"L8": "unchanged,partial"
|
||||
},
|
||||
"restriction_origins": {
|
||||
"delivery": "explicit Tempo authorisation",
|
||||
"preservation_and_restore": "permanent project instructions",
|
||||
"grouping_and_presentation": "implementation choice within the approved QA proposal; no new business authority"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -7260,3 +7260,144 @@ CI habitual do instalador: PostgreSQL1/3106asserções, Unit59/317, frontend1146
|
||||
`6d147693` está instalado, incluindo a base interna. A única pendência da conferência desta entrega é a validação visual autenticada: **Gurué → consultar oferta → comparar ideia → guardar → recuperar no mesmo dossier**, conservando fonte, data e incertezas. As435 observações de Gurué não são435 empresas únicas. Listas internas, cobertura nacional parcial e hipótese de investimento mantêm-se.
|
||||
|
||||
O erro actual, novamente observado, é **“The browser access host is unavailable”**: indisponibilidade do host do conector, distinta de deixar uma aba aberta. A orientação anterior para apenas manter a aba aberta era insuficiente. Restabelecer o conector por mecanismo suportado ou realizar a conferência pela equipa. Não reinstalar nem repetir as provas técnicas aceites; não declarar conferência visual concluída sem o seu resultado. O recibo remoto original e o historial do diagnóstico anterior ficam preservados; esta correcção é documental.
|
||||
|
||||
|
||||
## 28/10/2026 — revisão de menus: inventário antes da verificação do delta
|
||||
|
||||
Origem: recomendação expressa da Tempo após constatar que as entradas indicadas não aparecem ou ficam escondidas. Página relatada:https://teste-investidor.tempo.co.mz/. Preservados6d147693 e a base privada instalada,as provas QA do percurso e da navegação sectorial,os originais,dados,perfis,permissões e históricos. Não se declara uma funcionalidade anterior desaparecida apenas pela ausência de um novo teste.
|
||||
|
||||
Confirmado no código: barra lateral substitui cada grupo pelo seu primeiro destino,omitindo os restantes;menu principal esconde gestão/perfis dentro do menu do nome do utilizador;entrada de gestão de conteúdos existente não é incorporada nessa navegação principal. A conta e os props efectivos da sessão real permanecem por conferir,porque o conector está indisponível;não se presume falta de autorização.
|
||||
|
||||
Incremento em QA: área de trabalho explícita no menu principal,inclusive entrada neutra de acesso;destinos privados apenas segundo capacidades anteriores;mesmo catálogo completo na barra lateral,sem perda dos subdestinos;entrada directa na análise proactiva existente,sem substituir rascunhos editados;preservação de Descoberta/Realização/Suporte e todos os destinos anteriores aplicáveis. Sem alteração activa,schema,regras de negócio ou papéis. Escolhas de apresentação não são exigências organizacionais. Verificação dirigida do delta pendente nesta fotografia;nenhuma nova matriz ou backlog.
|
||||
|
||||
|
||||
## 28/10/2026 — reorganização dos menus implementada em QA, sem instalação
|
||||
|
||||
Recomendação expressa da Tempo após a página principal não apresentar as entradas sugeridas. Causa delimitada no código: a barra lateral omitia subdestinos ao seleccionar apenas o primeiro link de cada grupo; a navegação principal colocava gestão/perfis dentro do menu do nome do utilizador e não incorporava a entrada de gestão já calculada pelo servidor. Não se presume falta de permissões da sessão real, cujos props não foram observados. A entrega6d147693/base interna continua instalada e preservada; esta revisão não reinstala essa base nem repete as provas técnicas aceites.
|
||||
|
||||
**Proposta executável QA:** Área de trabalho visível ao lado de Descoberta,Realização,Suporte; entrada neutra Acesso à gestão explica o estado, mesmo sem acções privadas atribuídas. As acções autorizadas e Preparar análise e ideia vêm das capacidades existentes, sem criar papéis. A análise abre directamente no formulário existente; rascunhos guardados não são substituídos. A barra lateral põe trabalho primeiro e conserva todos os destinos e os filtros territoriais entre catálogos, em vez de reduzir grupos ao primeiro destino. O cabeçalho permite quebra de linha em largura intermédia; os controlos móveis e do teclado existentes são reutilizados.
|
||||
|
||||
**Verificação delimitada:**16 testes de navegação/renderização estrutural,0falhas;tipos,compilação QA e sintaxe PHP passaram. Quatro cenários de capacidades conservaram todos os destinos anteriores; não surgem operações privadas em cenário anónimo ou sem atribuições. SSR usa o componente real da barra lateral com wrappers semânticos de teste; não equivale a captura do navegador. A prévia HTML é um inventário interactivo de destinos, sem pedidos ao portal, identificado como proposta QA, não como sessão real.
|
||||
|
||||
**Pendente:** conferência visual desktop/móvel/teclado/toque e das capacidades efectivas da sessão relatada; o host do conector permanece indisponível no último diagnóstico. Não substituir essa conferência por alegação de acesso demonstrado. A instalação futura deve transportar só o delta de menus pelo processo Git/backup/restauro existente, preservando originais, dados, permissões, contexto,dossier e simulador.435 observações de Gurué não são435empresas únicas; listas internas/cobertura parcial/hipótese preservadas. L8 continua parcial.
|
||||
|
||||
Inventário anterior registado antes dos testes nesta matriz/manual. Actualização apenas nos requisitos existentesV2-01,V2-07,V2-10,MASTER-9dee08d0-0011,MASTER-9f6dd1d9-0001,MASTER-9f6dd1d9-0003,MASTER-02f44baf-0002;não há matriz ou backlog novos. Relatório:`navigation-reconciliation-qa-20261028.json`;prévia:`outputs/navigation-reconciliation-20261028/menu-proposta-qa.html`.
|
||||
|
||||
A apresentação da gestão antiga usa agora a decisão efectiva já existente (`legacyWriteAllowed`, com o requisito de email verificado das rotas), em vez de presumir que o indicador genérico de gestor basta. Não se alteraram regras, atribuições ou permissões. Preservada também a entrada de instalação de perfis anteriormente presente apenas na barra lateral autorizada. Os nomes longos quebram linha na barra lateral, sem reticências que escondam a função.
|
||||
|
||||
|
||||
## 28/10/2026 — menus 6e8de43a instalados pelo Git; conferência visual pendente
|
||||
|
||||
A Tempo aprovou a proposta QA e autenticou o transporte SSH existente. `main` avançou normalmente de `6d147693` para `6e8de43a`, sem force. A entrega usou o pipeline existente, sem alterar o seu contrato de schema, sem migrações, importações, atribuições de papéis ou permissões. Os 16 testes dirigidos e as provas QA aceites foram reutilizados; as verificações automáticas obrigatórias do pipeline não representam nova aceitação funcional.
|
||||
|
||||
Capacidade conferida antes da entrega: cerca de 78,5 GiB livres. Backup novo em `/var/backups/investmoz-navigation-delivery-20261028/backup`; restauro em base isolada, sem rede, confirmou as 176 tabelas por contagens/checksums. Os 369 ficheiros persistentes/configuração mantêm-se idênticos. As tabelas de domínio, incluindo base interna, relações e permissões, foram comparadas com o snapshot do backup; apenas alterações operacionais de cache/sessão são registadas separadamente. A versão anterior está preservada para retorno pelo mecanismo existente.
|
||||
|
||||
O delta instalado contém Área de trabalho no nível principal, destinos subordinados completos na barra lateral e continuidade para os destinos existentes de investimento, conteúdos e acompanhamento. A exposição das acções respeita a decisão efectiva do servidor; não se infere nova autorização pelo nome genérico de gestor. A presença dos assets e props instalados foi conferida tecnicamente, sem a apresentar como prova da sessão real.
|
||||
|
||||
Pendente: conferência visual autenticada desktop/móvel/teclado/toque e percurso Gurué → consultar oferta → comparar ideia → guardar → recuperar no mesmo dossier. Último bloqueio conhecido: `The browser access host is unavailable`; uma aba aberta não restabelece o host. Não repetir as provas QA aceites nem reinstalar a base interna para resolver essa pendência. As 435 observações de Gurué não equivalem a 435 empresas únicas; listas internas, cobertura parcial e hipótese de investimento mantêm-se explícitas. L8 permanece parcial.
|
||||
|
||||
Evidência: `docs/investmoz/unification/navigation-git-delivery-20261028.json`. O relatório QA anterior permanece como histórico do candidato antes da instalação. Actualizados os mesmos sete requisitos existentes, preservando o seu histórico; não foi criada outra matriz.
|
||||
# Inventário de preservação — consulta territorial, 28/10/2026
|
||||
|
||||
Antes das novas verificações: menus `6e8de43a` instalados, base interna e percurso proactivo preservados; conferência visual autenticada continua pendente. Reutilizam-se as provas anteriores. O caso relatado é Agronegócio / Maputo Província. Em leitura da QA isolada, as 37 oportunidades públicas incluem cinco do Corredor de Maputo; o filtro provincial devolve zero. A correspondência aprovada do corredor para Maputo Província e Maputo Cidade já existe em `config/investment_corridors.php` e `corridor-adaptive-context-20261023.json`, mas a pesquisa não a utiliza. Não se trata de eliminação dos registos. Os cartões mostram apenas província e omitem o detalhe territorial disponível. A correcção é de consulta/apresentação, sem criar localizações distritais não documentadas, relações a mestres, permissões ou novas publicações. Referência aos requisitos existentes V2-07/V2-10; a implementação transversal e a sessão real não ficam declaradas concluídas por este inventário.
|
||||
|
||||
|
||||
## 28/10/2026 — correcção provincial do catálogo em QA, ainda sem instalação
|
||||
|
||||
Caso da Tempo: Agronegócio / Maputo Província. A leitura QA reproduziu zero resultados para cinco oportunidades públicas do Corredor de Maputo. Reutilizada a decisão expressa de 23/10 que abrange Maputo Província e Maputo Cidade, antes disponível no percurso mas omitida na consulta. O filtro provincial passa a incluir esse contexto aprovado, mantendo sector e estado público, sem duplicar oportunidades nem atribuir distrito/posto administrativo ou coordenadas inexistentes. Uma localização explícita posterior prevalece sobre o contexto antigo.
|
||||
|
||||
Os resultados apresentam a hierarquia territorial disponível; o contexto de corredor é identificado e os níveis não indicados continuam explícitos. Pesquisa/API, vista por corredores e lista sem coordenadas do mapa concordam. O atalho «Ver toda a província» elimina a necessidade de limpar vários níveis manualmente. Não foram criadas publicações, relações a mestres ou permissões. Provas QA: 4 testes/70 verificações, zero falhas, transacções revertidas; tipos, compilação QA e sintaxe PHP passaram. O inventário anterior foi registado antes dos testes. Menus 6e8de43a, base interna, históricos e aceitação anterior preservados; L8 permanece parcial.
|
||||
|
||||
Relatório: `catalogue-province-coverage-qa-20261028.json`. Instalação pelo processo Git e conferência visual autenticada continuam pendentes. Não declarar auditados todos os outros menus por este delta. Cobertura actualizada nos requisitos existentes V2-07/V2-10; sem nova matriz.
|
||||
|
||||
|
||||
28/10 — Âmbito nacional confirmado pela Tempo: antes da extensão dos testes, preservar a correcção QA 1b2ede41 e verificar os seis corredores aprovados nas onze unidades provinciais, hierarquia descendente e reutilização entre sectores/entradas de localização. Não presumir cobertura de corredor onde não está documentada. Nenhuma prova anterior é revogada.
|
||||
|
||||
|
||||
|
||||
28/10 - National coverage: 6 tests / 617 assertions passed across all 11 provincial units, 6 configured corridors and 2 sectors, including descendant hierarchy, sector separation and both province/location entry points. The runtime correction already used the common national hierarchy; Maputo was the reported reproduction, not a geographic limit. Existing publication decisions and unknown district/post/site information remain preserved. This is not a claim that every unrelated portal menu has been audited. No additional runtime change since 1b2ede41; types/build accepted evidence reused. Installation remains pending.
|
||||
|
||||
|
||||
28/10 - Before selector delta checks: accepted national catalogue QA 47dae1b7, 6 tests/617 assertions, remains uninstalled. Existing TerritoryLevel and ProvinceSelect required two separate fields (search then select). Tempo requests one dropdown on the search field. Consolidate the shared controls while retaining saved values, hierarchy, endpoints, paging and permission decisions;browser visual proof remains separate.
|
||||
|
||||
|
||||
|
||||
## 28/10/2026 — selecção territorial num único campo de pesquisa, QA
|
||||
|
||||
Pedido expresso da Tempo: o dropdown deve abrir em «Pesquisar província», sem um segundo controlo «Seleccione». `ProvinceSelect` e `TerritoryLevel` passam a usar o mesmo combobox, aplicado a província, distrito, posto administrativo e localidade. Pesquisar e escolher fica num único campo; a paginação permanece na lista. Escrever ou sair com Escape não substitui a selecção guardada; escolher e limpar são acções expressas. Mantêm-se a hierarquia, os endpoints existentes e os controlos de acesso, sem novos dados ou publicações.
|
||||
|
||||
Quatro testes do contrato de eventos/estado passaram: abertura/escolha, preservação ao escrever/Escape, teclado e bloqueio de resultado antigo durante carregamento, limpeza e dependência do nível anterior. Tipos e compilação QA passaram. As 6 provas nacionais/617 verificações são reutilizadas porque o PHP territorial não mudou. Este delta continua em QA e não comprova apresentação ou sessão real no navegador. Será agrupado com a correcção provincial; falta autenticação SSH antes da entrega, sem nova aprovação organizacional.
|
||||
|
||||
|
||||
28/10 - Before catalogue presentation checks: accepted province QA6/617 and unified selector QA4 remain preserved and uninstalled. Tempo reports Tourism/Cabo Delgado shows educational text and broad sector links. Read-only public API confirmed zero filtered records;unfiltered tourism returns16 records,all declared in Inhambane. This does not establish absence of tourism supply in Cabo Delgado. Correct presentation to retain filters and expose guides only as optional links;do not republish or reassign opportunities to manufacture results.
|
||||
|
||||
## 28/10/2026 — resultados do catálogo separados do apoio educativo, QA
|
||||
|
||||
A Tempo esclareceu que a combinação província/sector deve apresentar as oportunidades correspondentes, sem texto educativo ou atalhos que troquem a consulta por todas as oportunidades do sector. A consulta pública anónima conferiu Turismo/Cabo Delgado = zero oportunidades cadastradas; Turismo sem localização = 16, todas declaradas em Inhambane. Este snapshot não prova ausência de oferta turística em Cabo Delgado e não substitui inventário de fontes ou consulta autenticada.
|
||||
|
||||
Correcção de apresentação em QA: título dos resultados explicita sector e hierarquia escolhidos; removidos os cartões educativos e o botão sectorial sem localização da área de resultados. Os guias mantêm-se como títulos ligados em apoio opcional fechado por defeito. A remoção da localização é uma acção expressamente identificada como pesquisa noutras províncias. O estado vazio refere o cadastro consultado e a cobertura incompleta, sem fabricar oportunidades nem alargar automaticamente filtros.
|
||||
|
||||
Dois testes SSR do novo apoio opcional passaram, bem como tipos e compilação. As provas territoriais nacionais 6/617 e os quatro testes do selector são reutilizados; não mudou a consulta PHP ou o controlo territorial neste delta. Mantêm-se histórico, publicações, permissões, fontes e base interna. Este candidato continua sem instalação, dependente de autenticação SSH; a sessão real permanece sem prova visual. Relatório existente: `catalogue-province-coverage-qa-20261028.json`, campo `catalogue_result_presentation`. Requisitos V2-07/V2-10 actualizados na mesma matriz; L8 permanece parcial.
|
||||
|
||||
|
||||
28/10 - Before investor usability checks: accepted catalogue candidate54d1b2a5 remains in QA,not installed;active menus6e8de43a and earlier supply proofs preserved. Two Tempo attachments identify duplicate profile navigation,an exposed long canonical form and ZEE/ZFI/park searches that keep prior results until manual submit. Prepare presentation-only adaptive field groups and safe save-before-resource navigation;verify territorial search/count/paging and documented scope without republishing records or changing permissions. Reuse prior proofs;existing V2-07/V2-10 scope retained.
|
||||
|
||||
## 28/10/2026 — usabilidade do investidor e consulta territorial, QA
|
||||
|
||||
Pedidos da Tempo e exemplos recebidos: menu/ficha de oportunidade, zonas/parques, pedido de Promotor, Os meus investimentos, documentos/formulários e recusa autenticada em Turismo. Inventário anterior registado antes dos testes: menus 6e8de43a e base interna instalados; candidato territorial 54d1b2a5 ainda em QA; originais, dados, relações, histórico, aprovações e provas anteriores preservados.
|
||||
|
||||
Delta QA: acções do investidor em primeiro plano, administração em detalhe consultável; campos do contrato existente agrupados por tarefa e modalidade, com navegação livre e todos os campos montados para conservar edições. Os grupos mostram as pendências da última gravação e os erros existentes; não criam seis ou oito formulários obrigatórios. Guardar usa os mesmos endpoints/ETags; abrir recursos pela preparação guarda primeiro e regressa à mesma oportunidade/grupo. Contactos e detalhes de disponibilidade ficam opcionais; códigos técnicos de categorias e campos conhecidos têm nomes em português. Só um contexto único de promotor é escolhido automaticamente.
|
||||
|
||||
Zonas: selecção territorial aplica pesquisa sem esperar por outro clique; a lista anterior deixa de aparecer durante carregamento/erro. Totais, intervalo visível e páginas identificados, sem apresentar a primeira página como o conjunto completo. «Todo o território» remove expressamente a localização, preservando os restantes critérios visíveis. Abrangência jurídica documentada e validada inclui os níveis descendentes; influência não se torna implantação. Não são criadas localizações, direitos, publicações ou certificados.
|
||||
|
||||
Pedido de Promotor: representação/modalidades com nomes claros; pesquisa de ficheiros e selecção expressa dos comprovativos, preservando os escolhidos ao pesquisar. Mantidos propriedade, análise antimalware e verificações existentes; legislação/imagem/teste não se torna comprovativo por estar disponível. Os meus investimentos destaca a próxima acção e permite abrir fases/etapas; fontes, códigos e acompanhamento interno ficam preservados em detalhes.
|
||||
|
||||
Formulários: entradas directas para os campos já existentes da preparação do pedido de investimento e Terra/DUAT; pedido de apoio identificado separadamente. Originais oficiais e guias continuam consultáveis, sem os confundir com um formulário preenchível ou converter leis em campos/cálculos. Não se declara executada a totalidade dos formulários oficiais do acervo.
|
||||
|
||||
Provas delimitadas: 8 testes frontend de contrato/SSR e 3 testes isolados/12 verificações, zero falhas; tipos, compilação e sintaxe PHP passaram. Dados sintéticos revertidos em QA. Provas nacionais/selector/catálogo anteriores reutilizadas. Turismo: leitura anónima activa HTTP200 e QA visitante/conta sem Promotor HTTP200; a recusa da sessão real relatada não foi reproduzida, nem atribuída a uma permissão sem prova. A conferência autenticada e visual continua pendente. Este registo não instala o candidato nem encerra a implementação transversal. L8 permanece parcial.
|
||||
|
||||
Evidência: `investor-usability-qa-20261028.json`. Actualizados V2-01,V2-07,V2-10 na matriz existente; sem nova matriz ou backlog.
|
||||
|
||||
|
||||
### 28/10 — botão de cadastro e compatibilidade do pipeline
|
||||
|
||||
A Tempo esclareceu que a recusa em Turismo ocorreu depois de clicar num botão; não foi possível recuperar o nome. A rota pública continuou HTTP200. Conferência de forma pública/origem não identificou anexos privados nos documentos públicos de Turismo; não se atribui a recusa à perda de publicação. Encontrada uma falha delimitada no consumidor: o botão de cadastro dependia da disponibilidade do módulo, sem a capacidade efectiva da conta. Corrigido para reutilizar o destino autorizado de criação de ContentManagement; sem essa capacidade, mostra expressamente o pedido de acesso já existente. Não cria papéis nem restringe a consulta pública ou a preparação de ideias. A confirmação visual da acção real permanece pendente.
|
||||
|
||||
O candidato 502e3ec4 falhou na Unit de agrupamento de corredores antes da troca de release; 6e8de43a ficou servido. Causa: a simulação do catálogo não representava a nova apresentação de localização e uma consulta era feita antes de conferir se a fonte era aplicável. Correcção: conferir primeiro a fonte e simular a nova dependência no teste, conservando as verificações anteriores de identidade, grupos e contagens. Regressão Unit1/13 passou; não foi alterado o pipeline, o contrato de schema ou a exigência dos testes. Frontend9, Feature3/14, tipos e compilação passaram. Rótulos conhecidos de temas, categorias e idiomas do acervo traduzidos para apresentação; valores dos filtros preservados.
|
||||
|
||||
|
||||
## 28/10/2026 — entrega agrupada de usabilidade e filtros instalada, 789fffd0
|
||||
|
||||
Entrega autorizada pela Tempo e autenticada pelo mecanismo SSH existente. `main` avançou normalmente e o pipeline existente instalou `789fffd0`, preservando a release anterior `6e8de43a`. O candidato inicial `502e3ec4` foi recusado antes da troca por uma dependência não representada no teste Unit do agrupamento de corredores; o activo ficou preservado. A consulta desnecessária foi corrigida e a nova dependência simulada, conservando as provas anteriores. O pipeline e o seu contrato de schema não foram enfraquecidos.
|
||||
|
||||
Backup/restauro de 176 tabelas confirmado numa instância isolada, sem rede. Os 369 ficheiros persistentes/configuração mantêm-se idênticos. A comparação do snapshot com o instalado preserva as tabelas de domínio, incluindo papéis, publicações, originais e base interna; diferenças de cache/sessões são registadas separadamente. Sem migrações, importações ou activação fiscal. A versão anterior permanece disponível para o mecanismo de retorno.
|
||||
|
||||
Incluídos: consulta provincial nacional/corredores e detalhe territorial; pesquisa/selecção num único controlo; resultados do catálogo separados do apoio educativo; grupos adaptáveis de preenchimento, navegação livre e gravação antes de abrir recursos; pedido de Promotor legível com comprovativos escolhidos expressamente; zonas filtradas ao seleccionar, contagens/paginação visíveis; fases/etapas do dossier e fontes em detalhes; entradas para formulários de preparação já existentes; CTA sectorial conforme capacidade efectiva; rótulos do acervo legíveis. Não são novas permissões, publicações ou formulários fiscais oficiais inventados.
|
||||
|
||||
Conferidos o commit servido, APIs filtradas e assets instalados. Reutilizadas as provas QA aceites; a bateria obrigatória do pipeline não reabre a sua aceitação. Mantém-se pendente a conferência visual autenticada, incluindo navegação, ida/volta a recursos e Gurué no mesmo dossier. A recusa relatada em Turismo ocorreu após um botão; a falha concreta do CTA de cadastro foi corrigida, mas não se declara reproduzida e resolvida a acção original sem a sessão real. A escolha do formulário fiscal concreto ainda precisa de ser esclarecida; os diplomas IVA mostrados não são formulários preenchíveis.
|
||||
|
||||
Estado actual: `investor-usability-git-delivery-20261028.json`. Os relatórios QA anteriores conservam o estado histórico antes da instalação. As 435 observações de Gurué não são 435 empresas; as listas são internas, a cobertura nacional é parcial e a comparação sustenta hipóteses. L8 permanece parcial. Actualizados V2-01/V2-07/V2-10 na matriz e manual existentes.
|
||||
|
||||
|
||||
## 28/10/2026 — preparação de formulários fiscais, inventário antes das provas
|
||||
|
||||
Pedido expresso da Tempo: preencher formulário de IVA ou IRPC, em vez de abrir legislação. Base preservada: entrega instalada 789fffd0, Modelo A e aquisições/apuramento já aceites, L6 M20/M22 instalado em 5aaf1a56 e incrementos de L8. Nenhuma perda confirmada neste recorte; não se apagam as aceitações nem se repetem provas fiscais anteriores. Fontes reutilizadas do inventário de 20 exemplares acessíveis em outputs/irpc-l6-values-forms/accessible-source-inventory.json da QA anterior, incluindo temporários identificados; inventário do corpus e originais preservados. M22: três páginas conferidas visualmente nesta revisão, SHA256 4b61bd83d1fbcfd3b7b5c5523cea5923f7d0f65dc4c004eff58e5db38f763c88. Modelo A: correspondência e divergências aceites em modelo-a-reconciliacao-20261021.md; sem nova validação de proveniência.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
### 03/11/2026 — pesquisa rápida, incremento local em preparação
|
||||
|
||||
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.
|
||||
|
||||
|
||||
### 03/11/2026 — pesquisa sem acesso à base
|
||||
|
||||
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.
|
||||
|
||||
|
||||
### 04/11/2026 — pesquisa unificada, candidata local
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -3006,3 +3006,65 @@ AUD-SIM-INT01 through AUD-SIM-INT08 are recorded in the same matrix and manual.
|
||||
Actualização QA de 20/10/2026: os mesmos oito itens foram reconciliados no manual e nas duas tabelas existentes. Data com mensagem junto ao campo; inventário dos parâmetros efectivos (zero regras fiscais QA); controlos matemáticos independentes; aviso de recálculo; quatro relatórios reais do exportador com 6/6/6/5 páginas; consulta fiscal com erro/nova tentativa e traduções comuns verificados. O formulário personalizado já não exige contexto fiscal que não envia ao cálculo. Restam continuidade autenticada entre dois dossiers/nova sessão e histórico, mudança de parâmetros, controlos delimitados de cash-flow/plano, impressão nativa Edge/comparação pela interface e mensagens dinâmicas/falhas dirigidas de gravação/exportação. Estimativa restante **6–10 h**, distinta das 18–30 h iniciais. Sem main, servidor remoto, importação ou activação fiscal. Exemplos PDF são renderizações do DOCX; não certificam impressão do Edge. Ver o saldo detalhado AUD-SIM-INT01–08 no mesmo manual.
|
||||
|
||||
Continuação delimitada: dois dossiers e nova entrada conferidos no navegador; histórico agora visível no percurso de pequeno negócio, hashes preservados; Abrir cálculo encaminha para a etapa financeira; repetição de gravação após 503 corrigida e conferida; controlos independentes de tesouraria/plano passaram. CSV e Word descarregados pela interface coincidem nos valores comuns e apresentam a receita completa do crédito. Seis páginas do DOCX conferidas; PDF nativo ainda aguarda gravação pelo utilizador. QA tem zero regras com visibilidade completa, mas existem três originais fiscais versionados e análises/referências reutilizáveis; não se concluiu ausência na homologação sem autenticação SSH. Versões sintéticas testadas apenas em memória, sem cadastro/activação. Encontrada e corrigida perda dos pressupostos da tesouraria: snapshot no JSON existente, recuperação por dossier e relatório, sem migration; testes HTTP/frontend passaram, falta conferência visual deste novo delta. Saldo **2–4 h** após acessos/ficheiro, detalhado no mesmo manual; integração do motor fiscal permanece separada e não foi implementada. Sem main ou intervenção remota.
|
||||
|
||||
|
||||
## 29/10/2026 — ACT-20261029-01, inventário antes da verificação do incremento
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
### 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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
### 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
|
||||
|
||||
## 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
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -236,6 +236,7 @@
|
||||
}
|
||||
@media (min-width: 1280px) {
|
||||
.tempo-header-inner {
|
||||
grid-template-rows: minmax(71px, auto);
|
||||
grid-template-columns: auto minmax(0, 1fr) auto auto auto;
|
||||
column-gap: 0.25rem;
|
||||
padding-inline: 1.25rem;
|
||||
@@ -256,6 +257,7 @@
|
||||
}
|
||||
.tempo-primary-navigation > ul {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { profileLinks } from '@/components/profile-navigation';
|
||||
import {PortalSidebarNavigation} from '@/components/portal-sidebar-navigation';
|
||||
import type { ProfileAccess } from '@/types/profile-access';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { LayoutGrid } from 'lucide-react';
|
||||
import { portalNavigation } from '@/lib/portal-navigation';
|
||||
import { portalNavigation,canShowLegacyManagement } from '@/lib/portal-navigation';
|
||||
import AppLogo from '@/components/app-logo';
|
||||
import { NavMain } from '@/components/nav-main';
|
||||
import { NavUser } from '@/components/nav-user';
|
||||
import {
|
||||
Sidebar,
|
||||
@@ -20,6 +18,7 @@ import type { Auth } from '@/types';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
export function AppSidebar() {
|
||||
const currentPage=usePage();
|
||||
const {
|
||||
auth,
|
||||
existingBusinessEnabled,
|
||||
@@ -27,7 +26,9 @@ export function AppSidebar() {
|
||||
aiEnabled,
|
||||
opportunityManagement,
|
||||
contentManagementHref,
|
||||
contentManagementAccess,
|
||||
profileAccess,
|
||||
scopedAdministration,
|
||||
} = usePage<{
|
||||
auth: Auth;
|
||||
existingBusinessEnabled?: boolean;
|
||||
@@ -36,45 +37,26 @@ export function AppSidebar() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
contentManagementHref?: string | null;
|
||||
scopedAdministration?: {label:string;href:string}[];
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
}>().props;
|
||||
const groups = portalNavigation({
|
||||
authenticated: !!auth.user,
|
||||
manager: auth.canManagePortal,
|
||||
manager: canShowLegacyManagement(auth),
|
||||
businesses: existingBusinessEnabled,
|
||||
education: educationEnabled,
|
||||
ai: aiEnabled,
|
||||
opportunityManagement,
|
||||
profileAccess,
|
||||
contentManagementHref,
|
||||
contentManagementAccess,
|
||||
scopedAdministration,
|
||||
legacyContent: currentPage.props.legacyContentEnabled as boolean|undefined,
|
||||
procurement: currentPage.props.procurementEnabled as boolean|undefined,
|
||||
businessReviewUrl: currentPage.props.businessReviewUrl as string|null|undefined,
|
||||
});
|
||||
const items = groups.map((group) => ({
|
||||
title: group.label,
|
||||
href: group.children?.find((item) => item.href)?.href ?? '/',
|
||||
icon: LayoutGrid,
|
||||
}));
|
||||
if (contentManagementHref) {
|
||||
items.unshift({ title: 'Gestão de conteúdos e oportunidades', href: contentManagementHref, icon: LayoutGrid });
|
||||
}
|
||||
if (auth.canManagePortal && opportunityManagement) {
|
||||
items.push({
|
||||
title: opportunityManagement.manage.label,
|
||||
href: opportunityManagement.manage.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
if (opportunityManagement.installed) {
|
||||
items.push({
|
||||
title: opportunityManagement.create.label,
|
||||
href: opportunityManagement.create.href,
|
||||
icon: LayoutGrid,
|
||||
});
|
||||
}
|
||||
}
|
||||
items.push(
|
||||
...profileLinks(profileAccess).map((link) => ({
|
||||
...link,
|
||||
icon: LayoutGrid,
|
||||
})),
|
||||
);
|
||||
return (
|
||||
<Sidebar collapsible="icon" variant="inset">
|
||||
<Sidebar collapsible="offcanvas" variant="inset">
|
||||
<SidebarHeader>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
@@ -88,7 +70,7 @@ export function AppSidebar() {
|
||||
</SidebarHeader>
|
||||
|
||||
<SidebarContent>
|
||||
<NavMain items={items} />
|
||||
<PortalSidebarNavigation groups={groups} url={currentPage.url}/>
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import type { EducationalArticle } from './educational-article-card';
|
||||
|
||||
/** Guides remain available on request; they are not matching investment results. */
|
||||
export default function CatalogueGuideLinks({ articles }: { articles: EducationalArticle[] }) {
|
||||
if (!articles.length) return null;
|
||||
return <details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-medium">Guias do sector — apoio opcional</summary>
|
||||
<ul className="mt-3 space-y-2">
|
||||
{articles.map((article) => <li key={article.href}>
|
||||
<Link className="underline" href={article.href}>Ler guia: {article.title}</Link>
|
||||
</li>)}
|
||||
</ul>
|
||||
</details>;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { forceLabels, forces } from '@/lib/cluster-competitiveness';
|
||||
import type { CompetitivenessDraft } from '@/lib/cluster-competitiveness';
|
||||
|
||||
export type ApprovedCompetitiveness = {
|
||||
draft: CompetitivenessDraft;
|
||||
version: number;
|
||||
at: string;
|
||||
};
|
||||
const pressures = {
|
||||
low: 'Baixa',
|
||||
medium: 'Média',
|
||||
high: 'Alta',
|
||||
'': 'Indeterminada',
|
||||
};
|
||||
|
||||
export default function ClusterCompetitivenessPublic({
|
||||
analysis,
|
||||
}: {
|
||||
analysis: ApprovedCompetitiveness;
|
||||
}) {
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Competitividade aprovada"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Competitividade — cinco forças de Porter
|
||||
</h2>
|
||||
<p>
|
||||
{analysis.draft.sector} · {analysis.draft.region} · Versão
|
||||
aprovada {analysis.version} · {analysis.at}
|
||||
</p>
|
||||
<p>
|
||||
Apreciação qualitativa fundamentada nas fontes e períodos
|
||||
indicados. Não representa garantia de procura ou viabilidade.
|
||||
</p>
|
||||
{forces.map((force) => {
|
||||
const row = analysis.draft.forces[force];
|
||||
return (
|
||||
<details key={force} className="rounded border p-3">
|
||||
<summary>
|
||||
{forceLabels[force]} · Pressão{' '}
|
||||
{pressures[row.pressure]}
|
||||
</summary>
|
||||
<dl className="space-y-2">
|
||||
{(
|
||||
[
|
||||
['evidence', 'Evidências'],
|
||||
['source', 'Fonte e referência'],
|
||||
['period', 'Período'],
|
||||
['rationale', 'Justificação'],
|
||||
['limitations', 'Limitações'],
|
||||
[
|
||||
'opportunity',
|
||||
'Oportunidade e fundamento',
|
||||
],
|
||||
] as const
|
||||
).map(([field, label]) => (
|
||||
<div key={field}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{row[field]}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</details>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -2,5 +2,5 @@ import { Link, usePage } from '@inertiajs/react';
|
||||
|
||||
export default function ContentManagementEntry() {
|
||||
const { contentManagementHref } = usePage<{ contentManagementHref?: string | null }>().props;
|
||||
return contentManagementHref ? <Link className="inline-block rounded-lg border px-4 py-3 font-semibold underline" href={contentManagementHref}>Gestão de conteúdos e oportunidades</Link> : null;
|
||||
return contentManagementHref ? <Link className="inline-block rounded-lg border px-4 py-3 font-semibold underline" href={contentManagementHref}>Área de trabalho</Link> : null;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
export default function InputError({
|
||||
message,
|
||||
className = '',
|
||||
...props
|
||||
}: HTMLAttributes<HTMLParagraphElement> & { message?: string }) {
|
||||
const { t } = useTempoUi();
|
||||
return message ? (
|
||||
<p
|
||||
{...props}
|
||||
className={cn('text-sm text-red-600 dark:text-red-400', className)}
|
||||
>
|
||||
{message}
|
||||
{t(message)}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,54 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
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.
|
||||
export function Trans({ children }: { children: string }) {
|
||||
const { t } = useTempoUi();
|
||||
return <span>{t(children)}</span>;
|
||||
// Only the fixed public institutional texts using this component are sent to Tempo.
|
||||
const cache = new Map<string, string>();
|
||||
const pending = new Map<string, Promise<string>>();
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useEffect, useId, useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
import { replaceTerritoryPath } from '@/lib/territory-path.js';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import TerritorySearchSelect from './territory-search-select';
|
||||
|
||||
export type TerritoryOption = {
|
||||
id: string;
|
||||
@@ -135,37 +136,11 @@ export function ProvinceSelect({
|
||||
total={options.length}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<input
|
||||
className={className}
|
||||
aria-label={`Pesquisar ${label}`}
|
||||
maxLength={100}
|
||||
placeholder="Pesquisar nome ou código"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-label={label}
|
||||
className={className}
|
||||
required={required}
|
||||
value={value}
|
||||
disabled={loading || Boolean(error)}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
{loading ? 'A carregar províncias…' : placeholder}
|
||||
</option>
|
||||
{value && !options.some((option) => option.name === value) && (
|
||||
<option value={value}>
|
||||
{value} (seleção guardada; conferir cadastro)
|
||||
</option>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<option key={option.id} value={option.name}>
|
||||
{option.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<TerritorySearchSelect id={id} label={label} className={className} required={required}
|
||||
placeholder={placeholder === 'Seleccione uma província' ? 'Pesquisar província' : placeholder}
|
||||
search={search} onSearch={setSearch} options={options} loading={loading} error={error}
|
||||
selected={value ? options.find((option) => option.name === value) ?? { id: value, name: value } : undefined}
|
||||
onChange={(option) => onChange(option?.name ?? '')} />
|
||||
{geometryFeedback && <p role="status">{geometryFeedback}</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={
|
||||
@@ -334,65 +309,15 @@ export function TerritoryLevel({
|
||||
<label htmlFor={id} className="font-medium">
|
||||
{labels[index]}
|
||||
</label>
|
||||
<input
|
||||
className={control}
|
||||
aria-label={`Pesquisar ${labels[index]}`}
|
||||
disabled={!enabled}
|
||||
maxLength={100}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={`Pesquisar ${labels[index].toLowerCase()}`}
|
||||
/>
|
||||
<select
|
||||
id={id}
|
||||
aria-invalid={Boolean(fieldError)}
|
||||
aria-describedby={fieldError ? `${id}-error` : undefined}
|
||||
className={control}
|
||||
disabled={!enabled || loading || !!error}
|
||||
value={selected?.id ?? ''}
|
||||
onChange={(e) =>
|
||||
onChange(options.find((o) => o.id === e.target.value))
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{enabled ? 'Seleccione' : 'Seleccione o nível anterior'}
|
||||
</option>
|
||||
{selected && !options.some((o) => o.id === selected.id) && (
|
||||
<option value={selected.id}>
|
||||
{selected.name}
|
||||
{selected.deleted_at
|
||||
? ' (arquivada)'
|
||||
: ' (selecção actual)'}
|
||||
</option>
|
||||
)}
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
{o.source_code ? ` (${o.source_code})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<TerritorySearchSelect id={id} label={labels[index]} className={control}
|
||||
disabled={!enabled} search={search} onSearch={(query) => { setSearch(query); setPage(1); }}
|
||||
options={options} selected={selected} onChange={onChange} loading={loading} error={fieldError || error}>
|
||||
<div className="flex gap-3 p-2 text-sm">
|
||||
{page > 1 && <button type="button" onClick={() => setPage(page - 1)}>Anterior</button>}
|
||||
{more && <button type="button" onClick={() => setPage(page + 1)}>Mais opções</button>}
|
||||
</div>
|
||||
</TerritorySearchSelect>
|
||||
{loading && <p role="status">A carregar…</p>}
|
||||
{fieldError && (
|
||||
<p id={`${id}-error`} role="alert">
|
||||
{fieldError}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-3 text-sm">
|
||||
{page > 1 && (
|
||||
<button type="button" onClick={() => setPage(page - 1)}>
|
||||
Anterior
|
||||
</button>
|
||||
)}
|
||||
{more && (
|
||||
<button type="button" onClick={() => setPage(page + 1)}>
|
||||
Mais opções
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { fiscalPreparationGuide } from '@/lib/fiscal-preparation-guide';
|
||||
|
||||
@@ -8,6 +8,8 @@ export function JourneyDocumentResources({
|
||||
stages?: string[];
|
||||
}) {
|
||||
const [stage, setStage] = useState('');
|
||||
const context=new URL(usePage().url,'https://portal.invalid').searchParams.get('context');
|
||||
const preparationHref=context&&/^[a-f0-9-]{36}$/i.test(context)?`/investimentos/${context}/contexto/editar#preparation-questions`:'/investimentos';
|
||||
function destination(path: string, type?: string) {
|
||||
const query = new URLSearchParams();
|
||||
if (stage) query.set('stage[0]', stage);
|
||||
@@ -20,8 +22,24 @@ export function JourneyDocumentResources({
|
||||
className="space-y-3 rounded-xl border border-emerald-200 bg-emerald-50 p-4"
|
||||
>
|
||||
<h2 className="font-semibold text-emerald-950">
|
||||
Fontes e guias para a jornada
|
||||
Preencher formulários e preparar documentos
|
||||
</h2>
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Pedido de investimento</h3>
|
||||
<p>Preencha a preparação digital no dossier existente, reutilizando os dados já guardados.</p>
|
||||
<Link className="underline" href={preparationHref}>Abrir o formulário no meu dossier</Link>
|
||||
</div>
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Terra e DUAT</h3>
|
||||
<p>Prepare os dados do pedido com os campos do formulário existente.</p>
|
||||
<Link className="underline" href="/terra-duat">Preencher ou continuar pedido de terra</Link>
|
||||
</div>
|
||||
<div className="rounded border bg-white p-3"><h3 className="font-semibold">Pedido de apoio do investidor</h3>
|
||||
<p>Identifique-se e preencha o pedido de apoio. Este formulário não é um pedido de autorização de investimento.</p>
|
||||
<Link className="underline" href="/formularios/investidor">Preencher pedido de apoio</Link>
|
||||
</div>
|
||||
</div>
|
||||
<p>Preparação digital e exemplar oficial são apresentados separadamente. Um guia ou diploma não é um formulário preenchível.</p>
|
||||
<details><summary className="cursor-pointer font-medium">Consultar exemplares, fontes e guias</summary>
|
||||
<p>
|
||||
Prepare as etapas em paralelo. A disponibilidade para consulta,
|
||||
a situação jurídica e a utilização numa regra ou cálculo são
|
||||
@@ -143,6 +161,7 @@ export function JourneyDocumentResources({
|
||||
<Link className="underline" href="/documentos">
|
||||
Explorar todo o acervo autorizado
|
||||
</Link>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import { valueText } from '@/lib/value-text';
|
||||
import OpportunityParcelGeometry from './opportunity-parcel-geometry';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import { control } from '@/pages/management/shared';
|
||||
import OpportunityFillFlow from './opportunity-fill-flow';
|
||||
import { opportunityFillGroups } from '@/lib/opportunity-fill-flow';
|
||||
import { modalityLabels } from './opportunity-search-filters';
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
type Schema = {
|
||||
@@ -241,6 +244,11 @@ const labels: Record<string, string> = {
|
||||
assessment_status: 'Estado da avaliação',
|
||||
environmental_category: 'Categoria ambiental',
|
||||
direct_jobs: 'Empregos diretos',
|
||||
indirect_jobs: 'Empregos indirectos',
|
||||
female_percentage: 'Participação de mulheres (%)',
|
||||
youth_percentage: 'Participação de jovens (%)',
|
||||
social_risks: 'Riscos sociais',
|
||||
mitigation_plan: 'Plano de mitigação',
|
||||
employment_type: 'Tipo de emprego',
|
||||
geometry: 'Geometria da parcela',
|
||||
start_date: 'Data de início',
|
||||
@@ -621,6 +629,8 @@ export default function OpportunityCanonicalFields({
|
||||
sectors,
|
||||
disabled = false,
|
||||
errors = {},
|
||||
onOpenResources,
|
||||
missingPaths,
|
||||
}: {
|
||||
value: Data;
|
||||
onChange: (v: Data) => void;
|
||||
@@ -631,6 +641,8 @@ export default function OpportunityCanonicalFields({
|
||||
sectors: { id: number; name: string }[];
|
||||
disabled?: boolean;
|
||||
errors?: Record<string, string>;
|
||||
onOpenResources?: (group: string) => void;
|
||||
missingPaths?: string[];
|
||||
}) {
|
||||
const initiative = (value.initiative ?? {}) as Data;
|
||||
const isInitiative = category === 'investment_project' && ['program', 'portfolio'].includes(valueText(initiative.kind ?? ''));
|
||||
@@ -815,7 +827,7 @@ export default function OpportunityCanonicalFields({
|
||||
: ['classified_other'];
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-4 rounded border p-4">
|
||||
<legend>Contrato da oportunidade — {category}</legend>
|
||||
<legend>Preparar oportunidade — {modalityLabels[category] ?? 'Modalidade por escolher'}</legend>
|
||||
<p>
|
||||
O rascunho pode ficar incompleto. A submissão verifica os campos
|
||||
aplicáveis e os recursos guardados. Validação interna não
|
||||
@@ -870,7 +882,7 @@ export default function OpportunityCanonicalFields({
|
||||
</>}
|
||||
</section>
|
||||
)}
|
||||
{[...new Set([...common, ...specialized])].map((key) => {
|
||||
<OpportunityFillFlow groups={opportunityFillGroups([...new Set([...common, ...specialized])].filter((key) => !ignoredFields.includes(key)))} errors={errors} missingPaths={missingPaths} onOpenResources={onOpenResources} renderField={(key) => {
|
||||
if (ignoredFields.includes(key)) return null;
|
||||
|
||||
if (key === 'relations' && options.classification) {
|
||||
@@ -1167,7 +1179,7 @@ export default function OpportunityCanonicalFields({
|
||||
onChange={(v) => set(key, v)}
|
||||
/>
|
||||
) : null;
|
||||
})}
|
||||
}} />
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
|
||||
type Item = {id:number;title:string;slug:string;summary:string|null;province:string|null;district:string|null;chains:string[];stages:string[];maturity_label:string|null};
|
||||
type Item = {id:number;title:string;slug:string;summary:string|null;province:string|null;district:string|null;provinces?:string[];territorial_summary?:string;chains:string[];stages:string[];maturity_label:string|null};
|
||||
export type CorridorGroup = {id:string;name:string;count:number;locations:string[];opportunities:Item[]};
|
||||
type Props = {groups:CorridorGroup[];selected:number[];onSelect:(id:number,checked:boolean)=>void;onCompare:(ids:number[])=>void;onClear:()=>void};
|
||||
|
||||
@@ -10,10 +10,11 @@ function Group({group,selected,onSelect}: {group:CorridorGroup} & Pick<Props,'se
|
||||
const [province,setProvince]=useState('');
|
||||
const [district,setDistrict]=useState('');
|
||||
const [chain,setChain]=useState('');
|
||||
const provinces=[...new Set(group.opportunities.map(r=>r.province).filter((s):s is string=>!!s))].sort();
|
||||
const districts=[...new Set(group.opportunities.filter(r=>!province||r.province===province).map(r=>r.district).filter((s):s is string=>!!s))].sort();
|
||||
const provinceNames=(r:Item)=>r.provinces??(r.province?[r.province]:[]);
|
||||
const provinces=[...new Set(group.opportunities.flatMap(provinceNames))].sort();
|
||||
const districts=[...new Set(group.opportunities.filter(r=>!province||provinceNames(r).includes(province)).map(r=>r.district).filter((s):s is string=>!!s))].sort();
|
||||
const chains=[...new Set(group.opportunities.flatMap(r=>r.chains))].sort();
|
||||
const rows=group.opportunities.filter(r=>(!province||r.province===province)&&(!district||r.district===district)&&(!chain||r.chains.includes(chain)));
|
||||
const rows=group.opportunities.filter(r=>(!province||provinceNames(r).includes(province))&&(!district||r.district===district)&&(!chain||r.chains.includes(chain)));
|
||||
return <section className={card+' space-y-4'} aria-label={group.name}>
|
||||
<header><h2 className="text-2xl font-bold">{group.name}</h2><p>{group.count} oportunidades publicadas</p>
|
||||
<p>{group.locations.length ? 'Localizações identificadas: '+group.locations.join(' · ') : 'Abrangência territorial por indicar.'}</p></header>
|
||||
@@ -25,7 +26,7 @@ function Group({group,selected,onSelect}: {group:CorridorGroup} & Pick<Props,'se
|
||||
<p role="status">{rows.length} oportunidades com estes filtros</p>
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{rows.map(r=><article key={r.id} className="space-y-3 rounded-lg border p-4">
|
||||
<h3 className="text-lg font-semibold"><Link href={'/oportunidades/'+r.slug}>{r.title}</Link></h3>
|
||||
<p>{[r.province,r.district].filter(Boolean).join(' / ')||'Localização por escolher'}</p>
|
||||
<p>{r.territorial_summary||[r.province,r.district].filter(Boolean).join(' / ')||'Localização por escolher'}</p>
|
||||
<p>Cadeia de valor: {r.chains.join(' · ')||'Por indicar'}</p>
|
||||
{r.summary && !r.stages.includes(r.summary) && <p>{r.summary}</p>}
|
||||
<p>Etapas e actividades: {r.stages.join(' · ')||'Por indicar'}</p><p>{r.maturity_label}</p>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { opportunityErrorGroup, opportunityMissingGroups, type FillGroup } from '@/lib/opportunity-fill-flow';
|
||||
|
||||
export default function OpportunityFillFlow({groups,errors,renderField,onOpenResources,missingPaths=[]}:{
|
||||
groups:FillGroup[];errors:Record<string,string>;renderField:(field:string)=>ReactNode;onOpenResources?:(group:string)=>void;
|
||||
missingPaths?:string[];
|
||||
}) {
|
||||
const [active,setActive]=useState(groups[0]?.id??'');
|
||||
const groupIds=groups.map(group=>group.id).join(',');
|
||||
useEffect(()=>{
|
||||
const saved=window.location.hash.replace('#fill-','');
|
||||
if(groupIds.split(',').includes(saved))setActive(saved);
|
||||
},[groupIds]);
|
||||
const heading=useRef<HTMLHeadingElement|null>(null);
|
||||
const errorGroup=opportunityErrorGroup(groups,errors);
|
||||
const missing=opportunityMissingGroups(groups,missingPaths);
|
||||
const errorKey=JSON.stringify(errors);
|
||||
useEffect(()=>{if(errorGroup)setActive(errorGroup);},[errorGroup,errorKey]);
|
||||
const index=Math.max(0,groups.findIndex(group=>group.id===active));
|
||||
const current=groups[index];
|
||||
if(!current)return null;
|
||||
const go=(id:string)=>{
|
||||
setActive(id);
|
||||
window.history.replaceState(window.history.state,'',`#fill-${id}`);
|
||||
requestAnimationFrame(()=>heading.current?.focus());
|
||||
};
|
||||
return <div className="space-y-4">
|
||||
<p>Pode escolher qualquer grupo, guardar incompleto e retomar. As informações já preenchidas mantêm-se ao avançar e regressar.</p>
|
||||
<nav aria-label="Preencher a oportunidade" className="flex flex-wrap gap-2">
|
||||
{groups.map(group=><a key={group.id} href={`#fill-${group.id}`} aria-current={current.id===group.id?'step':undefined}
|
||||
className={`rounded border px-3 py-2 text-left ${current.id===group.id?'bg-primary text-primary-foreground':'bg-background'}`}
|
||||
onClick={event=>{event.preventDefault();go(group.id);}}>{group.title}{opportunityErrorGroup([group],errors)?' — verificar':missing.some(item=>item.id===group.id)?' — dados em falta':''}</a>)}
|
||||
</nav>
|
||||
{missing.length>0&&<p>Pendências da última gravação: {missing.map(group=>group.title).join(' · ')}. Guarde para actualizar esta indicação.</p>}
|
||||
<h2 ref={heading} tabIndex={-1} className="text-xl font-semibold">{current.title}</h2>
|
||||
<p>{current.hint}</p>
|
||||
{groups.map(group=><section key={group.id} id={`fill-${group.id}`} hidden={current.id!==group.id}
|
||||
aria-label={group.title} className="space-y-4">
|
||||
{group.fields.map(field=><div key={field}>{renderField(field)}</div>)}
|
||||
{onOpenResources&&group.fields.some(field=>['locations','documents','images'].includes(field))&&
|
||||
<button type="button" className="rounded border px-4 py-2 font-medium" onClick={()=>onOpenResources(group.id)}>Guardar e abrir documentos, imagens e localizações</button>}
|
||||
</section>)}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-t pt-3">
|
||||
<span className="text-sm">Grupo {index+1} de {groups.length} · navegação livre</span>
|
||||
<div className="flex gap-3">
|
||||
{index>0&&<a href={`#fill-${groups[index-1].id}`} className="rounded border px-4 py-2" onClick={event=>{event.preventDefault();go(groups[index-1].id);}}>Anterior</a>}
|
||||
{index<groups.length-1&&<a href={`#fill-${groups[index+1].id}`} className="rounded border px-4 py-2" onClick={event=>{event.preventDefault();go(groups[index+1].id);}}>Continuar: {groups[index+1].title}</a>}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Field, input, button, groupLabels } from '@/pages/investment/shared';
|
||||
import type { References } from '@/pages/investment/shared';
|
||||
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> = {
|
||||
investment_project: 'Projecto de investimento',
|
||||
@@ -50,14 +53,19 @@ const labels: Record<string, string> = {
|
||||
publication_state: 'Critério herdado',
|
||||
};
|
||||
const specialisedEmpty: Record<string, string> = {
|
||||
corridor_id: 'Não existem corredores públicos cadastrados para esta localização.',
|
||||
cluster_id: 'Não existem clusters públicos cadastrados para esta localização.',
|
||||
corridor_id:
|
||||
'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.',
|
||||
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.',
|
||||
project_id: 'Não existem projectos âncora públicos cadastrados para esta localização.',
|
||||
park_id:
|
||||
'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.',
|
||||
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({
|
||||
data,
|
||||
@@ -78,6 +86,10 @@ export default function OpportunitySearchFilters({
|
||||
clear: () => void;
|
||||
errors: Record<string, string>;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Object.keys(errors).length) setExpanded(true);
|
||||
}, [errors]);
|
||||
const select = (
|
||||
key: string,
|
||||
choices: { value: string; label: string }[],
|
||||
@@ -87,8 +99,14 @@ export default function OpportunitySearchFilters({
|
||||
<select
|
||||
className={input}
|
||||
aria-label={labels[key]}
|
||||
aria-describedby={specialisedEmpty[key] ? `filter-help-${key}` : undefined}
|
||||
disabled={Boolean(specialisedEmpty[key]) && choices.length === 0 && !data[key]}
|
||||
aria-describedby={
|
||||
specialisedEmpty[key] ? `filter-help-${key}` : undefined
|
||||
}
|
||||
disabled={
|
||||
Boolean(specialisedEmpty[key]) &&
|
||||
choices.length === 0 &&
|
||||
!data[key]
|
||||
}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
change({
|
||||
@@ -100,9 +118,13 @@ export default function OpportunitySearchFilters({
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{data[key] && !choices.some((o) => o.value === String(data[key])) && (
|
||||
<option value={String(data[key])}>Selecção indisponível neste contexto — remova o filtro</option>
|
||||
)}
|
||||
{data[key] &&
|
||||
!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) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
@@ -114,7 +136,9 @@ export default function OpportunitySearchFilters({
|
||||
{choices.length === 0
|
||||
? specialisedEmpty[key]
|
||||
: `${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>
|
||||
)}
|
||||
{hint && <p className="text-sm text-slate-600">{hint}</p>}
|
||||
@@ -200,306 +224,399 @@ export default function OpportunitySearchFilters({
|
||||
);
|
||||
return (
|
||||
<form
|
||||
className="space-y-5 rounded-xl border bg-white p-4 sm:p-6"
|
||||
className="catalogue-filters"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
aria-label="Pesquisar oportunidades"
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
<Field label="O que procura">
|
||||
<input
|
||||
className={input}
|
||||
value={String(data.q)}
|
||||
placeholder="Palavras do título ou da descrição"
|
||||
onChange={(e) => change({ q: e.target.value })}
|
||||
/>
|
||||
</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>
|
||||
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<legend className="mb-2 font-semibold">Localização</legend>
|
||||
{(
|
||||
[
|
||||
'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.',
|
||||
<button
|
||||
type="button"
|
||||
className="catalogue-filters-toggle"
|
||||
aria-expanded={expanded}
|
||||
aria-controls="catalogue-filter-fields"
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
<SlidersHorizontal size={18} aria-hidden="true" />
|
||||
<span>Filtros</span>
|
||||
{active.length + path.length > 0 && (
|
||||
<span className="catalogue-count">
|
||||
{active.length + path.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<details>
|
||||
<summary className="cursor-pointer rounded border p-3 font-semibold focus-visible:outline-2">
|
||||
Mais filtros
|
||||
</summary>
|
||||
<div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{[
|
||||
'corridor_id',
|
||||
'cluster_id',
|
||||
'zee_id',
|
||||
'zfi_id',
|
||||
'park_id',
|
||||
'project_id',
|
||||
'subsector_id',
|
||||
'chain_id',
|
||||
].map((key) => select(key, choicesFor(key)))}
|
||||
<Field label="Data-alvo até">
|
||||
<ChevronDown size={18} aria-hidden="true" />
|
||||
</button>
|
||||
<h2 className="catalogue-filters-heading">
|
||||
<SlidersHorizontal size={17} aria-hidden="true" />
|
||||
Filtros
|
||||
</h2>
|
||||
<div
|
||||
id="catalogue-filter-fields"
|
||||
className={`${expanded ? 'block' : 'hidden'} space-y-5 lg:block`}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-1">
|
||||
<Field label="O que procura">
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
value={String(data.before)}
|
||||
onChange={(e) => change({ before: e.target.value })}
|
||||
value={String(data.q)}
|
||||
placeholder="Palavras do título ou da descrição"
|
||||
onChange={(e) => change({ q: e.target.value })}
|
||||
/>
|
||||
</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>
|
||||
<p className="my-3 text-sm">
|
||||
Estes filtros procuram associações documentadas. Estar perto
|
||||
de um parque ou no mesmo distrito não constitui associação,
|
||||
nem confirma incentivos ou disponibilidade.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(data.include_national)}
|
||||
onChange={(e) =>
|
||||
change({ include_national: e.target.checked })
|
||||
}
|
||||
/>
|
||||
Incluir oportunidades de âmbito nacional
|
||||
</label>
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Outras características
|
||||
</summary>
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<CatalogueFilterGroup title="Localização" count={path.length}>
|
||||
<p className="text-sm leading-relaxed text-slate-600">
|
||||
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>
|
||||
<fieldset className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
|
||||
<legend className="sr-only">Localização</legend>
|
||||
{(
|
||||
[
|
||||
'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>
|
||||
</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',
|
||||
'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(
|
||||
data.facets,
|
||||
) &&
|
||||
data.facets.includes(
|
||||
option.id,
|
||||
)
|
||||
}
|
||||
onChange={(e) => {
|
||||
const selected =
|
||||
'corridor_id',
|
||||
'cluster_id',
|
||||
'zee_id',
|
||||
'zfi_id',
|
||||
'park_id',
|
||||
'project_id',
|
||||
'subsector_id',
|
||||
'chain_id',
|
||||
].map((key) => select(key, choicesFor(key)))}
|
||||
<Field label="Data-alvo até">
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
value={String(data.before)}
|
||||
onChange={(e) =>
|
||||
change({ before: e.target.value })
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<p className="my-3 text-sm">
|
||||
Estes filtros procuram associações documentadas. Estar
|
||||
perto de um parque ou no mesmo distrito não constitui
|
||||
associação, nem confirma incentivos ou disponibilidade.
|
||||
</p>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(data.include_national)}
|
||||
onChange={(e) =>
|
||||
change({ include_national: e.target.checked })
|
||||
}
|
||||
/>
|
||||
Incluir oportunidades de âmbito nacional
|
||||
</label>
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
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(
|
||||
data.facets,
|
||||
) &&
|
||||
data.facets.includes(
|
||||
option.id,
|
||||
)
|
||||
? data.facets
|
||||
: [];
|
||||
change({
|
||||
facets: e.target
|
||||
.checked
|
||||
? [
|
||||
...selected,
|
||||
option.id,
|
||||
]
|
||||
: selected.filter(
|
||||
(id) =>
|
||||
id !==
|
||||
}
|
||||
onChange={(e) => {
|
||||
const selected =
|
||||
Array.isArray(
|
||||
data.facets,
|
||||
)
|
||||
? data.facets
|
||||
: [];
|
||||
change({
|
||||
facets: e.target
|
||||
.checked
|
||||
? [
|
||||
...selected,
|
||||
option.id,
|
||||
),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
</details>
|
||||
<section
|
||||
aria-label="Filtros activos"
|
||||
className="flex flex-wrap gap-2"
|
||||
>
|
||||
{path.map((node, index) => (
|
||||
<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="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}
|
||||
]
|
||||
: selected.filter(
|
||||
(
|
||||
id,
|
||||
) =>
|
||||
id !==
|
||||
option.id,
|
||||
),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
</CatalogueFilterGroup>
|
||||
<section
|
||||
aria-label="Filtros activos"
|
||||
className="catalogue-active-filters flex flex-wrap gap-2"
|
||||
>
|
||||
Limpar filtros
|
||||
</button>
|
||||
{path.map((node, index) => (
|
||||
<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>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ComponentProps, Ref } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
export default function PasswordInput({
|
||||
className,
|
||||
@@ -10,6 +11,7 @@ export default function PasswordInput({
|
||||
...props
|
||||
}: Omit<ComponentProps<'input'>, 'type'> & { ref?: Ref<HTMLInputElement> }) {
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const { t } = useTempoUi();
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
@@ -23,7 +25,7 @@ export default function PasswordInput({
|
||||
type="button"
|
||||
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"
|
||||
aria-label={showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe'}
|
||||
aria-label={t(showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe')}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPassword ? (
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
portalNavigation,
|
||||
canShowLegacyManagement,
|
||||
currentNavigationGroup,
|
||||
currentNavigationItem,
|
||||
} from '@/lib/portal-navigation';
|
||||
@@ -44,6 +45,7 @@ export function PortalGroupedMenu() {
|
||||
auth: {
|
||||
user: { name?: string; email?: string } | null;
|
||||
canManagePortal: boolean;
|
||||
legacyManagementAccess?:boolean;
|
||||
};
|
||||
existingBusinessEnabled?: boolean;
|
||||
businessReviewUrl?: string | null;
|
||||
@@ -54,6 +56,8 @@ export function PortalGroupedMenu() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
scopedAdministration?: { label: string; href: string }[];
|
||||
contentManagementHref?: string | null;
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
}>();
|
||||
const { t, language, requestCount } = useTempoUi();
|
||||
const mobile = useIsMobile();
|
||||
@@ -63,7 +67,7 @@ export function PortalGroupedMenu() {
|
||||
? { id: navigation.active, ...navigation.view.tools }
|
||||
: undefined,
|
||||
authenticated: !!props.auth?.user,
|
||||
manager: !!props.auth?.canManagePortal,
|
||||
manager: canShowLegacyManagement(props.auth),
|
||||
businesses: props.existingBusinessEnabled,
|
||||
businessReviewUrl: props.businessReviewUrl,
|
||||
education: props.educationEnabled,
|
||||
@@ -72,17 +76,10 @@ export function PortalGroupedMenu() {
|
||||
legacyContent: props.legacyContentEnabled,
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
profileAccess: props.profileAccess,
|
||||
contentManagementHref: props.contentManagementHref,
|
||||
contentManagementAccess: props.contentManagementAccess,
|
||||
scopedAdministration: props.scopedAdministration,
|
||||
});
|
||||
if (props.scopedAdministration?.length)
|
||||
groups.push({
|
||||
id: 'scoped-administration',
|
||||
label: 'Administração',
|
||||
children: props.scopedAdministration.map((item, index) => ({
|
||||
id: `scoped-${index}`,
|
||||
label: item.label,
|
||||
href: item.href,
|
||||
})),
|
||||
});
|
||||
const current = currentNavigationGroup(groups, url);
|
||||
const currentItem = currentNavigationItem(groups, url);
|
||||
const [loggingOut, setLoggingOut] = useState(false);
|
||||
@@ -134,7 +131,7 @@ export function PortalGroupedMenu() {
|
||||
);
|
||||
const accountGroups = groups.filter(
|
||||
(group) =>
|
||||
!['home', 'discovery', 'realization', 'support'].includes(group.id),
|
||||
!['home', 'discovery', 'realization', 'support','work'].includes(group.id),
|
||||
);
|
||||
const panelLabel = `${t('O meu painel')} — ${requestCount} ${t(requestCount === 1 ? 'pedido recebido' : 'pedidos recebidos')}`;
|
||||
const institutionalCurrent = url.split('?')[0] === '/contacto';
|
||||
@@ -200,6 +197,7 @@ export function PortalGroupedMenu() {
|
||||
'discovery',
|
||||
'realization',
|
||||
'support',
|
||||
'work',
|
||||
].includes(group.id),
|
||||
)
|
||||
.map((group) => (
|
||||
|
||||
@@ -231,14 +231,14 @@ export default function PortalHero({
|
||||
<form
|
||||
onSubmit={onSearch}
|
||||
role="search"
|
||||
aria-label="Pesquisar oportunidades"
|
||||
aria-label="Pesquisar no InvesteMoz"
|
||||
className="mt-7 w-full max-w-4xl"
|
||||
>
|
||||
<label
|
||||
htmlFor="portal-opportunity-search"
|
||||
className="mb-2 block text-left text-sm font-medium text-white/90"
|
||||
>
|
||||
Pesquisa rápida de oportunidades
|
||||
Pesquisa rápida no InvesteMoz
|
||||
</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">
|
||||
<input
|
||||
@@ -247,7 +247,7 @@ export default function PortalHero({
|
||||
name="q"
|
||||
value={query}
|
||||
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"
|
||||
/>
|
||||
<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 />;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {Link} from '@inertiajs/react';
|
||||
import {LayoutGrid} from 'lucide-react';
|
||||
import type {ReactNode} from 'react';
|
||||
import type {PortalNavItem} from '@/lib/portal-navigation';
|
||||
import {currentNavigationItem} from '@/lib/portal-navigation';
|
||||
import {searchTerritoryHref} from '@/lib/search-territory';
|
||||
import {SidebarGroup,SidebarGroupLabel,SidebarMenu,SidebarMenuButton,SidebarMenuItem} from '@/components/ui/sidebar';
|
||||
|
||||
/** Render every authorised destination; a group is never reduced to its first link. */
|
||||
export function PortalSidebarNavigation({groups,url}:{groups:PortalNavItem[];url:string}){
|
||||
const active=currentNavigationItem(groups,url);
|
||||
const ordered=[...groups.filter(group=>group.id==='work'),...groups.filter(group=>group.id!=='work')];
|
||||
const links=(items:PortalNavItem[],depth=0):ReactNode=>items.map(item=>item.children?
|
||||
<li key={item.id} className="list-none"><p className="px-2 pt-3 pb-1 text-xs font-medium text-muted-foreground">{item.label}</p><ul className="ml-2 border-l pl-2">{links(item.children,depth+1)}</ul></li>:
|
||||
item.href?<SidebarMenuItem key={item.id}><SidebarMenuButton asChild isActive={item.id===active} className="h-auto min-h-8 whitespace-normal py-2"><Link href={searchTerritoryHref(item.href,url)} aria-current={item.id===active?'page':undefined}>{depth===0&&<LayoutGrid aria-hidden="true"/>}<span className="min-w-0 flex-1" style={{whiteSpace:'normal',overflow:'visible',textOverflow:'clip',overflowWrap:'anywhere'}}>{item.label}</span></Link></SidebarMenuButton></SidebarMenuItem>:null);
|
||||
return <nav aria-label="Navegação completa do portal">{ordered.map(group=><SidebarGroup key={group.id}><SidebarGroupLabel>{group.label}</SidebarGroupLabel><SidebarMenu>{links(group.children??[])}</SidebarMenu></SidebarGroup>)}</nav>;
|
||||
}
|
||||
@@ -73,6 +73,8 @@ export function PreparationSummary({
|
||||
<h2 className="text-xl font-bold">
|
||||
Preparar o pedido de investimento privado
|
||||
</h2>
|
||||
{caseId&&<p><Link className="inline-block rounded border px-4 py-2 font-semibold" href={`/investimentos/${caseId}/contexto/editar#preparation-questions`}>Preencher ou continuar o formulário</Link></p>}
|
||||
<details><summary className="cursor-pointer font-medium">Consultar situação, documentos e fundamentos</summary>
|
||||
{!data.enabled ? (
|
||||
<p>
|
||||
Use os dados deste dossier para identificar o pedido e os
|
||||
@@ -219,10 +221,11 @@ export function PreparationSummary({
|
||||
className="underline"
|
||||
href={`/investimentos/${caseId}/contexto/editar#preparation-questions`}
|
||||
>
|
||||
Completar apenas os dados em falta ou editar declarações
|
||||
Editar os dados do formulário
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export function profileLinks(access: ProfileAccess | null | undefined) {
|
||||
...(access.administration
|
||||
? [
|
||||
{
|
||||
title: 'Instalação dos perfis 040000',
|
||||
title: 'Configuração dos perfis',
|
||||
href: '/management/profile-install',
|
||||
},
|
||||
]
|
||||
@@ -41,16 +41,26 @@ export default function ProfileNavigation() {
|
||||
profileAccess?: ProfileAccess | null;
|
||||
}>().props;
|
||||
if (!profileAccess) return null;
|
||||
const links = profileLinks(profileAccess);
|
||||
const workHrefs = [profileAccess.mine, profileAccess.create, profileAccess.review].filter(Boolean);
|
||||
const work = links.filter((link) => workHrefs.includes(link.href));
|
||||
const access = links.filter((link) => !workHrefs.includes(link.href));
|
||||
return (
|
||||
<nav
|
||||
aria-label="Perfil e oportunidades"
|
||||
className="flex flex-wrap gap-4 rounded border p-4"
|
||||
>
|
||||
{profileLinks(profileAccess).map((link) => (
|
||||
{work.map((link) => (
|
||||
<Link key={link.href} href={link.href} className="underline">
|
||||
{link.title}
|
||||
</Link>
|
||||
))}
|
||||
{access.length > 0 && <details className="basis-full">
|
||||
<summary className="cursor-pointer font-medium">O meu acesso e administração</summary>
|
||||
<div className="mt-3 flex flex-wrap gap-4">{access.map((link) =>
|
||||
<Link key={link.href} href={link.href} className="underline">{link.title}</Link>
|
||||
)}</div>
|
||||
</details>}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function ProfileProofPicker({documents,value,onChange,disabled=false}:{
|
||||
documents:{id:string;file_name:string}[];value:string[];onChange:(ids:string[])=>void;disabled?:boolean;
|
||||
}) {
|
||||
const [query,setQuery]=useState('');
|
||||
const [showAll,setShowAll]=useState(false);
|
||||
const [limit,setLimit]=useState(10);
|
||||
const normalize=(text:string)=>text.normalize('NFD').replace(/\p{Diacritic}/gu,'').toLocaleLowerCase();
|
||||
const matches=documents.filter(document=>normalize(document.file_name).includes(normalize(query)));
|
||||
const toggle=(id:string)=>onChange(value.includes(id)?value.filter(item=>item!==id):[...value,id]);
|
||||
return <fieldset disabled={disabled} className="space-y-3 rounded border p-4">
|
||||
<legend>Escolher comprovativos</legend>
|
||||
<p className="text-sm">Escolha os seus documentos que sustentam este pedido. A lista contém ficheiros próprios com análise antimalware concluída; não confirma a sua adequação como comprovativo.</p>
|
||||
<p role="status">{value.length} comprovativos escolhidos</p>
|
||||
{value.map(id=><div key={id} className="flex items-start justify-between gap-3 rounded border p-2">
|
||||
<span className="min-w-0 break-words">{documents.find(document=>document.id===id)?.file_name??'Ficheiro seleccionado indisponível nesta consulta'}</span>
|
||||
<button type="button" className="underline" onClick={()=>toggle(id)}>Retirar</button>
|
||||
</div>)}
|
||||
<label className="block">Pesquisar nos meus ficheiros
|
||||
<input type="search" className="mt-1 w-full rounded border p-2" value={query} onChange={event=>{setQuery(event.target.value);setLimit(10);}} />
|
||||
</label>
|
||||
<button type="button" className="underline" onClick={()=>setShowAll(!showAll)}>{showAll?'Fechar lista':'Ver ficheiros disponíveis'}</button>
|
||||
{(query||showAll)&&<div className="space-y-2">
|
||||
<p role="status">{matches.length} ficheiros encontrados · a mostrar até {Math.min(limit,matches.length)}</p>
|
||||
{matches.slice(0,limit).map(document=><label key={document.id} className="flex gap-2 rounded border p-2">
|
||||
<input type="checkbox" checked={value.includes(document.id)} onChange={()=>toggle(document.id)} />
|
||||
<span className="min-w-0 break-words">{document.file_name}</span>
|
||||
</label>)}
|
||||
{matches.length>limit&&<button type="button" className="underline" onClick={()=>setLimit(limit+10)}>Mostrar mais ficheiros</button>}
|
||||
</div>}
|
||||
</fieldset>;
|
||||
}
|
||||
@@ -50,7 +50,7 @@ function count(props: Record<string, unknown>): number | null {
|
||||
}
|
||||
export default function SearchFeedback() {
|
||||
const page = usePage();
|
||||
const handledLocally = page.component === 'investment/catalogue';
|
||||
const handledLocally = ['investment/catalogue', 'investment/zones'].includes(page.component);
|
||||
const [state, setState] = useState<'idle' | 'loading' | 'error'>('idle');
|
||||
const latest = useRef<{
|
||||
url: string;
|
||||
|
||||
@@ -19,6 +19,7 @@ export type SectorEntryData = {
|
||||
}[];
|
||||
start_href: string | null;
|
||||
register_href: string | null;
|
||||
register_label?: string;
|
||||
start_notice: string | null;
|
||||
register_notice: string | null;
|
||||
specialization_href: string | null;
|
||||
@@ -58,7 +59,7 @@ export default function SectorEntry({
|
||||
className="rounded border px-4 py-3"
|
||||
href={data.register_href}
|
||||
>
|
||||
Cadastrar oportunidade — escolher modalidade
|
||||
{data.register_label ?? 'Cadastrar oportunidade — escolher modalidade'}
|
||||
</Link>
|
||||
) : (
|
||||
<p role="status">{data.register_notice}</p>
|
||||
|
||||
@@ -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({
|
||||
language: 'pt',
|
||||
setLanguage: (_language: string) => {},
|
||||
@@ -255,13 +297,17 @@ export function TempoUiProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
try {
|
||||
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);
|
||||
} catch {
|
||||
/* Navigation remains usable without browser storage. */
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = language;
|
||||
}, [language]);
|
||||
const setLanguage = (next: string) => {
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9-]{0,19}$/.test(next)) return;
|
||||
setCurrentLanguage(next);
|
||||
try {
|
||||
localStorage.setItem('tempo-navigation-language', next);
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
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 };
|
||||
|
||||
@@ -97,12 +100,28 @@ export function TempoWeather() {
|
||||
}
|
||||
|
||||
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 (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger
|
||||
className="tempo-utility-button"
|
||||
aria-label="Idioma da navegação"
|
||||
aria-label={t('Idioma da navegação')}
|
||||
>
|
||||
<Globe size={16} aria-hidden="true" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
@@ -116,14 +135,10 @@ export function TempoLanguageSelector() {
|
||||
className="tempo-dropdown min-w-44"
|
||||
>
|
||||
<DropdownMenuLabel className="text-xs text-slate-500">
|
||||
Navegação institucional
|
||||
{t('Navegação institucional')}
|
||||
</DropdownMenuLabel>
|
||||
{[
|
||||
['pt', 'Português'],
|
||||
['en', 'English'],
|
||||
['fr', 'Français'],
|
||||
['es', 'Español'],
|
||||
].map(([code, name]) => (
|
||||
{!available && <DropdownMenuLabel className="text-xs text-slate-500">Tradução temporariamente indisponível</DropdownMenuLabel>}
|
||||
{languages.map(({ code, name }) => (
|
||||
<DropdownMenuItem
|
||||
key={code}
|
||||
onSelect={() => setLanguage(code)}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
type Choice = { id: string; name: string; source_code?: string | null };
|
||||
|
||||
/** One search field owns the list and commits only an explicitly chosen option. */
|
||||
export default function TerritorySearchSelect<T extends Choice>({
|
||||
id, label, search, onSearch, options, selected, onChange, disabled = false,
|
||||
loading = false, error, required = false, className, placeholder, children,
|
||||
}: {
|
||||
id: string; label: string; search: string; onSearch: (query: string) => void;
|
||||
options: T[]; selected?: T; onChange: (option?: T) => void;
|
||||
disabled?: boolean; loading?: boolean; error?: string; required?: boolean;
|
||||
className?: string; placeholder?: string; children?: ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(-1);
|
||||
const activeRef = useRef<HTMLButtonElement | null>(null);
|
||||
const expanded = open && !disabled;
|
||||
const listId = `${id}-options`;
|
||||
useEffect(() => { if (expanded) activeRef.current?.scrollIntoView({ block: 'nearest' }); }, [active, expanded]);
|
||||
const close = () => { setOpen(false); setActive(-1); onSearch(''); };
|
||||
const choose = (option?: T) => { onChange(option); close(); };
|
||||
return <div className="relative" onBlur={(event) => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) close();
|
||||
}}>
|
||||
<input id={id} className={className} role="combobox" aria-label={`Pesquisar ${label}`}
|
||||
aria-autocomplete="list" aria-expanded={expanded} aria-controls={expanded ? listId : undefined}
|
||||
aria-activedescendant={expanded && !loading && options[active] ? `${listId}-${active}` : undefined}
|
||||
aria-invalid={Boolean(error)} aria-describedby={error ? `${id}-error` : undefined}
|
||||
aria-required={required || undefined} required={required} autoComplete="off" maxLength={100}
|
||||
disabled={disabled} value={expanded ? search : selected?.name ?? ''}
|
||||
placeholder={disabled ? 'Seleccione o nível anterior' : placeholder ?? `Pesquisar ${label.toLowerCase()}`}
|
||||
onFocus={() => { setOpen(true); setActive(-1); onSearch(''); }}
|
||||
onClick={() => setOpen(true)}
|
||||
onChange={(event) => { setOpen(true); setActive(-1); onSearch(event.target.value); }}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
||||
event.preventDefault(); setOpen(true);
|
||||
setActive((current) => !options.length ? -1 : event.key === 'ArrowDown'
|
||||
? Math.min(current + 1, options.length - 1) : current < 0 ? options.length - 1 : Math.max(0, current - 1));
|
||||
}
|
||||
if (event.key === 'Enter' && expanded) {
|
||||
event.preventDefault();
|
||||
if (!loading && options[active < 0 ? 0 : active]) choose(options[active < 0 ? 0 : active]);
|
||||
}
|
||||
}} />
|
||||
{selected && !disabled && <button type="button" className="mt-1 text-sm underline"
|
||||
aria-label={`Limpar ${label}`} onClick={() => choose()}>Limpar</button>}
|
||||
{error && <p id={`${id}-error`} role="alert">{error}</p>}
|
||||
{expanded && <div className="absolute z-50 mt-1 max-h-72 w-full overflow-y-auto rounded border bg-background p-1 text-foreground shadow-lg">
|
||||
<div id={listId} role="listbox" aria-label={label} aria-busy={loading}>
|
||||
{loading && <p role="status" className="p-2">A carregar…</p>}
|
||||
{!loading && options.length === 0 && <p className="p-2">{error ? 'Não foi possível carregar as opções.' : 'Sem resultados para esta pesquisa.'}</p>}
|
||||
{options.map((option, index) => <button key={option.id} id={`${listId}-${index}`} type="button"
|
||||
ref={index === active ? activeRef : undefined} role="option" tabIndex={-1}
|
||||
aria-selected={option.id === selected?.id} disabled={loading}
|
||||
className={`block w-full rounded p-2 text-left hover:bg-accent ${index === active ? 'bg-accent' : ''}`}
|
||||
onMouseDown={(event) => event.preventDefault()} onClick={() => choose(option)}>
|
||||
{option.name}{option.source_code ? ` (${option.source_code})` : ''}
|
||||
</button>)}
|
||||
</div>
|
||||
{children}
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { AppShell } from '@/components/app-shell';
|
||||
import { AppSidebar } from '@/components/app-sidebar';
|
||||
import { AppSidebarHeader } from '@/components/app-sidebar-header';
|
||||
import { NavigationContextSummary } from '@/components/navigation-context';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
import type { AppLayoutProps } from '@/types';
|
||||
|
||||
export default function AppSidebarLayout({
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
export default function AuthLayout({
|
||||
title = '',
|
||||
@@ -9,8 +10,9 @@ export default function AuthLayout({
|
||||
description?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { t } = useTempoUi();
|
||||
return (
|
||||
<AuthLayoutTemplate title={title} description={description}>
|
||||
<AuthLayoutTemplate title={t(title)} description={t(description)}>
|
||||
{children}
|
||||
</AuthLayoutTemplate>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import SearchFeedback from '@/components/search-feedback';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { createContext, useContext } from 'react';
|
||||
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
||||
import { TempoUiProvider } from '@/components/tempo-brand';
|
||||
import { MenuPlacement, PortalMenu } from '@/components/portal-menu';
|
||||
import { TempoUiProvider, useTempoUi } from '@/components/tempo-brand';
|
||||
import { PageTranslator } from '@/translation/page-translator';
|
||||
import { TempoFooter } from '@/components/tempo-footer';
|
||||
import type { ReactNode } from 'react';
|
||||
import {
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
NavigationContextSummary,
|
||||
} from '@/components/navigation-context';
|
||||
|
||||
const MenuPlacement = createContext(false);
|
||||
|
||||
export const portalLinks = [
|
||||
['/', 'Início'],
|
||||
['/oportunidades', 'Oportunidades de Investimento'],
|
||||
@@ -67,6 +65,11 @@ export default function PortalNavigation({
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return <TempoUiProvider><PageTranslator /><PortalNavigationContent>{children}</PortalNavigationContent></TempoUiProvider>;
|
||||
}
|
||||
|
||||
function PortalNavigationContent({ children }: { children: ReactNode }) {
|
||||
const { t } = useTempoUi();
|
||||
const { url, props, component } = usePage();
|
||||
const printable = component === 'land-assistance/print';
|
||||
const portalShell =
|
||||
@@ -108,24 +111,23 @@ export default function PortalNavigation({
|
||||
? 'Definições da conta'
|
||||
: 'Detalhes');
|
||||
return (
|
||||
<TempoUiProvider>
|
||||
<NavigationContextProvider>
|
||||
<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">
|
||||
<nav
|
||||
aria-label="Atalho para o conteúdo"
|
||||
aria-label={t('Atalho para o conteúdo')}
|
||||
className={printable ? 'print:hidden' : undefined}
|
||||
>
|
||||
<a
|
||||
href="#portal-content"
|
||||
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>
|
||||
</nav>
|
||||
{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">
|
||||
Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.
|
||||
<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">
|
||||
{t('Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.')}
|
||||
</aside>
|
||||
)}
|
||||
{portalShell && (
|
||||
@@ -139,12 +141,12 @@ export default function PortalNavigation({
|
||||
)}
|
||||
{path !== '/' && (
|
||||
<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' : ''}`}
|
||||
>
|
||||
<>
|
||||
<Link href="/" className="underline">
|
||||
Início
|
||||
{t('Início')}
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
{parent && (
|
||||
@@ -153,12 +155,12 @@ export default function PortalNavigation({
|
||||
href={searchTerritoryHref(parent, url)}
|
||||
className="underline"
|
||||
>
|
||||
{names[parent]}
|
||||
{t(names[parent])}
|
||||
</Link>
|
||||
<span aria-hidden="true">/</span>
|
||||
</>
|
||||
)}
|
||||
<span aria-current="page">{title}</span>
|
||||
<span aria-current="page">{t(title)}</span>
|
||||
</>
|
||||
</nav>
|
||||
)}
|
||||
@@ -176,14 +178,14 @@ export default function PortalNavigation({
|
||||
{children}
|
||||
</div>
|
||||
<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' : ''}`}
|
||||
>
|
||||
<a
|
||||
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]"
|
||||
>
|
||||
Contactar Apoio ao Investidor
|
||||
{t('Contactar Apoio ao Investidor')}
|
||||
</a>
|
||||
</aside>
|
||||
<div className={printable ? 'print:hidden' : undefined}>
|
||||
@@ -192,11 +194,6 @@ export default function PortalNavigation({
|
||||
</div>
|
||||
</MenuPlacement.Provider>
|
||||
</NavigationContextProvider>
|
||||
</TempoUiProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function PortalMenu({ primary = false }: { primary?: boolean }) {
|
||||
const placed = useContext(MenuPlacement);
|
||||
return placed && !primary ? null : <PortalGroupedMenu />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
export const forceLabels = {
|
||||
rivalry: 'Rivalidade entre concorrentes',
|
||||
entrants: 'Ameaça de novos entrantes',
|
||||
substitutes: 'Ameaça de produtos ou serviços substitutos',
|
||||
suppliers: 'Poder negocial dos fornecedores',
|
||||
buyers: 'Poder negocial dos clientes',
|
||||
} as const;
|
||||
|
||||
export type Force = keyof typeof forceLabels;
|
||||
export type Assessment = {
|
||||
pressure: '' | 'low' | 'medium' | 'high';
|
||||
evidence: string;
|
||||
source: string;
|
||||
period: string;
|
||||
rationale: string;
|
||||
limitations: string;
|
||||
opportunity: string;
|
||||
};
|
||||
export type CompetitivenessDraft = {
|
||||
version: 1;
|
||||
clusterId: string;
|
||||
sector: string;
|
||||
region: string;
|
||||
forces: Record<Force, Assessment>;
|
||||
};
|
||||
|
||||
export const forces = Object.keys(forceLabels) as Force[];
|
||||
const fields = [
|
||||
'evidence',
|
||||
'source',
|
||||
'period',
|
||||
'rationale',
|
||||
'limitations',
|
||||
'opportunity',
|
||||
] as const;
|
||||
|
||||
export function newCompetitivenessDraft(
|
||||
clusterId: string,
|
||||
sector: string,
|
||||
): CompetitivenessDraft {
|
||||
return {
|
||||
version: 1,
|
||||
clusterId,
|
||||
sector,
|
||||
region: '',
|
||||
forces: Object.fromEntries(
|
||||
forces.map((force) => [
|
||||
force,
|
||||
{
|
||||
pressure: '',
|
||||
evidence: '',
|
||||
source: '',
|
||||
period: '',
|
||||
rationale: '',
|
||||
limitations: '',
|
||||
opportunity: '',
|
||||
},
|
||||
]),
|
||||
) as Record<Force, Assessment>,
|
||||
};
|
||||
}
|
||||
|
||||
// A pressure is an author's qualitative assessment, never inferred from missing data.
|
||||
export function assessmentReady(row: Assessment): boolean {
|
||||
return (
|
||||
['low', 'medium', 'high'].includes(row.pressure) &&
|
||||
fields.every((field) => row[field].trim().length > 0)
|
||||
);
|
||||
}
|
||||
|
||||
export function diagnosticReady(draft: CompetitivenessDraft): boolean {
|
||||
return (
|
||||
Boolean(draft.sector.trim() && draft.region.trim()) &&
|
||||
forces.every((force) => assessmentReady(draft.forces[force]))
|
||||
);
|
||||
}
|
||||
|
||||
export function readCompetitivenessDraft(
|
||||
raw: string,
|
||||
clusterId: string,
|
||||
): CompetitivenessDraft {
|
||||
if (raw.length > 250_000)
|
||||
throw Error('O ficheiro excede o limite de 250 KB.');
|
||||
const input = JSON.parse(raw);
|
||||
if (!input || input.version !== 1 || input.clusterId !== clusterId) {
|
||||
throw Error(
|
||||
'O ficheiro não corresponde a este cluster ou tem uma versão incompatível.',
|
||||
);
|
||||
}
|
||||
const text = (value: unknown, max: number): string => {
|
||||
if (typeof value !== 'string' || value.length > max)
|
||||
throw Error('O ficheiro contém campos inválidos.');
|
||||
return value;
|
||||
};
|
||||
const draft = newCompetitivenessDraft(clusterId, text(input.sector, 200));
|
||||
draft.region = text(input.region, 1000);
|
||||
for (const force of forces) {
|
||||
const row = input.forces?.[force];
|
||||
if (!row || !['', 'low', 'medium', 'high'].includes(row.pressure)) {
|
||||
throw Error('O ficheiro não contém as cinco forças válidas.');
|
||||
}
|
||||
draft.forces[force].pressure = row.pressure;
|
||||
for (const field of fields)
|
||||
draft.forces[force][field] = text(row[field], 5000);
|
||||
}
|
||||
return draft;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Presentation only. Original taxonomy identifiers remain the form/query values. */
|
||||
const names:Record<string,string>={
|
||||
agronegocio:'Agronegócio','bens-de-consumo-e-franquias':'Bens de consumo e franquias',energia:'Energia e mineração (catálogo histórico)',
|
||||
'energia-especifica':'Energia',fintech:'Fintech',fiscalidade:'Fiscalidade',imobiliario:'Imobiliário',infraestruturas:'Infraestruturas',
|
||||
iva:'IVA',mineracao:'Mineração','território':'Território',territorio:'Território',turismo:'Turismo','mercado-financeiro':'Mercado financeiro',
|
||||
education:'Formação e competências',media:'Imagens e conteúdos de apoio',pt:'Português',en:'Inglês',
|
||||
};
|
||||
export function documentFacetLabel(value:string):string{return names[value]??value;}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { modeloAFields, modeloAReference } from './iva-modelo-a.ts';
|
||||
|
||||
export type FiscalFormKind = 'iva' | 'irpc';
|
||||
export const fiscalFormVersion = 'investmoz-fiscal-preparation/1';
|
||||
export const fiscalForms = {
|
||||
iva: { title: 'IVA — Modelo A', source: modeloAReference.file, hash: modeloAReference.sha256, coverage: 'Campos 01–27 do exemplar, para preenchimento manual. A edição e as divergências já documentadas continuam identificadas.' },
|
||||
irpc: { title: 'IRPC — Modelo 22', source: 'IRPC M-22- DECLARACAO DE RENDIMENTOS.pdf', hash: '4b61bd83d1fbcfd3b7b5c5523cea5923f7d0f65dc4c004eff58e5db38f763c88', coverage: 'Preparação parcial: resultado, lucro, matéria colectável e liquidação nos campos abaixo. Os restantes ajustamentos e anexos do exemplar não são preenchidos aqui. L8 permanece parcial.' },
|
||||
} as const;
|
||||
const irpcFields = [
|
||||
['200', 'Resultado do exercício'], ['259', 'Prejuízo fiscal'], ['260', 'Lucro tributável'],
|
||||
['269', 'Prejuízo fiscal — regime geral'], ['270', 'Lucro tributável — regime geral'],
|
||||
['276', 'Prejuízos fiscais deduzidos'], ['277', 'Benefícios fiscais a deduzir'], ['278', 'Matéria colectável — regime geral'],
|
||||
['300', 'Imposto à taxa normal'], ['301', 'Imposto à taxa reduzida'], ['302', 'Colecta total'],
|
||||
['303', 'Dupla tributação económica'], ['304', 'Dupla tributação internacional'], ['305', 'Benefícios fiscais'],
|
||||
['306', 'Pagamento especial por conta'], ['308', 'Total das deduções'], ['309', 'IRPC liquidado'],
|
||||
['310', 'Retenções na fonte'], ['311', 'Pagamentos por conta'], ['312', 'IRPC a pagar antes de juros'],
|
||||
['313', 'IRPC a recuperar antes de juros'], ['314', 'Juros compensatórios'], ['315', 'IRPC a pagar'], ['316', 'IRPC a recuperar'],
|
||||
] as const;
|
||||
export function fiscalFormFields(kind: FiscalFormKind) {
|
||||
return kind === 'iva'
|
||||
? modeloAFields.map(f => ({ code: f.field, label: f.purpose, guidance: f.basis }))
|
||||
: irpcFields.map(([code, label]) => ({ code, label, guidance: Number(code) < 269 ? 'Quadro 10 do exemplar.' : Number(code) < 300 ? 'Quadro 11, regime geral. Outros regimes não incluídos nesta preparação.' : 'Quadro 12 do exemplar. Preenchimento manual, sem cálculo ou validação automática da liquidação.' }));
|
||||
}
|
||||
export type FiscalPreparation = {
|
||||
version: typeof fiscalFormVersion;
|
||||
kind: FiscalFormKind;
|
||||
sourceHash: string;
|
||||
name: string;
|
||||
nuit: string;
|
||||
period: string;
|
||||
notes: string;
|
||||
values: Record<string, string>;
|
||||
};
|
||||
export function newFiscalPreparation(kind: FiscalFormKind): FiscalPreparation {
|
||||
return { version: fiscalFormVersion, kind, sourceHash: fiscalForms[kind].hash, name: '', nuit: '', period: '', notes: '', values: {} };
|
||||
}
|
||||
export function readFiscalPreparation(raw: string): FiscalPreparation {
|
||||
if (raw.length > 100_000) throw new Error('O ficheiro excede o tamanho de uma preparação.');
|
||||
let p: unknown;
|
||||
try { p = JSON.parse(raw); } catch { throw new Error('Não foi possível ler este ficheiro de preparação. Os campos actuais foram preservados.'); }
|
||||
if (!p || typeof p !== 'object' || Array.isArray(p)) throw new Error('Ficheiro de preparação inválido.');
|
||||
const v = p as Record<string, unknown>;
|
||||
if (v.version !== fiscalFormVersion || (v.kind !== 'iva' && v.kind !== 'irpc') || v.sourceHash !== fiscalForms[v.kind].hash) throw new Error('Versão ou exemplar diferente. A preparação actual foi preservada.');
|
||||
for (const key of ['name', 'nuit', 'period', 'notes']) {
|
||||
if (typeof v[key] !== 'string' || v[key].length > 5000) throw new Error('Identificação ou notas inválidas.');
|
||||
}
|
||||
if (!v.values || typeof v.values !== 'object' || Array.isArray(v.values)) throw new Error('Campos inválidos.');
|
||||
const allowed = new Set(fiscalFormFields(v.kind).map(f => f.code));
|
||||
const values: Record<string, string> = {};
|
||||
for (const [code, value] of Object.entries(v.values)) {
|
||||
if (!allowed.has(code) || typeof value !== 'string' || value.length > 100) throw new Error('Campo não reconhecido. A preparação actual foi preservada.');
|
||||
values[code] = value;
|
||||
}
|
||||
return { ...newFiscalPreparation(v.kind), name: v.name as string, nuit: v.nuit as string, period: v.period as string, notes: v.notes as string, values };
|
||||
}
|
||||
export function fiscalPreparationIssues(p: FiscalPreparation): string[] {
|
||||
const issues: string[] = [];
|
||||
if (!p.name.trim()) issues.push('Indique o nome ou designação social.');
|
||||
if (!/^\d{9}$/.test(p.nuit)) issues.push('Indique o NUIT com 9 algarismos.');
|
||||
if (!(p.kind === 'iva' ? /^\d{4}-(0[1-9]|1[0-2])$/ : /^\d{4}$/).test(p.period)) issues.push(p.kind === 'iva' ? 'Indique ano e mês do período.' : 'Indique o ano do exercício.');
|
||||
for (const f of fiscalFormFields(p.kind)) {
|
||||
const value = p.values[f.code] ?? '';
|
||||
if (value !== '' && !/^-?\d{1,24}(?:[.,]\d{1,2})?$/.test(value)) issues.push(`Campo ${f.code}: use um montante sem separador de milhares, com até duas casas decimais.`);
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
export type FillGroup = { id: string; title: string; hint: string; fields: string[] };
|
||||
const definitions: Omit<FillGroup, 'fields'>[] = [
|
||||
{id:'idea',title:'Ideia e actividade',hint:'Identifique o investimento e descreva a necessidade que pretende responder.'},
|
||||
{id:'people',title:'Promotor e contactos',hint:'Reutilize os contactos guardados e escolha o que pode ser divulgado.'},
|
||||
{id:'territory',title:'Localização e enquadramento',hint:'Indique o território conhecido e as associações documentadas que se aplicam.'},
|
||||
{id:'operation',title:'Actividade e impacto',hint:'Complete os produtos, recursos, mercados e impactos relevantes para esta oportunidade.'},
|
||||
{id:'finance',title:'Investimento e financiamento',hint:'Preencha os valores conhecidos. O rascunho pode continuar incompleto.'},
|
||||
{id:'evidence',title:'Documentos e imagens',hint:'Reutilize os recursos guardados na mesma oportunidade.'},
|
||||
{id:'specific',title:'Dados específicos',hint:'Preencha os detalhes aplicáveis à modalidade escolhida.'},
|
||||
{id:'review',title:'Revisão e divulgação',hint:'Reveja riscos, condições e visibilidade antes das acções autorizadas de submissão.'},
|
||||
];
|
||||
const fields: Record<string,string[]> = {
|
||||
idea:['official_title','sector_id','subsector_id','economic_activity_id','executive_summary','demand_statement','opportunity_type','maturity_stage','enterprise_size'],
|
||||
people:['promoter_type','internal_contact_id','publish_contact','public_contact_id'],
|
||||
territory:['location_mode','geographic_scope','multi_district_rationale','locations','relations'],
|
||||
operation:['investment_modalities','investor_profiles','products','assets','inputs','markets','competitive_advantage','employment','impact_indicators'],
|
||||
finance:['total_investment','currency','investment_breakdown','secured_financing','funding_sought','financial_indicators'],
|
||||
evidence:['documents','evidences','images'],
|
||||
review:['publication_languages','visibility','review_due_date','truth_declaration','milestones','licenses','environmental_social','risks'],
|
||||
};
|
||||
|
||||
/** Presentation groups only: retain every applicable field exactly once, including future schema keys. */
|
||||
export function opportunityFillGroups(available: string[]): FillGroup[] {
|
||||
const unique=[...new Set(available)];
|
||||
return definitions.map(group=>({...group,fields:unique.filter(field=>{
|
||||
const owner=Object.keys(fields).find(key=>fields[key].includes(field))??'specific';
|
||||
return owner===group.id;
|
||||
})})).filter(group=>group.fields.length>0);
|
||||
}
|
||||
|
||||
export function opportunityErrorGroup(groups: FillGroup[], errors: Record<string,string>): string | undefined {
|
||||
return groups.find(group=>group.fields.some(field=>Object.keys(errors).some(path=>path===`canonical.${field}`||path.startsWith(`canonical.${field}.`))))?.id;
|
||||
}
|
||||
|
||||
export function opportunityMissingGroups(groups:FillGroup[], paths:string[]):FillGroup[] {
|
||||
return groups.filter(group=>group.fields.some(field=>paths.some(path=>{
|
||||
const normalized=path.replace(/^canonical\./,'');
|
||||
return normalized===field||normalized.startsWith(`${field}.`);
|
||||
})));
|
||||
}
|
||||
@@ -8,6 +8,9 @@ export type PortalNavItem = {
|
||||
children?: PortalNavItem[];
|
||||
};
|
||||
export type PortalNavAccess = {
|
||||
contentManagementHref?: string | null;
|
||||
contentManagementAccess?: {opportunities?:{index:string;create?:string|null}};
|
||||
scopedAdministration?: { label: string; href: string }[];
|
||||
procurement?: boolean;
|
||||
authenticated: boolean;
|
||||
manager: boolean;
|
||||
@@ -31,6 +34,10 @@ const link = (id: string, label: string, href: string): PortalNavItem => ({
|
||||
label,
|
||||
href,
|
||||
});
|
||||
/** Display the existing server decision; a generic manager flag cannot override a scoped denial. */
|
||||
export function canShowLegacyManagement(auth?:{user?:unknown;canManagePortal?:boolean;legacyManagementAccess?:boolean}):boolean {
|
||||
return !!auth?.user && (auth.legacyManagementAccess??auth.canManagePortal??false);
|
||||
}
|
||||
|
||||
/** One route catalogue for the public shell and authenticated pages. */
|
||||
export function legacyPortalNavigation(
|
||||
@@ -371,6 +378,7 @@ export function legacyPortalNavigation(
|
||||
'Gestão de perfis',
|
||||
profile.administration,
|
||||
),
|
||||
link('profile-installation','Instalação dos perfis 040000','/management/profile-install'),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
@@ -439,7 +447,10 @@ export function currentNavigationItem(
|
||||
|
||||
/** Investor organization; existing capability filters still determine private destinations. */
|
||||
export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
const previous = legacyPortalNavigation(access);
|
||||
const previous = legacyPortalNavigation({...access,manager:access.authenticated&&access.manager,profileAccess:access.authenticated?access.profileAccess:null});
|
||||
const workHub=access.authenticated?access.contentManagementHref:null;
|
||||
const workOpportunities=access.authenticated?access.contentManagementAccess?.opportunities:undefined;
|
||||
const workCreate=access.authenticated?(access.profileAccess?.create||workOpportunities?.create||(access.manager&&access.opportunityManagement?.installed?access.opportunityManagement.create.href:null)):null;
|
||||
return uniqueNavigationDestinations([
|
||||
{
|
||||
id: 'discovery',
|
||||
@@ -544,11 +555,20 @@ export function portalNavigation(access: PortalNavAccess): PortalNavItem[] {
|
||||
),
|
||||
],
|
||||
},
|
||||
...previous.filter((group) =>
|
||||
['account', 'management', 'profile-opportunities'].includes(
|
||||
group.id,
|
||||
),
|
||||
),
|
||||
...[{
|
||||
id: 'work',
|
||||
label: 'Área de trabalho',
|
||||
children: [
|
||||
link('work-entry', workHub ? 'Gestão de conteúdos e oportunidades':'Acesso à gestão', workHub || '/acesso-gestao'),
|
||||
...(workCreate ? [
|
||||
link('prepare-analysis', 'Preparar análise e ideia', workCreate+'?analysis=proactive'),
|
||||
] : []),
|
||||
...(workOpportunities ? [link('work-opportunities','Oportunidades em preparação',workOpportunities.index)] : []),
|
||||
...previous.filter(group=>['management','profile-opportunities'].includes(group.id)).flatMap(group=>group.children??[]),
|
||||
...(access.authenticated&&access.scopedAdministration?.length ? [{id:'work-administration',label:'Administração',children:access.scopedAdministration.map((item,index)=>link('scoped-'+index,item.label,item.href))}] : []),
|
||||
],
|
||||
}],
|
||||
...previous.filter((group) => group.id === 'account'),
|
||||
...(access.authenticated &&
|
||||
access.businesses &&
|
||||
access.businessReviewUrl
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
const territoryKeys=['province_id','district_id','admin_post_id','locality_id'];
|
||||
/** No fallback scope: an explicit empty path means all; a selected path replaces its old descendants. */
|
||||
export function territorialSearchParams(entries: Iterable<[string,FormDataEntryValue]>, path?: {id:string;location_type:string}[]): URLSearchParams {
|
||||
const params=new URLSearchParams();
|
||||
for(const [key,value] of entries)if(typeof value==='string'&&value!==''&&key!=='page')params.set(key,value);
|
||||
if(path){
|
||||
territoryKeys.forEach(key=>params.delete(key));
|
||||
for(const node of path){const key=`${node.location_type}_id`;if(territoryKeys.includes(key))params.set(key,node.id);}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import SearchState from '@/components/search-state';
|
||||
import { useInterestDraft } from '@/hooks/use-interest-draft';
|
||||
import { createContext, useContext, useRef, useState } from '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 { MATURITY_LEVELS } from '@/lib/investment-maturity';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
@@ -973,7 +973,7 @@ export default function PortalInvestidorApp({
|
||||
|
||||
function handleHeroSearch(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
router.get('/oportunidades', { q: heroQuery.trim() });
|
||||
router.get('/pesquisa', { q: heroQuery.trim() });
|
||||
}
|
||||
|
||||
function handleView(opportunity: Opportunity) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { participationIdentity } from '@/lib/participation-identity';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
import { Form, Head, usePage } from '@inertiajs/react';
|
||||
import InputError from '@/components/input-error';
|
||||
import PasswordInput from '@/components/password-input';
|
||||
@@ -24,11 +25,12 @@ type 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.
|
||||
const pageErrors = usePage<{ errors: { email?: string } }>().props.errors;
|
||||
return (
|
||||
<>
|
||||
<Head title="Entrar" />
|
||||
<Head title={t('Entrar')} />
|
||||
|
||||
{qaAccount && (
|
||||
<aside
|
||||
@@ -48,9 +50,9 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
|
||||
{/* @chisel-passkeys */}
|
||||
<PasskeyVerify
|
||||
label="Entrar com chave de acesso"
|
||||
loadingLabel="A autenticar…"
|
||||
separator="Ou continuar com email"
|
||||
label={t('Entrar com chave de acesso')}
|
||||
loadingLabel={t('A autenticar…')}
|
||||
separator={t('Ou continuar com email')}
|
||||
/>
|
||||
{/* @end-chisel-passkeys */}
|
||||
|
||||
@@ -85,7 +87,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center">
|
||||
<Label htmlFor="password">
|
||||
Palavra-passe
|
||||
{t('Palavra-passe')}
|
||||
</Label>
|
||||
{canResetPassword && (
|
||||
<TextLink
|
||||
@@ -93,7 +95,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
className="ml-auto text-sm"
|
||||
tabIndex={5}
|
||||
>
|
||||
Esqueceu a palavra-passe?
|
||||
{t('Esqueceu a palavra-passe?')}
|
||||
</TextLink>
|
||||
)}
|
||||
</div>
|
||||
@@ -103,7 +105,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
required
|
||||
tabIndex={2}
|
||||
autoComplete="current-password"
|
||||
placeholder="Palavra-passe"
|
||||
placeholder={t('Palavra-passe')}
|
||||
/>
|
||||
<InputError message={errors.password} />
|
||||
</div>
|
||||
@@ -115,7 +117,7 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
tabIndex={3}
|
||||
/>
|
||||
<Label htmlFor="remember">
|
||||
Manter sessão iniciada
|
||||
{t('Manter sessão iniciada')}
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
@@ -127,15 +129,15 @@ export default function Login({ status, canResetPassword, qaAccount }: Props) {
|
||||
data-test="login-button"
|
||||
>
|
||||
{processing && <Spinner />}
|
||||
Entrar
|
||||
{t('Entrar')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* @chisel-registration */}
|
||||
<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}>
|
||||
Criar conta
|
||||
{t('Criar conta')}
|
||||
</TextLink>
|
||||
</div>
|
||||
{/* @end-chisel-registration */}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { participationIdentity } from '@/lib/participation-identity';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
import { Form, Head } from '@inertiajs/react';
|
||||
import InputError from '@/components/input-error';
|
||||
import PasswordInput from '@/components/password-input';
|
||||
@@ -15,9 +16,10 @@ type Props = {
|
||||
};
|
||||
|
||||
export default function Register({ passwordRules }: Props) {
|
||||
const { t } = useTempoUi();
|
||||
return (
|
||||
<>
|
||||
<Head title="Criar conta" />
|
||||
<Head title={t('Criar conta')} />
|
||||
<Form
|
||||
{...store.form()}
|
||||
resetOnSuccess={['password', 'password_confirmation']}
|
||||
@@ -28,7 +30,7 @@ export default function Register({ passwordRules }: Props) {
|
||||
<>
|
||||
<div className="grid gap-6">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="name">Nome</Label>
|
||||
<Label htmlFor="name">{t('Nome')}</Label>
|
||||
<Input
|
||||
id="name"
|
||||
defaultValue={participationIdentity().name}
|
||||
@@ -37,7 +39,7 @@ export default function Register({ passwordRules }: Props) {
|
||||
tabIndex={1}
|
||||
autoComplete="name"
|
||||
name="name"
|
||||
placeholder="Nome completo"
|
||||
placeholder={t('Nome completo')}
|
||||
/>
|
||||
<InputError
|
||||
message={errors.name}
|
||||
@@ -61,14 +63,14 @@ export default function Register({ passwordRules }: Props) {
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">Palavra-passe</Label>
|
||||
<Label htmlFor="password">{t('Palavra-passe')}</Label>
|
||||
<PasswordInput
|
||||
id="password"
|
||||
required
|
||||
tabIndex={3}
|
||||
autoComplete="new-password"
|
||||
name="password"
|
||||
placeholder="Palavra-passe"
|
||||
placeholder={t('Palavra-passe')}
|
||||
passwordrules={passwordRules}
|
||||
/>
|
||||
<InputError message={errors.password} />
|
||||
@@ -76,7 +78,7 @@ export default function Register({ passwordRules }: Props) {
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password_confirmation">
|
||||
Confirmar palavra-passe
|
||||
{t('Confirmar palavra-passe')}
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="password_confirmation"
|
||||
@@ -84,7 +86,7 @@ export default function Register({ passwordRules }: Props) {
|
||||
tabIndex={4}
|
||||
autoComplete="new-password"
|
||||
name="password_confirmation"
|
||||
placeholder="Confirmar palavra-passe"
|
||||
placeholder={t('Confirmar palavra-passe')}
|
||||
passwordrules={passwordRules}
|
||||
/>
|
||||
<InputError
|
||||
@@ -99,14 +101,14 @@ export default function Register({ passwordRules }: Props) {
|
||||
data-test="register-user-button"
|
||||
>
|
||||
{processing && <Spinner />}
|
||||
Criar conta
|
||||
{t('Criar conta')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground text-center text-sm">
|
||||
Já tem conta?{' '}
|
||||
{t('Já tem conta?')}{' '}
|
||||
<TextLink href={login()} tabIndex={6}>
|
||||
Entrar
|
||||
{t('Entrar')}
|
||||
</TextLink>
|
||||
</div>
|
||||
</>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { TerritorialSourceEvidence } from '@/components/territorial-source-evidence';
|
||||
import type {
|
||||
@@ -53,6 +53,7 @@ export type Opportunity = {
|
||||
description: string | null;
|
||||
province: string | null;
|
||||
district: string | null;
|
||||
territorial_summary?: string;
|
||||
sector?: { name: string; slug: string };
|
||||
estimated_investment_amount: string | null;
|
||||
estimated_investment_currency: string;
|
||||
|
||||
@@ -3,7 +3,9 @@ import InvestmentZoneInstallation, {
|
||||
} from '@/components/investment-zone-installation';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import { searchTerritoryHref } from '@/lib/search-territory';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { territorialSearchParams } from '@/lib/territorial-search-params';
|
||||
import CatalogueFilterContext from '@/components/catalogue-filter-context';
|
||||
import { catalogueDetailHref } from '@/lib/catalogue-context';
|
||||
import {
|
||||
TerritoryFields,
|
||||
@@ -77,6 +79,10 @@ export default function Zones({
|
||||
total: number;
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
from?: number | null;
|
||||
to?: number | null;
|
||||
current_page?: number;
|
||||
last_page?: number;
|
||||
};
|
||||
filters: {
|
||||
q?: string;
|
||||
@@ -94,6 +100,30 @@ export default function Zones({
|
||||
const pageUrl = usePage().url;
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const searchForm=useRef<HTMLFormElement|null>(null);
|
||||
const searchTimer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined);
|
||||
const cancelSearch=useRef<(()=>void)|undefined>(undefined);
|
||||
const searchSequence=useRef(0);
|
||||
const [searching,setSearching]=useState(false);
|
||||
const [searchError,setSearchError]=useState('');
|
||||
const appliedKey=JSON.stringify([filters,territorySelection]);
|
||||
useEffect(()=>{searchForm.current?.reset();},[appliedKey]);
|
||||
useEffect(()=>()=>{clearTimeout(searchTimer.current);cancelSearch.current?.();},[]);
|
||||
const runSearch=(path?:TerritoryOption[])=>{
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();
|
||||
if(!searchForm.current)return;
|
||||
const sequence=++searchSequence.current;
|
||||
const params=territorialSearchParams(new FormData(searchForm.current),path);
|
||||
setSearching(true);setSearchError('');
|
||||
router.get(`${management?'/management/investment/zones':'/zonas'}?${params}`,{}, {
|
||||
preserveState:true,preserveScroll:true,replace:true,
|
||||
onCancelToken:token=>{cancelSearch.current=()=>token.cancel();},
|
||||
onError:()=>{if(sequence===searchSequence.current)setSearchError('A pesquisa não foi concluída. Confira os filtros e tente novamente.');},
|
||||
onNetworkError:()=>{if(sequence===searchSequence.current)setSearchError('Ligação indisponível. Os filtros escolhidos foram preservados.');return false;},
|
||||
onHttpException:()=>{if(sequence===searchSequence.current)setSearchError('Não foi possível consultar esta selecção.');return false;},
|
||||
onFinish:()=>{if(sequence===searchSequence.current)setSearching(false);},
|
||||
});
|
||||
};
|
||||
const exportParams = new URLSearchParams();
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach((field, index) => {
|
||||
if (territorySelection[index]) exportParams.set(field, territorySelection[index].id);
|
||||
@@ -160,22 +190,18 @@ export default function Zones({
|
||||
</Link>
|
||||
</nav>
|
||||
</details>
|
||||
<CatalogueFilterContext />
|
||||
<form
|
||||
ref={searchForm}
|
||||
method="get"
|
||||
onChange={(event)=>{
|
||||
if(!event.target.getAttribute('name'))return;
|
||||
clearTimeout(searchTimer.current);cancelSearch.current?.();searchSequence.current++;
|
||||
setSearching(true);setSearchError('');searchTimer.current=setTimeout(()=>runSearch(),350);
|
||||
}}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const url = new URL(form.action);
|
||||
const params = new URLSearchParams();
|
||||
for (const [name, value] of new FormData(form))
|
||||
if (typeof value === 'string')
|
||||
params.append(name, value);
|
||||
url.search = params.toString();
|
||||
router.get(
|
||||
url.toString(),
|
||||
{},
|
||||
{ preserveState: true, preserveScroll: true },
|
||||
);
|
||||
runSearch();
|
||||
}}
|
||||
className={card + ' grid gap-4 md:grid-cols-3'}
|
||||
>
|
||||
@@ -307,10 +333,14 @@ export default function Zones({
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
<TerritoryFields initial={territorySelection} />
|
||||
<TerritoryFields initial={territorySelection} onChange={path=>runSearch(path)} />
|
||||
<button type="button" className="underline" onClick={()=>runSearch([])}>Todo o território (remover localização)</button>
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
{!management && (
|
||||
<h2 className="text-xl font-semibold">{searching?'A pesquisar a selecção…':searchError?'Pesquisa por concluir':`${records.total} registos disponíveis · ${territorySelection.length?territorySelection.map(node=>node.name).join(' / '):'Todo o território'}`}</h2>
|
||||
{!searching&&!searchError&&records.total>0&&<p>A mostrar {records.from??1} a {records.to??records.data.length} de {records.total}. Página {records.current_page??1} de {records.last_page??1}.</p>}
|
||||
{searchError&&<p role="alert">{searchError}</p>}
|
||||
{!management && !searching && !searchError && (
|
||||
<a
|
||||
className="underline"
|
||||
href={`/api/v2/investment/zones/export.csv?${exportParams.toString()}`}
|
||||
@@ -318,12 +348,12 @@ export default function Zones({
|
||||
Exportar resultados filtrados (CSV)
|
||||
</a>
|
||||
)}
|
||||
{!records.total && (
|
||||
{!searching && !searchError && !records.total && (
|
||||
<p className={card}>
|
||||
Não foram encontrados resultados para esta pesquisa.
|
||||
</p>
|
||||
)}
|
||||
{records.data.map((zone) => (
|
||||
{!searching && !searchError && records.data.map((zone) => (
|
||||
<article className={card} key={zone.id}>
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
@@ -451,10 +481,10 @@ export default function Zones({
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Paginação" className="flex gap-4 underline">
|
||||
{records.prev_page_url && (
|
||||
{!searching && !searchError && records.prev_page_url && (
|
||||
<Link href={records.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
{records.next_page_url && (
|
||||
{!searching && !searchError && records.next_page_url && (
|
||||
<Link href={records.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
@@ -171,10 +171,8 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
];
|
||||
const states = path.canWrite ? ownerStates : reviewStates;
|
||||
return (
|
||||
<article id={step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<h3 className="font-semibold">
|
||||
{step.code} · {step.title}
|
||||
</h3>
|
||||
<details id={step.code} open={path.next?.code===step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer font-semibold">{step.title} · {pathStates[step.state]}</summary>
|
||||
<p>{pathStates[step.state]}</p>
|
||||
{step.context_review_required && (
|
||||
<label className="block rounded border border-amber-600 bg-amber-50 p-3">
|
||||
@@ -235,17 +233,18 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
: action === 'operate'
|
||||
? 'Operação'
|
||||
: 'Execução'}{' '}
|
||||
aguarda {gaps.join(', ')}. Pode continuar a preparar.
|
||||
aguarda {gaps.map(code=>path.steps.find(item=>item.code===code)?.title??code).join(', ')}. Pode continuar a preparar.
|
||||
</p>
|
||||
))}
|
||||
<p className="text-xs">
|
||||
<details className="text-xs"><summary className="cursor-pointer underline">Fonte e referência desta etapa</summary><p>
|
||||
Referência interna {step.code}.{' '}
|
||||
Documento original, parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p>
|
||||
</p></details>
|
||||
{step.preparation_allowed && (path.canWrite || path.canReview) && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
@@ -405,7 +404,7 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
</form>
|
||||
</details>
|
||||
)}
|
||||
</article>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -718,10 +717,10 @@ export default function InvestmentPath(path: Path) {
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<section className="space-y-3" key={number}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<details open={path.steps.some(step=>step.phase===Number(number)&&step.code===path.next?.code)} className="space-y-3 rounded border p-4" key={number}>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</h2>
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
@@ -733,7 +732,7 @@ export default function InvestmentPath(path: Path) {
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</details>
|
||||
))}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
@@ -819,10 +818,10 @@ export default function InvestmentPath(path: Path) {
|
||||
Anexar ou conferir no Balcão
|
||||
</Link>
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
<details className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Acompanhamento interno
|
||||
</h2>
|
||||
</summary>
|
||||
{path.canWrite && (
|
||||
<form
|
||||
className="grid min-w-0 gap-3 [&_input]:max-w-full [&_input]:min-w-0 [&_label]:min-w-0 [&_select]:max-w-full [&_select]:min-w-0"
|
||||
@@ -983,7 +982,7 @@ export default function InvestmentPath(path: Path) {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</details>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {ProactiveInvestmentEditor,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import {ProactiveInvestmentEditor,newProactive,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
@@ -140,18 +140,21 @@ export default function OpportunityDraft({
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const proactiveEntryUrl=usePage().url;
|
||||
const uniquePromoterContext=profileAccess?.contexts.length===1?profileAccess.contexts[0]:undefined;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(!record && !values.proactive && new URLSearchParams(proactiveEntryUrl.split('?')[1]??'').get('analysis')==='proactive' ? {proactive:newProactive()} : {}),
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: profileAccess?.internalPromoter
|
||||
? null
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
: (uniquePromoterContext?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
uniquePromoterContext?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
@@ -171,10 +174,11 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const hasCanonicalPreparation = profileMode && canonicalOptions && Boolean(data.opportunity_category) && !data.proactive;
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore', resourcesGroup?: string) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -222,8 +226,10 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record) router.visit(`${basePath}/${result.id}/edit`);
|
||||
if (resourcesGroup) router.visit(`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`);
|
||||
else if (!record) router.visit(`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`);
|
||||
else if (action !== 'save') router.reload();
|
||||
else if (profileMode) router.reload({only:['canonicalResponse','etag','history','workflowState','profileContext']});
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
@@ -235,10 +241,8 @@ export default function OpportunityDraft({
|
||||
document.querySelector<HTMLSelectElement>(
|
||||
'[data-association-index][aria-invalid="true"]',
|
||||
);
|
||||
(
|
||||
invalidAssociation ??
|
||||
document.getElementById('opportunity-result')
|
||||
)?.focus();
|
||||
if (invalidAssociation) invalidAssociation.focus();
|
||||
else document.getElementById('opportunity-result')?.focus({preventScroll:true});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -250,9 +254,7 @@ export default function OpportunityDraft({
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{!profileMode && <Link href={basePath}>Voltar à gestão</Link>}
|
||||
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
|
||||
{!!profileContext?.corridor_agribusiness && (
|
||||
<section className="my-4 space-y-2 rounded border p-4">
|
||||
@@ -271,11 +273,11 @@ export default function OpportunityDraft({
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && (
|
||||
<section
|
||||
aria-label="Âmbito desta entrega"
|
||||
<details
|
||||
aria-label="Disponibilidade por modalidade"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<h2>Âmbito desta entrega</h2>
|
||||
<summary className="cursor-pointer font-medium">Modalidades disponíveis e condições de submissão</summary>
|
||||
<p>
|
||||
Seis categorias base: projeto de investimento,
|
||||
imobiliário, fundiário, venda de negócio, parceria e
|
||||
@@ -304,7 +306,7 @@ export default function OpportunityDraft({
|
||||
certifica a viabilidade, a titularidade ou a decisão
|
||||
externa de cada caso.
|
||||
</p>
|
||||
</section>
|
||||
</details>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<ClassificationReview id={record.id} refreshToken={token} />
|
||||
@@ -334,8 +336,8 @@ export default function OpportunityDraft({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{profileAccess?.internalPromoter && (
|
||||
<option value="">
|
||||
{(profileAccess?.internalPromoter || !uniquePromoterContext) && (
|
||||
<option value="|">
|
||||
Selecionar o promotor real da oportunidade
|
||||
</option>
|
||||
)}
|
||||
@@ -821,7 +823,7 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Field
|
||||
{!hasCanonicalPreparation && <Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
@@ -832,8 +834,8 @@ export default function OpportunityDraft({
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
{!unavailable && (
|
||||
</Field>}
|
||||
{!unavailable && !hasCanonicalPreparation && (
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
@@ -891,7 +893,7 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{record && (
|
||||
{record && (!profileMode || readOnly || unavailable || !canonicalOptions || !data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
@@ -909,10 +911,10 @@ export default function OpportunityDraft({
|
||||
Associações territoriais e produtivas existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
{profileMode && canonicalOptions && Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<OpportunityContactForm
|
||||
<details><summary className="cursor-pointer font-medium">Acrescentar um contacto à oportunidade</summary><OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
organization={
|
||||
@@ -938,7 +940,7 @@ export default function OpportunityDraft({
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
/></details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
@@ -960,6 +962,7 @@ export default function OpportunityDraft({
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={canonicalResponse?.completion.missing_paths}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
@@ -967,16 +970,23 @@ export default function OpportunityDraft({
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={!readOnly && !unavailable && resourcesInstalled ? (group) => void send('save',group) : undefined}
|
||||
/>
|
||||
{!readOnly && !unavailable && (
|
||||
{!readOnly && !unavailable && hasCanonicalPreparation && (
|
||||
<div className="sticky bottom-0 space-y-3 rounded border bg-background p-4 shadow-sm">
|
||||
<Field label="O que alterou nesta preparação" error={errors.reason}>
|
||||
<textarea className={control} value={reason} onChange={(event) => setReason(event.target.value)} minLength={20} maxLength={1000} />
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar contrato no rascunho
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">Pode guardar incompleto e continuar mais tarde em Minhas oportunidades.</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
|
||||
@@ -179,6 +179,8 @@ export default function OpportunityResources({
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const returnGroup = new URLSearchParams(usePage().url.split('?')[1] ?? '').get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '') ? `#fill-${returnGroup}` : '#fill-evidence';
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
@@ -307,7 +309,7 @@ export default function OpportunityResources({
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`${basePath}/${opportunity.id}/edit`}>
|
||||
<Link href={`${basePath}/${opportunity.id}/edit${returnHash}`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
<p>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
import EditorialReading, {
|
||||
type EditorialArticle,
|
||||
} from '@/components/editorial-reading';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
type PublicDocument,
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
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 button = 'rounded border border-emerald-800 px-4 py-3 font-semibold text-emerald-900 disabled:opacity-50';
|
||||
export default function FiscalForms({ initialTax = 'iva' }: { initialTax?: FiscalFormKind }) {
|
||||
const [kind, setKind] = useState<FiscalFormKind>(initialTax);
|
||||
const [drafts, setDrafts] = useState({ iva: newFiscalPreparation('iva'), irpc: newFiscalPreparation('irpc') });
|
||||
const [step, setStep] = useState(0);
|
||||
const [notice, setNotice] = useState('');
|
||||
const [pending, setPending] = useState<FiscalPreparation | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const p = drafts[kind], source = fiscalForms[kind], fields = fiscalFormFields(kind);
|
||||
const issues = fiscalPreparationIssues(p);
|
||||
useEffect(() => {
|
||||
setKind(initialTax);
|
||||
}, [initialTax]);
|
||||
useEffect(() => {
|
||||
const warn = (e: BeforeUnloadEvent) => { if (dirty) { e.preventDefault(); e.returnValue = ''; } };
|
||||
window.addEventListener('beforeunload', warn);
|
||||
const unsubscribe = router.on('before', e => {
|
||||
if (dirty && !window.confirm('Os campos estão apenas nesta página. Guarde o ficheiro para continuar depois. Pretende sair?')) e.preventDefault();
|
||||
});
|
||||
return () => { window.removeEventListener('beforeunload', warn); unsubscribe(); };
|
||||
}, [dirty]);
|
||||
function patch(update: Partial<FiscalPreparation>) {
|
||||
setDrafts(d => ({ ...d, [kind]: { ...d[kind], ...update } }));
|
||||
setDirty(true); setNotice('');
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(p)], { type: 'application/json' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = `investmoz-preparacao-${kind}.json`; a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setNotice('Ficheiro de preparação gerado. Guarde-o para recuperar os campos. Não foi enviado ao portal nem à AT.');
|
||||
// Other tax preparation may still contain unsaved edits.
|
||||
}
|
||||
return <div className="min-h-screen bg-slate-50 text-slate-900">
|
||||
<Head title="Preencher formulário fiscal" />
|
||||
<div className="print:hidden"><PortalMenu /></div>
|
||||
<main className="mx-auto max-w-5xl space-y-6 px-5 py-8">
|
||||
<div className="print:hidden"><Link href="/documentos" className="underline">Documentos e Formulários</Link></div>
|
||||
<h1 className="text-3xl font-bold">Preencher formulário fiscal</h1>
|
||||
<p>Prepare os valores de IVA ou IRPC, confira e guarde um ficheiro para continuar depois. Os campos vazios significam informação em falta.</p>
|
||||
<p className="rounded border border-amber-600 bg-amber-50 p-3">Preparação para conferência, sem submissão à Autoridade Tributária. Os valores são introduzidos por si; não há apuramento automático nem confirmação de elegibilidade de deduções.</p>
|
||||
<label className="block max-w-lg print:hidden">Formulário
|
||||
<select className={input} value={kind} onChange={e => { setKind(e.target.value as FiscalFormKind); setStep(0); setNotice(''); setPending(null); }}>
|
||||
<option value="iva">IVA — Modelo A</option><option value="irpc">IRPC — Modelo 22</option>
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">{source.title}</h2>
|
||||
<p>{source.coverage}</p>
|
||||
<nav aria-label="Etapas de preenchimento" className="flex flex-wrap gap-2 print:hidden">
|
||||
{['Identificação e período', 'Preencher valores', 'Conferir e guardar'].map((label, n) => <button type="button" key={label} className={button} aria-current={step === n ? 'step' : undefined} onClick={() => setStep(n)}>{n + 1}. {label}</button>)}
|
||||
</nav>
|
||||
<form onSubmit={e => e.preventDefault()} className="space-y-5">
|
||||
<fieldset className={`${step !== 0 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Identificação e período</legend>
|
||||
<label className="block">Nome ou designação social<input className={input} autoComplete="organization" maxLength={5000} value={p.name} onChange={e => patch({ name: e.target.value })} /></label>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<label>NUIT<input className={input} inputMode="numeric" maxLength={9} value={p.nuit} onChange={e => patch({ nuit: e.target.value })} /></label>
|
||||
<label>{kind === 'iva' ? 'Período — ano e mês' : 'Exercício — ano'}<input className={input} type={kind === 'iva' ? 'month' : 'text'} inputMode={kind === 'irpc' ? 'numeric' : undefined} placeholder={kind === 'iva' ? 'AAAA-MM' : 'AAAA'} maxLength={7} value={p.period} onChange={e => patch({ period: e.target.value })} /></label>
|
||||
</div>
|
||||
<p className="text-sm">Dados mantidos apenas nesta página até descarregar o ficheiro. Não há gravação automática. Guarde antes de sair ou actualizar.</p>
|
||||
</fieldset>
|
||||
<fieldset className={`${step !== 1 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`}>
|
||||
<legend className="font-bold">Valores em meticais (MZN)</legend>
|
||||
<p>Sem separador de milhares; vírgula ou ponto para os cêntimos. Não preencha zero quando desconhece o valor.</p>
|
||||
{kind === 'irpc' && <p>Crédito económico (303) e internacional (304) são distintos. Não utilize a mesma parcela nos dois campos. Esta preparação manual não verifica as parcelas; conserve o suporte para conferência.</p>}
|
||||
<div className="grid gap-5 sm:grid-cols-2">{fields.map(f => <div key={f.code} className="break-inside-avoid">
|
||||
<label className="block">{f.code} — {f.label}<input className={input} inputMode="decimal" maxLength={100} value={p.values[f.code] ?? ''} onChange={e => patch({ values: { ...p.values, [f.code]: e.target.value } })} /></label>
|
||||
<details className="mt-1 text-sm print:hidden"><summary className="cursor-pointer underline">Orientação do campo</summary><p>{f.guidance}</p></details>
|
||||
</div>)}</div>
|
||||
</fieldset>
|
||||
<section className={`${step !== 2 ? 'hidden print:block' : ''} space-y-4 rounded border bg-white p-5`} aria-label="Conferir e guardar">
|
||||
<h3 className="font-bold">Conferência da preparação</h3>
|
||||
<p>{fields.filter(f => (p.values[f.code] ?? '') !== '').length} de {fields.length} campos com valor. Campos vazios não foram convertidos em zero.</p>
|
||||
{issues.length > 0 ? <div><p>Por conferir — pode guardar a preparação incompleta:</p><ul className="list-disc pl-6">{issues.map(i => <li key={i}>{i}</li>)}</ul></div> : <p>Formato dos campos conferido. Os montantes e a aplicação fiscal ainda devem ser conferidos.</p>}
|
||||
<dl className="grid gap-3 sm:grid-cols-2 print:hidden">{fields.filter(f => (p.values[f.code] ?? '') !== '').map(f => <div key={f.code}><dt>{f.code} — {f.label}</dt><dd className="font-semibold">{p.values[f.code]} MZN</dd></div>)}</dl>
|
||||
<label className="block">Notas e referências dos valores<textarea className={input} rows={4} maxLength={5000} value={p.notes} onChange={e => patch({ notes: e.target.value })} /></label>
|
||||
<div className="flex flex-wrap gap-3 print:hidden"><button type="button" className={button} onClick={download}>Guardar ficheiro para continuar</button><button type="button" className={button} onClick={() => window.print()}>Imprimir preparação</button></div>
|
||||
<p className="text-sm">O ficheiro contém os dados introduzidos. Guarde-o num local privado. Não fica associado automaticamente ao dossier.</p>
|
||||
</section>
|
||||
<div className="flex justify-between gap-3 print:hidden"><button type="button" className={button} disabled={step === 0} onClick={() => setStep(step - 1)}>Anterior</button><button type="button" className={button} disabled={step === 2} onClick={() => setStep(step + 1)}>Continuar</button></div>
|
||||
</form>
|
||||
<section className="space-y-3 rounded border p-4 print:hidden" aria-label="Recuperar preparação">
|
||||
<label className="block">Recuperar ficheiro guardado<input className={input} type="file" accept=".json,application/json" onChange={async e => {
|
||||
const file = e.target.files?.[0]; e.target.value = ''; if (!file) return;
|
||||
try { if (file.size > 100_000) throw new Error('O ficheiro é demasiado grande.'); setPending(readFiscalPreparation(await file.text())); setNotice('Ficheiro lido. Confirme a recuperação abaixo.'); }
|
||||
catch (error) { setPending(null); setNotice(error instanceof Error ? error.message : 'Não foi possível ler o ficheiro. Os campos actuais foram preservados.'); }
|
||||
}} /></label>
|
||||
{pending && <div className="space-y-2"><p>Recuperar {fiscalForms[pending.kind].title}, período {pending.period || 'por indicar'}? Substitui apenas os campos desse formulário nesta página.</p><button type="button" className={button} onClick={() => { setDrafts(d => ({ ...d, [pending.kind]: pending })); setKind(pending.kind); setStep(2); setPending(null); setDirty(true); setNotice('Preparação recuperada.'); }}>Confirmar recuperação</button> <button type="button" className={button} onClick={() => setPending(null)}>Cancelar</button></div>}
|
||||
</section>
|
||||
{notice && <p role="status" className="rounded border p-3">{notice}</p>}
|
||||
<details className="rounded border p-4"><summary className="cursor-pointer font-semibold">Exemplar e cobertura</summary><p>{source.source}</p><p className="break-all text-sm">SHA256: {source.hash}</p><p>{source.coverage}</p><p>Os cálculos e correspondências já disponíveis no simulador permanecem separados desta introdução manual. Não se executam fórmulas nem se transportam valores entre edições automaticamente.</p></details>
|
||||
<div className="flex flex-wrap gap-4 print:hidden"><Link href="/simulador-fiscal" className="underline">Consultar cálculos e preparação M20/M22 no simulador</Link><Link href="/legislacao" className="underline">Consultar legislação</Link></div>
|
||||
</main>
|
||||
</div>;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { PublicSectorCards } from '@/components/public-sector-cards';
|
||||
import { documentFacetLabel } from '@/lib/document-facet-label';
|
||||
import { PORTAL_MORE_LINK } from '@/lib/portal-presentation';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
@@ -6,7 +7,7 @@ import {
|
||||
} from '@/components/public-document-content';
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { PortalMenu } from '@/layouts/portal-navigation';
|
||||
import { PortalMenu } from '@/components/portal-menu';
|
||||
import { newSubmissionKey } from '@/lib/portal-api';
|
||||
import { ProvinceSelect } from '@/components/investment-territory';
|
||||
import { SimulationForm } from '@/components/simulation-form';
|
||||
@@ -537,6 +538,15 @@ export default function Services(p: Props) {
|
||||
opportunities={p.opportunities}
|
||||
/>
|
||||
)}
|
||||
{p.section === 'documents' && <section aria-label="Preencher formulários fiscais" className="space-y-3 rounded-xl border bg-white p-5">
|
||||
<h2 className="text-xl font-bold">Que formulário pretende preencher?</h2>
|
||||
<p>Abra os campos do formulário fiscal. A legislação e os guias de consulta ficam abaixo.</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link className={button} href="/formularios/fiscais?imposto=iva">Preencher IVA — Modelo A</Link>
|
||||
<Link className={button} href="/formularios/fiscais?imposto=irpc">Preparar IRPC — Modelo 22</Link>
|
||||
</div>
|
||||
<p className="text-sm">Preparação manual, com gravação em ficheiro. Cobertura parcial de IRPC; sem submissão à AT.</p>
|
||||
</section>}
|
||||
{['procedures', 'documents', 'legislation'].includes(
|
||||
p.section,
|
||||
) && <JourneyDocumentResources stages={p.stages} />}
|
||||
@@ -579,7 +589,7 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.topics?.map((topic) => (
|
||||
<option key={topic}>{topic}</option>
|
||||
<option key={topic} value={topic}>{documentFacetLabel(topic)}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -606,7 +616,7 @@ export default function Services(p: Props) {
|
||||
value={category}
|
||||
>
|
||||
{documentTypeLabels[category] ??
|
||||
category}
|
||||
documentFacetLabel(category)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -809,8 +819,8 @@ export default function Services(p: Props) {
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{p.languages?.map((language) => (
|
||||
<option key={language}>
|
||||
{language}
|
||||
<option key={language} value={language}>
|
||||
{documentFacetLabel(language)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -917,7 +927,7 @@ export default function Services(p: Props) {
|
||||
className="rounded-full border bg-white px-3 py-1 underline"
|
||||
href={`${p.section === 'documents' ? '/documentos' : '/legislacao'}?${new URLSearchParams({ topic }).toString()}`}
|
||||
>
|
||||
{topic}
|
||||
{documentFacetLabel(topic)}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Management } from '../management/shared';
|
||||
import { Layout, Field, control, button, labels, kind } from './shared';
|
||||
import type { Dossier } from './shared';
|
||||
import InvestmentComplements, { type ComplementOption } from '@/components/investment-complements';
|
||||
import ClusterCompetitivenessPublic, { type ApprovedCompetitiveness } from '@/components/cluster-competitiveness-public';
|
||||
export default function Show(props: Props) {
|
||||
return (
|
||||
<Editor
|
||||
@@ -21,6 +22,7 @@ export default function Show(props: Props) {
|
||||
}
|
||||
|
||||
type Props = {
|
||||
competitiveness?: ApprovedCompetitiveness | null;
|
||||
complements?: ComplementOption[];
|
||||
geography: StructureGeography;
|
||||
existingSubmissions?: { id: string; version: number; updated_at: string }[];
|
||||
@@ -54,6 +56,7 @@ type Props = {
|
||||
};
|
||||
|
||||
function Editor({
|
||||
competitiveness,
|
||||
complements = [],
|
||||
record,
|
||||
related,
|
||||
@@ -94,6 +97,7 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{competitiveness && <ClusterCompetitivenessPublic analysis={competitiveness} />}
|
||||
{!management && (
|
||||
<div className="space-y-2 rounded-xl border p-4">
|
||||
<Link className="underline" href={portfolioPreparationHref(record.id, pageUrl)}>
|
||||
|
||||
@@ -4,6 +4,11 @@ import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import ProfileProofPicker from '@/components/profile-proof-picker';
|
||||
|
||||
const representations: Record<string,string> = {individual:'Em nome próprio',company:'Empresa',public_entity:'Entidade pública',association:'Associação',partner:'Parceiro ou representante'};
|
||||
const requestStates: Record<string,string> = {pending:'Em análise',approved:'Aprovado',rejected:'Devolvido ou recusado',cancelled:'Cancelado'};
|
||||
|
||||
type RequestEntry = {
|
||||
id: string;
|
||||
@@ -67,9 +72,8 @@ export default function RequestProfile({
|
||||
Solicitar perfil de Promotor
|
||||
</h1>
|
||||
<p>
|
||||
A aprovação confirma identidade, representação e comprovativos.
|
||||
Só os tipos aprovados ficam disponíveis; o pedido não ativa o
|
||||
perfil.
|
||||
Indique em nome de quem vai actuar, as modalidades que pretende preparar e os comprovativos do pedido.
|
||||
Pode acompanhar a decisão nesta página. A submissão do pedido não activa o perfil.
|
||||
</p>
|
||||
<form
|
||||
className="max-w-2xl space-y-4"
|
||||
@@ -79,7 +83,7 @@ export default function RequestProfile({
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Representação
|
||||
Em nome de quem vai actuar?
|
||||
<select
|
||||
className={control}
|
||||
value={representation}
|
||||
@@ -92,7 +96,7 @@ export default function RequestProfile({
|
||||
'association',
|
||||
'partner',
|
||||
].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
<option key={v} value={v}>{representations[v]}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -115,9 +119,10 @@ export default function RequestProfile({
|
||||
</label>
|
||||
)}
|
||||
<fieldset>
|
||||
<legend>Tipos pretendidos</legend>
|
||||
<legend>Que oportunidades pretende preparar?</legend>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{types.map((type) => (
|
||||
<label key={type} className="block">
|
||||
<label key={type} className="flex gap-2 rounded border p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(type)}
|
||||
@@ -125,23 +130,12 @@ export default function RequestProfile({
|
||||
setSelected(toggle(selected, type))
|
||||
}
|
||||
/>{' '}
|
||||
{type}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Comprovativos próprios analisados</legend>
|
||||
{documents.map((d) => (
|
||||
<label key={d.id} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={proofs.includes(d.id)}
|
||||
onChange={() => setProofs(toggle(proofs, d.id))}
|
||||
/>{' '}
|
||||
{d.file_name}
|
||||
{modalityLabels[type] ?? 'Outra modalidade'}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<ProfileProofPicker documents={documents} value={proofs} onChange={setProofs} disabled={busy} />
|
||||
{!documents.length && (
|
||||
<p>
|
||||
Sem comprovativos próprios disponíveis. Pode anexar ao
|
||||
@@ -156,7 +150,7 @@ export default function RequestProfile({
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamentação
|
||||
Explique o seu pedido
|
||||
<textarea
|
||||
required
|
||||
minLength={20}
|
||||
@@ -180,7 +174,7 @@ export default function RequestProfile({
|
||||
{requests.map((r) => (
|
||||
<article key={r.id} className="border-b py-3">
|
||||
<p>
|
||||
{r.id} — {r.status}
|
||||
Pedido de {new Date(r.created_at).toLocaleDateString('pt-MZ')} — {requestStates[r.status] ?? 'Estado por consultar'}
|
||||
</p>
|
||||
<p>
|
||||
{r.decision_reason ??
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
import { useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from '@/lib/portal-api';
|
||||
import {
|
||||
assessmentReady,
|
||||
diagnosticReady,
|
||||
forceLabels,
|
||||
forces,
|
||||
newCompetitivenessDraft,
|
||||
readCompetitivenessDraft,
|
||||
} from '@/lib/cluster-competitiveness';
|
||||
import type {
|
||||
Assessment,
|
||||
CompetitivenessDraft,
|
||||
Force,
|
||||
} from '@/lib/cluster-competitiveness';
|
||||
import { button, control } from '../management/shared';
|
||||
|
||||
const labels = {
|
||||
evidence: 'Observações e evidências locais',
|
||||
source: 'Fonte e referência recuperável (documento, página ou endereço)',
|
||||
period: 'Período dos dados e data da consulta',
|
||||
rationale: 'Justificação da pressão atribuída',
|
||||
limitations: 'Limitações, cobertura e pressupostos',
|
||||
opportunity: 'Oportunidade de investimento e fundamento',
|
||||
} as const;
|
||||
|
||||
export type CompetitivenessState = {
|
||||
version: number;
|
||||
draft: CompetitivenessDraft | null;
|
||||
approved: {
|
||||
draft: CompetitivenessDraft;
|
||||
version: number;
|
||||
at: string;
|
||||
} | null;
|
||||
history: { version: number; action: string; at: string; actor: number }[];
|
||||
};
|
||||
const actions: Record<string, string> = {
|
||||
saved: 'Gravação',
|
||||
approved: 'Aprovação pública',
|
||||
withdrawn: 'Retirada da aprovação',
|
||||
restored: 'Recuperação do histórico',
|
||||
};
|
||||
|
||||
export default function Competitiveness({
|
||||
clusterId,
|
||||
sector,
|
||||
initial,
|
||||
}: {
|
||||
clusterId: string;
|
||||
sector: string;
|
||||
initial?: CompetitivenessState | null;
|
||||
}) {
|
||||
const [draft, setDraft] = useState(
|
||||
() => initial?.draft ?? newCompetitivenessDraft(clusterId, sector),
|
||||
);
|
||||
const [server, setServer] = useState<CompetitivenessState>(
|
||||
initial ?? { version: 0, draft: null, approved: null, history: [] },
|
||||
);
|
||||
const [serverPending, setServerPending] =
|
||||
useState<CompetitivenessState | null>(null);
|
||||
const [restoreVersion, setRestoreVersion] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [reason, setReason] = useState('');
|
||||
const [pending, setPending] = useState<CompetitivenessDraft | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const dirty =
|
||||
JSON.stringify(draft) !==
|
||||
JSON.stringify(
|
||||
server.draft ?? newCompetitivenessDraft(clusterId, sector),
|
||||
);
|
||||
const endpoint = `/management/clusters/${clusterId}/competitiveness`;
|
||||
function errorMessage(error: unknown) {
|
||||
if (error instanceof PortalApiError) {
|
||||
if (error.status === 409)
|
||||
return 'Conflito de versão. Os campos actuais foram conservados. Transfira o rascunho e consulte a versão do servidor antes de reconciliar.';
|
||||
if ([401, 403, 419].includes(error.status))
|
||||
return 'Sessão ou permissão indisponível. Os campos foram conservados; transfira o rascunho antes de autenticar-se novamente.';
|
||||
if (error.status === 422)
|
||||
return (
|
||||
Object.values(error.errors).flat().join(' ') ||
|
||||
error.message
|
||||
);
|
||||
}
|
||||
return 'Não foi possível concluir a operação; os campos actuais foram conservados.';
|
||||
}
|
||||
function apply(state: CompetitivenessState) {
|
||||
setServer(state);
|
||||
setDraft(state.draft ?? newCompetitivenessDraft(clusterId, sector));
|
||||
setPending(null);
|
||||
setServerPending(null);
|
||||
setRestoreVersion(null);
|
||||
}
|
||||
async function command(
|
||||
action: string,
|
||||
extra: Record<string, unknown> = {},
|
||||
) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const state = await portalRequest<CompetitivenessState>(
|
||||
`${endpoint}/${action}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
expected_version: server.version,
|
||||
...extra,
|
||||
}),
|
||||
},
|
||||
);
|
||||
apply(state);
|
||||
setMessage(
|
||||
`${actions[action]} concluída no servidor. Versão ${state.version}.`,
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
function change(force: Force, field: keyof Assessment, value: string) {
|
||||
setDraft((previous) => ({
|
||||
...previous,
|
||||
forces: {
|
||||
...previous.forces,
|
||||
[force]: { ...previous.forces[force], [field]: value },
|
||||
},
|
||||
}));
|
||||
}
|
||||
function download() {
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(draft, null, 2)], {
|
||||
type: 'application/json',
|
||||
}),
|
||||
);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `competitividade-${clusterId}.json`;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
setMessage(
|
||||
'Ficheiro preparado para transferência. Conserve-o para recuperar a análise.',
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section
|
||||
className="max-w-3xl space-y-4 rounded border p-4"
|
||||
aria-label="Diagnóstico de competitividade"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Competitividade — cinco forças de Porter
|
||||
</h2>
|
||||
<p>
|
||||
Análise qualitativa por sector e região ligada a este cluster.
|
||||
Descreva as evidências e justifique cada pressão; não existe
|
||||
pontuação automática nem média entre forças.
|
||||
</p>
|
||||
<p>
|
||||
Guarde o rascunho para o recuperar no servidor. A publicação
|
||||
exige aprovação expressa; a classificação representa a
|
||||
apreciação do autor.
|
||||
</p>
|
||||
<p role="status">
|
||||
Versão no servidor: {server.version}.{' '}
|
||||
{dirty
|
||||
? 'Existem alterações por guardar.'
|
||||
: 'Campos correspondem à versão recuperada.'}{' '}
|
||||
{server.approved
|
||||
? `Consulta pública: versão aprovada ${server.approved.version}; novas edições conservam essa versão até outra aprovação.`
|
||||
: 'Sem análise aprovada para consulta pública.'}
|
||||
</p>
|
||||
<fieldset disabled={busy} className="space-y-4">
|
||||
<label className="block">
|
||||
Sector analisado
|
||||
<input
|
||||
className={control}
|
||||
maxLength={200}
|
||||
value={draft.sector}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, sector: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{draft.sector !== sector && (
|
||||
<p>
|
||||
O sector da análise difere do sector actual do cluster (
|
||||
{sector}). Confira o âmbito antes de reutilizar
|
||||
conclusões.
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Região / província / distrito e abrangência
|
||||
<input
|
||||
className={control}
|
||||
maxLength={1000}
|
||||
value={draft.region}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, region: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p role="status">
|
||||
{diagnosticReady(draft)
|
||||
? 'Cinco forças preenchidas para revisão; fontes e conclusões requerem leitura do autor.'
|
||||
: 'Diagnóstico incompleto: indique o âmbito e complete as evidências das cinco forças.'}
|
||||
</p>
|
||||
{forces.map((force) => (
|
||||
<details key={force} className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{forceLabels[force]} ·{' '}
|
||||
{assessmentReady(draft.forces[force])
|
||||
? 'Preenchida para revisão'
|
||||
: 'Indeterminada / incompleta'}
|
||||
</summary>
|
||||
<div className="space-y-3 pt-3">
|
||||
<label className="block">
|
||||
Pressão competitiva
|
||||
<select
|
||||
className={control}
|
||||
value={draft.forces[force].pressure}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
force,
|
||||
'pressure',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Indeterminada</option>
|
||||
<option value="low">Baixa</option>
|
||||
<option value="medium">Média</option>
|
||||
<option value="high">Alta</option>
|
||||
</select>
|
||||
</label>
|
||||
{Object.entries(labels).map(([field, label]) => (
|
||||
<label key={field} className="block">
|
||||
{label}
|
||||
<textarea
|
||||
className={control}
|
||||
rows={3}
|
||||
maxLength={5000}
|
||||
value={
|
||||
draft.forces[force][
|
||||
field as keyof typeof labels
|
||||
]
|
||||
}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
force,
|
||||
field as keyof typeof labels,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
<button type="button" className={button} onClick={download}>
|
||||
Transferir análise / rascunho
|
||||
</button>
|
||||
<label className="block">
|
||||
Recuperar ficheiro deste cluster
|
||||
<input
|
||||
className={control}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
onChange={async (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (!file) return;
|
||||
setPending(null);
|
||||
try {
|
||||
if (file.size > 250_000)
|
||||
throw Error(
|
||||
'O ficheiro excede o limite de 250 KB.',
|
||||
);
|
||||
setPending(
|
||||
readCompetitivenessDraft(
|
||||
await file.text(),
|
||||
clusterId,
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
'Ficheiro lido. Confira o âmbito e confirme a substituição dos campos actuais.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível ler o ficheiro.',
|
||||
);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{pending && (
|
||||
<div className="space-y-2 rounded border p-3">
|
||||
<p>
|
||||
Recuperar análise de{' '}
|
||||
{pending.sector || 'sector não indicado'} em{' '}
|
||||
{pending.region || 'região não indicada'}? Os campos
|
||||
actuais serão substituídos. Transfira primeiro o
|
||||
rascunho actual se o quiser conservar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setDraft(pending);
|
||||
setPending(null);
|
||||
setMessage('Análise recuperada para edição.');
|
||||
}}
|
||||
>
|
||||
Confirmar recuperação
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
setPending(null);
|
||||
setMessage(
|
||||
'Recuperação cancelada; campos actuais preservados.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!dirty}
|
||||
onClick={() => command('saved', { draft })}
|
||||
>
|
||||
Guardar rascunho no servidor
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setServerPending(
|
||||
await portalRequest<CompetitivenessState>(
|
||||
endpoint,
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
'Versão do servidor lida. Confirme antes de substituir os campos.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Consultar versão actual do servidor
|
||||
</button>
|
||||
</div>
|
||||
{serverPending && (
|
||||
<div className="rounded border p-3">
|
||||
<p>
|
||||
Versão {serverPending.version}:{' '}
|
||||
{serverPending.draft?.sector ||
|
||||
'Sector não indicado'}{' '}
|
||||
/{' '}
|
||||
{serverPending.draft?.region ||
|
||||
'Região não indicada'}
|
||||
. Recuperar substitui os campos actuais. Transfira
|
||||
primeiro alterações que queira conservar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
apply(serverPending);
|
||||
setMessage(
|
||||
'Versão actual recuperada do servidor.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
Confirmar recuperação do servidor
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setServerPending(null)}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<details className="rounded border p-3">
|
||||
<summary>
|
||||
Histórico no servidor (últimas 50 versões)
|
||||
</summary>
|
||||
{!server.history.length && (
|
||||
<p>Ainda não existem gravações.</p>
|
||||
)}
|
||||
{server.history.map((entry) => (
|
||||
<p key={entry.version}>
|
||||
Versão {entry.version} ·{' '}
|
||||
{actions[entry.action] ?? entry.action} · {entry.at}{' '}
|
||||
· Utilizador {entry.actor}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setRestoreVersion(entry.version)}
|
||||
>
|
||||
Recuperar como rascunho
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
{restoreVersion !== null && (
|
||||
<div>
|
||||
<p>
|
||||
Recuperar a versão {restoreVersion} cria uma
|
||||
nova versão no servidor e substitui os campos
|
||||
actuais. A versão pública aprovada mantém-se.
|
||||
Transfira primeiro alterações por guardar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
command('restored', {
|
||||
revision: restoreVersion,
|
||||
})
|
||||
}
|
||||
>
|
||||
Confirmar recuperação do histórico
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setRestoreVersion(null)}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</details>
|
||||
<details className="rounded border p-3">
|
||||
<summary>Aprovação para consulta pública</summary>
|
||||
<p>
|
||||
Aprovar torna a versão guardada consultável na ficha
|
||||
pública deste cluster, quando essa ficha estiver
|
||||
publicada. Guardar um rascunho não o publica. A
|
||||
evidência de aprovação e as identidades do histórico
|
||||
ficam na gestão.
|
||||
</p>
|
||||
<label className="block">
|
||||
Evidência / motivo da aprovação ou retirada
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={3000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
dirty ||
|
||||
!diagnosticReady(draft) ||
|
||||
server.version === 0 ||
|
||||
reason.trim().length < 10
|
||||
}
|
||||
onClick={() => command('approved', { reason })}
|
||||
>
|
||||
Aprovar versão guardada para consulta pública
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
dirty ||
|
||||
!server.approved ||
|
||||
reason.trim().length < 10
|
||||
}
|
||||
onClick={() => command('withdrawn', { reason })}
|
||||
>
|
||||
Retirar aprovação pública
|
||||
</button>
|
||||
{dirty && (
|
||||
<p>
|
||||
Guarde primeiro as alterações ou recupere a versão
|
||||
pretendida antes de decidir a aprovação.
|
||||
</p>
|
||||
)}
|
||||
</details>
|
||||
</fieldset>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { Management, Field, button, control } from '../management/shared';
|
||||
import { titles, statuses, stages, roles } from './types';
|
||||
import type { Structure, StructureRecord, Chain } from './types';
|
||||
import ValueNetwork from './value-network';
|
||||
import Competitiveness from './competitiveness';
|
||||
import type { CompetitivenessState } from './competitiveness';
|
||||
import type { ChainLink, Gap } from './value-network';
|
||||
|
||||
function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
|
||||
@@ -75,6 +77,7 @@ export default function Editor({
|
||||
memberships,
|
||||
chainLinks,
|
||||
gaps,
|
||||
competitiveness,
|
||||
}: {
|
||||
structure: Structure;
|
||||
record: StructureRecord | null;
|
||||
@@ -83,6 +86,7 @@ export default function Editor({
|
||||
chains: Chain[];
|
||||
chainLinks: ChainLink[];
|
||||
gaps: Gap[];
|
||||
competitiveness?: CompetitivenessState | null;
|
||||
memberships: {
|
||||
id: string;
|
||||
project_id: string;
|
||||
@@ -298,6 +302,12 @@ export default function Editor({
|
||||
</form>
|
||||
{isCluster && record && (
|
||||
<>
|
||||
<Competitiveness
|
||||
key={record.id}
|
||||
clusterId={record.id}
|
||||
sector={record.sector ?? ''}
|
||||
initial={competitiveness}
|
||||
/>
|
||||
<section className="max-w-3xl space-y-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Projectos associados
|
||||
|
||||
@@ -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
|
||||
|
||||
use App\Http\Controllers\Api\TranslationApiController;
|
||||
use App\Http\Controllers\Api\V1\HomeController;
|
||||
use App\Http\Controllers\Api\V1\InterestRequestController;
|
||||
use App\Http\Controllers\Api\V1\LegislationSourceController;
|
||||
@@ -17,6 +18,9 @@ use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
||||
use App\Services\SimulationPublishedFiscal;
|
||||
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::get('/catalogs/{catalog}', [ReferenceCatalogController::class, 'index'])
|
||||
->whereIn('catalog', ['authorities', 'jurisdictions', 'economic-activities', 'countries']);
|
||||
|
||||
@@ -50,6 +50,11 @@ use Laravel\Fortify\Features;
|
||||
// Route::inertia('/', 'welcome')->name('home');
|
||||
Route::get('/', [PortalServicesController::class, 'home'])->name('home');
|
||||
Route::inertia('/contextos-de-investimento', 'portal/investment-contexts')->name('portal.investment-contexts');
|
||||
Route::get('/formularios/fiscais', function (\Illuminate\Http\Request $request) {
|
||||
$input = $request->validate(['imposto' => ['nullable', 'in:iva,irpc']]);
|
||||
|
||||
return Inertia::render('portal/fiscal-forms', ['initialTax' => $input['imposto'] ?? 'iva']);
|
||||
})->name('portal.fiscal-forms');
|
||||
Route::inertia('/politica-de-privacidade', 'portal/privacy-policy')->name('legal.privacy');
|
||||
Route::inertia('/termos-de-uso', 'portal/terms-of-use')->name('legal.terms');
|
||||
foreach (['sectores' => 'sectors', 'como-investir' => 'procedures', 'legislacao' => 'legislation', 'documentos' => 'documents',
|
||||
@@ -93,6 +98,7 @@ Route::get('/artigos/{id}', [\App\Http\Controllers\EditorialArticleController::c
|
||||
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}/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/{slug}', [InvestmentDiscoveryController::class, 'detail'])->name('portal.opportunity');
|
||||
Route::get('/negocios', [PublicBusinessOpportunityController::class, 'index'])->name('business-marketplace.index');
|
||||
@@ -249,6 +255,8 @@ Route::middleware(['auth', 'verified', \App\Http\Middleware\EnsureScopedPortalAd
|
||||
Route::get('portfolio/{id}', [InvestmentPortfolioController::class, 'show'])->whereUuid('id')->name('portfolio.show');
|
||||
Route::put('portfolio/{dossier}', [InvestmentPortfolioController::class, 'save'])->name('portfolio.save');
|
||||
Route::post('portfolio/{dossier}/publish', [InvestmentPortfolioController::class, 'publish'])->name('portfolio.publish');
|
||||
Route::get('clusters/{cluster}/competitiveness', [\App\Http\Controllers\ClusterCompetitivenessController::class, 'show'])->name('clusters.competitiveness.show');
|
||||
Route::post('clusters/{cluster}/competitiveness/{action}', [\App\Http\Controllers\ClusterCompetitivenessController::class, 'change'])->whereIn('action', ['saved', 'approved', 'withdrawn', 'restored'])->name('clusters.competitiveness.change');
|
||||
Route::post('clusters/{cluster}/chain-links', [ClusterValueChainController::class, 'link'])->name('clusters.chain-links.store');
|
||||
Route::delete('clusters/{cluster}/chain-links/{link}', [ClusterValueChainController::class, 'removeLink'])->name('clusters.chain-links.delete');
|
||||
Route::post('clusters/{cluster}/gaps', [ClusterValueChainController::class, 'gap'])->name('clusters.gaps.store');
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class CatalogueProvinceCoverageTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
private const PROVINCE = 'bfde2651-2b46-5d9c-a500-733fa55a8c5c';
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();\Tests\Support\ProactiveInvestmentFixture::guard();$this->withoutVite();
|
||||
}
|
||||
|
||||
public function test_accepted_maputo_source_is_found_in_both_approved_provinces_without_becoming_a_district_site(): void
|
||||
{
|
||||
$c=app(InvestmentCatalogue::class);
|
||||
$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([self::PROVINCE,'4aa31470-997e-5c63-8fe0-ff2f62586f56']as$province){
|
||||
foreach(['all','context']as$basis){
|
||||
$ids=$c->query(['sector'=>'agronegocio','province_id'=>$province,'territory_basis'=>$basis])->pluck('id')->all();
|
||||
foreach($expected as$id)$this->assertContains($id,$ids);
|
||||
}
|
||||
}
|
||||
foreach($expected as$id)$this->assertNotContains($id,$c->query(['province_id'=>self::PROVINCE,'territory_basis'=>'direct'])->pluck('id')->all());
|
||||
$district=app(InvestmentGeography::class)->publicReferences()->where('parent_id',self::PROVINCE)->where('location_type','district')->first();
|
||||
$this->assertNotNull($district);
|
||||
foreach($expected as$id)$this->assertNotContains($id,$c->query(['province_id'=>self::PROVINCE,'district_id'=>$district->id])->pluck('id')->all());
|
||||
$label=$c->presentLocation(Opportunity::findOrFail($expected[0]))->territorial_summary;
|
||||
$this->assertStringContainsString('contexto provincial do corredor',$label);
|
||||
$this->assertStringContainsString('distrito e posto administrativo não indicados',$label);
|
||||
foreach($expected as$id)$this->assertContains($id,$c->query(['geo_location_id'=>self::PROVINCE])->pluck('id')->all());
|
||||
$this->assertSame([],array_intersect($expected,$c->query(['province_id'=>'059b02ca-7095-577a-8705-4d4c46896747'])->pluck('id')->all()));
|
||||
}
|
||||
|
||||
public function test_province_includes_its_descendants_with_full_location_and_excludes_private_and_other_provinces(): void
|
||||
{
|
||||
$geo=app(InvestmentGeography::class);$c=app(InvestmentCatalogue::class);
|
||||
$district=$geo->publicReferences()->where('parent_id',self::PROVINCE)->where('location_type','district')->first();
|
||||
$post=$geo->publicReferences()->where('parent_id',$district->id)->where('location_type','admin_post')->first();
|
||||
$this->assertNotNull($post);
|
||||
$make=fn($territory,$status='published')=>Opportunity::create(['sector_id'=>1,'reference'=>'SYNTHETIC-QA-'.Str::uuid(),'slug'=>'synthetic-'.Str::uuid(),'title'=>'SYNTHETIC QA province coverage','status'=>$status,'published_at'=>now()->subMinute(),'primary_territory_id'=>$territory,'geography_scope'=>'specific']);
|
||||
$record=$make($post->id);$private=$make($post->id,'draft');$other=$make('059b02ca-7095-577a-8705-4d4c46896747');
|
||||
$ids=$c->query(['province_id'=>self::PROVINCE,'sector'=>'agronegocio'])->pluck('id')->all();
|
||||
$this->assertContains($record->id,$ids);$this->assertNotContains($private->id,$ids);$this->assertNotContains($other->id,$ids);
|
||||
$label=$c->presentLocation($record)->territorial_summary;
|
||||
foreach(['Maputo Província',$district->name,$post->name]as$name)$this->assertStringContainsString($name,$label);
|
||||
}
|
||||
|
||||
public function test_actual_territory_and_publication_decisions_override_old_corridor_context(): void
|
||||
{
|
||||
$c=app(InvestmentCatalogue::class);
|
||||
$record=Opportunity::published()->where('workflow_context->corridor_agribusiness->corridor','Corredor de Maputo')->firstOrFail();
|
||||
$record->primary_territory_id='059b02ca-7095-577a-8705-4d4c46896747';$record->save();
|
||||
$this->assertNotContains($record->id,$c->query(['province_id'=>self::PROVINCE])->pluck('id')->all());
|
||||
$record->primary_territory_id=null;$record->status='draft';$record->save();
|
||||
$this->assertNotContains($record->id,$c->query(['province_id'=>self::PROVINCE])->pluck('id')->all());
|
||||
}
|
||||
|
||||
public function test_public_search_and_corridor_view_agree_without_inventing_map_coordinates(): void
|
||||
{
|
||||
$filters=['province_id'=>self::PROVINCE,'sector'=>'agronegocio'];
|
||||
$response=$this->getJson('/api/v1/investment/search?'.http_build_query($filters))->assertOk()->assertJsonPath('total',5);
|
||||
foreach($response->json('data')as$row)$this->assertStringContainsString('contexto provincial do corredor',$row['territorial_summary']);
|
||||
$groups=app(\App\Services\OpportunityCorridorExplorer::class)->groups($filters);
|
||||
$this->assertCount(1,$groups);$this->assertSame(5,$groups[0]['count']);
|
||||
foreach($groups[0]['opportunities']as$row){$this->assertContains('Maputo Província',$row['provinces']);$this->assertNull($row['district']);}
|
||||
$map=app(InvestmentCatalogue::class)->map($filters);
|
||||
$this->assertCount(5,$map['unlocated']);$this->assertSame([],$map['features']);
|
||||
}
|
||||
|
||||
public function test_all_approved_corridors_are_found_in_their_provinces_and_not_in_unrelated_provinces(): void
|
||||
{
|
||||
$catalogue=app(InvestmentCatalogue::class);
|
||||
$provinces=app(InvestmentGeography::class)->publicReferences()->where('location_type','province')->get();
|
||||
$this->assertCount(11,$provinces);
|
||||
foreach(config('investment_corridors')as$entry){
|
||||
$records=Opportunity::published()->whereNull('primary_territory_id')
|
||||
->where('workflow_context->corridor_agribusiness->source_sha256',CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||
->where('workflow_context->corridor_agribusiness->corridor',$entry['name'])->pluck('id')->all();
|
||||
$this->assertNotEmpty($records,$entry['name']);
|
||||
foreach($provinces as$province){
|
||||
$ids=$catalogue->query(['province_id'=>$province->id,'sector'=>'agronegocio'])->pluck('id')->all();
|
||||
foreach($records as$id){
|
||||
if(in_array($province->source_code,$entry['provinces'],true))$this->assertContains($id,$ids);
|
||||
else $this->assertNotContains($id,$ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_descendant_coverage_is_national_and_shared_by_sectors_and_location_entry_points(): void
|
||||
{
|
||||
$geo=app(InvestmentGeography::class);$catalogue=app(InvestmentCatalogue::class);
|
||||
$provinces=$geo->publicReferences()->where('location_type','province')->get();
|
||||
$sectors=DB::table('sectors')->where('is_active',true)->whereNotNull('published_at')->whereNull('deleted_at')->orderBy('id')->limit(2)->get();
|
||||
$this->assertCount(2,$sectors);
|
||||
foreach($provinces as$province){
|
||||
$district=$geo->publicReferences()->where('parent_id',$province->id)->where('location_type','district')->first();
|
||||
$this->assertNotNull($district,$province->name);
|
||||
$post=$geo->publicReferences()->where('parent_id',$district->id)->where('location_type','admin_post')->first();
|
||||
$leaf=$post?:$district;
|
||||
foreach($sectors as$sector){
|
||||
$record=Opportunity::create(['sector_id'=>$sector->id,'reference'=>'SYNTHETIC-QA-'.Str::uuid(),'slug'=>'synthetic-'.Str::uuid(),
|
||||
'title'=>'SYNTHETIC QA national coverage','status'=>'published','published_at'=>now()->subMinute(),'primary_territory_id'=>$leaf->id,'geography_scope'=>'specific']);
|
||||
foreach([['province_id'=>$province->id],['geo_location_id'=>$province->id],['province_id'=>$province->id,'district_id'=>$district->id]]as$entry){
|
||||
$this->assertContains($record->id,$catalogue->query([...$entry,'sector'=>$sector->slug])->pluck('id')->all());
|
||||
}
|
||||
$other=$sectors->firstWhere('id','!=',$sector->id);
|
||||
$this->assertNotContains($record->id,$catalogue->query(['province_id'=>$province->id,'sector'=>$other->slug])->pluck('id')->all());
|
||||
$label=$catalogue->presentLocation($record)->territorial_summary;
|
||||
$this->assertStringContainsString($province->name,$label);$this->assertStringContainsString($district->name,$label);
|
||||
if($post)$this->assertStringContainsString($post->name,$label);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\User;
|
||||
use App\Services\ClusterCompetitiveness;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ClusterCompetitivenessTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
}
|
||||
|
||||
private function manager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email], 'portal.profile_access_enabled' => false]);
|
||||
$this->actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function cluster(): EconomicCluster
|
||||
{
|
||||
return EconomicCluster::create(['code' => 'COMP-'.bin2hex(random_bytes(6)), 'name' => 'Cluster de teste de persistência', 'sector' => 'Energia', 'status' => 'planned']);
|
||||
}
|
||||
|
||||
private function draft(EconomicCluster $cluster): array
|
||||
{
|
||||
$draft = ['version' => 1, 'clusterId' => $cluster->id, 'sector' => 'Energia', 'region' => 'Distrito de demonstração', 'forces' => []];
|
||||
foreach (ClusterCompetitiveness::FORCES as $force) {
|
||||
$draft['forces'][$force] = ['pressure' => 'medium', 'evidence' => 'Observação de teste, não publicável como facto real',
|
||||
'source' => 'Fonte de demonstração p. 2', 'period' => '2025', 'rationale' => 'Apreciação de teste',
|
||||
'limitations' => 'Dados sintéticos', 'opportunity' => 'Hipótese de demonstração'];
|
||||
}
|
||||
|
||||
return $draft;
|
||||
}
|
||||
|
||||
private function url(EconomicCluster $cluster): string
|
||||
{
|
||||
return '/management/clusters/'.$cluster->id.'/competitiveness';
|
||||
}
|
||||
|
||||
public function test_save_recovers_from_database_across_requests_and_records_encrypted_history(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])
|
||||
->assertOk()->assertJsonPath('version', 1)->assertJsonPath('draft', $draft)->assertJsonPath('approved', null);
|
||||
$this->getJson($this->url($cluster))->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertJsonPath('draft', $draft)->assertJsonPath('history.0.actor', $actor->id)->assertJsonPath('history.0.action', 'saved');
|
||||
$this->get('/management/clusters/'.$cluster->id.'/edit')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->component('structures/editor')->where('competitiveness.version', 1)->where('competitiveness.draft.region', $draft['region']));
|
||||
$event = DB::table('audit_events')->where('source_system', 'cluster-competitiveness')->where('entity_id', $cluster->id)->first();
|
||||
$this->assertStringNotContainsString($draft['forces']['rivalry']['evidence'], $event->after_data);
|
||||
$this->assertSame('restricted', $event->data_classification);
|
||||
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($cluster->id));
|
||||
}
|
||||
|
||||
public function test_validation_conflict_and_server_error_do_not_overwrite_the_saved_version(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
|
||||
$changed = $draft;
|
||||
$changed['region'] = 'Outra região';
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $changed])->assertConflict();
|
||||
$changed['forces']['buyers']['pressure'] = 'zero';
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $changed])->assertUnprocessable();
|
||||
$changed = $draft;
|
||||
$changed['clusterId'] = $this->cluster()->id;
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $changed])->assertUnprocessable();
|
||||
$this->getJson($this->url($cluster))->assertJsonPath('version', 1)->assertJsonPath('draft', $draft)->assertJsonCount(1, 'history');
|
||||
}
|
||||
|
||||
public function test_approval_pins_content_and_later_drafts_and_restoration_do_not_publish(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$url = $this->url($cluster);
|
||||
$this->postJson($url.'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
|
||||
$this->postJson($url.'/approved', ['expected_version' => 1, 'reason' => 'Aprovação sintética em QA'])->assertOk()->assertJsonPath('version', 2);
|
||||
$changed = $draft;
|
||||
$changed['region'] = 'Rascunho privado posterior';
|
||||
$this->postJson($url.'/saved', ['expected_version' => 2, 'draft' => $changed])->assertOk();
|
||||
$public = app(ClusterCompetitiveness::class)->publicData($cluster->id);
|
||||
$this->assertSame($draft, $public['draft']);
|
||||
$this->assertSame(['draft', 'version', 'at'], array_keys($public));
|
||||
$this->postJson($url.'/restored', ['expected_version' => 3, 'revision' => 1])->assertOk()
|
||||
->assertJsonPath('version', 4)->assertJsonPath('draft', $draft)->assertJsonPath('approved.version', 2);
|
||||
$this->assertSame($public, app(ClusterCompetitiveness::class)->publicData($cluster->id));
|
||||
$this->postJson($url.'/withdrawn', ['expected_version' => 4, 'reason' => 'Retirada sintética em QA'])->assertOk()->assertJsonCount(5, 'history');
|
||||
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($cluster->id));
|
||||
$this->getJson($url)->assertJsonPath('draft', $draft);
|
||||
}
|
||||
|
||||
public function test_incomplete_drafts_are_saved_but_not_approved_and_unknown_revisions_do_not_write(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$draft['forces']['buyers']['source'] = '';
|
||||
$draft['forces']['entrants']['pressure'] = '';
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
|
||||
$this->postJson($this->url($cluster).'/approved', ['expected_version' => 1, 'reason' => 'Pedido de aprovação QA'])->assertUnprocessable();
|
||||
$this->postJson($this->url($cluster).'/restored', ['expected_version' => 1, 'revision' => 99])->assertNotFound();
|
||||
$this->getJson($this->url($cluster))->assertJsonPath('version', 1)->assertJsonPath('draft.forces.buyers.source', '');
|
||||
}
|
||||
|
||||
public function test_saved_data_keeps_the_portable_file_contract_and_rejects_missing_forces(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$draft['version'] = '1';
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])
|
||||
->assertOk()->assertJsonPath('draft.version', 1);
|
||||
unset($draft['forces']['suppliers']);
|
||||
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $draft])->assertUnprocessable();
|
||||
$this->getJson($this->url($cluster))->assertJsonPath('version', 1);
|
||||
}
|
||||
|
||||
public function test_anonymous_and_unauthorised_users_cannot_read_history_or_mutate(): void
|
||||
{
|
||||
$cluster = $this->cluster();
|
||||
$url = $this->url($cluster);
|
||||
$this->getJson($url)->assertUnauthorized();
|
||||
$this->postJson($url.'/saved', [])->assertUnauthorized();
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->getJson($url)->assertForbidden();
|
||||
foreach (['saved', 'approved', 'withdrawn', 'restored'] as $action) {
|
||||
$this->postJson($url.'/'.$action, [])->assertForbidden();
|
||||
}
|
||||
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'cluster-competitiveness')->where('entity_id', $cluster->id)->count());
|
||||
}
|
||||
|
||||
public function test_public_dossier_returns_only_the_approved_projection_and_unpublished_dossiers_remain_hidden(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$cluster = $this->cluster();
|
||||
$draft = $this->draft($cluster);
|
||||
$dossier = InvestmentDossier::create(['cluster_id' => $cluster->id, 'title' => 'Ficha sintética QA', 'source' => 'Fonte sintética QA',
|
||||
'content' => ['sector' => 'Energia'], 'publication_status' => 'published', 'approval_basis' => 'document_owner',
|
||||
'approval_evidence' => 'Aprovação sintética só na base QA', 'published_at' => now()]);
|
||||
$service = app(ClusterCompetitiveness::class);
|
||||
$service->change($cluster, $actor->id, 0, 'saved', ['draft' => $draft]);
|
||||
$this->app['auth']->forgetGuards();
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page->where('competitiveness', null));
|
||||
$service->change($cluster, $actor->id, 1, 'approved', ['reason' => 'Aprovação privada de teste']);
|
||||
$draft['region'] = 'CONTEÚDO PRIVADO NÃO APROVADO';
|
||||
$service->change($cluster, $actor->id, 2, 'saved', ['draft' => $draft]);
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('competitiveness.version', 2)->where('competitiveness.draft.region', 'Distrito de demonstração')
|
||||
->missing('competitiveness.actor')->missing('competitiveness.evidence')->missing('competitiveness.history'));
|
||||
$dossier->update(['publication_status' => 'draft']);
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
$dossier->update(['publication_status' => 'published']);
|
||||
$service->change($cluster, $actor->id, 3, 'withdrawn', ['reason' => 'Retirada privada de teste']);
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page->where('competitiveness', null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class FiscalFormEntryTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
\Tests\Support\ProactiveInvestmentFixture::guard();
|
||||
$this->withoutVite();
|
||||
}
|
||||
|
||||
public function test_both_fiscal_forms_are_public_and_do_not_redirect_to_legal_documents(): void
|
||||
{
|
||||
config(['portal.homologation_only' => false]);
|
||||
foreach (['iva', 'irpc'] as $tax) {
|
||||
$this->get('/formularios/fiscais?imposto='.$tax)
|
||||
->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page->component('portal/fiscal-forms')->where('initialTax', $tax));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,57 @@
|
||||
<?php
|
||||
namespace Tests\Feature;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZones;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestorUsabilityScopeTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
protected function setUp():void{parent::setUp();\Tests\Support\ProactiveInvestmentFixture::guard();$this->withoutVite();}
|
||||
|
||||
public function test_public_sector_is_consultable_by_guest_and_accounts_without_promoter_grants():void
|
||||
{
|
||||
config(['portal.homologation_only'=>false,'portal.legacy_content_enabled'=>false,'portal.legacy_content_qa_enabled'=>false]);
|
||||
$this->get('/sectores/turismo')->assertOk();
|
||||
$actor=User::factory()->create();
|
||||
$this->actingAs($actor)->get('/sectores/turismo')->assertOk();
|
||||
$this->assertSame(0,DB::table('portal_role_assignments')->where('user_id',$actor->id)->count());
|
||||
config(['portal.profile_access_enabled'=>true]);
|
||||
$entry=app(\App\Services\SectorInvestment::class)->publicView(\App\Models\Sector::where('slug','turismo')->firstOrFail());
|
||||
$this->assertSame('/perfil/promotor',$entry['register_href']);
|
||||
$this->assertSame('Pedir acesso para cadastrar oportunidades',$entry['register_label']);
|
||||
}
|
||||
|
||||
public function test_zones_all_equals_visible_set_and_province_and_district_never_fall_back_to_all():void
|
||||
{
|
||||
$zones=app(InvestmentZones::class);$geo=app(InvestmentGeography::class);
|
||||
$province='059b02ca-7095-577a-8705-4d4c46896747';
|
||||
$district=$geo->publicReferences()->where('parent_id',$province)->where('location_type','district')->first();
|
||||
$template=$zones->visible()->firstOrFail();
|
||||
$make=function($territory,$published=true)use($template){$zone=$template->replicate();$zone->id=(string)Str::uuid();$zone->code='SYNTHETIC-'.Str::random(12);$zone->name='SYNTHETIC QA zone scope';$zone->primary_territory_id=$territory;$zone->publication_status=$published?'published':'draft';$zone->save();return$zone;};
|
||||
$inside=$make($district->id);$outside=$make('9e42dac8-fd9b-523f-bf59-71a7d3aa0fb8');$private=$make($district->id,false);
|
||||
$all=$zones->search([])->orderBy('id')->pluck('id')->all();
|
||||
$this->assertSame($zones->visible()->orderBy('id')->pluck('id')->all(),$all);
|
||||
foreach([['province_id'=>$province],['province_id'=>$province,'district_id'=>$district->id]]as$selection){
|
||||
$ids=$zones->search($selection)->pluck('id')->all();
|
||||
$this->assertContains($inside->id,$ids);$this->assertNotContains($outside->id,$ids);$this->assertNotContains($private->id,$ids);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_documented_legal_scope_covers_child_area_but_influence_does_not_become_an_installation():void
|
||||
{
|
||||
$zones=app(InvestmentZones::class);$geo=app(InvestmentGeography::class);$province='059b02ca-7095-577a-8705-4d4c46896747';
|
||||
$district=$geo->publicReferences()->where('parent_id',$province)->where('location_type','district')->first();
|
||||
$editor=User::factory()->create();$reviewer=User::factory()->create();$template=$zones->visible()->firstOrFail();$ids=[];
|
||||
foreach(['legal_scope','influence']as$scope){
|
||||
$zone=$template->replicate();$zone->id=(string)Str::uuid();$zone->code='SYNTHETIC-'.Str::random(12);$zone->name='SYNTHETIC QA legal coverage';$zone->primary_territory_id='9e42dac8-fd9b-523f-bf59-71a7d3aa0fb8';$zone->save();$ids[$scope]=$zone->id;
|
||||
DB::table('investment_zone_locations')->insert(['id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'geo_location_id'=>$scope==='legal_scope'?$province:$district->id,'scope_type'=>$scope,'source_reference'=>'SYNTHETIC isolated QA scope fixture','validation_status'=>'validated','editor_id'=>$editor->id,'reviewer_id'=>$reviewer->id,'valid_from'=>now()->subDay(),'version_no'=>1,'created_at'=>now(),'updated_at'=>now()]);
|
||||
}
|
||||
$matches=$zones->search(['province_id'=>$province,'district_id'=>$district->id])->pluck('id')->all();
|
||||
$this->assertContains($ids['legal_scope'],$matches);$this->assertNotContains($ids['influence'],$matches);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user