Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e7bd4fde3 | ||
|
|
1263b4f6b7 | ||
|
|
2f1ef2fdfc | ||
|
|
61b4d9f1f9 | ||
|
|
1d52c3d8f4 | ||
|
|
0f79d0d54c | ||
|
|
d325b72fad | ||
|
|
8854b2928c | ||
|
|
f53a308327 | ||
|
|
723ce2a0a4 | ||
|
|
eab09dd61e | ||
|
|
71f2fcbb84 | ||
|
|
f6c1b60612 |
@@ -3,34 +3,107 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\EditorialReading;
|
||||
use App\Services\FederatedSearch;
|
||||
use App\Services\FundingInstitutionDetails;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\SearchTerms;
|
||||
use App\Services\SectorOrganization;
|
||||
use App\Services\SectorResourceReferences;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
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'] ?? '');
|
||||
$input = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'], 'category' => ['nullable', 'in:all,physical,financial']]);
|
||||
$original = trim($input['q'] ?? '');
|
||||
$intent = $search->requestIntent($original);
|
||||
if (isset($input['category']) && ($intent === null || $intent['type'] === 'products')) {
|
||||
$intent = ['type' => 'products', 'label' => 'Produtos e localização', 'kind' => null,
|
||||
'filter' => $intent['filter'] ?? $original,
|
||||
'category' => match ($input['category']) {
|
||||
'physical' => 'Produtos e localizações', 'financial' => 'Produtos financeiros', default => null,
|
||||
}];
|
||||
}
|
||||
$term = $intent['filter'] ?? $original;
|
||||
$tokens = $search->tokens($term);
|
||||
$results = ['data' => [], 'total' => 0, 'current_page' => 1, 'last_page' => 1, 'per_page' => 5, 'unavailable' => []];
|
||||
if ($tokens !== []) {
|
||||
if ($tokens !== [] || $intent !== null) {
|
||||
$factories = [
|
||||
'Produtos e localizações' => function () use ($search, $tokens, $term) {
|
||||
try {
|
||||
return $this->productReferences($search, $tokens, $term);
|
||||
} catch (\RuntimeException $exception) {
|
||||
throw new HttpException(503, 'Referências de produtos temporariamente indisponíveis.', $exception);
|
||||
}
|
||||
},
|
||||
'Produtos financeiros' => function () use ($search, $tokens, $term) {
|
||||
$service = app(FundingProgrammes::class);
|
||||
if (! $service->installed()) {
|
||||
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
|
||||
}
|
||||
$query = $service->catalogueQuery([])->select('p.id', 'v.payload')->selectRaw("v.payload->>'title' AS title");
|
||||
foreach ($tokens as $token) {
|
||||
$query->where(function ($match) use ($search, $token) {
|
||||
$search->orFields($match, ["(v.payload->>'title')",
|
||||
"(SELECT string_agg(product->>'title', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product)",
|
||||
"(SELECT string_agg(place->>'location_text', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) place)",
|
||||
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.locations[*].territory_path[*]') node)",
|
||||
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.products[*].territory_paths[*][*]') node)"], $token);
|
||||
foreach (FundingInstitutionDetails::NEEDS as $code => $label) {
|
||||
$text = in_array($code, ['investment', 'working_capital'], true) ? 'Financiamento '.$label : $label;
|
||||
if ($search->matches($text, [$token])) {
|
||||
$match->orWhereJsonContains('v.payload->institution_services', $code)->orWhereJsonContains('v.payload->funding_needs', $code)
|
||||
->orWhereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product WHERE product->'needs' @> ?::jsonb)", [json_encode([$code], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
foreach (FundingInstitutionDetails::NATURES as $code => $label) {
|
||||
if ($search->matches($label, [$token])) {
|
||||
$match->orWhere('v.payload->institution_nature', $code);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $this->source($query, $search, $term, $tokens, "(v.payload->>'title')", 'p.id', function ($row) {
|
||||
$p = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
$products = array_values(array_unique(array_filter(array_column($p['products'] ?? [], 'title'))));
|
||||
$services = array_values(array_intersect_key(FundingInstitutionDetails::NEEDS, array_flip($p['institution_services'] ?? [])));
|
||||
$places = [];
|
||||
foreach ($p['locations'] ?? [] as $location) {
|
||||
if (! empty($location['location_text'])) {
|
||||
$places[] = $location['location_text'];
|
||||
}
|
||||
foreach ($location['territory_path'] ?? [] as $node) {
|
||||
if ($node['type'] !== 'country') {
|
||||
$places[] = $node['name'];
|
||||
}
|
||||
}
|
||||
}
|
||||
$national = array_any($p['products'] ?? [], fn ($product) => ($product['coverage'] ?? '') === 'national');
|
||||
|
||||
return ['title' => $row->title, 'description' => implode(' · ', $products ?: $services) ?: 'Instituição financeira.',
|
||||
'location' => $places === [] ? null : 'Presença física: '.implode(' · ', array_unique($places)),
|
||||
'coverage' => $national ? 'Existe produto com cobertura nacional indicada; consulte as condições.' : 'Cobertura financeira: consultar cada produto.',
|
||||
'url' => '/fundos/'.$row->id];
|
||||
});
|
||||
},
|
||||
'Páginas e serviços' => function () use ($search, $tokens, $term) {
|
||||
$pages = array_values(array_filter($this->pages(), fn ($page) => $search->matches(implode(' ', $page), $tokens)
|
||||
&& $search->score($page['title'], $term, $tokens) > 0));
|
||||
$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']));
|
||||
|
||||
@@ -64,9 +137,15 @@ class GlobalSearchController extends Controller
|
||||
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) {
|
||||
'Carteira: projectos, clusters e corredores' => function () use ($search, $tokens, $term, $intent) {
|
||||
$query = InvestmentPortfolioController::visible();
|
||||
$search->constrain($query, ['investment_dossiers.title', 'investment_dossiers.content'], $tokens);
|
||||
if ($intent !== null && $intent['kind'] !== null) {
|
||||
[$column, $table] = ['corridor' => ['corridor_id', 'development_corridors'], 'cluster' => ['cluster_id', 'economic_clusters'], 'project' => ['project_id', 'projects']][$intent['kind']];
|
||||
$query->whereNotNull($column)->whereExists(fn ($entity) => $entity->selectRaw('1')->from($table)
|
||||
->whereColumn($table.'.id', 'investment_dossiers.'.$column)->whereNull($table.'.deleted_at'));
|
||||
// The existing unique entity key already prevents duplicate dossiers.
|
||||
}
|
||||
|
||||
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]);
|
||||
@@ -127,13 +206,75 @@ class GlobalSearchController extends Controller
|
||||
fn ($r) => ['title' => $r->title, 'description' => implode(' · ', array_filter([$r->sector, $r->province])), 'url' => '/parcerias/'.$r->id]);
|
||||
},
|
||||
];
|
||||
if ($intent !== null) {
|
||||
$categories = $intent['category'] === null ? ['Produtos e localizações', 'Produtos financeiros'] : [$intent['category']];
|
||||
$factories = array_intersect_key($factories, array_flip($categories));
|
||||
}
|
||||
$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]);
|
||||
$answer = $intent === null ? null : ['type' => $intent['type'], 'label' => $intent['label'], 'filter' => $term,
|
||||
'count' => $results['unavailable'] === [] ? $results['total'] : null];
|
||||
|
||||
if ($answer !== null && $intent['type'] === 'products') {
|
||||
$answer['category'] = match ($intent['category']) {
|
||||
'Produtos e localizações' => 'physical', 'Produtos financeiros' => 'financial', default => 'all',
|
||||
};
|
||||
}
|
||||
|
||||
return Inertia::render('portal/search', ['query' => $original, 'results' => $results, 'answer' => $answer]);
|
||||
}
|
||||
|
||||
/** @param list<string> $tokens
|
||||
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
|
||||
*/
|
||||
private function productReferences(SearchTerms $search, array $tokens, string $term): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach (['mineracao', 'energia-especifica'] as $sector) {
|
||||
if (! Sector::where('slug', $sector)->where('is_active', true)->whereNotNull('published_at')->exists()) {
|
||||
continue;
|
||||
}
|
||||
$data = app(SectorResourceReferences::class)->view($sector);
|
||||
foreach ($data['groups'] as $group) {
|
||||
$locations = array_values(array_filter($group['location_labels'], fn ($name) => $search->matches($term, $search->tokens($name))));
|
||||
$rows[] = ['title' => $group['name'], 'description' => $sector === 'mineracao' ? 'Referência mineral; não identifica uma concessão ou produção disponível.' : 'Segmento energético e cadeia de valor.',
|
||||
'location' => $group['locations_text'], 'url' => '/sectores/'.$sector.'?'.http_build_query(['resource_group' => $group['id'],
|
||||
...(count($locations) === 1 ? ['resource_location' => $locations[0]] : [])])];
|
||||
}
|
||||
}
|
||||
if (app(LegacyContent::class)->available() && Sector::where('slug', 'agronegocio')->where('is_active', true)->whereNotNull('published_at')->exists()) {
|
||||
try {
|
||||
app(LegacyContent::class)->article('agronegocio', false);
|
||||
$entries = app(CorridorAgribusinessOpportunities::class)->entries();
|
||||
$published = Opportunity::published()->whereIn('management_creation_key', array_column($entries, 'key'))->pluck('slug', 'management_creation_key');
|
||||
foreach ($entries as $entry) {
|
||||
if (! isset($published[$entry['key']])) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['title' => $entry['chain'], 'description' => 'Cadeia agrícola: '.$entry['summary'], 'location' => 'Enquadramento territorial: '.$entry['corridor'],
|
||||
'url' => '/oportunidades/'.rawurlencode($published[$entry['key']])];
|
||||
}
|
||||
} catch (HttpException $exception) {
|
||||
if ($exception->getStatusCode() !== 404) {
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
$rows = array_values(array_filter($rows, fn ($row) => $search->matches(implode(' ', $row), $tokens)));
|
||||
usort($rows, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens) ?: strcmp($a['title'], $b['title']));
|
||||
|
||||
return ['count' => count($rows), 'fetch' => fn ($offset, $limit) => array_slice($rows, $offset, $limit)];
|
||||
}
|
||||
|
||||
/** @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
|
||||
* @param list<string> $tokens
|
||||
* @param callable(mixed):array<string,mixed> $present
|
||||
* @param literal-string $title
|
||||
* @param literal-string $id
|
||||
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
|
||||
*/
|
||||
private function source($query, SearchTerms $search, string $term, array $tokens, string $title, string $id, callable $present): array
|
||||
{
|
||||
$count = (clone $query)->reorder()->count();
|
||||
@@ -143,10 +284,14 @@ class GlobalSearchController extends Controller
|
||||
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. */
|
||||
/** Public service entry points and terms used to find them.
|
||||
* @return list<array{title:string,description:string,url:string}>
|
||||
*/
|
||||
private function pages(): array
|
||||
{
|
||||
return [
|
||||
['title' => 'Licenciamento da empresa', 'description' => 'Roteiro de constituição e licenciamento conforme a actividade e localização.', 'url' => '/como-investir#planeamento'],
|
||||
['title' => 'Preparar licenciamento no dossier', 'description' => 'Continuar a preparação na etapa de licenciamento prévio.', 'url' => '/investimentos/iniciar?step=S08'],
|
||||
['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'],
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\QueryException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** 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 */
|
||||
/** @param array<string, callable(): array{count:int, fetch:callable(int,int): iterable<array<string,mixed>>}> $factories
|
||||
* @return array{data:list<array<string,mixed>>,total:int,current_page:int,last_page:int,per_page:int,unavailable:list<string>}
|
||||
*/
|
||||
public function page(array $factories, int $requestedPage, int $size = 5, ?callable $score = null): array
|
||||
{
|
||||
$sources = [];
|
||||
@@ -15,7 +18,10 @@ final class FederatedSearch
|
||||
foreach ($factories as $label => $factory) {
|
||||
try {
|
||||
$sources[$label] = $factory();
|
||||
} catch (QueryException $exception) {
|
||||
} catch (QueryException|HttpException $exception) {
|
||||
if ($exception instanceof HttpException && ! in_array($exception->getStatusCode(), [404, 503], true)) {
|
||||
throw $exception;
|
||||
}
|
||||
report($exception);
|
||||
$unavailable[] = $label;
|
||||
}
|
||||
@@ -45,7 +51,10 @@ final class FederatedSearch
|
||||
if ($batch === []) {
|
||||
$positions[$label] = $source['count'];
|
||||
}
|
||||
} catch (QueryException $exception) {
|
||||
} catch (QueryException|HttpException $exception) {
|
||||
if ($exception instanceof HttpException && ! in_array($exception->getStatusCode(), [404, 503], true)) {
|
||||
throw $exception;
|
||||
}
|
||||
report($exception);
|
||||
$unavailable[] = $label;
|
||||
unset($sources[$label]);
|
||||
|
||||
@@ -7,6 +7,64 @@ use Illuminate\Support\Str;
|
||||
/** Text matching shared by the database and the built-in page catalogue. */
|
||||
final class SearchTerms
|
||||
{
|
||||
/** @return array{type:string,category:?string,label:string,kind:?string,filter:string}|null */
|
||||
public function requestIntent(string $query): ?array
|
||||
{
|
||||
if ($count = $this->countIntent($query)) {
|
||||
return ['type' => 'count', ...$count];
|
||||
}
|
||||
$normalized = trim(mb_strtolower(Str::ascii($query)), " \t\n\r\0\x0B?!.");
|
||||
if (preg_match('/^(?:como|onde|quero|preciso de)\s+(?:(?:posso|faco para|devo)\s+)?licenciar(?:$|\s+(?:(?:uma|a|minha|o|um|meu)\s+)?(?:empresa|negocio|actividade|atividade|investimento)\b)/', $normalized)) {
|
||||
return ['type' => 'guide', 'category' => 'Páginas e serviços', 'label' => 'Licenciamento da empresa', 'kind' => null, 'filter' => 'licenciamento'];
|
||||
}
|
||||
$product = null;
|
||||
if (preg_match('/^(?:(?:tipos?|lista|catalogo) de |quais (?:sao )?(?:os )?)?produtos?\b(.*)$/', $normalized, $match)) {
|
||||
$product = $match[1];
|
||||
} elseif (preg_match('/^onde (?:encontrar|produzir|se produz|existem|ha)\s+(.+)$/', $normalized, $match)) {
|
||||
$product = $match[1];
|
||||
}
|
||||
if ($product !== null) {
|
||||
$category = preg_match('/\bfinanceiros?\b/', $product) ? 'Produtos financeiros' : (preg_match('/\bfisicos?\b/', $product) ? 'Produtos e localizações' : null);
|
||||
$product = preg_replace('/\b(?:e (?:a )?(?:sua )?localizacao|e (?:as )?(?:suas )?localizacoes|financeiros?|fisicos?|existem|disponiveis|no portal)\b/', ' ', $product);
|
||||
|
||||
return ['type' => 'products', 'category' => $category, 'label' => 'Produtos e localização', 'kind' => null, 'filter' => trim(preg_replace('/\s+/', ' ', $product))];
|
||||
}
|
||||
if (preg_match('/^(?:listar|mostrar|mostre|ver|quais (?:sao )?(?:os|as))\s+(.+)$/', $normalized, $match)
|
||||
&& ($list = $this->countIntent('quantos '.$match[1]))) {
|
||||
return ['type' => 'list', ...$list];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return array{category:string,label:string,kind:?string,filter:string}|null */
|
||||
public function countIntent(string $query): ?array
|
||||
{
|
||||
$query = trim(mb_strtolower(Str::ascii($query)), " \t\n\r\0\x0B?!.");
|
||||
$types = [
|
||||
'corredor|corredores' => ['Carteira: projectos, clusters e corredores', 'corredores', 'corridor'],
|
||||
'cluster|clusters' => ['Carteira: projectos, clusters e corredores', 'clusters', 'cluster'],
|
||||
'projectos? ancora|projetos? ancora' => ['Carteira: projectos, clusters e corredores', 'projectos âncora', 'project'],
|
||||
'oportunidade|oportunidades' => ['Oportunidades', 'oportunidades', null],
|
||||
'negocio|negocios' => ['Negócios', 'negócios', null],
|
||||
'documento|documentos' => ['Documentos e legislação', 'documentos', null],
|
||||
'artigo|artigos' => ['Artigos', 'artigos', null],
|
||||
'sector|sectores|setor|setores' => ['Sectores', 'sectores', null],
|
||||
'localizacao|localizacoes' => ['Localizações', 'localizações', null],
|
||||
'zonas? de investimento|zona|zonas' => ['Zonas de investimento', 'zonas de investimento', null],
|
||||
'parceria|parcerias' => ['Parcerias', 'parcerias', null],
|
||||
];
|
||||
foreach ($types as $pattern => [$category, $label, $kind]) {
|
||||
if (preg_match('/^(?:quantos|quantas|numero de|quantidade de|total de|qual (?:e )?o numero de)\s+(?:'.$pattern.')\b(.*)$/u', $query, $match)) {
|
||||
$filter = preg_replace('/\b(?:no portal|no investemoz|em mocambique|de investimento|existem|existe|existentes|existente|ha|temos|estao|sao|disponiveis|disponivel|publicados|publicadas|registados|registadas|cadastrados|cadastradas)\b/u', ' ', $match[1]);
|
||||
|
||||
return ['category' => $category, 'label' => $label, 'kind' => $kind, 'filter' => trim(preg_replace('/\s+/', ' ', $filter))];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function tokens(string $query): array
|
||||
{
|
||||
@@ -24,13 +82,16 @@ final class SearchTerms
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
/** Known Portuguese spelling and number variants; do not infer semantic equivalence. */
|
||||
/** Known Portuguese spelling and number variants; do not infer semantic equivalence.
|
||||
* @return list<string>
|
||||
*/
|
||||
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) {
|
||||
['provincia', 'provincias'], ['corredor', 'corredores'], ['cluster', 'clusters'], ['imposto', 'impostos'], ['licenca', 'licencas'],
|
||||
['banco', 'bancos'], ['seguro', 'seguros'], ['produto', 'produtos'], ['agricola', 'agricolas']] as $group) {
|
||||
if (in_array($token, $group, true)) {
|
||||
return $group;
|
||||
}
|
||||
@@ -44,7 +105,10 @@ final class SearchTerms
|
||||
return '%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $token).'%';
|
||||
}
|
||||
|
||||
/** Columns are trusted application constants, never user input. */
|
||||
/** Columns are trusted application constants, never user input.
|
||||
* @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
|
||||
* @param list<literal-string> $columns
|
||||
*/
|
||||
public function orFields($query, array $columns, string $token): void
|
||||
{
|
||||
foreach ($columns as $column) {
|
||||
@@ -54,6 +118,10 @@ final class SearchTerms
|
||||
}
|
||||
}
|
||||
|
||||
/** @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
|
||||
* @param list<literal-string> $columns
|
||||
* @param list<string> $tokens
|
||||
*/
|
||||
public function constrain($query, array $columns, array $tokens): void
|
||||
{
|
||||
foreach ($tokens as $token) {
|
||||
@@ -61,6 +129,7 @@ final class SearchTerms
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string> $tokens */
|
||||
public function matches(string $text, array $tokens): bool
|
||||
{
|
||||
$text = mb_strtolower(Str::ascii($text));
|
||||
@@ -73,40 +142,55 @@ final class SearchTerms
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param literal-string $column
|
||||
* @return literal-string
|
||||
*/
|
||||
private function normalizedColumn(string $column): string
|
||||
{
|
||||
return "translate(lower(coalesce({$column}::text, '')), 'áàâãäéèêëíìîïóòôõöúùûüçñ', 'aaaaaeeeeiiiiooooouuuucn')";
|
||||
}
|
||||
|
||||
/** @param list<string> $tokens */
|
||||
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);
|
||||
$score = $title === $phrase ? 1000 : (str_starts_with($title, $phrase) ? 600 : (str_contains($title, $phrase) ? 400 : 0));
|
||||
foreach ($tokens as $token) {
|
||||
if ($this->matches($title, [$token])) {
|
||||
$score += 20;
|
||||
$score++;
|
||||
}
|
||||
}
|
||||
|
||||
return $score;
|
||||
}
|
||||
|
||||
/** The same title score used for in-memory pages, with bound search terms. */
|
||||
/** The same title score used for in-memory pages, with bound search terms.
|
||||
* @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
|
||||
* @param list<string> $tokens
|
||||
* @param literal-string $titleColumn
|
||||
* @param literal-string $tieColumn
|
||||
*/
|
||||
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)];
|
||||
$sql = "CASE WHEN {$column} = ? THEN 1000 WHEN {$column} LIKE ? ESCAPE '!' THEN 600 WHEN {$column} LIKE ? ESCAPE '!' THEN 400 ELSE 0 END";
|
||||
$bindings = [$phrase, ltrim($this->pattern($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';
|
||||
$sql .= ' + CASE WHEN ('.implode(' OR ', $conditions).') THEN 1 ELSE 0 END';
|
||||
}
|
||||
$query->orderByRaw('('.$sql.') DESC', $bindings)->orderBy($titleColumn)->orderBy($tieColumn);
|
||||
$query->orderByRaw('('.$sql.') DESC', $bindings);
|
||||
if (str_contains($titleColumn, '(')) {
|
||||
$query->orderByRaw($titleColumn);
|
||||
} else {
|
||||
$query->orderBy($titleColumn);
|
||||
}
|
||||
$query->orderBy($tieColumn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
## 13/11/2026 — pesquisa rápida: intenções e categorias, implementada em QA
|
||||
|
||||
A pesquisa reconhece contagens do catálogo publicado (por exemplo, «quantos corredores existem»), sem misturar projectos ou oportunidades apenas por mencionarem corredores. Zero registos e indisponibilidade de uma fonte têm apresentação distinta. «Como licenciar uma empresa» conduz ao roteiro existente e à preparação de S08 no dossier, sem inventar requisitos oficiais.
|
||||
|
||||
Produtos físicos e financeiros aparecem em categorias separadas, com opções Todos / Produtos físicos / Produtos financeiros e preservação do filtro e paginação. Exemplos: «tipo de produtos e sua localização», «onde encontrar grafite em Cabo Delgado» e «produtos financeiros em Nampula». Reutiliza as referências aceites de Mineração/Energia, oportunidades agrícolas publicadas e versões publicadas das instituições. A ligação mineral conserva grupo/local seleccionado; a ligação financeira abre a instituição existente. Presença física e cobertura financeira aparecem separadas. Rascunhos e publicações futuras não são divulgados.
|
||||
|
||||
Limites: localização nestes exemplos é correspondência textual aos dados documentados; não representa geocodificação, elegibilidade ou garantia de oferta/financiamento. Só entram conteúdos publicados das fontes efectivamente disponíveis. Não é uma resposta aberta por IA. Erros 404/503 de fontes são identificados sem ocultar os outros resultados; 403 continua recusado.
|
||||
|
||||
Verificação focada em QA isolado 55441: integração 4 testes/118 asserções; regressão federada 3 aprovados e 1 ignorado por guarda de ambiente; unidade 8 testes/39 asserções; frontend 7 testes. Tipos TypeScript, PHPStan e compilação aprovados. Provas em `outputs/quick-search-20261113/`. Sem migrações, alterações de dados ou permissões. Conferência visual no navegador e instalação desta candidata ainda pendentes. Preservar as entregas e os doze lotes demográficos já aceites.
|
||||
|
||||
## 13/11/2026 — erro 500 corrigido e verificado no PHP web, revisão 4988ca89
|
||||
|
||||
A recusa de acesso anterior estava corrigida, mas a abertura do instalador revelou outra incompatibilidade: o PHP-FPM bloqueia `proc_open`; a criação de `Symfony Process` na pré-visualização provocava 500. Os registos de 13:49:58 e 13:50:10 identificaram esta causa. Conferência de leitura confirmou que não existiam tabelas demográficas nem recibos de importação no destino.
|
||||
@@ -9762,3 +9772,60 @@ Provas: `outputs/dossier-reports-20261113/`. Vinte e um testes frontend aprovado
|
||||
|
||||
|
||||
Relatórios do dossier — conferência final de 13/11/2026: regressão focada do servidor 4 testes/168 asserções; caso final de recuperação, descargas privadas, âmbito, repetição e bloqueio com módulo desactivado 45 asserções. Os 21 testes frontend passaram; tipos, análise PHP, lint e compilação QA aprovados. Delta próprio de relatórios preparado, sem instalação remota e sem interferir na incorporação demográfica em curso.
|
||||
|
||||
|
||||
## 13/11/2026 — relatórios do dossier instalados na homologação em 07182c7c
|
||||
|
||||
Entrega autorizada pelo proprietário e instalada pelo executor Git em `https://teste-investidor.tempo.co.mz`. A revisão servida é `07182c7c735efa88d850551da71b671c3dadfa9d`. Entrada: `/investimentos`, abrir o dossier autorizado e a secção `#relatorios`. Índice por etapa e exportação consolidada Word/HTML disponíveis; cópias fiscais preservadas são recuperadas pelo titular a partir do próprio dossier. Continua sem envio ou publicação automática.
|
||||
|
||||
Backup/restauro fresco:193 tabelas e381ficheiros. Conferência pós-entrega:12ficheiros de fonte por SHA256,HTTPS e controlos de entrada privada,12tabelas de negócio/geometria sem alteração,mais os três lotes demográficos presentes no backup conservados por contagens/checksum de metadados,observações e eventos. Durante a entrega foram concluídas,por operações autenticadas independentes,as restantes incorporações demográficas:a verificação final encontrou12lotes aprovados/920456observações. Esta entrega de relatórios não fez importações ou migrações;actualizou o vínculo da readiness à nova revisão,preservando as preparações CLI aceites.
|
||||
|
||||
Prova final `outputs/dossier-reports-20261113/homologation-installed.json`;estado agregado `verification.json`. QA funcional,privacidade,recuperação,exportações,tipos,lint,análise PHP e compilação aprovados. A conferência visual no uso normal permanece pendente,sem reabrir a instalação nem as provas aceites. Este estado substitui a indicação histórica de QA sem instalação acima e não declara concluídos outros módulos ou relatórios ainda por implementar.
|
||||
|
||||
|
||||
## 13/11/2026 — consulta e descarga de resumos das 19 etapas, correcção em QA
|
||||
|
||||
Conferência com conta sintética e MFA normal em `http://127.0.0.1:18814/investimentos/5245f06c-bdbd-4caf-bc37-900f10bf582c`, base isolada `investmoz_demography_test:55441`. Novo dossier, versão 21: os serviços existentes guardaram fundamentos sintéticos em S01–S19. Não foram alterados dossiers anteriores nem simuladas decisões/licenças externas. Na homologação foi criado apenas o dossier separado de ensaio `db85f087-0737-4164-892a-4fa4fe1313df`, com fundamento sintético S01; os três dossiers anteriores foram preservados.
|
||||
|
||||
Lacuna corrigida: o componente existente passa a permitir seleccionar a etapa, consultar o resumo dos registos recuperados e preparar Word ou HTML. A ligação de descarga permanece visível com indicação de ficheiro pronto; o conteúdo e as pendências não são confundidos com documentos oficiais em falta. As limitações do modelo passam a integrar ambos os formatos. Mudar de dossier, versão ou oportunidade reinicializa a selecção/ligação local para não reutilizar uma exportação de outro contexto.
|
||||
|
||||
Prova integrada: consulta das 19 etapas e 38 descargas reais pelo Edge (19 Word/19 HTML), conferidas em disco por identidade, etapa, versão, fundamento, limitações e ausência de registos de outra etapa. Actualizar a página recuperou os 19 registos e a versão 21. Evidência em `outputs/dossier-reports-20261113/stage-authenticated-browser-checks.json`, `stage-authenticated-download-verification.json`, `stage-recovery.json` e `visual/04-dossier-qa-S19-descarga.jpg`. Os ensaios isolados do componente estão identificados separadamente, sem os apresentar como prova de persistência.
|
||||
|
||||
Validação nova, limitada ao delta: dois testes frontend (incluem exportação das 19 etapas e escape das limitações), tipos, lint dos três ficheiros de produto afectados e compilação QA. Não foram repetidas as provas aceites de APIEX/SWOT, cálculo fiscal, permissões ou instalação. O perfil antigo de QA referia contas que já não existem no cluster actualmente ligado; foi localizado e usado o perfil documentado da demografia, sem criar permissões ou reiniciar o cluster. A serialização da chave MFA da conta recém-criada foi corrigida apenas nessa conta sintética.
|
||||
|
||||
Estado: correcção implementada e conferida em QA, ainda sem instalação. A homologação mantém `07182c7c` para o recorte de relatórios anteriormente instalado. A prova demonstra resumos de preparação por etapa; não declara produzidos estudos financeiros, licenças, decisões, pacotes APIEX ou documentos que não existam nos respectivos percursos. A instalação deste novo delta é a pendência de entrega; os saldos próprios dos outros módulos mantêm-se.
|
||||
|
||||
|
||||
## 13/11/2026 — resumos por etapa instalados na homologação em 8854b292
|
||||
|
||||
Autorização expressa do proprietário recebida e executada. Revisão servida `8854b2928c6907b6742a1eb622ae70e6b6a9e998`, construída em 2026-11-13T13:16:06Z; troca concluída em 13:16:09Z. Entrada habitual: `https://teste-investidor.tempo.co.mz/investimentos`, abrir o dossier e a secção de relatórios, seleccionar a etapa, consultar o resumo, preparar Word ou HTML e descarregar o ficheiro pronto. O relatório consolidado permanece disponível.
|
||||
|
||||
Backup/restauro fresco: 193 tabelas/409 ficheiros, conferidos por contagens e hashes. Verificação pós-entrega: quatro ficheiros por SHA256; 18 tabelas protegidas inalteradas, incluindo instituições, dossiers, rascunhos, documentos, jornadas, etapas e as três tabelas demográficas. Mantidos 12 lotes aprovados/920456 observações. Sem migrações, importações, publicação ou alterações de permissões. Preparação demográfica e os controlos autenticados foram preservados e a readiness foi vinculada à revisão instalada, mantendo o exemplar anterior arquivado.
|
||||
|
||||
O executor Git existente e os seus controlos obrigatórios de CI foram reutilizados sem alteração de fonte ou da configuração partilhada. A entrega ficou fixada na branch aprovada `entrega/relatorios-etapas-20261113`, pois a main já continha alterações alheias de pesquisa/suporte com integração falhada. Essas alterações e a main não foram substituídas nem instaladas por esta autorização.
|
||||
|
||||
Prova pós-instalação no Edge, na sessão autorizada já existente: dossier sintético `db85f087-0737-4164-892a-4fa4fe1313df`, resumo S01 e fundamento guardado recuperados; Word e HTML efectivamente descarregados e conferidos. Nenhum dossier foi alterado nesta conferência. Não se repetiram as 19 consultas/38 descargas aceites em QA; o CI obrigatório do executor correu normalmente. Recibo: `outputs/dossier-reports-20261113/stage-homologation-installed.json`; captura `visual/06-homologacao-S01-descarga.jpg` no mesmo directório.
|
||||
|
||||
Estado deste delta: instalado e conferido. Substitui a pendência de instalação do registo anterior, preservando os seus limites: são resumos de preparação dos registos disponíveis; não se declaram produzidas licenças, decisões, estudos ou outros originais ainda em falta nos respectivos percursos. O pacote QA selado `outputs/entrega-relatorios-etapas-20261113.zip` permanece inalterado; o recibo posterior comprova a instalação.
|
||||
|
||||
|
||||
## 13/11/2026 — ACT-02: confronto de observações quantitativas, QA
|
||||
|
||||
Primeiro recorte executável da continuidade documentada de ACT-20261029-02: a comparação das observações públicas já recebidas no mapa. Reutiliza `InvestmentMapIndicators` e os filtros existentes; não acrescenta API, cadastro, publicação, fonte externa ou acesso a dados privados. Duas selecções progressivas mostram território, descrição/natureza da grandeza, indicador, valor textual exacto, unidade, período, âmbito, população/base, metodologia, situação, fonte/data e versão.
|
||||
|
||||
A conferência assinala diferenças de território/indicador/unidade/âmbito/base/metodologia, campos em falta (incluindo descrição/natureza), datas inválidas, escolha repetida e informação desconhecida/em divergência. Metadados alinhados não são certificação de comparabilidade. Duração, sobreposição dos períodos e natureza prevista/efectiva exigem leitura da fonte. Não soma, calcula evolução, converte grandezas, cria pontuação ou índice regional. Zero, precisão decimal e fontes originais são preservados.
|
||||
|
||||
Selecções identificadas por território, observação e versão. Fora dos filtros deixam de entrar na comparação; mudar a versão exige nova selecção. Conferência no Edge com três observações inteiramente sintéticas, sem API/escritas na base, exercitando o componente real compilado. Capturas e recibo em `outputs/map-comparison-20261113/`. Três testes novos dirigidos ao delta, tipos, lint e compilação QA aprovados; os testes aceites dos filtros anteriores não foram repetidos.
|
||||
|
||||
Estado: implementado e conferido em QA, sem instalação. V2-07/V2-10 e ACT-02 permanecem parciais: cobertura factual nacional/regional, séries estatisticamente comparáveis, oferta laboral, natureza estruturada das grandezas e metodologia de potencial económico continuam com o seu saldo próprio. Este incremento encerra apenas a ferramenta de confronto das observações recebidas. Não altera dossiers, relatórios de 8854b292, pesquisa ou suporte aceites. A candidata incorpora também o recibo documental de 8854b292, sem repetir a instalação ou as provas dessa entrega.
|
||||
|
||||
|
||||
## 13/11/2026 — ACT-02: comparação de observações instalada em 1263b4f6
|
||||
|
||||
Instalação expressamente autorizada e concluída pelo executor Git existente na main, em `https://teste-investidor.tempo.co.mz`. A revisão servida é `1263b4f6b7609c3d4d293c2b9f8a68abb9d3e3c4`. No mapa das oportunidades, o bloco de indicadores apresenta «Comparar duas observações» quando há pelo menos duas observações públicas nos filtros actuais. A comparação mantém valores, descrições, unidades, períodos, âmbito, base, metodologia, situação, fontes e versões; não infere evolução, conversão, elegibilidade ou potencial regional.
|
||||
|
||||
Backup/restauro fresco de 193 tabelas/410 ficheiros, com contagens e hashes conferidos; verificação pós-entrega de 21 tabelas protegidas sem diferenças, incluindo dados territoriais, instituições, dossiers, jornadas, etapas, documentos, permissões e demografia. Mantidos 12 lotes aprovados/920456 observações. Fontes entregues verificadas por SHA256; configuração/fonte do executor preservadas. Sem migrações, importações, publicação de conteúdo ou novas permissões. A readiness demográfica foi vinculada à revisão, com o exemplar anterior arquivado.
|
||||
|
||||
Reutilizadas as provas aceites: três testes novos e a conferência visual sintética do componente; o CI obrigatório do executor correu normalmente, sem nova ronda manual dos percursos aceites. HTTPS do mapa, instituições, demografia e entrada privada conferido. Os originais e a pesquisa, suporte e relatórios de 8854b292 foram preservados. Não foram criadas observações sintéticas na homologação para fazer aparecer a comparação. Recibo: `outputs/map-comparison-20261113/homologation-installed.json`; pacote QA selado inalterado.
|
||||
|
||||
Estado do incremento: instalado. ACT-02/V2-07/V2-10 permanecem parciais quanto à cobertura factual, séries estatisticamente comparáveis, oferta laboral, natureza estruturada das grandezas e metodologia económica. Esta entrega fecha a ferramenta de confronto das observações recebidas, não esses requisitos amplos.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -54,9 +54,26 @@
|
||||
.catalogue-filters-heading {
|
||||
display: none;
|
||||
}
|
||||
#catalogue-filter-fields {
|
||||
#catalogue-filter-fields,
|
||||
.catalogue-service-fields {
|
||||
padding: 0 1.15rem 1.15rem;
|
||||
}
|
||||
|
||||
.catalogue-service-fields label {
|
||||
min-width: 0;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.catalogue-service-fields label input:not([type='checkbox']),
|
||||
.catalogue-service-fields label select {
|
||||
margin-top: 0.35rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
.catalogue-service-fields .catalogue-filter-submit > button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.catalogue-filters input:not([type='checkbox']),
|
||||
.catalogue-filters select {
|
||||
min-height: 44px;
|
||||
|
||||
@@ -55,6 +55,238 @@ const completeDate = (value?: string | null) =>
|
||||
new Date(value).toISOString().slice(0, 10) === value,
|
||||
);
|
||||
|
||||
type MapObservation = QuantitativeMapContext['records'][number];
|
||||
const observationKey = (row: MapObservation) =>
|
||||
JSON.stringify([row.zone_id, row.id, row.zone_version]);
|
||||
|
||||
export function compareMapObservations(
|
||||
first: MapObservation,
|
||||
second: MapObservation,
|
||||
) {
|
||||
const issues: string[] = [];
|
||||
if (observationKey(first) === observationKey(second))
|
||||
issues.push('Escolha duas observações distintas.');
|
||||
if (first.zone_id !== second.zone_id)
|
||||
issues.push(
|
||||
'Territórios distintos: os valores não representam uma série do mesmo local.',
|
||||
);
|
||||
for (const [label, row] of [
|
||||
['Primeira', first],
|
||||
['Segunda', second],
|
||||
] as const) {
|
||||
if (row.knowledge !== 'documented')
|
||||
issues.push(
|
||||
`${label} observação: informação desconhecida ou em divergência.`,
|
||||
);
|
||||
if (
|
||||
row.value === null ||
|
||||
!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(row.value)
|
||||
)
|
||||
issues.push(
|
||||
`${label} observação: valor quantitativo por confirmar.`,
|
||||
);
|
||||
const comparisonMetadata: Record<string, string> = {
|
||||
...metadataLabels,
|
||||
description: 'descrição/natureza da grandeza',
|
||||
};
|
||||
const missing = Object.keys(comparisonMetadata).filter(
|
||||
(field) => !row[field as keyof MapObservation]?.toString().trim(),
|
||||
);
|
||||
if (missing.length)
|
||||
issues.push(
|
||||
`${label} observação sem ${missing.map((field) => comparisonMetadata[field]).join(', ')}.`,
|
||||
);
|
||||
if (
|
||||
!completeDate(row.period_start) ||
|
||||
!completeDate(row.period_end) ||
|
||||
(row.period_start ?? '') > (row.period_end ?? '')
|
||||
)
|
||||
issues.push(`${label} observação: período incompleto ou inválido.`);
|
||||
if (!completeDate(row.source_date))
|
||||
issues.push(
|
||||
`${label} observação: data da fonte incompleta ou inválida.`,
|
||||
);
|
||||
}
|
||||
for (const [field, label] of Object.entries({
|
||||
indicator: 'Indicador',
|
||||
unit: 'Unidade',
|
||||
scope: 'Âmbito',
|
||||
population: 'População/base',
|
||||
methodology: 'Metodologia',
|
||||
})) {
|
||||
if (
|
||||
(first[field as keyof MapObservation] ?? '').toString().trim() !==
|
||||
(second[field as keyof MapObservation] ?? '').toString().trim()
|
||||
)
|
||||
issues.push(`${label} diferente entre as observações.`);
|
||||
}
|
||||
return {
|
||||
state: issues.length ? 'review_required' : 'metadata_aligned',
|
||||
issues,
|
||||
};
|
||||
}
|
||||
|
||||
export function MapObservationComparison({
|
||||
first,
|
||||
second,
|
||||
}: {
|
||||
first?: MapObservation;
|
||||
second?: MapObservation;
|
||||
}) {
|
||||
if (!first || !second)
|
||||
return (
|
||||
<p role="status">
|
||||
Seleccione duas observações disponíveis nos filtros actuais.
|
||||
</p>
|
||||
);
|
||||
const assessment = compareMapObservations(first, second);
|
||||
const fields: [string, (row: MapObservation) => string][] = [
|
||||
['Território', (row) => row.zone_name],
|
||||
['Observação', (row) => text(row.label)],
|
||||
['Descrição e natureza da grandeza', (row) => text(row.description)],
|
||||
['Indicador', (row) => labels[row.indicator] ?? row.indicator],
|
||||
[
|
||||
'Valor original',
|
||||
(row) => (row.value === null ? 'Por confirmar' : row.value),
|
||||
],
|
||||
['Unidade', (row) => text(row.unit)],
|
||||
[
|
||||
'Período',
|
||||
(row) => `${text(row.period_start)} — ${text(row.period_end)}`,
|
||||
],
|
||||
['Âmbito', (row) => text(row.scope)],
|
||||
['População/base', (row) => text(row.population)],
|
||||
['Metodologia', (row) => text(row.methodology)],
|
||||
[
|
||||
'Situação da informação',
|
||||
(row) =>
|
||||
row.knowledge === 'documented'
|
||||
? 'Documentada'
|
||||
: row.knowledge === 'disputed'
|
||||
? 'Em divergência'
|
||||
: 'Por confirmar',
|
||||
],
|
||||
['Fonte', (row) => text(row.source_reference)],
|
||||
['Data da fonte', (row) => text(row.source_date)],
|
||||
['Versão da ficha territorial', (row) => String(row.zone_version)],
|
||||
];
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p role="status">
|
||||
{assessment.state === 'metadata_aligned'
|
||||
? 'Metadados alinhados; confirme nas fontes se os valores podem ser comparados.'
|
||||
: 'Há diferenças ou lacunas a conferir antes de comparar os valores.'}
|
||||
</p>
|
||||
{!!assessment.issues.length && (
|
||||
<ul className="list-disc pl-5">
|
||||
{assessment.issues.map((issue) => (
|
||||
<li key={issue}>{issue}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p>
|
||||
Períodos distintos ou sobrepostos exigem conferência da duração
|
||||
e da base na fonte. Esta apresentação não calcula evolução,
|
||||
soma, conversão, pontuação ou estimativa regional. A natureza
|
||||
prevista ou efectiva depende da descrição da fonte.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="sr-only">
|
||||
Conferência de duas observações quantitativas
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2">Campo</th>
|
||||
<th className="p-2">Primeira observação</th>
|
||||
<th className="p-2">Segunda observação</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{fields.map(([label, value]) => (
|
||||
<tr key={label} className="border-t">
|
||||
<th className="p-2" scope="row">
|
||||
{label}
|
||||
</th>
|
||||
<td className="p-2 break-words">
|
||||
{value(first)}
|
||||
</td>
|
||||
<td className="p-2 break-words">
|
||||
{value(second)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MapObservationComparisonPicker({ rows }: { rows: MapObservation[] }) {
|
||||
const id = useId();
|
||||
const [firstKey, setFirst] = useState('');
|
||||
const [secondKey, setSecond] = useState('');
|
||||
const first = rows.find((row) => observationKey(row) === firstKey);
|
||||
const second = rows.find((row) => observationKey(row) === secondKey);
|
||||
return (
|
||||
<details className="space-y-3 rounded border p-3">
|
||||
<summary>Comparar duas observações</summary>
|
||||
<p>
|
||||
Confronte os dados e as fontes antes de os usar na decisão.
|
||||
Selecções fora dos filtros deixam de ser comparadas; uma versão
|
||||
nova exige nova selecção.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{(['Primeira', 'Segunda'] as const).map((label, index) => (
|
||||
<label
|
||||
className="grid gap-1"
|
||||
key={label}
|
||||
htmlFor={`${id}-${index}`}
|
||||
>
|
||||
{label} observação
|
||||
<select
|
||||
className="w-full min-w-0 rounded border p-2"
|
||||
id={`${id}-${index}`}
|
||||
value={
|
||||
index === 0
|
||||
? first
|
||||
? firstKey
|
||||
: ''
|
||||
: second
|
||||
? secondKey
|
||||
: ''
|
||||
}
|
||||
onChange={(event) =>
|
||||
(index === 0 ? setFirst : setSecond)(
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccionar observação</option>
|
||||
{rows.map((row) => (
|
||||
<option
|
||||
key={observationKey(row)}
|
||||
value={observationKey(row)}
|
||||
>
|
||||
{row.zone_name} —{' '}
|
||||
{row.label ||
|
||||
labels[row.indicator] ||
|
||||
row.indicator}{' '}
|
||||
— {row.period_start || '?'} /{' '}
|
||||
{row.period_end || '?'} — v
|
||||
{row.zone_version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<MapObservationComparison first={first} second={second} />
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
export function filterMapIndicators(
|
||||
records: QuantitativeMapContext['records'],
|
||||
indicator: string,
|
||||
@@ -242,6 +474,9 @@ export default function InvestmentMapIndicators({
|
||||
observações. Refine a localização.
|
||||
</p>
|
||||
)}
|
||||
{rows.length > 1 && (
|
||||
<MapObservationComparisonPicker rows={rows} />
|
||||
)}
|
||||
{rows.length === 0 ? (
|
||||
<p>
|
||||
{filtered
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
createInvestorDossierReport,
|
||||
createInvestorStageReport,
|
||||
investorDossierReportIndex,
|
||||
type InvestorDossierReportInput,
|
||||
} from '@/lib/investor-dossier-report';
|
||||
@@ -13,9 +14,33 @@ export function InvestorDossierReports({
|
||||
dossier,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
}) {
|
||||
return (
|
||||
<InvestorDossierReportsContent
|
||||
key={`${dossier.case.id}:${dossier.case.version}:${dossier.context_opportunity ?? ''}`}
|
||||
dossier={dossier}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function InvestorDossierReportsContent({
|
||||
dossier,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [stage, setStage] = useState('');
|
||||
const [download, setDownload] = useState<{
|
||||
url: string;
|
||||
name: string;
|
||||
} | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (download) URL.revokeObjectURL(download.url);
|
||||
},
|
||||
[download],
|
||||
);
|
||||
const requiresChoice =
|
||||
dossier.opportunity_options.length > 1 && !dossier.context_opportunity;
|
||||
const entries = requiresChoice ? [] : investorDossierReportIndex(dossier);
|
||||
@@ -23,7 +48,9 @@ export function InvestorDossierReports({
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const model = createInvestorDossierReport(dossier);
|
||||
const model = stage
|
||||
? createInvestorStageReport(dossier, stage)
|
||||
: createInvestorDossierReport(dossier);
|
||||
const blob =
|
||||
format === 'word'
|
||||
? await generateProjectDossierDocx(model, [], true)
|
||||
@@ -38,11 +65,8 @@ export function InvestorDossierReports({
|
||||
{ type: 'text/html;charset=utf-8' },
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `dossier-${dossier.case.id}-v${dossier.case.version}-${dossier.context_opportunity ? encodeURIComponent(dossier.context_opportunity) : 'comum'}.${format === 'word' ? 'docx' : 'html'}`;
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
const name = `dossier-${dossier.case.id}-v${dossier.case.version}-${dossier.context_opportunity ? encodeURIComponent(dossier.context_opportunity) : 'comum'}${stage ? `-${stage}` : ''}.${format === 'word' ? 'docx' : 'html'}`;
|
||||
setDownload({ url, name });
|
||||
} catch (cause) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
@@ -72,22 +96,61 @@ export function InvestorDossierReports({
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="block">
|
||||
Relatório a consultar e descarregar
|
||||
<select
|
||||
className="mt-1 block w-full rounded border p-2"
|
||||
value={stage}
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
setStage(event.target.value);
|
||||
setDownload(null);
|
||||
}}
|
||||
>
|
||||
<option value="">Dossier completo</option>
|
||||
{dossier.steps.map((step) => (
|
||||
<option key={step.code} value={step.code}>
|
||||
{step.code} — {step.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{stage && (
|
||||
<StageReportPreview dossier={dossier} stage={stage} />
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
onClick={() => exportReport('word')}
|
||||
>
|
||||
Descarregar relatório consolidado (Word)
|
||||
Preparar{' '}
|
||||
{stage
|
||||
? `relatório ${stage}`
|
||||
: 'relatório consolidado'}{' '}
|
||||
(Word)
|
||||
</button>
|
||||
<button
|
||||
className="rounded border px-3 py-2"
|
||||
disabled={busy}
|
||||
onClick={() => exportReport('html')}
|
||||
>
|
||||
Descarregar versão para impressão/PDF
|
||||
Preparar versão para impressão/PDF
|
||||
</button>
|
||||
</div>
|
||||
{busy && <p role="status">A preparar o ficheiro…</p>}
|
||||
{download && (
|
||||
<p role="status">
|
||||
Ficheiro pronto.{' '}
|
||||
<a
|
||||
className="font-medium underline"
|
||||
href={download.url}
|
||||
download={download.name}
|
||||
>
|
||||
Descarregar {download.name}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
A versão HTML pode ser aberta e impressa ou guardada
|
||||
como PDF. As descargas são privadas; não enviam
|
||||
@@ -163,3 +226,46 @@ export function InvestorDossierReports({
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function StageReportPreview({
|
||||
dossier,
|
||||
stage,
|
||||
}: {
|
||||
dossier: InvestorDossierReportInput;
|
||||
stage: string;
|
||||
}) {
|
||||
const report = createInvestorStageReport(dossier, stage);
|
||||
return (
|
||||
<article
|
||||
className="space-y-3 rounded border p-3"
|
||||
aria-label={`Relatório da etapa ${stage}`}
|
||||
>
|
||||
<h3 className="font-semibold">{report.title}</h3>
|
||||
<p className="text-sm">{report.version}</p>
|
||||
{report.sections.map((section) => (
|
||||
<section key={section.id} className="space-y-2">
|
||||
<h4 className="font-medium">{section.title}</h4>
|
||||
{section.paragraphs.map((text) => (
|
||||
<p key={text}>{text}</p>
|
||||
))}
|
||||
<dl className="space-y-2">
|
||||
{section.rows.map((row, index) => (
|
||||
<div key={index} className="break-words">
|
||||
<dt className="font-medium">{row.field}</dt>
|
||||
<dd>{row.value}</dd>
|
||||
<dd className="text-sm">
|
||||
{row.classification} · {row.origin}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
{report.limitations.map((text) => (
|
||||
<p className="text-sm" key={text}>
|
||||
{text}
|
||||
</p>
|
||||
))}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ export default function PortalHero({
|
||||
aria-describedby="portal-opportunity-search-help"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Ex.: agronegócio, Nampula, legislação..."
|
||||
placeholder="Corredores, produtos e locais, licenciamento…"
|
||||
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
|
||||
@@ -274,8 +274,8 @@ export default function PortalHero({
|
||||
id="portal-opportunity-search-help"
|
||||
className="mt-2 text-left text-sm text-white/90"
|
||||
>
|
||||
Combine palavras-chave, sector e localização. Ex.:
|
||||
plantio de algodão ou agronegócio Nampula.
|
||||
Ex.: quantos corredores existem; grafite Cabo Delgado;
|
||||
como licenciar uma empresa.
|
||||
</p>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -552,3 +552,63 @@ export function createInvestorDossierReport(
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** A preparation summary, never a substitute for an external act or its original. */
|
||||
export function createInvestorStageReport(
|
||||
input: InvestorDossierReportInput,
|
||||
stageCode: string,
|
||||
generatedAt = new Date().toISOString(),
|
||||
): DossierReportModel {
|
||||
const step = input.steps.find((item) => item.code === stageCode);
|
||||
if (!step) throw new Error('Etapa não encontrada neste dossier.');
|
||||
const report = createInvestorDossierReport(input, generatedAt);
|
||||
const entries = investorDossierReportIndex(input).filter((entry) =>
|
||||
entry.stage.split(', ').includes(stageCode),
|
||||
);
|
||||
const origins = new Set(entries.map((entry) => entry.href));
|
||||
const specificSections = new Set([
|
||||
...(stageCode === 'S02' ? ['market'] : []),
|
||||
...(stageCode === 'S03' ? ['finance'] : []),
|
||||
...(['S06', 'S07'].includes(stageCode) ? ['sources'] : []),
|
||||
]);
|
||||
return {
|
||||
...report,
|
||||
title: `${input.case.title} — ${stageCode}: ${step.title}`,
|
||||
version: `${report.version} · etapa v${step.version ?? 'não registada'}`,
|
||||
limitations: [
|
||||
...report.limitations,
|
||||
'Resumo dos registos disponíveis nesta etapa; não cria documentos, decisões ou resultados em falta.',
|
||||
],
|
||||
sections: report.sections
|
||||
.filter(
|
||||
(section) =>
|
||||
['project', 'summary', 'execution', 'resources'].includes(
|
||||
section.id,
|
||||
) || specificSections.has(section.id),
|
||||
)
|
||||
.map((section) => {
|
||||
if (section.id === 'summary')
|
||||
return {
|
||||
...section,
|
||||
rows: section.rows.filter((item) =>
|
||||
origins.has(item.origin),
|
||||
),
|
||||
};
|
||||
if (section.id === 'execution')
|
||||
return {
|
||||
...section,
|
||||
rows: section.rows.filter((item) =>
|
||||
item.field.startsWith(`${stageCode} —`),
|
||||
),
|
||||
};
|
||||
if (section.id === 'resources')
|
||||
return {
|
||||
...section,
|
||||
rows: section.rows.filter((item) =>
|
||||
origins.has(item.origin),
|
||||
),
|
||||
};
|
||||
return section;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -396,6 +396,11 @@ export async function generateProjectDossierDocx(
|
||||
],
|
||||
}),
|
||||
];
|
||||
for (const limitation of model.limitations) {
|
||||
children.push(
|
||||
new Paragraph({ children: [new TextRun({ text: limitation })] }),
|
||||
);
|
||||
}
|
||||
for (const section of model.sections) {
|
||||
if (section.id === 'annexes') {
|
||||
if (!attachments.some((item) => item.include)) {
|
||||
@@ -591,6 +596,8 @@ export async function createProjectDossierPrintHtml(
|
||||
annexesIncluded: boolean,
|
||||
): Promise<string> {
|
||||
const content: string[] = [];
|
||||
for (const limitation of model.limitations)
|
||||
content.push(`<p>${escapeHtml(limitation)}</p>`);
|
||||
for (const section of model.sections) {
|
||||
if (
|
||||
section.id === 'annexes' &&
|
||||
|
||||
@@ -23,6 +23,8 @@ type Result = {
|
||||
description: string | null;
|
||||
url: string;
|
||||
category: string;
|
||||
location?: string | null;
|
||||
coverage?: string | null;
|
||||
};
|
||||
type Results = {
|
||||
data: Result[];
|
||||
@@ -33,9 +35,26 @@ type Results = {
|
||||
unavailable: string[];
|
||||
};
|
||||
|
||||
type SearchAnswer = {
|
||||
type: 'count' | 'guide' | 'products' | 'list';
|
||||
label: string;
|
||||
count: number | null;
|
||||
filter: string;
|
||||
category?: 'all' | 'physical' | 'financial';
|
||||
};
|
||||
|
||||
const ANSWER_HELP: Record<SearchAnswer['type'], string> = {
|
||||
count: 'Contagem dos registos publicados e disponíveis para consulta no InvesteMoz.',
|
||||
list: 'Registos publicados e disponíveis para consulta no InvesteMoz.',
|
||||
guide: 'Consulte o roteiro público e prepare depois o licenciamento no seu dossier. Os requisitos dependem da actividade e localização.',
|
||||
products: 'Produtos físicos e referências de cadeias de valor separados dos produtos financeiros. A presença física de uma instituição não determina a cobertura do financiamento.',
|
||||
};
|
||||
|
||||
type CategoryMeta = { icon: LucideIcon; iconClass: string; badgeClass: string };
|
||||
|
||||
const CATEGORY_META: Record<string, CategoryMeta> = {
|
||||
'Produtos e localizações': { icon: Factory, iconClass: 'bg-teal-50 text-teal-700', badgeClass: 'bg-teal-50 text-teal-700' },
|
||||
'Produtos financeiros': { icon: Landmark, iconClass: 'bg-blue-50 text-blue-700', badgeClass: 'bg-blue-50 text-blue-700' },
|
||||
'Páginas e serviços': {
|
||||
icon: Compass,
|
||||
iconClass: 'bg-slate-100 text-slate-700',
|
||||
@@ -292,9 +311,11 @@ function QuickLinks() {
|
||||
export default function Search({
|
||||
query,
|
||||
results,
|
||||
answer = null,
|
||||
}: {
|
||||
query: string;
|
||||
results: Results;
|
||||
answer?: SearchAnswer | null;
|
||||
}) {
|
||||
const [input, setInput] = useState(query);
|
||||
useEffect(() => setInput(query), [query]);
|
||||
@@ -308,7 +329,7 @@ export default function Search({
|
||||
unavailable,
|
||||
} = results;
|
||||
const pageUrl = (page: number) =>
|
||||
`/pesquisa?${new URLSearchParams({ q: query, page: String(page) })}`;
|
||||
`/pesquisa?${new URLSearchParams({ q: query, page: String(page), ...(answer?.category ? { category: answer.category } : {}) })}`;
|
||||
const start = total ? (current - 1) * perPage + 1 : 0;
|
||||
const end = Math.min(start + data.length - 1, total);
|
||||
const highlight = useMemo(() => buildHighlightRegex(query), [query]);
|
||||
@@ -340,6 +361,7 @@ export default function Search({
|
||||
role="search"
|
||||
className="mt-6 flex max-w-3xl flex-col gap-2 sm:flex-row"
|
||||
>
|
||||
{answer?.category && <input type="hidden" name="category" value={answer.category} />}
|
||||
<label htmlFor="search-query" className="sr-only">
|
||||
Pesquisar no InvesteMoz
|
||||
</label>
|
||||
@@ -376,6 +398,26 @@ export default function Search({
|
||||
</section>
|
||||
|
||||
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
|
||||
{answer && (
|
||||
<section aria-label="Resposta à pesquisa" className="mb-6 rounded-xl border border-slate-200 bg-white p-5">
|
||||
<p className="text-xl font-semibold text-[#101820]" aria-live="polite">
|
||||
{answer.type !== 'count' ? answer.label : answer.count === null ? 'Contagem indisponível de momento' : `${answer.count.toLocaleString('pt-MZ')} ${answer.label}`}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-slate-600">{ANSWER_HELP[answer.type]}</p>
|
||||
{answer.filter && answer.type !== 'guide' && <p className="mt-1 text-sm text-slate-600">Correspondência textual: {answer.filter}.</p>}
|
||||
{answer.type === 'products' && (
|
||||
<nav aria-label="Categoria de produtos" className="mt-4 flex flex-wrap gap-2">
|
||||
{([['all', 'Todos'], ['physical', 'Produtos físicos'], ['financial', 'Produtos financeiros']] as const).map(([category, label]) => (
|
||||
<Link key={category} href={`/pesquisa?${new URLSearchParams({ q: answer.filter, category })}`}
|
||||
aria-current={(answer.category ?? 'all') === category ? 'page' : undefined}
|
||||
className={`rounded-full border px-3 py-2 text-sm font-semibold ${(answer.category ?? 'all') === category ? 'border-slate-800 bg-slate-800 text-white' : 'border-slate-200 text-slate-700 hover:bg-slate-100'}`}>
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{unavailable.length > 0 && (
|
||||
<p
|
||||
role="alert"
|
||||
@@ -387,7 +429,7 @@ export default function Search({
|
||||
</p>
|
||||
)}
|
||||
|
||||
{query ? (
|
||||
{query || answer ? (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<p
|
||||
@@ -395,8 +437,8 @@ export default function Search({
|
||||
className="text-sm text-slate-600"
|
||||
>
|
||||
{total > 0
|
||||
? `Resultados ${start}–${end} de ${total} para “${query}”.`
|
||||
: `Nenhum resultado nas fontes consultadas para “${query}”.`}
|
||||
? `Resultados ${start}–${end} de ${total} para “${query || answer?.label}”.`
|
||||
: `Nenhum resultado nas fontes consultadas para “${query || answer?.label}”.`}
|
||||
</p>
|
||||
{last > 1 && (
|
||||
<span className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-slate-600 ring-1 ring-slate-200">
|
||||
@@ -473,6 +515,8 @@ export default function Search({
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
{item.location && <p className="mt-2 text-sm text-slate-700"><MapPin size={14} className="mr-1 inline" aria-hidden="true" />{item.location}</p>}
|
||||
{item.coverage && <p className="mt-1 text-xs text-slate-600">{item.coverage}</p>}
|
||||
</div>
|
||||
<ArrowUpRight
|
||||
size={20}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\DevelopmentCorridor;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class GlobalSearchCountTest extends TestCase
|
||||
{
|
||||
use DatabaseTransactions;
|
||||
|
||||
public function test_licensing_question_opens_existing_guidance_without_mixing_catalogue_matches(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => 'como licenciar uma empresa']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('answer.type', 'guide')->where('results.total', 2)
|
||||
->where('results.data.0.url', '/como-investir#planeamento')
|
||||
->where('results.data.1.url', '/investimentos/iniciar?step=S08'));
|
||||
}
|
||||
|
||||
public function test_physical_product_search_keeps_the_product_and_documented_location_in_its_link(): void
|
||||
{
|
||||
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
|
||||
$this->withoutVite();
|
||||
config(['portal.legacy_content_enabled' => false, 'portal.legacy_content_qa_enabled' => false]);
|
||||
$sector = Sector::firstOrCreate(['slug' => 'mineracao'], ['name' => 'Mineração']);
|
||||
$sector->forceFill(['is_active' => true, 'published_at' => now()->subMinute()])->save();
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => 'onde encontrar grafite em Cabo Delgado']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
|
||||
->where('results.data.0.title', 'Grafite')->where('results.data.0.category', 'Produtos e localizações')
|
||||
->where('results.data.0.location', fn ($text) => str_contains($text, 'Cabo Delgado'))
|
||||
->where('results.data.0.url', fn ($url) => str_contains($url, 'resource_group=') && str_contains($url, 'resource_location=Cabo+Delgado')));
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => 'grafite Cabo Delgado', 'category' => 'physical']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('answer.category', 'physical')->where('results.total', 1)
|
||||
->where('results.data.0.category', 'Produtos e localizações'));
|
||||
$this->get('/pesquisa?category=invalid')->assertRedirect();
|
||||
}
|
||||
|
||||
public function test_financial_product_search_excludes_drafts_and_future_publications_and_distinguishes_coverage(): void
|
||||
{
|
||||
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
|
||||
$this->withoutVite();
|
||||
if (! Schema::hasTable('funding_programmes')) {
|
||||
// Only this transaction in the isolated QA database; no active schema changes.
|
||||
(require database_path('migrations/2026_11_02_210000_funding_programme_catalogue.php'))->up();
|
||||
}
|
||||
$actor = User::factory()->create();
|
||||
$marker = 'SYNTHFIN'.Str::random(8);
|
||||
foreach (['published', 'draft', 'future', 'historical', 'merged'] as $state) {
|
||||
$id = (string) Str::uuid();
|
||||
$version = (string) Str::uuid();
|
||||
$payload = json_encode(['title' => $marker.' '.$state, 'kind' => 'institution', 'summary' => 'Nota de preparação: ficha e documento gerador.',
|
||||
'institution_nature' => 'bank', 'institution_services' => ['investment'],
|
||||
'institution_status' => in_array($state, ['historical', 'merged'], true) ? $state : 'reported',
|
||||
'locations' => [['location_text' => 'Nampula']], 'products' => [['title' => 'Crédito PME', 'coverage' => 'national', 'needs' => ['investment']]]], JSON_THROW_ON_ERROR);
|
||||
DB::table('funding_programmes')->insert(['id' => $id, 'code' => $marker.$state, 'draft' => $payload, 'created_by' => $actor->id]);
|
||||
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => 1, 'payload' => $payload,
|
||||
'reason' => 'Synthetic QA only', 'actor_id' => $actor->id, 'published_at' => $state === 'future' ? now()->addDay() : now()->subMinute()]);
|
||||
if ($state !== 'draft') {
|
||||
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version]);
|
||||
}
|
||||
}
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => 'produtos financeiros '.$marker.' em Nampula']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
|
||||
->where('results.data.0.category', 'Produtos financeiros')->where('results.data.0.description', 'Crédito PME')
|
||||
->where('results.data.0.location', 'Presença física: Nampula')
|
||||
->where('results.data.0.coverage', fn ($text) => str_contains($text, 'nacional')));
|
||||
}
|
||||
|
||||
public function test_corridor_count_excludes_other_types_drafts_and_deleted_entities(): void
|
||||
{
|
||||
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
|
||||
$this->withoutVite();
|
||||
$marker = 'SYNTHCOUNT'.Str::random(10);
|
||||
foreach (range(1, 4) as $n) {
|
||||
$corridor = DevelopmentCorridor::create(['code' => $marker.$n, 'name' => $marker.$n, 'status' => 'active', 'data_classification' => 'public']);
|
||||
InvestmentDossier::create(['corridor_id' => $corridor->id, 'title' => $marker.' '.$n,
|
||||
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => $n === 3 ? 'draft' : 'published',
|
||||
'published_at' => now()->subMinute(), 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
|
||||
if ($n === 4) {
|
||||
$corridor->delete();
|
||||
}
|
||||
}
|
||||
InvestmentDossier::create(['project_id' => Project::factory()->create()->id, 'title' => $marker.' corredor relacionado',
|
||||
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => 'published', 'published_at' => now(),
|
||||
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
|
||||
$query = 'quantos corredores existem '.$marker;
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => $query]))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component('portal/search')->where('query', $query)->where('answer.count', 2)->where('answer.label', 'corredores')
|
||||
->where('results.total', 2)->has('results.data', 2)->where('results.unavailable', []));
|
||||
$this->get('/pesquisa?'.http_build_query(['q' => 'quantos corredores existem '.$marker.' inexistente']))
|
||||
->assertOk()->assertInertia(fn (Assert $page) => $page->where('answer.count', 0)->where('results.total', 0));
|
||||
$this->get('/pesquisa?q=quantos+corredores+existem')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('answer.label', 'corredores')->where('answer.count', fn ($count) => $count >= 2)
|
||||
->where('results.unavailable', []));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Services\FederatedSearch;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class GlobalSearchTest extends TestCase
|
||||
@@ -35,6 +36,18 @@ final class GlobalSearchTest extends TestCase
|
||||
$this->assertSame('Como investir', $result['data'][0]['title']);
|
||||
}
|
||||
|
||||
public function test_unavailable_public_reference_does_not_hide_other_sources_or_swallow_forbidden_access(): void
|
||||
{
|
||||
$result = app(FederatedSearch::class)->page([
|
||||
'Referências' => fn () => throw new HttpException(503),
|
||||
'Páginas' => fn () => ['count' => 1, 'fetch' => fn () => [['title' => 'Como investir', 'url' => '/como-investir']]],
|
||||
], 1);
|
||||
$this->assertSame(1, $result['total']);
|
||||
$this->assertSame(['Referências'], $result['unavailable']);
|
||||
$this->expectException(HttpException::class);
|
||||
app(FederatedSearch::class)->page(['Restrito' => fn () => throw new HttpException(403)], 1);
|
||||
}
|
||||
|
||||
public function test_public_search_uses_the_existing_portfolio_visibility_scope(): void
|
||||
{
|
||||
if (getenv('GLOBAL_SEARCH_QA') !== '1') {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\FederatedSearch;
|
||||
use App\Services\SearchTerms;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class FederatedSearchTest extends TestCase
|
||||
@@ -44,4 +45,24 @@ final class FederatedSearchTest extends TestCase
|
||||
$result = (new FederatedSearch)->page($factories, 1, 5, fn ($item) => $item['score']);
|
||||
$this->assertSame(['Sectores', 'Informação'], array_column($result['data'], 'title'));
|
||||
}
|
||||
|
||||
public function test_direct_matches_precede_associations_across_sources_and_pages(): void
|
||||
{
|
||||
$search = new SearchTerms;
|
||||
$term = 'corredor da beira';
|
||||
$tokens = $search->tokens($term);
|
||||
$sources = [
|
||||
'Oportunidades' => fn () => ['count' => 2, 'fetch' => fn ($offset, $limit) => array_slice([
|
||||
['title' => 'Açúcar no Corredor da Beira'], ['title' => 'Produção de açúcar'],
|
||||
], $offset, $limit)],
|
||||
'Carteira' => fn () => ['count' => 1, 'fetch' => fn ($offset, $limit) => array_slice([
|
||||
['title' => 'Corredor da Beira'],
|
||||
], $offset, $limit)],
|
||||
];
|
||||
$score = fn ($item) => $search->score($item['title'], $term, $tokens);
|
||||
$service = new FederatedSearch;
|
||||
|
||||
$this->assertSame(['Corredor da Beira', 'Açúcar no Corredor da Beira'], array_column($service->page($sources, 1, 2, $score)['data'], 'title'));
|
||||
$this->assertSame(['Produção de açúcar'], array_column($service->page($sources, 2, 2, $score)['data'], 'title'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,33 @@ use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class SearchTermsTest extends TestCase
|
||||
{
|
||||
public function test_count_questions_select_a_category_instead_of_searching_question_words(): void
|
||||
{
|
||||
$search = new SearchTerms;
|
||||
$intent = $search->countIntent('Quantos corredores existem?');
|
||||
$this->assertSame('corridor', $intent['kind']);
|
||||
$this->assertSame('', $intent['filter']);
|
||||
$this->assertSame('corredores', $intent['label']);
|
||||
$this->assertSame('Oportunidades', $search->countIntent('Quantas oportunidades existem no portal?')['category']);
|
||||
$this->assertSame('em nampula', $search->countIntent('Quantos corredores existem em Nampula?')['filter']);
|
||||
$this->assertSame('cluster', $search->countIntent('Qual é o número de clusters disponíveis?')['kind']);
|
||||
$this->assertNull($search->countIntent('oportunidades nos corredores'));
|
||||
$this->assertNull($search->countIntent('documentos sobre quantos corredores existem'));
|
||||
}
|
||||
|
||||
public function test_investor_requests_distinguish_products_guidance_and_lists(): void
|
||||
{
|
||||
$search = new SearchTerms;
|
||||
$this->assertSame('guide', $search->requestIntent('como licenciar uma empresa')['type']);
|
||||
$this->assertSame('guide', $search->requestIntent('como faço para licenciar a empresa em Nampula?')['type']);
|
||||
$this->assertNull($search->requestIntent('como licenciar software'));
|
||||
$this->assertSame('list', $search->requestIntent('quais são os corredores existentes')['type']);
|
||||
$this->assertSame('Produtos financeiros', $search->requestIntent('produtos financeiros em Nampula')['category']);
|
||||
$this->assertNull($search->requestIntent('tipo de produtos e sua localização')['category']);
|
||||
$this->assertSame('', $search->requestIntent('tipo de produtos e sua localização')['filter']);
|
||||
$this->assertSame('grafite em cabo delgado', $search->requestIntent('onde encontrar grafite em Cabo Delgado?')['filter']);
|
||||
}
|
||||
|
||||
public function test_matches_all_words_in_any_order_without_case_or_accents(): void
|
||||
{
|
||||
$search = new SearchTerms;
|
||||
@@ -56,4 +83,29 @@ final class SearchTermsTest extends TestCase
|
||||
$this->assertGreaterThan($search->score('Como investir', 'investir', ['investir']), $search->score('Investir', 'investir', ['investir']));
|
||||
$this->assertSame(['de'], $search->tokens('de'));
|
||||
}
|
||||
|
||||
public function test_direct_titles_precede_titles_and_descriptions_that_reference_the_query(): void
|
||||
{
|
||||
$search = new SearchTerms;
|
||||
$phrase = 'corredor da beira';
|
||||
$tokens = $search->tokens($phrase);
|
||||
$titles = ['Açúcar no Corredor da Beira', 'Corredor da Beira e investimentos', 'Corredor da Beira', 'Produção de açúcar'];
|
||||
usort($titles, fn ($a, $b) => $search->score($b, $phrase, $tokens) <=> $search->score($a, $phrase, $tokens));
|
||||
|
||||
$this->assertSame(['Corredor da Beira', 'Corredor da Beira e investimentos', 'Açúcar no Corredor da Beira', 'Produção de açúcar'], $titles);
|
||||
$this->assertSame($search->score('Corredor da Beira', $phrase, $tokens), $search->score('CORREDOR DA BEIRA', $phrase, $tokens));
|
||||
}
|
||||
|
||||
public function test_database_relevance_uses_the_same_levels_and_escaped_prefix(): void
|
||||
{
|
||||
$connection = new PostgresConnection(fn () => throw new \LogicException('A database must not be opened.'));
|
||||
$query = $connection->table('records');
|
||||
$search = new SearchTerms;
|
||||
$search->orderByRelevance($query, 'title', '100% açúcar', $search->tokens('100% açúcar'), 'id');
|
||||
|
||||
$this->assertStringContainsString('THEN 1000', $query->toSql());
|
||||
$this->assertStringContainsString('THEN 600', $query->toSql());
|
||||
$this->assertStringContainsString('THEN 400', $query->toSql());
|
||||
$this->assertSame(['100% acucar', '100!% acucar%', '%100!% acucar%'], array_slice($query->getBindings(), 0, 3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const Empty = () => null;
|
||||
function render(section, filters = {}) {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/pages/portal/services.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
const module = { exports: {} };
|
||||
const props = { auth: { user: null } };
|
||||
const mocks = {
|
||||
'lucide-react': {
|
||||
ChevronDown: Empty,
|
||||
Search: Empty,
|
||||
SlidersHorizontal: Empty,
|
||||
},
|
||||
'@inertiajs/react': {
|
||||
Head: Empty,
|
||||
Link: 'a',
|
||||
usePage: () => ({ props, url: '/documentos' }),
|
||||
useForm: (data) => ({ data, setData() {}, get() {} }),
|
||||
},
|
||||
'@/lib/document-facet-label': { documentFacetLabel: (value) => value },
|
||||
'@/lib/portal-presentation': { PORTAL_MORE_LINK: '' },
|
||||
'../../../css/investment-catalogue.css': {},
|
||||
};
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(name) => {
|
||||
if (mocks[name]) return mocks[name];
|
||||
if (name.startsWith('@/'))
|
||||
return new Proxy(
|
||||
{ __esModule: true, default: Empty },
|
||||
{ get: (target, key) => target[key] ?? Empty },
|
||||
);
|
||||
return require(name);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return renderToStaticMarkup(
|
||||
createElement(module.exports.default, {
|
||||
section,
|
||||
filters,
|
||||
topics: ['Fiscalidade'],
|
||||
categories: ['Legislação'],
|
||||
documentTypes: ['guide'],
|
||||
activities: ['CAE exemplo'],
|
||||
stages: ['Etapa exemplo'],
|
||||
modules: ['simulator'],
|
||||
issuers: ['Instituição exemplo'],
|
||||
languages: ['Português'],
|
||||
legalStatuses: ['amended'],
|
||||
territories: [{ id: 'territory', name: 'Cabo Delgado' }],
|
||||
resources: {
|
||||
data: [],
|
||||
total: 0,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
test('biblioteca e legislação mantêm todos os critérios e opções visíveis no painel aberto', () => {
|
||||
for (const section of ['documents', 'legislation']) {
|
||||
const html = render(section);
|
||||
for (const label of [
|
||||
'Pesquisar',
|
||||
'Tema',
|
||||
'Fiscalidade',
|
||||
'Categoria',
|
||||
'Legislação',
|
||||
'Tipo documental',
|
||||
'Guia',
|
||||
'Actividade ou CAE',
|
||||
'CAE exemplo',
|
||||
'Etapa do projecto',
|
||||
'Etapa exemplo',
|
||||
'Módulo',
|
||||
'Simulador fiscal',
|
||||
'Entidade emitente',
|
||||
'Instituição exemplo',
|
||||
'Idioma',
|
||||
'Português',
|
||||
'Situação jurídica indicada',
|
||||
'Alterada; consulte alterações posteriores',
|
||||
'Confirmação da fonte',
|
||||
'Fonte oficial confirmada',
|
||||
'Âmbito territorial',
|
||||
'Cabo Delgado',
|
||||
'Limpar filtros',
|
||||
])
|
||||
assert.ok(html.includes(label), `${section}: ${label}`);
|
||||
assert.match(html, /aria-expanded="true"/);
|
||||
}
|
||||
});
|
||||
|
||||
test('critérios seleccionados continuam acessíveis quando já não constam das opções', () => {
|
||||
const html = render('documents', {
|
||||
topic: 'Tema antigo',
|
||||
activity: ['CAE antigo'],
|
||||
stage: ['Etapa antiga'],
|
||||
module: ['outro'],
|
||||
territory_id: 'old-territory',
|
||||
});
|
||||
for (const value of [
|
||||
'Tema antigo',
|
||||
'CAE antigo',
|
||||
'Etapa antiga',
|
||||
'Documentos de apoio',
|
||||
'old-territory',
|
||||
'Localização seleccionada indisponível',
|
||||
])
|
||||
assert.ok(html.includes(value), value);
|
||||
});
|
||||
@@ -35,6 +35,53 @@ new Function('require', 'module', 'exports', compiled)(
|
||||
);
|
||||
const Search = module.exports.default;
|
||||
|
||||
test('product categories preserve the location filter and pagination even without a query', () => {
|
||||
const results = { data: [{ title: 'Grafite', description: '', category: 'Produtos e localizações', url: '/sectores/mineracao' }], total: 6, current_page: 1, last_page: 2, per_page: 5, unavailable: [] };
|
||||
const html = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: 'Nampula', results,
|
||||
answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: 'Nampula', category: 'physical' },
|
||||
}));
|
||||
assert.match(html, /q=Nampula&category=financial/);
|
||||
assert.match(html, /q=Nampula&page=2&category=physical/);
|
||||
assert.match(html, /name="category" value="physical"/);
|
||||
const all = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: '', results, answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: '', category: 'all' },
|
||||
}));
|
||||
assert.match(all, /href="\/sectores\/mineracao"/);
|
||||
});
|
||||
|
||||
test('count answer is explicit and zero is distinct from an unavailable count', () => {
|
||||
const results = { data: [], total: 0, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
|
||||
const html = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: 'quantos corredores existem', results,
|
||||
answer: { type: 'count', label: 'corredores', count: 0, filter: '' },
|
||||
}));
|
||||
assert.match(html, /0 corredores/);
|
||||
assert.match(html, /registos publicados/);
|
||||
const failed = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: 'quantos corredores existem', results,
|
||||
answer: { type: 'count', label: 'corredores', count: null, filter: '' },
|
||||
}));
|
||||
assert.match(failed, /Contagem indisponível/);
|
||||
assert.doesNotMatch(failed, /0 corredores/);
|
||||
});
|
||||
|
||||
test('products show their location separately from financial coverage and guidance has no invented count', () => {
|
||||
const results = { data: [{ title: 'Banco de ensaio', description: 'Crédito PME', location: 'Presença física: Maputo', coverage: 'Cobertura nacional', category: 'Produtos financeiros', url: '/fundos/qa' }], total: 1, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
|
||||
const html = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: 'produtos financeiros', results, answer: { type: 'products', label: 'Produtos e localização', count: 1, filter: '' },
|
||||
}));
|
||||
assert.match(html, /Produtos financeiros/);
|
||||
assert.match(html, /Presença física: Maputo/);
|
||||
assert.match(html, /Cobertura nacional/);
|
||||
assert.match(html, /não determina a cobertura/);
|
||||
const guide = renderToStaticMarkup(React.createElement(Search, {
|
||||
query: 'como licenciar empresa', results: { ...results, data: [] }, answer: { type: 'guide', label: 'Licenciamento da empresa', count: 2, filter: 'licenciamento' },
|
||||
}));
|
||||
assert.match(guide, /Licenciamento da empresa/);
|
||||
assert.doesNotMatch(guide, /2 Licenciamento/);
|
||||
});
|
||||
|
||||
test('shows five results in one sequence with numbered pagination and the query preserved', () => {
|
||||
const results = {
|
||||
data: [
|
||||
|
||||
@@ -29,6 +29,8 @@ compileFunction(compiled, ['require', 'module', 'exports'])(
|
||||
);
|
||||
const Component = module.exports.default;
|
||||
const filterIndicators = module.exports.filterMapIndicators;
|
||||
const compareObservations = module.exports.compareMapObservations;
|
||||
const Comparison = module.exports.MapObservationComparison;
|
||||
const row = {
|
||||
id: '1',
|
||||
zone_id: 'park-a',
|
||||
@@ -219,3 +221,84 @@ test('quantitative filters are labelled, scoped and explain source date and cove
|
||||
assert.match(html, /não alteram oportunidades ou limites de cobertura/);
|
||||
assert.match(html, /Limpar filtros dos indicadores/);
|
||||
});
|
||||
|
||||
test('comparison delta: metadata alignment never manufactures a trend or changes exact source values', () => {
|
||||
const first = {
|
||||
...row,
|
||||
description: 'Emprego observado na fonte sintética.',
|
||||
value: '1234567890123.456789',
|
||||
};
|
||||
const second = {
|
||||
...first,
|
||||
id: 'next-period',
|
||||
period_start: '2026-01-01',
|
||||
period_end: '2026-12-31',
|
||||
value: '0',
|
||||
};
|
||||
const before = JSON.stringify([first, second]);
|
||||
assert.equal(compareObservations(first, second).state, 'metadata_aligned');
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Comparison, { first, second }),
|
||||
);
|
||||
assert.match(html, /1234567890123\.456789/);
|
||||
assert.match(html, />0</);
|
||||
assert.match(html, /confirme nas fontes/);
|
||||
assert.match(html, /não calcula evolução/);
|
||||
assert.ok(!html.includes('<script>synthetic source</script>'));
|
||||
assert.match(html, /<script>synthetic source/);
|
||||
assert.equal(JSON.stringify([first, second]), before);
|
||||
});
|
||||
|
||||
test('comparison delta: differences, missing evidence, unknown values and disputed information require review', () => {
|
||||
const documented = {
|
||||
...row,
|
||||
description: 'Emprego observado na fonte sintética.',
|
||||
};
|
||||
const second = { ...documented, id: 'different' };
|
||||
assert.equal(
|
||||
compareObservations(documented, second).state,
|
||||
'metadata_aligned',
|
||||
);
|
||||
for (const change of [
|
||||
{ zone_id: 'other' },
|
||||
{ indicator: 'exports' },
|
||||
{ unit: 'USD' },
|
||||
{ scope: 'other base' },
|
||||
{ population: 'other population' },
|
||||
{ methodology: 'other method' },
|
||||
{ knowledge: 'disputed' },
|
||||
{ knowledge: 'unknown', value: null },
|
||||
{ value: 'NaN' },
|
||||
{ source_reference: '' },
|
||||
{ description: '' },
|
||||
{ source_date: '2026-02-30' },
|
||||
{ period_end: '2024-01-01' },
|
||||
]) {
|
||||
const result = compareObservations(documented, {
|
||||
...second,
|
||||
...change,
|
||||
});
|
||||
assert.equal(result.state, 'review_required', JSON.stringify(change));
|
||||
assert.ok(result.issues.length);
|
||||
}
|
||||
assert.equal(compareObservations(row, row).state, 'review_required');
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Comparison, {
|
||||
first: row,
|
||||
second: { ...second, knowledge: 'unknown', value: null },
|
||||
}),
|
||||
);
|
||||
assert.match(html, /Por confirmar/);
|
||||
assert.match(html, /lacunas a conferir/);
|
||||
});
|
||||
|
||||
test('comparison delta: progressive selection stays inside the received filters and shows an incomplete pair explicitly', () => {
|
||||
const html = render(context);
|
||||
assert.match(html, /Comparar duas observações/);
|
||||
assert.match(html, /Primeira.*observação/);
|
||||
assert.match(html, /Segunda.*observação/);
|
||||
assert.match(html, /uma versão nova exige nova selecção/);
|
||||
assert.match(html, /Seleccione duas observações/);
|
||||
const single = render({ ...context, records: [row] });
|
||||
assert.ok(!single.includes('Comparar duas observações'));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import { createInvestorStageReport } from '../../resources/js/lib/investor-dossier-report.ts';
|
||||
import {
|
||||
createProjectDossierPrintHtml,
|
||||
generateProjectDossierDocx,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
const input = {
|
||||
case: {
|
||||
id: 'synthetic-stage-dossier',
|
||||
title: 'Ensaio sintético',
|
||||
version: 3,
|
||||
},
|
||||
context_opportunity: null,
|
||||
opportunity_options: [],
|
||||
investment_context: {
|
||||
revision: 1,
|
||||
fields: { project_title: 'Fábrica sintética', province: 'Sofala' },
|
||||
},
|
||||
phases: { 1: 'Preparação sintética' },
|
||||
results: [],
|
||||
documents: [],
|
||||
steps: Array.from({ length: 19 }, (_, i) => ({
|
||||
code: `S${String(i + 1).padStart(2, '0')}`,
|
||||
title: `Etapa sintética ${i + 1}`,
|
||||
phase: 1,
|
||||
version: i + 2,
|
||||
state: 'preparing',
|
||||
reason: `Fundamento sintético exclusivo ${i + 1}.`,
|
||||
detail: { recorded_at: '2026-11-13' },
|
||||
})),
|
||||
};
|
||||
|
||||
void test('all 19 stage reports can be consulted and exported without inventing outcomes or changing source data', async () => {
|
||||
const before = JSON.stringify(input);
|
||||
for (const step of input.steps) {
|
||||
const model = createInvestorStageReport(
|
||||
input,
|
||||
step.code,
|
||||
'2026-11-13T15:00:00Z',
|
||||
);
|
||||
assert.match(model.title, new RegExp(step.code));
|
||||
const execution = model.sections.find((s) => s.id === 'execution');
|
||||
assert.equal(execution.rows.length, 1);
|
||||
assert.ok(execution.rows[0].value.includes(step.reason));
|
||||
assert.ok(
|
||||
model.sections
|
||||
.find((s) => s.id === 'summary')
|
||||
.rows.every((r) => r.field.startsWith(step.code)),
|
||||
);
|
||||
assert.ok(
|
||||
!model.sections.some((s) => s.id === 'finance') ||
|
||||
step.code === 'S03',
|
||||
);
|
||||
const html = await createProjectDossierPrintHtml(model, [], true);
|
||||
assert.ok(html.includes(step.reason));
|
||||
assert.ok(html.includes('synthetic-stage-dossier'));
|
||||
const blob = await generateProjectDossierDocx(model, [], true);
|
||||
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||
const xml = await zip.file('word/document.xml').async('string');
|
||||
assert.ok(xml.includes(step.reason));
|
||||
assert.ok(xml.includes('não cria documentos'));
|
||||
}
|
||||
assert.equal(JSON.stringify(input), before);
|
||||
assert.throws(
|
||||
() => createInvestorStageReport(input, 'S99'),
|
||||
/não encontrada/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
createInvestorStageReport(
|
||||
{ ...input, opportunity_options: ['a', 'b'] },
|
||||
'S01',
|
||||
),
|
||||
/Seleccione/,
|
||||
);
|
||||
});
|
||||
|
||||
void test('exported limitations retain literal text and cannot inject active HTML', async () => {
|
||||
const model = createInvestorStageReport(input, 'S08');
|
||||
model.limitations.push('Limite <script>alert(1)</script> & origem');
|
||||
const html = await createProjectDossierPrintHtml(model, [], true);
|
||||
assert.ok(
|
||||
html.includes(
|
||||
'Limite <script>alert(1)</script> & origem',
|
||||
),
|
||||
);
|
||||
assert.ok(!html.includes('<script>alert(1)</script>'));
|
||||
const zip = await JSZip.loadAsync(
|
||||
await (await generateProjectDossierDocx(model, [], true)).arrayBuffer(),
|
||||
);
|
||||
assert.ok(
|
||||
(await zip.file('word/document.xml').async('string')).includes(
|
||||
'Limite <script>alert(1)</script> & origem',
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,7 @@ function load(file, page) {
|
||||
const module = { exports: {} };
|
||||
const aliases = new Proxy({ default: Empty }, { get: (target, name) => name in target ? target[name] : Empty });
|
||||
compileFunction(code, ['require', 'module', 'exports'])((name) => {
|
||||
if (name.endsWith('.css')) return {};
|
||||
if (name === 'lucide-react') return aliases;
|
||||
if (name === '@inertiajs/react') return {
|
||||
Link: 'a', Head: Empty, usePage: () => page,
|
||||
|
||||
Reference in New Issue
Block a user