resolucao dos inputs das provincias, distritos, localidades
tests / ci (push) Waiting to run

This commit is contained in:
2026-09-30 12:59:28 +02:00
parent 3dc7c5c649
commit 3395424d82
13 changed files with 355 additions and 92 deletions
+5
View File
@@ -66,5 +66,10 @@ jobs:
- name: Run CI Checks - name: Run CI Checks
run: composer ci:check run: composer ci:check
- name: Validate PostgreSQL/PostGIS schema lifecycle
env:
INVESTMOZ_SCHEMA_TESTS: '1'
run: php vendor/bin/phpunit --configuration=phpunit.investmoz.xml --do-not-cache-result
- name: Test frontend API contracts - name: Test frontend API contracts
run: node --test tests/frontend/portal-api.test.mjs run: node --test tests/frontend/portal-api.test.mjs
+4 -1
View File
@@ -62,7 +62,9 @@ class EducationController extends Controller
'providers' => TrainingProvider::where('status', '!=', 'inactive')->orderBy('name')->get(['id', 'name']), 'providers' => TrainingProvider::where('status', '!=', 'inactive')->orderBy('name')->get(['id', 'name']),
'courses' => Course::where('status', '!=', 'retired')->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'))->orderBy('title')->get(['id', 'title', 'provider_id']), 'courses' => Course::where('status', '!=', 'retired')->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'))->orderBy('title')->get(['id', 'title', 'provider_id']),
'projects' => Project::orderBy('name')->get(['id', 'code', 'name']), 'projects' => Project::orderBy('name')->get(['id', 'code', 'name']),
'territories' => DB::table('geo_locations')->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'code']), 'territories' => DB::table('geo_locations')->whereNull('deleted_at')
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']),
'today' => now()->toDateString(), 'today' => now()->toDateString(),
]); ]);
} }
@@ -148,6 +150,7 @@ class EducationController extends Controller
return Inertia::render('education/analysis', ['demand' => $demand, 'candidates' => $candidates, return Inertia::render('education/analysis', ['demand' => $demand, 'candidates' => $candidates,
'proposal' => EducationInvestmentProposal::where('labour_demand_id', $id)->first(), 'proposal' => EducationInvestmentProposal::where('labour_demand_id', $id)->first(),
'sectors' => Sector::orderBy('name')->get(['id', 'name']), 'sectors' => Sector::orderBy('name')->get(['id', 'name']),
'territoryPath' => app(InvestmentGeography::class)->path($demand->getAttribute('geo_location_id'), true),
'eligible' => $eligible, 'gap' => $calculator->observed((int) $demand->getAttribute('quantity'), null, $eligible, $current)]); 'eligible' => $eligible, 'gap' => $calculator->observed((int) $demand->getAttribute('quantity'), null, $eligible, $current)]);
} }
} }
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Models\EducationInvestmentProposal; use App\Models\EducationInvestmentProposal;
use App\Models\LabourDemand; use App\Models\LabourDemand;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Services\InvestmentGeography;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -27,6 +28,10 @@ class EducationInvestmentController extends Controller
'risks' => ['required', 'string', 'min:10', 'max:5000'], 'risks' => ['required', 'string', 'min:10', 'max:5000'],
'source' => ['required', 'string', 'min:10', 'max:5000'], 'source' => ['required', 'string', 'min:10', 'max:5000'],
'currency' => ['required', Rule::in(['MZN', 'USD', 'EUR', 'ZAR'])], 'currency' => ['required', Rule::in(['MZN', 'USD', 'EUR', 'ZAR'])],
'province_id' => ['required', 'uuid'],
'district_id' => ['nullable', 'uuid'],
'admin_post_id' => ['nullable', 'uuid'],
'locality_id' => ['nullable', 'uuid'],
]); ]);
DB::transaction(function () use ($request, $id, $data): void { DB::transaction(function () use ($request, $id, $data): void {
@@ -38,6 +43,10 @@ class EducationInvestmentController extends Controller
if (EducationInvestmentProposal::withTrashed()->where('labour_demand_id', $id)->exists()) { if (EducationInvestmentProposal::withTrashed()->where('labour_demand_id', $id)->exists()) {
return; return;
} }
$territory = app(InvestmentGeography::class)->selection($data, true);
$province = $territory[0];
$district = $territory[1] ?? null;
$primaryTerritory = $territory[array_key_last($territory)];
$reference = 'EDU-'.Str::uuid(); $reference = 'EDU-'.Str::uuid();
$opportunity = new Opportunity; $opportunity = new Opportunity;
PortalAudit::save($opportunity, [ PortalAudit::save($opportunity, [
@@ -45,6 +54,8 @@ class EducationInvestmentController extends Controller
'slug' => strtolower($reference), 'title' => $data['title'], 'slug' => strtolower($reference), 'title' => $data['title'],
'summary' => 'Proposta educativa em preparação. Lacuna e viabilidade pendentes de validação institucional.', 'summary' => 'Proposta educativa em preparação. Lacuna e viabilidade pendentes de validação institucional.',
'description' => $data['intervention'], 'estimated_investment_currency' => $data['currency'], 'description' => $data['intervention'], 'estimated_investment_currency' => $data['currency'],
'province' => $province->name, 'district' => $district?->name,
'primary_territory_id' => $primaryTerritory->id, 'territory_version' => 1,
'status' => 'draft', 'is_featured' => false, 'status' => 'draft', 'is_featured' => false,
], $request->user()->id); ], $request->user()->id);
PortalAudit::save(new EducationInvestmentProposal, [ PortalAudit::save(new EducationInvestmentProposal, [
@@ -24,7 +24,7 @@ class InvestmentDiscoveryController extends Controller
$filters['education'] = true; $filters['education'] = true;
} }
return Inertia::render('investment/catalogue', ['filters' => $filters, 'references' => $catalogue->references(), return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(),
'territorySelection' => app(InvestmentGeography::class)->selection($filters), 'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(), 'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [], 'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
@@ -0,0 +1,96 @@
# Execução do plano de remediação — 30/09/2026
## Resumo
Linha de base: branch `main`, commit `3dc7c5c649d433527e2e261e33b8d45eb9e71bd8`,
árvore limpa antes desta remediação. A auditoria de 25/09 tinha uma conclusão de
CI desactualizada: o workflow actual já usa PHP 8.5 e disponibiliza PostgreSQL /
PostGIS 17-3.5. A lacuna reproduzível era o teste protegido de ciclo de esquema
não ser invocado pelo workflow.
Foi adicionado ao CI um passo dedicado para executar
`tests/InvestMoz/SchemaLifecycleTest.php` contra o serviço PostgreSQL efémero do
job. O teste exige explicitamente `INVESTMOZ_SCHEMA_TESTS=1`, valida que o nome
da base termina em `_test` e recusa configuração em cache antes de executar
`migrate:fresh`. Não houve ligação a produção nem alteração de bases de dados
nesta sessão.
**Decisão global: No-Go.** O reforço do CI não fecha as lacunas funcionais e
operacionais da matriz de requisitos.
## Salvaguardas e ambiente
- Git confirmou `main` e a árvore limpa no início. Não criei commit.
- Versões locais observadas: PHP 8.5.0, Laravel 13.30.1, Node 24.20.0 e npm 11.19.0.
- O workflow executa num job Ubuntu e num serviço PostgreSQL/PostGIS efémero,
com base `investmoz_test` e credenciais exclusivas do job.
- Não há Docker, `psql` ou `pg_isready` instalados localmente. Não foi possível
confirmar ou criar uma instância local descartável.
- Nenhum segredo foi lido ou incluído neste documento. Nenhuma base de dados,
credencial ou serviço externo foi alterado.
## Matriz de remediação
| ID | Domínio | Severidade / causa-raiz | Acção correctiva | Responsável sugerido / dependências | Esforço inicial* | Evidência e critério de aceitação | Estado |
| ---------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------- |
| REM-CI-01 | CI / esquema | Alta: o teste de ciclo do esquema era ignorado sem `INVESTMOZ_SCHEMA_TESTS=1`. | Adicionado passo explícito ao workflow, dirigido ao serviço efémero PostGIS. | DevOps; depende de execução GitHub Actions. | Pequeno, 1–2 horas | Job GitHub Actions verde; teste dedicado sem skip e com resultado aprovado. | Implementado; execução remota Não verificada. |
| REM-DOC-01 | Rastreabilidade | Baixa: auditoria de 25/09 afirmava PHP 8.3 e ausência de PostgreSQL no workflow actual. | Corrigida a conclusão e identificada a data histórica das outras classificações. | Manutenção técnica; sem dependência externa. | Pequeno, menos de 1 hora | Documento corresponde ao YAML actual; diferenças funcionais continuam explicitamente abertas. | Corrigido por inspecção estática. |
| REM-GEO-01 | GIS / dados oficiais | Crítica: testes de esquema não provam importação oficial, desempenho representativo ou permissões no ambiente-alvo. | Validar por domínio sem tocar dados até existir fonte e ambiente aprovados. | Responsáveis GIS/dados + backend; depende de dados licenciados e staging descartável. | Grande, 1–2 semanas (estimativa) | Origem/licença, SRID, reconciliação, testes espaciais, perfis e tempos reproduzíveis. | Pendente; Não verificado. |
| REM-SEC-01 | Segurança / privacidade | Crítica: sem evidência nesta sessão de pentest, revisão completa de perfis, retenção e base legal. | Revisão de segurança e validação jurídica com responsáveis competentes. | AppSec, privacidade e assessoria jurídica; depende de requisitos e perfis aprovados. | Grande, 1–2 semanas (estimativa) | Matriz de permissões aprovada, achados tratados e requisitos legais referenciados. | Pendente; Não verificado. |
| REM-OPS-01 | Operação / recuperação | Alta: deploy descrito, mas backup/restauro, monitorização e resposta não demonstrados no alvo. | Ensaio de restauro isolado e validação operacional. | SRE/infraestrutura; depende do ambiente-alvo e política de backup. | Médio/grande, 3–5 dias (estimativa) | Restore reproduzível, health checks, alertas e runbook exercitado. | Pendente; Não verificado. |
| REM-BIZ-01 | Âmbito funcional | Crítica: matriz de 25/09 identifica requisitos de CRM, negócios, jornadas, integrações e outros domínios incompletos. | Priorizar com proprietário funcional; implementar por domínio com critérios aprovados. | Proprietário do produto + líderes de domínio; depende de MVP aprovado. | Extra grande, por fases (estimativa não aprovada) | Fluxos críticos aprovados ponta a ponta e rastreados a requisitos e testes. | Pendente; Não conforme para aceite integral. |
\* Estimativas de planeamento preliminares, não aprovadas; devem ser revistas pelos responsáveis após decomposição do trabalho.
## Alterações realizadas
- `.github/workflows/tests.yml`: acrescentado o passo “Validate PostgreSQL/PostGIS
schema lifecycle”, com `INVESTMOZ_SCHEMA_TESTS=1` e a configuração PHPUnit
dedicada. O serviço já existente no workflow é efémero e tem nome de base
terminado em `_test`.
- `docs/investmoz/requirements-audit.md`: corrigida a afirmação obsoleta sobre
versão PHP e ausência de serviço PostGIS; registado que o resultado remoto
continua por verificar e que a decisão funcional global não muda.
- `docs/investmoz/remediation-execution-2026-09-30.md`: criado este registo,
incluindo matriz, salvaguardas e evidência pendente.
Não foram removidos ficheiros, requisitos, testes ou controlos. Não foram
alteradas migrations, dados, dependências, contratos de API ou credenciais.
## Verificações desta sessão
| Verificação | Comando / método | Resultado |
| ----------------------------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Branch, commit e estado inicial | `git status --short --branch`; `git rev-parse HEAD` | `main`, commit `3dc7c5c…`, limpo antes das alterações. |
| Versões locais | `php -v`; `php artisan --version`; `node.exe --version`; `npm.cmd --version` | PHP 8.5.0, Laravel 13.30.1, Node 24.20.0, npm 11.19.0. |
| Workflow actual | Inspecção de `.github/workflows/tests.yml` | PHP 8.5, serviço `postgis/postgis:17-3.5`, credenciais limitadas ao job. |
| Protecção do teste | Inspecção de `SchemaLifecycleTest.php` e `phpunit.investmoz.xml` | Teste exige opt-in, ambiente `testing`, driver pgsql, nome `_test` e ausência de config cache antes de `migrate:fresh`. |
| Testes API frontend | `node.exe --test tests/frontend/portal-api.test.mjs` | Aprovado: 13 testes, 0 falhas. |
| TypeScript | `npm.cmd run types:check` | Aprovado (`tsc --noEmit`). |
| PHPStan | `php vendor/bin/phpstan analyse --no-progress --debug --memory-limit=512M` | Aprovado: 0 erros. A primeira execução falhou no limite local de 128 MB; repetida sem workers paralelos com 512 MB. |
| Composer | `composer validate --no-check-publish` | Aprovado. |
| Formatação dos ficheiros alterados | `vp check --no-lint .github/workflows/tests.yml docs/investmoz/remediation-execution-2026-09-30.md` | Aprovada para o documento; o verificador não reporta YAML como ficheiro formatável. |
| Formatação PHP global | `php vendor/bin/pint --test` | Falhou em 2 ficheiros PHP preexistentes não alterados: migration `2026_09_28_160000_investment_primary_territory.php` e `tools/test-mne-integrity.php`. |
| Check frontend global | `npm.cmd run check` | Falhou por 103 ficheiros fora do padrão no primeiro scan; não apliquei autofix em massa. TypeScript passou separadamente. |
| Integridade do diff | `git diff --check` | Aprovado; sem whitespace errors. |
| Protecção local do teste de esquema | `php vendor/bin/phpunit --configuration=phpunit.investmoz.xml --do-not-cache-result` sem opt-in | PHPUnit terminou com 1 teste ignorado pela guarda, 0 asserções; não ligou à base de dados. |
| Ciclo de esquema PostgreSQL/PostGIS | Não executado localmente | Sem servidor/cliente PostgreSQL local; ligação do PHPUnit não pôde ser comprovada como descartável. A execução real foi delegada ao serviço efémero no CI. |
| Sintaxe YAML do workflow | Não verificada por parser dedicado | Python, Ruby, Docker e actionlint não estão disponíveis; a inspecção estática não substitui validação pelo GitHub Actions. |
| Resultado GitHub Actions | Não disponível nesta sessão | Não afirmar aprovação do pipeline até execução do workflow alterado. |
## Pendências, reversão e aceitação
Para reverter apenas esta remediação, remover o passo dedicado do workflow e
restaurar o texto histórico em `requirements-audit.md`; manter o registo desta
execução como evidência histórica, assinalando a reversão. A alteração do CI só
afecta o job efémero e não requer reversão de dados.
O critério de encerramento de REM-CI-01 é um run verde do workflow no commit que
contém a alteração, com o teste dedicado efectivamente executado. O critério de
Go global continua a exigir os gates funcionais, geográficos, de segurança,
integridade, desempenho, operação, legalidade e recuperação; esses gates não
foram satisfeitos nem reavaliados nesta sessão.
Nenhuma evidência foi fabricada. Os resultados históricos permanecem atribuídos
às respectivas datas e ambientes; tudo o que não foi reproduzido está marcado
como Não verificado ou pendente.
+17 -5
View File
@@ -98,11 +98,14 @@ O próprio DOCX contém uma frase auto-contraditória na precedência de A.31
(parágrafo 6932); conservar a reconciliação aprovada e resolver a documentação, (parágrafo 6932); conservar a reconciliação aprovada e resolver a documentação,
sem executar cegamente os blocos históricos. sem executar cegamente os blocos históricos.
**Falha concreta de CI:** `.github/workflows/tests.yml` configura PHP 8.3, enquanto **Actualização em 30/09/2026:** a observação de CI acima, registada na auditoria de
vendor/composer/platform_check.php exige >=8.4.1. Também não provisiona serviço 25/09, ficou desactualizada. O workflow actual configura PHP 8.5 e provisiona um
PostgreSQL/PostGIS, embora os testes e migrations precisem dele. Existe workflow, serviço `postgis/postgis:17-3.5` para o job. A lacuna reproduzível era outra: o
mas a sua execução bem sucedida com o projecto actual não está comprovada. Não foi teste `SchemaLifecycleTest` exige `INVESTMOZ_SCHEMA_TESTS=1`, mas o workflow não
executada nem alterada nesta auditoria. activava esse teste destrutivo protegido. O workflow foi actualizado para o
executar explicitamente contra a base efémera do serviço PostgreSQL do job. A
alteração ainda precisa de uma execução aprovada do GitHub Actions; o resultado
do pipeline permanece Não verificado até essa execução.
`decisions.md` continua útil, mas não está totalmente actualizado: P-14 recebeu `decisions.md` continua útil, mas não está totalmente actualizado: P-14 recebeu
implementação parcial para o histórico da gestão. Isso não conclui a auditoria implementação parcial para o histórico da gestão. Isso não conclui a auditoria
@@ -126,3 +129,12 @@ transversal nem resolve automaticamente as restantes decisões.
staging e validação operacional antes da publicação integral. staging e validação operacional antes da publicação integral.
Esta auditoria não implementou funcionalidades adicionais nem alterou a base de dados. Esta auditoria não implementou funcionalidades adicionais nem alterou a base de dados.
## Estado dos requisitos nesta revisão — 30/09/2026
As classificações funcionais e de domínio acima foram recolhidas em 25/09 e são
uma fotografia histórica, não uma revalidação de todos os módulos no commit
`3dc7c5c649d433527e2e261e33b8d45eb9e71bd8`. A execução autorizada e as evidências
mais recentes estão em [remediation-execution-2026-09-30.md](remediation-execution-2026-09-30.md).
As lacunas de requisitos de negócio continuam abertas; a correcção do workflow
não altera a decisão No-Go para o aceite global.
@@ -13,9 +13,86 @@ type Option = TerritoryOption;
const levels = ["province", "district", "admin_post", "locality"]; const levels = ["province", "district", "admin_post", "locality"];
const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"]; const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"];
const control = "w-full rounded border bg-background p-2 text-foreground"; const control = "w-full rounded border bg-background p-2 text-foreground";
const emptyTerritoryPath: TerritoryOption[] = [];
export function ProvinceSelect({
value,
onChange,
endpoint = "/api/v1/investment/territory-options",
placeholder = "Seleccione uma província",
className = control,
label = "Província",
required = false,
}: {
value: string;
onChange: (value: string) => void;
endpoint?: string;
placeholder?: string;
className?: string;
label?: string;
required?: boolean;
}) {
const id = useId();
const [options, setOptions] = useState<Option[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [retry, setRetry] = useState(0);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError("");
fetch(`${endpoint}?type=province&page=1`, {
signal: controller.signal,
headers: { Accept: "application/json" },
})
.then(async (response) => {
if (!response.ok) throw new Error("Não foi possível carregar as províncias.");
return response.json();
})
.then((data) => setOptions(data.data))
.catch((cause) => {
if (!controller.signal.aborted)
setError(cause instanceof Error ? cause.message : "Erro de ligação.");
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [endpoint, retry]);
return (
<>
<select
id={id}
aria-label={label}
className={className}
required={required}
value={options.some((option) => option.name === value) ? value : ""}
disabled={loading || Boolean(error)}
onChange={(event) => onChange(event.target.value)}
>
<option value="">{loading ? "A carregar províncias…" : placeholder}</option>
{options.map((option) => (
<option key={option.id} value={option.name}>
{option.name}
</option>
))}
</select>
{error && (
<span role="alert" className="block text-sm">
{error}{" "}
<button type="button" onClick={() => setRetry((current) => current + 1)}>
Tentar novamente
</button>
</span>
)}
</>
);
}
export function TerritoryFields({ export function TerritoryFields({
initial = [], initial = emptyTerritoryPath,
onChange, onChange,
endpoint = "/api/v1/investment/territory-options", endpoint = "/api/v1/investment/territory-options",
}: { }: {
@@ -24,6 +101,7 @@ export function TerritoryFields({
endpoint?: string; endpoint?: string;
}) { }) {
const [path, setPath] = useState(initial); const [path, setPath] = useState(initial);
useEffect(() => setPath(initial), [initial]);
return ( return (
<div className="grid gap-4 md:col-span-full md:grid-cols-2"> <div className="grid gap-4 md:col-span-full md:grid-cols-2">
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map( {(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
@@ -64,7 +142,6 @@ export function TerritoryLevel({
fieldError?: string; fieldError?: string;
}) { }) {
const id = useId(); const id = useId();
const [q, setQ] = useState("");
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [options, setOptions] = useState<Option[]>([]); const [options, setOptions] = useState<Option[]>([]);
const [more, setMore] = useState(false); const [more, setMore] = useState(false);
@@ -85,7 +162,6 @@ export function TerritoryLevel({
const params = new URLSearchParams({ const params = new URLSearchParams({
type: levels[index], type: levels[index],
parent_id: parent, parent_id: parent,
q,
page: String(page), page: String(page),
}); });
const response = await fetch(`${endpoint}?${params}`, { const response = await fetch(`${endpoint}?${params}`, {
@@ -108,23 +184,12 @@ export function TerritoryLevel({
clearTimeout(timer); clearTimeout(timer);
controller.abort(); controller.abort();
}; };
}, [index, parent, q, page, enabled, endpoint, retry]); }, [index, parent, page, enabled, endpoint, retry]);
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<label htmlFor={id} className="font-medium"> <label htmlFor={id} className="font-medium">
{labels[index]} {labels[index]}
</label> </label>
<input
className={control}
aria-label={`Pesquisar ${labels[index]}`}
disabled={!enabled}
value={q}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
}}
placeholder="Pesquisar por código ou nome"
/>
<select <select
id={id} id={id}
aria-invalid={Boolean(fieldError)} aria-invalid={Boolean(fieldError)}
+5 -25
View File
@@ -1,6 +1,7 @@
import { createContext, useContext, useRef, useState } from "react"; import { createContext, useContext, useRef, useState } from "react";
import { router } from "@inertiajs/react"; import { router } from "@inertiajs/react";
import { PortalMenu } from "@/layouts/portal-navigation"; import { PortalMenu } from "@/layouts/portal-navigation";
import { ProvinceSelect } from "@/components/investment-territory";
import { MATURITY_LEVELS } from "@/lib/investment-maturity"; import { MATURITY_LEVELS } from "@/lib/investment-maturity";
import type { Dispatch, FormEvent, ReactNode, SetStateAction } from "react"; import type { Dispatch, FormEvent, ReactNode, SetStateAction } from "react";
import type { LucideIcon } from "lucide-react"; import type { LucideIcon } from "lucide-react";
@@ -81,21 +82,6 @@ function QueryStatus({
); );
} }
const PROVINCES = [
"Maputo Cidade",
"Maputo Província",
"Gaza",
"Inhambane",
"Sofala",
"Manica",
"Tete",
"Zambézia",
"Nampula",
"Cabo Delgado",
"Niassa",
];
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Componentes */ /* Componentes */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
@@ -386,18 +372,12 @@ function OpportunitiesView({
</option> </option>
))} ))}
</select> </select>
<select <ProvinceSelect
value={filters.province} value={filters.province}
onChange={(e) => changeFilters({ ...filters, province: e.target.value })} onChange={(province) => changeFilters({ ...filters, province })}
placeholder="Todas as províncias"
className="rounded-lg border border-slate-200 px-3 py-2 text-sm" className="rounded-lg border border-slate-200 px-3 py-2 text-sm"
> />
<option value="">Todas as províncias</option>
{PROVINCES.map((p) => (
<option key={p} value={p}>
{p}
</option>
))}
</select>
<select <select
value={filters.maturity} value={filters.maturity}
onChange={(e) => changeFilters({ ...filters, maturity: e.target.value })} onChange={(e) => changeFilters({ ...filters, maturity: e.target.value })}
+6 -3
View File
@@ -2,6 +2,7 @@ import { Link, router, useForm } from "@inertiajs/react";
import { useState } from "react"; import { useState } from "react";
import { Management, Field, control, button } from "../management/shared"; import { Management, Field, control, button } from "../management/shared";
import { capabilities, purposes, states } from "./labels"; import { capabilities, purposes, states } from "./labels";
import { ProvinceSelect } from "@/components/investment-territory";
type Source = { type Source = {
id: string; id: string;
@@ -157,10 +158,12 @@ export default function Index({ controls, sources, documents, runs, today }: Pro
{query.data.capability === "recommend" && ( {query.data.capability === "recommend" && (
<> <>
<Field label={t("Província declarada", "Declared province")}> <Field label={t("Província declarada", "Declared province")}>
<input <ProvinceSelect
className={control}
value={query.data.province} value={query.data.province}
onChange={(e) => query.setData("province", e.target.value)} onChange={(province) => query.setData("province", province)}
className={control}
placeholder={t("Seleccione uma província", "Select a province")}
label={t("Província declarada", "Declared province")}
/> />
</Field> </Field>
<Field label={t("Maturidade pretendida", "Desired maturity")}> <Field label={t("Maturidade pretendida", "Desired maturity")}>
+46 -1
View File
@@ -1,5 +1,7 @@
import { Link, useForm } from "@inertiajs/react"; import { Link, useForm } from "@inertiajs/react";
import { useState } from "react";
import { Management, Field, control, button } from "../management/shared"; import { Management, Field, control, button } from "../management/shared";
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
export default function Analysis({ export default function Analysis({
demand, demand,
candidates, candidates,
@@ -7,8 +9,15 @@ export default function Analysis({
gap, gap,
proposal, proposal,
sectors, sectors,
territoryPath,
}: { }: {
demand: { id: string; version_no: number; quantity: number; qualification: string }; demand: {
id: string;
version_no: number;
quantity: number;
qualification: string;
geo_location_id: string;
};
candidates: { candidates: {
id: string; id: string;
quantity: number; quantity: number;
@@ -29,7 +38,9 @@ export default function Analysis({
source: string; source: string;
} | null; } | null;
sectors: { id: number; name: string }[]; sectors: { id: number; name: string }[];
territoryPath: TerritoryOption[];
}) { }) {
const [selectedTerritory, setSelectedTerritory] = useState(territoryPath);
const form = useForm({ const form = useForm({
demand_version: demand.version_no, demand_version: demand.version_no,
sector_id: "", sector_id: "",
@@ -41,12 +52,19 @@ export default function Analysis({
risks: "", risks: "",
source: "", source: "",
currency: "MZN", currency: "MZN",
province_id: territoryPath[0]?.id ?? "",
district_id: territoryPath[1]?.id ?? "",
admin_post_id: territoryPath[2]?.id ?? "",
locality_id: territoryPath[3]?.id ?? "",
}); });
return ( return (
<Management title="Análise assistida de competências"> <Management title="Análise assistida de competências">
<p> <p>
Procura: {demand.quantity} trabalhadores · {demand.qualification} Procura: {demand.quantity} trabalhadores · {demand.qualification}
</p> </p>
<p>
Localização da procura: {territoryPath.map((territory) => territory.name).join(" · ") || "Não indicada"}
</p>
<p className="rounded border p-4"> <p className="rounded border p-4">
{gap.state === "expired" {gap.state === "expired"
? "Fonte expirada. Actualize a declaração antes de analisar." ? "Fonte expirada. Actualize a declaração antes de analisar."
@@ -120,6 +138,33 @@ export default function Analysis({
form.post(`/management/education/demands/${demand.id}/investment`); form.post(`/management/education/demands/${demand.id}/investment`);
}} }}
> >
<div className="space-y-2 md:col-span-2">
<p className="font-medium">Localização da oportunidade educativa</p>
<p className="text-sm text-muted-foreground">
Inicialmente preenchida com a localização da procura. Confirme ou ajuste cada nível territorial.
</p>
<TerritoryFields
initial={selectedTerritory}
endpoint="/management/territory-options"
onChange={(path) => {
setSelectedTerritory(path);
form.setData((data) => ({
...data,
province_id: path[0]?.id ?? "",
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
}));
}}
/>
{Object.entries(form.errors)
.filter(([key]) => key.endsWith("_id"))
.map(([key, error]) => (
<p role="alert" key={key}>
{error}
</p>
))}
</div>
<Field label="Sector"> <Field label="Sector">
<select <select
required required
+39 -22
View File
@@ -1,6 +1,8 @@
import { Link, useForm } from "@inertiajs/react"; import { Link, useForm } from "@inertiajs/react";
import { useState } from "react";
import { Management, Field, control, button, Pagination } from "../management/shared"; import { Management, Field, control, button, Pagination } from "../management/shared";
import type { Paginated } from "../management/shared"; import type { Paginated } from "../management/shared";
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
type Option = { id: string; name?: string; title?: string; code?: string }; type Option = { id: string; name?: string; title?: string; code?: string };
type RecordRow = { type RecordRow = {
id: string; id: string;
@@ -21,7 +23,7 @@ type Props = {
providers: Option[]; providers: Option[];
courses: Option[]; courses: Option[];
projects: Option[]; projects: Option[];
territories: Option[]; territories: TerritoryOption[];
today: string; today: string;
filters: { q?: string; status?: string; geo_location_id?: string }; filters: { q?: string; status?: string; geo_location_id?: string };
indicators: { indicators: {
@@ -31,6 +33,19 @@ type Props = {
pending_demands: number; pending_demands: number;
}; };
}; };
const territoryLevels = ["province", "district", "admin_post", "locality"];
function territoryPath(id: string, territories: TerritoryOption[]): TerritoryOption[] {
const byId = new Map(territories.map((territory) => [territory.id, territory]));
const path: TerritoryOption[] = [];
let current = byId.get(id);
while (current && path.length < territoryLevels.length) {
if (territoryLevels.includes(current.location_type)) path.unshift(current);
current = current.parent_id ? byId.get(current.parent_id) : undefined;
}
return path;
}
function Errors({ errors }: { errors: Record<string, string> }) { function Errors({ errors }: { errors: Record<string, string> }) {
return ( return (
<> <>
@@ -124,6 +139,7 @@ function Catalog({ kind, title, providers }: { kind: string; title: string; prov
} }
function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props }) { function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props }) {
const demand = kind === "demands"; const demand = kind === "demands";
const [territoryResetKey, setTerritoryResetKey] = useState(0);
const form = useForm({ const form = useForm({
project_id: "", project_id: "",
course_id: "", course_id: "",
@@ -149,7 +165,10 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
form.post(`/management/education/${kind}`, { form.post(`/management/education/${kind}`, {
onSuccess: () => form.reset(), onSuccess: () => {
form.reset();
setTerritoryResetKey((key) => key + 1);
},
}); });
}} }}
> >
@@ -171,12 +190,15 @@ function Intake({ kind, props }: { kind: "demands" | "capacities"; props: Props
value={form.data.skill_id} value={form.data.skill_id}
onChange={(v) => form.setData("skill_id", v)} onChange={(v) => form.setData("skill_id", v)}
/> />
<Select <div className="md:col-span-2">
label="Território" <TerritoryFields
options={props.territories} key={territoryResetKey}
value={form.data.geo_location_id} endpoint="/management/territory-options"
onChange={(v) => form.setData("geo_location_id", v)} onChange={(path) =>
/> form.setData("geo_location_id", path[path.length - 1]?.id ?? "")
}
/>
</div>
{demand && ( {demand && (
<Field label="Empregador declarante"> <Field label="Empregador declarante">
<input <input
@@ -389,20 +411,15 @@ export default function Index(props: Props) {
<option value="expired">Fonte expirada</option> <option value="expired">Fonte expirada</option>
</select> </select>
</Field> </Field>
<Field label="Território"> <div className="md:col-span-2">
<select <TerritoryFields
className={control} initial={territoryPath(search.data.geo_location_id, props.territories)}
value={search.data.geo_location_id} endpoint="/management/territory-options"
onChange={(e) => search.setData("geo_location_id", e.target.value)} onChange={(path) =>
> search.setData("geo_location_id", path[path.length - 1]?.id ?? "")
<option value="">Todos</option> }
{props.territories.map((t) => ( />
<option key={t.id} value={t.id}> </div>
{t.name}
</option>
))}
</select>
</Field>
<div> <div>
<button className={button} disabled={search.processing}> <button className={button} disabled={search.processing}>
Filtrar Filtrar
+8 -6
View File
@@ -17,6 +17,7 @@ export default function Catalogue({
favourites, favourites,
territorial, territorial,
territorySelection, territorySelection,
catalogueUrl,
}: { }: {
filters: Record<string, string | string[] | boolean>; filters: Record<string, string | string[] | boolean>;
references: References; references: References;
@@ -28,6 +29,7 @@ export default function Catalogue({
}; };
favourites: number[]; favourites: number[];
territorySelection: TerritoryOption[]; territorySelection: TerritoryOption[];
catalogueUrl: string;
territorial: { territorial: {
id: string; id: string;
title: string; title: string;
@@ -87,7 +89,7 @@ export default function Catalogue({
const data = JSON.parse(draftFilterKey); const data = JSON.parse(draftFilterKey);
lastRequest.current = draftFilterKey; lastRequest.current = draftFilterKey;
router.get( router.get(
"/oportunidades", catalogueUrl,
{ ...data, education: data.education ? 1 : 0 }, { ...data, education: data.education ? 1 : 0 },
{ {
preserveState: true, preserveState: true,
@@ -103,7 +105,7 @@ export default function Catalogue({
clearTimeout(timer); clearTimeout(timer);
cancel?.(); cancel?.();
}; };
}, [draftFilterKey]); }, [draftFilterKey, catalogueUrl]);
useEffect(() => { useEffect(() => {
let active = true; let active = true;
const values = JSON.parse(filterKey) as Record<string, string | string[] | boolean>; const values = JSON.parse(filterKey) as Record<string, string | string[] | boolean>;
@@ -180,7 +182,7 @@ export default function Catalogue({
const params = new URLSearchParams(query()); const params = new URLSearchParams(query());
params.set("dimension", dimension); params.set("dimension", dimension);
params.delete("page"); params.delete("page");
return `/oportunidades?${params}`; return `${catalogueUrl}?${params}`;
}; };
return ( return (
<Frame <Frame
@@ -212,7 +214,7 @@ export default function Catalogue({
setComparison([]); setComparison([]);
setSelected([]); setSelected([]);
form.transform((data) => ({ ...data, education: data.education ? 1 : 0 })); form.transform((data) => ({ ...data, education: data.education ? 1 : 0 }));
form.get("/oportunidades", { preserveState: true }); form.get(catalogueUrl, { preserveState: true });
}} }}
> >
<Field label="Pesquisar oportunidades"> <Field label="Pesquisar oportunidades">
@@ -455,7 +457,7 @@ export default function Catalogue({
<button className={button} disabled={form.processing}> <button className={button} disabled={form.processing}>
Aplicar filtros Aplicar filtros
</button> </button>
<Link href="/oportunidades" className="underline"> <Link href={catalogueUrl} className="underline">
Limpar filtros Limpar filtros
</Link> </Link>
</div> </div>
@@ -475,7 +477,7 @@ export default function Catalogue({
onClick={() => { onClick={() => {
const params = new URLSearchParams(query()); const params = new URLSearchParams(query());
params.set("view", value); params.set("view", value);
router.get(`/oportunidades?${params}`, {}, { preserveScroll: true }); router.get(`${catalogueUrl}?${params}`, {}, { preserveScroll: true });
}} }}
> >
{["Grelha", "Lista", "Mapa", "Lista e mapa"][i]} {["Grelha", "Lista", "Mapa", "Lista e mapa"][i]}
+37 -13
View File
@@ -2,6 +2,7 @@ import { Head, Link, useForm, usePage } from "@inertiajs/react";
import { useState } from "react"; import { useState } from "react";
import { PortalMenu } from "@/layouts/portal-navigation"; import { PortalMenu } from "@/layouts/portal-navigation";
import { newSubmissionKey } from "@/lib/portal-api"; import { newSubmissionKey } from "@/lib/portal-api";
import { ProvinceSelect } from "@/components/investment-territory";
const input = "w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900"; const input = "w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900";
const button = const button =
@@ -249,14 +250,25 @@ function PartnershipForm() {
seeking: "Parceiro ou capacidade que procura", seeking: "Parceiro ou capacidade que procura",
}[key] }[key]
} }
<textarea {key === "province" ? (
className={input} <ProvinceSelect
required value={form.data.province}
minLength={key === "offer" || key === "seeking" ? 20 : 1} onChange={(province) => form.setData("province", province)}
maxLength={key === "offer" || key === "seeking" ? 2000 : 100} className={input}
value={form.data[key]} required
onChange={(e) => form.setData(key, e.target.value)} placeholder="Seleccione uma província"
/> label="Província"
/>
) : (
<textarea
className={input}
required
minLength={key === "offer" || key === "seeking" ? 20 : 1}
maxLength={key === "offer" || key === "seeking" ? 2000 : 100}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
/>
)}
</label> </label>
))} ))}
<label className="flex gap-2"> <label className="flex gap-2">
@@ -680,11 +692,23 @@ export default function Services(p: Props) {
key key
] ]
} }
<input {key === "province" ? (
className={input} <ProvinceSelect
value={filter.data[key]} value={filter.data.province}
onChange={(e) => filter.setData(key, e.target.value)} onChange={(province) =>
/> filter.setData("province", province)
}
className={input}
placeholder="Todas as províncias"
label="Filtrar por província"
/>
) : (
<input
className={input}
value={filter.data[key]}
onChange={(e) => filter.setData(key, e.target.value)}
/>
)}
</label> </label>
))} ))}
<button className={button}>Filtrar</button> <button className={button}>Filtrar</button>