Compare commits

...
Author SHA1 Message Date
nala e69ab1499f docs: comprovar guias na biblioteca QA existente
tests / ci (push) Canceled after 0s
2026-10-20 19:49:55 +02:00
nala 3258a25f76 feat: apresentar guias educativos com imagem resumo e contexto 2026-10-20 19:45:45 +02:00
nala 0e7d51f18f fix: concluir apresentacao publica dos negocios e zonas
tests / ci (push) Canceled after 0s
2026-10-20 19:00:32 +02:00
nala fd341b627e fix: harmonizar pesquisa e navegacao dos catalogos em QA 2026-10-20 18:53:41 +02:00
nala 1350b4df73 autenticacao 1
tests / ci (push) Canceled after 0s
2026-10-20 17:51:31 +02:00
nala 8cf820ef49 Reservar espaco minimo antes de compilar nova release
tests / ci (push) Canceled after 0s
2026-10-20 17:26:01 +02:00
nala 210b7d273b Clarificar comando de consulta para demonstrar entrega automatica 2026-10-20 17:25:29 +02:00
nala be49f4c39c Integrar navbar e sobre dos programadores preservando identidade e acessos 2026-10-20 17:23:45 +02:00
nala 9b3c20fc2a Registar resolucao do diagnostico e alinhar traducao financeira aceite 2026-10-20 17:23:20 +02:00
nala de061b81aa Conferir alteracoes durante CI e sinalizar falha ao systemd 2026-10-20 15:12:54 +02:00
nala 6e439def02 Reconciliar verificacoes com navegacao e relatorios aprovados 2026-10-20 15:12:17 +02:00
nala 74b081e93e Evitar migracao desnecessaria no teste unitario de exemplo 2026-10-20 15:09:51 +02:00
nala 9d148ca241 Preservar diagnostico mais recente dos programadores e isolar fixtures unitarias 2026-10-20 15:07:54 +02:00
nala 5be831ac44 Usar contrato QA existente e documentar operacao e reversao 2026-10-20 15:06:45 +02:00
nala f0e26e0d8a Preparar cadeia Git com verificacao isolada e releases reversiveis 2026-10-20 14:57:08 +02:00
nala 9ab721c97f Reconciliar fontes instaladas 423bd512d8c5 com main 2026-10-20 14:45:19 +02:00
paulomassigue 02d4e6b2fd remocao de publicidade em sobre nos e alinhamento de items no navbar
tests / ci (push) Canceled after 0s
2026-10-20 14:38:37 +02:00
paulomassigue 507387502c Correcao no aviso dos chunks
tests / ci (push) Waiting to run
2026-10-20 12:08:09 +02:00
paulomassigue 97a08df2a0 ajuste no header e organizaco de elementos, e ajuste no footer
tests / ci (push) Canceled after 0s
2026-10-20 11:39:25 +02:00
nala a128c5a1b8 Merge origin/main preservando reconciliacao da matriz
tests / ci (push) Canceled after 0s
2026-10-20 09:14:24 +02:00
nala 6e57d1f601 autenticacao 2026-10-20 09:09:57 +02:00
paulomassigue 9bc450e87c correcao do tamanho da frase:invista em mocambique
tests / ci (push) Canceled after 0s
2026-10-19 15:13:54 +02:00
paulomassigue cb438b2b28 correcao dos links do footer
tests / ci (push) Canceled after 0s
2026-10-19 15:01:58 +02:00
paulomassigue becb211f8c ajuste de texto inicial e centralizacao da informaco
tests / ci (push) Canceled after 0s
2026-10-19 14:45:30 +02:00
paulomassigue 14ad2f60c5 header:navbar e footer
tests / ci (push) Canceled after 0s
2026-10-19 13:07:16 +02:00
nala 3ca67a53c1 chore: exclude local QA outputs and nested dependencies
tests / ci (push) Canceled after 0s
2026-10-18 16:00:55 +02:00
nala cf003c8623 versao nrgocios 4
tests / ci (push) Canceled after 0s
2026-10-18 15:57:06 +02:00
nala 6bc0cc6f52 versao nrgocios 3
tests / ci (push) Canceled after 0s
2026-10-18 11:17:35 +02:00
nala cef6e201c7 versao nrgocios 2
tests / ci (push) Canceled after 0s
2026-10-16 20:11:05 +02:00
nala 2d23157e40 versao nrgocios
tests / ci (push) Canceled after 0s
2026-10-16 13:06:58 +02:00
nala 6a76aac80f versao compilada 1
tests / ci (push) Canceled after 0s
2026-10-16 09:17:28 +02:00
nala c13f250b87 versao compilada
tests / ci (push) Canceled after 0s
2026-10-15 17:37:00 +02:00
nala 9a96ee8dfe oportunidades 10
tests / ci (push) Canceled after 0s
2026-10-15 08:50:21 +02:00
nala 5738418838 oportunidades 9
tests / ci (push) Canceled after 0s
2026-10-14 16:57:56 +02:00
nala ba1c0340ea oportunidades 8
tests / ci (push) Canceled after 0s
2026-10-14 08:25:30 +02:00
nala 287e991486 oportunidades 7
tests / ci (push) Waiting to run
2026-10-13 11:40:29 +02:00
nala 20971d523f oportunidades 6
tests / ci (push) Canceled after 0s
2026-10-10 21:17:46 +02:00
nala 01405cbf8a oportunidades 5
tests / ci (push) Canceled after 0s
2026-10-10 14:15:28 +02:00
nala 6ddafc95ba oportunidades 4
tests / ci (push) Canceled after 0s
2026-10-10 07:03:59 +02:00
nala e662230df7 oportunidades 3
tests / ci (push) Canceled after 0s
2026-10-09 15:00:37 +02:00
nala 9d6176f55b feat: verify active opportunity management and prepare versioned resources 2026-10-09 13:16:41 +02:00
961 changed files with 170684 additions and 6534 deletions
+3
View File
@@ -1,5 +1,8 @@
* text=auto eol=lf * text=auto eol=lf
# Preserve the exact bytes pinned by EconomicReferenceCatalog::MANIFEST_SHA256.
database/data/economic-references-lot-01.json text eol=crlf
*.blade.php diff=html *.blade.php diff=html
*.css diff=css *.css diff=css
*.html diff=html *.html diff=html
+5
View File
@@ -63,6 +63,11 @@ jobs:
npm ci npm ci
npm run build npm run build
- name: Prevent accidental diagnostic exposure (C132)
run: |
php tools/portal-diagnostics-deployment-guard.php --self-test
php tools/portal-diagnostics-deployment-guard.php
- name: Run CI Checks - name: Run CI Checks
run: composer ci:check run: composer ci:check
+4
View File
@@ -1,7 +1,11 @@
/.phpunit.cache /.phpunit.cache
/bootstrap/ssr /bootstrap/ssr
/node_modules /node_modules
**/node_modules/
**/vendor/
/outputs/
/public/build /public/build
/public/build-qa-opportunities
/public/fonts-manifest.dev.json /public/fonts-manifest.dev.json
/public/hot /public/hot
/public/storage /public/storage
+25 -1
View File
@@ -1,4 +1,28 @@
# Regras do acervo documental InvestMoz # Instruções permanentes do projeto InvesteMoz
## Regras permanentes do InvesteMoz — decisão da Tempo, 12/10/2026
1. O portal InvesteMoz é propriedade da Tempo, Lda.
2. As regras de funcionamento são ditadas pela Tempo, Lda.
3. Os papéis dos seus funcionários são determinados e regidos pela Tempo, Lda.
4. As funcionalidades do portal são determinadas pela Tempo, Lda.
5. Este portal é de âmbito nacional e serve tanto a pessoas nacionais como estrangeiras e exigirá vários intervenientes para a sua operação (manutenção, cadastro, viabilização dos negócios, etc.). Se as regras não são ditadas por quem opera e, ao mesmo tempo, é proprietário, a sua viabilidade é nula.
6. Os constrangimentos criados sem a autorização da Tempo e que impedem o desenvolvimento normal devem ser removidos ou alterados.
7. Antes de iniciar a execução de uma nova funcionalidade, verificar quais são os constrangimentos que podem criar atrasos e círculos viciosos de correcção de erros que poderiam ter sido evitados.
8. As instruções anteriores ditadas pela Tempo mantêm-se.
Registar a origem das restrições: decisão expressa da Tempo, requisito anterior aprovado ou escolha de implementação. Uma escolha de implementação não constitui uma nova exigência organizacional. As autorizações e limites específicos de cada tarefa mantêm-se, incluindo a separação entre preparação em QA e alteração no ativo.
### Aplicação na execução — referência permanente confirmada em 12/10/2026
A Tempo, Lda define o produto, as regras operacionais e as funções dos seus funcionários. As instruções anteriores mantêm-se. Esta formulação consolida as oito regras acima e orienta a leitura das especificações e da matriz de auditoria existente.
- Cada restrição deve ter origem identificável: decisão expressa da Tempo, referência e versão de uma instrução anterior aprovada ou escolha técnica. Escolhas técnicas não se tornam regras de negócio sem autorização da Tempo.
- Constrangimentos introduzidos sem autorização devem ser identificados e removidos ou ajustados, preservando dados, relações, histórico e instruções aprovadas.
- Antes de implementar, verificar as dependências técnicas e operacionais que possam causar bloqueios previsíveis. Distinguir dependências reais de opções de implementação e apresentar antecipadamente as decisões concretas necessárias.
- O portal deve contemplar investidores nacionais e estrangeiros e os diferentes intervenientes da operação, incluindo manutenção, cadastro e viabilização de negócios. O âmbito do portal é nacional.
Referenciar estas orientações nos requisitos correspondentes da matriz existente, sem criar outra matriz ou backlog. A referência documental não encerra um requisito funcional nem substitui a demonstração do seu critério de aceitação.
## Aceitação das fontes oficiais — decisão do responsável, 08/10/2026 ## Aceitação das fontes oficiais — decisão do responsável, 08/10/2026
+13 -1
View File
@@ -1,4 +1,16 @@
# Portal do Investidor — esqueleto Laravel # Portal do Investidor — InvesteMoz
## Executar esta plataforma no Windows
Consulte [Execução local](deploy/local/README.md). Com Docker Desktop iniciado,
execute `./deploy/local/start.ps1`. Depois da preparação, `composer run dev`
inicia a plataforma em http://127.0.0.1:8000.
O ambiente local usa uma base PostgreSQL/PostGIS de demonstração isolada.
Não execute os exemplos históricos de criação de um projecto novo sobre esta
instalação ou sobre dados existentes.
## Referência histórica do pacote inicial
Estes ficheiros correspondem ao domínio de **sectores**, **oportunidades** e Estes ficheiros correspondem ao domínio de **sectores**, **oportunidades** e
**manifestações de interesse** do Portal do Investidor. Foram desenhados **manifestações de interesse** do Portal do Investidor. Foram desenhados
@@ -0,0 +1,120 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Sleep;
use Throwable;
class CheckDevelopmentEnvironment extends Command
{
protected $signature = 'portal:dev-check {--wait=0 : Segundos para aguardar uma falha transitória do PostgreSQL}';
protected $description = 'Verifica o arranque local sem alterar dados ou mostrar credenciais';
public function handle(): int
{
$wait = filter_var($this->option('wait'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 3600]]);
if ($wait === false) {
$this->error('--wait deve ser um inteiro entre 0 e 3600 segundos.');
return self::INVALID;
}
$checks = [
'PHP >= 8.4.1' => version_compare(PHP_VERSION, '8.4.1', '>='),
'Driver PostgreSQL activo' => extension_loaded('pdo_pgsql'),
'APP_KEY definida' => filled(config('app.key')),
'Base PostgreSQL configurada' => config('database.default') === 'pgsql',
'Cache de vistas gravável' => is_dir(config('view.compiled') ?: '') && is_writable(config('view.compiled') ?: ''),
'Sessões e logs graváveis' => is_writable(storage_path('framework/sessions')) && is_writable(storage_path('logs')),
'Dependências frontend instaladas' => is_file(base_path('node_modules/.bin/vp')) || is_file(base_path('node_modules/.bin/vp.cmd')),
];
if ($checks['Driver PostgreSQL activo'] && $checks['Base PostgreSQL configurada']) {
$checks['Ligação à base de dados'] = $this->checkConnection($wait);
}
if ($checks['Ligação à base de dados'] ?? false) {
try {
$checks['Extensão PostGIS instalada'] = (bool) DB::selectOne("SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'postgis') AS installed")->installed;
$checks['Tabelas principais instaladas'] = collect(['migrations', 'users', 'sectors', 'opportunities', 'sessions', 'cache', 'jobs'])
->every(fn (string $table): bool => Schema::hasTable($table));
} catch (Throwable) {
$checks['Esquema da base de dados verificável'] = false;
$this->warn('A ligação foi estabelecida, mas a verificação do esquema falhou. Verifique as permissões e a preparação QA.');
}
}
foreach ($checks as $label => $passed) {
$this->line(($passed ? '[OK] ' : '[FALHA] ').$label);
}
if (in_array(false, $checks, true)) {
$this->error('Arranque interrompido. Consulte deploy/local/README.md e corrija os itens acima.');
return self::FAILURE;
}
return self::SUCCESS;
}
private function checkConnection(int $wait): bool
{
$deadline = microtime(true) + $wait;
while (true) {
try {
DB::selectOne('SELECT 1');
return true;
} catch (Throwable $error) {
[$reason, $retryable] = $this->connectionFailure($error);
$remaining = $deadline - microtime(true);
if (! $retryable || $remaining <= 0) {
$this->warn($reason);
if ($retryable) {
$this->warn('Inicie Docker Desktop e execute ./deploy/local/start.ps1. Consulte os registos com docker compose --env-file .env -f deploy/local/compose.yaml logs --tail 40 postgres.');
}
return false;
}
$this->line('[AGUARDA] '.$reason.' Nova tentativa; prazo restante: '.(int) ceil($remaining).' s.');
DB::purge();
Sleep::for(min(5, $remaining))->seconds();
}
}
}
/** @return array{string, bool} */
private function connectionFailure(Throwable $error): array
{
// Inspect the chain internally; never print exception messages, DSNs or credentials.
$messages = '';
do {
$messages .= ' '.strtolower($error->getMessage()).' '.strtolower((string) $error->getCode());
$error = $error->getPrevious();
} while ($error !== null);
if (str_contains($messages, '28p01') || str_contains($messages, '28000')
|| str_contains($messages, 'password authentication failed') || str_contains($messages, 'no pg_hba.conf entry')) {
return ['Autenticação PostgreSQL recusada. Verifique as credenciais e as regras de acesso; aguardar não corrige este erro.', false];
}
if (str_contains($messages, '3d000') || preg_match('/database .* does not exist/', $messages)) {
return ['A base PostgreSQL configurada não existe. Verifique a configuração e a preparação QA.', false];
}
if (str_contains($messages, '57p03') || str_contains($messages, 'recovery mode')
|| str_contains($messages, 'not yet accepting connections') || str_contains($messages, 'database system is starting up')) {
return ['PostgreSQL em arranque ou recuperação; aguarde a conclusão sem remover o volume.', true];
}
if (preg_match('/\b08[0-9a-z]{3}\b/', $messages) || str_contains($messages, 'connection refused')
|| str_contains($messages, '57p01') || str_contains($messages, '57p02')) {
return ['PostgreSQL indisponível. Verifique se Docker Desktop e o contentor local estão iniciados.', true];
}
return ['Falha PostgreSQL não transitória. Verifique a configuração e os registos do servidor.', false];
}
}
+154 -3
View File
@@ -3,6 +3,7 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\ScanDocumentForMalware; use App\Jobs\ScanDocumentForMalware;
use App\Models\User;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -13,12 +14,52 @@ use Throwable;
class ImportDocumentBatch extends Command class ImportDocumentBatch extends Command
{ {
protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import}'; protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import} {--pilot-agronegocio : Restrict to the approved two-original pilot} {--sectors-lot20 : Restrict to the named 20-resource sector batch} {--sectors-trio : Restrict to the three named sector articles and reuse the existing image} {--backup-proof= : Fresh verified destination backup receipt for active pilot apply}';
protected $description = 'Preview or idempotently import a document batch into the existing private library'; protected $description = 'Preview or idempotently import a document batch into the existing private library';
private const MAX_BYTES = 10485760; private const MAX_BYTES = 10485760;
private const PILOT_MANIFEST_SHA256 = '0b720b0a6f7539de1d3eca9e32f89a6b9038848dc0b97ad21ace605154d9ddd8';
private const PILOT_HASHES = [
'legacy-tempo-post-171985-20260420' => '0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2',
'legacy-tempo-agronegocio-image-5e3840705cf98226' => '5e3840705cf98226d1f189cf665aaa98cb05da96c645159a1332a1d429d642eb',
];
private const SECTORS_MANIFEST_SHA256 = 'ade9a00c031534f4341e8f6bd5e425b502ee03efc9fcfaec4f463a10fb28201b';
private const SECTORS_HASHES = [
'legacy-tempo-post-171981-20260430' => '26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1',
'legacy-tempo-post-172679-20260430' => '2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb',
'legacy-tempo-post-172674-20260430' => '3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54',
'legacy-tempo-post-171990-20260616' => '8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72',
'legacy-tempo-post-172263-20260414' => '538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211',
'legacy-tempo-post-172256-20260414' => 'dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf',
'legacy-tempo-post-172261-20260414' => '88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a',
'legacy-tempo-post-172258-20260417' => '48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9',
'legacy-tempo-post-172253-20260414' => 'e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678',
'legacy-tempo-post-172240-20260414' => '8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d',
'legacy-tempo-post-172237-20260417' => 'a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c',
'legacy-tempo-post-172233-20260417' => '345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97',
'legacy-tempo-post-172230-20260414' => '4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e',
'legacy-tempo-post-172223-20260414' => '514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d',
'legacy-tempo-post-172219-20260414' => '0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c',
'legacy-tempo-post-171992-20260430' => '05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032',
'legacy-tempo-image-0a2c50d91dad3a60' => '0a2c50d91dad3a6007544634540e0f61b11d3506682a5a19066bae03cdcba490',
'legacy-tempo-image-28f41f12e10ab345' => '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa',
'legacy-tempo-image-fe9a2e382e385b35' => 'fe9a2e382e385b35f6e61ae320e199a979678677fd327fb7d4b07d8ce0111c11',
'legacy-tempo-image-8e58544e49e719f9' => '8e58544e49e719f9c865c91e07ef1030155a9e3d59260e6dc93e9c9e25674e39',
];
private const TRIO_MANIFEST_SHA256 = '9210ad7e1bea557349c440fd8295b321a10c2ddd34cc170f3dad18b5517751f8';
private const TRIO_REUSED_IMAGE_SHA256 = '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa';
private const TRIO_HASHES = [
'legacy-tempo-post-173209-20260623' => '926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941',
'legacy-tempo-post-173218-20260616' => '43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5',
'legacy-tempo-post-173213-20260616' => '0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0',
];
public function handle(): int public function handle(): int
{ {
$staging = storage_path('app/private/document-import-staging'); $staging = storage_path('app/private/document-import-staging');
@@ -42,7 +83,8 @@ class ImportDocumentBatch extends Command
} }
try { try {
$manifest = json_decode((string) file_get_contents($manifestPath), true, 512, JSON_THROW_ON_ERROR); $manifestBytes = (string) file_get_contents($manifestPath);
$manifest = json_decode($manifestBytes, true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) { } catch (Throwable) {
$this->error('Manifest is not valid JSON.'); $this->error('Manifest is not valid JSON.');
@@ -56,11 +98,43 @@ class ImportDocumentBatch extends Command
$apply = (bool) $this->option('apply'); $apply = (bool) $this->option('apply');
$actorId = $this->option('actor'); $actorId = $this->option('actor');
$pilot = (bool) $this->option('pilot-agronegocio');
$sectors = (bool) $this->option('sectors-lot20');
$trio = (bool) $this->option('sectors-trio');
if ((int) $pilot + (int) $sectors + (int) $trio > 1) {
$this->error('Select exactly one named batch; agribusiness scope is unchanged.');
return self::FAILURE;
}
if ($pilot || $sectors || $trio) {
try {
$this->validatePilot($manifestPath, $manifestBytes, $manifest, $stagingReal, $apply, $actorId, $sectors, $trio);
} catch (Throwable $exception) {
$this->error('Pilot refused before import: '.$exception->getMessage());
return self::FAILURE;
}
}
if ($apply && ! $pilot && ! $sectors && ! $trio) {
// CLI attribution is not an authenticated active installation. Rehearsals stay isolated.
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
if (! app()->environment('testing') || ! str_ends_with($target->database, '_test') || (int) $target->port !== 55441
|| config('database.connections.pgsql.host') !== '127.0.0.1' || config('database.connections.pgsql.url')) {
$this->error('CLI apply is restricted to isolated QA. Active imports require the authenticated activation mechanism; --actor is attribution only.');
return self::FAILURE;
}
}
if ($apply && (! is_numeric($actorId) || ! DB::table('users')->where('id', (int) $actorId)->exists())) { if ($apply && (! is_numeric($actorId) || ! DB::table('users')->where('id', (int) $actorId)->exists())) {
$this->error('Apply requires --actor=<existing-user-id>; no author identity will be fabricated.'); $this->error('Apply requires --actor=<existing-user-id>; no author identity will be fabricated.');
return self::FAILURE; return self::FAILURE;
} }
if ($apply && ! User::findOrFail((int) $actorId)->can('manage-portal')) {
$this->error('QA import requires an authorized library manager; no permission is granted by naming an account.');
return self::FAILURE;
}
$disk = Storage::disk('local'); $disk = Storage::disk('local');
$seenHashes = []; $seenHashes = [];
$seenExternalIds = []; $seenExternalIds = [];
@@ -71,6 +145,9 @@ class ImportDocumentBatch extends Command
$label = is_array($record) ? (string) ($record['external_id'] ?? '#'.($index + 1)) : '#'.($index + 1); $label = is_array($record) ? (string) ($record['external_id'] ?? '#'.($index + 1)) : '#'.($index + 1);
try { try {
$validated = $this->validateRecord($record, $stagingReal); $validated = $this->validateRecord($record, $stagingReal);
if (($pilot || $sectors || $trio) && ! hash_equals(($trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES))[$validated['external_id']] ?? '', $validated['sha256'])) {
throw new RuntimeException('Approved pilot bytes changed after preview validation.');
}
$hash = $validated['sha256']; $hash = $validated['sha256'];
if (isset($seenHashes[$hash])) { if (isset($seenHashes[$hash])) {
$this->line($label.' | duplicate bytes within batch; references item '.$seenHashes[$hash]); $this->line($label.' | duplicate bytes within batch; references item '.$seenHashes[$hash]);
@@ -199,6 +276,80 @@ class ImportDocumentBatch extends Command
return $failures > 0 ? self::FAILURE : self::SUCCESS; return $failures > 0 ? self::FAILURE : self::SUCCESS;
} }
/** The extra CLI path is a named, byte-bound pilot; it is not a general active import gate. */
private function validatePilot(string $manifestPath, string $manifestBytes, array $manifest, string $staging, bool $apply, mixed $actorId, bool $sectors = false, bool $trio = false): void
{
$allowed = $trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES);
$manifestName = $trio ? 'legacy-trio-20261015/manifest.json' : ($sectors ? 'legacy-setores-lote20-20261015/manifest.json' : 'legacy-agronegocio/manifest.json');
$manifestHash = $trio ? self::TRIO_MANIFEST_SHA256 : ($sectors ? self::SECTORS_MANIFEST_SHA256 : self::PILOT_MANIFEST_SHA256);
if ($manifestPath !== realpath($staging.'/'.$manifestName)
|| ! hash_equals($manifestHash, hash('sha256', $manifestBytes))
|| count($manifest['documents']) !== count($allowed)) {
throw new RuntimeException('Only the exact selected manifest and its fixed resource list are allowed.');
}
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$host = config('database.connections.pgsql.host');
$qa = app()->environment('testing') && str_ends_with($target->database, '_test') && (int) $target->port === 55441;
$active = ! app()->environment('testing') && $target->database === 'investemoz' && (int) $target->port === 5432;
if ((! $qa && ! $active) || ! in_array($host, ['127.0.0.1', 'localhost'], true) || config('database.connections.pgsql.url')) {
throw new RuntimeException('Pilot target identity is not permitted.');
}
if ($apply || $actorId !== null) {
$actor = is_string($actorId) && preg_match('/^[1-9][0-9]*$/D', $actorId) ? User::find((int) $actorId) : null;
if (! $actor || ! $actor->can('manage-portal')) {
throw new RuntimeException('A real existing account with effective manage-portal authorization is required.');
}
}
if ($active && $apply) {
$this->validatePilotBackup($this->option('backup-proof'));
}
if ($trio) {
$images = DB::table('documents as d')->join('portal_resources as r', 'r.document_id', '=', 'd.id')
->where('d.external_id', 'legacy-tempo-image-28f41f12e10ab345')->where('d.sha256', self::TRIO_REUSED_IMAGE_SHA256)
->whereNull('d.deleted_at')->where('d.status', 'active')->where('d.data_classification', 'public')
->where('d.rights_status', 'authorized')->where('r.rights_status', 'authorized')->where('r.published', true)
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->get(['d.storage_key']);
if ($images->count() !== 1 || ! Storage::disk('local')->exists($images[0]->storage_key)
|| ! hash_equals(self::TRIO_REUSED_IMAGE_SHA256, hash_file('sha256', Storage::disk('local')->path($images[0]->storage_key)))) {
throw new RuntimeException('The shared image must already exist once, published, authorized and clean with the exact original bytes; no image is imported.');
}
}
foreach ($manifest['documents'] as $record) {
$entry = $this->validateRecord($record, $staging);
if (! hash_equals($allowed[$entry['external_id']] ?? '', $entry['sha256'])) {
throw new RuntimeException('Article or image differs from the approved SHA-256.');
}
$existing = DB::table('documents')->where('sha256', $entry['sha256'])->whereNull('deleted_at')->first();
if ($existing && ($existing->external_id !== $entry['external_id']
|| ! DB::table('portal_resources')->where('document_id', $existing->id)->exists())) {
throw new RuntimeException('Matching bytes have another identity or no library resource; reconcile explicitly.');
}
if (DB::table('documents')->where('external_id', $entry['external_id'])->whereNull('deleted_at')
->where('sha256', '!=', $entry['sha256'])->exists()
|| (! $existing && DB::table('portal_resources')->where('document_identity_key', $this->identity($entry))->exists())) {
throw new RuntimeException('Existing identity/version conflicts with this pilot; no overwrite or partial preflight import.');
}
}
}
private function validatePilotBackup(mixed $path): void
{
if (! is_string($path) || ! is_file($path)) {
throw new RuntimeException('Active pilot apply requires a fresh verified backup/restoration receipt.');
}
$proof = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
$verified = strtotime($proof['verified_at'] ?? '');
if (! ($proof['restore_verified'] ?? false) || ! ($proof['files_verified'] ?? false)
|| ($proof['target']['database'] ?? '') !== 'investemoz' || (int) ($proof['target']['port'] ?? 0) !== 5432
|| ! str_ends_with($proof['restore_target']['database'] ?? '', '_test') || (int) ($proof['restore_target']['port'] ?? 0) !== 55441
|| $verified === false || $verified > time() || $verified < time() - 86400
|| ! is_file($proof['dump_path'] ?? '') || ! is_file($proof['files_path'] ?? '')
|| ! hash_equals($proof['sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
|| ! hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))) {
throw new RuntimeException('Backup/restoration identity, freshness or integrity does not match the active pilot.');
}
}
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function validateRecord(mixed $record, string $stagingRoot): array private function validateRecord(mixed $record, string $stagingRoot): array
{ {
@@ -238,7 +389,7 @@ class ImportDocumentBatch extends Command
throw new RuntimeException('File size is outside the 1 byte to 10 MiB import limit.'); throw new RuntimeException('File size is outside the 1 byte to 10 MiB import limit.');
} }
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($path); $mime = (new \finfo(FILEINFO_MIME_TYPE))->file($path);
$allowed = ['application/pdf', 'text/plain', 'text/csv', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', $allowed = ['application/pdf', 'application/json', 'text/plain', 'text/csv', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/png', 'image/jpeg', 'image/webp']; 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/png', 'image/jpeg', 'image/webp'];
if (! is_string($mime) || ! in_array($mime, $allowed, true)) { if (! is_string($mime) || ! in_array($mime, $allowed, true)) {
throw new RuntimeException('Detected media type is not supported by the document library.'); throw new RuntimeException('Detected media type is not supported by the document library.');
@@ -20,10 +20,8 @@ class HomeController extends Controller
$locale = $validated['locale'] ?? 'pt'; $locale = $validated['locale'] ?? 'pt';
$data = Cache::remember("portal_home_v2_{$locale}", now()->addMinutes(10), function () { $data = Cache::remember("portal_home_sector_organization_v1_{$locale}", now()->addMinutes(10), function () {
$sectors = Sector::withCount([ $sectors = \App\Services\SectorOrganization::catalog();
'opportunities as opportunities_count' => fn ($q) => $q->published(),
])->where('is_active', true)->orderBy('sort_order')->get();
$featured = Opportunity::with('sector:id,name,slug') $featured = Opportunity::with('sector:id,name,slug')
->published()->where('is_featured', true) ->published()->where('is_featured', true)
@@ -31,14 +29,14 @@ class HomeController extends Controller
return [ return [
'sectors' => $sectors->map(fn ($s) => [ 'sectors' => $sectors->map(fn ($s) => [
'name' => $s->name, 'id' => $s->id, 'specializations' => $s->specializations, 'name' => $s->name,
'slug' => $s->slug, 'slug' => $s->slug,
'shortDescription' => $s->short_description, 'shortDescription' => $s->short_description,
'opportunitiesCount' => $s->opportunities_count, 'opportunitiesCount' => $s->opportunities_count,
'url' => "/sectores/{$s->slug}", 'url' => "/sectores/{$s->slug}",
])->values()->all(), ])->values()->all(),
'featuredOpportunities' => $featured->map(fn ($o) => [ 'featuredOpportunities' => $featured->map(fn ($o) => [
'reference' => $o->reference, 'id' => $o->id, 'reference' => $o->reference,
'title' => $o->title, 'title' => $o->title,
'sector' => $o->sector?->name, 'sector' => $o->sector?->name,
'province' => $o->province, 'province' => $o->province,
@@ -51,7 +49,7 @@ class HomeController extends Controller
])->values()->all(), ])->values()->all(),
'stats' => [ 'stats' => [
'opportunities' => Opportunity::published()->count(), 'opportunities' => Opportunity::published()->count(),
'sectors' => Sector::where('is_active', true)->count(), 'sectors' => $sectors->count(),
'provinces' => Opportunity::published()->distinct('province')->count('province'), 'provinces' => Opportunity::published()->distinct('province')->count('province'),
], ],
]; ];
@@ -23,8 +23,9 @@ class InterestRequestController extends Controller
{ {
public function store(StoreInterestRequestRequest $request, InterestSubmission $submission): JsonResponse public function store(StoreInterestRequestRequest $request, InterestSubmission $submission): JsonResponse
{ {
$validated = $request->validated(); $validated = [...$request->validated(), '_actor_id' => $request->user()->id];
$key = $request->header('Idempotency-Key'); $key = $request->header('Idempotency-Key');
abort_unless(is_string($key), 422, 'Identificador do envio em falta.');
Validator::make(['idempotency_key' => $key], ['idempotency_key' => [$key === null ? 'nullable' : 'required', 'uuid']])->validate(); Validator::make(['idempotency_key' => $key], ['idempotency_key' => [$key === null ? 'nullable' : 'required', 'uuid']])->validate();
try { try {
@@ -53,6 +54,7 @@ class InterestRequestController extends Controller
'phone' => $validated['phone'] ?? null, 'phone' => $validated['phone'] ?? null,
'investor_type' => $validated['investorType'], 'investor_type' => $validated['investorType'],
'country' => $validated['country'], 'country' => $validated['country'],
'metadata' => ['portal_user_id' => $request->user()->id, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
'sector_interest' => $validated['sectorInterest'], 'sector_interest' => $validated['sectorInterest'],
'opportunity_reference' => $validated['opportunityReference'] ?? null, 'opportunity_reference' => $validated['opportunityReference'] ?? null,
'investment_range' => $validated['investmentRange'] ?? null, 'investment_range' => $validated['investmentRange'] ?? null,
@@ -76,6 +78,19 @@ class InterestRequestController extends Controller
} }
} }
$row = \App\Models\InvestmentSubmission::create([
'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id,
'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1,
'payload' => ['simple_participation' => true, 'opportunity_title' => $opportunity?->title ?? $business?->title, 'opportunity_reference' => $opportunity?->reference, 'phone' => $validated['phone'] ?? null, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null, 'full_name' => $validated['fullName'], 'email' => $validated['email'],
'objective' => $validated['message'], 'sector' => $validated['sectorInterest'],
'country' => $validated['country'], 'existing_business_id' => $business?->id,
'modality' => $validated['modality'] ?? null],
]);
\Illuminate\Support\Facades\DB::table('investment_submission_events')->insert([
'submission_id' => $row->id, 'actor_id' => $request->user()->id,
'action' => 'submitted', 'version' => 1, 'created_at' => now(),
]);
$interest->forceFill(['metadata' => [...$interest->metadata, 'submission_id' => $row->id]])->save();
return $interest; return $interest;
}); });
@@ -84,7 +99,8 @@ class InterestRequestController extends Controller
'message' => 'Manifestação de interesse registada com sucesso.', 'message' => 'Manifestação de interesse registada com sucesso.',
'data' => [ 'data' => [
'reference' => $interestRequest->reference, 'reference' => $interestRequest->reference,
'status' => 'received', 'status' => $interestRequest->status,
'tracking_url' => '/investidor/manifestacoes',
], ],
], 201); ], 201);
} catch (IdempotencyConflict) { } catch (IdempotencyConflict) {
@@ -36,6 +36,7 @@ class OpportunityController extends Controller
$term = $validated['q']; $term = $validated['q'];
$query->where(fn ($q) => $q $query->where(fn ($q) => $q
->whereLike('title', "%{$term}%") ->whereLike('title', "%{$term}%")
->orWhereLike('description', "%{$term}%")
->orWhereLike('summary', "%{$term}%") ->orWhereLike('summary', "%{$term}%")
->orWhereLike('reference', "%{$term}%") ->orWhereLike('reference', "%{$term}%")
->orWhereLike('province', "%{$term}%") ->orWhereLike('province', "%{$term}%")
@@ -46,7 +47,7 @@ class OpportunityController extends Controller
if (! empty($validated['sector'])) { if (! empty($validated['sector'])) {
$sector = $validated['sector']; $sector = $validated['sector'];
$query->whereHas('sector', fn ($q) => $q->where('slug', $sector)); \App\Services\SectorOrganization::constrain($query, $sector);
} }
if (! empty($validated['province'])) { if (! empty($validated['province'])) {
@@ -54,7 +55,7 @@ class OpportunityController extends Controller
} }
if (! empty($validated['maturity_level'])) { if (! empty($validated['maturity_level'])) {
$query->where('maturity_level', $validated['maturity_level']); \App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
} }
$results = $query->orderByDesc('is_featured') $results = $query->orderByDesc('is_featured')
@@ -3,19 +3,25 @@
namespace App\Http\Controllers\Api\V1; namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Services\CountryCatalogue;
use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Builder;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
class ReferenceCatalogController extends Controller class ReferenceCatalogController extends Controller
{ {
private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities']; private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities', 'countries'];
public function index(Request $request, string $catalog): JsonResponse public function index(Request $request, string $catalog): JsonResponse
{ {
$catalog = $this->validatedCatalog($catalog); $catalog = $this->validatedCatalog($catalog);
if ($catalog === 'countries') {
return $this->countries($request);
}
$rules = [ $rules = [
'q' => ['nullable', 'string', 'max:100'], 'q' => ['nullable', 'string', 'max:100'],
@@ -32,10 +38,13 @@ class ReferenceCatalogController extends Controller
} }
if ($catalog === 'economic-activities') { if ($catalog === 'economic-activities') {
$rules['sector_id'] = ['nullable', 'integer', 'exists:sectors,id']; $rules['sector_id'] = ['nullable', 'integer', 'exists:sectors,id'];
$rules['origin'] = ['nullable', 'in:portal,cae'];
} }
$data = $request->validate($rules); $data = $request->validate($rules);
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $catalog)->where('locale', 'pt-MZ'); $cae = $catalog === 'economic-activities' && ($data['origin'] ?? 'portal') === 'cae';
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $cae ? 'economic-activities-cae' : $catalog)->where('locale', 'pt-MZ');
if ($cae && ! app(\App\Services\EconomicReferenceCatalog::class)->available()) { $versionQuery->whereRaw('false'); }
if (isset($data['version'])) { if (isset($data['version'])) {
$versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']); $versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']);
} else { } else {
@@ -72,6 +81,10 @@ class ReferenceCatalogController extends Controller
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString(); $page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values(); $items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values();
if ($cae) {
$paths = app(\App\Services\EconomicReferenceCatalog::class)->activities()->keyBy('id');
$items = $items->map(fn ($row) => [...$row, 'level' => $paths[$row['id']]->level, 'path' => $paths[$row['id']]->path, 'source_version' => $paths[$row['id']]->source_version, 'edition' => 'not_determined', 'divergence' => '600/579 documentalmente aberta']);
}
return response()->json([ return response()->json([
'data' => $items, 'data' => $items,
@@ -89,6 +102,21 @@ class ReferenceCatalogController extends Controller
->header('ETag', 'W/"catalog-'.substr(hash('sha256', $catalog.'|'.$version->version_no.'|'.json_encode($data, JSON_THROW_ON_ERROR)), 0, 32).'"'); ->header('ETag', 'W/"catalog-'.substr(hash('sha256', $catalog.'|'.$version->version_no.'|'.json_encode($data, JSON_THROW_ON_ERROR)), 0, 32).'"');
} }
private function countries(Request $request): JsonResponse
{
$data = $request->validate(['q' => 'nullable|string|max:100', 'page' => 'nullable|integer|min:1', 'per_page' => 'nullable|integer|min:1|max:100', 'parent_id' => 'prohibited', 'version' => 'prohibited']);
$term = strtolower(Str::ascii(trim($data['q'] ?? '')));
$items = collect(app(CountryCatalogue::class)->all())
->filter(fn (array $country) => $term === '' || str_contains(strtolower(Str::ascii(implode(' ', $country))), $term))
->values()->map(fn (array $country) => ['id' => $country['code'], 'value' => $country['code'], 'code' => $country['code'], 'name' => $country['name'], 'label' => $country['name']]);
$page = (int) ($data['page'] ?? 1);
$perPage = (int) ($data['per_page'] ?? 50);
$result = new LengthAwarePaginator($items->forPage($page, $perPage)->values(), $items->count(), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
return response()->json([...$result->toArray(), 'meta' => ['catalog' => 'countries', 'source' => 'Local ISO 3166 catalogue', 'sha256' => hash_file('sha256', resource_path('data/iso3166.tab'))]])
->header('Cache-Control', 'public, max-age=300');
}
/** @param array<string,mixed> $data */ /** @param array<string,mixed> $data */
private function authorities(string $versionId, array $data): Builder private function authorities(string $versionId, array $data): Builder
{ {
@@ -141,13 +169,15 @@ class ReferenceCatalogController extends Controller
->where('valid_from', '<=', today()->toDateString()) ->where('valid_from', '<=', today()->toDateString())
->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString())) ->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()))
->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']); ->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']);
if (empty($data['version'])) $query->where('id', '!=', \App\Services\SectorOrganization::LEGACY_ACTIVITY_ID);
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) { if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) {
$query->where('parent_id', $data['parent_id']); $query->where('parent_id', $data['parent_id']);
} else { } else {
$query->whereNull('parent_id'); $query->whereNull('parent_id');
} }
if (! empty($data['sector_id'])) { if (! empty($data['sector_id'])) {
$query->where('sector_id', $data['sector_id']); $sector = \App\Models\Sector::find($data['sector_id']);
$query->whereIn('sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
} }
if (! empty($data['q'])) { if (! empty($data['q'])) {
$this->search($query, $data['q'], ['code', 'label_pt_mz']); $this->search($query, $data['q'], ['code', 'label_pt_mz']);
@@ -171,7 +201,7 @@ class ReferenceCatalogController extends Controller
}); });
} }
/** @return 'authorities'|'jurisdictions'|'economic-activities' */ /** @return 'authorities'|'jurisdictions'|'economic-activities'|'countries' */
private function validatedCatalog(string $catalog): string private function validatedCatalog(string $catalog): string
{ {
abort_unless(in_array($catalog, self::CATALOGS, true), 404); abort_unless(in_array($catalog, self::CATALOGS, true), 404);
@@ -10,22 +10,12 @@ class SectorController extends Controller
{ {
public function index(): JsonResponse public function index(): JsonResponse
{ {
$sectors = Sector::withCount([ $sectors = \App\Services\SectorOrganization::catalog()->map(fn ($s) => [
'opportunities as opportunities_count' => fn ($q) => $q->published(), 'id' => $s->id, 'name' => $s->name, 'slug' => $s->slug,
]) 'shortDescription' => $s->short_description, 'description' => $s->description,
->where('is_active', true) 'icon' => $s->icon, 'opportunitiesCount' => $s->opportunities_count,
->orderBy('sort_order') 'url' => $s->url, 'specializations' => $s->specializations,
->get() ]);
->map(fn ($s) => [
'id' => $s->id,
'name' => $s->name,
'slug' => $s->slug,
'shortDescription' => $s->short_description,
'description' => $s->description,
'icon' => $s->icon,
'opportunitiesCount' => $s->opportunities_count,
'url' => "/sectores/{$s->slug}",
]);
return response()->json(['success' => true, 'data' => $sectors]); return response()->json(['success' => true, 'data' => $sectors]);
} }
@@ -35,6 +25,7 @@ class SectorController extends Controller
$sector = Sector::with(['opportunities' => fn ($q) => $q->published()]) $sector = Sector::with(['opportunities' => fn ($q) => $q->published()])
->where('slug', $slug)->firstOrFail(); ->where('slug', $slug)->firstOrFail();
return response()->json(['success' => true, 'data' => $sector]); $sector->setRelation('opportunities', \App\Services\SectorOrganization::opportunities($sector)->get());
return response()->json(['success' => true, 'data' => $sector, 'canonical_url' => \App\Services\SectorOrganization::href($slug), 'specialization_of' => $slug === 'fintech' ? 'mercado-financeiro' : null]);
} }
} }
+7 -2
View File
@@ -9,6 +9,8 @@ use App\Models\Investor;
use App\Models\Lead; use App\Models\Lead;
use App\Models\User; use App\Models\User;
use App\Services\ConvertInterestToLead; use App\Services\ConvertInterestToLead;
use App\Services\CountryCatalogue;
use App\Services\DeclaredOriginStatistics;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -77,7 +79,8 @@ class CrmController extends Controller
{ {
$filters = $request->validate(['q' => ['nullable', 'string', 'max:150'], $filters = $request->validate(['q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in(['new', 'qualified', 'disqualified', 'converted'])], 'status' => ['nullable', Rule::in(['new', 'qualified', 'disqualified', 'converted'])],
'owner_user_id' => ['nullable', 'integer', 'exists:users,id']]); 'owner_user_id' => ['nullable', 'integer', 'exists:users,id'],
'origin' => ['nullable', Rule::in(['unknown', ...array_column(app(CountryCatalogue::class)->all(), 'code')])]]);
$query = Lead::with(['investor:id,legal_name', 'owner:id,name']) $query = Lead::with(['investor:id,legal_name', 'owner:id,name'])
->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())]); ->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())]);
if ($term = $filters['q'] ?? null) { if ($term = $filters['q'] ?? null) {
@@ -92,7 +95,9 @@ class CrmController extends Controller
} }
return Inertia::render('crm/leads', ['leads' => $query->latest()->orderBy('id')->paginate(20)->withQueryString(), return Inertia::render('crm/leads', ['leads' => $query->latest()->orderBy('id')->paginate(20)->withQueryString(),
'filters' => $filters, 'owners' => $this->owners()]); 'filters' => $filters, 'owners' => $this->owners(),
'countries' => app(CountryCatalogue::class)->all(),
'originStatistics' => app(DeclaredOriginStatistics::class)->forManager($request->user(), $filters['origin'] ?? null)]);
} }
public function prepare(InterestRequest $interest): Response|RedirectResponse public function prepare(InterestRequest $interest): Response|RedirectResponse
+20 -3
View File
@@ -5,7 +5,10 @@ namespace App\Http\Controllers;
use App\Models\InterestRequest; use App\Models\InterestRequest;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Sector; use App\Models\Sector;
use App\Services\InvestorPath;
use App\Services\PortalProfileAccess;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -14,18 +17,32 @@ class DashboardController extends Controller
public function __invoke(Request $request): Response public function __invoke(Request $request): Response
{ {
if (! $request->user()->can('manage-portal')) { if (! $request->user()->can('manage-portal')) {
return Inertia::render('dashboard', ['summary' => null]); $path = app(InvestorPath::class);
$contexts = $path->contexts($request->user());
$current = $contexts ? $path->view($request->user(), $contexts[0]['id']) : null;
return Inertia::render('dashboard', ['summary' => null, 'investorPath' => $path->available() ? [
'contexts' => $contexts,
'current' => $current ? ['id' => $current['case']['id'], 'next' => $current['next'],
'pending' => count(array_filter($current['steps'], fn ($step) => ! in_array($step['state'], ['completed', 'approved', 'dispensed'], true))),
'documents' => count($current['documents']), 'results' => count($current['results']), 'tasks' => count($current['tasks'])] : null,
] : null]);
} }
$counts = InterestRequest::query()->selectRaw('status, count(*) as total') $counts = InterestRequest::query()->selectRaw('status, count(*) as total')
->groupBy('status')->pluck('total', 'status'); ->groupBy('status')->pluck('total', 'status');
$drafts = Opportunity::where('status', 'draft');
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
$drafts = app(PortalProfileAccess::class)->scope($drafts, $request->user());
}
return Inertia::render('dashboard', ['summary' => [ return Inertia::render('dashboard', ['summary' => [
'canCreateOpportunity' => app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed']) 'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed'])
->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]), ->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]),
'publishedOpportunities' => Opportunity::published()->count(), 'publishedOpportunities' => Opportunity::published()->count(),
'draftOpportunities' => Opportunity::where('status', 'draft')->count(), 'draftOpportunities' => $drafts->count(),
'activeSectors' => Sector::where('is_active', true)->count(), 'activeSectors' => Sector::catalog()->count(),
'recentRequests' => InterestRequest::orderByDesc('id')->limit(5) 'recentRequests' => InterestRequest::orderByDesc('id')->limit(5)
->get(['id', 'reference', 'sector_interest', 'status', 'created_at']), ->get(['id', 'reference', 'sector_interest', 'status', 'created_at']),
]]); ]]);
@@ -11,8 +11,8 @@ class DocumentMalwareController extends Controller
{ {
public function retry(Request $request, string $id): RedirectResponse public function retry(Request $request, string $id): RedirectResponse
{ {
DB::transaction(function () use ($id): void { DB::transaction(function () use ($id, $request): void {
$document = DB::table('documents')->where('id', $id)->lockForUpdate()->first(); $document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first();
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404); abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422, abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.'); 'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers;
use App\Services\EconomicReferenceInstallation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class EconomicReferenceController extends Controller
{
public function preview(Request $request, EconomicReferenceInstallation $service): JsonResponse|Response
{
$plan = $service->preview($request->user());
return $request->expectsJson() ? response()->json(['plan' => $plan]) : Inertia::render('management/economic-references', ['plan' => $plan]);
}
public function apply(Request $request, string $operation, EconomicReferenceInstallation $service): JsonResponse
{
return response()->json(['receipt' => $service->apply($request->user(), $operation, $request->all())]);
}
}
@@ -0,0 +1,145 @@
<?php
namespace App\Http\Controllers;
use App\Services\VerifiedDocumentBinary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
class EditorialArticleController extends Controller
{
public function installation(Request $request, \App\Services\EditorialInstallation $installation)
{
$plan = $installation->preview($request->user());
return $request->expectsJson() ? response()->json(['plan' => $plan])->header('Cache-Control', 'private, no-store')
: response()->view('management.editorial-installation', ['plan' => $plan, 'operationKey' => (string) \Illuminate\Support\Str::uuid(), 'receipt' => null])->header('Cache-Control', 'private, no-store');
}
public function install(Request $request, \App\Services\EditorialInstallation $installation)
{
$receipt = $installation->apply($request->user(), $request->all());
return $request->expectsJson() ? response()->json(['receipt' => $receipt])->header('Cache-Control', 'private, no-store')
: response()->view('management.editorial-installation', ['plan' => $installation->preview($request->user()), 'operationKey' => (string) \Illuminate\Support\Str::uuid(), 'receipt' => $receipt])->header('Cache-Control', 'private, no-store');
}
public function showMfa(Request $request)
{
return $this->confirmMfa($request);
}
public function confirmMfa(Request $request)
{
$actor = $request->user();
abort_unless($actor->two_factor_secret !== null && $actor->two_factor_confirmed_at !== null, 403, 'MFA configurado e confirmado necessário.');
if (app(\App\Services\PortalProfileAccess::class)->mfa($actor)) {
return redirect()->route('editorial.installation');
}
if ($request->isMethod('get')) {
return response()->view('management.editorial-mfa')->header('Cache-Control', 'private, no-store');
}
abort_if(array_diff(array_keys($request->all()), ['code', 'recovery_code', '_token']), 422, 'A conta e o destino são obtidos da sessão e do servidor.');
$data = $request->validate(['code' => 'nullable|string|max:32', 'recovery_code' => 'nullable|string|max:255']);
try {
$recovery = collect($actor->recoveryCodes())->first(fn ($code) => isset($data['recovery_code']) && hash_equals($code, $data['recovery_code']));
$valid = $recovery !== null || (!empty($data['code']) && app(\Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider::class)->verify(
\Laravel\Fortify\Fortify::currentEncrypter()->decrypt($actor->two_factor_secret), $data['code']
));
} catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
$valid = false;
}
if (!$valid) {
event(new \Laravel\Fortify\Events\TwoFactorAuthenticationFailed($actor));
throw ValidationException::withMessages(['code' => 'Não foi possível confirmar o código MFA.']);
}
if ($recovery !== null) {
$actor->replaceRecoveryCode($recovery);
}
event(new \Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided($actor));
$request->session()->regenerate();
return redirect()->route('editorial.installation')->header('Cache-Control', 'private, no-store');
}
private function installed(): void
{
abort_unless(Schema::hasColumn('portal_resources', 'editorial_content'), 503, 'Editor editorial ainda não instalado.');
}
private function publicResources()
{
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.published', true)->where('r.rights_status', 'authorized')->where('d.rights_status', 'authorized')
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256');
}
public function edit(int $id)
{
$this->installed();
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
$r = DB::table('portal_resources')->find($id);
abort_unless($r, 404);
$content = $r->editorial_content ? json_decode($r->editorial_content, true) : null;
if ($content === null) {
$document = DB::table('documents')->find($r->document_id);
if ($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
&& in_array($document->media_type, ['text/plain', 'application/json'], true)) {
$binary = app(VerifiedDocumentBinary::class)->respond($document);
$bytes = $binary instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse
? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
$original = json_decode($bytes, true);
if (is_array($original) && ($original['format'] ?? '') === 'investmoz-legacy-article-v1') {
$html = preg_replace('~</(?:p|div|li|h[1-6])>|<br\s*/?>~i', "\n\n", $original['content_html'] ?? '');
$content = ['body' => trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')), 'image_resource_id' => null];
}
}
}
return Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version],
'content' => $content, 'images' => $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->get(['r.id', 'r.title']),
'revisions' => DB::table('portal_resource_revisions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['revision_no', 'change_type', 'created_at'])]);
}
public function save(Request $request, int $id)
{
$this->installed();
$data = $request->validate(['body' => ['required', 'string', 'max:100000'], 'image_resource_id' => ['nullable', 'integer'], 'metadata_version' => ['required', 'integer', 'min:1']]);
DB::transaction(function () use ($request, $id, $data) {
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
abort_unless($r, 404);
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
abort_unless((int) $r->metadata_version === (int) $data['metadata_version'], 409, 'O artigo foi alterado noutra sessão. Recarregue antes de editar.');
if (! empty($data['image_resource_id'])) {
abort_unless($this->publicResources()->where('r.id', $data['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->exists(), 422, 'Escolha uma imagem pública disponível na biblioteca.');
}
$body = trim($data['body']);
if ($body === '') {
throw ValidationException::withMessages(['body' => 'Escreva o corpo do artigo.']);
}
$content = ['format' => 1, 'body' => $body, 'image_resource_id' => $data['image_resource_id'] ?? null];
$revision = (int) $r->metadata_version + 1;
DB::table('portal_resources')->where('id', $id)->update(['editorial_content' => json_encode($content, JSON_THROW_ON_ERROR), 'published' => false, 'approved_by' => null, 'metadata_version' => $revision, 'last_reviewed_by' => $request->user()->id, 'last_reviewed_at' => now(), 'updated_at' => now()]);
$resource = DB::table('portal_resources')->find($id);
$links = DB::table('portal_resource_links')->where('resource_id', $id)->orderBy('id')->get();
DB::table('portal_resource_revisions')->insert(['resource_id' => $id, 'revision_no' => $revision, 'change_type' => 'metadata_updated', 'snapshot' => json_encode(['resource' => $resource, 'associations' => $links], JSON_THROW_ON_ERROR), 'actor_user_id' => $request->user()->id, 'created_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'portal-management', 'actor_user_id' => $request->user()->id, 'entity_type' => 'portal_resources', 'entity_id' => null, 'action' => 'editorial_updated', 'before_data' => json_encode(['record_id' => $id, 'metadata_version' => $r->metadata_version]), 'after_data' => json_encode(['record_id' => $id, 'metadata_version' => $revision, 'published' => false])]);
});
return redirect('/management/portal-services/resources/'.$id.'/article')->with('success', 'Artigo guardado como rascunho. Publique expressamente no acervo quando estiver pronto.');
}
public function show(int $id)
{
$this->installed();
$r = $this->publicResources()->where('r.id', $id)->first(['r.id', 'r.title', 'r.description', 'r.editorial_content', 'r.document_id', 'd.issuer']);
abort_unless($r && $r->editorial_content, 404);
$content = json_decode($r->editorial_content, true);
// Recheck the original bytes using the same binary gate as the library.
$binary = app(VerifiedDocumentBinary::class)->respond($this->publicResources()->where('r.id', $id)->first(['r.*', 'd.*']));
$image = ! empty($content['image_resource_id']) ? $this->publicResources()->where('r.id', $content['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->value('r.id') : null;
return Inertia::render('portal/article', ['article' => ['id' => $id, 'title' => $r->title, 'description' => $r->description, 'author' => $r->issuer, 'body' => $content['body'], 'image_url' => $image ? '/documentos/'.$image.'/view' : null, 'original_url' => '/documentos/'.$id]]);
}
}
+1 -1
View File
@@ -167,7 +167,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::choices()->orderBy('name')->get(['id', 'name', 'slug']),
'territoryPath' => app(InvestmentGeography::class)->path($demand->getAttribute('geo_location_id'), true), '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)]);
} }
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers;
use App\Services\ExistingBusinessClassification;
use App\Services\Mne\BusinessRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class ExistingBusinessClassificationController extends Controller
{
public function show(Request $request, string $id, ExistingBusinessClassification $service): Response|JsonResponse
{
$props = ['supplement' => $service->privateView($request->user(), app(BusinessRepository::class)->find($id))];
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/business-classification', $props);
}
public function act(Request $request, string $id, ExistingBusinessClassification $service): JsonResponse
{
$business = $service->act($request->user(), $id, $request->all());
return response()->json(['supplement' => $service->privateView($request->user(), $business)]);
}
}
@@ -5,7 +5,9 @@ namespace App\Http\Controllers;
use App\Models\ExistingBusiness; use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject; use App\Models\ExistingBusinessObject;
use App\Models\Sector; use App\Models\Sector;
use App\Policies\ExistingBusinessPolicy;
use App\Services\BusinessFormSchema; use App\Services\BusinessFormSchema;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts; use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake; use App\Services\ExistingBusinessIntake;
use App\Services\ExistingBusinessObjects; use App\Services\ExistingBusinessObjects;
@@ -15,9 +17,11 @@ use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibilityShadow; use App\Services\Mne\CompatibilityShadow;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -32,10 +36,27 @@ class ExistingBusinessController extends Controller
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', [ $query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', [
'submitted', 'triage', 'in_review', 'needs_information', 'approval_l1', 'approval_l2', 'approved', 'submitted', 'triage', 'in_review', 'needs_information', 'approval_l1', 'approval_l2', 'approved',
]); ]);
app(ExistingBusinessPolicy::class)->scopeReviewQueue($query, $request->user());
} else { } else {
$query->where('owner_user_id', $request->user()->id); $query->where('owner_user_id', $request->user()->id);
} }
$props = ['records' => $query->orderByDesc('updated_at')->paginate(20)->through(fn ($row) => $this->record($row)), $filters = $request->validate(['country' => ['nullable', app(CountryCatalogue::class)->rule()], 'origin' => ['nullable', Rule::in([...array_column(app(CountryCatalogue::class)->all(), 'code'), 'unknown'])], 'page' => ['nullable', 'integer', 'min:1']]);
$query->orderByDesc('updated_at');
if (! empty($filters['country']) || ! empty($filters['origin'])) {
// The private payload is encrypted: filter only the already-authorized collection.
$matches = $query->get()->filter(function ($business) use ($filters) {
$payload = $business->payload;
$origin = $payload['declared_origin_country_code'] ?? null;
$validOrigin = in_array($origin, array_column(app(CountryCatalogue::class)->all(), 'code'), true) ? $origin : 'unknown';
return (empty($filters['country']) || ($payload['country'] ?? null) === $filters['country']) && (empty($filters['origin']) || $validOrigin === $filters['origin']);
})->values();
$page = (int) ($filters['page'] ?? 1);
$records = new LengthAwarePaginator($matches->forPage($page, 20)->values(), $matches->count(), 20, $page, ['path' => $request->url(), 'query' => $request->query()]);
} else {
$records = $query->paginate(20)->withQueryString();
}
$props = ['records' => $records->through(fn ($row) => $this->record($row)), 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all(),
'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES]; 'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES];
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props); return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props);
@@ -46,7 +67,7 @@ class ExistingBusinessController extends Controller
$business = app(BusinessRepository::class)->find($id); $business = app(BusinessRepository::class)->find($id);
Gate::authorize('view', $business); Gate::authorize('view', $business);
app(CompatibilityShadow::class)->schedule($id); app(CompatibilityShadow::class)->schedule($id);
$props = ['sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business), $props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'modalityFormType' => \App\Services\ExistingBusinessProfileCategory::formType($business->modality), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business), 'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
'canTriage' => $request->user()->can('triage', $business), 'canTriage' => $request->user()->can('triage', $business),
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business), 'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
@@ -10,6 +10,7 @@ use App\Services\InvestmentZones;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -26,6 +27,7 @@ class InvestmentDiscoveryController extends Controller
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters), return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
'territorySelection' => app(InvestmentGeography::class)->selection($filters), 'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'guides' => app(\App\Services\SectorInvestment::class)->guides(\App\Models\Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(), 'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
'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') : [],
'territorial' => $this->territorial($filters)]); 'territorial' => $this->territorial($filters)]);
@@ -52,7 +54,7 @@ class InvestmentDiscoveryController extends Controller
if (! empty($filters['geo_location_id'])) { if (! empty($filters['geo_location_id'])) {
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, app(InvestmentGeography::class)->descendants($filters['geo_location_id'])); app(InvestmentGeography::class)->constrainDossiersToTerritories($query, app(InvestmentGeography::class)->descendants($filters['geo_location_id']));
} }
foreach (['zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) { foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation'] as $field) {
if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) { if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) {
return $query->whereRaw('false')->get(); return $query->whereRaw('false')->get();
} }
@@ -74,9 +76,9 @@ class InvestmentDiscoveryController extends Controller
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString()); return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString());
} }
public function references(InvestmentCatalogue $catalogue): JsonResponse public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
{ {
return response()->json($catalogue->references()); return response()->json($catalogue->references(false, $catalogue->filters($request)));
} }
public function detail(Request $request, string $slug, InvestmentCatalogue $catalogue): Response public function detail(Request $request, string $slug, InvestmentCatalogue $catalogue): Response
@@ -105,6 +107,7 @@ class InvestmentDiscoveryController extends Controller
unset($returnFilters['zone_id'], $returnFilters['from_dossier']); unset($returnFilters['zone_id'], $returnFilters['from_dossier']);
return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin, return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin,
'guides' => app(\App\Services\SectorInvestment::class)->guides($record->sector),
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null, 'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]); 'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]);
} }
@@ -128,7 +131,24 @@ class InvestmentDiscoveryController extends Controller
public function map(Request $request, InvestmentCatalogue $catalogue): JsonResponse public function map(Request $request, InvestmentCatalogue $catalogue): JsonResponse
{ {
return response()->json($catalogue->map($catalogue->filters($request))); $filters = $catalogue->filters($request);
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
$zoneFilters = $filters;
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
$zoneFilters['category'] = $filters['dimension'];
}
$zones = app(InvestmentZones::class)->search($zoneFilters);
foreach (['zee_id', 'zfi_id', 'park_id'] as $key) {
if (! empty($filters[$key])) {
$zones->where('id', $filters[$key]);
}
}
$context = $context->concat($zones->orderBy('name')->limit(30)->get(['id', 'name', 'category'])->map(fn ($z) => ['id' => 'zone:'.$z->id, 'title' => $z->name, 'kind' => ['zee' => 'ZEE', 'zfi' => 'ZFI', 'industrial_park' => 'Parque industrial'][$z->category] ?? $z->category, 'url' => '/zonas/'.$z->id]));
}
return response()->json([...$catalogue->map($filters), 'territorial_context' => $context->values(), 'context_limit_per_collection' => 30]);
} }
public function compare(Request $request, InvestmentCatalogue $catalogue): JsonResponse public function compare(Request $request, InvestmentCatalogue $catalogue): JsonResponse
@@ -7,13 +7,17 @@ use App\Models\InterestRequest;
use App\Models\InvestmentSpecificNeed; use App\Models\InvestmentSpecificNeed;
use App\Models\InvestmentSubmission; use App\Models\InvestmentSubmission;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission; use App\Services\InterestSubmission;
use App\Services\InvestmentCatalogue; use App\Services\InvestmentCatalogue;
use App\Services\InvestmentWorkspace; use App\Services\InvestmentWorkspace;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\InvestorContextConsumers;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@@ -27,7 +31,14 @@ class InvestmentSubmissionController extends Controller
{ {
public function index(Request $request): Response|JsonResponse public function index(Request $request): Response|JsonResponse
{ {
$submissions = InvestmentSubmission::where('user_id', $request->user()->id)->latest()->paginate(20)->through(function ($row) { $query = InvestmentSubmission::where('user_id', $request->user()->id);
if (! $request->user()->hasVerifiedEmail()) {
// The existing payload is encrypted; scope after decryption, never infer ownership from email.
$simpleIds = InvestmentSubmission::where('user_id', $request->user()->id)->where('status', 'submitted')->get(['id', 'payload'])
->filter(fn ($row) => ($row->payload['simple_participation'] ?? false) === true)->modelKeys();
$query->whereIn('id', $simpleIds);
}
$submissions = $query->latest()->paginate(20)->through(function ($row) {
$interest = $row->interest_request_id ? InterestRequest::find($row->interest_request_id) : null; $interest = $row->interest_request_id ? InterestRequest::find($row->interest_request_id) : null;
return ['id' => $row->id, 'status' => $row->status, 'version' => $row->version, 'created_at' => $row->created_at, return ['id' => $row->id, 'status' => $row->status, 'version' => $row->version, 'created_at' => $row->created_at,
@@ -49,7 +60,10 @@ class InvestmentSubmissionController extends Controller
$company = DB::table('investment_company_declarations')->where('id', $data['company_id'])->where('user_id', $request->user()->id)->first(); $company = DB::table('investment_company_declarations')->where('id', $data['company_id'])->where('user_id', $request->user()->id)->first();
abort_unless($company !== null, 404); abort_unless($company !== null, 404);
$companyData = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR); $companyData = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
$payload = [...$payload, 'organisation' => $companyData['name'], 'representative_role' => $companyData['role'], 'country' => $companyData['country']]; $payload = [...$payload, 'organisation' => $companyData['name'], 'representative_role' => $companyData['role'], 'incorporation_country_code' => $companyData['incorporation_country_code'] ?? null];
if (isset($companyData['organization_country_snapshot'])) {
$payload['organization_country_snapshot'] = $companyData['organization_country_snapshot'];
}
} }
unset($data['company_id']); unset($data['company_id']);
if (! empty($data['opportunity_id'])) { if (! empty($data['opportunity_id'])) {
@@ -111,24 +125,56 @@ class InvestmentSubmissionController extends Controller
$target = $row->opportunity_id ? Opportunity::published()->find($row->opportunity_id) : null; $target = $row->opportunity_id ? Opportunity::published()->find($row->opportunity_id) : null;
$dossier = $row->dossier_id ? InvestmentPortfolioController::visible()->find($row->dossier_id) : null; $dossier = $row->dossier_id ? InvestmentPortfolioController::visible()->find($row->dossier_id) : null;
$zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']); $zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']);
$data = ['submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin, $contextAvailable = app(VirtualDesk::class)->installed();
'target' => ($target ? $target->title : null) ?? ($dossier ? $dossier->title : null), 'references' => [ $boundCase = $contextAvailable ? DB::table('desk_cases')->where('submission_id', $id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first() : null;
$contextChoices = $contextAvailable && (int) $row->user_id === (int) $request->user()->id && $row->status === 'draft' && ! $boundCase
? DB::table('desk_cases')->where('user_id', $request->user()->id)->whereNotNull('journey_id')->whereNull('closed_at')->whereNull('submission_id')->orderBy('title')->get(['id', 'title', 'version']) : [];
$data = ['contextDossierId' => $boundCase?->id, 'contextChoices' => $contextChoices, 'boundContextRevision' => $contextAvailable ? app(InvestorContextConsumers::class)->submissionRevision($id) : 0, 'countries' => app(CountryCatalogue::class)->all(), 'submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
'target' => ($target ? $target->title : null) ?? ($dossier ? $dossier->title : null) ?? ($row->payload['opportunity_title'] ?? null), 'references' => [
...$catalogue->references(), 'options' => DB::table('investment_reference_options')->orderBy('label')->get()], ...$catalogue->references(), 'options' => DB::table('investment_reference_options')->orderBy('label')->get()],
'needs' => InvestmentSpecificNeed::where('submission_id', $id)->get(), 'needs' => InvestmentSpecificNeed::where('submission_id', $id)->get(),
'attachments' => DB::table('investment_submission_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id') 'attachments' => DB::table('investment_submission_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.submission_id', $id)->whereNull('d.deleted_at')->get(['a.id', 'd.file_name']), ->where('a.submission_id', $id)->whereNull('d.deleted_at')->get(['a.id', 'd.file_name']),
'events' => DB::table('investment_submission_events')->where('submission_id', $id)->orderBy('id')->get(['action', 'version', 'created_at']), 'events' => DB::table('investment_submission_events')->where('submission_id', $id)->orderBy('id')->get(['action', 'version', 'created_at'])
->concat($interest ? DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)->orderBy('created_at')->get(['to_status', 'created_at'])->map(fn ($event) => ['action' => $event->to_status, 'version' => $row->version, 'created_at' => $event->created_at]) : [])->sortBy('created_at')->values(),
'revisions' => DB::table('investment_submission_revisions')->where('submission_id', $id)->orderByDesc('version')->get(['version', 'created_at']), 'revisions' => DB::table('investment_submission_revisions')->where('submission_id', $id)->orderByDesc('version')->get(['version', 'created_at']),
'messages' => DB::table('investment_messages')->where('submission_id', $id)->orderBy('created_at')->get(['id', 'sender_role', 'body', 'created_at'])->map(function ($message) { 'messages' => DB::table('investment_messages')->where('submission_id', $id)->orderBy('created_at')->get(['id', 'sender_role', 'body', 'created_at'])->map(function ($message) {
$message->body = Crypt::decryptString($message->body); $message->body = Crypt::decryptString($message->body);
return $message; return $message;
}), }),
'receipt' => $interest?->only(['reference', 'status']), 'management' => (int) $row->user_id !== $request->user()->id]; 'receipt' => $interest?->only(['reference', 'status', 'next_action', 'next_action_due_at']), 'management' => (int) $row->user_id !== $request->user()->id];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/submission', $data); return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/submission', $data);
} }
public function bindContext(Request $request, string $id): JsonResponse
{
abort_unless(app(VirtualDesk::class)->installed(), 422, 'O vínculo ao percurso do investimento não está disponível neste destino. A manifestação e a sua origem permanecem guardadas.');
abort_if(array_diff(array_keys($request->all()), ['case_id', 'case_version', 'version', '_token']), 422, 'Parâmetros de associação inválidos.');
$data = $request->validate(['case_id' => 'required|uuid', 'case_version' => 'required|integer|min:1', 'version' => 'required|integer|min:1']);
$result = DB::transaction(function () use ($request, $id, $data) {
// Serialize all links for this submission before locking the selected case.
$row = $this->owned($request, $id, true, true);
$desk = app(VirtualDesk::class);
$case = $desk->case($request->user(), $data['case_id'], true, true);
abort_unless((int) $case->user_id === (int) $request->user()->id && $case->journey_id, 403, 'Dossier próprio autorizado necessário.');
$existing = DB::table('desk_cases')->where('submission_id', $id)->first(['id']);
if ($existing && $existing->id === $case->id) {
return ['case_id' => $case->id, 'version' => $row->version, 'case_version' => (int) $case->version, 'replayed' => true];
}
abort_if($existing || $case->submission_id, 409, 'Existe um vínculo anterior; não foi substituído nem criado outro dossier.');
abort_unless($row->status === 'draft' && ! $case->closed_at && (int) $row->version === (int) $data['version'] && (int) $case->version === (int) $data['case_version'], 409, 'Rascunho ou dossier alterado. Recarregue antes de associar.');
DB::table('desk_cases')->where('id', $case->id)->update(['submission_id' => $id, 'version' => $case->version + 1, 'updated_at' => now()]);
$row->update(['version' => $row->version + 1]);
// Binding does not save form edits or assert that the context has been reviewed.
$this->event($row, $request, 'context_bound');
$desk->event($desk->case($request->user(), $case->id), $request->user(), 'manifestation_context_bound', ['submission_id' => $id, 'previous_case_version' => (int) $case->version]);
return ['case_id' => $case->id, 'version' => $row->version, 'case_version' => (int) $case->version + 1, 'replayed' => false];
}, 3);
return response()->json($result);
}
private function owned(Request $request, string $id, bool $lock = false, bool $ownerOnly = false): InvestmentSubmission private function owned(Request $request, string $id, bool $lock = false, bool $ownerOnly = false): InvestmentSubmission
{ {
$query = InvestmentSubmission::whereKey($id); $query = InvestmentSubmission::whereKey($id);
@@ -144,10 +190,14 @@ class InvestmentSubmissionController extends Controller
{ {
$required = $submitting ? 'required' : 'nullable'; $required = $submitting ? 'required' : 'nullable';
$data = $request->validate(['version' => ['required', 'integer', 'min:1'], $data = $request->validate(['version' => ['required', 'integer', 'min:1'],
'payload' => ['required', 'array:full_name,email,phone,country,organisation,representative_role,experience,investment_capacity,profile_id,sector,objective,participation_id,partnership_id,estimated_amount,currency,horizon,location,cluster_ids,corridor_ids,project_ids,contact_consent,other_details'], 'payload' => ['required', 'array:full_name,email,phone,country,residence_country_code,incorporation_country_code,organization_country_snapshot,declared_origin_country_code,organisation,representative_role,experience,investment_capacity,profile_id,sector,objective,participation_id,partnership_id,estimated_amount,currency,horizon,location,cluster_ids,corridor_ids,project_ids,contact_consent,other_details'],
'payload.organization_country_snapshot' => ['sometimes', 'array', 'max:10'],
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.other_details' => ['nullable', 'string', 'max:5000'], 'payload.other_details' => ['nullable', 'string', 'max:5000'],
'payload.full_name' => [$required, 'string', ...($submitting ? ['min:3'] : []), 'max:150'], 'payload.email' => [$required, $submitting ? 'email:rfc' : 'string', 'max:150'], 'payload.full_name' => [$required, 'string', ...($submitting ? ['min:3'] : []), 'max:150'], 'payload.email' => [$required, $submitting ? 'email:rfc' : 'string', 'max:150'],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => [$required, 'string', 'max:100'], 'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => [$submitting ? 'required_without:payload.declared_origin_country_code' : 'nullable', 'nullable', 'string', 'max:100'],
'payload.organisation' => ['nullable', 'string', 'max:200'], 'payload.representative_role' => ['nullable', 'string', 'max:150'], 'payload.organisation' => ['nullable', 'string', 'max:200'], 'payload.representative_role' => ['nullable', 'string', 'max:150'],
'payload.experience' => ['nullable', 'string', 'max:2000'], 'payload.investment_capacity' => ['nullable', 'string', 'max:1000'], 'payload.experience' => ['nullable', 'string', 'max:2000'], 'payload.investment_capacity' => ['nullable', 'string', 'max:1000'],
'payload.profile_id' => [$required, 'integer'], 'payload.sector' => [$required, 'string', 'max:150'], 'payload.profile_id' => [$required, 'integer'], 'payload.sector' => [$required, 'string', 'max:150'],
@@ -213,7 +263,7 @@ class InvestmentSubmissionController extends Controller
$version = DB::transaction(function () use ($request, $id, $data) { $version = DB::transaction(function () use ($request, $id, $data) {
$row = $this->owned($request, $id, true, true); $row = $this->owned($request, $id, true, true);
abort_unless($row->status === 'draft' && $row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue antes de guardar.'); abort_unless($row->status === 'draft' && $row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue antes de guardar.');
$row->update(['payload' => $data['payload'], 'version' => $row->version + 1]); $row->update(['payload' => $this->preserveCountrySource($row, $data['payload']), 'version' => $row->version + 1]);
InvestmentSpecificNeed::where('submission_id', $id)->delete(); InvestmentSpecificNeed::where('submission_id', $id)->delete();
foreach ($data['needs'] ?? [] as $need) { foreach ($data['needs'] ?? [] as $need) {
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]); InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
@@ -226,6 +276,23 @@ class InvestmentSubmissionController extends Controller
return $request->expectsJson() ? response()->json(['version' => $version]) : back()->with('success', 'Rascunho guardado.'); return $request->expectsJson() ? response()->json(['version' => $version]) : back()->with('success', 'Rascunho guardado.');
} }
/** @param array<string, mixed> $payload
* @return array<string, mixed> */
private function preserveCountrySource(InvestmentSubmission $row, array $payload): array
{
$source = $row->payload['organization_country_snapshot'] ?? null;
if (isset($payload['organization_country_snapshot']) && (! is_array($payload['organization_country_snapshot']) || ! is_array($source) ||
Arr::sortRecursive($payload['organization_country_snapshot']) !== Arr::sortRecursive($source))) {
throw ValidationException::withMessages(['payload.organization_country_snapshot' => 'A proveniência é recuperada no servidor; não pode ser substituída pelo formulário.']);
}
unset($payload['organization_country_snapshot']);
if ($source && ($row->payload['incorporation_country_code'] ?? null) === ($payload['incorporation_country_code'] ?? null)) {
$payload['organization_country_snapshot'] = $source;
}
return $payload;
}
public function submit(Request $request, string $id, InterestSubmission $intake): RedirectResponse|JsonResponse public function submit(Request $request, string $id, InterestSubmission $intake): RedirectResponse|JsonResponse
{ {
// Replaying a completed submission returns only the owner's existing receipt. // Replaying a completed submission returns only the owner's existing receipt.
@@ -244,7 +311,7 @@ class InvestmentSubmissionController extends Controller
if ($row->dossier_id) { if ($row->dossier_id) {
InvestmentPortfolioController::visible()->findOrFail($row->dossier_id); InvestmentPortfolioController::visible()->findOrFail($row->dossier_id);
} }
$p = $data['payload']; $p = $this->preserveCountrySource($row, $data['payload']);
$zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']); $zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']);
if ($zoneOrigin) { if ($zoneOrigin) {
$zone = app(InvestmentZones::class)->visible()->whereKey($zoneOrigin->zone_id)->lockForUpdate()->firstOrFail(); $zone = app(InvestmentZones::class)->visible()->whereKey($zoneOrigin->zone_id)->lockForUpdate()->firstOrFail();
@@ -257,10 +324,14 @@ class InvestmentSubmissionController extends Controller
$interest = $intake->receive(['email' => $p['email'], 'fullName' => $p['full_name'], 'message' => $p['objective'], 'submission_id' => $id], $id, $interest = $intake->receive(['email' => $p['email'], 'fullName' => $p['full_name'], 'message' => $p['objective'], 'submission_id' => $id], $id,
fn () => InterestRequest::create(['reference' => 'IR-'.now()->year.'-'.Str::ulid(), 'opportunity_id' => $opportunity?->id, fn () => InterestRequest::create(['reference' => 'IR-'.now()->year.'-'.Str::ulid(), 'opportunity_id' => $opportunity?->id,
'opportunity_reference' => $opportunity?->reference, 'full_name' => $p['full_name'], 'email' => $p['email'], 'phone' => $p['phone'] ?? null, 'opportunity_reference' => $opportunity?->reference, 'full_name' => $p['full_name'], 'email' => $p['email'], 'phone' => $p['phone'] ?? null,
'country' => $p['country'], 'investor_type' => empty($p['organisation']) ? 'individual' : 'empresa', 'country' => $p['country'] ?? 'Não informado', 'investor_type' => empty($p['organisation']) ? 'individual' : 'empresa',
'sector_interest' => $p['sector'], 'message' => $p['objective'], 'privacy_consent' => true, 'consented_at' => now(), 'sector_interest' => $p['sector'], 'message' => $p['objective'], 'privacy_consent' => true, 'consented_at' => now(),
'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$id, 'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$id,
'metadata' => ['submission_id' => $id, 'portal_user_id' => $request->user()->id, 'dossier_id' => $row->dossier_id, 'metadata' => ['submission_id' => $id, 'portal_user_id' => $request->user()->id, 'dossier_id' => $row->dossier_id,
'declared_origin_country_code' => $p['declared_origin_country_code'] ?? null,
'residence_country_code' => $p['residence_country_code'] ?? null,
'incorporation_country_code' => $p['incorporation_country_code'] ?? null,
...(isset($p['organization_country_snapshot']) ? ['organization_country_snapshot' => $p['organization_country_snapshot']] : []),
...($zoneOrigin ? ['zone_origin' => (array) $zoneOrigin] : [])]])); ...($zoneOrigin ? ['zone_origin' => (array) $zoneOrigin] : [])]]));
$row->update(['payload' => $p, 'version' => $row->version + 1, 'interest_request_id' => $interest->id, 'status' => 'submitted']); $row->update(['payload' => $p, 'version' => $row->version + 1, 'interest_request_id' => $interest->id, 'status' => 'submitted']);
InvestmentSpecificNeed::where('submission_id', $id)->delete(); InvestmentSpecificNeed::where('submission_id', $id)->delete();
@@ -334,10 +405,18 @@ class InvestmentSubmissionController extends Controller
private function event(InvestmentSubmission $row, Request $request, string $action): void private function event(InvestmentSubmission $row, Request $request, string $action): void
{ {
$boundCase = app(VirtualDesk::class)->installed() ? DB::table('desk_cases')->where('submission_id', $row->id)->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first() : null;
$binding = null;
if ($boundCase) {
$binding = app(InvestorContextConsumers::class)->submissionRevision($row->id);
if ($action === 'submitted' || $request->boolean('context_reviewed')) {
$binding = app(InvestorContextConsumers::class)->assertReviewed($request->user(), $boundCase->id, $request->all(), $binding);
}
}
app(InvestmentWorkspace::class)->snapshot($row); app(InvestmentWorkspace::class)->snapshot($row);
DB::table('investment_submission_events')->insert(['submission_id' => $row->id, 'actor_id' => $request->user()->id, 'action' => $action, 'version' => $row->version, 'created_at' => now()]); DB::table('investment_submission_events')->insert(['submission_id' => $row->id, 'actor_id' => $request->user()->id, 'action' => $action, 'version' => $row->version, 'created_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'investment-submission', 'entity_type' => 'investment_submissions', DB::table('audit_events')->insert(['source_system' => 'investment-submission', 'entity_type' => 'investment_submissions',
'entity_id' => $row->id, 'actor_user_id' => $request->user()->id, 'action' => $action, 'entity_id' => $row->id, 'actor_user_id' => $request->user()->id, 'action' => $action,
'after_data' => json_encode(['version' => $row->version, 'status' => $row->status], JSON_THROW_ON_ERROR)]); 'after_data' => json_encode(['version' => $row->version, 'status' => $row->status, ...($binding !== null ? ['investment_context_revision' => $binding] : [])], JSON_THROW_ON_ERROR)]);
} }
} }
@@ -2,14 +2,31 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\PortalProfileAccess;
use App\Services\TerritoryGeometry;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
class InvestmentTerritoryController extends Controller class InvestmentTerritoryController extends Controller
{ {
public function geometries(Request $request): JsonResponse
{
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
$profile = $request->is('minhas-oportunidades/*');
$management = $request->is('management/*') || $profile;
if ($management) {
$access = app(PortalProfileAccess::class);
abort_unless($profile ? ($access->grants($request->user()) !== [] || $access->superuser($request->user())) : $request->user()?->can('manage-portal'), 403);
}
return response()->json(app(TerritoryGeometry::class)->context($data['territory_id'], $management));
}
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones']; private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
public function subjects(Request $request): JsonResponse public function subjects(Request $request): JsonResponse
@@ -17,6 +34,9 @@ class InvestmentTerritoryController extends Controller
$data = $request->validate(['kind' => ['required', 'in:'.implode(',', array_keys(self::TABLES))], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]); $data = $request->validate(['kind' => ['required', 'in:'.implode(',', array_keys(self::TABLES))], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$column = $data['kind'] === 'opportunities' ? 'title' : 'name'; $column = $data['kind'] === 'opportunities' ? 'title' : 'name';
$query = DB::table(self::TABLES[$data['kind']])->whereNull('deleted_at'); $query = DB::table(self::TABLES[$data['kind']])->whereNull('deleted_at');
if ($data['kind'] === 'opportunities' && Schema::hasColumn('opportunities', 'owner_user_id')) {
$query->whereIn('id', app(PortalProfileAccess::class)->scope(Opportunity::query(), $request->user())->select('id'));
}
if (! empty($data['q'])) { if (! empty($data['q'])) {
$query->whereRaw($column.' ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']); $query->whereRaw($column.' ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
} }
@@ -26,6 +46,10 @@ class InvestmentTerritoryController extends Controller
public function options(Request $request): JsonResponse public function options(Request $request): JsonResponse
{ {
if ($request->is('minhas-oportunidades/*')) {
$access = app(PortalProfileAccess::class);
abort_unless($access->grants($request->user()) !== [] || $access->superuser($request->user()), 403);
}
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]); $data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type']) $query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type'])
->whereIn('data_classification', ['public', 'internal']); ->whereIn('data_classification', ['public', 'internal']);
@@ -4,7 +4,9 @@ namespace App\Http\Controllers;
use App\Models\InvestmentSubmission; use App\Models\InvestmentSubmission;
use App\Models\User; use App\Models\User;
use App\Services\CountryCatalogue;
use App\Services\InvestmentWorkspace; use App\Services\InvestmentWorkspace;
use App\Services\OrganizationCountry;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -18,9 +20,10 @@ class InvestmentWorkspaceController extends Controller
{ {
public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse
{ {
$data = ['account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations') $data = ['organizationCountryAvailable' => app(OrganizationCountry::class)->available(), 'organizations' => app(OrganizationCountry::class)->represented($request->user()), 'countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) { ->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) {
$company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR); $company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
$company->countrySource = $company->payload['organization_country_snapshot'] ?? null;
return $company; return $company;
})]; })];
@@ -31,7 +34,8 @@ class InvestmentWorkspaceController extends Controller
public function saveProfile(Request $request): RedirectResponse|JsonResponse public function saveProfile(Request $request): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], $data = $request->validate(['version' => ['required', 'integer', 'min:0'],
'payload' => ['required', 'array:phone,country,sector,experience,investment_capacity'], 'payload' => ['required', 'array:phone,country,residence_country_code,sector,experience,investment_capacity'],
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'], 'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'],
'payload.sector' => ['nullable', 'string', 'max:150'], 'payload.experience' => ['nullable', 'string', 'max:2000'], 'payload.sector' => ['nullable', 'string', 'max:150'], 'payload.experience' => ['nullable', 'string', 'max:2000'],
'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]); 'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]);
@@ -53,8 +57,9 @@ class InvestmentWorkspaceController extends Controller
public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], $data = $request->validate(['version' => ['required', 'integer', 'min:0'],
'payload' => ['required', 'array:name,country,registration,sector,role,description'], 'payload' => ['required', 'array:name,country,incorporation_country_code,registration,sector,role,description'],
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required', 'string', 'max:100'], 'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required_without:payload.incorporation_country_code', 'nullable', 'string', 'max:100'],
'payload.registration' => ['nullable', 'string', 'max:100'], 'payload.sector' => ['nullable', 'string', 'max:150'], 'payload.registration' => ['nullable', 'string', 'max:100'], 'payload.sector' => ['nullable', 'string', 'max:150'],
'payload.role' => ['required', 'string', 'max:150'], 'payload.description' => ['nullable', 'string', 'max:2000']]); 'payload.role' => ['required', 'string', 'max:150'], 'payload.description' => ['nullable', 'string', 'max:2000']]);
$result = DB::transaction(function () use ($request, $id, $data) { $result = DB::transaction(function () use ($request, $id, $data) {
@@ -65,9 +70,15 @@ class InvestmentWorkspaceController extends Controller
abort_if(! $id && DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->count() >= 20, 422, 'Máximo de vinte empresas declaradas.'); abort_if(! $id && DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->count() >= 20, 422, 'Máximo de vinte empresas declaradas.');
$id ??= (string) Str::uuid(); $id ??= (string) Str::uuid();
$version = (int) $data['version'] + 1; $version = (int) $data['version'] + 1;
$previous = $row ? json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR) : [];
$payload = [...$previous, ...$data['payload']];
if (($previous['incorporation_country_code'] ?? null) !== ($payload['incorporation_country_code'] ?? null)) {
unset($payload['organization_country_snapshot']);
}
$encrypted = Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR));
DB::table('investment_company_declarations')->updateOrInsert(['id' => $id], ['user_id' => $request->user()->id, 'version' => $version, DB::table('investment_company_declarations')->updateOrInsert(['id' => $id], ['user_id' => $request->user()->id, 'version' => $version,
'payload' => Crypt::encryptString(json_encode($data['payload'], JSON_THROW_ON_ERROR)), 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]); 'payload' => $encrypted, 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
$this->audit($request, 'company_declared', 'investment_company_declarations', $id, ['version' => $version]); $this->audit($request, 'company_declared', 'investment_company_declarations', $id, ['version' => $version, 'before_payload' => $row?->payload, 'after_payload' => $encrypted]);
return ['id' => $id, 'version' => $version]; return ['id' => $id, 'version' => $version];
}); });
@@ -75,6 +86,36 @@ class InvestmentWorkspaceController extends Controller
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Declaração de empresa guardada.'); return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Declaração de empresa guardada.');
} }
public function organizationCountry(Request $request, string $id, OrganizationCountry $service): RedirectResponse|JsonResponse
{
$result = $service->save($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'País de constituição guardado no cadastro mestre; submissões anteriores preservadas.');
}
public function reuseOrganizationCountry(Request $request, string $id, OrganizationCountry $service): RedirectResponse|JsonResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'organization_id' => 'required|uuid', 'organization_version' => 'required|integer|min:1']);
$result = DB::transaction(function () use ($request, $id, $data, $service) {
$row = DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->lockForUpdate()->first();
abort_unless($row !== null, 404);
abort_unless((int) $row->version === (int) $data['version'], 409, 'Declaração alterada. Recarregue.');
$snapshot = $service->snapshot($request->user(), $data['organization_id']);
abort_unless((int) $snapshot['organization_version'] === (int) $data['organization_version'], 409, 'País mestre alterado. Recarregue.');
$payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
$payload['incorporation_country_code'] = $snapshot['country'];
$payload['organization_country_snapshot'] = $snapshot;
$encrypted = Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR));
DB::table('investment_company_declarations')->where('id', $id)->update(['payload' => $encrypted, 'version' => $row->version + 1, 'updated_at' => now()]);
$this->audit($request, 'organization_country_reused', 'investment_company_declarations', $id, ['version' => $row->version + 1,
'before_payload' => $row->payload, 'after_payload' => $encrypted, 'organization_id' => $data['organization_id'], 'organization_version' => $snapshot['organization_version']]);
return ['version' => $row->version + 1, 'country' => $snapshot['country']];
});
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'País mestre reutilizado nesta declaração; manifestações anteriores não alteradas.');
}
public function notifications(Request $request): Response|JsonResponse public function notifications(Request $request): Response|JsonResponse
{ {
$query = DB::table('investment_notifications')->where('user_id', $request->user()->id); $query = DB::table('investment_notifications')->where('user_id', $request->user()->id);
@@ -10,6 +10,9 @@ use App\Services\InvestmentGeography;
use App\Services\InvestmentTerritorialTraceability; use App\Services\InvestmentTerritorialTraceability;
use App\Services\InvestmentZoneAccess; use App\Services\InvestmentZoneAccess;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\InvestmentZoneOperationalProfile;
use App\Services\InvestmentZonePathContext;
use App\Services\InvestmentZoneProfileInstallation;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -30,7 +33,8 @@ class InvestmentZoneController extends Controller
$zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province); $zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province);
$zone->setAttribute('district', collect($territoryPath)->firstWhere('location_type', 'district')->name ?? $zone->district); $zone->setAttribute('district', collect($territoryPath)->firstWhere('location_type', 'district')->name ?? $zone->district);
$zone->setAttribute('territory_path', $territoryPath); $zone->setAttribute('territory_path', $territoryPath);
$publicFields = ['id', 'code', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'historical_territory', 'data_as_of', 'sources_consulted_at', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'territory_path', 'validation_status', 'updated_at']; $zone->setAttribute('operational_details_public',app(\App\Services\InvestmentZoneOperationalDetails::class)->publicData($zone));
$publicFields = ['operational_details_public', 'version_no', 'published_at', 'id', 'code', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'historical_territory', 'data_as_of', 'sources_consulted_at', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'territory_path', 'validation_status', 'updated_at'];
$locations = DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id') $locations = DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
->where('zl.zone_id', $id)->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public')) ->where('zl.zone_id', $id)->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
->whereNull('g.deleted_at')->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'g.parent_id', 'zl.scope_type', 'zl.source_reference', 'zl.validation_status']); ->whereNull('g.deleted_at')->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'g.parent_id', 'zl.scope_type', 'zl.source_reference', 'zl.validation_status']);
@@ -62,7 +66,9 @@ class InvestmentZoneController extends Controller
? url('/management/investment/zones/'.$id.'/attachments/'.$attachment->id) ? url('/management/investment/zones/'.$id.'/attachments/'.$attachment->id)
: url('/zonas/'.$id.'/anexos/'.$attachment->id); : url('/zonas/'.$id.'/anexos/'.$attachment->id);
}); });
$props = ['record' => $management ? $zone : $zone->only($publicFields), 'source' => $source, 'operator' => $operator, 'management' => $management, $props = ['record' => $management ? app(InvestmentZoneOperationalProfile::class)->management($zone) : app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->only($publicFields)), 'source' => $source, 'operator' => $operator, 'management' => $management,
'profileAvailable' => $management && app(InvestmentZoneOperationalProfile::class)->installed(),
'zoneContext' => !$management && $zone->category === 'industrial_park' ? app(InvestmentZonePathContext::class)->context($id,(int)$zone->version_no) : null,
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence'), 'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence'),
'related' => $related->unique('id')->values(), 'related' => $related->unique('id')->values(),
'relations' => $management ? DB::table('investment_zone_relations')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [], 'relations' => $management ? DB::table('investment_zone_relations')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
@@ -71,6 +77,7 @@ class InvestmentZoneController extends Controller
'dossiers' => InvestmentDossier::orderBy('title')->limit(200)->get(['id', 'title', 'project_id', 'cluster_id', 'corridor_id'])] : null, 'dossiers' => InvestmentDossier::orderBy('title')->limit(200)->get(['id', 'title', 'project_id', 'cluster_id', 'corridor_id'])] : null,
'opportunities' => $opportunities, 'opportunities' => $opportunities,
'legalSources' => $management ? DB::table('investment_legal_sources')->orderByDesc('created_at')->limit(100)->get() : [], 'legalSources' => $management ? DB::table('investment_legal_sources')->orderByDesc('created_at')->limit(100)->get() : [],
'economicActivities' => $management ? app(\App\Services\EconomicReferenceCatalog::class)->activities() : [],
'operators' => $management ? DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->limit(200)->get(['id', 'name']) : [], 'operators' => $management ? DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->limit(200)->get(['id', 'name']) : [],
'links' => $management ? DB::table('investment_zone_links')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [], 'links' => $management ? DB::table('investment_zone_links')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
'locations' => $locations, 'locations' => $locations,
@@ -91,7 +98,8 @@ class InvestmentZoneController extends Controller
abort_if((! empty($filters['development_status']) || ! empty($filters['availability_status'])) && ! Schema::hasColumn('investment_zones', 'source_evidence'), 503, abort_if((! empty($filters['development_status']) || ! empty($filters['availability_status'])) && ! Schema::hasColumn('investment_zones', 'source_evidence'), 503,
'Os filtros de desenvolvimento e disponibilidade estarão disponíveis após a migração do catálogo de zonas.'); 'Os filtros de desenvolvimento e disponibilidade estarão disponíveis após a migração do catálogo de zonas.');
$path = app(InvestmentGeography::class)->selection($filters); $path = app(InvestmentGeography::class)->selection($filters);
$publicColumns = ['id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at']; $publicColumns = ['primary_territory_id', 'version_no', 'id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'];
if(app(\App\Services\InvestmentZoneOperationalDetails::class)->installed()){$publicColumns[]='operational_details';}
$publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column))); $publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id') $rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString(); ->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString();
@@ -105,9 +113,11 @@ class InvestmentZoneController extends Controller
->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public')) ->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'zl.scope_type'])); ->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'zl.scope_type']));
return $zone; if (! $management) { $zone->makeHidden('primary_territory_id'); }
return $management ? $zone : [...app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->toArray()),'operational_details_public'=>app(\App\Services\InvestmentZoneOperationalDetails::class)->publicData($zone)];
}); });
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path, $props = ['detailsInstallation'=>$management ? app(\App\Services\InvestmentZoneOperationalDetailsInstallation::class)->preview($request->user()) : null, 'installation' => $management ? app(InvestmentZoneProfileInstallation::class)->preview($request->user()) : null, 'records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path,
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence')]; 'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence')];
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props); return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
@@ -183,10 +193,35 @@ class InvestmentZoneController extends Controller
'source_evidence.*.source_date' => ['nullable', 'date_format:Y-m-d'], 'source_evidence.*.source_date' => ['nullable', 'date_format:Y-m-d'],
'area_value' => ['nullable', 'numeric', 'min:0'], 'area_unit' => ['nullable', 'string', 'max:24'], 'area_value' => ['nullable', 'numeric', 'min:0'], 'area_unit' => ['nullable', 'string', 'max:24'],
'aliases' => ['sometimes', 'array', 'max:20'], 'aliases.*' => ['string', 'max:120'], 'aliases' => ['sometimes', 'array', 'max:20'], 'aliases.*' => ['string', 'max:120'],
'activities' => ['sometimes', 'array', 'max:50'], 'activities.*' => ['array:name,status,source_reference'], 'operational_details' => ['sometimes','array'],
'activities' => ['sometimes', 'array', 'max:50'], 'activities.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
'activities.*.id' => ['nullable','uuid'],
'activities.*.source_date' => ['nullable','date_format:Y-m-d'],
'activities.*.kind' => ['nullable','in:infrastructure,service,access,other'],
'activities.*.scope' => ['nullable','in:inside,regional,unknown'],
'activities.*.capacity_type' => ['nullable','string','max:120'],
'activities.*.capacity_value' => ['nullable','numeric','min:0'],
'activities.*.capacity_unit' => ['nullable','string','max:40'],
'activities.*.focus' => ['nullable','in:promotional,potential,installed,unknown'],
'activities.*.economic_activity_id' => ['nullable','uuid','exists:economic_activities,id'],
'activities.*.support_document_ids' => ['sometimes','array','max:10'],
'activities.*.support_document_ids.*' => ['uuid'],
'activities.*.private_note' => ['nullable','string','max:2000'],
'activities.*.name' => ['required', 'string', 'max:300'], 'activities.*.status' => ['required', 'in:proposed,authorized,conditional,excluded,potential'], 'activities.*.name' => ['required', 'string', 'max:300'], 'activities.*.status' => ['required', 'in:proposed,authorized,conditional,excluded,potential'],
'activities.*.source_reference' => ['nullable', 'string', 'max:2000'], 'activities.*.source_reference' => ['nullable', 'string', 'max:2000'],
'resources' => ['sometimes', 'array', 'max:50'], 'resources.*' => ['array:name,status,source_reference'], 'resources' => ['sometimes', 'array', 'max:50'], 'resources.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
'resources.*.id' => ['nullable','uuid'],
'resources.*.source_date' => ['nullable','date_format:Y-m-d'],
'resources.*.kind' => ['nullable','in:infrastructure,service,access,other'],
'resources.*.scope' => ['nullable','in:inside,regional,unknown'],
'resources.*.capacity_type' => ['nullable','string','max:120'],
'resources.*.capacity_value' => ['nullable','numeric','min:0'],
'resources.*.capacity_unit' => ['nullable','string','max:40'],
'resources.*.focus' => ['nullable','in:promotional,potential,installed,unknown'],
'resources.*.economic_activity_id' => ['nullable','uuid','exists:economic_activities,id'],
'resources.*.support_document_ids' => ['sometimes','array','max:10'],
'resources.*.support_document_ids.*' => ['uuid'],
'resources.*.private_note' => ['nullable','string','max:2000'],
'resources.*.name' => ['required', 'string', 'max:120'], 'resources.*.status' => ['required', 'in:existing,planned,unconfirmed'], 'resources.*.name' => ['required', 'string', 'max:120'], 'resources.*.status' => ['required', 'in:existing,planned,unconfirmed'],
'resources.*.source_reference' => ['nullable', 'string', 'max:2000'], 'data_as_of' => ['nullable', 'date_format:Y-m-d'], 'resources.*.source_reference' => ['nullable', 'string', 'max:2000'], 'data_as_of' => ['nullable', 'date_format:Y-m-d'],
'sources_consulted_at' => ['nullable', 'date_format:Y-m-d'], 'parent_zone_id' => ['nullable', 'uuid', 'exists:investment_zones,id'], 'sources_consulted_at' => ['nullable', 'date_format:Y-m-d'], 'parent_zone_id' => ['nullable', 'uuid', 'exists:investment_zones,id'],
@@ -222,15 +257,18 @@ class InvestmentZoneController extends Controller
$data['district'] = $path[1]->name ?? null; $data['district'] = $path[1]->name ?? null;
} }
return response()->json($zones->save($id, $data, $request->user()->id), $id ? 200 : 201); $saved=$zones->save($id, $data, $request->user()->id);
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved), $id ? 200 : 201);
} }
public function transition(Request $request, InvestmentZones $zones, string $id, string $action): JsonResponse public function transition(Request $request, InvestmentZones $zones, string $id, string $action): JsonResponse
{ {
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]); $data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'base_public_version'=>['required_if:action,reconcile','nullable','integer','min:1']]);
if($action==='reconcile'){
return response()->json($action === 'publish' ? $zones->publish($id, $data['version_no'], $request->user()->id) $request->validate(['base_public_version'=>'required|integer|min:1']);
: $zones->suspend($id, $data['version_no'], $request->user()->id)); $saved=DB::transaction(function()use($id,$data,$request){$zone=InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();abort_unless($zone->category==='industrial_park',422);return app(InvestmentZoneOperationalProfile::class)->reconcile($zone,(int)$data['version_no'],(int)$data['base_public_version'],$request->user()->id);});
}else{$saved=$action === 'publish' ? $zones->publish($id,$data['version_no'],$request->user()->id) : $zones->suspend($id,$data['version_no'],$request->user()->id);}
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved));
} }
public function revisions(string $id): JsonResponse public function revisions(string $id): JsonResponse
@@ -0,0 +1,73 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentGeography;
use App\Services\InvestorContext;
use App\Services\InvestorContextInstallation;
use App\Services\InvestorPath;
use Illuminate\Http\Request;
use Inertia\Inertia;
final class InvestorContextController extends Controller
{
public function current(Request $r, InvestorContext $context)
{
return response()->json($context->current($r->user()));
}
public function focus(Request $r, InvestorContext $context)
{
return response()->json($context->focus($r->user(), $r->all()));
}
public function show(Request $r, string $id, InvestorContext $context)
{
return response()->json($context->view($r->user(), $id));
}
public function options(Request $r, InvestorContext $context)
{
$d = $r->validate(['q' => 'nullable|string|max:120']);
return response()->json($context->options($d['q'] ?? ''));
}
public function edit(Request $r, string $id, InvestorContext $context)
{
$data = $context->view($r->user(), $id);
abort_unless($data['can_write'], 403);
return Inertia::render('investor-path/context', ['initial' => $data, 'options' => $context->options(), 'source' => $r->query('source') ? $context->reference($r->validate(['source' => 'required|string|max:100'])['source']) : null, 'territorySelection' => isset($data['context']['selection']['territory']) ? app(InvestmentGeography::class)->path($data['context']['selection']['territory']['id']) : []]);
}
public function preview(Request $r, string $id, InvestorContext $context)
{
return response()->json($context->preview($r->user(), $id, $r->all()));
}
public function commit(Request $r, string $id, InvestorContext $context)
{
return response()->json($context->commit($r->user(), $id, $r->all()));
}
public function start(Request $r, InvestorPath $path, InvestorContext $context)
{
$d = $r->validate(['source' => 'nullable|string|max:100', 'step' => ['nullable', 'regex:/^S(0[1-9]|1[0-9])$/']]);
$ref = isset($d['source']) ? $context->reference($d['source']) : null;
return Inertia::render('investor-path/context-start', ['contexts' => $path->contexts($r->user()), 'source' => $ref, 'step' => $d['step'] ?? null]);
}
public function installation(Request $r, InvestorContextInstallation $install)
{
$plan = $install->preview($r->user());
return $r->expectsJson() ? response()->json($plan) : Inertia::render('investor-path/context-installation', ['plan' => $plan]);
}
public function install(Request $r, InvestorContextInstallation $install)
{
return response()->json($install->apply($r->user(),$r->all()));
}
}
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Services\Ai\EvidenceRepository; use App\Services\Ai\EvidenceRepository;
use App\Services\Ai\InvestorGuidance; use App\Services\Ai\InvestorGuidance;
use App\Services\InvestorPath;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -18,7 +19,10 @@ class InvestorGuidanceController extends Controller
$actor = $request->user(); $actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id'); $organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$cases = DB::table('desk_cases')->whereNull('closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations)) $cases = DB::table('desk_cases')->whereNull('closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))
->orderByDesc('updated_at')->get(['id', 'title']); ->orderByDesc('updated_at')->get(['id', 'title', 'journey_id'])->map(function ($case) {
return ['id' => $case->id, 'title' => $case->title, 'path_supported' => app(InvestorPath::class)->available()
&& $case->journey_id && DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->exists()];
});
return response()->json(['cases' => $cases]); return response()->json(['cases' => $cases]);
} }
@@ -0,0 +1,139 @@
<?php
namespace App\Http\Controllers;
use App\Services\FintechInvestment;
use App\Services\InvestorPath;
use App\Services\InvestmentZonePathContext;
use App\Services\LegacyContent;
use App\Services\SectorInvestment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;
class InvestorPathController extends Controller
{
public function index(Request $request, InvestorPath $path): JsonResponse|Response
{
abort_unless($path->available(), 404);
$data = ['contexts' => $path->contexts($request->user())];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
}
public function sectorStart(Request $request, string $sectorSlug, InvestorPath $path): JsonResponse|Response
{
abort_unless($path->available(), 404);
$data = ['contexts' => $path->contexts($request->user()), 'sectorSource' => app(SectorInvestment::class)->context($sectorSlug)];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
}
public function sectorAttach(Request $request, string $id): JsonResponse|RedirectResponse
{
app(SectorInvestment::class)->attach($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['ok' => true]) : redirect('/investimentos/'.$id)->with('success', 'Setor associado ao mesmo dossier.');
}
public function zoneStart(Request $request,string $zoneId,InvestorPath $path): JsonResponse|Response
{
abort_unless($path->available(),404);
$data=$request->validate(['consulted_public_version'=>'required|integer|min:1']);
$data=['contexts'=>$path->contexts($request->user()),'zoneSource'=>app(InvestmentZonePathContext::class)->context($zoneId,(int)$data['consulted_public_version'])];
return $request->expectsJson()?response()->json($data):Inertia::render('investor-path/index',$data);
}
public function zoneAttach(Request $request,string $id): JsonResponse|RedirectResponse
{
app(InvestmentZonePathContext::class)->attach($request->user(),$id,$request->all());
return $request->expectsJson()?response()->json(['ok'=>true]):redirect('/investimentos/'.$id)->with('success','Referência do parque guardada; não constitui reserva ou autorização.');
}
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
{
$zone=$request->has('zone_id') ? app(InvestmentZonePathContext::class)->input($request->all()) : null;
if($zone){ $request->validate(['confirm'=>'required|accepted']); app(InvestmentZonePathContext::class)->context($zone['zone_id'],(int)$zone['consulted_public_version']); }
$sector = $request->validate(['sector_slug' => 'nullable|string|max:150'])['sector_slug'] ?? null;
if ($sector !== null) {
app(SectorInvestment::class)->context($sector);
}
$source = $request->input('content_resource_id');
if ($source !== null) {
$resourceId = filter_var($source, FILTER_VALIDATE_INT);
abort_unless(is_int($resourceId) && $resourceId !== 0, 422);
app(LegacyContent::class)->articleForResource($resourceId);
}
$id = DB::transaction(function () use ($path, $request, $source, $sector, $zone): string {
$id = $path->create($request->user(), $request->all());
if ($source !== null) {
$case = $path->view($request->user(), $id)['case'];
app(LegacyContent::class)->attach($request->user(), $id, ['version' => $case['version'], 'resource_id' => (int) $source]);
}
if ($sector !== null) {
$case = $path->view($request->user(), $id)['case'];
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector]);
}
if($zone){$case=$path->view($request->user(),$id)['case']; app(InvestmentZonePathContext::class)->attach($request->user(),$id,[...$zone,'version'=>$case['version'],'confirm'=>true]);}
return $id;
});
return $request->expectsJson() ? response()->json(['id' => $id], 201) : redirect('/investimentos/'.$id)->with('success', 'Investimento guardado no seu dossier.');
}
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
{
$data = $path->view($request->user(), $id);
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/show', $data);
}
public function facts(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$path->facts($request->user(), $id, $request->all());
return $this->saved($request, 'Aplicabilidade registada; o histórico foi preservado.');
}
public function stage(Request $request, string $id, string $code, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$path->stage($request->user(), $id, $code, $request->all());
return $this->saved($request, 'Etapa e fundamento registados.');
}
public function tool(Request $request, string $id, InvestorPath $path): JsonResponse
{
abort_unless($path->available(), 404);
return response()->json(['result' => $path->returnTool($request, $id, $request->all())]);
}
public function task(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$task = $path->task($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['id' => $task], 201) : back()->with('success', 'Tarefa assumida no acompanhamento interno.');
}
public function fintech(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
app(FintechInvestment::class)->save($request->user(), $id, $request->all());
return $this->saved($request, 'Caracterização Fintech guardada no mesmo dossier; pendências e histórico preservados.');
}
private function saved(Request $request, string $message): JsonResponse|RedirectResponse
{
return $request->expectsJson() ? response()->json(['message' => $message]) : back()->with('success', $message);
}
}
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Models\InterestRequest; use App\Models\InterestRequest;
use App\Models\Investor; use App\Models\Investor;
use App\Models\InvestorJourney; use App\Models\InvestorJourney;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission; use App\Services\InterestSubmission;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -23,10 +24,12 @@ class InvestorWorkspaceController extends Controller
$interest = $journey->interest_request_id ? InterestRequest::find($journey->interest_request_id) : null; $interest = $journey->interest_request_id ? InterestRequest::find($journey->interest_request_id) : null;
return ['id' => $journey->id, 'dossier_id' => $dossier?->id, 'title' => $dossier->title ?? 'Ficha temporariamente indisponível', return ['id' => $journey->id, 'dossier_id' => $dossier?->id, 'title' => $dossier->title ?? 'Ficha temporariamente indisponível',
'status' => $journey->status, 'reference' => $interest?->reference, 'request_status' => $interest?->status]; 'status' => $journey->status, 'reference' => $interest?->reference, 'request_status' => $interest?->status,
'country' => $interest?->country,
'declared_origin' => app(CountryCatalogue::class)->describe($interest?->metadata['declared_origin_country_code'] ?? null)];
}); });
return Inertia::render('portfolio/workspace', ['journeys' => $journeys]); return Inertia::render('portfolio/workspace', ['journeys' => $journeys, 'countries' => app(CountryCatalogue::class)->all()]);
} }
public function start(Request $request, string $id): RedirectResponse public function start(Request $request, string $id): RedirectResponse
@@ -57,7 +60,8 @@ class InvestorWorkspaceController extends Controller
public function submit(Request $request, string $id, InterestSubmission $submission): RedirectResponse public function submit(Request $request, string $id, InterestSubmission $submission): RedirectResponse
{ {
$data = $request->validate(['message' => ['required', 'string', 'min:20', 'max:5000'], 'country' => ['required', 'string', 'max:100'], $data = $request->validate(['message' => ['required', 'string', 'min:20', 'max:5000'], 'country' => ['required', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'privacy_consent' => ['accepted'], 'role' => ['required', 'in:investir,financiar,fornecer,operar,parceria'], 'privacy_consent' => ['accepted'], 'role' => ['required', 'in:investir,financiar,fornecer,operar,parceria'],
'horizon' => ['required', 'string', 'max:100']]); 'horizon' => ['required', 'string', 'max:100']]);
DB::transaction(function () use ($request, $id, $data, $submission) { DB::transaction(function () use ($request, $id, $data, $submission) {
@@ -74,6 +78,7 @@ class InvestorWorkspaceController extends Controller
'sector_interest' => Str::limit($dossier->content['sector'] ?? $dossier->title, 150, ''), 'message' => $data['message'], 'sector_interest' => Str::limit($dossier->content['sector'] ?? $dossier->title, 150, ''), 'message' => $data['message'],
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/carteira/'.$dossier->id, 'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/carteira/'.$dossier->id,
'metadata' => ['journey_id' => $journey->id, 'dossier_id' => $dossier->id, 'origin_dossier_id' => $journey->origin_dossier_id, 'metadata' => ['journey_id' => $journey->id, 'dossier_id' => $dossier->id, 'origin_dossier_id' => $journey->origin_dossier_id,
'declared_origin_country_code' => $data['declared_origin_country_code'] ?? null,
'project_id' => $dossier->project_id ?? $origin?->project_id, 'project_id' => $dossier->project_id ?? $origin?->project_id,
'cluster_id' => $dossier->cluster_id ?? $origin?->cluster_id, 'corridor_id' => $dossier->corridor_id ?? $origin?->corridor_id, 'cluster_id' => $dossier->cluster_id ?? $origin?->cluster_id, 'corridor_id' => $dossier->corridor_id ?? $origin?->corridor_id,
'role' => $data['role'], 'horizon' => $data['horizon'], 'purpose' => 'Acompanhamento da manifestação de interesse'], 'role' => $data['role'], 'horizon' => $data['horizon'], 'purpose' => 'Acompanhamento da manifestação de interesse'],
+111 -17
View File
@@ -8,10 +8,17 @@ use App\Http\Requests\StoreLandAssistanceCaseRequest;
use App\Jobs\ScanDocumentForMalware; use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest; use App\Models\InterestRequest;
use App\Models\LandAssistanceCase; use App\Models\LandAssistanceCase;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission; use App\Services\InterestSubmission;
use App\Services\InvestmentGeography;
use App\Services\InvestorContext;
use App\Services\InvestorContextConsumers;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
@@ -52,11 +59,22 @@ class LandAssistanceController extends Controller
public function create(Request $request): Response public function create(Request $request): Response
{ {
$context = $request->validate(['context' => ['nullable', 'uuid']])['context'] ?? null;
$dossier = null;
if ($context !== null) {
$case = app(VirtualDesk::class)->case($request->user(), $context);
abort_unless(config('investor-path.enabled') && (int) $case->user_id === $request->user()->id && ! $case->closed_at && $case->journey_id
&& DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(), 403);
$dossier = ['id' => $case->id, 'title' => $case->title, 'url' => '/investimentos/'.$case->id];
}
return Inertia::render('land-assistance/form', [ return Inertia::render('land-assistance/form', [
'case' => null, 'case' => null, 'boundContextRevision' => null,
'returnDossier' => $dossier,
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email], 'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER, 'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1', 'modelVersion' => 'land-assistance-v1',
'countries' => app(CountryCatalogue::class)->all(),
]); ]);
} }
@@ -66,10 +84,12 @@ class LandAssistanceController extends Controller
abort_unless(in_array($case->status, ['draft', 'waiting_applicant'], true), 409, 'Este pedido não está aberto para edição.'); abort_unless(in_array($case->status, ['draft', 'waiting_applicant'], true), 409, 'Este pedido não está aberto para edição.');
return Inertia::render('land-assistance/form', [ return Inertia::render('land-assistance/form', [
'case' => $case->only(['id', 'reference', 'version', 'status', 'payload']), 'case' => $case->only(['id', 'reference', 'version', 'status', 'payload']), 'boundContextRevision' => app(InvestorContextConsumers::class)->landRevision($case->id),
'returnDossier' => $this->dossierContext($case),
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email], 'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER, 'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1', 'modelVersion' => 'land-assistance-v1',
'countries' => app(CountryCatalogue::class)->all(),
]); ]);
} }
@@ -102,6 +122,7 @@ class LandAssistanceController extends Controller
{ {
$case = $this->owned($request, $id); $case = $this->owned($request, $id);
$data = [ $data = [
...$this->presentation($case),
'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']), 'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']),
'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id') 'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at') ->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')
@@ -145,9 +166,15 @@ class LandAssistanceController extends Controller
$data = $request->validated(); $data = $request->validated();
$submittedPayload = $request->payload(); $submittedPayload = $request->payload();
$case = DB::transaction(function () use ($request, $id, $data, $submission, $submittedPayload): LandAssistanceCase { $case = DB::transaction(function () use ($request, $id, $data, $submission, $submittedPayload): LandAssistanceCase {
if ($boundId = $submittedPayload['investor_path_case_id'] ?? null) {
app(InvestorContextConsumers::class)->assertReviewed($request->user(), $boundId, $request->all(), app(InvestorContextConsumers::class)->landRevision($id));
}
$case = $this->owned($request, $id, true); $case = $this->owned($request, $id, true);
abort_unless(in_array($case->status, ['draft', 'waiting_applicant'], true), 409, 'Este pedido já não pode ser submetido neste estado.'); $replaying = $case->status === 'support_requested';
$this->checkVersion($case, (int) $data['version']); abort_unless(in_array($case->status, ['draft', 'waiting_applicant', 'support_requested'], true), 409, 'Este pedido já não pode ser submetido neste estado.');
if (! $replaying) {
$this->checkVersion($case, (int) $data['version']);
}
$payload = [...$case->payload, ...$submittedPayload]; $payload = [...$case->payload, ...$submittedPayload];
$payload['full_name'] = $payload['full_name'] ?? $request->user()->name; $payload['full_name'] = $payload['full_name'] ?? $request->user()->name;
if (! array_key_exists('email', $payload)) { if (! array_key_exists('email', $payload)) {
@@ -155,6 +182,14 @@ class LandAssistanceController extends Controller
} }
$payload['email'] = is_string($payload['email']) && trim($payload['email']) !== '' ? strtolower(trim($payload['email'])) : null; $payload['email'] = is_string($payload['email']) && trim($payload['email']) !== '' ? strtolower(trim($payload['email'])) : null;
abort_if(empty($payload['email']) && empty($payload['phone']), 422, 'Indique pelo menos um contacto valido.'); abort_if(empty($payload['email']) && empty($payload['phone']), 422, 'Indique pelo menos um contacto valido.');
if ($replaying) {
// A retry of the same accepted attempt recovers its original receipt.
// Changed data, another version or a missing receipt must not reopen the case.
abort_unless((int) $case->version === (int) $data['version'] + 1 && $case->interest_request_id
&& hash_equals(hash('sha256', json_encode(Arr::sortRecursive($case->payload), JSON_THROW_ON_ERROR)),
hash('sha256', json_encode(Arr::sortRecursive($payload), JSON_THROW_ON_ERROR))),
409, 'O pedido mudou; recupere o estado atual antes de voltar a enviar.');
}
$message = trim(($payload['request_description'] ?? 'Pedido de apoio sobre Terra e DUAT.')."\nReferência interna: {$case->reference}. Tipo: ".($payload['support_kind'] ?? 'não indicado').'.'); $message = trim(($payload['request_description'] ?? 'Pedido de apoio sobre Terra e DUAT.')."\nReferência interna: {$case->reference}. Tipo: ".($payload['support_kind'] ?? 'não indicado').'.');
$interest = $submission->receive([ $interest = $submission->receive([
'kind' => 'support', 'fullName' => $payload['full_name'], 'email' => $payload['email'], 'kind' => 'support', 'fullName' => $payload['full_name'], 'email' => $payload['email'],
@@ -162,15 +197,29 @@ class LandAssistanceController extends Controller
'sectorInterest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000), 'sectorInterest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacyConsent' => true, 'portal_user_id' => $request->user()->id, 'privacyConsent' => true, 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference, 'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
'declared_origin_country_code' => $payload['declared_origin_country_code'] ?? null,
], $case->crm_submission_key, fn () => InterestRequest::create([ ], $case->crm_submission_key, fn () => InterestRequest::create([
'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $payload['full_name'], 'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $payload['full_name'],
'email' => $payload['email'], 'phone' => $payload['phone'] ?? null, 'email' => $payload['email'], 'phone' => $payload['phone'] ?? null,
'country' => $payload['country'] ?? 'Não indicado', 'investor_type' => 'individual', 'country' => $payload['country'] ?? 'Não indicado',
// Use the existing intake vocabulary; retain the more specific declared category.
// This factory only runs for a new receipt. Older submissions/replay hashes stay intact.
'investor_type' => match ($payload['applicant_category'] ?? null) {
'individual' => 'individual', 'entity' => 'empresa', default => 'outro',
},
'sector_interest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000), 'sector_interest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/terra-duat', 'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/terra-duat',
'metadata' => ['kind' => 'support', 'portal_user_id' => $request->user()->id, 'metadata' => ['kind' => 'support', 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference], 'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
'applicant_category' => $payload['applicant_category'] ?? null,
'declared_origin_country_code' => $payload['declared_origin_country_code'] ?? null],
])); ]));
if ($replaying) {
abort_unless((int) $interest->getKey() === (int) $case->interest_request_id && ! $interest->trashed(),
409, 'O recibo original não está disponível; recupere o estado do pedido.');
return $case;
}
$case->forceFill([ $case->forceFill([
'payload' => $payload, 'payload' => $payload,
'status' => 'support_requested', 'status' => 'support_requested',
@@ -250,7 +299,9 @@ class LandAssistanceController extends Controller
'media_type' => (string) $file->getMimeType(), 'media_type' => (string) $file->getMimeType(),
'storage_key' => $stored, 'storage_key' => $stored,
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)),
// No antivirus engine is configured in this project; fail closed until an operator scans it. 'size_bytes' => $file->getSize(),
'uploaded_by' => $request->user()->id,
// The configured scanner releases only the exact original hash after a clean result.
'status' => 'quarantined', 'status' => 'quarantined',
'created_at' => now(), 'created_at' => now(),
'updated_at' => now(), 'updated_at' => now(),
@@ -275,22 +326,26 @@ class LandAssistanceController extends Controller
: back()->with('status', 'Documento privado anexado; a revisão ainda está pendente.'); : back()->with('status', 'Documento privado anexado; a revisão ainda está pendente.');
} }
public function download(Request $request, string $id, string $attachment): BinaryFileResponse public function download(Request $request, string $id, string $attachment): \Illuminate\Http\Response|BinaryFileResponse
{ {
$this->owned($request, $id); // Management uses its existing explicit permission; the owner URL stays owner-only.
if ($request->routeIs('land-assistance.manage.download')) {
abort_unless($request->user()->can('manage-portal'), 403);
$case = LandAssistanceCase::whereKey($id)->firstOrFail();
} else {
$case = $this->owned($request, $id);
}
$document = DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id') $document = DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
->where('link.case_id', $id)->where('link.id', $attachment)->where('document.status', 'active')->whereNull('document.deleted_at') ->where('link.case_id', $id)->where('link.id', $attachment)->where('document.status', 'active')->whereNull('document.deleted_at')
->where('document.malware_scan_status', 'clean')->whereColumn('document.malware_scanned_sha256', 'document.sha256') ->where('document.malware_scan_status', 'clean')->whereColumn('document.malware_scanned_sha256', 'document.sha256')
->first(['document.file_name', 'document.storage_key', 'document.sha256', 'document.malware_scanned_sha256']); ->first(['document.*']);
abort_if($document === null, 404); abort_if($document === null, 404);
$root = realpath(Storage::disk('local')->path('')); $response = app(VerifiedDocumentBinary::class)->respond($document);
$path = realpath(Storage::disk('local')->path($document->storage_key)); DB::table('audit_events')->insert(['source_system' => 'land-assistance', 'entity_type' => 'documents', 'entity_id' => $document->id,
abort_unless($root && $path && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path), 404); 'actor_user_id' => $request->user()->id, 'action' => 'document_downloaded', 'data_classification' => 'restricted',
$checksum = hash_file('sha256', $path); 'after_data' => json_encode(['case_id' => $case->id, 'attachment_id' => $attachment], JSON_THROW_ON_ERROR)]);
abort_unless(is_string($checksum) && hash_equals($document->sha256, $checksum)
&& hash_equals($document->sha256, (string) $document->malware_scanned_sha256), 404);
return response()->download($path, basename($document->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']); return $response;
} }
public function print(Request $request, string $id): Response public function print(Request $request, string $id): Response
@@ -301,9 +356,39 @@ class LandAssistanceController extends Controller
'case' => $case->only(['reference', 'version', 'payload', 'updated_at']), 'case' => $case->only(['reference', 'version', 'payload', 'updated_at']),
'disclaimer' => self::DISCLAIMER, 'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1', 'modelVersion' => 'land-assistance-v1',
'country' => app(CountryCatalogue::class)->describe($case->payload['country'] ?? null),
'declaredOrigin' => app(CountryCatalogue::class)->describe($case->payload['declared_origin_country_code'] ?? null),
]); ]);
} }
/** @return array<string,mixed> */
private function presentation(LandAssistanceCase $case, bool $management = false): array
{
$payload = $case->payload;
$countries = app(CountryCatalogue::class);
$country = $countries->describe($payload['country'] ?? null);
$paths = [];
foreach ($payload['parcels'] ?? [] as $parcel) {
$id = $parcel['locality_id'] ?? $parcel['admin_post_id'] ?? $parcel['district_id'] ?? $parcel['province_id'] ?? null;
$paths[] = app(InvestmentGeography::class)->path($id ?: null, $management);
}
return ['countryName' => $country['code'] !== null ? $country['name'] : ($payload['country'] ?? 'Não informado'),
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths, 'returnDossier' => $this->dossierContext($case)];
}
private function dossierContext(LandAssistanceCase $case): ?array
{
$id = $case->payload['investor_path_case_id'] ?? null;
$actor = request()->user();
if (! $actor || (int) $case->user_id !== $actor->id || ! is_string($id) || ! Str::isUuid($id) || ! config('investor-path.enabled')) {
return null;
}
$dossier = DB::table('desk_cases')->where('id', $id)->where('user_id', $actor->id)->first();
return $dossier ? ['id' => $dossier->id, 'title' => $dossier->title, 'url' => '/investimentos/'.$dossier->id] : null;
}
public function manage(Request $request): Response public function manage(Request $request): Response
{ {
$cases = LandAssistanceCase::query()->latest('updated_at')->paginate(30)->through(fn (LandAssistanceCase $case): array => [ $cases = LandAssistanceCase::query()->latest('updated_at')->paginate(30)->through(fn (LandAssistanceCase $case): array => [
@@ -321,6 +406,7 @@ class LandAssistanceController extends Controller
$events = DB::table('land_assistance_events')->where('case_id', $id)->orderBy('created_at')->get(['action', 'version', 'metadata', 'created_at']); $events = DB::table('land_assistance_events')->where('case_id', $id)->orderBy('created_at')->get(['action', 'version', 'metadata', 'created_at']);
return Inertia::render('land-assistance/case', [ return Inertia::render('land-assistance/case', [
...$this->presentation($case, true),
'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']), 'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']),
'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id') 'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')->get(['link.id', 'link.category', 'document.file_name', 'document.status']), ->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')->get(['link.id', 'link.category', 'document.file_name', 'document.status']),
@@ -385,6 +471,14 @@ class LandAssistanceController extends Controller
/** @param array<string,mixed> $metadata */ /** @param array<string,mixed> $metadata */
private function event(LandAssistanceCase $case, Request $request, string $action, array $metadata = []): void private function event(LandAssistanceCase $case, Request $request, string $action, array $metadata = []): void
{ {
$contextId = $case->payload['investor_path_case_id'] ?? null;
if ($contextId) {
$binding = app(InvestorContextConsumers::class)->landRevision($case->id);
if ($action === 'draft_created' || $request->boolean('context_reviewed')) {
$binding = app(InvestorContextConsumers::class)->assertReviewed($request->user(), $contextId, $action === 'draft_created' ? ['context_reviewed' => true, 'context_revision' => app(InvestorContext::class)->state(app(VirtualDesk::class)->case($request->user(), $contextId))['revision']] : $request->all(), $binding);
}
$metadata['investment_context_revision'] = $binding;
}
DB::table('land_assistance_events')->insert([ DB::table('land_assistance_events')->insert([
'case_id' => $case->id, 'actor_id' => $request->user()->id, 'case_id' => $case->id, 'actor_id' => $request->user()->id,
'action' => $action, 'version' => $case->version, 'metadata' => json_encode($metadata, JSON_THROW_ON_ERROR), 'created_at' => now(), 'action' => $action, 'version' => $case->version, 'metadata' => json_encode($metadata, JSON_THROW_ON_ERROR), 'created_at' => now(),
@@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestorPath;
use App\Services\LegacyContent;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class LegacyContentController extends Controller
{
public function landing(Request $request, LegacyContent $legacy, string $sectorSlug = 'agronegocio'): Response
{
$filters = $request->validate(['q' => 'nullable|string|max:120']);
$articles = $legacy->articlesForGroup($sectorSlug);
$root = config('legacy_content.groups.'.$sectorSlug.'.root');
$article = $legacy->article($root);
$q = $filters['q'] ?? '';
$articles = array_values(array_filter($articles, fn ($item) => $q === ''
|| str_contains(mb_strtolower(strip_tags($item['html'].' '.$item['title'])), mb_strtolower($q))));
$match = $articles !== [];
return Inertia::render('portal/legacy', ['article' => $article, 'articles' => $articles, 'view' => 'landing', 'query' => $q, 'match' => $match]);
}
public function article(Request $request, LegacyContent $legacy, string $legacySlug = 'agronegocio'): Response
{
return Inertia::render('portal/legacy', ['article' => $legacy->article($legacySlug), 'view' => 'article', 'contentContext' => $this->context($request)]);
}
public function start(Request $request, LegacyContent $legacy, InvestorPath $path, string $legacySlug = 'agronegocio'): Response
{
abort_unless($path->available(), 404);
$article = $legacy->article($legacySlug);
return Inertia::render('investor-path/index', ['contexts' => $path->contexts($request->user()), 'contentSource' => $article]);
}
public function attach(Request $request, string $id, LegacyContent $legacy): JsonResponse|RedirectResponse
{
$legacy->attach($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['saved' => true]) : redirect('/investimentos/'.$id)->with('success', 'Referência guardada no dossier.');
}
/** @return array{id: string, title: string}|null */
private function context(Request $request): ?array
{
$data = $request->validate(['context' => 'nullable|uuid']);
if (! $request->user() || empty($data['context'])) {
return null;
}
try {
$case = app(VirtualDesk::class)->case($request->user(), $data['context'], true);
return $case->closed_at ? null : ['id' => $case->id, 'title' => $case->title];
} catch (HttpException $error) {
if (! in_array($error->getStatusCode(), [403, 404], true)) {
throw $error;
}
return null; // Consultation stays public; an unauthorized private context is never returned.
}
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\OpportunityClassification;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAccess;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class OpportunityClassificationController extends Controller
{
public function index(Request $request, int $id, OpportunityClassification $service): JsonResponse
{
$record = Opportunity::findOrFail($id);
app(PortalProfileAccess::class)->authorize($request->user(), 'view', $record);
return response()->json(['version' => $service::VERSION, 'etag' => app(OpportunityManagement::class)->etag($record), 'rows' => $service->listing($request->user(), $record), 'duplicates' => $service->duplicates($request->user(), $record)])->header('Cache-Control', 'private, no-store');
}
public function review(Request $request, int $id, OpportunityClassification $service): JsonResponse
{
$record = $service->review($request->user(), Opportunity::findOrFail($id), $request->all());
return response()->json(['etag' => app(OpportunityManagement::class)->etag($record), 'rows' => $service->listing($request->user(), $record)])->header('Cache-Control', 'private, no-store');
}
}
@@ -6,12 +6,21 @@ use App\Domain\Opportunities\Enums\OpportunityStatus;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Sector; use App\Models\Sector;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\OpportunityCanonicalContract;
use App\Services\OpportunityCanonicalResponse;
use App\Services\OpportunityManagement; use App\Services\OpportunityManagement;
use App\Services\OpportunityManagementInstallation; use App\Services\OpportunityManagementInstallation;
use App\Services\OpportunityMaturity;
use App\Services\OpportunityProfileWorkflow;
use App\Services\OpportunityResources;
use App\Services\OpportunityWorkflowTasks;
use App\Services\PortalProfileAccess;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -36,28 +45,70 @@ class OpportunityManagementController extends Controller
if (! $service->installed()) { if (! $service->installed()) {
return app(PortalManagementController::class)->catalog($request, 'opportunities'); return app(PortalManagementController::class)->catalog($request, 'opportunities');
} }
$filters = $request->validate(['q' => 'nullable|string|max:150', 'status' => ['nullable', Rule::in([...array_column(OpportunityStatus::cases(), 'value'), 'returned', 'auto_validation_failed', 'technical_review', 'legal_territorial_review', 'approval_pending', 'publication_pending'])], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])], 'category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)], 'deleted' => 'nullable|boolean', 'page' => 'nullable|integer|min:1']); $filters = $request->validate(['queue' => 'nullable|in:review,publication,appeal,assigned', 'q' => 'nullable|string|max:150', 'status' => ['nullable', Rule::in([...array_column(OpportunityStatus::cases(), 'value'), 'returned', 'auto_validation_failed', 'technical_review', 'legal_territorial_review', 'approval_pending', 'publication_pending'])], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])], 'category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)], 'deleted' => 'nullable|boolean', 'page' => 'nullable|integer|min:1']);
$query = Opportunity::query(); $query = Opportunity::query();
$access = app(PortalProfileAccess::class);
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
$query = $access->scope($query, $request->user());
if (str_starts_with($request->path(), 'minhas-oportunidades')) {
$query->whereNotNull('owner_user_id');
}
}
if ($filters['deleted'] ?? false) { if ($filters['deleted'] ?? false) {
$query->onlyTrashed(); $query->withoutGlobalScope(SoftDeletingScope::class)->whereNotNull('opportunities.deleted_at');
} }
if ($filters['q'] ?? null) { if ($filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%')); $query->where(function ($q) use ($filters) {
$q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%');
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
$q->orWhere(fn ($draft) => $draft->whereNotNull('owner_user_id')->whereRaw("management_draft::jsonb->'canonical'->>'official_title' ILIKE ?", ['%'.$filters['q'].'%']));
}
});
} }
if ($filters['status'] ?? null) { if ($filters['status'] ?? null) {
$query->where('status', $filters['status']); if (Schema::hasColumn('opportunities', 'workflow_context')) {
$query->whereRaw("COALESCE(workflow_context->>'working_state',status)=?", [$filters['status']]);
} else {
$query->where('status', $filters['status']);
}
} }
if ($filters['category'] ?? null) { if ($filters['category'] ?? null) {
$query->where('opportunity_category', $filters['category']); $query->where('opportunity_category', $filters['category']);
} }
if ($filters['sector_id'] ?? null) { if ($filters['sector_id'] ?? null) {
$query->where('sector_id', $filters['sector_id']); $sector = Sector::find($filters['sector_id']);
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
} }
if ($filters['geography_scope'] ?? null) { if ($filters['geography_scope'] ?? null) {
$query->where('geography_scope', $filters['geography_scope']); $query->where('geography_scope', $filters['geography_scope']);
} }
return Inertia::render('management/opportunities', ['records' => $query->orderByDesc('id')->paginate(20)->withQueryString(), 'filters' => $filters, 'counts' => Opportunity::selectRaw('status,count(*) AS total')->groupBy('status')->pluck('total', 'status'), 'categories' => OpportunityManagement::CATEGORIES, 'geographyReviewCount' => Opportunity::where('geography_scope', 'unspecified')->count(), 'sectors' => Sector::orderBy('name')->get(['id', 'name'])]); if ($filters['queue'] ?? null) {
$queue = $filters['queue'];
if ($queue === 'review') {
$query->whereRaw("COALESCE(workflow_context->>'working_state',status) IN ('submitted','in_review','information_pending')");
} elseif ($queue === 'publication') {
$query->whereRaw("COALESCE(workflow_context->>'working_state',status)='approved'");
} elseif ($queue === 'appeal') {
$query->whereRaw("workflow_context->'appeal'->>'pending'='true'");
} else {
$query->whereExists(fn ($q) => $q->selectRaw('1')->from('tasks')->where('tasks.source_system', 'opportunity-workflow')->where('tasks.assignee_user_id', $request->user()->id)->whereIn('tasks.status', ['open', 'in_progress'])->whereRaw("tasks.external_id LIKE 'portal-opportunity:' || opportunities.id::text || ':%'"));
}
}
$base = str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities';
$stateSql = Schema::hasColumn('opportunities', 'workflow_context') ? "COALESCE(workflow_context->>'working_state',status)" : 'status';
$counts = (clone $query)->selectRaw($stateSql.' AS working_status,count(*) AS total')->groupByRaw($stateSql)->pluck('total', 'working_status');
$geographyReviewCount = (clone $query)->where('geography_scope', 'unspecified')->count();
$records = $query->orderByDesc('id')->paginate(20)->withQueryString();
$records->getCollection()->each(function (Opportunity $r) use ($access, $service, $request) {
$r->setAttribute('can_edit', $access->canEdit($request->user(), $r));
$r->setAttribute('working_status', $access->state($r));
$r->setAttribute('publication', $r->publicationPresentation());
$r->setAttribute('draft_title', $service->values($r)['canonical']['official_title'] ?? $r->title);
});
return Inertia::render('management/opportunities', ['basePath' => $base, 'canCreate' => $base === '/management/opportunities' ? $access->legacyWriteAllowed($request->user()) : (bool) ($access->navigation($request->user())['contexts'] ?? []), 'records' => $records, 'filters' => $filters, 'counts' => $counts, 'categories' => OpportunityManagement::CATEGORIES, 'geographyReviewCount' => $geographyReviewCount, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug'])]);
} }
public function edit(Request $request, OpportunityManagement $service, ?int $id = null): Response public function edit(Request $request, OpportunityManagement $service, ?int $id = null): Response
@@ -66,10 +117,36 @@ class OpportunityManagementController extends Controller
return app(PortalManagementController::class)->edit('opportunities', $id); return app(PortalManagementController::class)->edit('opportunities', $id);
} }
$record = $id ? Opportunity::withTrashed()->findOrFail($id) : null; $record = $id ? Opportunity::withTrashed()->findOrFail($id) : null;
$values = $record ? ($record->management_draft ? json_decode($record->management_draft, true) : $record->only(OpportunityManagement::FIELDS)) : []; $access = app(PortalProfileAccess::class);
if (! $record && ! str_starts_with($request->path(), 'minhas-oportunidades')) {
abort_unless($access->legacyWriteAllowed($request->user()), 403);
}
if ($record) {
$access->authorize($request->user(), 'view', $record);
}
Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities',
'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null,
'workflowState' => $record ? $access->state($record) : null,
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
? app(OpportunityProfileWorkflow::class)->reauthenticationRequired($request->user(), $record) : false,
'publicationState' => $record?->publicationPresentation(),
'canonicalResponse' => $record?->owner_user_id !== null ? app(OpportunityCanonicalResponse::class)->read($request->user(), $record) : null,
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
'workflowTasks' => $record && $record->owner_user_id !== null ? app(OpportunityWorkflowTasks::class)->listing($record) : [],
'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'),
'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]);
$values = $record ? $service->values($record) : [];
if (! $record && $request->filled('sector_id')) {
$selection = $request->validate(['sector_id' => ['required', 'integer', Rule::exists('sectors', 'id')->where('is_active', true)->whereNull('deleted_at')]]);
$values['sector_id'] = (int) $selection['sector_id'];
$values['canonical']['sector_id'] = (int) $selection['sector_id'];
}
Inertia::share('publicationPreview', app(OpportunityCanonicalContract::class)->publicProjection($values['canonical'] ?? []));
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null; $classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
return Inertia::render('management/opportunity-draft', ['record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view'), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'categories' => OpportunityManagement::CATEGORIES, return Inertia::render('management/opportunity-draft', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view') || ($record && ! $access->canEdit($request->user(), $record)), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'categories' => OpportunityManagement::CATEGORIES,
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES, 'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS],
'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true), 'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true),
'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]); 'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]);
} }
@@ -84,6 +161,12 @@ class OpportunityManagementController extends Controller
return response()->json(['id' => $record->id, 'etag' => $service->etag($record), 'message' => 'Rascunho guardado no servidor. Não foi submetido, aprovado ou publicado.'], $id ? 200 : 201)->header('ETag', '"'.$service->etag($record).'"'); return response()->json(['id' => $record->id, 'etag' => $service->etag($record), 'message' => 'Rascunho guardado no servidor. Não foi submetido, aprovado ou publicado.'], $id ? 200 : 201)->header('ETag', '"'.$service->etag($record).'"');
} }
public function canonicalResponse(Request $request, int $id, OpportunityCanonicalResponse $response): JsonResponse
{
return response()->json($response->read($request->user(), Opportunity::withTrashed()->findOrFail($id)))
->header('Cache-Control', 'private, no-store');
}
public function lifecycle(Request $request, int $id, OpportunityManagement $service): JsonResponse public function lifecycle(Request $request, int $id, OpportunityManagement $service): JsonResponse
{ {
abort_unless($service->installed(), 503); abort_unless($service->installed(), 503);
@@ -3,27 +3,36 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Services\CountryCatalogue;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\OpportunityImageProcessor;
use App\Services\OpportunityManagement; use App\Services\OpportunityManagement;
use App\Services\OpportunityResourceInstallation; use App\Services\OpportunityResourceInstallation;
use App\Services\OpportunityResources; use App\Services\OpportunityResources;
use App\Services\OrganizationCountryInstallation;
use App\Services\PortalProfileAccess;
use App\Services\VerifiedDocumentBinary;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Inertia\Inertia; use Inertia\Inertia;
use Symfony\Component\HttpFoundation\HeaderUtils; use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class OpportunityResourceController extends Controller class OpportunityResourceController extends Controller
{ {
public function installation(Request $request, OpportunityResourceInstallation $service) public function installation(Request $request, OpportunityResourceInstallation $service): JsonResponse|Response
{ {
$preview = [...$service->preview(), 'actionUrl' => '/management/opportunity-resources-install']; $preview = [...$service->preview(), 'imageProcessingAvailable' => app(OpportunityImageProcessor::class)->available(), 'actionUrl' => '/management/opportunity-resources-install'];
$preview['changes'] = [...$preview['changes'], 'Código reconciliado: catálogo ISO comum; residência e constituição distintas; origem declarada guardada no payload existente e estatísticas internas autorizadas. Não converte países históricos nem usa IP.', 'Seletores territoriais reutilizados com pesquisa; filtros contextuais do catálogo e fichas territoriais consultáveis no percurso do mapa. Zero geometrias não permite desenhar estruturas sem dados.', 'Não reinstala a gestão básica nem acrescenta associações territoriais. Revisão transversal, cadastro completo em todos os campos e percursos educativos continuam parciais; consultar a matriz por módulo.'];
return $request->expectsJson() ? response()->json($preview) : Inertia::render('management/opportunity-install', $preview); return $request->expectsJson() ? response()->json($preview) : Inertia::render('management/opportunity-install', $preview);
} }
public function applyInstallation(Request $request, OpportunityResourceInstallation $service) public function applyInstallation(Request $request, OpportunityResourceInstallation $service): RedirectResponse
{ {
$data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'required|accepted']); $data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'required|accepted']);
$service->apply($request->user(), $data['hash']); $service->apply($request->user(), $data['hash']);
@@ -31,11 +40,48 @@ class OpportunityResourceController extends Controller
return back()->with('success', 'Recursos instalados; nenhum ficheiro publicado ou oportunidade submetida.'); return back()->with('success', 'Recursos instalados; nenhum ficheiro publicado ou oportunidade submetida.');
} }
public function index(int $id, OpportunityResources $service) public function organizationCountryPreview(Request $request, OrganizationCountryInstallation $service): JsonResponse|Response
{
$plan = $service->preview($request->user());
$scope = $this->countryOperationScope($request, $plan);
$operation = $request->session()->get('portal.country_installation_operation');
if (! is_array($operation) || ($operation['scope'] ?? null) !== $scope) {
$operation = ['scope' => $scope, 'key' => (string) Str::uuid()];
$request->session()->put('portal.country_installation_operation', $operation);
}
$plan = [...$plan, 'operationKey' => $operation['key'], 'actionUrl' => '/management/opportunity-resources-install/organization-country', 'extension' => true];
return $request->expectsJson() ? response()->json($plan) : Inertia::render('management/opportunity-install', $plan);
}
public function organizationCountryApply(Request $request, OrganizationCountryInstallation $service): JsonResponse|RedirectResponse
{
// Preview authorizes the actor; the UUID remains stable until this scope changes or logout.
$plan = $service->preview($request->user());
$operation = $request->session()->get('portal.country_installation_operation');
$data = $request->validate(['idempotency_key' => 'required|uuid']);
abort_unless(is_array($operation) && ($operation['scope'] ?? null) === $this->countryOperationScope($request, $plan)
&& hash_equals($operation['key'], $data['idempotency_key']), 409, 'A operação não corresponde a esta prévia. Atualize a página antes de tentar novamente.');
$result = $service->apply($request->user(), $request->all());
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'País mestre instalado; nenhuma submissão anterior alterada.');
}
/** @param array<string, mixed> $plan */
private function countryOperationScope(Request $request, array $plan): string
{
return hash('sha256', json_encode([$request->user()->getAuthIdentifier(), $plan['target'], $plan['migration'], $plan['code_hash']], JSON_THROW_ON_ERROR));
}
public function index(int $id, OpportunityResources $service): Response
{ {
$opportunity = Opportunity::withTrashed()->findOrFail($id); $opportunity = Opportunity::withTrashed()->findOrFail($id);
app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
Inertia::share(['basePath' => str_starts_with(request()->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities', 'readOnly' => ! app(PortalProfileAccess::class)->canEdit(request()->user(), $opportunity)]);
abort_unless($service->installed(), 503, 'Recursos ainda não instalados; consulte o plano autenticado.'); abort_unless($service->installed(), 503, 'Recursos ainda não instalados; consulte o plano autenticado.');
$resources = []; $resources = [];
Inertia::share('imageProcessingAvailable', app(OpportunityImageProcessor::class)->available());
Inertia::share('countries', app(CountryCatalogue::class)->all());
foreach (OpportunityResources::KINDS as $kind) { foreach (OpportunityResources::KINDS as $kind) {
$resources[$kind] = $service->listing($id, $kind); $resources[$kind] = $service->listing($id, $kind);
} }
@@ -43,11 +89,25 @@ class OpportunityResourceController extends Controller
$p = $location->payload; $p = $location->payload;
$location->territoryPath = app(InvestmentGeography::class)->path($p['locality_id'] ?? $p['admin_post_id'] ?? $p['district_id'] ?? $p['province_id'] ?? null, true); $location->territoryPath = app(InvestmentGeography::class)->path($p['locality_id'] ?? $p['admin_post_id'] ?? $p['district_id'] ?? $p['province_id'] ?? null, true);
} }
foreach ($resources['images'] as $image) {
$image->derivativePreviews = [];
foreach ($image->payload['derivatives'] ?? [] as $derived) {
if (DB::table('documents')->where('id', $derived['document_id'])->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->exists()) {
$image->derivativePreviews[] = [...$derived, 'url' => URL::temporarySignedRoute(str_starts_with(request()->path(), 'minhas-oportunidades') ? 'promoter.opportunity-image-preview' : 'management.opportunity-image-preview', now()->addMinutes(10), ['id' => $id, 'resourceId' => $image->id, 'documentId' => $derived['document_id']])];
}
}
}
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'assessment' => $this->assessment($resources)]); return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'librarySources' => !app(\App\Services\PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(\App\Services\OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(\App\Services\OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)]);
} }
public function save(Request $request, int $id, string $kind, OpportunityResources $service, ?string $resourceId = null) public function reuseLibrary(Request $request, int $id): JsonResponse
{
$row = app(\App\Services\OpportunityLibrarySupport::class)->attach($request->user(), Opportunity::findOrFail($id), $request->all());
return response()->json(['id' => $row->id, 'message' => 'Original associado como suporte privado, sem copiar ficheiros ou publicar.']);
}
public function save(Request $request, int $id, string $kind, OpportunityResources $service, ?string $resourceId = null): JsonResponse
{ {
$input = $request->all(); $input = $request->all();
if (is_string($input['payload'] ?? null)) { if (is_string($input['payload'] ?? null)) {
@@ -58,30 +118,51 @@ class OpportunityResourceController extends Controller
return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201); return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201);
} }
public function lifecycle(Request $request, int $id, string $kind, string $resourceId, OpportunityResources $service) public function lifecycle(Request $request, int $id, string $kind, string $resourceId, OpportunityResources $service): JsonResponse
{ {
$service->lifecycle($request->user(), $id, $kind, $resourceId, $request->all()); $service->lifecycle($request->user(), $id, $kind, $resourceId, $request->all());
return response()->json(['message' => 'Exclusão lógica/restauração registada; original e versões preservados.']); return response()->json(['message' => 'Exclusão lógica/restauração registada; original e versões preservados.']);
} }
public function download(int $id, string $kind, string $resourceId, OpportunityResources $service) public function prepareImage(Request $request, int $id, string $resourceId, OpportunityImageProcessor $service): JsonResponse
{
$service->prepare($request->user(), $id, $resourceId, $request->all());
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']);
}
public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response|BinaryFileResponse
{
$o = Opportunity::findOrFail($id);
abort_if($o->status === 'archived', 404);
$image = DB::table('opportunity_images')->where('opportunity_id', $id)->where('id', $resourceId)->whereNull('deleted_at')->first();
abort_unless($image !== null, 404);
$metadata = json_decode($image->payload, true);
abort_unless(in_array($documentId, array_column($metadata['derivatives'] ?? [], 'document_id'), true), 404);
$doc = DB::table('documents')->where('id', $documentId)->whereNull('deleted_at')->first();
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && hash_equals(trim($doc->sha256), (string) $doc->malware_scanned_sha256), 423, 'Scan da derivada pendente.');
return app(VerifiedDocumentBinary::class)->respond($doc, true);
}
public function download(int $id, string $kind, string $resourceId, OpportunityResources $service): \Illuminate\Http\Response|BinaryFileResponse
{ {
abort_unless(in_array($kind, ['documents', 'images'], true), 404); abort_unless(in_array($kind, ['documents', 'images'], true), 404);
$opportunity = Opportunity::findOrFail($id); $opportunity = Opportunity::findOrFail($id);
app(\App\Services\PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
abort_if($opportunity->status === 'archived', 404); abort_if($opportunity->status === 'archived', 404);
$record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']); $record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']);
abort_unless($record && $record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.'); abort_unless($record !== null, 404, 'Recurso indisponível ou excluído logicamente.');
$disk = Storage::disk('local'); abort_unless($record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
$path = $disk->path($record->storage_key);
abort_unless($disk->exists($record->storage_key), 409, 'Ficheiro indisponível.');
$bytes = $record->storage_encryption === 'laravel' ? Crypt::decryptString($disk->get($record->storage_key)) : $disk->get($record->storage_key);
abort_unless(hash_equals(trim($record->sha256), hash('sha256', $bytes)), 409, 'Integridade do ficheiro divergente.');
return response($bytes)->header('Content-Type', $record->media_type)->header('Content-Disposition', HeaderUtils::makeDisposition('attachment', $record->file_name, 'document'))->header('X-Content-Type-Options', 'nosniff')->header('Cache-Control', 'no-store'); $support = DB::table($service->table($kind))->where('id', $resourceId)->first();
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($support, $record);
if (request()->filled('source_sha256')) abort_unless(hash_equals(trim($record->sha256), (string)request('source_sha256')), 409, 'O original já não corresponde à versão consultada.');
return app(VerifiedDocumentBinary::class)->respond($record);
} }
/** @param array<string,list<object>> $resources /** @param array<string,list<\stdClass>> $resources
* @return list<string> * @return list<string>
*/ */
private function assessment(array $resources): array private function assessment(array $resources): array
@@ -102,13 +183,20 @@ class OpportunityResourceController extends Controller
$districts = []; $districts = [];
foreach ($locations as $location) { foreach ($locations as $location) {
$p = $location->payload; $p = $location->payload;
if (empty($p['province_id']) || empty($p['district_id']) || empty($p['role'])) { $mozambican = empty($p['country_code']) || $p['country_code'] === 'MZ';
$issues[] = 'Uma localização tem província, distrito ou papel pendente.'; if ($mozambican && (empty($p['province_id']) || empty($p['district_id']))) {
$issues[] = 'Uma localização em Moçambique tem província ou distrito pendente.';
} }
if (! empty($p['district_id'])) { if (! $mozambican && array_filter(array_intersect_key($p, array_flip(['province_id', 'district_id', 'admin_post_id', 'locality_id'])))) {
$issues[] = 'Uma localização noutro país conserva uma seleção territorial de Moçambique incompatível; corrigir explicitamente sem converter o histórico.';
}
if (empty($p['role'])) {
$issues[] = 'Uma localização tem papel pendente.';
}
if ($mozambican && ! empty($p['district_id'])) {
$districts[$p['district_id']] = true; $districts[$p['district_id']] = true;
} }
if (! empty($p['province_id'])) { if ($mozambican && ! empty($p['province_id'])) {
$provinces[$p['province_id']] = true; $provinces[$p['province_id']] = true;
} }
if (($p['role'] ?? null) === 'other' && empty($p['role_description'])) { if (($p['role'] ?? null) === 'other' && empty($p['role_description'])) {
@@ -127,6 +215,9 @@ class OpportunityResourceController extends Controller
if (count($districts) > 1 && ! array_filter($locations, fn ($r) => mb_strlen($r->payload['multi_district_rationale'] ?? '') >= 50)) { if (count($districts) > 1 && ! array_filter($locations, fn ($r) => mb_strlen($r->payload['multi_district_rationale'] ?? '') >= 50)) {
$issues[] = 'Multidistrito/interprovincial exige fundamento operacional de 50–1000 caracteres.'; $issues[] = 'Multidistrito/interprovincial exige fundamento operacional de 50–1000 caracteres.';
} }
if ($locations) {
$issues[] = 'Modo preparado: '.(count($locations) > 1 ? 'multiple' : 'single').'; âmbito administrativo moçambicano derivado: '.(count($provinces) > 1 ? 'interprovincial' : (count($districts) > 1 ? 'multi_district' : ($districts ? 'district' : 'sem seleção moçambicana'))).'. Sem conversão de contexto em implantação.';
}
foreach (['images', 'documents'] as $kind) { foreach (['images', 'documents'] as $kind) {
foreach ($resources[$kind] as $r) { foreach ($resources[$kind] as $r) {
if ($r->deleted_at) { if ($r->deleted_at) {
@@ -142,7 +233,21 @@ class OpportunityResourceController extends Controller
} }
} }
if ($kind === 'images') { if ($kind === 'images') {
$issues[] = 'Imagem '.$r->file->file_name.': revisão, derivadas sem EXIF e aprovação de divulgação ainda pendentes.'; if (empty($r->payload['derivatives'])) {
$issues[] = 'Imagem '.$r->file->file_name.': derivadas sem EXIF ainda por preparar (GD/WebP e scan necessários).';
}
$issues[] = 'Imagem '.$r->file->file_name.': revisão de dados pessoais/direitos e aprovação de divulgação ainda pendentes.';
foreach (['title' => 5, 'caption' => 10, 'alt_text' => 10, 'author_source' => 2] as $field => $minimum) {
if (mb_strlen($r->payload[$field] ?? '') < $minimum) {
$issues[] = 'Imagem '.$r->file->file_name.': '.$field.' abaixo do mínimo para validação final.';
}
}
if (($r->payload['role'] ?? null) === 'location' && empty($r->payload['location_id'])) {
$issues[] = 'Imagem de localização exige ligação a um local ativo da mesma oportunidade.';
}
if (in_array($r->payload['role'] ?? null, ['asset', 'product', 'evidence'], true)) {
$issues[] = 'Imagem de ativo/produto/evidência: módulo e associação específica ainda pendentes.';
}
if (in_array($r->payload['rights_status'] ?? null, ['licensed', 'authorized'], true) && empty($r->payload['rights_document_id'])) { if (in_array($r->payload['rights_status'] ?? null, ['licensed', 'authorized'], true) && empty($r->payload['rights_document_id'])) {
$issues[] = 'Imagem licenciada/autorizada exige comprovativo.'; $issues[] = 'Imagem licenciada/autorizada exige comprovativo.';
} }
@@ -11,6 +11,7 @@ use App\Services\InvestmentRelations;
use App\Services\PartnershipExchange; use App\Services\PartnershipExchange;
use App\Services\PartnershipMatching; use App\Services\PartnershipMatching;
use App\Services\PartnershipSources; use App\Services\PartnershipSources;
use App\Services\VerifiedDocumentBinary;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -33,7 +34,7 @@ class PartnershipExchangeController extends Controller
app(PartnershipSources::class)->resolve($type, $id, $request->user()); app(PartnershipSources::class)->resolve($type, $id, $request->user());
return response()->json(['available' => true, 'items' => DB::table('portal_partnerships as p')->join('partnership_origins as origin', 'origin.partnership_id', '=', 'p.id') return response()->json(['available' => true, 'items' => DB::table('portal_partnerships as p')->join('partnership_origins as origin', 'origin.partnership_id', '=', 'p.id')
->where('origin.type', $type)->where('origin.target_id', $id)->where('p.status', 'published')->orderByDesc('p.id')->get(['p.id', 'p.title'])])->header('Cache-Control', 'private, no-store'); ->where('origin.type', $type)->where('origin.target_id', $id)->where('p.status', 'published')->orderByDesc('p.id')->distinct()->get(['p.id', 'p.title'])])->header('Cache-Control', 'private, no-store');
} }
public function index(Request $request): Response|JsonResponse public function index(Request $request): Response|JsonResponse
@@ -43,7 +44,10 @@ class PartnershipExchangeController extends Controller
$query = DB::table('portal_partnerships as p')->where('p.status', 'published'); $query = DB::table('portal_partnerships as p')->where('p.status', 'published');
foreach (['sector_id', 'partnership_type', 'kind'] as $field) { foreach (['sector_id', 'partnership_type', 'kind'] as $field) {
if (! empty($filters[$field])) { if (! empty($filters[$field])) {
$query->where('p.'.$field, $filters[$field]); if ($field === 'sector_id') {
$sector = \App\Models\Sector::find($filters[$field]);
$query->whereIn('p.sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
} else { $query->where('p.'.$field, $filters[$field]); }
} }
} }
if (! empty($filters['q'])) { if (! empty($filters['q'])) {
@@ -317,7 +321,7 @@ class PartnershipExchangeController extends Controller
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409); abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409);
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'partnership-exchange', 'data_classification' => 'restricted', DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'partnership-exchange', 'data_classification' => 'restricted',
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored, 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored,
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined']); 'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined', 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id]);
DB::table('partnership_documents')->insert(['room_id' => $id, 'document_id' => $documentId, 'owner_id' => $request->user()->id, 'shared' => $data['shared']]); DB::table('partnership_documents')->insert(['room_id' => $id, 'document_id' => $documentId, 'owner_id' => $request->user()->id, 'shared' => $data['shared']]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_added.v1', ['room_id' => $id, 'document_id' => $documentId, 'shared' => $data['shared']], 'Documento privado anexado'); app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_added.v1', ['room_id' => $id, 'document_id' => $documentId, 'shared' => $data['shared']], 'Documento privado anexado');
}); });
@@ -330,21 +334,17 @@ class PartnershipExchangeController extends Controller
return $request->expectsJson() ? response()->json(['uploaded' => true]) : back()->with('success', 'Documento privado guardado; análise antimalware pendente.'); return $request->expectsJson() ? response()->json(['uploaded' => true]) : back()->with('success', 'Documento privado guardado; análise antimalware pendente.');
} }
public function download(Request $request, int $id, int $attachment): BinaryFileResponse public function download(Request $request, int $id, int $attachment): \Illuminate\Http\Response|BinaryFileResponse
{ {
$context = app(PartnershipExchange::class)->room($request->user(), $id); $context = app(PartnershipExchange::class)->room($request->user(), $id);
$document = DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.room_id', $id)->where('link.id', $attachment) $document = DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.room_id', $id)->where('link.id', $attachment)
->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))->where('d.status', 'active')->whereNull('d.deleted_at') ->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))->where('d.status', 'active')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')->first(['d.storage_key', 'd.file_name', 'd.sha256']); ->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')->first(['d.*']);
abort_unless($document !== null, 404); abort_unless($document !== null, 404);
$root = realpath(Storage::disk('local')->path('')); $response = app(VerifiedDocumentBinary::class)->respond($document);
$path = realpath(Storage::disk('local')->path($document->storage_key));
abort_unless($root && $path && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless(is_string($checksum) && hash_equals($document->sha256, $checksum), 404);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_accessed.v1', ['room_id' => $id, 'attachment_id' => $attachment], 'Documento consultado'); app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_accessed.v1', ['room_id' => $id, 'attachment_id' => $attachment], 'Documento consultado');
return response()->download($path, basename($document->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']); return $response;
} }
public function share(Request $request, int $id, int $attachment): RedirectResponse|JsonResponse public function share(Request $request, int $id, int $attachment): RedirectResponse|JsonResponse
@@ -393,7 +393,7 @@ class PartnershipExchangeController extends Controller
} }
} }
return ['types' => config('partnerships.types'), 'criteria' => config('partnerships.criteria'), 'sources' => $sources, 'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name']), return ['types' => config('partnerships.types'), 'criteria' => config('partnerships.criteria'), 'sources' => $sources, 'sectors' => \App\Models\Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type', 'parent_id']), 'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type', 'parent_id']),
'organizations' => $request->user() ? DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id) 'organizations' => $request->user() ? DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id)
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']) : []]; ->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']) : []];
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers;
use App\Mail\ContactMessageReceivedMail;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
class PortalContactController extends Controller
{
// Adapter for investidor's contact form: preserve its fields and validation,
// using the configured mail transport without adding a database dependency.
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'name' => ['required', 'string', 'min:2', 'max:150'],
'email' => ['required', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:30'],
'subject' => ['required', 'string', 'min:3', 'max:100'],
'message' => ['required', 'string', 'min:10', 'max:2000'],
]);
try {
Mail::to(config('contact_messages.recipient'))
->send(new ContactMessageReceivedMail([
'name' => $data['name'], 'email' => $data['email'], 'phone' => $data['phone'] ?? null,
'subject' => $data['subject'], 'message' => $data['message'], 'platform' => 'InvesteMoz',
]));
} catch (Throwable $exception) {
Log::warning('Falha no envio de contacto do portal.', ['exception' => $exception::class]);
return response()->json(['success' => false, 'message' => 'Ocorreu um erro ao enviar a mensagem.'], 500);
}
return response()->json(['success' => true, 'message' => 'Mensagem enviada com sucesso.'], 201);
}
}
@@ -7,11 +7,14 @@ use App\Models\InvestmentSubmission;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Sector; use App\Models\Sector;
use App\Models\User; use App\Models\User;
use App\Services\CountryCatalogue;
use App\Services\DeclaredOriginStatistics;
use App\Services\InterestWorkflow; use App\Services\InterestWorkflow;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\InvestmentWorkspace; use App\Services\InvestmentWorkspace;
use App\Services\OpportunityManagement; use App\Services\OpportunityManagement;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use App\Services\PortalProfileAccess;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -50,16 +53,60 @@ class PortalManagementController extends Controller
return Inertia::render('management/history', ['events' => $events]); return Inertia::render('management/history', ['events' => $events]);
} }
private function interestAssignmentEtag(InterestRequest $interest): string
{
return hash('sha256',json_encode([$interest->id,$interest->status,$interest->assigned_to,$interest->updated_at?->format('Y-m-d H:i:s.u')],JSON_THROW_ON_ERROR));
}
public function interestAssignments(Request $request): Response|JsonResponse
{
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
$rows=InterestRequest::whereNotIn('status',['cancelled','closed','refused','converted'])->orderBy('id')->get(['id','reference','status','assigned_to','updated_at'])
->map(fn($row)=>['id'=>$row->id,'protocol'=>$row->reference,'status'=>$row->status,'analyst_id'=>$row->assigned_to,'version'=>0,'etag'=>$this->interestAssignmentEtag($row),'due_at'=>null]);
$data=['kind'=>'interest','requests'=>$rows,'analysts'=>$this->interestAssignees()->get(['id','name'])];
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
}
public function assignInterest(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
{
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
$data=$request->validate(['etag'=>'required|string|size:64','analyst_id'=>['required','integer',Rule::in($this->interestAssignees()->pluck('id'))],'reason'=>'required|string|min:10|max:2000'],['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 10 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.in'=>'Seleccione um responsável autorizado.']);
DB::transaction(function()use($request,$interest,$data){
$row=InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
if (!hash_equals($this->interestAssignmentEtag($row),$data['etag'])) throw ValidationException::withMessages(['etag'=>'A atribuição mudou. Recupere a lista actual e tente novamente.']);
if (in_array($row->status,['cancelled','closed','refused','converted'],true)) throw ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
$owner=(int)($row->metadata['portal_user_id']??0);
abort_if($owner===(int)$data['analyst_id'] || InvestmentSubmission::where('interest_request_id',$row->id)->where('user_id',$data['analyst_id'])->exists(),422,'O interessado não pode acompanhar o seu próprio pedido como equipa.');
PortalAudit::save($row,['assigned_to'=>(int)$data['analyst_id']],$request->user()->id);
app(\App\Services\PortalProfileAccess::class)->audit($request->user(),'interest_assigned',['interest_id'=>$row->id,'assigned_to'=>(int)$data['analyst_id'],'reason'=>$data['reason']]);
});
return $request->expectsJson()?response()->json(['ok'=>true]):back()->with('success','Responsável atribuído.');
}
public function interests(Request $request): Response public function interests(Request $request): Response
{ {
$filters = $request->validate([ $filters = $request->validate([
'q' => ['nullable', 'string', 'max:150'], 'q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in(self::STATES)], 'status' => ['nullable', Rule::in(self::STATES)],
'follow_up' => ['nullable', Rule::in(['overdue', 'upcoming', 'unassigned'])], 'follow_up' => ['nullable', Rule::in(['overdue', 'upcoming', 'unassigned'])],
'country' => ['nullable', app(CountryCatalogue::class)->rule()],
'origin' => ['nullable', Rule::in([...array_column(app(CountryCatalogue::class)->all(), 'code'), 'unknown'])],
]); ]);
$query = InterestRequest::query()->with('assignee:id,name')->select([ $query = InterestRequest::query()->with('assignee:id,name')->select([
'id', 'reference', 'full_name', 'email', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at', 'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
]); ]);
app(\App\Services\ScopedPortalAdministration::class)->interestQuery($query, $request->user());
if ($country = $filters['country'] ?? null) {
$values = app(CountryCatalogue::class)->filterValues($country);
$query->whereIn(DB::raw('LOWER(BTRIM(country))'), $values);
}
if ($origin = $filters['origin'] ?? null) {
if ($origin === 'unknown') {
$query->where(fn ($q) => $q->whereNull('metadata->declared_origin_country_code')->orWhereNotIn('metadata->declared_origin_country_code', array_column(app(CountryCatalogue::class)->all(), 'code')));
} else {
$query->where('metadata->declared_origin_country_code', $origin);
}
}
if ($term = $filters['q'] ?? null) { if ($term = $filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('reference', "%{$term}%") $query->where(fn ($q) => $q->whereLike('reference', "%{$term}%")
->orWhereLike('full_name', "%{$term}%")->orWhereLike('email', "%{$term}%")); ->orWhereLike('full_name', "%{$term}%")->orWhereLike('email', "%{$term}%"));
@@ -78,13 +125,24 @@ class PortalManagementController extends Controller
} }
return Inertia::render('management/interests', [ return Inertia::render('management/interests', [
'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString(), 'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString()->through(function ($row) {
$result = $row->toArray();
$result['declaredOrigin'] = app(CountryCatalogue::class)->describe($row->metadata['declared_origin_country_code'] ?? null);
$country = app(CountryCatalogue::class)->describe($row->country);
$result['countryName'] = $country['code'] !== null ? $country['name'] : $row->country;
unset($result['metadata']);
return $result;
}),
'filters' => $filters, 'filters' => $filters,
'countries' => app(CountryCatalogue::class)->all(),
'originStatistics' => app(DeclaredOriginStatistics::class)->forManager($request->user(), $filters['origin'] ?? null),
]); ]);
} }
public function interest(InterestRequest $interest): Response public function interest(InterestRequest $interest): Response
{ {
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id) $history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at']) ->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
->map(function ($row) { ->map(function ($row) {
@@ -97,11 +155,12 @@ class PortalManagementController extends Controller
->orderBy('created_at')->get(['purpose', 'policy_version', 'status', 'granted_at', 'withdrawn_at']); ->orderBy('created_at')->get(['purpose', 'policy_version', 'status', 'granted_at', 'withdrawn_at']);
return Inertia::render('management/interest', [ return Inertia::render('management/interest', [
'declaredOrigin' => app(CountryCatalogue::class)->describe($interest->metadata['declared_origin_country_code'] ?? null),
'interest' => $interest->only([ 'interest' => $interest->only([
'id', 'reference', 'full_name', 'email', 'phone', 'investor_type', 'country', 'id', 'reference', 'full_name', 'email', 'phone', 'investor_type', 'country',
'sector_interest', 'opportunity_reference', 'investment_range', 'message', 'sector_interest', 'opportunity_reference', 'investment_range', 'message',
'privacy_consent', 'consented_at', 'status', 'created_at', 'reviewed_at', 'reviewed_by', 'metadata', 'privacy_consent', 'consented_at', 'status', 'created_at', 'reviewed_at', 'reviewed_by', 'metadata',
'existing_business_id', 'modality', 'assigned_to', 'next_action', 'next_action_due_at', 'existing_business_id', 'modality', 'assigned_to', 'next_action', 'next_action_due_at', 'source_page',
]), ]),
'history' => $history, 'history' => $history,
'consents' => $consents, 'consents' => $consents,
@@ -111,12 +170,18 @@ class PortalManagementController extends Controller
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
{ {
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
$validated = $request->validate([ $validated = $request->validate([
'status' => ['required', Rule::in(self::STATES)], 'status' => ['required', Rule::in(self::STATES)],
'note' => ['nullable', 'string', 'min:10', 'max:2000'], 'note' => ['nullable', 'string', 'min:10', 'max:2000'],
'next_action' => ['nullable', 'required_with:next_action_due_at', 'string', 'max:180'], 'next_action' => ['nullable', 'required_with:next_action_due_at', 'string', 'max:180'],
'next_action_due_at' => ['nullable', 'required_with:next_action', 'date', 'after_or_equal:today'], 'next_action_due_at' => ['nullable', 'required_with:next_action', 'date', 'after_or_equal:today'],
'assigned_to' => ['nullable', 'integer', Rule::in($this->interestAssignees()->pluck('id'))], 'assigned_to' => ['nullable', 'integer', Rule::in($this->interestAssignees()->pluck('id'))],
], [
'next_action_due_at.required_with' => 'Indique o prazo da próxima acção.',
'next_action_due_at.date' => 'Indique uma data válida para a próxima acção.',
'next_action_due_at.after_or_equal' => 'O prazo da próxima acção deve ser hoje ou uma data futura.',
'next_action.required_with' => 'Descreva a próxima acção correspondente ao prazo indicado.',
]); ]);
$before = $interest->status; $before = $interest->status;
$updated = $workflow->transition($request->user(), $interest, $validated['status'], $validated['note'] ?? null, $updated = $workflow->transition($request->user(), $interest, $validated['status'], $validated['note'] ?? null,
@@ -133,6 +198,7 @@ class PortalManagementController extends Controller
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
{ {
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]); $data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
$this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent'); $this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent');
@@ -142,6 +208,7 @@ class PortalManagementController extends Controller
public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
{ {
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]); $data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
$this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest'); $this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest');
@@ -190,7 +257,9 @@ class PortalManagementController extends Controller
['triagers', 'reviewers', 'approvers_l1', 'approvers_l2', 'publishers'], ['triagers', 'reviewers', 'approvers_l1', 'approvers_l2', 'publishers'],
))); )));
return User::query()->whereNotNull('email_verified_at')->whereIn(DB::raw('lower(email)'), $emails)->orderBy('name'); return User::query()->whereNotNull('email_verified_at')->where(function ($q) use ($emails) {
$q->whereIn(DB::raw('lower(email)'), $emails)->orWhereIn('id', DB::table('portal_superuser_pair')->select('first_user_id'))->orWhereIn('id', DB::table('portal_superuser_pair')->select('second_user_id'));
})->orderBy('name');
} }
public function catalog(Request $request, string $resource): Response public function catalog(Request $request, string $resource): Response
@@ -205,6 +274,9 @@ class PortalManagementController extends Controller
]); ]);
$query = $model::query(); $query = $model::query();
if ($resource === 'opportunities') { if ($resource === 'opportunities') {
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
$query = app(PortalProfileAccess::class)->scope(Opportunity::query(), $request->user());
}
$query->with('primaryTerritory:id,name,location_type,source_system,source_code'); $query->with('primaryTerritory:id,name,location_type,source_system,source_code');
if (isset($filters['geography_scope'])) { if (isset($filters['geography_scope'])) {
$query->where('geography_scope', $filters['geography_scope']); $query->where('geography_scope', $filters['geography_scope']);
@@ -229,16 +301,17 @@ class PortalManagementController extends Controller
} }
} }
if ($resource === 'opportunities' && ($filters['sector_id'] ?? null)) { if ($resource === 'opportunities' && ($filters['sector_id'] ?? null)) {
$query->where('sector_id', $filters['sector_id']); $sector = Sector::find($filters['sector_id']);
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
} }
return Inertia::render('management/catalog', [ return Inertia::render('management/catalog', [
'resource' => $resource, 'resource' => $resource,
'records' => $query->orderByDesc('id')->paginate(20)->withQueryString(), 'records' => $query->orderByDesc('id')->paginate(20)->withQueryString(),
'filters' => $filters, 'filters' => $filters,
'sectors' => $resource === 'opportunities' ? Sector::orderBy('name')->get(['id', 'name']) : [], 'sectors' => $resource === 'opportunities' ? Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']) : [],
'geographyReviewCount' => $resource === 'opportunities' 'geographyReviewCount' => $resource === 'opportunities'
? Opportunity::where('geography_scope', 'unspecified')->count() ? (clone $query)->where('geography_scope', 'unspecified')->count()
: 0, : 0,
]); ]);
} }
@@ -252,7 +325,7 @@ class PortalManagementController extends Controller
'resource' => $resource, 'resource' => $resource,
'record' => $record, 'record' => $record,
'territoryPath' => $record instanceof Opportunity ? app(InvestmentGeography::class)->path($record->primary_territory_id, true) : [], 'territoryPath' => $record instanceof Opportunity ? app(InvestmentGeography::class)->path($record->primary_territory_id, true) : [],
'sectors' => Sector::orderBy('name')->get(['id', 'name']), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
]); ]);
} }
@@ -270,6 +343,7 @@ class PortalManagementController extends Controller
'description' => ['nullable', 'string', 'max:20000'], 'description' => ['nullable', 'string', 'max:20000'],
'sort_order' => ['required', 'integer', 'min:0', 'max:2147483647'], 'sort_order' => ['required', 'integer', 'min:0', 'max:2147483647'],
'is_active' => ['required', 'boolean'], 'is_active' => ['required', 'boolean'],
'editorial_published' => ['required', 'boolean'],
] : [ ] : [
'sector_id' => ['required', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'sector_id' => ['required', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')],
'reference' => ['required', 'string', 'max:80', Rule::unique('opportunities')->ignore($record->id)], 'reference' => ['required', 'string', 'max:80', Rule::unique('opportunities')->ignore($record->id)],
@@ -297,6 +371,10 @@ class PortalManagementController extends Controller
$rules['territory_version'] = [$id && $request->hasAny(array_keys(InvestmentGeography::FIELDS)) ? 'required' : 'nullable', 'integer', 'min:0']; $rules['territory_version'] = [$id && $request->hasAny(array_keys(InvestmentGeography::FIELDS)) ? 'required' : 'nullable', 'integer', 'min:0'];
} }
$data = $request->validate($rules); $data = $request->validate($rules);
if ($resource === 'sectors') {
$data['published_at'] = $data['editorial_published'] ? ($record->published_at ?? now()) : null;
unset($data['editorial_published']);
}
if ($resource === 'opportunities' && $data['status'] === 'published' && $record->exists if ($resource === 'opportunities' && $data['status'] === 'published' && $record->exists
&& Schema::hasTable('education_investment_proposals') && Schema::hasTable('education_investment_proposals')
&& DB::table('education_investment_proposals')->where('opportunity_id', $record->id)->exists()) { && DB::table('education_investment_proposals')->where('opportunity_id', $record->id)->exists()) {
@@ -0,0 +1,185 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\OpportunityCanonicalContract;
use App\Services\OpportunityContacts;
use App\Services\OpportunityManagement;
use App\Services\OpportunityProfileWorkflow;
use App\Services\PortalInternalDesignation;
use App\Services\PortalProfileAccess;
use App\Services\PortalProfileAdministration;
use App\Services\PortalSuperusers;
use App\Services\VerifiedDocumentBinary;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class PortalProfileController extends Controller
{
public function requests(Request $request, PortalProfileAccess $access): Response
{
return Inertia::render('profiles/request', ['requests' => DB::table('portal_profile_requests')->where('user_id', $request->user()->id)->latest()->get(),
'types' => OpportunityManagement::CATEGORIES,
'organizations' => DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id)
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']),
'documents' => DB::table('documents')->where('uploaded_by', $request->user()->id)->whereNull('deleted_at')->where('status', 'active')->where('malware_scan_status', 'clean')
->whereColumn('sha256', 'malware_scanned_sha256')->get(['id', 'file_name']), 'grants' => $access->grants($request->user(), 'promoter')]);
}
public function requestProfile(Request $request, PortalProfileAdministration $service): JsonResponse
{
return response()->json(['id' => $service->request($request->user(), $request->all()), 'message' => 'Pedido recebido; perfil ainda não ativado.'], 201);
}
public function requestStatus(Request $request, string $id): JsonResponse
{
$row = DB::table('portal_profile_requests')->where('id', $id)->where('user_id', $request->user()->id)->first();
abort_unless($row !== null, 403);
return response()->json($row);
}
public function administration(Request $request, PortalProfileAdministration $service): Response
{
$service->administrative($request->user());
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(),
'assignments' => DB::table('portal_role_assignments')->get(), 'pair' => DB::table('portal_superuser_pair')->first(),
'operatorOrganizations' => app(PortalInternalDesignation::class)->organizations(),
'internalTypes' => OpportunityCanonicalContract::BASE_CATEGORIES,
'actorId' => $request->user()->id, 'types' => OpportunityManagement::CATEGORIES,
'organizations' => DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']),
'securityRequests' => DB::table('portal_security_approvals')->latest()->limit(30)->get(),
'securityAlerts' => DB::table('audit_events')->where('source_system', 'portal-profiles-v1')->whereIn('action', ['superuser_pair_initialized', 'superuser_replaced', 'role_revoked'])->latest('occurred_at')->limit(20)->get(['id', 'action', 'actor_user_id', 'occurred_at'])]);
}
public function decide(Request $request, string $id, PortalProfileAdministration $service): JsonResponse
{
$service->decide($request->user(), $id, $request->all());
return response()->json(['message' => 'Decisão registada; somente os tipos aprovados ficam autorizados.']);
}
public function audit(Request $request, PortalProfileAccess $access): Response|JsonResponse
{
abort_unless($access->has($request->user(), 'auditor') || ($access->superuser($request->user()) && $access->mfa($request->user())), 403);
$filters = $request->validate(['actor_id' => 'nullable|integer|min:1', 'action' => 'nullable|string|max:100', 'record_id' => 'nullable|integer|min:1', 'from' => 'nullable|date', 'until' => 'nullable|date|after_or_equal:from', 'format' => 'nullable|in:json']);
$query = DB::table('audit_events')->when($filters['actor_id'] ?? null, fn ($q, $v) => $q->where('actor_user_id', $v))
->when($filters['action'] ?? null, fn ($q, $v) => $q->where('action', $v))
->when($filters['record_id'] ?? null, fn ($q, $v) => $q->where('after_data->record_id', $v))
->when($filters['from'] ?? null, fn ($q, $v) => $q->where('occurred_at', '>=', $v))
->when($filters['until'] ?? null, fn ($q, $v) => $q->where('occurred_at', '<=', $v));
// Minimized metadata: never decrypt private snapshots or export authentication bodies.
$query->select(['id', 'source_system', 'action', 'actor_user_id', 'entity_type', 'occurred_at', 'correlation_id']);
if (($filters['format'] ?? null) === 'json') {
$records = $query->orderByDesc('occurred_at')->limit(1000)->get();
$access->audit($request->user(), 'audit_metadata_exported', ['filters' => $filters, 'count' => $records->count()]);
return response()->json(['filters' => $filters, 'records' => $records, 'limit' => 1000])->header('Content-Disposition', 'attachment; filename="audit-metadata.json"')->header('Cache-Control', 'private, no-store');
}
$records = $query->orderByDesc('occurred_at')->paginate(30)->withQueryString();
$access->audit($request->user(), 'audit_metadata_read', ['filters' => $filters, 'count' => $records->count()]);
return Inertia::render('profiles/audit', ['records' => $records, 'filters' => $filters]);
}
public function registerOperatorOrganization(Request $request, PortalInternalDesignation $service): JsonResponse
{
return response()->json($service->registerOrganization($request->user(), $request->all()), 201);
}
public function grant(Request $request, PortalProfileAdministration $service): JsonResponse
{
return response()->json(['id' => $service->grant($request->user(), $request->all())], 201);
}
public function requestDocument(Request $request, string $id, string $documentId, PortalProfileAdministration $service): \Illuminate\Http\Response|BinaryFileResponse
{
$service->administrative($request->user());
$row = DB::table('portal_profile_requests')->where('id', $id)->first();
abort_unless($row && in_array($documentId, json_decode($row->document_ids, true), true), 404);
$document = DB::table('documents')->where('id', $documentId)->first();
abort_unless($document !== null, 404);
return app(VerifiedDocumentBinary::class)->respond($document, true);
}
public function revoke(Request $request, string $id, PortalProfileAdministration $service): JsonResponse
{
$service->revoke($request->user(), $id, (string) $request->input('reason'));
return response()->json(['message' => 'Papel revogado; sessões e tokens anteriores invalidados.']);
}
public function opportunities(Request $request, PortalProfileAccess $access): Response
{
abort_unless($access->grants($request->user()) !== [] || $access->superuser($request->user()), 403);
return app(OpportunityManagementController::class)->index($request, app(OpportunityManagement::class));
}
public function edit(Request $request, PortalProfileAccess $access, ?int $id = null): Response|\Symfony\Component\HttpFoundation\Response
{
if ($id) {
$access->authorize($request->user(), str_ends_with($request->path(), '/view') ? 'view' : 'edit', Opportunity::withTrashed()->findOrFail($id));
} else {
if (! ($access->navigation($request->user())['contexts'] ?? [])) {
$reason = $access->has($request->user(), 'auditor')
? 'O papel de Auditor permite consulta e impede a criação de oportunidades.'
: 'Esta conta não dispõe de um contexto ativo de Promotor para uma organização e modalidade autorizadas. Confirme a vigência, o âmbito e os tipos atribuídos na gestão de perfis. A elevação excecional de Superutilizador não substitui a autorização de Promotor.';
if ($request->expectsJson()) {
abort(403, $reason);
}
return response()->view('profiles.creation-unavailable', ['reason' => $reason], 403);
}
}
return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id);
}
public function workflow(Request $request, int $id, OpportunityProfileWorkflow $service): JsonResponse
{
$record = $service->transition($request->user(), $id, $request->all());
return response()->json(['id' => $id, 'status' => app(PortalProfileAccess::class)->state($record), 'publication_status' => $record->status, 'etag' => app(OpportunityManagement::class)->etag($record), 'message' => 'Ação interna registada; não representa decisão externa.']);
}
public function contact(Request $request, int $id, OpportunityContacts $service): JsonResponse
{
return response()->json($service->save($request->user(), $id, $request->all()));
}
public function replacement(Request $request, PortalSuperusers $service): JsonResponse
{
$data = $request->validate(['old_user_id' => 'required|integer', 'new_user_id' => 'required|integer', 'reason' => 'required|string|min:20|max:1000']);
return response()->json(['id' => $service->requestReplacement($request->user(), $data['old_user_id'], $data['new_user_id'], $data['reason'])], 201);
}
public function approveSecurity(Request $request, string $id, PortalSuperusers $service): JsonResponse
{
$service->approve($request->user(), $id);
return response()->json(['message' => 'Aprovação independente registada.']);
}
public function replace(Request $request, string $id, PortalSuperusers $service): JsonResponse
{
$service->applyReplacement($request->user(), $id);
return response()->json(['message' => 'Titular substituído atomicamente; continuam dois titulares.']);
}
public function elevation(Request $request, PortalSuperusers $service): JsonResponse
{
$data = $request->validate(['action' => 'required|string', 'record_id' => 'nullable|integer|exists:opportunities,id', 'reason' => 'required|string|min:20|max:1000']);
return response()->json(['id' => $service->requestElevation($request->user(), $data['action'], $data['record_id'] ?? null, $data['reason'])], 201);
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers;
use App\Services\PortalProfileInstallation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class PortalProfileInstallationController extends Controller
{
public function preview(Request $request, PortalProfileInstallation $installation): JsonResponse|Response
{
$plan = $installation->preview($request->user());
return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/installation', $plan);
}
public function apply(Request $request, PortalProfileInstallation $installation): JsonResponse
{
return response()->json($installation->apply($request->user(), $request->all()));
}
public function bootstrap(Request $request, PortalProfileInstallation $installation): JsonResponse
{
return response()->json($installation->bootstrap($request->user(), $request->all()));
}
public function bootstrapPreview(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse|Response
{
$plan = $installation->bootstrapPreview($request->user(), $id);
return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/bootstrap-confirmation', $plan);
}
public function confirmBootstrap(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse
{
return response()->json($installation->confirmBootstrap($request->user(), $id, $request->all()));
}
}
@@ -5,9 +5,12 @@ namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware; use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest; use App\Models\InterestRequest;
use App\Models\Sector; use App\Models\Sector;
use App\Services\CountryCatalogue;
use App\Services\IdempotencyConflict; use App\Services\IdempotencyConflict;
use App\Services\InterestSubmission; use App\Services\InterestSubmission;
use App\Services\LegacyContent;
use App\Services\Malware\MalwareScanner; use App\Services\Malware\MalwareScanner;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Builder;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
@@ -37,7 +40,7 @@ class PortalServicesController extends Controller
$essentialResources = collect(); $essentialResources = collect();
} }
return Inertia::render('PortalInvestidor', ['essentialResources' => $essentialResources]); return Inertia::render('PortalInvestidor', ['essentialResources' => $essentialResources, 'countries' => app(CountryCatalogue::class)->all()]);
} }
private function resources(): Builder private function resources(): Builder
@@ -64,9 +67,9 @@ class PortalServicesController extends Controller
'stage' => ['nullable', 'array', 'max:10'], 'stage.*' => ['string', 'max:80'], 'stage' => ['nullable', 'array', 'max:10'], 'stage.*' => ['string', 'max:80'],
'module' => ['nullable', 'array', 'max:10'], 'module.*' => ['string', 'max:80'], 'module' => ['nullable', 'array', 'max:10'], 'module.*' => ['string', 'max:80'],
]); ]);
$props = ['section' => $page, 'filters' => $filters]; $props = ['section' => $page, 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all()];
if ($page === 'sectors') { if ($page === 'sectors') {
$props['sectors'] = Sector::where('is_active', true)->withCount(['opportunities' => fn ($q) => $q->published()])->orderBy('sort_order')->get(['id', 'name', 'slug', 'short_description']); $props['sectors'] = \App\Services\SectorOrganization::catalog();
} }
if (in_array($page, ['documents', 'legislation'], true)) { if (in_array($page, ['documents', 'legislation'], true)) {
$query = $this->resources(); $query = $this->resources();
@@ -112,19 +115,7 @@ class PortalServicesController extends Controller
'r.source_confirmation', 'r.legal_status', 'r.rights_status', 'r.last_reviewed_at', 'r.last_reviewed_by', 'r.independent_review', 'r.metadata_version', 'r.source_reference', 'r.essential', 'r.source_confirmation', 'r.legal_status', 'r.rights_status', 'r.last_reviewed_at', 'r.last_reviewed_by', 'r.independent_review', 'r.metadata_version', 'r.source_reference', 'r.essential',
'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no',
])->paginate(20)->withQueryString(); ])->paginate(20)->withQueryString();
$pageResult->getCollection()->transform(function ($resource) { $pageResult->getCollection()->transform(fn ($resource) => app(\App\Services\PublicDocumentPresentation::class)->resource($resource));
$resource->links = DB::table('portal_resource_links')->where('resource_id', $resource->id)
->orderBy('target_type')->orderBy('target_key')->get($this->resourceLinkColumns());
$resource->links->transform(fn ($link) => (object) [...(array) $link,
'target_label' => $link->target_type === 'requirement'
? config('document-requirements.catalogue.'.$link->target_key.'.label', $link->target_key)
: null]);
$resource->download_url = route('services.download', ['id' => $resource->id]);
$resource->view_url = in_array($resource->media_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true)
? route('services.document.view', ['id' => $resource->id]) : null;
return $resource;
});
$props['resources'] = $pageResult; $props['resources'] = $pageResult;
$props['documentTypes'] = (clone $this->resources())->distinct()->orderBy('r.document_type')->pluck('r.document_type'); $props['documentTypes'] = (clone $this->resources())->distinct()->orderBy('r.document_type')->pluck('r.document_type');
$props['languages'] = (clone $this->resources())->distinct()->orderBy('r.language')->pluck('r.language'); $props['languages'] = (clone $this->resources())->distinct()->orderBy('r.language')->pluck('r.language');
@@ -195,24 +186,8 @@ class PortalServicesController extends Controller
$matches = [...$matches, ...array_map(fn ($id) => ['type' => 'territory', 'key' => $id], $ids)]; $matches = [...$matches, ...array_map(fn ($id) => ['type' => 'territory', 'key' => $id], $ids)];
} }
$resources = $query->orderByDesc('r.essential')->orderBy('r.title')->limit(10) $resources = $query->orderByDesc('r.essential')->orderBy('r.title')->limit(10)
->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'r.source_reference']); ->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.document_date', 'r.document_number', 'r.applicable_from', 'r.applicable_until', 'r.language', 'r.territorial_scope', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'd.issuer', 'd.media_type', 'd.size_bytes']);
$resources->transform(function ($resource) use ($matches): array { $resources->transform(fn ($resource) => app(\App\Services\PublicDocumentPresentation::class)->resource($resource));
$matched = DB::table('portal_resource_links')->where('resource_id', $resource->id)->whereIn('target_type', array_column($matches, 'type'))
->whereIn('target_key', array_column($matches, 'key'))->orderBy('target_type')->first(['target_type', 'target_key', 'applicability', 'condition_text', 'basis_reference']);
$evidence = $this->requirementEvidenceEnabled()
? DB::table('portal_resource_links')->where('resource_id', $resource->id)->where('target_type', 'requirement')
->where('review_status', 'confirmed')->orderBy('target_key')->get(['target_key', 'basis_reference', 'review_status'])
: collect();
return [...(array) $resource,
'download_url' => route('services.download', ['id' => $resource->id]),
'recommendation_reason' => $matched->condition_text ?? ('Relacionado com '.$matched?->target_type.' '.$matched?->target_key.'; confirme a aplicabilidade ao seu projecto.'),
'applicability' => $matched->applicability ?? 'support',
'basis_reference' => $matched?->basis_reference,
'documentary_evidence' => $evidence->map(fn ($link) => ['key' => $link->target_key,
'label' => config('document-requirements.catalogue.'.$link->target_key.'.label', $link->target_key),
'citation' => $link->basis_reference, 'status' => 'citation_checked_application_pending'])->values()];
});
return response()->json(['data' => $resources]); return response()->json(['data' => $resources]);
} }
@@ -222,7 +197,8 @@ class PortalServicesController extends Controller
$data = $request->validate([ $data = $request->validate([
'kind' => ['required', 'in:support,investor,company,partnership'], 'kind' => ['required', 'in:support,investor,company,partnership'],
'fullName' => ['required', 'string', 'min:3', 'max:150'], 'email' => ['required', 'email:rfc', 'max:150'], 'fullName' => ['required', 'string', 'min:3', 'max:150'], 'email' => ['required', 'email:rfc', 'max:150'],
'phone' => ['nullable', 'string', 'max:30'], 'country' => ['required', 'string', 'max:100'], 'phone' => ['nullable', 'string', 'max:30'], 'country' => ['required', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'company' => ['nullable', 'required_if:kind,company', 'string', 'max:150'], 'company' => ['nullable', 'required_if:kind,company', 'string', 'max:150'],
'sectorInterest' => ['required', 'string', 'max:150'], 'message' => ['required', 'string', 'min:20', 'max:2000'], 'sectorInterest' => ['required', 'string', 'max:150'], 'message' => ['required', 'string', 'min:20', 'max:2000'],
'privacyConsent' => ['required', 'accepted'], 'submission_key' => ['required', 'uuid'], 'privacyConsent' => ['required', 'accepted'], 'submission_key' => ['required', 'uuid'],
@@ -232,15 +208,25 @@ class PortalServicesController extends Controller
abort_unless(DB::table('portal_partnerships')->where('id', $data['partnership_id'])->where('status', 'published')->exists(), 422); abort_unless(DB::table('portal_partnerships')->where('id', $data['partnership_id'])->where('status', 'published')->exists(), 422);
} }
$data['portal_user_id'] = $request->user()?->id; $data['portal_user_id'] = $request->user()?->id;
// Preserve the actual entry form, not only the shared POST endpoint. Never accept an external or administrative referrer as the entry page.
$entry = parse_url($request->headers->get('referer', ''));
$sourcePage = '/apoio';
if (is_array($entry) && strtolower($entry['scheme'] ?? '') === $request->getScheme()
&& strtolower($entry['host'] ?? '') === strtolower($request->getHost())
&& (int) ($entry['port'] ?? (($entry['scheme'] ?? '') === 'https' ? 443 : 80)) === $request->getPort()
&& in_array($entry['path'] ?? '', ['/apoio', '/formularios/investidor', '/formularios/empresa', '/parcerias', '/parcerias/painel'], true)) {
$sourcePage = $entry['path'];
}
try { try {
$interest = $submission->receive($data, $data['submission_key'], fn () => InterestRequest::create([ $interest = $submission->receive($data, $data['submission_key'], fn () => InterestRequest::create([
'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $data['fullName'], 'email' => $data['email'], 'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $data['fullName'], 'email' => $data['email'],
'phone' => $data['phone'] ?? null, 'country' => $data['country'], 'phone' => $data['phone'] ?? null, 'country' => $data['country'],
'investor_type' => $data['kind'] === 'company' ? 'empresa' : 'individual', 'investor_type' => $data['kind'] === 'company' ? 'empresa' : 'individual',
'sector_interest' => $data['sectorInterest'], 'message' => $data['message'], 'sector_interest' => $data['sectorInterest'], 'message' => $data['message'],
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/apoio', 'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => $sourcePage,
'metadata' => ['kind' => $data['kind'], 'company' => $data['company'] ?? null, 'metadata' => ['kind' => $data['kind'], 'company' => $data['company'] ?? null,
'portal_user_id' => $data['portal_user_id'], 'partnership_id' => $data['partnership_id'] ?? null], 'portal_user_id' => $data['portal_user_id'], 'partnership_id' => $data['partnership_id'] ?? null,
'declared_origin_country_code' => $data['declared_origin_country_code'] ?? null],
])); ]));
} catch (IdempotencyConflict) { } catch (IdempotencyConflict) {
abort(409, 'Este envio já foi usado com dados diferentes. Recarregue o formulário.'); abort(409, 'Este envio já foi usado com dados diferentes. Recarregue o formulário.');
@@ -260,17 +246,12 @@ class PortalServicesController extends Controller
return back()->with('success', 'Proposta recebida para publicação. Acompanhe no Balcão Virtual.'); return back()->with('success', 'Proposta recebida para publicação. Acompanhe no Balcão Virtual.');
} }
public function download(int $id): BinaryFileResponse public function download(int $id): BinaryFileResponse|\Illuminate\Http\Response
{ {
$resource = $this->resources()->where('r.id', $id)->first(['d.storage_key', 'd.file_name', 'd.sha256']); $resource = $this->resources()->where('r.id', $id)->first(['d.*']);
abort_unless($resource !== null, 404); abort_unless($resource !== null, 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($resource->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($resource->sha256, $checksum), 404);
return response()->download($path, basename($resource->file_name), ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store']); return app(VerifiedDocumentBinary::class)->respond($resource);
} }
public function showDocument(Request $request, int $id): Response public function showDocument(Request $request, int $id): Response
@@ -282,19 +263,9 @@ class PortalServicesController extends Controller
'r.essential', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no', 'r.essential', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no',
]); ]);
abort_unless($resource !== null, 404); abort_unless($resource !== null, 404);
$resource->links = DB::table('portal_resource_links')->where('resource_id', $id) $resource->territory_name = $resource->territory_id
->orderBy('target_type')->orderBy('target_key') ? DB::table('geo_locations')->where('id', $resource->territory_id)->value('name') : null;
->get($this->resourceLinkColumns()); $resource = app(\App\Services\PublicDocumentPresentation::class)->resource($resource);
$resource->links->transform(fn ($link) => (object) [...(array) $link,
'target_label' => $link->target_type === 'requirement'
? config('document-requirements.catalogue.'.$link->target_key.'.label', $link->target_key)
: null]);
$territory = $resource->territory_id
? DB::table('geo_locations')->where('id', $resource->territory_id)->value('name')
: null;
$resource->territory_name = $territory;
$resource->view_url = in_array($resource->media_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true)
? route('services.document.view', ['id' => $id]) : null;
$back = $request->query('back'); $back = $request->query('back');
$backUrl = is_string($back) && (str_starts_with($back, '/documentos') || str_starts_with($back, '/legislacao')) && ! str_starts_with($back, '//') $backUrl = is_string($back) && (str_starts_with($back, '/documentos') || str_starts_with($back, '/legislacao')) && ! str_starts_with($back, '//')
? $back : '/documentos'; ? $back : '/documentos';
@@ -303,49 +274,59 @@ class PortalServicesController extends Controller
'resource' => $resource, 'resource' => $resource,
'backUrl' => $backUrl, 'backUrl' => $backUrl,
'downloadUrl' => route('services.download', ['id' => $id]), 'downloadUrl' => route('services.download', ['id' => $id]),
'articleUrl' => Schema::hasColumn('portal_resources','editorial_content') && DB::table('portal_resources')->where('id',$id)->whereNotNull('editorial_content')->exists() ? '/artigos/'.$id : null,
]); ]);
} }
public function viewDocument(int $id): BinaryFileResponse public function viewDocument(int $id): BinaryFileResponse|\Illuminate\Http\Response
{ {
$document = $this->resources()->where('r.id', $id)->first([ $document = $this->resources()->where('r.id', $id)->first(['d.*']);
'd.storage_key', 'd.file_name', 'd.sha256', 'd.media_type',
]);
abort_unless($document && in_array($document->media_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true), 404); abort_unless($document && in_array($document->media_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true), 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($document->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($document->sha256, $checksum), 404);
return response()->file($path, [ return app(VerifiedDocumentBinary::class)->respond($document, true);
'Content-Type' => $document->media_type,
'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "sandbox; default-src 'none'; style-src 'unsafe-inline'",
'Cache-Control' => 'private, no-store',
])->setContentDisposition('inline', basename($document->file_name));
} }
public function downloadForManager(string $id): BinaryFileResponse public function downloadForManager(Request $request, string $id): BinaryFileResponse|\Illuminate\Http\Response
{ {
$document = DB::table('documents')->where('id', $id)->whereNull('deleted_at')->first([ $document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->first();
'storage_key', 'file_name', 'sha256', 'status', 'malware_scan_status', 'malware_scanned_sha256',
]);
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean' abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404); && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($document->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($document->sha256, $checksum), 404);
return response()->download($path, basename($document->file_name), [ return app(VerifiedDocumentBinary::class)->respond($document);
'X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store',
]);
} }
public function manage(MalwareScanner $scanner): Response public function manage(Request $request, MalwareScanner $scanner): Response
{ {
$access = app(\App\Services\DocumentManagementAccess::class);
if (! $access->full($request->user())) {
$documents = $access->documents($request->user())->where('status', '!=', 'deleted');
$health = $scanner->health();
$health['signatures_at'] = $health['signatures_at']?->format(DATE_ATOM);
$editorial = $access->editorial($request->user());
$resources = $editorial ? $access->editorialResources($request->user())->orderByDesc('r.updated_at')
->get(['r.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.status as file_status', 'd.data_classification', 'd.version_no as file_version', 'd.rights_status as file_rights_status', 'd.malware_scan_status', 'd.malware_failure_reason']) : collect();
$links = DB::table('portal_resource_links')->whereIn('resource_id', $resources->pluck('id'))->orderBy('id')->get()->groupBy('resource_id');
$revisions = DB::table('portal_resource_revisions')->whereIn('resource_id', $resources->pluck('id'))->orderByDesc('revision_no')->get(['resource_id', 'revision_no', 'change_type', 'actor_user_id', 'created_at'])->groupBy('resource_id');
$resources->each(function ($resource) use ($links, $revisions) {
$resource->links = $links->get($resource->id, collect())->values();
$resource->revisions = $revisions->get($resource->id, collect())->values();
});
return Inertia::render('portal/manage', [
'documentAccessOnly' => ! $editorial, 'editorialScopeOnly' => $editorial, 'resources' => $resources, 'partnerships' => [], 'territories' => [],
'requirementCatalogue' => [], 'requirementAssociationsEnabled' => false,
'disclosureAuthorization' => null, 'incompleteCount' => $resources->filter(fn ($r) => ! $r->description || ! $r->issuer || ! $r->source_url || $r->source_confirmation === 'unconfirmed' || $r->legal_status === 'unknown' || $r->rights_status === 'unconfirmed')->count(), 'possibleDuplicates' => $resources->whereNotNull('duplicate_of_resource_id')->count(),
'documents' => (clone $documents)->latest()->limit(250)->get([
'id', 'file_name', 'media_type', 'size_bytes', 'issuer', 'issued_on', 'valid_until',
'uploaded_by', 'created_at', 'status', 'data_classification', 'version_no', 'sha256',
'rights_status', 'malware_scan_status', 'malware_scanned_at', 'malware_failure_reason',
'malware_engine_version', 'malware_signatures_at', 'malware_scan_attempts',
]),
'malwareCounts' => (clone $documents)->select('malware_scan_status', DB::raw('count(*) as total'))
->groupBy('malware_scan_status')->pluck('total', 'malware_scan_status'),
'malwareHealth' => $health,
]);
}
$disclosureAuthorization = DB::table('audit_events')->where('source_system', 'user-instruction') $disclosureAuthorization = DB::table('audit_events')->where('source_system', 'user-instruction')
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1') ->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']); ->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
@@ -388,7 +369,7 @@ class PortalServicesController extends Controller
public function upload(Request $request): RedirectResponse public function upload(Request $request): RedirectResponse
{ {
$this->validateManagement($request, ['file' => ['required', 'file', 'mimetypes:application/pdf,text/plain,text/csv,image/jpeg,image/png,image/webp,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.text', 'max:10240'], $this->validateManagement($request, ['file' => ['required', 'file', 'mimetypes:application/pdf,text/plain,text/csv,image/jpeg,image/png,image/webp,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.text'.(app(LegacyContent::class)->available() ? ',application/json' : ''), 'max:10240'],
'original_source' => ['nullable', 'url:https', 'max:2000'], 'issuer' => ['nullable', 'string', 'max:180']]); 'original_source' => ['nullable', 'url:https', 'max:2000'], 'issuer' => ['nullable', 'string', 'max:180']]);
$file = $request->file('file'); $file = $request->file('file');
$checksum = hash_file('sha256', $file->getRealPath()); $checksum = hash_file('sha256', $file->getRealPath());
@@ -427,6 +408,7 @@ class PortalServicesController extends Controller
$id = DB::transaction(function () use ($data, $request): int { $id = DB::transaction(function () use ($data, $request): int {
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first(); $document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.'); abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
$identity = $this->identityKey($data); $identity = $this->identityKey($data);
if ($identity) { if ($identity) {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]); DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
@@ -437,8 +419,8 @@ class PortalServicesController extends Controller
$id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]); $id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]);
$this->syncResourceLinks($id, $data['associations'] ?? []); $this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'created', $request->user()->id, 1); $this->recordResourceRevision($id, 'created', $request->user()->id, 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer, DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'], 'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]); 'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, $duplicate ? 'resource_registered_possible_duplicate' : 'resource_registered', 'portal_resources', $id); $this->audit($request, $duplicate ? 'resource_registered_possible_duplicate' : 'resource_registered', 'portal_resources', $id);
@@ -455,9 +437,11 @@ class PortalServicesController extends Controller
DB::transaction(function () use ($data, $request, $id, $expectedVersion): void { DB::transaction(function () use ($data, $request, $id, $expectedVersion): void {
$resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first(); $resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
abort_unless($resource !== null, 404); abort_unless($resource !== null, 404);
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
abort_if((int) $resource->metadata_version !== $expectedVersion, 409, 'O documento foi alterado por outra sessão. Recarregue a revisão antes de editar.'); abort_if((int) $resource->metadata_version !== $expectedVersion, 409, 'O documento foi alterado por outra sessão. Recarregue a revisão antes de editar.');
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first(); $document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.'); abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
$identity = $this->identityKey($data); $identity = $this->identityKey($data);
if ($identity) { if ($identity) {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]); DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
@@ -475,8 +459,8 @@ class PortalServicesController extends Controller
DB::table('portal_resource_links')->where('resource_id', $id)->delete(); DB::table('portal_resource_links')->where('resource_id', $id)->delete();
$this->syncResourceLinks($id, $data['associations'] ?? []); $this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'metadata_updated', $request->user()->id, $expectedVersion + 1); $this->recordResourceRevision($id, 'metadata_updated', $request->user()->id, $expectedVersion + 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer, DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'], 'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]); 'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, 'resource_metadata_updated', 'portal_resources', $id); $this->audit($request, 'resource_metadata_updated', 'portal_resources', $id);
}); });
@@ -486,6 +470,11 @@ class PortalServicesController extends Controller
public function moderate(Request $request, string $type, int $id): RedirectResponse public function moderate(Request $request, string $type, int $id): RedirectResponse
{ {
$access = app(\App\Services\DocumentManagementAccess::class);
if (! $access->full($request->user())) {
abort_unless($type === 'resources', 403);
$access->assertEditableResource($request->user(), $id);
}
if ($type === 'partnerships' && Schema::hasColumn('portal_partnerships', 'partnership_type')) { if ($type === 'partnerships' && Schema::hasColumn('portal_partnerships', 'partnership_type')) {
return redirect('/parcerias/'.$id)->with('success', 'Reveja a proposta e registe uma decisão fundamentada na ficha da Bolsa.'); return redirect('/parcerias/'.$id)->with('success', 'Reveja a proposta e registe uma decisão fundamentada na ficha da Bolsa.');
} }
@@ -493,6 +482,7 @@ class PortalServicesController extends Controller
$table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships'; $table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships';
DB::transaction(function () use ($request, $data, $table, $type, $id) { DB::transaction(function () use ($request, $data, $table, $type, $id) {
abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404); abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404);
if ($type === 'resources') app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
if ($type === 'resources' && $data['published']) { if ($type === 'resources' && $data['published']) {
$resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id') $resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.id', $id)->first(['r.document_type', 'r.legislation', 'r.source_confirmation', 'r.legal_status', 'r.rights_status', ->where('r.id', $id)->first(['r.document_type', 'r.legislation', 'r.source_confirmation', 'r.legal_status', 'r.rights_status',
@@ -657,7 +647,9 @@ class PortalServicesController extends Controller
$data = $this->validateManagement($request, [ $data = $this->validateManagement($request, [
'document_id' => ['required', 'uuid'], 'title' => ['required', 'string', 'max:200'], 'document_id' => ['required', 'uuid'], 'title' => ['required', 'string', 'max:200'],
'description' => ['nullable', 'string', 'max:4000'], 'category' => ['required', 'string', 'max:80'], 'description' => ['nullable', 'string', 'max:4000'], 'category' => ['required', 'string', 'max:80'],
'topic' => ['required', 'string', 'max:80'], 'document_type' => ['required', 'in:legislation,procedure,official_form,digital_adaptation,guidance_template,guide,study,reference_data,unknown'], // QA legacy originals may have no theme (e.g. a shared image). Do not invent a sector to disclose an authorized original.
'topic' => [app(LegacyContent::class)->available() ? 'nullable' : 'required', 'string', 'max:80'],
'document_type' => ['required', 'in:legislation,procedure,official_form,digital_adaptation,guidance_template,guide,study,reference_data,unknown'],
'issuer' => ['nullable', 'string', 'max:180'], 'document_number' => ['nullable', 'string', 'max:120'], 'issuer' => ['nullable', 'string', 'max:180'], 'document_number' => ['nullable', 'string', 'max:120'],
'document_date' => ['nullable', 'date_format:Y-m-d'], 'source_url' => ['nullable', 'url:https', 'max:2000'], 'document_date' => ['nullable', 'date_format:Y-m-d'], 'source_url' => ['nullable', 'url:https', 'max:2000'],
'applicable_from' => ['nullable', 'date_format:Y-m-d'], 'applicable_from' => ['nullable', 'date_format:Y-m-d'],
@@ -678,6 +670,7 @@ class PortalServicesController extends Controller
'associations.*.applicability' => ['required', 'in:required,conditional,support,optional_template,evidence'], 'associations.*.applicability' => ['required', 'in:required,conditional,support,optional_template,evidence'],
'associations.*.condition_text' => ['nullable', 'string', 'max:2000'], 'associations.*.basis_reference' => ['nullable', 'string', 'max:2000'], 'associations.*.condition_text' => ['nullable', 'string', 'max:2000'], 'associations.*.basis_reference' => ['nullable', 'string', 'max:2000'],
]); ]);
$data['topic'] = $data['topic'] ?? '';
if (! empty($data['applicable_from']) && ! empty($data['applicable_until']) && $data['applicable_until'] < $data['applicable_from']) { if (! empty($data['applicable_from']) && ! empty($data['applicable_until']) && $data['applicable_until'] < $data['applicable_from']) {
throw $this->managementValidationException(['applicable_until' => 'A data final deve ser igual ou posterior à data inicial.']); throw $this->managementValidationException(['applicable_until' => 'A data final deve ser igual ou posterior à data inicial.']);
} }
@@ -4,7 +4,10 @@ namespace App\Http\Controllers;
use App\Http\Resources\PublicBusinessOpportunityResource; use App\Http\Resources\PublicBusinessOpportunityResource;
use App\Models\ExistingBusiness; use App\Models\ExistingBusiness;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts; use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessClassification;
use App\Services\OpportunityClassification;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -18,16 +21,10 @@ class PublicBusinessOpportunityController extends Controller
{ {
public function index(Request $request): Response|JsonResponse public function index(Request $request): Response|JsonResponse
{ {
$filters = $request->validate([ $filters = $this->filters($request);
'q' => ['nullable', 'string', 'max:120'],
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
'sector' => ['nullable', 'integer', 'min:1'],
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
]);
$query = $this->publishedQuery(); $query = $this->publishedQuery();
app(ExistingBusinessClassification::class)->constrain($query, $filters);
$path = app(InvestmentGeography::class)->selection($filters); $path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) { if ($path !== []) {
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id); $territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
@@ -46,18 +43,34 @@ class PublicBusinessOpportunityController extends Controller
->orWhereLike('existing_businesses.objective', '%'.$term.'%')); ->orWhereLike('existing_businesses.objective', '%'.$term.'%'));
} }
if (! empty($filters['sector'])) { if (! empty($filters['sector'])) {
$query->where('existing_businesses.sector_id', $filters['sector']); $sector = \App\Models\Sector::find($filters['sector']);
$query->whereIn('existing_businesses.sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
} }
if (! empty($filters['modality'])) { if (! empty($filters['modality'])) {
$query->where('existing_businesses.modality', $filters['modality']); $query->where('existing_businesses.modality', $filters['modality']);
} }
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->withQueryString()); $results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->appends($filters));
if ($request->expectsJson()) { if ($request->expectsJson()) {
return $results->response(); return $results->response();
} }
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path]); return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path,
'classificationOptions' => app(OpportunityClassification::class)->options(),
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz'])]);
}
private function filters(Request $request): array
{
return $request->validate([
'q' => ['nullable', 'string', 'max:120'],
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
'sector' => ['nullable', 'integer', 'min:1'],
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
...app(ExistingBusinessClassification::class)->filterRules(),
]);
} }
public function show(Request $request, string $slug): Response|JsonResponse public function show(Request $request, string $slug): Response|JsonResponse
@@ -68,7 +81,7 @@ class PublicBusinessOpportunityController extends Controller
return $resource->response(); return $resource->response();
} }
$returnFilters = $request->query(); $returnFilters = $this->filters($request);
return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request), return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request),
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters), 'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
@@ -79,11 +92,12 @@ class PublicBusinessOpportunityController extends Controller
{ {
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail(); $record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
$returnFilters = $request->query(); $returnFilters = $this->filters($request);
return Inertia::render('investment/business-interest', [ return Inertia::render('investment/business-interest', [
'record' => (new PublicBusinessOpportunityResource($record))->resolve($request), 'record' => (new PublicBusinessOpportunityResource($record))->resolve($request),
'modalities' => ExistingBusinessDrafts::MODALITIES, 'modalities' => ExistingBusinessDrafts::MODALITIES,
'countries' => app(CountryCatalogue::class)->all(),
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters), 'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
]); ]);
} }
@@ -107,6 +121,7 @@ class PublicBusinessOpportunityController extends Controller
'existing_businesses.activity_code', 'existing_businesses.stage', 'existing_businesses.objective', 'existing_businesses.activity_code', 'existing_businesses.stage', 'existing_businesses.objective',
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max', 'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id', 'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
'existing_businesses.owner_user_id', 'existing_businesses.organization_id', 'existing_businesses.version_no', 'existing_businesses.expires_at', 'existing_businesses.status', 'existing_businesses.modality',
'public_location.province', 'public_location.district', 'public_location.locality']); 'public_location.province', 'public_location.district', 'public_location.locality']);
} }
} }
@@ -4,6 +4,8 @@ namespace App\Http\Controllers;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Sector; use App\Models\Sector;
use App\Services\CountryCatalogue;
use App\Services\SectorInvestment;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -17,12 +19,15 @@ class PublicPortalController extends Controller
return Inertia::render('PortalInvestidor', ['initialView' => 'opportunities', 'initialQuery' => $filters['q'] ?? '', 'initialSector' => $filters['sector'] ?? '']); return Inertia::render('PortalInvestidor', ['initialView' => 'opportunities', 'initialQuery' => $filters['q'] ?? '', 'initialSector' => $filters['sector'] ?? '']);
} }
public function sector(string $slug): Response public function sector(string $slug): Response|\Illuminate\Http\RedirectResponse
{ {
$sector = Sector::where('slug', $slug)->where('is_active', true)->firstOrFail(); if (in_array($slug, ['energia', 'fintech'], true)) return redirect(\App\Services\SectorOrganization::href($slug), 301);
if ($slug === 'mercado-financeiro/fintech') $slug = 'fintech';
$sector = Sector::where('slug', $slug)->where('is_active', true)->whereNotNull('published_at')->firstOrFail();
return Inertia::render('portal/services', ['section' => 'sector', 'sector' => $sector->only(['name', 'slug', 'description', 'short_description']), return Inertia::render('portal/services', ['section' => 'sector', 'sector' => $sector->only(['id', 'name', 'slug', 'description', 'short_description']),
'opportunities' => $sector->opportunities()->published()->latest('published_at')->limit(12)->get(['title', 'slug', 'province', 'summary'])]); 'sectorEntry' => array_key_exists($sector->slug, SectorInvestment::CONTENT) ? app(SectorInvestment::class)->publicView($sector) : null,
'opportunities' => \App\Services\SectorOrganization::opportunities($sector)->latest('published_at')->limit(12)->get(['id', 'title', 'slug', 'province', 'summary'])]);
} }
public function opportunity(string $slug): Response public function opportunity(string $slug): Response
@@ -32,13 +37,13 @@ class PublicPortalController extends Controller
public function interest(?string $slug = null): Response public function interest(?string $slug = null): Response
{ {
return $slug ? $this->detail($slug, 'interest') : Inertia::render('PortalInvestidor', ['initialView' => 'interest']); return $slug ? $this->detail($slug, 'interest') : Inertia::render('PortalInvestidor', ['initialView' => 'interest', 'countries' => app(CountryCatalogue::class)->all()]);
} }
private function detail(string $slug, string $view): Response private function detail(string $slug, string $view): Response
{ {
$opportunity = Opportunity::with('sector:id,name,slug')->published()->where('slug', $slug)->firstOrFail(); $opportunity = Opportunity::with('sector:id,name,slug')->published()->where('slug', $slug)->firstOrFail();
return Inertia::render('PortalInvestidor', ['initialView' => $view, 'initialOpportunity' => $opportunity]); return Inertia::render('PortalInvestidor', ['initialView' => $view, 'initialOpportunity' => $opportunity, 'countries' => app(CountryCatalogue::class)->all()]);
} }
} }
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers;
use App\Services\SectorReconciliationExecution;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
final class SectorReconciliationController extends Controller
{
public function preview(Request $request, SectorReconciliationExecution $execution)
{
$plan = $execution->preview($request);
return $request->expectsJson() ? response()->json($plan)->header('Cache-Control', 'private, no-store')
: response()->view('management.sector-reconciliation', ['plan' => $plan, 'operationKey' => (string)Str::uuid()])->header('Cache-Control', 'private, no-store');
}
public function apply(Request $request, SectorReconciliationExecution $execution)
{
return response()->json($execution->apply($request))->header('Cache-Control', 'private, no-store');
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers;
use App\Services\TerritoryGeometryImport;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class TerritoryGeometryImportController extends Controller
{
public function preview(Request $request, TerritoryGeometryImport $service): JsonResponse|Response
{
$data = $request->validate(['level' => 'nullable|integer|in:1,2,3']);
$plan = $service->preview($request->user(), (int) ($data['level'] ?? 1));
return $request->expectsJson() ? response()->json($plan) : Inertia::render('management/territory-geometry-import', ['plan' => $plan]);
}
public function apply(Request $request, TerritoryGeometryImport $service): JsonResponse
{
return response()->json($service->apply($request->user(), $request->all()));
}
public function reverse(Request $request, string $batch, TerritoryGeometryImport $service): JsonResponse
{
return response()->json($service->reverse($request->user(), $batch, $request->all()));
}
}
+47 -17
View File
@@ -3,10 +3,14 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware; use App\Jobs\ScanDocumentForMalware;
use App\Models\InvestmentSubmission;
use App\Models\User; use App\Models\User;
use App\Services\Ai\InvestorGuidance; use App\Services\Ai\InvestorGuidance;
use App\Services\CountryCatalogue;
use App\Services\InstitutionalLinkMonitor; use App\Services\InstitutionalLinkMonitor;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\InvestorContextConsumers;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -48,8 +52,8 @@ class VirtualDeskController extends Controller
$data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(), $data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(),
'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']), 'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']),
'companies' => DB::table('investment_company_declarations')->where('user_id', $actor->id)->get(['id', 'payload'])->map(fn ($c) => ['id' => $c->id, 'name' => $desk->decode($c->payload)['name'] ?? 'Declaração empresarial']), 'companies' => DB::table('investment_company_declarations')->where('user_id', $actor->id)->get(['id', 'payload'])->map(fn ($c) => ['id' => $c->id, 'name' => $desk->decode($c->payload)['name'] ?? 'Declaração empresarial']),
'submissions' => DB::table('investment_submissions')->where('user_id', $actor->id)->get(['id', 'status']), 'submissions' => InvestmentSubmission::where('user_id', $actor->id)->get()->map(fn ($s) => ['id' => $s->id, 'status' => $s->status, 'name' => ($s->opportunity_id ? DB::table('opportunities')->where('id', $s->opportunity_id)->value('title') : null) ?? ($s->dossier_id ? DB::table('investment_dossiers')->where('id', $s->dossier_id)->value('title') : null) ?? ($s->payload['organisation'] ?? null)]),
'journeys' => DB::table('investor_journeys')->where('user_id', $actor->id)->whereNull('deleted_at')->get(['id', 'dossier_id', 'status']), 'journeys' => DB::table('investor_journeys as j')->leftJoin('investment_dossiers as d', 'd.id', '=', 'j.dossier_id')->where('j.user_id', $actor->id)->whereNull('j.deleted_at')->get(['j.id', 'j.dossier_id', 'j.status', 'd.title as name']),
'simulationDrafts' => DB::table('simulation_form_drafts')->where('owner_user_id', $actor->id)->whereNull('deleted_at')->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->get(['id', 'version_no']), 'simulationDrafts' => DB::table('simulation_form_drafts')->where('owner_user_id', $actor->id)->whereNull('deleted_at')->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->get(['id', 'version_no']),
'guidanceTasks' => app(InvestorGuidance::class)->installed() ? DB::table('tasks as t')->join('desk_cases as c', 'c.id', '=', 't.desk_case_id') 'guidanceTasks' => app(InvestorGuidance::class)->installed() ? DB::table('tasks as t')->join('desk_cases as c', 'c.id', '=', 't.desk_case_id')
->whereNull('t.deleted_at')->when(! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->where('t.assignee_user_id', $actor->id)->orWhere(fn ($s) => $s->where('c.user_id', $actor->id)->whereNull('c.organization_id'))->orWhereIn('c.organization_id', $organizations))) ->whereNull('t.deleted_at')->when(! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->where('t.assignee_user_id', $actor->id)->orWhere(fn ($s) => $s->where('c.user_id', $actor->id)->whereNull('c.organization_id'))->orWhereIn('c.organization_id', $organizations)))
@@ -72,7 +76,11 @@ class VirtualDeskController extends Controller
$case = $desk->case($request->user(), $id); $case = $desk->case($request->user(), $id);
$owner = $desk->owns($request->user(), $case, false); $owner = $desk->owns($request->user(), $case, false);
$this->auditRead($request, 'desk_cases', $id); $this->auditRead($request, 'desk_cases', $id);
$data = ['case' => [...(array) $case, 'payload' => Arr::except($desk->decode($case->payload), $owner ? ['_creation_hash'] : ['_creation_hash', 'profile', 'company', 'investment', 'name', 'email']), 'workflow' => json_decode($case->workflow, true)], $hidden = $owner ? ['_creation_hash'] : ['_creation_hash', 'profile', 'company', 'investment', 'name', 'email'];
if ((int) $case->user_id !== $request->user()->id) {
$hidden[] = 'investor_path';
}
$data = ['case' => [...(array) $case, 'payload' => Arr::except($desk->decode($case->payload), $hidden), 'workflow' => json_decode($case->workflow, true)],
'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at') 'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at')
->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id)) ->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id))
->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null, ->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null,
@@ -122,6 +130,13 @@ class VirtualDeskController extends Controller
$row = $desk->request($request->user(), $id); $row = $desk->request($request->user(), $id);
$case = $desk->case($request->user(), $row->case_id); $case = $desk->case($request->user(), $row->case_id);
$payload = $desk->decode($row->payload); $payload = $desk->decode($row->payload);
$definition = $desk->definition($row);
$territoryPaths = [];
foreach ($definition['fields'] as $key => $field) {
if ($field['type'] === 'territory') {
$territoryPaths[$key] = app(InvestmentGeography::class)->path($payload[$key] ?? null);
}
}
$messageKinds = []; $messageKinds = [];
foreach (DB::table('desk_events')->where('request_id', $id)->where('action', 'message_added')->get() as $event) { foreach (DB::table('desk_events')->where('request_id', $id)->where('action', 'message_added')->get() as $event) {
$original = $desk->decode($event->payload); $original = $desk->decode($event->payload);
@@ -130,10 +145,10 @@ class VirtualDeskController extends Controller
} }
} }
$this->auditRead($request, 'desk_requests', $id); $this->auditRead($request, 'desk_requests', $id);
$data = ['request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)], $data = ['boundContextRevision' => app(InvestorContextConsumers::class)->requestRevision($row), 'countries' => app(CountryCatalogue::class)->all(), 'toolPrefill' => $desk->requestToolPrefill($request->user(), $row), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $desk->definition($row), 'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true), 'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
'owner' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'), 'analyst' => (int) $row->analyst_id === $request->user()->id, 'owner' => $desk->owns($request->user(), $case), 'manager' => app(\App\Services\ScopedPortalAdministration::class)->deskDecision($request->user(),$row), 'analyst' => (int) $row->analyst_id === $request->user()->id,
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []), 'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(), 'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body), 'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
@@ -161,14 +176,26 @@ class VirtualDeskController extends Controller
return $request->expectsJson() ? response()->json(['version' => $row->version, 'status' => $row->status]) : back()->with('success', 'Decisão interna registada.'); return $request->expectsJson() ? response()->json(['version' => $row->version, 'status' => $row->status]) : back()->with('success', 'Decisão interna registada.');
} }
public function assignments(Request $request): JsonResponse|Response
{
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
// Triage projection deliberately excludes payloads, documents, investor identity and case titles.
$data=['requests'=>DB::table('desk_requests')->whereNotIn('status',['draft','cancelled','closed'])->orderBy('created_at')->get(['id','protocol','status','version','analyst_id','due_at']),
'analysts'=>User::whereNotNull('email_verified_at')->orderBy('name')->get(['id','name'])];
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
}
public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{ {
abort_unless($request->user()->can('manage-portal'), 403); abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()), 403);
$data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date']); $data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date'], ['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 3 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.exists'=>'Seleccione um responsável com conta disponível.']);
DB::transaction(function () use ($request, $id, $desk, $data) { DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true); $row = DB::table('desk_requests')->where('id',$id)->lockForUpdate()->first();
$case = $desk->case($request->user(), $row->case_id); abort_unless($row,404);
abort_unless((int) $row->version === (int) $data['version'] && ! in_array($row->status, ['draft', 'cancelled', 'closed'], true), 409); $case = DB::table('desk_cases')->where('id',$row->case_id)->first();
abort_unless($case,404);
if ((int)$row->version !== (int)$data['version']) throw \Illuminate\Validation\ValidationException::withMessages(['version'=>'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
if (in_array($row->status,['draft','cancelled','closed'],true)) throw \Illuminate\Validation\ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
$analyst = User::where('id', $data['analyst_id'])->firstOrFail(); $analyst = User::where('id', $data['analyst_id'])->firstOrFail();
abort_unless($analyst->hasVerifiedEmail(), 422, 'O responsável deve ter conta verificada.'); abort_unless($analyst->hasVerifiedEmail(), 422, 'O responsável deve ter conta verificada.');
abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.'); abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.');
@@ -202,13 +229,18 @@ class VirtualDeskController extends Controller
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Mensagem privada guardada.'); return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Mensagem privada guardada.');
} }
public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse|\Illuminate\Http\Response
{ {
$row = $desk->request($request->user(), $id); $row = $desk->request($request->user(), $id);
abort_unless($row->protocol && $row->submitted_snapshot, 404); abort_unless($row->protocol && $row->submitted_snapshot, 404);
$snapshot = $desk->decode($row->submitted_snapshot); $snapshot = $desk->decode($row->submitted_snapshot);
$format = $request->validate(['format' => 'nullable|in:html'])['format'] ?? null;
$this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded'); $this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded');
if ($format === 'html') {
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $desk->definition($row)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
}
return response()->streamDownload(function () use ($row, $snapshot) { return response()->streamDownload(function () use ($row, $snapshot) {
echo 'Balcão Virtual — recibo de submissão interna'.PHP_EOL.$row->protocol.PHP_EOL.'Data: '.$row->submitted_at.PHP_EOL.'Versão: '.$row->version.PHP_EOL; echo 'Balcão Virtual — recibo de submissão interna'.PHP_EOL.$row->protocol.PHP_EOL.'Data: '.$row->submitted_at.PHP_EOL.'Versão: '.$row->version.PHP_EOL;
echo json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); echo json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
@@ -274,7 +306,7 @@ class VirtualDeskController extends Controller
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Documento privado associado; consulte o estado da análise.'); return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Documento privado associado; consulte o estado da análise.');
} }
public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse|\Illuminate\Http\Response
{ {
$desk->case($request->user(), $id); $desk->case($request->user(), $id);
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('l.id', $document)->whereNull('d.deleted_at')->first(['d.*', 'l.request_id']); $doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('l.id', $document)->whereNull('d.deleted_at')->first(['d.*', 'l.request_id']);
@@ -282,12 +314,10 @@ class VirtualDeskController extends Controller
$desk->request($request->user(), $doc->request_id); $desk->request($request->user(), $doc->request_id);
} }
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 404); abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 404);
$path = realpath(Storage::disk('local')->path($doc->storage_key)); $response = app(VerifiedDocumentBinary::class)->respond($doc);
$root = realpath(Storage::disk('local')->path(''));
abort_unless($path && $root && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path) && is_string($actualHash = hash_file('sha256', $path)) && hash_equals(trim($doc->sha256), $actualHash), 404);
$this->auditRead($request, 'documents', $doc->id, 'document_downloaded'); $this->auditRead($request, 'documents', $doc->id, 'document_downloaded');
return response()->download($path, $doc->file_name, ['Cache-Control' => 'private, no-store']); return $response;
} }
public function notification(Request $request, int $id): RedirectResponse public function notification(Request $request, int $id): RedirectResponse
@@ -0,0 +1,38 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class AuditProfileDecision
{
public function handle(Request $request, Closure $next): Response
{
$access = app(PortalProfileAccess::class);
if (! $request->user() || ! $access->governanceAvailable() || ! preg_match('#^(perfil/|perfis/|minhas-oportunidades)#', $request->path())) {
return $next($request);
}
try {
$response = $next($request);
} catch (\Throwable $error) {
$status = $error instanceof HttpExceptionInterface ? $error->getStatusCode() : ($error instanceof ValidationException ? 422 : 500);
$this->record($request, $access, $status);
throw $error;
}
if ($response->getStatusCode() >= 400) {
$this->record($request, $access, $response->getStatusCode());
}
return $response;
}
private function record(Request $request, PortalProfileAccess $access, int $status): void
{
$access->audit($request->user(), 'request_denied', ['method' => $request->method(), 'path' => $request->path(), 'status' => $status]);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use App\Services\DocumentManagementAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureDocumentManagement
{
public function handle(Request $request, Closure $next): Response
{
$actor = $request->user();
abort_unless($actor, 403);
$access = app(DocumentManagementAccess::class);
if ($access->full($actor)) {
return $next($request); // Preserve existing management controls.
}
$allowed = $access->limited($actor) || $access->editorial($actor);
$access->audit($actor, $allowed ? 'document_access_allowed' : 'document_access_denied', [
'scope' => $access->editorial($actor) ? 'approved-editorial-catalogue-and-own-files' : 'own-portal-services-files', 'method' => $request->method(), 'path' => $request->path(),
]);
abort_unless($allowed, 403, 'O acesso documental exige autorização, email confirmado e autenticação MFA nesta sessão.');
return $next($request);
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/** Environment reservation is not a portal identity or a business permission. */
class EnsureHomologationAccess
{
public function handle(Request $request, Closure $next): Response
{
if (!config('portal.homologation_only', false)) return $next($request);
$mode=config('portal.homologation_access_mode', 'reviewers');
if ($mode==='perimeter') {
// Set only by the trusted server after its environment-access check.
// A client HTTP_INVESTMOZ_* header is deliberately not accepted.
abort_unless($request->server('INVESTMOZ_HOMOLOGATION_ACCESS')==='granted',403,
'Este ambiente de homologação tem acesso reservado à Tempo.');
$response=$next($request);
$response->headers->set('Cache-Control','private, no-store');
$response->headers->set('X-Robots-Tag','noindex, nofollow, noarchive');
return $response;
}
abort_unless($mode==='reviewers',503,'A reserva da homologação não está configurada.');
// Compatibility until an independent perimeter is explicitly configured.
if ($request->is('login','logout','register','forgot-password','reset-password','reset-password/*',
'email/verify','email/verify/*','email/verification-notification','two-factor-challenge',
'user/confirm-password','user/confirmed-password-status','user/two-factor-*',
'settings/security','settings/password','user/password','passkeys/*','user/passkeys/*','up')) return $next($request);
$actor=$request->user();
if (!$actor) return $request->expectsJson()
? response()->json(['message'=>'Entre na conta autorizada para homologação.'],401)
: redirect()->guest(route('login'));
abort_unless($actor->hasVerifiedEmail() && in_array(strtolower(trim($actor->email)),config('portal.homologation_reviewers',[]),true),403,
'Esta homologação está reservada às contas indicadas pela Tempo.');
$response=$next($request);$response->headers->set('Cache-Control','private, no-store');return $response;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsurePortalProfileAdministration
{
public function handle(Request $request, Closure $next): Response
{
abort_unless(config('portal.profile_administration_enabled') || config('portal.profile_access_enabled'), 404);
abort_unless(app(PortalProfileAccess::class)->governanceAvailable(), 503, 'Autorização por perfis ainda não instalada.');
return $next($request);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsurePortalProfiles
{
public function handle(Request $request, Closure $next): Response
{
abort_unless(config('portal.profile_access_enabled'), 404);
abort_unless(app(PortalProfileAccess::class)->available(), 503, 'Autorização por perfis ainda não instalada.');
return $next($request);
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureScopedEditorial
{
public function handle(Request $request, Closure $next): Response
{
$actor = $request->user();
abort_unless($actor, 403);
$access = app(\App\Services\DocumentManagementAccess::class);
if ($access->full($actor)) {
return $next($request);
}
abort_unless($access->editorial($actor), 403);
$allowed = in_array($request->route()->getName(), ['editorial.edit', 'editorial.save', 'services.resource', 'services.resource.update'], true)
|| ($request->route()->getName() === 'services.moderate' && $request->route('type') === 'resources');
abort_unless($allowed, 403);
if ($request->route('id') !== null) {
$access->assertEditableResource($actor, (int) $request->route('id'));
}
return $next($request);
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Services\ScopedPortalAdministration;
final class EnsureScopedPortalAdministration
{
public function handle(Request $request, Closure $next): Response
{
$actor=$request->user();abort_unless($actor,403);
$scope=app(ScopedPortalAdministration::class);
$path=$request->path();
$interests=$request->is('management/interests','management/interests/*','api/v1/investment/admin/interests/*');
// Exact areas of P1; unrelated management, fiscal rules and private records keep their gate.
$catalogue=$request->is('management/economic-references/lot-01','management/economic-references/lot-01/*',
'management/education','management/education/*','management/investment/references','management/investment/references/*','api/v1/investment/admin/references','api/v1/investment/admin/references/*',
'management/investment/zones','management/investment/zones/*','api/v2/investment/admin/zones','api/v2/investment/admin/zones/*',
'management/balcao/atribuicoes','management/balcao/atribuicoes/*','management/balcao/servicos',
'management/balcao/fontes') || ($request->isMethod('GET') && $path==='management/balcao-install');
$allowed=$interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor));
abort_unless($allowed || ($actor->can('manage-portal') && !app(\App\Services\PortalProfileAccess::class)->has($actor,'auditor')),403,'Acesso reservado ao âmbito já designado.');
$response=$next($request);
if (!$request->isMethod('GET') && $response->getStatusCode()<400) {
app(\App\Services\PortalProfileAccess::class)->audit($actor,'scoped_administration',[
'method'=>$request->method(),'route'=>$request->route()?->uri(),'scope'=>$interests?'assigned-interest':'catalogue-administration']);
}
return $response;
}
}
@@ -2,6 +2,11 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Models\ExistingBusiness;
use App\Services\InvestorPath;
use App\Services\LegacyContent;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAccess;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Middleware; use Inertia\Middleware;
@@ -23,6 +28,14 @@ class HandleInertiaRequests extends Middleware
*/ */
public function version(Request $request): ?string public function version(Request $request): ?string
{ {
if (app()->environment('testing') && config('portal.qa_build_directory')) {
$manifest = public_path(config('portal.qa_build_directory').'/manifest.json');
$version = is_file($manifest) ? hash_file('xxh128', $manifest) : false;
return $version === false ? null : $version;
}
return parent::version($request); return parent::version($request);
} }
@@ -38,11 +51,33 @@ class HandleInertiaRequests extends Middleware
return [ return [
...parent::share($request), ...parent::share($request),
'name' => config('app.name'), 'name' => config('app.name'),
'homologationReserved' => (bool) config('portal.homologation_only', false),
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
'portalOperator' => config('portal.operator_name'), 'portalOperator' => config('portal.operator_name'),
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
'legacyContentEnabled' => app(LegacyContent::class)->available(),
'educationEnabled' => (bool) config('education.enabled', false), 'educationEnabled' => (bool) config('education.enabled', false),
'aiEnabled' => (bool) config('investmoz_ai.enabled', false), 'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false), 'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
'businessReviewUrl' => config('existing-business.enabled') && $request->user()?->can('reviewQueue', ExistingBusiness::class)
? '/management/negocios' : null,
'investorPathEnabled' => app(InvestorPath::class)->available(),
'opportunityManagement' => config('portal.opportunity_dashboard_access_enabled') && $request->user() && app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()) ? [
'installed' => app(OpportunityManagement::class)->installed(),
'manage' => ['label' => 'Gestão de Oportunidades', 'href' => '/management/opportunities'],
'create' => ['label' => 'Nova oportunidade', 'href' => '/management/opportunities/create'],
'installationHref' => '/management/opportunity-management-install',
] : null,
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')], 'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
'scopedAdministration' => $request->user() && app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()) ? [
['label'=>'Zonas e parques','href'=>'/management/investment/zones'],
['label'=>'Referências económicas','href'=>'/management/economic-references/lot-01'],
['label'=>'Referências e formulários','href'=>'/management/investment/references'],
['label'=>'Educação e competências','href'=>'/management/education'],
['label'=>'Interesses atribuídos','href'=>'/management/interests'],
['label'=>'Atribuições de interesses','href'=>'/management/interests/atribuicoes'],
['label'=>'Atribuições do Balcão','href'=>'/management/balcao/atribuicoes'],
] : [],
'auth' => [ 'auth' => [
'user' => $request->user(), 'user' => $request->user(),
'canManagePortal' => $request->user()?->can('manage-portal') ?? false, 'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
class PortalProfileSession
{
public function handle(Request $request, Closure $next): Response
{
$access = app(PortalProfileAccess::class);
$available = $access->governanceAvailable();
if ($request->user() && (config('portal.profile_access_enabled') || config('portal.profile_administration_enabled')) && ! $available) {
$recovery = $request->is('management/profile-install', 'management/profile-install/bootstrap')
|| ($request->is('logout') && $request->isMethod('POST'));
abort_if(! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && ! $recovery, 503,
'Autorizações indisponíveis: recuperar a consistência dos perfis antes de gravar. Pode terminar a sessão ou consultar o instalador.');
}
if ($request->user() && $available) {
$revision = (int) DB::table('users')->where('id', $request->user()->id)->value('portal_access_revision');
$bound = $request->session()->get('portal.access_revision');
if (($bound === null && $revision > 0) || ($bound !== null && (int) $bound !== $revision)) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return $request->expectsJson() ? response()->json(['message' => 'A autorização foi alterada. Inicie uma nova sessão.'], 401)
: redirect('/login')->withErrors(['email' => 'A autorização foi alterada. Inicie uma nova sessão.']);
}
$request->session()->put('portal.access_revision', $revision);
}
return $next($request);
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
class ProtectPrivilegedIdentity
{
public function handle(Request $request, Closure $next): Response
{
$actor = $request->user();
$access = app(PortalProfileAccess::class);
if (! $actor || ! $access->governanceAvailable()) {
return $next($request);
}
if (! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && $access->has($actor, 'auditor')
&& $request->is('management/*', 'api/v1/investment/admin/*', 'api/v2/investment/admin/*')) {
$access->audit($actor, 'auditor_administrative_write_denied', ['method' => $request->method(), 'path' => $request->path()]);
abort(403, 'Auditor só permite leitura administrativa, mesmo com outro papel ou permissão legada.');
}
$mandatoryMfa = $access->superuser($actor) || $access->has($actor, 'validator') || $access->has($actor, 'publisher');
$denied = $request->isMethod('DELETE') && $request->is('user/two-factor-authentication') && $mandatoryMfa;
$denied = $denied || ($access->superuser($actor) && $request->is('settings/profile') && $request->isMethod('PATCH')
&& $request->has('email') && $request->input('email') !== $actor->email);
if ($request->isMethod('DELETE') && $request->is('settings/profile')) {
$denied = $denied || $access->superuser($actor)
|| DB::table('portal_role_assignments')->where('user_id', $actor->id)->orWhere('approved_by', $actor->id)->exists()
|| DB::table('portal_profile_requests')->where('user_id', $actor->id)->orWhere('decided_by', $actor->id)->exists();
}
if ($denied) {
$access->audit($actor, 'privileged_identity_change_denied', ['method' => $request->method(), 'path' => $request->path()]);
abort(403, 'Esta alteração removeria MFA obrigatório, um titular ou histórico de autorização. Use revogação ou substituição controlada; não desative MFA para recuperar acesso.');
}
return $next($request);
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Middleware;
use App\Models\Opportunity;
use App\Services\PortalProfileAccess;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response;
class ProtectProfileOpportunity
{
public function handle(Request $request, Closure $next): Response
{
$id = null;
if (preg_match('#^(?:(?:management|api/v1)/opportunities|api/v1/investment/admin/opportunities|minhas-oportunidades|management/territories/opportunities)/(\d+)(?:/|$)#', $request->path(), $match)) {
$id = (int) $match[1];
} elseif ($request->is('management/opportunity-origin/preview', 'management/opportunity-origin/apply')) {
$id = filter_var($request->input('id'), FILTER_VALIDATE_INT) ?: null;
} elseif ($request->is('api/v2/investment/admin/zones/*/links')) {
$id = filter_var($request->input('opportunity_id'), FILTER_VALIDATE_INT) ?: null;
}
if ($request->user() && $id !== null && Schema::hasColumn('opportunities', 'owner_user_id')) {
$record = Opportunity::withTrashed()->find($id);
if ($record && $record->owner_user_id === null && ! $request->isMethod('GET')) {
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 403, 'O papel v1 não contorna os controlos através de um registo legado.');
}
if ($record && ($record->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades'))) {
abort_if($record->owner_user_id === null && str_starts_with($request->path(), 'minhas-oportunidades'), 403, 'Registo legado não convertido para a política v1.');
$access = app(PortalProfileAccess::class);
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') || $request->is('minhas-oportunidades/*/classification/review') ? 'view' : 'edit', $record);
abort_if($request->is('management/opportunity-origin/apply'), 403, 'O cadastro privado v1 não usa a classificação editorial dos exemplos legados.');
abort_if($request->isMethod('POST') && str_ends_with($request->path(), '/lifecycle') && ! str_contains($request->path(), '/resources/'), 403, 'Use o workflow com decisões segregadas; o perfil não concede exclusão.');
}
}
return $next($request);
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Middleware;
use App\Models\InvestmentSubmission;
use Closure;
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/** Tempo 19/10/2026: exception for simple participation only; formal operations retain verification. */
class VerifiedOrSimpleParticipation
{
public function handle(Request $request, Closure $next): Response
{
if ($request->user()->hasVerifiedEmail()) return $next($request);
if ($request->isMethod('GET') && $request->is('investidor/manifestacoes', 'api/v1/investment/submissions')) return $next($request);
$id = $request->route('id');
$show = $request->isMethod('GET') && $request->is('investidor/manifestacoes/'.$id, 'api/v1/investment/submissions/'.$id);
$message = $request->isMethod('POST') && $request->is('investidor/manifestacoes/'.$id.'/messages', 'api/v1/investment/submissions/'.$id.'/messages');
if ($id && ($show || $message)) {
$row = InvestmentSubmission::whereKey($id)->where('user_id', $request->user()->id)->firstOrFail();
if ($row->status === 'submitted' && ($row->payload['simple_participation'] ?? false) === true) return $next($request);
}
return app(EnsureEmailIsVerified::class)->handle($request, $next);
}
}
@@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts; use App\Services\ExistingBusinessDrafts;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -25,12 +26,13 @@ class StoreInterestRequestRequest extends FormRequest
return [ return [
'fullName' => ['required', 'string', 'min:3', 'max:150'], 'fullName' => ['required', 'string', 'min:3', 'max:150'],
'email' => ['required', 'email:rfc,dns', 'max:150'], 'email' => ['required', 'email:rfc', 'max:150'],
'phone' => ['nullable', 'string', 'max:30'], 'phone' => ['nullable', 'string', 'max:30'],
'investorType' => ['required', 'string', Rule::in([ 'investorType' => ['required', 'string', Rule::in([
'individual', 'empresa', 'fundo', 'entidade_publica', 'outro', 'individual', 'empresa', 'fundo', 'entidade_publica', 'outro',
])], ])],
'country' => ['required', 'string', 'max:100'], 'country' => ['required', 'string', 'max:100', ...($knownKey ? [] : [app(CountryCatalogue::class)->legacyCountryRule()])],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'sectorInterest' => ['required', 'string', 'max:150'], 'sectorInterest' => ['required', 'string', 'max:150'],
// A known receipt can replay after withdrawal; the service verifies the payload hash. // A known receipt can replay after withdrawal; the service verifies the payload hash.
'opportunityReference' => ['nullable', 'string', 'max:80', ...($knownKey ? [] : [ 'opportunityReference' => ['nullable', 'string', 'max:80', ...($knownKey ? [] : [
@@ -4,8 +4,12 @@ declare(strict_types=1);
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Models\LandAssistanceCase;
use App\Services\CountryCatalogue;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator; use Illuminate\Validation\Validator;
class StoreLandAssistanceCaseRequest extends FormRequest class StoreLandAssistanceCaseRequest extends FormRequest
@@ -28,17 +32,20 @@ class StoreLandAssistanceCaseRequest extends FormRequest
{ {
return [ return [
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'], 'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
'payload' => ['required', 'array:support_kind,request_description,project_reference,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'], 'context_revision' => ['nullable', 'integer', 'min:0'], 'context_reviewed' => ['nullable', 'boolean'],
'payload' => ['required', 'array:support_kind,request_description,project_reference,investor_path_case_id,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
'payload.support_kind' => ['nullable', 'in:investment,home,family_exploitation,recognition,regularization,delimitation,change_of_use,transfer,existing_process,conflict_guidance,other'], 'payload.support_kind' => ['nullable', 'in:investment,home,family_exploitation,recognition,regularization,delimitation,change_of_use,transfer,existing_process,conflict_guidance,other'],
'payload.request_description' => ['nullable', 'string', 'max:4000'], 'payload.request_description' => ['nullable', 'string', 'max:4000'],
'payload.project_reference' => ['nullable', 'string', 'max:160'], 'payload.project_reference' => ['nullable', 'string', 'max:160'],
'payload.investor_path_case_id' => ['nullable', 'uuid'],
'payload.applicant_category' => ['nullable', 'in:individual,entity,community,other'], 'payload.applicant_category' => ['nullable', 'in:individual,entity,community,other'],
'payload.full_name' => ['nullable', 'string', 'max:150'], 'payload.full_name' => ['nullable', 'string', 'max:150'],
'payload.contact_person' => ['nullable', 'string', 'max:200'], 'payload.contact_person' => ['nullable', 'string', 'max:200'],
'payload.email' => ['nullable', 'email:rfc', 'max:150'], 'payload.email' => ['nullable', 'email:rfc', 'max:150'],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.phone' => ['nullable', 'string', 'max:30'],
'payload.preferred_contact' => ['nullable', 'in:email,phone,any'], 'payload.preferred_contact' => ['nullable', 'in:email,phone,any'],
'payload.country' => ['nullable', 'string', 'max:100'], 'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.nationality' => ['nullable', 'string', 'max:120'], 'payload.nationality' => ['nullable', 'string', 'max:120'],
'payload.representative_name' => ['nullable', 'string', 'max:200'], 'payload.representative_name' => ['nullable', 'string', 'max:200'],
'payload.representative_role' => ['nullable', 'string', 'max:120'], 'payload.representative_role' => ['nullable', 'string', 'max:120'],
@@ -115,6 +122,23 @@ class StoreLandAssistanceCaseRequest extends FormRequest
{ {
$validator->after(function (Validator $validator): void { $validator->after(function (Validator $validator): void {
$payload = $this->input('payload', []); $payload = $this->input('payload', []);
$context = is_array($payload) ? ($payload['investor_path_case_id'] ?? null) : null;
$previous = $this->route('id') ? LandAssistanceCase::whereKey($this->route('id'))->where('user_id', $this->user()->id)->first() : null;
$bound = $previous?->payload['investor_path_case_id'] ?? null;
if ($context !== null) {
$case = is_string($context) && Str::isUuid($context)
? DB::table('desk_cases')->where('id', $context)->first() : null;
if ((! config('investor-path.enabled') && $bound !== $context) || ! $case || (int) $case->user_id !== $this->user()->id
|| ($case->closed_at && $bound !== $context) || ! $case->journey_id
|| ! DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists()) {
$validator->errors()->add('payload.investor_path_case_id', 'Use um dossier do seu percurso disponível para preparação. O acesso direto a Terra e DUAT continua disponível.');
}
}
if ($this->route('id')) {
if ($bound !== null && $context !== $bound) {
$validator->errors()->add('payload.investor_path_case_id', 'Preserve o vínculo deste pedido ao dossier original.');
}
}
if (is_array($payload) && is_array($payload['parcels'] ?? null)) { if (is_array($payload) && is_array($payload['parcels'] ?? null)) {
$geography = app(InvestmentGeography::class); $geography = app(InvestmentGeography::class);
$levels = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality']; $levels = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
@@ -132,7 +156,9 @@ class StoreLandAssistanceCaseRequest extends FormRequest
continue; continue;
} }
$record = $geography->publicReferences()->where('id', $id)->first(['id', 'parent_id', 'location_type']); $record = $geography->publicReferences()->where('id', $id)->first(['id', 'parent_id', 'location_type']);
if ($gap || ! $record || $record->location_type !== $expectedType || ($expectedType === 'province' ? $record->parent_id !== null : (string) $record->parent_id !== $parent)) { // The populated workbook hierarchy has country -> province. The public
// selector deliberately starts at province; it is not a root in storage.
if ($gap || ! $record || $record->location_type !== $expectedType || ($expectedType !== 'province' && (string) $record->parent_id !== $parent)) {
$validator->errors()->add("payload.parcels.$index.$field", 'A hierarquia territorial declarada é incoerente ou não está publicada.'); $validator->errors()->add("payload.parcels.$index.$field", 'A hierarquia territorial declarada é incoerente ou não está publicada.');
$gap = true; $gap = true;
} }
@@ -2,6 +2,7 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Services\CountryCatalogue;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator; use Illuminate\Validation\Validator;
@@ -62,6 +63,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$rules = [ $rules = [
// Anonymous clients must send an empty snapshot; `required` rejects // Anonymous clients must send an empty snapshot; `required` rejects
// an empty array before the privacy policy can enforce that shape. // an empty array before the privacy policy can enforce that shape.
'context' => ['nullable', 'uuid'],
'personal_snapshot' => ['present', 'array:'.implode(',', $personal)], 'personal_snapshot' => ['present', 'array:'.implode(',', $personal)],
'economic_snapshot' => ['required', 'array:'.implode(',', $economic)], 'economic_snapshot' => ['required', 'array:'.implode(',', $economic)],
'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'], 'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'],
@@ -169,6 +171,10 @@ class StoreSimulationFormDraftRequest extends FormRequest
'contact_province', 'contact_district', 'preferred_channel'] as $field) { 'contact_province', 'contact_district', 'preferred_channel'] as $field) {
$rules['personal_snapshot.'.$field] = ['nullable', 'string', 'max:3000']; $rules['personal_snapshot.'.$field] = ['nullable', 'string', 'max:3000'];
} }
foreach (['tax_residency_country', 'fiscal_residency_country', 'contact_country'] as $field) {
$rules['personal_snapshot.'.$field][] = app(CountryCatalogue::class)->legacyCountryRule();
}
$rules['economic_snapshot.funds_origin_countries.*'][] = app(CountryCatalogue::class)->legacyCountryRule();
return $rules; return $rules;
} }
@@ -27,6 +27,7 @@ class PublicBusinessOpportunityResource extends JsonResource
'province' => $this->resource->getAttribute('province'), 'province' => $this->resource->getAttribute('province'),
'district' => $this->resource->getAttribute('district'), 'district' => $this->resource->getAttribute('district'),
'locality' => $this->resource->getAttribute('locality'), 'locality' => $this->resource->getAttribute('locality'),
'multidimensional' => app(\App\Services\ExistingBusinessClassification::class)->publicRows($this->resource),
]; ];
} }
} }
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
// Adapted from investidor/app/Mail/ContactMessageReceivedMail.php.
class ContactMessageReceivedMail extends Mailable
{
use Queueable, SerializesModels;
/** @param array{name: string, email: string, phone?: string|null, subject: string, message: string, platform: string} $contactMessage */
public function __construct(public readonly array $contactMessage) {}
public function envelope(): Envelope
{
return new Envelope(
replyTo: [new Address($this->contactMessage['email'], $this->contactMessage['name'])],
subject: $this->contactMessage['subject'],
);
}
public function content(): Content
{
return new Content(
view: 'emails.contact-message-received',
text: 'emails.contact-message-received-text',
);
}
}
+3 -1
View File
@@ -22,7 +22,9 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
*/ */
class InvestmentZone extends DomainRecord class InvestmentZone extends DomainRecord
{ {
protected $casts = ['version_no' => 'integer', 'published_at' => 'datetime', 'aliases' => 'array', 'activities' => 'array', 'resources' => 'array', 'historical_territory' => 'array', 'area_components' => 'array', 'source_evidence' => 'array', 'area_value' => 'decimal:4', 'data_as_of' => 'date', 'sources_consulted_at' => 'date']; protected $hidden = ['editorial_draft', 'operational_details'];
protected $casts = ['operational_details' => 'array', 'operational_details' => 'array', 'version_no' => 'integer', 'published_at' => 'datetime', 'aliases' => 'array', 'activities' => 'array', 'resources' => 'array', 'historical_territory' => 'array', 'area_components' => 'array', 'source_evidence' => 'array', 'area_value' => 'decimal:4', 'data_as_of' => 'date', 'sources_consulted_at' => 'date'];
/** @return BelongsTo<GeoLocation, $this> */ /** @return BelongsTo<GeoLocation, $this> */
public function primaryTerritory(): BelongsTo public function primaryTerritory(): BelongsTo
+35 -1
View File
@@ -7,8 +7,12 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Schema;
/** /**
* @property int|null $owner_user_id
* @property string|null $organization_id
* @property array<string,mixed>|null $workflow_context
* @property string|null $primary_territory_id * @property string|null $primary_territory_id
* @property int $territory_version * @property int $territory_version
* @property int $management_version * @property int $management_version
@@ -23,7 +27,18 @@ class Opportunity extends Model
{ {
use SoftDeletes; use SoftDeletes;
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once']; protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context'];
protected $appends = ['maturity_catalogue_version'];
public function getMaturityCatalogueVersionAttribute(): ?string
{
// Only published metadata is public; never expose the current private draft.
$version = data_get($this->workflow_context, 'publication.maturity.catalogue_version');
return in_array($version, [\App\Services\OpportunityMaturity::VERSION, \App\Services\OpportunityMaturity::LEGACY], true)
? $version : null;
}
protected $fillable = [ protected $fillable = [
'sector_id', 'reference', 'title', 'slug', 'summary', 'description', 'sector_id', 'reference', 'title', 'slug', 'summary', 'description',
@@ -37,6 +52,7 @@ class Opportunity extends Model
]; ];
protected $casts = [ protected $casts = [
'workflow_context' => 'array',
'is_featured' => 'boolean', 'is_featured' => 'boolean',
'territory_version' => 'integer', 'territory_version' => 'integer',
'published_at' => 'datetime', 'published_at' => 'datetime',
@@ -44,6 +60,20 @@ class Opportunity extends Model
'estimated_investment_amount' => 'decimal:2', 'estimated_investment_amount' => 'decimal:2',
]; ];
/** @return array{scope:string,label:string,public_catalog:bool} */
public function publicationPresentation(): array
{
$public = $this->exists && self::query()->whereKey($this->id)->published()->exists();
$visible = ! $this->trashed() && $this->status === 'published' && $this->published_at !== null && $this->published_at->lte(now());
$scope = $public ? 'public' : ($visible && $this->owner_user_id !== null ? 'restricted' : 'unpublished');
return ['scope' => $scope, 'public_catalog' => $public, 'label' => match ($scope) {
'public' => 'Publicada no catálogo público',
'restricted' => 'Disponibilizada com acesso restrito — perfis e organização autorizados',
default => 'Sem versão disponibilizada; aprovação interna é uma etapa distinta',
}];
}
/** @return BelongsTo<Sector, $this> */ /** @return BelongsTo<Sector, $this> */
public function sector(): BelongsTo public function sector(): BelongsTo
{ {
@@ -67,6 +97,10 @@ class Opportunity extends Model
*/ */
public function scopePublished(Builder $query): Builder public function scopePublished(Builder $query): Builder
{ {
if (Schema::hasColumn('opportunities', 'workflow_context')) {
$query->where(fn ($q) => $q->whereNull('owner_user_id')->orWhere('workflow_context->publication->visibility', 'public'));
}
return $query->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now()) return $query->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())
->whereRaw("COALESCE((SELECT origin.after_data->>'classification' FROM audit_events origin WHERE origin.source_system='opportunity-origin-review' AND origin.after_data->>'opportunity_id'=opportunities.id::text ORDER BY origin.occurred_at DESC,origin.id DESC LIMIT 1),'undetermined') <> 'example'"); ->whereRaw("COALESCE((SELECT origin.after_data->>'classification' FROM audit_events origin WHERE origin.source_system='opportunity-origin-review' AND origin.after_data->>'opportunity_id'=opportunities.id::text ORDER BY origin.occurred_at DESC,origin.id DESC LIMIT 1),'undetermined') <> 'example'");
} }
+16
View File
@@ -20,6 +20,22 @@ class Sector extends Model
'published_at' => 'datetime', 'published_at' => 'datetime',
]; ];
/** Presentation only: historical masters and foreign keys remain untouched. */
public function scopeChoices($query)
{
return $query->where('is_active', true)->where('slug', '!=', 'energia');
}
public function scopeCatalog($query)
{
return $query->choices()->whereNotNull('published_at')->where('slug', '!=', 'fintech');
}
public function getNameAttribute($value)
{
return ($this->attributes['slug'] ?? null) === 'fintech' ? 'Mercado Financeiro — Fintech' : $value;
}
/** @return HasMany<Opportunity, $this> */ /** @return HasMany<Opportunity, $this> */
public function opportunities(): HasMany public function opportunities(): HasMany
{ {
+1
View File
@@ -19,6 +19,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
* @property string $name * @property string $name
* @property string $email * @property string $email
* @property Carbon|null $email_verified_at * @property Carbon|null $email_verified_at
* @property int $portal_access_revision
* @property string $password * @property string $password
* @property string|null $two_factor_secret * @property string|null $two_factor_secret
* @property string|null $two_factor_recovery_codes * @property string|null $two_factor_recovery_codes
+101 -10
View File
@@ -4,6 +4,9 @@ namespace App\Policies;
use App\Models\ExistingBusiness; use App\Models\ExistingBusiness;
use App\Models\User; use App\Models\User;
use App\Services\PortalProfileAccess;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class ExistingBusinessPolicy class ExistingBusinessPolicy
{ {
@@ -24,9 +27,14 @@ class ExistingBusinessPolicy
return true; return true;
} }
$reviewedStates = ['rejected', 'published', 'suspended', 'cancelled', 'archived'];
if (app(PortalProfileAccess::class)->available()) {
$reviewedStates[] = 'approved';
}
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& in_array($business->status, ['rejected', 'published', 'suspended', 'cancelled', 'archived'], true) && in_array($business->status, $reviewedStates, true)
&& $this->reviewQueue($user); && $this->designatedAny($user, $business);
} }
public function delete(User $user, ExistingBusiness $business): bool public function delete(User $user, ExistingBusiness $business): bool
@@ -43,41 +51,100 @@ class ExistingBusinessPolicy
{ {
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& in_array($business->status, ['triage', 'in_review', 'needs_information'], true) && in_array($business->status, ['triage', 'in_review', 'needs_information'], true)
&& $this->designated($user, 'reviewers'); && $this->designated($user, 'reviewers', $business);
} }
public function triage(User $user, ExistingBusiness $business): bool public function triage(User $user, ExistingBusiness $business): bool
{ {
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& in_array($business->status, ['submitted', 'triage'], true) && in_array($business->status, ['submitted', 'triage'], true)
&& $this->designated($user, 'triagers'); && $this->designated($user, 'triagers', $business);
} }
public function approveLevelOne(User $user, ExistingBusiness $business): bool public function approveLevelOne(User $user, ExistingBusiness $business): bool
{ {
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& $business->status === 'approval_l1' && $business->status === 'approval_l1'
&& $this->designated($user, 'approvers_l1'); && $this->designated($user, 'approvers_l1', $business);
} }
public function approveLevelTwo(User $user, ExistingBusiness $business): bool public function approveLevelTwo(User $user, ExistingBusiness $business): bool
{ {
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& $business->status === 'approval_l2' && $business->status === 'approval_l2'
&& $this->designated($user, 'approvers_l2'); && $this->designated($user, 'approvers_l2', $business);
} }
public function publish(User $user, ExistingBusiness $business): bool public function publish(User $user, ExistingBusiness $business): bool
{ {
return ! $business->trashed() && $business->owner_user_id !== $user->id return ! $business->trashed() && $business->owner_user_id !== $user->id
&& $business->status === 'approved' && $business->status === 'approved'
&& $this->designated($user, 'publishers'); && $this->designated($user, 'publishers', $business);
} }
public function reviewQueue(User $user): bool public function reviewQueue(User $user): bool
{
return $this->designatedAny($user);
}
/** Filter before projecting or decrypting private fields in the review queue. */
public function scopeReviewQueue(Builder $query, User $user): void
{
if (app(PortalProfileAccess::class)->available()) {
$query->whereIn('modality',array_keys(\App\Services\ExistingBusinessProfileCategory::MAP));
$ids = (clone $query)->get()->filter(fn (ExistingBusiness $business) => $this->view($user, $business))->modelKeys();
$query->whereKey($ids);
}
}
/** Supplement-only authority never changes the normal content/workflow abilities. */
public function prepareClassification(User $user, ExistingBusiness $business): bool
{
return $this->owns($user, $business) && ! app(PortalProfileAccess::class)->has($user, 'auditor')
&& in_array($business->status, ['draft', 'needs_information', 'published'], true);
}
public function reviewClassification(User $user, ExistingBusiness $business): bool
{
return ! $business->trashed() && $business->owner_user_id !== $user->id
&& ! app(PortalProfileAccess::class)->has($user, 'auditor')
&& in_array($business->status, ['triage', 'in_review', 'needs_information', 'published'], true)
&& $this->designated($user, 'reviewers', $business);
}
/** Current responsibility check without requiring a reviewer's live browser session on public reads. */
public function classificationReviewerScope(User $user, ExistingBusiness $business, string $dimension): bool
{
if ($business->trashed() || ! $user->hasVerifiedEmail() || (int) $business->owner_user_id === (int) $user->id) {
return false;
}
$access = app(PortalProfileAccess::class);
if ($access->has($user, 'auditor')) { return false; }
if (! $access->available()) {
return $access->legacyWriteAllowed($user) && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
}
if ($business->modality !== 'company_sale') { return false; }
$responsibility = $dimension === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
return collect($access->grants($user, 'validator'))->contains(fn ($g) => $g->organization_id === null
&& in_array('business_sale', json_decode($g->opportunity_types, true), true)
&& in_array($responsibility, json_decode($g->responsibilities, true), true));
}
public function discloseClassification(User $user, ExistingBusiness $business): bool
{
if ($business->trashed() || $business->status !== 'published' || (int) $business->owner_user_id === (int) $user->id
|| app(PortalProfileAccess::class)->has($user, 'auditor') || ! $this->designated($user, 'publishers', $business)) {
return false;
}
return ! DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
->whereIn('to_status', ['approval_l2', 'approved'])->where('actor_id', $user->id)->exists();
}
private function designatedAny(User $user, ?ExistingBusiness $business = null): bool
{ {
foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) { foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) {
if ($this->designated($user, $designation)) { if ($this->designated($user, $designation, $business)) {
return true; return true;
} }
} }
@@ -85,9 +152,33 @@ class ExistingBusinessPolicy
return false; return false;
} }
private function designated(User $user, string $designation): bool private function designated(User $user, string $designation, ?ExistingBusiness $business = null): bool
{ {
return $user->hasVerifiedEmail() && $user->can('manage-portal') $access = app(PortalProfileAccess::class);
if ($access->available()) {
$category=$business ? \App\Services\ExistingBusinessProfileCategory::category($business) : null;
if (($business !== null && $category === null) || ! $access->mfa($user) || $access->has($user,'auditor')) {
return false;
}
$role = $designation === 'publishers' ? 'publisher' : 'validator';
if (! $access->operational($user, $role === 'publisher' ? 'publish' : 'validate')) {
return false;
}
foreach ($access->grants($user, $role) as $grant) {
$organizationMatches = $grant->organization_id === null
|| ($business !== null && $grant->organization_id === $business->organization_id);
if ($organizationMatches
&& ($category !== null ? in_array($category,json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR),true) : array_intersect(array_values(\App\Services\ExistingBusinessProfileCategory::MAP),json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR)) !== [])) {
return true;
}
}
return false;
}
// Legacy-only environments retain their explicit lists; a revoked/scoped v1
// assignment must never regain wider permissions through that allowlist.
return $user->hasVerifiedEmail() && $access->legacyWriteAllowed($user)
&& (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
&& in_array(strtolower($user->email), config('existing-business.'.$designation, []), true); && in_array(strtolower($user->email), config('existing-business.'.$designation, []), true);
} }
+29
View File
@@ -9,16 +9,20 @@ use App\Services\Malware\ClamDScanner;
use App\Services\Malware\MalwareScanner; use App\Services\Malware\MalwareScanner;
use App\Services\Mne\BusinessRepository; use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibleBusinessRepository; use App\Services\Mne\CompatibleBusinessRepository;
use App\Services\PortalProfileAccess;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Auth\Events\Login;
use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
@@ -39,6 +43,31 @@ class AppServiceProvider extends ServiceProvider
{ {
$this->configureDefaults(); $this->configureDefaults();
// Fortify calls this response AFTER invalidating/regenerating the server session.
// Clear the client's encryption key too, so Back must reauthorize private pages.
$this->app->bind(\Laravel\Fortify\Contracts\LogoutResponse::class, function () {
return new class extends \Laravel\Fortify\Http\Responses\LogoutResponse
{
public function toResponse($request)
{
\Inertia\Inertia::clearHistory();
return parent::toResponse($request);
}
};
});
Event::listen(ValidTwoFactorAuthenticationCodeProvided::class, function ($event): void {
// The authenticated installers also operate before the optional profile schema exists.
// Record a completed Fortify challenge, never enrollment or a password-only login.
session()->put(['portal.mfa_actor' => $event->user->id, 'portal.mfa_at' => time()]);
});
Event::listen(Login::class, function ($event): void {
if (app(PortalProfileAccess::class)->governanceAvailable()) {
session()->put('portal.access_revision', (int) DB::table('users')->where('id', $event->user->id)->value('portal_access_revision'));
}
});
Gate::define('manage-portal', fn (User $user) => $user->hasVerifiedEmail() Gate::define('manage-portal', fn (User $user) => $user->hasVerifiedEmail()
&& in_array(strtolower($user->email), config('portal.managers', []), true)); && in_array(strtolower($user->email), config('portal.managers', []), true));
+4 -2
View File
@@ -132,9 +132,11 @@ class InvestorGuidance
$actions = ['opportunities' => '/oportunidades', 'locations' => '/oportunidades?view=map', 'partners' => '/parcerias', $actions = ['opportunities' => '/oportunidades', 'locations' => '/oportunidades?view=map', 'partners' => '/parcerias',
'documents' => '/documentos', 'plan' => $case->submission_id && (int) $case->user_id === $actor->id ? '/investidor/manifestacoes/'.$case->submission_id : '/balcao-virtual/dossiers/'.$id, 'documents' => '/documentos', 'plan' => $case->submission_id && (int) $case->user_id === $actor->id ? '/investidor/manifestacoes/'.$case->submission_id : '/balcao-virtual/dossiers/'.$id,
'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id]; 'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id];
// The simulator recovers its current owner-scoped draft; do not pass private payload in URLs. // Pin the linked owner-scoped draft instead of opening another project's current draft.
// The receiving API still enforces ownership; no private payload is carried in the URL.
if ($case->simulation_id && $context['financial_draft'] !== null) { if ($case->simulation_id && $context['financial_draft'] !== null) {
$actions['plan'] = '/simulador-fiscal'; $actions['simulator'] = '/simulador-fiscal?draft='.rawurlencode($case->simulation_id);
$actions['plan'] = $actions['simulator'];
} }
$phases = $this->rules->evaluate($context['facts'], $context['evidence']); $phases = $this->rules->evaluate($context['facts'], $context['evidence']);
foreach ($phases as &$phase) { foreach ($phases as &$phase) {
+19 -7
View File
@@ -3,6 +3,7 @@
namespace App\Services; namespace App\Services;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
final class BusinessFormSchema final class BusinessFormSchema
@@ -13,7 +14,8 @@ final class BusinessFormSchema
return [ return [
'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']], 'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']],
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200], 'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição (código ISO de duas letras)', 'en' => 'Country of origin or incorporation (two-letter ISO code)', 'type' => 'text', 'max' => 2], 'country' => ['step' => 1, 'pt' => 'País de origem ou constituição', 'en' => 'Country of origin or incorporation', 'type' => 'country', 'max' => 100],
'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem declarado desta solicitação (opcional)', 'en' => 'Declared country of origin of this request (optional)', 'type' => 'country', 'max' => 2],
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50], 'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50],
'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200], 'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200],
'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254], 'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
@@ -77,7 +79,7 @@ final class BusinessFormSchema
]; ];
} }
/** @return array<string, array<int,string>> */ /** @return array<string, list<string|\Closure|In>> */
public static function rules(): array public static function rules(): array
{ {
$rules = []; $rules = [];
@@ -89,7 +91,8 @@ final class BusinessFormSchema
} }
$rules['payload.contact_email'][] = 'nullable'; $rules['payload.contact_email'][] = 'nullable';
$rules['payload.contact_email'][] = 'email'; $rules['payload.contact_email'][] = 'email';
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/'; $rules['payload.country'][] = app(CountryCatalogue::class)->legacyCountryRule();
$rules['payload.declared_origin_country_code'][] = app(CountryCatalogue::class)->rule();
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/'; $rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/'; $rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/'; $rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
@@ -97,8 +100,11 @@ final class BusinessFormSchema
$rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/'; $rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.source_date'][] = 'date_format:Y-m-d'; $rules['payload.source_date'][] = 'date_format:Y-m-d';
$rules['payload.official_source_url'][] = 'url'; $rules['payload.official_source_url'][] = 'url';
$rules['payload.equity_percentage'][] = 'numeric'; // The field limit is a text length, not an 8% ceiling.
$rules['payload.equity_percentage'][] = 'between:0,100'; $rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
function ($attribute, $value, $fail) {
if (strlen((string) $value) > 8) $fail('Indique a percentagem com até 8 caracteres.');
}];
foreach (['valid_until', 'mandate_valid_until'] as $date) { foreach (['valid_until', 'mandate_valid_until'] as $date) {
$rules['payload.'.$date][] = 'date_format:Y-m-d'; $rules['payload.'.$date][] = 'date_format:Y-m-d';
} }
@@ -113,8 +119,12 @@ final class BusinessFormSchema
/** @param array<string,mixed> $payload */ /** @param array<string,mixed> $payload */
public static function validateSubmission(array $payload, ?int $sectorId, string $modality): void public static function validateSubmission(array $payload, ?int $sectorId, string $modality): void
{ {
if (($payload['opportunity_type'] ?? null) !== $modality) { $expectedType = ExistingBusinessProfileCategory::formType($modality);
throw ValidationException::withMessages(['opportunity_type' => 'O tipo da oportunidade não corresponde à classificação guardada.']); if ($expectedType === null) {
throw ValidationException::withMessages(['opportunity_type' => 'Esta modalidade pode ser guardada em preparação. O formulário de submissão correspondente ainda não está definido; a modalidade não será alterada automaticamente.']);
}
if (($payload['opportunity_type'] ?? null) !== $expectedType) {
throw ValidationException::withMessages(['opportunity_type' => 'O tipo de oportunidade não corresponde à modalidade guardada. Recupere o formulário; a modalidade original foi preservada.']);
} }
$rules = []; $rules = [];
@@ -122,6 +132,8 @@ final class BusinessFormSchema
$rules[$field] = ['required']; $rules[$field] = ['required'];
} }
$rules['sector_id'] = ['required']; $rules['sector_id'] = ['required'];
$rules['country'] = ['required', 'string', app(CountryCatalogue::class)->rule()];
$rules['declared_origin_country_code'] = ['nullable', 'string', app(CountryCatalogue::class)->rule()];
$rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email']; $rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email'];
$rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/']; $rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/'];
$rules['legitimacy_declaration'] = ['required', 'in:yes']; $rules['legitimacy_declaration'] = ['required', 'in:yes'];
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Services;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
/** Shared ISO identifiers; independent of administrative territories and IP data. */
final class CountryCatalogue
{
/** @return list<array{code: string, name: string, name_en: string}> */
public function all(): array
{
$countries = [];
$lines = file(resource_path('data/iso3166.tab'), FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new \RuntimeException('Catálogo ISO local indisponível.');
}
foreach ($lines as $line) {
if (str_starts_with($line, '#')) {
continue;
}
[$code, $english] = explode("\t", $line, 2);
$name = class_exists(\Locale::class) ? \Locale::getDisplayRegion('und_'.$code, 'pt') : $english;
$countries[] = ['code' => $code, 'name' => is_string($name) && $name !== '' ? $name : $english, 'name_en' => $english];
}
usort($countries, fn ($a, $b) => strnatcasecmp($a['name'], $b['name']));
return $countries;
}
public function rule(): In
{
return Rule::in(array_column($this->all(), 'code'));
}
/** Accept existing free-text integrations; validate ISO-shaped values without rewriting them. */
public function legacyCountryRule(): \Closure
{
$codes = array_column($this->all(), 'code');
return static function (string $attribute, mixed $value, \Closure $fail) use ($codes): void {
if (is_string($value) && preg_match('/^[a-zA-Z]{2}$/D', $value) && ! in_array($value, $codes, true)) {
$fail('Seleccione um código ISO de país válido.');
}
};
}
/**
* Exact catalogue labels for reading legacy free-text country values.
* Does not infer request origin, alter stored values or classify unmatched text.
* Only labels belonging to one ISO country are included.
*
* @return list<string> Case-folded country code and catalogue labels.
*/
public function filterValues(string $code): array
{
$countries = $this->all();
$owners = [];
$selected = [];
foreach ($countries as $country) {
foreach (array_unique([$country['code'], $country['name'], $country['name_en']]) as $label) {
$key = mb_strtolower(trim($label), 'UTF-8');
$owners[$key][$country['code']] = true;
if ($country['code'] === $code) {
$selected[$key] = true;
}
}
}
return array_values(array_filter(array_keys($selected), fn ($key) => count($owners[$key]) === 1));
}
/** @return array{code:string|null,name:string} */
public function describe(?string $code): array
{
$names = array_column($this->all(), 'name', 'code');
return isset($names[$code ?? '']) ? ['code' => $code, 'name' => $names[$code]] : ['code' => null, 'name' => 'Não informado'];
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
final class DeclaredOriginStatistics
{
/** @return array<string, list<array{code: string|null, name: string, count: int}>> */
public function forManager(User $actor, ?string $origin = null): array
{
abort_unless(app(ScopedPortalAdministration::class)->interestOperator($actor), 403);
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
$groups = [];
$interests=DB::table('interest_requests')->whereNull('deleted_at');
app(ScopedPortalAdministration::class)->interestQuery($interests,$actor);
foreach ($interests->select('metadata')->cursor() as $row) {
$metadata = json_decode($row->metadata ?? '{}', true);
$code = $metadata['declared_origin_country_code'] ?? null;
$key = is_string($code) && isset($names[$code]) ? $code : '';
$groups[$key] = ($groups[$key] ?? 0) + 1;
}
$desk = [];
if ($actor->can('manage-portal') && Schema::hasTable('desk_requests')) {
foreach (DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled'])->select('payload')->cursor() as $row) {
$code = app(VirtualDesk::class)->decode($row->payload)['declared_origin_country_code'] ?? null;
$key = is_string($code) && isset($names[$code]) ? $code : '';
$desk[$key] = ($desk[$key] ?? 0) + 1;
}
}
$businesses = [];
if ($actor->can('manage-portal') && Schema::hasTable('existing_businesses')) {
foreach (app(BusinessRepository::class)->query()->whereNotIn('status', ['draft', 'cancelled'])->cursor() as $business) {
$code = $business->payload['declared_origin_country_code'] ?? null;
$key = is_string($code) && isset($names[$code]) ? $code : '';
$businesses[$key] = ($businesses[$key] ?? 0) + 1;
}
}
// Distinct request collections; summing them could count the same investor twice.
if ($origin !== null && $origin !== '') {
$key = $origin === 'unknown' ? '' : $origin;
$groups = array_intersect_key($groups, [$key => true]);
$desk = array_intersect_key($desk, [$key => true]);
$businesses = array_intersect_key($businesses, [$key => true]);
}
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names), 'businesses' => $this->format($businesses, $names)];
}
/** @param array<string, int> $counts
* @param array<string, string> $names
* @return list<array{code: string|null, name: string, count: int}> */
private function format(array $counts, array $names): array
{
ksort($counts);
return array_map(fn (string $code, int $count) => ['code' => $code ?: null, 'name' => $names[$code] ?? 'Não informado', 'count' => $count], array_keys($counts), array_values($counts));
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
class DocumentManagementAccess
{
public function full(User $actor): bool
{
return Gate::forUser($actor)->allows('manage-portal');
}
public function limited(User $actor): bool
{
// Explicit Tempo authorisation; registration itself never grants access.
return $actor->hasVerifiedEmail()
&& in_array(strtolower(trim($actor->email)), config('portal.document_managers', []), true)
&& app(PortalProfileAccess::class)->mfa($actor);
}
/** Restore the approved editorial operation without a global management grant. */
public function editorial(User $actor): bool
{
return config('portal.homologation_only', false)
&& in_array(strtolower(trim($actor->email)), config('homologation_editorial.accounts', []), true)
&& app(PortalProfileAccess::class)->superuser($actor)
&& ! app(PortalProfileAccess::class)->has($actor, 'auditor')
&& app(PortalProfileAccess::class)->mfa($actor);
}
public function editorialResources(User $actor): Builder
{
abort_unless($this->editorial($actor), 403);
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
->where(function ($query) use ($actor) {
$query->where(function ($own) use ($actor) {
$own->where('r.created_by', $actor->id)->where('d.uploaded_by', $actor->id)
->where('d.source_system', 'portal-services');
});
foreach (config('homologation_editorial.resources', []) as $item) {
$query->orWhere(function ($listed) use ($item) {
$listed->where('r.id', $item['id'])->where('d.sha256', $item['sha256'])
->where('d.external_id', $item['external_id']);
});
}
});
}
public function assertEditableResource(User $actor, int $id): void
{
abort_unless($this->full($actor) || $this->editorialResources($actor)->where('r.id', $id)->exists(), 403);
}
public function documents(User $actor): Builder
{
$query = DB::table('documents')->whereNull('deleted_at');
if (! $this->full($actor)) {
$editorial = $this->editorial($actor);
abort_unless($this->limited($actor) || $editorial, 403);
$query->where(function ($scope) use ($actor, $editorial) {
$scope->where(fn ($own) => $own->where('uploaded_by', $actor->id)->where('source_system', 'portal-services'));
if ($editorial) {
$scope->orWhereIn('id', $this->editorialResources($actor)->select('d.id'));
}
});
}
return $query;
}
public function audit(User $actor, string $action, array $data): void
{
DB::table('audit_events')->insert([
'source_system' => 'document-access-v1', 'entity_type' => 'authorization',
'actor_user_id' => $actor->id, 'action' => $action,
'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
'after_data' => json_encode($data, JSON_THROW_ON_ERROR),
]);
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
namespace App\Services;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/** Shared read contract. It deliberately has no dependency on the installation controller/service. */
class EconomicReferenceCatalog
{
public const LOT = 'lot-01';
public const SOURCE = 'economic-reference-lot-01';
public const MANIFEST_SHA256 = 'ba1bb3406fd55e39c19fd2a2755f3dfc2a1160b67eee8b3b6e12cd43f4223b04';
public function manifest(): array
{
$file = database_path('data/economic-references-lot-01.json');
abort_unless(is_file($file) && hash_equals(self::MANIFEST_SHA256, hash_file('sha256', $file)), 422, 'Manifesto económico ausente ou diferente da revisão delimitada.');
$manifest = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
abort_unless(($manifest['lot'] ?? '') === self::LOT && count($manifest['activities'] ?? []) === 5
&& count($manifest['chains'] ?? []) === 5 && count($manifest['links'] ?? []) === 4, 422, 'Lote económico fora do âmbito.');
return $manifest;
}
public function schemaAvailable(): bool
{
return Schema::hasColumn('economic_activities', 'metadata');
}
public function publicationState(): string
{
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->whereIn('action', ['publish', 'withdraw'])
->orderByDesc('occurred_at')->orderByDesc('id')->first(['action']);
return $event?->action === 'publish' ? 'published' : ($event ? 'withdrawn' : 'private');
}
public function available(): bool
{
if (! $this->schemaAvailable() || $this->publicationState() !== 'published') { return false; }
return DB::table('reference_catalog_versions')->where('id', $this->manifest()['catalog']['id'])->where('status', 'published')->exists();
}
public function constrain(Builder $query, string $kind): Builder
{
$manifest = $this->manifest();
if ($kind === 'activity') $query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
if (in_array($kind, ['activity', 'chain'], true) && ! $this->available()) {
$query->whereNotIn('id', array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'));
}
return $query;
}
/** A withdrawn published reference can be retained verbatim, never introduced as a new choice. */
public function historicalTarget(string $kind, string $id): bool
{
if ($kind === 'activity' && $id === SectorOrganization::LEGACY_ACTIVITY_ID) return DB::table('economic_activities')->where('id', $id)->where('sector_id', 2)->where('status', 'published')->exists();
if (! in_array($kind, ['activity', 'chain'], true) || ! $this->schemaAvailable()) { return false; }
$manifest = $this->manifest();
if (! in_array($id, array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'), true)) { return false; }
if (! DB::table('audit_events')->where('source_system', self::SOURCE)->where('action', 'publish')->exists()) { return false; }
return $kind === 'activity'
? DB::table('economic_activities')->where('id', $id)->where('status', 'published')->exists()
: DB::table('value_chains')->where('id', $id)->whereNull('deleted_at')->exists();
}
public function activities(array $historicalIds = []): Collection
{
$rows = DB::table('economic_activities')->where('status', 'published')->get();
$allowed = $this->constrain(DB::table('economic_activities')->where('status', 'published'), 'activity')->pluck('id')->all();
// A used published UUID may still be shown after withdrawal, together with its exact ancestors.
$byId = $rows->keyBy('id');
foreach ($historicalIds as $id) {
$seen = [];
while (isset($byId[$id]) && ! isset($seen[$id])) {
$allowed[] = $id; $seen[$id] = true; $id = $byId[$id]->parent_id;
}
}
$available = $this->available();
return $rows->filter(fn ($r) => in_array($r->id, $allowed, true))->map(function ($row) use ($byId, $available) {
$meta = property_exists($row, 'metadata') ? json_decode($row->metadata, true) : [];
$path = []; $current = $row; $seen = [];
while ($current && ! isset($seen[$current->id])) {
$seen[$current->id] = true;
array_unshift($path, ['id' => $current->id, 'code' => $current->code, 'label' => $current->label_pt_mz]);
$current = $current->parent_id ? ($byId[$current->parent_id] ?? null) : null;
}
$isLot = ($meta['lot'] ?? '') === self::LOT;
return (object) ['id' => $row->id, 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
'label_pt_mz' => $row->label_pt_mz, 'catalog_version_id' => $row->catalog_version_id, 'code' => $row->code,
'level' => $meta['level'] ?? null, 'path' => $path, 'display_label' => implode(' → ', array_column($path, 'code')).' — '.$row->label_pt_mz,
'source_version' => $meta['source_version'] ?? null, 'edition' => $meta['edition'] ?? null,
'historical_only' => $isLot && ! $available];
})->values();
}
public function validHierarchy(int $sectorId, ?string $subsectorId, ?string $activityId, bool $historical = false): bool
{
if (! $subsectorId || ! $activityId) { return false; }
$sector = DB::table('sectors')->where('id', $sectorId)->whereNull('deleted_at')->where('is_active', true)->exists();
$subsector = DB::table('economic_activities')->where('id', $subsectorId)->where('status', 'published')->first();
$activity = DB::table('economic_activities')->where('id', $activityId)->where('status', 'published')->first();
if (! $sector || ! $subsector || ! $activity || $activity->catalog_version_id !== $subsector->catalog_version_id) { return false; }
$manifest = $this->manifest();
if ($activity->catalog_version_id !== $manifest['catalog']['id']) {
$root = $subsector->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
return $root && (int) $root->sector_id === $sectorId && $activity->parent_id === $subsector->id;
}
if ((! $this->available() && ! $historical) || $sectorId !== (int) $manifest['existing']['sector']['id']
|| $subsector->code !== '01' || $activity->code !== '01120') { return false; }
$current = $activity; $codes = []; $seen = [];
while ($current && ! isset($seen[$current->id])) {
$seen[$current->id] = true; array_unshift($codes, $current->code);
$current = $current->parent_id ? DB::table('economic_activities')->where('id', $current->parent_id)->where('catalog_version_id', $activity->catalog_version_id)->where('status', 'published')->first() : null;
}
return $codes === ['A', '01', '011', '0112', '01120'] && (int) $subsector->sector_id === $sectorId && (int) $activity->sector_id === $sectorId;
}
}
@@ -0,0 +1,291 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Bounded authenticated extension. No generic seeding, arbitrary path or caller-supplied actor. */
class EconomicReferenceInstallation
{
public const MIGRATION = '2026_10_16_120000_extend_economic_reference_hierarchy';
public const OPERATIONS = ['schema', 'import', 'publish', 'withdraw'];
public function files(): array
{
return ['app/Services/EconomicReferenceCatalog.php', 'app/Services/EconomicReferenceInstallation.php',
'app/Http/Controllers/EconomicReferenceController.php', 'app/Services/OpportunityCanonicalContract.php',
'app/Services/OpportunityClassification.php', 'app/Services/ExistingBusinessClassification.php',
'app/Http/Controllers/Api/V1/ReferenceCatalogController.php', 'resources/js/components/opportunity-canonical-fields.tsx',
'resources/js/components/opportunity-classification.tsx', 'resources/js/pages/management/economic-references.tsx',
'routes/web.php', 'database/migrations/'.self::MIGRATION.'.php', 'database/data/economic-references-lot-01.json'];
}
public function fingerprint(): string
{
return hash('sha256', json_encode(array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files()), JSON_THROW_ON_ERROR));
}
private function directory(): string { return storage_path('app/private/investmoz-v2/economic-references/lot-01'); }
private function target(): array
{
return (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
}
private function qa(array $target): bool
{
return app()->environment('testing') && str_ends_with($target['database'], '_test') && (int) $target['port'] === 55441
&& config('database.connections.pgsql.host') === '127.0.0.1' && ! config('database.connections.pgsql.url');
}
private function authorize(User $actor, bool $write = false, string $operation = ''): void
{
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Acesso reservado à gestão autorizada.');
if (! $write) { return; }
$access = app(PortalProfileAccess::class);
abort_if($access->has($actor, 'auditor'), 403, 'A restrição de Auditor permite apenas consulta.');
abort_unless($access->mfa($actor), 403, 'Conclua MFA nesta sessão para executar esta ação.');
if ($operation === 'schema') { app(PortalProfileInstallation::class)->authorize($actor, true); }
abort_unless(! app()->environment('testing') || $this->qa($this->target()), 403, 'Alvo QA isolado inválido.');
}
private function evidence(array $target, string $code, string $operation): array
{
if ($this->qa($target)) { return ['ready' => true, 'mode' => 'isolated_QA', 'date' => null]; }
if (app()->environment('testing')) { return ['ready' => false, 'mode' => 'invalid_QA', 'date' => null]; }
$path = $this->directory().'/readiness.json';
$proof = is_file($path) ? json_decode(file_get_contents($path), true) : [];
$date = strtotime($proof['verified_at'] ?? '');
$permission = $proof['active_authorization'] ?? [];
$ready = ! config('database.connections.pgsql.url') && in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
&& $target['database'] === 'investemoz' && (int) $target['port'] === 5432
&& ($proof['target']['database'] ?? '') === $target['database'] && (int) ($proof['target']['port'] ?? 0) === (int) $target['port']
&& ($proof['code_hash'] ?? '') === $code && ($proof['manifest_sha256'] ?? '') === EconomicReferenceCatalog::MANIFEST_SHA256
&& $date !== false && $date <= time() && $date >= time() - 86400
&& ($proof['restore_verified'] ?? false) && ($proof['files_verified'] ?? false)
&& ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
&& str_ends_with($proof['restore_target']['database'] ?? '', '_test') && (int) ($proof['restore_target']['port'] ?? 0) === 55441
&& is_file($proof['dump_path'] ?? '') && is_file($proof['files_path'] ?? '')
&& hash_equals($proof['dump_sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
&& hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))
&& ($permission['decision_record'] ?? '') !== '' && ($permission['code_hash'] ?? '') === $code
&& ($permission['manifest_sha256'] ?? '') === EconomicReferenceCatalog::MANIFEST_SHA256
&& in_array($operation, $permission['operations'] ?? [], true);
return ['ready' => $ready, 'mode' => 'active_requires_own_authorization_and_fresh_proof', 'date' => $proof['verified_at'] ?? null,
'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
}
/** No source scan/write in preview. Paths are fixed, private and confined to this lot. */
private function sources(array $manifest): array
{
$root = realpath($this->directory()); $sources = [];
foreach ($manifest['sources'] as $entry) {
$path = $root ? realpath($root.DIRECTORY_SEPARATOR.$entry['relative_path']) : false;
$inside = $path && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $root)).'/');
$matches = $inside && is_file($path) && filesize($path) === $entry['bytes'] && hash_equals($entry['sha256'], hash_file('sha256', $path));
$sources[] = ['name' => $entry['name'], 'sha256' => $entry['sha256'], 'bytes' => $entry['bytes'], 'ready' => (bool) $matches];
}
return $sources;
}
private function referenceRows(array $manifest): array
{
$rows = [['table' => 'reference_catalog_versions', 'data' => $manifest['catalog']]];
foreach (['activities' => 'economic_activities', 'chains' => 'value_chains', 'links' => 'value_chain_links'] as $group => $table) {
foreach ($manifest[$group] as $row) { $rows[] = ['table' => $table, 'data' => $row]; }
}
return $rows;
}
private function createdHere(string $id): bool
{
return DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('action', 'import')
->whereRaw("after_data->'result'->'changed' @> ?::jsonb", [json_encode([$id])])->exists();
}
private function references(array $manifest, bool $schemaReady): array
{
$results = [];
foreach ($this->referenceRows($manifest) as $row) {
$expected = $row['data']; $table = $row['table'];
$current = DB::table($table)->where('id', $expected['id'])->first();
$conflict = false;
foreach ($expected as $key => $value) {
if (! $current || ($key === 'metadata' && ! $schemaReady)) { continue; }
if ($key === 'status') { $conflict = $conflict || ! in_array($current->$key, ['draft', 'published'], true); continue; }
if ($key === 'data_classification') { $conflict = $conflict || ! in_array($current->$key, ['internal', 'public'], true); continue; }
$actual = $key === 'metadata' ? json_decode($current->$key, true) : $current->$key;
if (OpportunityCanonicalValue::hash($actual) !== OpportunityCanonicalValue::hash($value)) { $conflict = true; }
}
$identity = DB::table($table)->where('id', '!=', $expected['id']);
if ($table === 'reference_catalog_versions') { $identity->where('catalog_code', $expected['catalog_code'])->where('version_no', $expected['version_no'])->where('locale', $expected['locale']); }
elseif ($table === 'economic_activities') { $identity->where('catalog_version_id', $expected['catalog_version_id'])->where('code', $expected['code']); }
else { $identity->where('source_system', $expected['source_system'])->where('external_id', $expected['external_id']); }
$conflict = $conflict || $identity->exists();
if ($table === 'value_chains') {
$conflict = $conflict || DB::table($table)->where('id', '!=', $expected['id'])->where('cluster_id', $expected['cluster_id'])->where('code', $expected['code'])->whereNull('deleted_at')->exists();
}
$results[] = ['table' => $table, 'id' => $expected['id'], 'code' => $expected['code'] ?? $expected['external_id'] ?? $expected['catalog_code'],
'status' => $conflict ? 'conflict' : ($current ? 'reuse' : 'insert'), 'current_hash' => $current ? OpportunityCanonicalValue::hash((array) $current) : null,
'current_visibility' => $current?->status ?? $current?->data_classification ?? null];
}
return $results;
}
public function preview(User $actor): array
{
$this->authorize($actor);
$catalog = app(EconomicReferenceCatalog::class); $manifest = $catalog->manifest();
$target = $this->target(); $code = $this->fingerprint();
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
$column = $catalog->schemaAvailable();
$unique = DB::selectOne("SELECT 1 FROM pg_constraint WHERE conrelid='public.economic_activities'::regclass AND conname='economic_activities_sector_uq'") !== null;
$sectorNullable = DB::selectOne("SELECT is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='economic_activities' AND column_name='sector_id'")?->is_nullable === 'YES';
$index = DB::selectOne("SELECT 1 FROM pg_indexes WHERE schemaname='public' AND indexname='economic_activities_sector_idx'") !== null;
$installed = $ledger && $column && ! $unique && $sectorNullable && $index;
$consistent = $installed || (! $ledger && ! $column && $unique && ! $sectorNullable && ! $index);
$rows = $this->references($manifest, $column); $sources = $this->sources($manifest); $reasons = [];
foreach (['sector' => 'sectors', 'cluster' => 'economic_clusters'] as $name => $table) {
$expected = $manifest['existing'][$name]; $record = DB::table($table)->where('id', $expected['id'])->whereNull('deleted_at')->first();
foreach (array_filter($expected, fn ($v) => $v !== null) as $field => $value) {
if (! $record || (string) ($record->$field ?? '') !== (string) $value) { $reasons[] = 'Identidade/atributos do '.$name.' divergentes do manifesto; não foi usada semelhança de nomes.'; break; }
}
}
if (! $consistent) { $reasons[] = 'Ledger e esquema divergentes; reconciliar antes de instalar.'; }
if (collect($rows)->contains('status', 'conflict')) { $reasons[] = 'Conflito de identidade/versão: não será aplicado parcialmente.'; }
if (collect($sources)->contains('ready', false)) { $reasons[] = 'Exemplar privado ausente ou com bytes diferentes.'; }
$imported = ! collect($rows)->contains(fn ($r) => $r['status'] !== 'reuse');
$scanPath = $this->directory().'/scans.json';
$scan = is_file($scanPath) ? json_decode(file_get_contents($scanPath), true) : null;
$state = ['target' => $target, 'code_hash' => $code, 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256,
'migration' => self::MIGRATION, 'installed' => $installed, 'consistent' => $consistent, 'imported' => $imported,
'publication' => $catalog->publicationState(), 'rows' => $rows, 'sources' => $sources, 'scan' => $scan,
'divergence' => $manifest['divergence'], 'convention' => $manifest['convention'], 'common_reasons' => $reasons];
$operations = [];
foreach (self::OPERATIONS as $operation) {
$why = $reasons;
try { $this->authorize($actor, true, $operation); } catch (HttpException $e) { $why[] = $e->getMessage(); }
$evidence = $this->evidence($target, $code, $operation);
if (! $evidence['ready']) { $why[] = 'Decisão própria do ativo e prova fresca desta revisão/alvo/backup/restauro necessárias.'; }
if ($operation !== 'schema' && ! $installed) { $why[] = 'Instale primeiro o esquema nominal.'; }
if (in_array($operation, ['publish', 'withdraw'], true) && ! $imported) { $why[] = 'Importação privada completa necessária antes de publicar/retirar.'; }
if (in_array($operation, ['publish', 'withdraw'], true) && ! DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('action', 'import')->where('after_data->result->manifest_sha256', EconomicReferenceCatalog::MANIFEST_SHA256)->exists()) {
$why[] = 'Execute a importação privada autenticada, inclusive para registos reutilizados.';
}
if ($operation === 'withdraw' && $state['publication'] === 'private') { $why[] = 'O lote ainda não teve publicação para retirar.'; }
if ($operation === 'withdraw' && collect($rows)->contains(fn ($r) => $r['status'] === 'reuse'
&& in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id']))) {
$why[] = 'Há referências anteriores já públicas reutilizadas: reconciliar o mapa de retirada antes de agir.';
}
$token = hash_hmac('sha256', OpportunityCanonicalValue::hash([$actor->id, session()->getId(), $operation, $state, $evidence]), config('app.key'));
$operations[$operation] = ['ready' => $why === [], 'reasons' => array_values(array_unique($why)), 'hash' => $token, 'backupDate' => $evidence['date'], 'evidence_mode' => $evidence['mode']];
}
return [...$state, 'operations' => $operations];
}
private function scan(array $manifest): array
{
$directory = realpath($this->directory()); $records = [];
abort_unless($directory, 422, 'Área privada do lote indisponível.');
$paths = [['name' => 'manifesto', 'path' => database_path('data/economic-references-lot-01.json'), 'sha256' => EconomicReferenceCatalog::MANIFEST_SHA256]];
foreach ($manifest['sources'] as $source) { $paths[] = ['name' => $source['name'], 'path' => $directory.'/'.$source['relative_path'], 'sha256' => $source['sha256']]; }
foreach ($paths as $file) {
abort_unless(is_file($file['path']) && hash_equals($file['sha256'], hash_file('sha256', $file['path'])), 409, 'Originais alterados após prévia.');
// Scanner's path confinement uses the private source directory; manifest is scanned via a private exact copy.
$path = $file['path'];
if ($file['name'] === 'manifesto') { $path = $directory.'/manifest-scanned.json'; file_put_contents($path, file_get_contents($file['path'])); }
$result = app(MalwareScanner::class)->scan($path, filesize($path), $directory);
if ($result['signatures_at'] instanceof \DateTimeInterface) { $result['signatures_at'] = $result['signatures_at']->format(DATE_ATOM); }
$records[] = ['name' => $file['name'], 'sha256' => $file['sha256'], 'scan' => $result];
abort_unless($result['result'] === 'clean', 423, 'Scan não concluído ou não limpo para '.$file['name'].'. Nenhuma referência foi importada/publicada.');
abort_unless(hash_equals($file['sha256'], hash_file('sha256', $file['path'])) && hash_equals($file['sha256'], hash_file('sha256', $path)), 409, 'Bytes alterados durante o scan.');
}
$proof = ['at' => now()->toIso8601String(), 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'files' => $records];
file_put_contents($directory.'/scans.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
return $proof;
}
public function apply(User $actor, string $operation, array $input): array
{
abort_unless(in_array($operation, self::OPERATIONS, true), 404);
$this->authorize($actor, true, $operation);
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', 'reason', '_token']), 422, 'Campo de ator, manifesto ou conteúdo arbitrário não permitido.');
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
return DB::transaction(function () use ($actor, $operation, $data) {
DB::select('SELECT pg_advisory_xact_lock(161026,120000)');
$requestHash = OpportunityCanonicalValue::hash([$operation, $data]);
$old = DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('correlation_id', $data['idempotency_key'])->first();
if ($old) {
$receipt = json_decode($old->after_data, true, 512, JSON_THROW_ON_ERROR);
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave de repetição já usada com ator/conteúdo diferentes.');
return [...$receipt['result'], 'replayed' => true, 'current_publication' => app(EconomicReferenceCatalog::class)->publicationState()];
}
$plan = $this->preview($actor); $phase = $plan['operations'][$operation];
abort_unless(hash_equals($phase['hash'], $data['hash']), 409, 'Alvo, ator, revisão ou estado alterados; consulte nova prévia.');
abort_unless($phase['ready'], 422, implode(' ', $phase['reasons']));
$manifest = app(EconomicReferenceCatalog::class)->manifest(); $changed = []; $reused = [];
foreach ($this->referenceRows($manifest) as $row) { DB::table($row['table'])->where('id', $row['data']['id'])->lockForUpdate()->first(); }
DB::table('sectors')->where('id', $manifest['existing']['sector']['id'])->lockForUpdate()->first();
DB::table('economic_clusters')->where('id', $manifest['existing']['cluster']['id'])->lockForUpdate()->first();
// Recheck after locks in case another approved writer changed a reused master.
abort_unless($this->preview($actor)['operations'][$operation]['hash'] === $phase['hash'], 409, 'Referências alteradas durante a preparação da operação.');
if ($operation === 'schema' && ! $plan['installed']) {
config(['economic_references.authenticated_installation' => true]);
try { abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na migration nominal.'); }
finally { config(['economic_references.authenticated_installation' => false]); }
abort_unless($this->preview($actor)['installed'], 500, 'Esquema instalado não corresponde ao plano.');
$changed[] = self::MIGRATION;
} elseif ($operation === 'import') {
$scan = $this->scan($manifest);
foreach ($this->referenceRows($manifest) as $i => $row) {
if ($plan['rows'][$i]['status'] === 'reuse') { $reused[] = $row['data']['id']; continue; }
$values = $row['data']; if (isset($values['metadata'])) { $values['metadata'] = json_encode($values['metadata'], JSON_THROW_ON_ERROR); }
DB::table($row['table'])->insert([...$values, 'created_at' => now(), 'updated_at' => now()]);
$changed[] = $values['id'];
}
} elseif ($operation === 'publish' || $operation === 'withdraw') {
if ($operation === 'publish') { $scan = $this->scan($manifest); }
foreach ($this->referenceRows($manifest) as $row) {
$table = $row['table']; $record = DB::table($table)->where('id', $row['data']['id'])->lockForUpdate()->first();
if (in_array($table, ['reference_catalog_versions', 'economic_activities'], true)) {
if ($operation === 'publish' && $record->status === 'draft') {
DB::table($table)->where('id', $record->id)->update(['status' => 'published', 'updated_at' => now()]); $changed[] = $record->id;
} else { $reused[] = $record->id; }
} else {
$visibility = $operation === 'publish' ? 'public' : 'internal';
// Withdrawal touches only objects this importer created, never pre-existing public references.
$createdHere = $this->createdHere($record->id);
if ($operation === 'withdraw' && ! $createdHere) { $reused[] = $record->id; continue; }
if ($record->data_classification !== $visibility) { DB::table($table)->where('id', $record->id)->update(['data_classification' => $visibility, 'updated_at' => now()]); $changed[] = $record->id; }
else { $reused[] = $record->id; }
}
}
}
$result = ['operation' => $operation, 'lot' => 'lot-01', 'target' => $plan['target'], 'changed' => $changed, 'reused' => $reused,
'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'code_hash' => $plan['code_hash'], 'replayed' => false,
'publications' => $operation === 'publish' ? 'references only; no investment or original source publication' : 'none', 'business_records_changed' => 0,
'receipt' => $data['idempotency_key'], 'scan' => $scan ?? null];
if ($operation === 'import') { $result['previously_public'] = array_values(array_column(array_filter($plan['rows'], fn ($r) => $r['status'] === 'reuse' && in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id'])), 'id')); }
DB::table('audit_events')->insert(['source_system' => EconomicReferenceCatalog::SOURCE, 'entity_type' => 'economic-reference-batch', 'entity_id' => $manifest['catalog']['id'],
'actor_user_id' => $actor->id, 'correlation_id' => $data['idempotency_key'], 'action' => $operation, 'data_classification' => 'restricted',
'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
class EditorialInstallation
{
public const SOURCE='editorial-schema-installation';
public const MIGRATION='2026_10_18_160000_add_portal_editorial_content';
public function files(): array
{
return ['app/Http/Controllers/EditorialArticleController.php', 'app/Http/Controllers/PortalManagementController.php', 'app/Http/Controllers/PortalServicesController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Services/InvestmentCatalogue.php', 'app/Services/LegacyContent.php', 'app/Services/OpportunityClassification.php', 'routes/web.php', 'database/migrations/2026_10_18_160000_add_portal_editorial_content.php', 'resources/js/pages/management/editor.tsx', 'resources/js/pages/portal/article-editor.tsx', 'resources/js/pages/portal/article.tsx', 'resources/js/pages/portal/document.tsx', 'resources/js/pages/portal/manage.tsx', 'app/Services/EditorialInstallation.php', 'resources/views/management/editorial-installation.blade.php', 'resources/views/management/editorial-mfa.blade.php'];
}
public function fingerprint(): string
{
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
}
private function authorize(User $actor,bool $write=false): void
{
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
}
private function evidence(array $target,string $code): array
{
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
$path=storage_path('app/private/investmoz-v2/editorial/readiness.json');
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===self::MIGRATION;
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
}
public function preview(User $actor): array
{
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
$ledgerCount=DB::table('migrations')->where('migration',self::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('portal_resources','editorial_content');
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='portal_resources' AND column_name='editorial_content'");
$correct=$shape && $shape->data_type==='jsonb' && $shape->is_nullable==='YES';
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
$state=['target'=>$target,'migration'=>self::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
}
public function apply(User $actor,array $input): array
{
$this->authorize($actor,true);
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
return DB::transaction(function()use($actor,$data){
DB::select('SELECT pg_advisory_xact_lock(181026,160000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
if(!$plan['installed']){
config(['editorial.authenticated_installation'=>true]);
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.self::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
finally{config(['editorial.authenticated_installation'=>false]);}
}
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'portal-editorial-schema','entity_id'=>null,'actor_user_id'=>$actor->id,
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
@@ -0,0 +1,273 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\User;
use App\Policies\ExistingBusinessPolicy;
use App\Services\Mne\BusinessRepository;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Supplement of the same UUID. All state remains in the existing immutable encrypted journal. */
class ExistingBusinessClassification
{
public const VERSION = 'business-classification-20261016-v1';
private const ACTIONS = ['classification_prepared', 'classification_reviewed', 'classification_disclosed', 'classification_withdrawn'];
public function context(ExistingBusiness $business): array
{
$revision = DB::table('existing_business_revisions')->where('business_id', $business->id)->whereIn('action', self::ACTIONS)->orderByDesc('version_no')->first(['snapshot']);
if (! $revision) {
return ['schema_version' => self::VERSION, 'relations' => [], 'authors' => [], 'decisions' => [], 'publication' => []];
}
$state = json_decode(Crypt::decryptString($revision->snapshot), true, 512, JSON_THROW_ON_ERROR)['context']['multidimensional'] ?? null;
abort_unless(is_array($state) && ($state['schema_version'] ?? '') === self::VERSION, 409, 'Versão do suplemento não reconhecida; preserve o histórico.');
return $state;
}
private function hash(array $row): string
{
return OpportunityCanonicalValue::hash($row);
}
private function evidence(array $row, ExistingBusiness $business): ?array
{
$id = $row['classification']['document_id'] ?? null;
if (! $id) {
return null;
}
$document = DB::table('existing_business_document_links as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.existing_business_id', $business->id)->where('d.id', $id)
->first(['l.id as link_id', 'd.id', 'd.sha256', 'd.version_no', 'd.status', 'd.deleted_at', 'd.valid_until', 'd.malware_scan_status', 'd.malware_scanned_sha256']);
return $document ? (array) $document : ['unavailable' => $id];
}
private function evidenceHash(array $row, ExistingBusiness $business): ?string
{
$evidence = $this->evidence($row, $business);
return $evidence === null ? null : OpportunityCanonicalValue::hash($evidence);
}
private function validateRows(array $rows, ExistingBusiness $business, bool $confirming = false): void
{
$seen = [];
foreach ($rows as $i => $row) {
$fail = fn ($key, $message) => throw ValidationException::withMessages(['canonical.relations.'.$i.'.'.$key => $message]);
Validator::make($row, [
'related_id' => ['required', 'string', 'max:80'], 'relation_type' => ['required', 'string', 'max:80'],
'classification' => ['required', 'array:target_type,purpose,criteria,justification,source_reference,citation,document_id,authority_id,requested_state,disclosure,valid_from,valid_until,external_status,external_act_reference,production_stage'],
'classification.target_type' => ['required', Rule::in(array_keys(OpportunityClassification::TARGETS))],
'classification.purpose' => ['required', Rule::in(array_keys(OpportunityClassification::PURPOSES))],
'classification.requested_state' => ['required', Rule::in(['draft', 'preliminary', 'in_validation'])],
'classification.disclosure' => ['required', Rule::in(['restricted', 'public'])],
'classification.criteria' => ['nullable', 'string', 'max:2000'], 'classification.justification' => ['nullable', 'string', 'max:4000'],
'classification.source_reference' => ['nullable', 'string', 'max:2000'], 'classification.citation' => ['nullable', 'string', 'max:1000'],
'classification.document_id' => ['nullable', 'uuid'], 'classification.authority_id' => ['nullable', 'uuid'],
'classification.valid_from' => ['nullable', 'date_format:Y-m-d'], 'classification.valid_until' => ['nullable', 'date_format:Y-m-d'],
'classification.external_status' => ['required', Rule::in(OpportunityClassification::EXTERNAL)],
'classification.external_act_reference' => ['nullable', 'string', 'max:2000'], 'classification.production_stage' => ['nullable', 'string', 'max:250'],
])->validate();
if (array_diff(array_keys($row), ['related_id', 'relation_type', 'classification'])) {
$fail('classification', 'Metadados de decisão ou campos desconhecidos não podem ser enviados pelo autor.');
}
$c = $row['classification']; $kind = $c['target_type'];
if (($kind === 'sector' && ! ctype_digit($row['related_id'])) || ($kind !== 'sector' && ! Str::isUuid($row['related_id']))) {
$fail('related_id', 'Identificador de referência inválido.');
}
if (! app(OpportunityClassification::class)->canRetainReference($kind, $row['related_id'], $row, $this->context($business)['relations'])) {
$fail('related_id', 'Selecione uma referência existente e consultável.');
}
if (in_array($c['purpose'], ['regime_recognition', 'enterprise_admission', 'specific_benefit'], true) && $kind !== 'zone') {
$fail('classification.purpose', 'Regime, admissão e benefício usam a relação regulatória com a zona.');
}
$identity = OpportunityClassification::TARGETS[$kind][0].':'.$row['related_id'].':'.$c['purpose'];
if (isset($seen[$identity])) { $fail('related_id', 'Referência e finalidade já associadas; recupere a relação existente.'); }
$seen[$identity] = true;
if (! empty($c['valid_from']) && ! empty($c['valid_until']) && $c['valid_until'] < $c['valid_from']) {
$fail('classification.valid_until', 'O fim da vigência precede o início.');
}
if (! empty($c['authority_id']) && ! DB::table('authorities')->where('id', $c['authority_id'])->where('status', 'published')->exists()) {
$fail('classification.authority_id', 'Entidade competente não consta do catálogo publicado.');
}
$evidence = $this->evidence($row, $business);
if ($evidence && isset($evidence['unavailable'])) { $fail('classification.document_id', 'Documento não está associado a este anúncio.'); }
if (($c['external_status'] ?? '') === 'documented_granted' && (empty($c['document_id']) || empty(trim($c['external_act_reference'] ?? '')))) {
$fail('classification.external_act_reference', 'Um ato declarado como concedido exige documento e referência próprios.');
}
if ($confirming) {
foreach (['criteria', 'justification', 'source_reference', 'citation'] as $key) {
if (empty(trim($c[$key] ?? ''))) { $fail('classification.'.$key, 'Confirmação exige fundamento e fonte/citação por relação; a preparação pode continuar preliminar.'); }
}
if ($evidence && ($evidence['status'] !== 'active' || $evidence['deleted_at'] !== null || $evidence['malware_scan_status'] !== 'clean'
|| ! hash_equals(trim($evidence['sha256']), trim((string) $evidence['malware_scanned_sha256']))
|| (! empty($evidence['valid_until']) && $evidence['valid_until'] < today()->toDateString()))) {
$fail('classification.document_id', 'O suporte associado não está disponível, íntegro e analisado para esta confirmação.');
}
}
}
}
private function effective(ExistingBusiness $business, array $row, array $state): string
{
$decision = $state['decisions'][$this->hash($row)] ?? null;
if (! $decision) { return $row['classification']['requested_state'] ?? 'preliminary'; }
if ($decision['state'] !== 'confirmed') { return $decision['state']; }
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
$reviewer = User::find($decision['actor_id']);
if (! $reviewer || ! app(ExistingBusinessPolicy::class)->classificationReviewerScope($reviewer, $business, $dimension)
|| (int) ($state['authors'][$this->hash($row)] ?? 0) === (int) $reviewer->id
|| ($decision['evidence_hash'] ?? null) !== $this->evidenceHash($row, $business)) {
return 'in_validation';
}
return 'confirmed';
}
public function privateView(User $actor, ExistingBusiness $business): array
{
Gate::forUser($actor)->authorize('view', $business);
$state = $this->context($business);
$rows = [];
foreach ($state['relations'] as $row) {
$hash = $this->hash($row); $dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
$rows[] = ['hash' => $hash, 'relation' => $row, 'dimension' => $dimension, 'state' => $this->effective($business, $row, $state),
'can_review' => Gate::forUser($actor)->allows('reviewClassification', $business) && app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
&& (int) ($state['authors'][$hash] ?? 0) !== (int) $actor->id,
'history' => $state['decisions'][$hash]['history'] ?? []];
}
$documents = DB::table('existing_business_document_links as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.existing_business_id', $business->id)->whereNull('d.deleted_at')->get(['d.id', 'd.file_name', 'd.sha256']);
return ['id' => $business->id, 'title' => $business->public_title, 'status' => $business->status, 'version_no' => $business->version_no,
'rows' => $rows, 'publication' => $this->publicRows($business), 'publication_version' => $state['publication_version'] ?? null,
'preview' => $this->publicRows($business, [...$state, 'publication' => array_values(array_filter($state['relations'], fn ($r) => $r['classification']['disclosure'] === 'public'))]),
'can_prepare' => Gate::forUser($actor)->allows('prepareClassification', $business),
'can_disclose' => Gate::forUser($actor)->allows('discloseClassification', $business),
'options' => app(OpportunityClassification::class)->options(),
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz']),
'documents' => $documents->map(fn ($d) => ['id' => $d->id, 'payload' => ['title' => $d->file_name], 'file' => ['file_name' => $d->file_name]])];
}
public function act(User $actor, string $id, array $input): ExistingBusiness
{
$data = Validator::make($input, [
'action' => ['required', Rule::in(['prepare', 'review', 'disclose', 'withdraw'])], 'version_no' => ['required', 'integer', 'min:1'],
'reason' => ['required', 'string', 'min:20', 'max:1000'],
'rows' => ['required_if:action,prepare', 'array', 'max:100'],
'hash' => ['required_if:action,review', 'string', 'size:64'],
'state' => ['required_if:action,review', Rule::in(['in_validation', 'confirmed', 'rejected', 'archived', 'revoked'])],
], ['reason.required' => 'Indique o fundamento da ação.', 'reason.min' => 'O fundamento deve ter pelo menos 20 caracteres.'])->validate();
abort_if(array_diff(array_keys($input), ['action', 'version_no', 'reason', 'rows', 'hash', 'state']), 422, 'Esta ação aceita apenas campos da classificação.');
return DB::transaction(function () use ($actor, $id, $data) {
$business = app(BusinessRepository::class)->find($id, true);
$action = $data['action'];
Gate::forUser($actor)->authorize(match ($action) { 'prepare' => 'prepareClassification', 'review' => 'reviewClassification', default => 'discloseClassification' }, $business);
abort_unless($business->version_no === (int) $data['version_no'], 409, 'A versão mudou. Atualize antes de decidir; preserve os valores preparados.');
$state = $this->context($business);
if ($action === 'prepare') {
$this->validateRows($data['rows'], $business);
$state['relations'] = $data['rows'];
foreach ($data['rows'] as $row) { $state['authors'][$this->hash($row)] ??= $actor->id; }
} elseif ($action === 'review') {
$search = in_array($data['state'], ['revoked', 'archived'], true) ? [...$state['relations'], ...$state['publication']] : $state['relations'];
$row = collect($search)->first(fn ($r) => hash_equals($this->hash($r), $data['hash']));
abort_unless($row, 409, 'Associação inexistente nesta versão.');
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
abort_unless(app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
&& (int) ($state['authors'][$data['hash']] ?? 0) !== (int) $actor->id, 403, 'Revisão exige responsabilidade e independência aplicáveis.');
if ($data['state'] === 'confirmed') { $this->validateRows([$row], $business, true); }
$prior = $state['decisions'][$data['hash']] ?? [];
$decision = ['state' => $data['state'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'],
'evidence_hash' => $this->evidenceHash($row, $business), 'version' => ($prior['version'] ?? 0) + 1];
$state['decisions'][$data['hash']] = [...$decision, 'history' => [...($prior['history'] ?? []), $decision]];
if (in_array($data['state'], ['revoked', 'archived'], true)) {
// Explicit withdrawal is retained: a later confirmation must not silently republish it.
$state['publication'] = array_values(array_filter($state['publication'], fn ($r) => $this->hash($r) !== $data['hash']));
}
} else {
$publication = $action === 'withdraw' ? [] : array_values(array_filter($state['relations'], fn ($r) => $r['classification']['disclosure'] === 'public'));
$this->validateRows($publication, $business);
// Existing publication independence also applies to the actors deciding this supplement.
foreach ($publication as $row) {
abort_if((int) ($state['decisions'][$this->hash($row)]['actor_id'] ?? 0) === (int) $actor->id, 403, 'A divulgação deve ser feita por pessoa diferente de quem decidiu a associação.');
}
$state['publication'] = $publication;
$state['publication_version'] = $business->version_no + 1;
$state['publication_actor'] = $actor->id;
$state['publication_at'] = now()->toIso8601String();
}
$business->version_no++;
$business->save();
$event = ['prepare' => 'classification_prepared', 'review' => 'classification_reviewed', 'disclose' => 'classification_disclosed', 'withdraw' => 'classification_withdrawn'][$action];
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $event, $data['reason'], ['multidimensional' => $state]);
return $business;
});
}
public function publicRows(ExistingBusiness $business, ?array $preparedState = null): array
{
if ($business->trashed() || $business->status !== 'published' || ! $business->published_at || $business->published_at->isFuture()
|| ($business->expires_at && $business->expires_at->isBefore(today()))) { return []; }
$state = $preparedState ?? $this->context($business); $rows = [];
foreach ($state['publication'] as $row) {
$c = $row['classification']; $kind = $c['target_type'];
if (($c['disclosure'] ?? '') !== 'public' || ! isset(OpportunityClassification::TARGETS[$kind])) { continue; }
$target = app(OpportunityClassification::class)->targets($kind)->where('id', $row['related_id'])->first();
if (! $target || (! empty($c['valid_from']) && $c['valid_from'] > today()->toDateString()) || (! empty($c['valid_until']) && $c['valid_until'] < today()->toDateString())) { continue; }
$effective = $this->effective($business, $row, $state);
if (in_array($effective, ['archived', 'revoked'], true)) { continue; }
$rows[] = ['dimension' => OpportunityClassification::TARGETS[$kind][2], 'target_type' => $kind, 'target_id' => (string) $row['related_id'],
'label' => $target->{OpportunityClassification::TARGETS[$kind][1]}, 'target_code' => $target->code ?? null,
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)?->path ?? []) : [], 'purpose' => $c['purpose'], 'purpose_label' => OpportunityClassification::PURPOSES[$c['purpose']],
'state' => $effective, 'source_reference' => $c['source_reference'] ?? null, 'citation' => $c['citation'] ?? null,
'authority_id' => $c['authority_id'] ?? null, 'production_stage' => $c['production_stage'] ?? null,
'external_status' => $c['external_status'], 'valid_from' => $c['valid_from'] ?? null, 'valid_until' => $c['valid_until'] ?? null];
}
return $rows;
}
public function filterRules(): array
{
return ['association_type' => ['nullable', Rule::in(array_keys(OpportunityClassification::TARGETS))],
'association_target' => ['nullable', 'string', 'max:80'], 'association_purpose' => ['nullable', Rule::in(array_keys(OpportunityClassification::PURPOSES))],
'association_state' => ['nullable', Rule::in(OpportunityClassification::STATES)],
'chain_id' => ['nullable', 'uuid'], 'authority_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid']];
}
public function constrain(Builder $query, array $filters): void
{
$filters = array_filter(array_intersect_key($filters, $this->filterRules()), fn ($v) => $v !== null && $v !== '');
if ($filters === []) { return; }
$ids = [];
(clone $query)->reorder()->select('existing_businesses.*')->chunkById(200, function ($records) use ($filters, &$ids) {
foreach ($records as $business) {
$rows = $this->publicRows($business); $same = array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_purpose', 'association_state']));
$matches = ! $same || collect($rows)->contains(function ($row) use ($same) {
foreach (['association_type' => 'target_type', 'association_target' => 'target_id', 'association_purpose' => 'purpose', 'association_state' => 'state'] as $key => $field) {
if (isset($same[$key]) && $same[$key] !== $row[$field]) { return false; }
}
return true;
});
foreach (['chain_id' => 'chain', 'subsector_id' => 'activity'] as $key => $type) {
if (! empty($filters[$key])) { $matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === $type && $r['target_id'] === $filters[$key]); }
}
if (! empty($filters['authority_id'])) { $matches = $matches && collect($rows)->contains(fn ($r) => ($r['authority_id'] ?? null) === $filters['authority_id']); }
if ($matches) { $ids[] = $business->id; }
}
}, 'existing_businesses.id', 'id');
$query->whereIn('existing_businesses.id', $ids);
}
}
+14 -3
View File
@@ -37,6 +37,7 @@ final class ExistingBusinessIntake
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) { return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) {
$business = app(BusinessRepository::class)->find($id, true); $business = app(BusinessRepository::class)->find($id, true);
$profileWorkflow = ExistingBusinessProfileCategory::category($business) !== null && app(PortalProfileAccess::class)->available();
$ability = match ($action) { $ability = match ($action) {
OpportunityStatus::Submitted->value, OpportunityStatus::Withdrawn->value => 'owns', OpportunityStatus::Submitted->value, OpportunityStatus::Withdrawn->value => 'owns',
OpportunityStatus::Triage->value => 'triage', OpportunityStatus::Triage->value => 'triage',
@@ -64,6 +65,14 @@ final class ExistingBusinessIntake
OpportunityStatus::Triage->value, OpportunityStatus::InReview->value, OpportunityStatus::NeedsInformation->value], OpportunityStatus::Triage->value, OpportunityStatus::InReview->value, OpportunityStatus::NeedsInformation->value],
]; ];
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.'); abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
// Reuse the bounded delivery contract: profile correspondence is access, not functional enablement.
$category = ExistingBusinessProfileCategory::category($business);
if ($category !== null && in_array($action, ['submitted', 'published'], true)) {
$blockers = app(OpportunityCanonicalContract::class)->deliveryBlockers(['opportunity_category' => $category]);
if ($blockers) {
throw ValidationException::withMessages(['modality' => implode(' ', array_values($blockers))]);
}
}
if ($action === 'submitted') { if ($action === 'submitted') {
if (($business->payload['wizard_version'] ?? null) === '2') { if (($business->payload['wizard_version'] ?? null) === '2') {
BusinessFormSchema::validateSubmission($business->payload, $business->sector_id, $business->modality); BusinessFormSchema::validateSubmission($business->payload, $business->sector_id, $business->modality);
@@ -81,7 +90,8 @@ final class ExistingBusinessIntake
} elseif (($business->payload['wizard_version'] ?? null) === '1') { } elseif (($business->payload['wizard_version'] ?? null) === '1') {
Validator::make($business->payload, [ Validator::make($business->payload, [
'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'], 'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'],
'contact_email' => ['required', 'email'], 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'contact_email' => ['required', 'email'], 'country' => ['required', app(CountryCatalogue::class)->rule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'], 'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'],
'legitimacy_declaration' => ['required', 'in:yes'], 'legitimacy_declaration' => ['required', 'in:yes'],
'mandate_reference' => ['required_if:acting_capacity,representative'], 'mandate_reference' => ['required_if:acting_capacity,representative'],
@@ -116,7 +126,7 @@ final class ExistingBusinessIntake
if ($action === OpportunityStatus::Approved->value) { if ($action === OpportunityStatus::Approved->value) {
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id) $levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
->where('to_status', OpportunityStatus::ApprovalL2->value)->orderByDesc('created_at')->value('actor_id'); ->where('to_status', OpportunityStatus::ApprovalL2->value)->orderByDesc('created_at')->value('actor_id');
abort_unless($levelOneActor !== null && (int) $levelOneActor !== (int) $actor->id, 403, abort_unless($levelOneActor !== null && ($profileWorkflow || (int) $levelOneActor !== (int) $actor->id), 403,
'A aprovação de nível 2 deve ser feita por uma pessoa diferente da aprovação de nível 1.'); 'A aprovação de nível 2 deve ser feita por uma pessoa diferente da aprovação de nível 1.');
} }
if ($action === OpportunityStatus::Published->value) { if ($action === OpportunityStatus::Published->value) {
@@ -145,7 +155,8 @@ final class ExistingBusinessIntake
'actor_id' => $actor->id, 'actor_id' => $actor->id,
'reason' => Crypt::encryptString($note), 'reason' => Crypt::encryptString($note),
'correlation_id' => $correlationId, 'correlation_id' => $correlationId,
'metadata' => json_encode(['version_no' => $business->version_no, 'source' => 'portal-intake'], JSON_THROW_ON_ERROR), 'metadata' => json_encode(['version_no' => $business->version_no, 'source' => 'portal-intake',
'authorization_mode' => $profileWorkflow ? 'profiles-v1-company-sale' : 'legacy-designations'], JSON_THROW_ON_ERROR),
'created_at' => now(), 'created_at' => now(),
]); ]);
if ($action === OpportunityStatus::Submitted->value) { if ($action === OpportunityStatus::Submitted->value) {
@@ -0,0 +1,45 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
/** Access correspondence, never evidence of legality, title, finance or publication. */
final class ExistingBusinessProfileCategory
{
// Exact catalogue correspondences plus the explicit mappings already present
// in BusinessWizard and the transaction variants in OpportunityCategoryFields.
public const MAP = [
'company_sale'=>'business_sale', 'participation_sale'=>'business_sale',
'buyer_search'=>'business_sale', 'succession'=>'business_sale',
'franchise'=>'franchise', 'real_estate'=>'real_estate', 'land_right'=>'land_rights',
'investment_project'=>'investment_project', 'expansion'=>'investment_project',
'internationalization'=>'investment_project', 'agricultural_investment'=>'investment_project',
'business_partnership'=>'business_partnership', 'strategic_partner'=>'business_partnership',
'joint_venture'=>'business_partnership', 'capital_increase'=>'financing',
'financial_investor'=>'financing', 'financing_request'=>'financing',
'concession_opportunity'=>'concession', 'supply_opportunity'=>'supply',
];
// Native form types are separate from the persisted modality. No default to a project.
public const FORM_TYPES = [
'investment_project'=>'investment_project', 'company_sale'=>'company_sale',
'asset_sale'=>'asset_sale', 'business_partnership'=>'business_partnership',
'financing_request'=>'financing_request', 'concession_opportunity'=>'concession_opportunity',
'supply_opportunity'=>'supply_opportunity', 'participation_sale'=>'company_sale',
'asset_lease'=>'asset_sale', 'capital_increase'=>'financing_request',
'financial_investor'=>'financing_request', 'strategic_partner'=>'business_partnership',
'joint_venture'=>'business_partnership', 'expansion'=>'investment_project',
'agricultural_investment'=>'investment_project', 'internationalization'=>'investment_project',
'buyer_search'=>'company_sale', 'succession'=>'company_sale',
];
public static function category(ExistingBusiness $business): ?string
{
return self::MAP[$business->modality] ?? null;
}
public static function formType(string $modality): ?string
{
return self::FORM_TYPES[$modality] ?? null;
}
}
+180
View File
@@ -0,0 +1,180 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Ai\InvestorGuidanceRules;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Private characterization in the existing dossier; no legal classification or new workflow. */
final class FintechInvestment
{
public const VERSION = 'fintech-preparation-v1';
public const FIELDS = [
'problem' => 'Problema a resolver', 'clients' => 'Público-alvo e clientes nacionais/estrangeiros',
'value' => 'Proposta de valor', 'revenues' => 'Modelo de receitas', 'services' => 'Serviços pretendidos',
'channels' => 'Canais de prestação', 'currencies' => 'Moedas de operação declaradas',
'location' => 'Localização efetiva e instalações', 'coverage' => 'Abrangência de operação',
'technology' => 'Tecnologia e arquitetura', 'infrastructure' => 'Infraestrutura',
'suppliers' => 'Fornecedores críticos', 'security' => 'Segurança e resposta a incidentes',
'continuity' => 'Continuidade e recuperação', 'partners' => 'Instituições financeiras e parceiros',
'team' => 'Equipa e capacidade operacional', 'maturity' => 'Maturidade declarada',
'dependencies' => 'Dependências concretas', 'schedule' => 'Calendário de implementação',
];
public const ACTIVITIES = ['moves_funds' => 'Movimentar fundos', 'deposits' => 'Receber depósitos',
'custody' => 'Custodiar fundos', 'credit' => 'Conceder crédito', 'payments' => 'Serviços de pagamento',
'investment_intermediation' => 'Intermediar investimentos', 'other' => 'Outra atividade potencialmente regulada'];
public const DOCUMENTS = ['business_plan' => ['S04', 'Modelo de negócio, mercado e plano de investimento'],
'entity' => ['S05', 'Entidade, representação e participação'], 'architecture' => ['S06', 'Arquitetura tecnológica e fluxos de dados'],
'security' => ['S16', 'Segurança, continuidade e fornecedores'], 'fund_flows' => ['S08', 'Fluxos de fundos e enquadramento da atividade'],
'customers' => ['S17', 'Atendimento, reclamações e proteção do utilizador'],
'external' => ['S08', 'Pedido ou decisão externa e respetivo âmbito'], 'tests' => ['S17', 'Testes e preparação operacional']];
public function __construct(private readonly VirtualDesk $desk) {}
public function save(User $actor, string $id, array $input): void
{
$keys = implode(',', array_keys(self::FIELDS));
$activities = implode(',', array_keys(self::ACTIVITIES));
$rules = ['version' => 'required|integer|min:1', 'profile' => ['required', 'array:model,fields,operation_countries,activities,activity_basis,documents'],
'profile.model' => ['nullable', Rule::in(['technology_provider', 'financial_operator', 'undetermined'])],
'profile.fields' => ['nullable', 'array:'.$keys], 'profile.operation_countries' => 'nullable|array|max:249',
'profile.operation_countries.*' => ['required', 'distinct', app(CountryCatalogue::class)->rule()],
'profile.activities' => ['nullable', 'array:'.$activities], 'profile.activity_basis' => 'nullable|string|max:3000',
'profile.documents' => 'nullable|array|max:8', 'profile.documents.*' => 'nullable|uuid'];
foreach (self::FIELDS as $key => $label) {
$rules['profile.fields.'.$key] = 'nullable|string|max:4000';
}
foreach (self::ACTIVITIES as $key => $label) {
$rules['profile.activities.'.$key] = ['nullable', Rule::in(['yes', 'no', 'unknown'])];
}
$rules['profile.documents'] = ['nullable', 'array:'.implode(',', array_keys(self::DOCUMENTS))];
$data = Validator::make($input, $rules)->validate();
DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409, 'O dossier está encerrado.');
abort_unless($this->desk->owns($actor, $case), 403, 'Sem autorização para preparar este dossier.');
$payload = $this->desk->decode($case->payload);
$profile = $data['profile'];
$profile['model'] = $profile['model'] ?? 'undetermined';
$profile['fields'] = array_map(fn ($v) => trim((string) $v), $profile['fields'] ?? []);
$profile['activities'] = array_replace(array_fill_keys(array_keys(self::ACTIVITIES), 'unknown'), $profile['activities'] ?? []);
$profile['operation_countries'] = $profile['operation_countries'] ?? [];
sort($profile['operation_countries']);
$profile['documents'] = array_filter($profile['documents'] ?? []);
$profile['activity_basis'] = trim($profile['activity_basis'] ?? '');
foreach ($profile['documents'] as $key => $document) {
if (! DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('l.document_id', $document)->whereNull('d.deleted_at')->exists()) {
throw ValidationException::withMessages(['profile.documents.'.$key => 'O documento deixou de estar disponível neste dossier. Selecione um anexo associado e disponível; os campos preenchidos foram preservados.']);
}
}
$hash = $this->fingerprint($profile);
$old = $payload['investor_path']['fintech'] ?? null;
if (($old['sha256'] ?? null) === $hash) {
return;
}
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi alterado; recupere a versão atual antes de guardar.');
if ($old) {
$payload['investor_path']['fintech_history'][] = $old;
}
$payload['investor_path']['fintech'] = ['schema' => self::VERSION, 'sha256' => $hash, 'profile' => $profile, 'actor_id' => $actor->id, 'saved_at' => now()->toIso8601String()];
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'fintech_characterization_saved', ['schema' => self::VERSION, 'sha256' => $hash, 'previous_sha256' => $old['sha256'] ?? null]);
});
}
private function fingerprint(array $value): string
{
$canonical = function ($v) use (&$canonical) {
if (! is_array($v)) {
return $v;
}
if (! array_is_list($v)) {
ksort($v);
}
return array_map($canonical, $v);
};
return hash('sha256', json_encode($canonical($value), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
public function reviewFingerprints(array $record): array
{
$profile = $record['profile'] ?? [];
$fields = $profile['fields'] ?? [];
$project = static fn (array $keys) => array_replace(array_fill_keys($keys, ''), array_intersect_key($fields, array_flip($keys)));
$countries = $profile['operation_countries'] ?? [];
sort($countries);
// Country order and an omitted versus empty optional field are not material changes.
return [
'S02' => $this->fingerprint($project(['problem', 'clients', 'value', 'revenues'])),
'S08' => $this->fingerprint([$profile['model'] ?? 'undetermined', $profile['activities'] ?? [], $countries, $fields['services'] ?? '', $profile['activity_basis'] ?? '']),
'S17' => $this->fingerprint($project(['technology', 'infrastructure', 'suppliers', 'security', 'continuity', 'channels', 'location'])),
];
}
public function adjustSteps(array $payload, array $steps): array
{
$record = $payload['investor_path']['fintech'] ?? null;
if (! $record) {
return $steps;
}
$fingerprints = $this->reviewFingerprints($record);
foreach ($steps as &$step) {
$hash = $fingerprints[$step['code']] ?? null;
if (! $hash) {
continue;
}
$reviewed = in_array($step['saved_state'], ['approved', 'reviewing', 'completed', 'ready_to_submit', 'submitted'], true);
if ($reviewed && ($step['detail']['fintech_fingerprint'] ?? null) !== $hash) {
$step['fintech_review_required'] = true;
$step['state'] = 'correction_required';
$step['reason'] = 'Pressupostos Fintech alterados ou ainda não abrangidos por esta revisão. O parecer anterior está preservado; é necessária conferência deste âmbito.';
}
}
unset($step);
return $steps;
}
public function view(array $payload, array $steps): array
{
$record = $payload['investor_path']['fintech'] ?? null;
$p = $record['profile'] ?? [];
$declared = $p['activities'] ?? [];
$basis = $p['activity_basis'] ?? '';
$requirements = [];
foreach (self::ACTIVITIES as $key => $label) {
$value = $declared[$key] ?? 'unknown';
$requirements[] = ['code' => $key, 'activity' => $label,
'declared' => $value, 'state' => $value === 'yes' ? 'applicable' : ($value === 'no' && mb_strlen($basis) >= 3 ? 'dispensed' : 'undetermined'),
'action' => 'Preparar o enquadramento documental desta atividade', 'preparation_allowed' => true,
'basis' => $value === 'no' && mb_strlen($basis) >= 3 ? $basis : 'Declaração do promotor; a atividade e o enquadramento jurídico concreto ainda precisam de correspondência documental.',
'source' => ['nature' => 'investor_declaration', 'reference' => $record['sha256'] ?? null, 'provision' => null, 'version' => null, 'valid_period' => null],
'legal_license_state' => 'undetermined', 'limit' => 'Dispensa apenas desta preparação declarada; não é dispensa de licença ou confirmação externa.'];
}
$docs = [];
foreach (self::DOCUMENTS as $key => [$stage,$label]) {
$conditional = in_array($key, ['fund_flows', 'external'], true);
$needed = $conditional ? (in_array('yes', $declared, true) ? 'applicable' : 'undetermined') : 'support';
$docs[] = ['code' => $key, 'stage' => $stage, 'label' => $label, 'applicability' => $needed, 'document_id' => $p['documents'][$key] ?? null, 'required_at_creation' => false, 'action' => $key === 'external' ? 'Documentar o ato quando existir; usar a etapa e a conferência independente existentes.' : 'Preparar e associar ao dossier sem duplicar originais.'];
}
$facts = ['project_summary' => $p['fields']['problem'] ?? '', 'activity' => $p['fields']['services'] ?? '', 'target_customers' => $p['fields']['clients'] ?? '', 'location' => $p['fields']['location'] ?? '', 'resource_plan' => $p['fields']['technology'] ?? '', 'schedule' => $p['fields']['schedule'] ?? ''];
$guidance = app(InvestorGuidanceRules::class)->evaluate($facts);
$map = ['idea' => 'S01', 'market' => 'S02', 'location' => 'S09', 'resources' => 'S06', 'finance' => 'S12', 'execution' => 'S16', 'support' => 'S19'];
$guidance = array_map(fn ($item) => ['stage' => $map[$item['id']], 'recommendations' => $item['recommendations']], $guidance);
return ['guidance' => $guidance, 'guidance_version' => InvestorGuidanceRules::VERSION, 'schema' => self::VERSION, 'record' => $record, 'fields' => self::FIELDS, 'activities' => self::ACTIVITIES, 'countries' => app(CountryCatalogue::class)->all(),
'requirements' => $requirements, 'documents' => $docs, 'review_fingerprints' => $record ? $this->reviewFingerprints($record) : [],
'affected_reviews' => array_values(array_column(array_filter($steps,fn ($s) => $s['fintech_review_required'] ?? false), 'code')),
'limits' => ['Fintech é caracterização do investimento, não nova categoria jurídica ou autorização.', 'Preparação de orçamento, tecnologia, documentos e parceiros pode avançar em paralelo.', 'Países de operação não alteram país mestre, origem, nacionalidade ou residências.', 'Capitais mínimos, taxas, prazos e licenças específicos permanecem por determinar sem disposição e período aplicáveis.']];
}
}
+1
View File
@@ -41,6 +41,7 @@ final class InterestWorkflow
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) { return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id); $locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
abort_unless(app(ScopedPortalAdministration::class)->interest($actor,$locked),403);
$from = $locked->status; $from = $locked->status;
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null; $actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction $followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
+109 -15
View File
@@ -18,6 +18,7 @@ class InvestmentCatalogue
public function filters(Request $request): array public function filters(Request $request): array
{ {
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'], $filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
'opportunity_id' => ['nullable', 'integer', 'min:1'], 'opportunity_id' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'], 'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'], 'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
@@ -26,13 +27,31 @@ class InvestmentCatalogue
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'], 'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'], 'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'],
'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined'], 'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined'],
'maturity_level' => ['nullable', 'integer', 'between:1,6'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'], 'maturity_level' => ['nullable', 'integer', 'between:1,8'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'], 'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])], 'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'], 'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'], 'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'],
'association_type' => ['nullable', 'in:'.implode(',', array_keys(OpportunityClassification::TARGETS))],
'association_target' => ['nullable', 'string', 'max:80'],
'association_state' => ['nullable', 'in:'.implode(',', OpportunityClassification::STATES)],
'association_purpose' => ['nullable', 'in:'.implode(',', array_keys(OpportunityClassification::PURPOSES))],
'authority_id' => ['nullable', 'uuid'], 'chain_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid'],
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
'publication_state' => ['nullable', 'in:published'],
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]); 'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
app(InvestmentGeography::class)->selection($filters); app(InvestmentGeography::class)->selection($filters);
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
throw \Illuminate\Validation\ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
}
if (\Illuminate\Support\Str::isUuid($filters['association_target'])) {
$filters[$alias] = $filters['association_target'];
unset($filters['association_type'], $filters['association_target']);
}
}
return $filters; return $filters;
} }
@@ -44,6 +63,7 @@ class InvestmentCatalogue
public function query(array $filters): Builder public function query(array $filters): Builder
{ {
$query = Opportunity::published()->with('sector:id,name,slug'); $query = Opportunity::published()->with('sector:id,name,slug');
$associated = $this->publicAssociatedIds($filters);
if (($filters['territory_basis'] ?? 'all') === 'direct') { if (($filters['territory_basis'] ?? 'all') === 'direct') {
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))); $query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
} elseif (($filters['territory_basis'] ?? 'all') === 'context') { } elseif (($filters['territory_basis'] ?? 'all') === 'context') {
@@ -85,15 +105,17 @@ class InvestmentCatalogue
} }
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) { foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) {
if (! empty($filters[$field])) { if (! empty($filters[$field])) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links() $legacy = app(InvestmentZones::class)->links()->where('zl.association_type', '<>', 'proximity')
->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id') ->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $category) ->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $category)
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id')); ->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id');
$query->where(fn ($matches) => $matches->whereIn('opportunities.id', $legacy)
->orWhereIn('opportunities.id', $associated[$field] ?? []));
} }
} }
if (! empty($filters['q'])) { if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%'; $term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term) $query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('description', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term)) ->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term))
->orWhereExists(fn ($g) => $g->selectRaw('1')->from('geo_locations as search_location')->whereNull('search_location.deleted_at')->where('search_location.data_classification', 'public') ->orWhereExists(fn ($g) => $g->selectRaw('1')->from('geo_locations as search_location')->whereNull('search_location.deleted_at')->where('search_location.data_classification', 'public')
->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id')) ->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
@@ -107,13 +129,23 @@ class InvestmentCatalogue
->orWhereExists(fn ($c) => $c->selectRaw('1')->from('opportunity_clusters as search_cluster')->whereColumn('search_cluster.opportunity_id', 'opportunities.id')->whereColumn('search_cluster.cluster_id', 'searchable_dossier.cluster_id'))))); ->orWhereExists(fn ($c) => $c->selectRaw('1')->from('opportunity_clusters as search_cluster')->whereColumn('search_cluster.opportunity_id', 'opportunities.id')->whereColumn('search_cluster.cluster_id', 'searchable_dossier.cluster_id')))));
} }
if (! empty($filters['sector'])) { if (! empty($filters['sector'])) {
$query->whereHas('sector', fn ($s) => $s->where('slug', $filters['sector'])); SectorOrganization::constrain($query, $filters['sector']);
} }
foreach (['province', 'district', 'maturity_level'] as $field) { foreach (['province', 'district'] as $field) {
if (! empty($filters[$field])) { if (! empty($filters[$field])) {
$query->where($field, $filters[$field]); $query->where($field, $filters[$field]);
} }
} }
if (! empty($filters['preparation'])) {
OpportunityMaturity::constrainSearch($query, $filters['preparation']);
} elseif (! empty($filters['maturity_level'])) {
// Legacy links predate the eight-stage catalogue: retain their original meaning.
OpportunityMaturity::constrainSearch($query, match ((int) $filters['maturity_level']) {
7 => 'stage:implementation',
8 => 'stage:operational',
default => 'historical:'.$filters['maturity_level'],
});
}
foreach (self::RELATIONS as $relation => [$foreign, $table]) { foreach (self::RELATIONS as $relation => [$foreign, $table]) {
if (! empty($filters[$foreign])) { if (! empty($filters[$foreign])) {
$locationIds = $relation === 'locations' $locationIds = $relation === 'locations'
@@ -134,13 +166,15 @@ class InvestmentCatalogue
continue; continue;
} }
if (in_array($relation, ['clusters', 'corridors'], true)) { if (in_array($relation, ['clusters', 'corridors'], true)) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link') $query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign]) ->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign))); ->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)))
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
} else { } else {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign) $query->where(fn ($matches) => $matches->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at') ->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign))); ->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)))
->orWhereIn('opportunities.id', $associated[$foreign] ?? []));
} }
} }
} }
@@ -164,6 +198,8 @@ class InvestmentCatalogue
if (! empty($filters['before'])) { if (! empty($filters['before'])) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before'])); $query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
} }
if (! empty($filters['category'])) $query->where('opportunity_category', $filters['category']);
app(OpportunityClassification::class)->constrain($query, $filters);
$sort = $filters['sort'] ?? 'recent'; $sort = $filters['sort'] ?? 'recent';
// Monetary sorting stays grouped by currency; no undocumented FX conversion. // Monetary sorting stays grouped by currency; no undocumented FX conversion.
@@ -178,8 +214,15 @@ class InvestmentCatalogue
* @return array<string,mixed> */ * @return array<string,mixed> */
public function references(bool $management = false, array $territoryFilters = []): array public function references(bool $management = false, array $territoryFilters = []): array
{ {
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(), $path = app(InvestmentGeography::class)->selection($territoryFilters);
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug'])]; $result = ['classification' => app(OpportunityClassification::class)->options(),
'preparationOptions' => OpportunityMaturity::searchOptions(),
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
'categories' => OpportunityManagement::CATEGORIES,
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
'sectors' => \App\Models\Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
foreach (self::RELATIONS as $relation => [$foreign, $table]) { foreach (self::RELATIONS as $relation => [$foreign, $table]) {
$query = DB::table($table)->whereNull('deleted_at'); $query = DB::table($table)->whereNull('deleted_at');
if (! $management) { if (! $management) {
@@ -191,18 +234,67 @@ class InvestmentCatalogue
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)); $query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
} }
} }
if (! $management && $path !== [] && $relation !== 'locations') {
$dossiers = InvestmentPortfolioController::visible();
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
$query->whereIn('id', $dossiers->whereNotNull($foreign)->select($foreign));
}
$result[$relation] = $query->orderBy('name')->get(['id', 'name']); $result[$relation] = $query->orderBy('name')->get(['id', 'name']);
} }
$zones = app(InvestmentZones::class)->visible(); $zones = app(InvestmentZones::class)->visible();
if (! $management && $territoryFilters !== []) { if (! $management && $territoryFilters !== []) {
$zones = app(InvestmentZones::class)->search($territoryFilters); // Opportunity words/modalities are not names/categories of zones.
$zones = app(InvestmentZones::class)->search(\Illuminate\Support\Arr::only($territoryFilters,
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
} }
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']); $result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
if (! $management && ($path !== [] || ! empty($territoryFilters['sector']))) {
$scope = \Illuminate\Support\Arr::only($territoryFilters, ['sector','province_id','district_id','admin_post_id','locality_id','include_national']);
$available = ['chain' => [], 'activity' => []];
$this->query($scope)->reorder()->chunkById(200, function ($records) use (&$available) {
foreach ($records as $record) {
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
if (isset($available[$row['target_type']])) $available[$row['target_type']][] = $row['target_id'];
}
foreach (['subsector_id','economic_activity_id'] as $key) {
$id = $record->workflow_context['publication']['taxonomy'][$key] ?? null;
if ($id) $available['activity'][] = $id;
}
}
}, 'opportunities.id', 'id');
foreach ($available as $kind => $ids) {
$result['classification']['targets'][$kind] = collect($result['classification']['targets'][$kind])->whereIn('id', $ids)->values();
}
}
return $result; return $result;
} }
private function publicAssociatedIds(array $filters): array
{
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
$selected = array_filter(array_intersect_key($filters, $kinds));
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) unset($selected[$key]);
}
if ($selected === []) return [];
$ids = [];
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
foreach ($records as $record) {
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') continue;
foreach ($selected as $field => $target) {
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) $ids[$field][] = $record->id;
}
}
}
});
return $ids;
}
private function publicStructureIds(string $relation, string $foreign): \Illuminate\Database\Query\Builder private function publicStructureIds(string $relation, string $foreign): \Illuminate\Database\Query\Builder
{ {
$table = self::RELATIONS[$relation][1]; $table = self::RELATIONS[$relation][1];
@@ -243,6 +335,8 @@ class InvestmentCatalogue
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id') $result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id) ->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id)
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']); ->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
$opportunity = Opportunity::findOrFail($id);
$result['classification'] = $management ? [] : app(OpportunityClassification::class)->publicRows($opportunity);
$result['primary_territory_path'] = app(InvestmentGeography::class)->path(DB::table('opportunities')->where('id', $id)->value('primary_territory_id')); $result['primary_territory_path'] = app(InvestmentGeography::class)->path(DB::table('opportunities')->where('id', $id)->value('primary_territory_id'));
$result['opportunity_locations'] = app(InvestmentRelations::class)->opportunityLocations($id, $management); $result['opportunity_locations'] = app(InvestmentRelations::class)->opportunityLocations($id, $management);
$result['source_evidence'] = app(InvestmentTerritorialTraceability::class)->sources('opportunities', $id); $result['source_evidence'] = app(InvestmentTerritorialTraceability::class)->sources('opportunities', $id);
@@ -313,11 +407,11 @@ class InvestmentCatalogue
DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'território declarado da oportunidade' ELSE 'contexto do projeto associado; implantação da oportunidade por confirmar' END AS basis")]) DB::raw("CASE WHEN o.primary_territory_id=g.id OR EXISTS (SELECT 1 FROM opportunity_locations direct WHERE direct.opportunity_id=o.id AND direct.geo_location_id=g.id) THEN 'território declarado da oportunidade' ELSE 'contexto do projeto associado; implantação da oportunidade por confirmar' END AS basis")])
->map(fn ($area) => ['geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')', ->map(fn ($area) => ['geometry' => json_decode($area->geometry, true), 'title' => $area->title.' — '.$area->name.' ('.$area->basis.')',
'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null, 'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null,
'url' => '/oportunidades/'.$area->slug])->all(); 'url' => '/oportunidades/'.$area->slug.($filters === [] ? '' : '?'.http_build_query($filters))])->all();
$located = 0; $located = 0;
foreach ($records as $record) { foreach ($records as $record) {
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name, $properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug]; 'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
foreach ($relations as $relation => $groups) { foreach ($relations as $relation => $groups) {
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all(); $properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
} }
+7 -1
View File
@@ -117,8 +117,14 @@ class InvestmentRelations
/** @return array<string,mixed> */ /** @return array<string,mixed> */
public function dossier(InvestmentDossier $dossier, bool $management = false): array public function dossier(InvestmentDossier $dossier, bool $management = false): array
{ {
$sourceEvidence = [];
if ($dossier->project_id) {
$sourceEvidence = app(InvestmentTerritorialTraceability::class)->sources('projects', $dossier->project_id);
} elseif ($dossier->cluster_id) {
$sourceEvidence = app(InvestmentTerritorialTraceability::class)->sources('economic_clusters', $dossier->cluster_id);
}
$result = ['locations' => [], 'members' => [], 'clusters' => [], 'chainLinks' => [], 'chains' => [], $result = ['locations' => [], 'members' => [], 'clusters' => [], 'chainLinks' => [], 'chains' => [],
'source_evidence' => app(InvestmentTerritorialTraceability::class)->sources($dossier->project_id ? 'projects' : 'economic_clusters', $dossier->project_id ?? $dossier->cluster_id ?? '')]; 'source_evidence' => $sourceEvidence];
if ($dossier->project_id) { if ($dossier->project_id) {
$result['locations'] = $this->projectLocations($dossier->project_id, $management); $result['locations'] = $this->projectLocations($dossier->project_id, $management);
$memberships = $this->memberships()->where('cp.project_id', $dossier->project_id)->get(['cp.cluster_id', 'cp.role', 'cp.validation_status', 'cp.source_reference']); $memberships = $this->memberships()->where('cp.project_id', $dossier->project_id)->get(['cp.cluster_id', 'cp.role', 'cp.validation_status', 'cp.source_reference']);
@@ -0,0 +1,97 @@
<?php
namespace App\Services;
use App\Models\InvestmentZone;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/** Subordinate documentary records in the existing encrypted park envelope. */
class InvestmentZoneIntegralDetails
{
public const GROUPS = ['titles', 'phases', 'plots', 'occupants', 'observations', 'chains'];
public const EXTRA = [
'titles' => ['kind', 'identifier', 'valid_from', 'valid_until'],
'phases' => ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
'plots' => ['code', 'phase_id', 'area', 'area_unit', 'status', 'geometry_id'],
'occupants' => ['organization_id', 'documentary_name', 'phase_id', 'plot_id', 'status', 'valid_from', 'valid_until'],
'observations' => ['indicator', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
'chains' => ['kind', 'organization_id', 'documentary_name', 'zone_link_id', 'phase_id', 'plot_id'],
];
public const COMMON = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', 'disclosure', 'private_note', 'support_document_ids'];
public function merge(InvestmentZone $zone, array $before, array $input): array
{
abort_if(array_diff(array_keys($input), ['schema_version', 'remove_ids', ...self::GROUPS]), 422, 'Campo da ficha integral desconhecido.');
$rules = ['schema_version' => 'sometimes|in:1', 'remove_ids' => 'sometimes|array:'.implode(',', self::GROUPS)];
foreach (self::GROUPS as $group) {
$rules[$group] = 'sometimes|array|max:200';
$rules[$group.'.*'] = 'array:'.implode(',', [...self::COMMON, ...self::EXTRA[$group]]);
foreach (['id'=>'nullable|uuid','label'=>'required|string|max:300','label_en'=>'nullable|string|max:300','description'=>'nullable|string|max:3000','description_en'=>'nullable|string|max:3000','knowledge'=>'required|in:unknown,documented,disputed','source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500','disclosure'=>'required|boolean','private_note'=>'nullable|string|max:4000','support_document_ids'=>'sometimes|array|max:20','support_document_ids.*'=>'uuid'] as $key=>$rule) $rules[$group.'.*.'.$key]=$rule;
foreach (self::EXTRA[$group] as $key) $rules[$group.'.*.'.$key]=match ($key) {
'organization_id','phase_id','plot_id','zone_link_id','geometry_id'=>'nullable|uuid',
'area'=>'nullable|numeric|min:0|max:999999999999999',
'value'=>'nullable|numeric|between:-999999999999999,999999999999999',
'starts_at','ends_at','valid_from','valid_until','period_start','period_end'=>'nullable|date_format:Y-m-d',
'expansion'=>'nullable|boolean',
default=>'nullable|string|max:2000',
};
$rules['remove_ids.'.$group]='sometimes|array|max:200';$rules['remove_ids.'.$group.'.*']='uuid';
}
$rules['plots.*.area_unit']='nullable|in:ha,m2';
$rules['plots.*.status']='nullable|in:unknown,planned,available_declared,reserved,occupied,construction,inactive';
$rules['phases.*.status']='nullable|in:unknown,planned,construction,operational,suspended,closed';
$rules['occupants.*.status']='nullable|in:unknown,approved,construction,installed,inactive';
$rules['titles.*.kind']='nullable|in:creation,land_use,licence,special_regime,other';
$rules['chains.*.kind']='nullable|in:anchor,supplier,unmet_need,other';
$rules['observations.*.indicator']='required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
$data=Validator::make($input,$rules)->validate();$result=$before;
foreach(self::GROUPS as$group){
$rows=collect($before[$group]??[])->keyBy('id')->all();$remove=$data['remove_ids'][$group]??[];$seen=[];
foreach($data[$group]??[]as$item){
$id=$item['id']??(string)Str::uuid();abort_if(in_array($id,$seen,true)||in_array($id,$remove,true),422,'Identificador repetido ou removido na mesma operação.');$seen[]=$id;
$item=[...($rows[$id]??[]),...$item,'id'=>$id];
if($item['knowledge']!=='unknown')abort_unless(trim($item['source_reference']??'')!=='',422,'Indique a fonte documental ou preserve como desconhecido.');
if($item['knowledge']==='unknown')abort_if(isset($item['value'])||isset($item['area']),422,'Quantidade desconhecida deve permanecer vazia, não zero.');
if($item['knowledge']==='unknown'&&!empty($item['status']))abort_unless($item['status']==='unknown',422,'Situação operacional declarada exige fonte ou indicação de divergência.');
foreach([['starts_at','ends_at'],['valid_from','valid_until'],['period_start','period_end']]as[$a,$b])if(isset($item[$a],$item[$b]))abort_if($item[$b]<$item[$a],422,'Período final anterior ao início.');
if($group==='plots'&&isset($item['area']))abort_unless(!empty($item['area_unit'])&&!empty($item['scope']),422,'Área declarada exige unidade e âmbito.');
if($group==='plots'&&($item['status']??'')==='available_declared')abort_unless($item['knowledge']==='documented'&&!empty($item['source_date']),422,'Disponibilidade declarada exige fonte e data; não é disponibilidade em tempo real.');
if($group==='observations'&&isset($item['value']))abort_unless(!empty($item['unit'])&&!empty($item['period_start'])&&!empty($item['period_end'])&&!empty($item['scope'])&&!empty($item['population']),422,'Indicador numérico exige unidade, período, âmbito e base/população.');
if(!empty($item['organization_id']))abort_unless(DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->exists(),422,'Reutilize uma entidade existente.');
if(!empty($item['geometry_id']))abort_unless(DB::table('investment_zone_geometries')->where('zone_id',$zone->id)->where('geometry_id',$item['geometry_id'])->exists(),422,'Geometria deve estar associada a este parque; limite administrativo não é perímetro.');
if(!empty($item['zone_link_id']))abort_unless(DB::table('investment_zone_links')->where('zone_id',$zone->id)->where('id',$item['zone_link_id'])->exists(),422,'Relação económica deve pertencer a este parque.');
foreach($item['support_document_ids']??[]as$doc)abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d','d.id','=','a.document_id')->where('a.zone_id',$zone->id)->where('d.id',$doc)->whereNull('d.deleted_at')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256')->exists(),422,'Suporte deve estar consultável e associado a este parque.');
$rows[$id]=$item;
}
foreach($remove as$id){abort_unless(isset($rows[$id]),422,'O detalhe a remover não pertence ao parque.');unset($rows[$id]);}
abort_if(count($rows)>200,422,'Limite de detalhes excedido.');$result[$group]=array_values($rows);
}
// References resolve only inside this park, including new items in the same transaction.
foreach(self::GROUPS as$group)foreach($result[$group]as$item){
foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key]))abort_unless(in_array($item[$key],array_column($result[$target],'id'),true),422,'Referência interna inexistente ou de outro parque.');
if(!empty($item['phase_id'])&&!empty($item['plot_id'])){$plot=collect($result['plots'])->firstWhere('id',$item['plot_id']);abort_if(!empty($plot['phase_id'])&&$plot['phase_id']!==$item['phase_id'],422,'Lote e fase não correspondem.');}
}
foreach(['phases','plots']as$group){$codes=[];foreach($result[$group]as$item)if(trim($item['code']??'')!==''){$code=mb_strtolower(trim($item['code']));abort_if(in_array($code,$codes,true),422,'Código interno repetido no parque.');$codes[]=$code;}}
$keys=[];foreach($result['occupants']as$item){$key=implode('|',[$item['organization_id']??$item['documentary_name']??$item['id'],$item['plot_id']??'',$item['valid_from']??'',$item['valid_until']??'']);abort_if(in_array($key,$keys,true),422,'Ocupante/período já registado; reutilize o detalhe.');$keys[]=$key;}
$keys=[];foreach($result['observations']as$item){if(!isset($item['period_start'],$item['period_end']))continue;$key=implode('|',[$item['indicator'],$item['period_start'],$item['period_end'],$item['scope']??'',$item['population']??'',$item['unit']??'',$item['methodology']??'',$item['source_reference']??'',$item['source_date']??'',$item['phase_id']??'',$item['plot_id']??'']);abort_if(in_array($key,$keys,true),422,'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');$keys[]=$key;}
return [...$result,'schema_version'=>1];
}
public function publicData(array $fields): array
{
$public=['schema_version'=>1];
foreach(self::GROUPS as$group){$public[$group]=[];foreach($fields[$group]??[]as$item){
if(!($item['disclosure']??false))continue;
$keys=['id','label','label_en','description','description_en','knowledge','source_reference','source_date','scope',...self::EXTRA[$group]];
$visible=array_intersect_key($item,array_flip($keys));unset($visible['organization_id'],$visible['documentary_name'],$visible['geometry_id'],$visible['zone_link_id']);
if(in_array($group,['occupants','chains'],true)&&!empty($item['organization_id'])){$org=DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->where('data_classification','public')->first();abort_unless($org&&$item['knowledge']==='documented',422,'Divulgar entidade exige cadastro público e fonte; a menção preliminar permanece privada.');$visible['organization_name']=$org->name;}
if($group==='occupants')abort_unless(!empty($visible['organization_name']),422,'Ocupante por identificar permanece privado.');
$public[$group][]=$visible;
}}
// A disclosed item must not leak the identifier of an undisclosed phase or plot.
foreach(self::GROUPS as$group)foreach($public[$group]as&$item)foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key])&&!in_array($item[$key],array_column($public[$target],'id'),true))unset($item[$key]);unset($item);
return $public;
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use App\Models\InvestmentZone;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/** L1 supplement in the same park master; publication never implies land or commercial entitlement. */
class InvestmentZoneOperationalDetails
{
public const MIGRATION = '2026_10_16_140000_add_investment_zone_operational_details';
public const GROUPS = ['responsibilities', 'conditions', 'risks'];
public function installed(): bool { return Schema::hasColumn('investment_zones', 'operational_details'); }
public function stored(InvestmentZone $zone): ?array
{
$raw = $zone->getRawOriginal('operational_details');
return $raw ? json_decode($raw, true, 512, JSON_THROW_ON_ERROR) : null;
}
public function recover(InvestmentZone $zone): array
{
$stored = $this->stored($zone);
if (!$stored) { return ['schema_version'=>1, 'responsibilities'=>[], 'conditions'=>[], 'risks'=>[], 'review'=>[]]; }
try {
if (($stored['schema_version'] ?? null) !== 1) { throw new \RuntimeException('Unsupported supplement'); }
return json_decode(Crypt::decryptString($stored['private_ciphertext']), true, 512, JSON_THROW_ON_ERROR);
} catch (\Throwable $e) {
throw ValidationException::withMessages(['operational_details'=>'Não foi possível recuperar os detalhes privados. Os dados foram preservados; contacte o suporte.']);
}
}
public function publicData(InvestmentZone $zone): array
{
return $this->stored($zone)['public'] ?? [];
}
/** Merge only supplied keys. An absent group/item is preserved; removal requires explicit IDs. */
public function merge(InvestmentZone $zone, array $before, array $input, ?string $operatorId): array
{
abort_unless($zone->category==='industrial_park',422,'O complemento L1 aplica-se à ficha de parques.');
abort_unless($this->installed(),503,'Detalhes L1 ainda não instalados. A ficha pública foi preservada.');
$rules=['integral'=>'sometimes|array','schema_version'=>'sometimes|in:1','responsibilities'=>'sometimes|array|max:40','conditions'=>'sometimes|array|max:60','risks'=>'sometimes|array|max:40',
'remove_ids'=>'sometimes|array:responsibilities,conditions,risks','review'=>'sometimes|array:source_reference,source_date,scope,confidence,last_reviewed_at,next_review_at,private_note',
'review.confidence'=>'nullable|in:unknown,reported,documented,disputed','review.last_reviewed_at'=>'nullable|date_format:Y-m-d','review.next_review_at'=>'nullable|date_format:Y-m-d','review.private_note'=>'nullable|string|max:4000'];
$common='id,label,knowledge,disclosure,source_reference,source_date,scope,private_note,support_document_ids';
foreach(self::GROUPS as $g){
$extra=$g==='responsibilities'?',role,organization_id,documentary_name,private_contact,public_contact,declared_nature,management_model':($g==='conditions'?',value,currency,unit,period,valid_from,valid_until,modality':',risk_type,mitigation,responsible_role,channel,channel_owner');
$rules[$g.'.*']=['array:'.$common.$extra];
foreach(['id'=>'nullable|uuid','label'=>'required|string|max:300','knowledge'=>'required|in:unknown,documented,disputed','disclosure'=>'required|boolean',
'source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500','private_note'=>'nullable|string|max:4000',
'support_document_ids'=>'sometimes|array|max:10','support_document_ids.*'=>'uuid'] as $k=>$r){$rules[$g.'.*.'.$k]=$r;}
$rules['remove_ids.'.$g]='sometimes|array|max:60';$rules['remove_ids.'.$g.'.*']='uuid';
}
foreach(['source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500']as$k=>$r){$rules['review.'.$k]=$r;}
foreach(['role'=>'required|in:owner,promoter,operator,manager','organization_id'=>'nullable|uuid','documentary_name'=>'nullable|string|max:300','private_contact'=>'nullable|string|max:1000','public_contact'=>'nullable|string|max:1000','declared_nature'=>'nullable|string|max:300','management_model'=>'nullable|string|max:500']as$k=>$r){$rules['responsibilities.*.'.$k]=$r;}
foreach(['value'=>'nullable|numeric|min:0','currency'=>'nullable|in:MZN,USD,EUR,ZAR','unit'=>'nullable|string|max:80','period'=>'nullable|string|max:80','valid_from'=>'nullable|date_format:Y-m-d','valid_until'=>'nullable|date_format:Y-m-d','modality'=>'nullable|string|max:300']as$k=>$r){$rules['conditions.*.'.$k]=$r;}
foreach(['risk_type'=>'nullable|string|max:300','mitigation'=>'nullable|string|max:2000','responsible_role'=>'nullable|in:owner,promoter,operator,manager,unknown','channel'=>'nullable|string|max:1000','channel_owner'=>'nullable|in:park,tempo,unknown']as$k=>$r){$rules['risks.*.'.$k]=$r;}
abort_if(array_diff(array_keys($input),['schema_version',...self::GROUPS,'review','remove_ids','integral']),422,'Campo L1 não reconhecido.');
$data=Validator::make($input,$rules)->validate();$result=$before;
foreach(self::GROUPS as $g){
$rows=collect($before[$g] ?? [])->keyBy('id')->all();$removals=$data['remove_ids'][$g] ?? []; $seen=[];
foreach($data[$g] ?? [] as $item){
$id=$item['id'] ?? (string)Str::uuid();
abort_if(in_array($id,$seen,true)||in_array($id,$removals,true),422,'Identificador L1 repetido ou removido na mesma operação.');$seen[]=$id;
$item=[...($rows[$id] ?? []),...$item,'id'=>$id];
if($item['knowledge']==='unknown') { abort_if(isset($item['value']),422,'Valor desconhecido deve permanecer vazio, nunca zero por defeito.'); }
else { abort_unless(trim($item['source_reference'] ?? '')!=='',422,'Identifique a fonte da informação documentada ou divergente.'); }
if($g==='conditions' && isset($item['value'])){
abort_unless(trim($item['currency'] ?? '')!=='' && trim($item['unit'] ?? '')!=='' && trim($item['scope'] ?? '')!=='',422,'Uma tarifa numérica exige moeda, unidade/base e âmbito; pode manter o valor desconhecido.');
}
if($g==='conditions' && isset($item['valid_from'],$item['valid_until'])){
abort_if($item['valid_until']<$item['valid_from'],422,'O fim da vigência é anterior ao início; preserve datas desconhecidas como desconhecidas.');
}
if($g==='risks' && !empty($item['channel']) && ($item['channel_owner'] ?? 'unknown')==='park'){
abort_unless($item['knowledge']==='documented' && trim($item['source_reference'] ?? '')!=='',422,'O canal próprio do parque exige fonte; pode manter o canal desconhecido ou usar o apoio da Tempo identificado como tal.');
}
if($g==='responsibilities'){
$org=$item['organization_id'] ?? null;
if($org){abort_unless(DB::table('organizations')->where('id',$org)->whereNull('deleted_at')->exists(),422,'Reutilize uma entidade existente ou mantenha a menção documental preliminar.');}
if($item['role']==='operator' && $org){
$operator=$operatorId;
abort_unless($operator===$org,422,'O operador é a associação canónica da ficha; não crie outro no suplemento.');
}
}
foreach($item['support_document_ids'] ?? []as$document){
abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d','d.id','=','a.document_id')->where('a.zone_id',$zone->id)->where('d.id',$document)
->whereNull('d.deleted_at')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256')->exists(),422,'Selecione suporte consultável já associado à ficha; a publicação do anexo é independente.');
}
$rows[$id]=$item;
}
foreach($removals as$id){abort_unless(isset($rows[$id]),422,'Detalhe a remover não pertence à ficha.');unset($rows[$id]);}
abort_if(count($rows)>($g==='conditions'?60:40),422,'Limite de detalhes por grupo excedido.');
$result[$g]=array_values($rows);
}
$pairs=[];foreach($result['responsibilities'] as$item){$key=$item['role'].'|'.($item['organization_id'] ?? $item['documentary_name'] ?? $item['id']);abort_if(in_array($key,$pairs,true),422,'A mesma entidade/função já está registada; reutilize o detalhe existente.');$pairs[]=$key;}
if(array_key_exists('review',$data)){$result['review']=[...($before['review'] ?? []),...$data['review']];}
if(array_key_exists('integral',$data)){$result['integral']=app(InvestmentZoneIntegralDetails::class)->merge($zone,$before['integral'] ?? [],$data['integral']);}
$result['schema_version']=1;
return $result;
}
public function pack(array $fields): array
{
$public=[];
foreach(self::GROUPS as$g){
$public[$g]=[];
foreach($fields[$g] ?? []as$item){
if(!($item['disclosure'] ?? false)){continue;}
$keys=['label','knowledge','source_reference','source_date','scope'];
if($g==='conditions'){$keys=[...$keys,'value','currency','unit','period','valid_from','valid_until','modality'];}
if($g==='risks'){$keys=[...$keys,'risk_type','mitigation','responsible_role','channel','channel_owner'];}
$visible=array_intersect_key($item,array_flip($keys));
if($g==='responsibilities'){
$org=empty($item['organization_id'])?null:DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->where('data_classification','public')->first();
abort_unless($org && $item['knowledge']==='documented',422,'Divulgação de função exige entidade pública existente e fundamento; menção preliminar continua privada.');
$visible=[...$visible,'role'=>$item['role'],'organization_name'=>$org->name,'public_contact'=>$item['public_contact'] ?? null,'declared_nature'=>$item['declared_nature'] ?? null,'management_model'=>$item['management_model'] ?? null];
}
$public[$g][]=$visible;
}
}
if(isset($fields['integral'])){$public['integral']=app(InvestmentZoneIntegralDetails::class)->publicData($fields['integral']);}
$public['review']=array_intersect_key($fields['review'] ?? [],array_flip(['source_reference','source_date','scope','confidence','last_reviewed_at','next_review_at']));
return ['schema_version'=>1,'public'=>$public,'private_ciphertext'=>Crypt::encryptString(json_encode($fields,JSON_THROW_ON_ERROR))];
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
class InvestmentZoneOperationalDetailsInstallation
{
public const SOURCE='investment-zone-details-installation';
public function files(): array
{
return ['app/Models/InvestmentZone.php', 'app/Http/Controllers/InvestmentZoneController.php', 'app/Services/InvestmentZones.php', 'app/Services/InvestmentZoneOperationalProfile.php', 'resources/js/pages/investment/zone.tsx', 'resources/js/pages/investment/zones.tsx', 'routes/investment-zones.php', 'resources/js/components/investment-zone-installation.tsx', 'app/Services/InvestmentZoneOperationalDetails.php', 'app/Services/InvestmentZoneOperationalDetailsInstallation.php', 'resources/js/components/investment-zone-operational-details.tsx', 'database/migrations/2026_10_16_140000_add_investment_zone_operational_details.php'];
}
public function fingerprint(): string
{
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
}
private function authorize(User $actor,bool $write=false): void
{
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
}
private function evidence(array $target,string $code): array
{
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
$path=storage_path('app/private/investmoz-v2/park-details/readiness.json');
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===InvestmentZoneOperationalDetails::MIGRATION;
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
}
public function preview(User $actor): array
{
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
$ledgerCount=DB::table('migrations')->where('migration',InvestmentZoneOperationalDetails::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('investment_zones','operational_details');
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='operational_details'");
$correct=$shape && $shape->data_type==='jsonb' && $shape->is_nullable==='YES';
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
if(!app(InvestmentZoneOperationalProfile::class)->installed() || DB::table('migrations')->where('migration',InvestmentZoneOperationalProfile::MIGRATION)->count()!==1){$reasons[]='Base 130000 ausente ou divergente; instalar/verificar antes de L1.';}
$state=['target'=>$target,'migration'=>InvestmentZoneOperationalDetails::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
}
public function apply(User $actor,array $input): array
{
$this->authorize($actor,true);
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
return DB::transaction(function()use($actor,$data){
DB::select('SELECT pg_advisory_xact_lock(161026,140000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
if(!$plan['installed']){
config(['investment-zone-details.authenticated_installation'=>true]);
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.InvestmentZoneOperationalDetails::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
finally{config(['investment-zone-details.authenticated_installation'=>false]);}
}
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'investment-zone-profile','entity_id'=>null,'actor_user_id'=>$actor->id,
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
@@ -0,0 +1,143 @@
<?php
namespace App\Services;
use App\Models\InvestmentZone;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/** Editorial preparation in the existing master. No operational/land entitlement is inferred. */
class InvestmentZoneOperationalProfile
{
public const MIGRATION = '2026_10_16_130000_add_investment_zone_editorial_draft';
public const FIELDS = ['code','category','name','name_en','description','description_en','province','district','operator_id','legal_source_id',
'physical_category','legal_regime','operational_status','development_status','availability_status','area_components','source_evidence',
'area_value','area_unit','aliases','activities','resources','data_as_of','sources_consulted_at','parent_zone_id','historical_territory'];
public const DETAIL_PUBLIC = ['id','name','status','source_reference','source_date','kind','scope','capacity_type','capacity_value','capacity_unit','focus','economic_activity_id'];
public function installed(): bool { return Schema::hasColumn('investment_zones', 'editorial_draft'); }
public function draft(InvestmentZone $zone): ?array
{
$raw = $zone->getRawOriginal('editorial_draft');
if (! $raw) { return null; }
try { $data = json_decode(Crypt::decryptString($raw), true, 512, JSON_THROW_ON_ERROR); }
catch (\Throwable $e) { throw ValidationException::withMessages(['editorial_draft'=>'Não foi possível recuperar a preparação privada. Os dados foram preservados; contacte o suporte.']); }
abort_unless(($data['schema_version'] ?? null) === 1 && is_array($data['fields'] ?? null), 409, 'Formato de preparação incompatível; os dados foram preservados.');
return $data;
}
public function workingVersion(InvestmentZone $zone): int { return (int) ($this->draft($zone)['working_version'] ?? $zone->version_no); }
public function nextVersion(InvestmentZone $zone): int
{
return max((int) $zone->version_no, (int) DB::table('investment_zone_revisions')->where('zone_id',$zone->id)->max('version_no')) + 1;
}
public function management(InvestmentZone $zone): array
{
$draft = $this->draft($zone);
return [...$zone->toArray(), ...($draft['fields'] ?? []), 'version_no'=>$draft['working_version'] ?? $zone->version_no,
'public_version_no'=>$zone->version_no, 'base_public_version'=>$draft['base_public_version'] ?? $zone->version_no,
'has_private_draft'=>$draft !== null, 'profile_available'=>$this->installed(),
'operational_details'=>($draft['fields']['operational_details'] ?? app(InvestmentZoneOperationalDetails::class)->recover($zone)),
'details_available'=>app(InvestmentZoneOperationalDetails::class)->installed()];
}
public function publicDetails(array $record): array
{
unset($record['editorial_draft'], $record['operational_details']);
foreach (['activities','resources'] as $key) {
if (isset($record[$key])) { $record[$key] = array_map(fn ($item)=>array_intersect_key($item,array_flip(self::DETAIL_PUBLIC)), $record[$key]); }
}
return $record;
}
private function mergeDetails(string $zoneId,array $before, array $after): array
{
$result=[];
foreach ($after as $item) {
$old = collect($before)->first(fn($b)=>isset($item['id']) ? ($b['id'] ?? null)===$item['id'] : ($b['name'] ?? null)===($item['name'] ?? null));
$item=[...($old ?? []), ...$item];
$item['id'] ??= (string) Str::uuid();
if (isset($item['capacity_value']) && empty($item['capacity_unit'])) { throw ValidationException::withMessages(['resources'=>'Indique a unidade da capacidade declarada; pode deixar o valor desconhecido.']); }
if (!empty($item['economic_activity_id'])) {
abort_unless(trim((string)($item['source_reference'] ?? '')) !== '' && DB::table('economic_activities')->where('id',$item['economic_activity_id'])->where('data_classification','public')->whereNull('deleted_at')->exists(),422,'A correspondência CAE exige referência publicada e fundamento explícito.');
}
foreach ($item['support_document_ids'] ?? [] as $document) {
abort_unless(DB::table('investment_zone_attachments')->where('zone_id',$zoneId)->where('document_id',$document)->exists(),422,'Selecione suporte privado já associado a esta ficha.');
$d=DB::table('documents')->where('id',$document)->whereNull('deleted_at')->first();
abort_unless($d && $d->status==='active' && $d->malware_scan_status==='clean' && trim($d->sha256)===$d->malware_scanned_sha256,422,'Documento de suporte ainda não consultável.');
}
$result[]=$item;
}
return $result;
}
/** Called with zone row locked by InvestmentZones. Only this encrypted column is written. */
public function prepare(InvestmentZone $zone,array $data,int $actor): InvestmentZone
{
abort_unless($this->installed(),503,'A preparação privada requer a instalação nominal da ficha de parques. A publicação anterior foi preservada.');
abort_unless((int)$data['version_no']===$this->workingVersion($zone),409,'A preparação mudou; recupere a versão atual antes de guardar.');
$previous=$this->draft($zone);
$base=$previous['fields'] ?? array_intersect_key($zone->toArray(),array_flip(self::FIELDS));
$fields=[...$base,...array_intersect_key($data,array_flip(self::FIELDS))];
$details=app(InvestmentZoneOperationalDetails::class);
if (array_key_exists('operational_details',$data)) {
$fields['operational_details']=$details->merge($zone,$base['operational_details'] ?? $details->recover($zone),$data['operational_details'],$fields['operator_id'] ?? null);
} elseif ($details->stored($zone) && !array_key_exists('operational_details',$fields)) {
$fields['operational_details']=$details->recover($zone);
}
$details=app(InvestmentZoneOperationalDetails::class);
if (array_key_exists('operational_details',$data)) {
$fields['operational_details']=$details->merge($zone,$base['operational_details'] ?? $details->recover($zone),$data['operational_details'],$fields['operator_id'] ?? null);
} elseif ($details->stored($zone) && !array_key_exists('operational_details',$fields)) {
$fields['operational_details']=$details->recover($zone);
}
foreach (['activities','resources'] as $key) { if (array_key_exists($key,$data)) { $fields[$key]=$this->mergeDetails($zone->id,$base[$key] ?? [],$data[$key]); } }
$draft=['schema_version'=>1,'base_public_version'=>$previous['base_public_version'] ?? (int)$zone->version_no,
'working_version'=>$this->nextVersion($zone),'fields'=>$fields,'actor_id'=>$actor,'prepared_at'=>now()->toIso8601String()];
DB::table('investment_zones')->where('id',$zone->id)->update(['editorial_draft'=>Crypt::encryptString(json_encode($draft,JSON_THROW_ON_ERROR))]);
$this->snapshot($zone,$draft['working_version'],$actor,'profile_prepared',['public'=>[...$zone->toArray(),'operational_details'=>$details->stored($zone)],'draft'=>$draft]);
return $zone->fresh();
}
/** Apply only inside the publication transaction; a failed validation rolls everything back. */
public function promote(InvestmentZone $zone,int $version): void
{
$draft=$this->draft($zone);
abort_unless($version===$this->workingVersion($zone),409,'A preparação mudou; recupere a versão atual antes de publicar.');
if (!$draft) { return; }
abort_unless((int)$draft['base_public_version']===(int)$zone->version_no,409,'A publicação base mudou. Reconcilie a preparação antes de publicar; ambos os estados foram preservados.');
$zone->fill(array_intersect_key($draft['fields'],array_flip(self::FIELDS)));
if (array_key_exists('operational_details',$draft['fields'])) {
$zone->setAttribute('operational_details',app(InvestmentZoneOperationalDetails::class)->pack($draft['fields']['operational_details']));
}
// Existing resource support remains in the encrypted snapshot; L1 private fields are durable.
foreach(['activities','resources'] as $key) { $zone->setAttribute($key,$this->publicDetails([$key=>$zone->$key ?? []])[$key]); }
$zone->setAttribute('editorial_draft',null);
}
public function reconcile(InvestmentZone $zone,int $working,int $public,int $actor): InvestmentZone
{
$draft=$this->draft($zone);
abort_unless($draft && $working===(int)$draft['working_version'] && $public===(int)$zone->version_no,409,'Versões alteradas; recupere a ficha pública e a preparação antes de reconciliar.');
abort_if((int)$draft['base_public_version']===$public,422,'A preparação já corresponde à versão pública atual.');
$draft['base_public_version']=$public;$draft['working_version']=$this->nextVersion($zone);$draft['actor_id']=$actor;$draft['prepared_at']=now()->toIso8601String();
DB::table('investment_zones')->where('id',$zone->id)->update(['editorial_draft'=>Crypt::encryptString(json_encode($draft,JSON_THROW_ON_ERROR))]);
$this->snapshot($zone,$draft['working_version'],$actor,'profile_reconciled',['public'=>[...$zone->toArray(),'operational_details'=>app(InvestmentZoneOperationalDetails::class)->stored($zone)],'draft'=>$draft]);
return $zone->fresh();
}
public function snapshot(InvestmentZone $zone,int $version,int $actor,string $action,array $data): void
{
$json=json_encode($data,JSON_THROW_ON_ERROR);$hash=hash('sha256',$json);
DB::table('investment_zone_revisions')->insert(['id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'version_no'=>$version,
'actor_id'=>$actor,'action'=>$action,'snapshot'=>Crypt::encryptString($json),'sha256'=>$hash]);
DB::table('audit_events')->insert(['source_system'=>'investment-zones','entity_type'=>'investment_zones','entity_id'=>$zone->id,
'actor_user_id'=>$actor,'action'=>$action,'after_data'=>json_encode(['version_no'=>$version,'sha256'=>$hash],JSON_THROW_ON_ERROR)]);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class InvestmentZonePathContext
{
public const NOTICE='Referência para preparação; não constitui reserva de lote, confirmação de disponibilidade ou autorização de instalação.';
public function context(string $id,int $version): array
{
$zone=app(InvestmentZones::class)->visible()->where('category','industrial_park')->findOrFail($id);
abort_unless((int)$zone->version_no===$version,409,'A ficha pública mudou. Consulte a versão atual e confirme novamente; a seleção anterior não foi substituída.');
return ['zone_id'=>$zone->id,'consulted_public_version'=>(int)$zone->version_no,'title'=>$zone->name,'href'=>'/zonas/'.$zone->id,
'province'=>$zone->province,'district'=>$zone->district,'notice'=>self::NOTICE];
}
public function input(array $input): array
{
return Validator::make($input,['zone_id'=>'required|uuid','consulted_public_version'=>'required|integer|min:1'])->validate();
}
public function attach(User $actor,string $id,array $input): void
{
abort_unless(app(InvestorPath::class)->available(),404);
$data=Validator::make($input,['zone_id'=>'required|uuid','consulted_public_version'=>'required|integer|min:1','version'=>'required|integer|min:1','confirm'=>'required|accepted'])->validate();
DB::transaction(function()use($actor,$id,$data){
$desk=app(VirtualDesk::class);$case=$desk->case($actor,$id,true,true);
abort_if($case->closed_at,409,'O dossier está encerrado.');
abort_unless(DB::table('investor_journeys')->where('id',$case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(),409,'Este dossier conserva outro roteiro.');
$payload=$desk->decode($case->payload);
foreach($payload['investor_path']['zone_contexts'] ?? [] as $existing){
if($existing['zone_id']===$data['zone_id'] && (int)$existing['consulted_public_version']===(int)$data['consulted_public_version']){return;}
}
abort_unless((int)$case->version===(int)$data['version'],409,'O dossier mudou; recupere a versão atual.');
// Lock the public record while checking the consulted version and recording its reference.
DB::table('investment_zones')->where('id',$data['zone_id'])->lockForUpdate()->firstOrFail();
$context=$this->context($data['zone_id'],(int)$data['consulted_public_version']);
abort_unless(count($payload['investor_path']['zone_contexts'] ?? [])<100,422,'Limite de referências deste dossier atingido.');
$payload['investor_path']['zone_contexts'][]=[...$context,'selected_at'=>now()->toIso8601String()];
DB::table('desk_cases')->where('id',$id)->update(['payload'=>$desk->encode($payload),'version'=>$case->version+1,'updated_at'=>now()]);
$desk->event($desk->case($actor,$id),$actor,'park_reference_selected',['zone_id'=>$context['zone_id'],'consulted_public_version'=>$context['consulted_public_version'],'scope'=>'preparation_reference_only']);
});
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
class InvestmentZoneProfileInstallation
{
public const SOURCE='investment-zone-profile-installation';
public function files(): array
{
return ['app/Models/InvestmentZone.php','app/Services/InvestmentZones.php','app/Services/InvestmentZoneOperationalProfile.php',
'app/Services/InvestmentZonePathContext.php','app/Services/InvestmentZoneProfileInstallation.php','app/Http/Controllers/InvestmentZoneController.php',
'app/Http/Controllers/InvestorPathController.php','app/Services/InvestorPath.php','routes/investment-zones.php','routes/investor-path.php',
'resources/js/pages/investment/zone.tsx','resources/js/pages/investment/zones.tsx','resources/js/pages/investor-path/index.tsx',
'resources/js/pages/investor-path/show.tsx','resources/js/components/investment-zone-installation.tsx',
'database/migrations/'.InvestmentZoneOperationalProfile::MIGRATION.'.php'];
}
public function fingerprint(): string
{
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
}
private function authorize(User $actor,bool $write=false): void
{
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
}
private function evidence(array $target,string $code): array
{
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
$path=storage_path('app/private/investmoz-v2/park-profile/readiness.json');
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===InvestmentZoneOperationalProfile::MIGRATION;
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
}
public function preview(User $actor): array
{
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
$ledgerCount=DB::table('migrations')->where('migration',InvestmentZoneOperationalProfile::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('investment_zones','editorial_draft');
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='editorial_draft'");
$correct=$shape && $shape->data_type==='text' && $shape->is_nullable==='YES';
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
$state=['target'=>$target,'migration'=>InvestmentZoneOperationalProfile::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
}
public function apply(User $actor,array $input): array
{
$this->authorize($actor,true);
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
return DB::transaction(function()use($actor,$data){
DB::select('SELECT pg_advisory_xact_lock(161026,130000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
if(!$plan['installed']){
config(['investment-zone-profile.authenticated_installation'=>true]);
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.InvestmentZoneOperationalProfile::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
finally{config(['investment-zone-profile.authenticated_installation'=>false]);}
}
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'investment-zone-profile','entity_id'=>null,'actor_user_id'=>$actor->id,
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
+26 -5
View File
@@ -93,10 +93,16 @@ class InvestmentZones
{ {
return DB::transaction(function () use ($id, $data, $actor) { return DB::transaction(function () use ($id, $data, $actor) {
$zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone; $zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone;
if ($id && $zone->category === 'industrial_park') {
$prepared=app(InvestmentZoneOperationalProfile::class)->prepare($zone,$data,$actor);
$this->storePendingLocations($zone,$data['locations'] ?? [],$actor);
return $prepared;
}
abort_if($id && (int) $zone->version_no !== (int) $data['version_no'], 409, 'Versão alterada. Recarregue antes de guardar.'); abort_if($id && (int) $zone->version_no !== (int) $data['version_no'], 409, 'Versão alterada. Recarregue antes de guardar.');
$version = $id ? (int) $zone->version_no + 1 : 1; $version = $id ? (int) $zone->version_no + 1 : 1;
$locations = $data['locations'] ?? []; $locations = $data['locations'] ?? [];
unset($data['locations'], $data['version_no']); unset($data['locations'], $data['version_no']);
abort_if(array_key_exists('operational_details',$data),422,'Prepare L1 numa ficha de parque existente; não cria outro cadastro.');
$zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null, $zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null,
'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save(); 'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save();
foreach ($locations as $location) { foreach ($locations as $location) {
@@ -117,7 +123,9 @@ class InvestmentZones
{ {
return DB::transaction(function () use ($id, $version, $actor) { return DB::transaction(function () use ($id, $version, $actor) {
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail(); $zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.'); $profile = app(InvestmentZoneOperationalProfile::class);
if ($zone->category === 'industrial_park') { $profile->promote($zone,$version); }
else { abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.'); }
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first(); $source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
$evidence = $zone->source_evidence ?? []; $evidence = $zone->source_evidence ?? [];
$officialEvidence = collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional'], true) $officialEvidence = collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional'], true)
@@ -143,7 +151,7 @@ class InvestmentZones
->where('zl.zone_id', $id)->where('zl.validation_status', 'validated')->where('g.data_classification', 'public')->whereNull('g.deleted_at') ->where('zl.zone_id', $id)->where('zl.validation_status', 'validated')->where('g.data_classification', 'public')->whereNull('g.deleted_at')
->whereIn('g.id', app(InvestmentGeography::class)->publicReferences()->select('id'))->exists(); ->whereIn('g.id', app(InvestmentGeography::class)->publicReferences()->select('id'))->exists();
abort_unless($publicLocation, 422, 'Seleccione uma província ou distrito existente e público.'); abort_unless($publicLocation, 422, 'Seleccione uma província ou distrito existente e público.');
$zone->fill(['version_no' => $version + 1, 'reviewer_id' => $actor, 'publication_status' => 'published', $zone->fill(['version_no' => $zone->category === 'industrial_park' ? $profile->nextVersion($zone) : $version + 1, 'reviewer_id' => $actor, 'publication_status' => 'published',
'validation_status' => 'validated', 'published_at' => now()])->save(); 'validation_status' => 'validated', 'published_at' => now()])->save();
$this->snapshot($zone, $actor, 'published'); $this->snapshot($zone, $actor, 'published');
@@ -155,8 +163,9 @@ class InvestmentZones
{ {
return DB::transaction(function () use ($id, $version, $actor) { return DB::transaction(function () use ($id, $version, $actor) {
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail(); $zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada.'); $profile=app(InvestmentZoneOperationalProfile::class);
$zone->fill(['version_no' => $version + 1, 'publication_status' => 'suspended'])->save(); abort_if(($zone->category === 'industrial_park' ? $profile->workingVersion($zone) : (int)$zone->version_no) !== $version, 409, 'Versão alterada.');
$zone->fill(['version_no' => $zone->category === 'industrial_park' ? $profile->nextVersion($zone) : $version + 1, 'publication_status' => 'suspended'])->save();
$this->snapshot($zone, $actor, 'suspended'); $this->snapshot($zone, $actor, 'suspended');
return $zone; return $zone;
@@ -189,7 +198,7 @@ class InvestmentZones
private function snapshot(InvestmentZone $zone, int $actor, string $action): void private function snapshot(InvestmentZone $zone, int $actor, string $action): void
{ {
$json = $zone->toJson(JSON_THROW_ON_ERROR); $json = json_encode([...$zone->toArray(),'operational_details'=>app(InvestmentZoneOperationalDetails::class)->stored($zone)],JSON_THROW_ON_ERROR);
DB::table('investment_zone_revisions')->insert(['id' => (string) Str::uuid(), 'zone_id' => $zone->id, DB::table('investment_zone_revisions')->insert(['id' => (string) Str::uuid(), 'zone_id' => $zone->id,
'version_no' => $zone->version_no, 'actor_id' => $actor, 'action' => $action, 'version_no' => $zone->version_no, 'actor_id' => $actor, 'action' => $action,
'snapshot' => Crypt::encryptString($json), 'sha256' => hash('sha256', $json)]); 'snapshot' => Crypt::encryptString($json), 'sha256' => hash('sha256', $json)]);
@@ -197,4 +206,16 @@ class InvestmentZones
'entity_id' => $zone->id, 'actor_user_id' => $actor, 'action' => $action, 'entity_id' => $zone->id, 'actor_user_id' => $actor, 'action' => $action,
'after_data' => json_encode(['version_no' => $zone->version_no, 'sha256' => hash('sha256', $json)], JSON_THROW_ON_ERROR)]); 'after_data' => json_encode(['version_no' => $zone->version_no, 'sha256' => hash('sha256', $json)], JSON_THROW_ON_ERROR)]);
} }
/** Existing explicit territorial control: new associations remain pending, never promoted with the profile. */
private function storePendingLocations(InvestmentZone $zone,array $locations,int $actor): void
{
foreach($locations as $location){
DB::table('investment_zone_locations')->insertOrIgnore([
'id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'geo_location_id'=>$location['geo_location_id'],
'scope_type'=>$location['scope_type'] ?? 'administrative','source_reference'=>$location['source_reference'],
'legal_source_id'=>$location['legal_source_id'] ?? null,'validation_status'=>'pending','editor_id'=>$actor,'version_no'=>1,'created_at'=>now(),'updated_at'=>now(),
]);
}
}
} }
+413
View File
@@ -0,0 +1,413 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Context belongs to the existing encrypted dossier. Sources remain read-only. */
final class InvestorContext
{
public const MIGRATION = '2026_10_16_150000_create_investor_navigation_preferences';
public const SOURCE = 'investor-context';
public const FIELDS = ['project_title', 'project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'];
public function __construct(private readonly VirtualDesk $desk) {}
public function installed(): bool
{
return Schema::hasTable('investor_navigation_preferences');
}
public function state(\stdClass $case): array
{
$payload = $this->desk->decode($case->payload);
return $payload['investor_path']['context'] ?? ['revision' => 0, 'selection' => [],
'fields' => ['project_title' => $case->title], 'provenance' => ['project_title' => ['kind' => 'dossier', 'id' => $case->id, 'version' => $case->version]], 'review_steps' => []];
}
public function dependencyHash(array $selection): string
{
return hash('sha256', json_encode(Arr::sortRecursive($selection), JSON_THROW_ON_ERROR));
}
public function reference(string $key): array
{
[$kind,$id] = array_pad(explode(':', $key, 2), 2, '');
$fields = [];
$href = '';
$title = '';
$version = null;
$documents = [];
$visibility = 'public';
$state = null;
if ($kind === 'opportunity') {
abort_unless(ctype_digit($id), 422, 'Identificador de oportunidade inválido.');
$o = Opportunity::with('sector')->findOrFail((int) $id);
$published = Opportunity::published()->whereKey($o->id)->exists();
if (!$published) {
abort_unless(request()->user() && $o->status !== 'archived' && app(PortalProfileAccess::class)->canView(request()->user(), $o), 404, 'Ficha privada indisponível neste âmbito.');
$visibility = 'private';
$state = app(PortalProfileAccess::class)->state($o);
}
if (request()->user()) $documents = app(OpportunityLibrarySupport::class)->snapshot(request()->user(), $o);
$draft = !$published ? app(OpportunityManagement::class)->values($o) : [];
$title = $draft['canonical']['official_title'] ?? $o->title;
$href = $published ? '/oportunidades/'.$o->slug : '/minhas-oportunidades/'.$o->id.'/view';
$version = $o->management_version;
$fields = ['project_title' => $title, 'project_summary' => $draft['canonical']['executive_summary'] ?? $o->summary];
if ($o->sector) {
$fields['sector_id'] = (string) $o->sector_id;
$fields['sector'] = $o->sector->name;
}
// Text labels do not establish a canonical territorial correspondence.
if ($o->province) {
$fields['province'] = $o->province;
}
if ($o->district) {
$fields['district'] = $o->district;
}
if ($o->primary_territory_id) {
$fields = [...$fields, ...$this->territoryFields($o->primary_territory_id)];
}
} elseif ($kind === 'business') {
abort_unless(config('existing-business.enabled') && Str::isUuid($id), 404);
$o = ExistingBusiness::published()->with('sector')->findOrFail($id);
$title = $o->public_title;
$href = '/negocios/'.$o->public_slug;
$version = $o->version_no;
$fields = ['project_title' => $o->public_title, 'project_summary' => $o->objective];
if ($o->sector) {
$fields['sector_id'] = (string) $o->sector_id;
$fields['sector'] = $o->sector->name;
}
$location = DB::table('existing_business_locations')->where('existing_business_id', $id)->where('is_public', true)->where('is_primary', true)->first();
if ($location) {
$leaf = $location->province_id;
foreach (['district', 'admin_post', 'locality'] as $level) {
if (in_array($location->precision_level, array_slice(['province', 'district', 'admin_post', 'locality', 'exact'], array_search($level, ['province', 'district', 'admin_post', 'locality', 'exact'])), true) && $location->{$level.'_id'}) {
$leaf = $location->{$level.'_id'};
}
}
if ($leaf) {
$fields = [...$fields, ...$this->territoryFields($leaf)];
}
}
} elseif ($kind === 'sector') {
abort_unless(ctype_digit($id), 422);
$s = Sector::where('is_active', true)->findOrFail((int) $id);
$title = $s->name;
$href = SectorOrganization::href($s->slug);
$version = $s->updated_at?->toIso8601String();
$fields = ['sector_id' => (string) $s->id, 'sector' => $s->name];
} elseif ($kind === 'territory') {
abort_unless(Str::isUuid($id), 422);
$t = app(InvestmentGeography::class)->publicReferences()->whereIn('location_type', array_values(InvestmentGeography::FIELDS))->where('id', $id)->first();
abort_unless($t, 404, 'Território público indisponível.');
$title = $t->name;
$version = $t->version_no;
$href = '/oportunidades?'.$t->location_type.'_id='.$id;
$fields = $this->territoryFields($id);
} elseif ($kind === 'park') {
abort_unless(Str::isUuid($id), 422);
$p = app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->findOrFail($id);
$title = $p->name;
$version = $p->version_no;
$href = '/zonas/'.$id;
if ($p->primary_territory_id) {
$fields = $this->territoryFields($p->primary_territory_id);
}
} else {
abort(422, 'Tipo de referência inválido.');
}
$fields = array_filter($fields, fn ($v) => is_scalar($v) && trim((string) $v) !== '');
$record = ['key' => $key, 'kind' => $kind, 'id' => $id, 'title' => $title, 'version' => $version, 'href' => $href, 'fields' => $fields];
if ($documents || $visibility === 'private') $record += ['documents' => $documents, 'visibility' => $visibility, 'state' => $state];
return [...$record, 'sha256' => hash('sha256', json_encode($record, JSON_THROW_ON_ERROR))];
}
private function territoryFields(string $id): array
{
$path = app(InvestmentGeography::class)->path($id);
$fields = [];
$names = [];
foreach ($path as $n) {
if (! in_array($n->location_type, array_values(InvestmentGeography::FIELDS), true)) {
continue;
}
$fields[$n->location_type.'_id'] = $n->id;
$names[] = $n->name;
if (in_array($n->location_type, ['province', 'district'], true)) {
$fields[$n->location_type] = $n->name;
}
}
if ($names) {
$fields['location'] = implode(' / ', $names);
}
return $fields;
}
public function options(string $query = ''): array
{
$query = mb_substr(trim($query), 0, 120);
$items = [];
foreach (Opportunity::published()->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get(['id', 'title']) as $o) {
$items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title, 'kind' => 'opportunity'];
}
if (request()->user()) {
$private = app(PortalProfileAccess::class)->scope(Opportunity::query(), request()->user())->where('status', '!=', 'published')->where('status', '!=', 'archived')->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get();
foreach ($private as $o) if (app(PortalProfileAccess::class)->canView(request()->user(), $o)) $items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title.' — preparação privada', 'kind' => 'opportunity'];
}
if (config('existing-business.enabled')) {
foreach (ExistingBusiness::published()->when($query, fn ($q) => $q->where('public_title', 'ilike', '%'.$query.'%'))->orderBy('public_title')->limit(51)->get(['id', 'public_title']) as $o) {
$items[] = ['key' => 'business:'.$o->id, 'title' => $o->public_title, 'kind' => 'business'];
}
}
return ['opportunities' => $items, 'search_limited' => count($items) > 50, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
'parks' => app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->orderBy('name')->get(['id', 'name', 'version_no'])];
}
public function current(User $actor): array
{
if (! $this->installed()) {
return ['installed' => false, 'focus' => null];
}
$p = DB::table('investor_navigation_preferences')->where('user_id', $actor->id)->first();
if (! $p) {
return ['installed' => true, 'focus' => null];
}
try {
$case = $this->desk->case($actor, $p->case_id);
app(InvestorPath::class)->view($actor, $case->id);
} catch (ModelNotFoundException $e) {
return ['installed' => true, 'focus' => null, 'message' => 'O contexto anterior já não está disponível para esta conta.'];
} catch (HttpException $e) {
if (in_array($e->getStatusCode(), [403, 404, 409], true)) {
return ['installed' => true, 'focus' => null, 'message' => 'O contexto anterior já não está disponível para esta conta.'];
}throw $e;
}
if ($case->closed_at) {
return ['installed' => true, 'focus' => null];
}
return ['installed' => true, 'focus' => ['case_id' => $case->id, 'step_code' => $p->step_code, 'version' => (int) $p->version]];
}
public function focus(User $actor, array $input): array
{
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
$data = Validator::make($input, ['case_id' => 'required|uuid', 'step_code' => ['nullable', 'regex:/^S(0[1-9]|1[0-9])$/'], 'version' => 'required|integer|min:0'])->validate();
return DB::transaction(function () use ($actor, $data) {
DB::table('users')->where('id', $actor->id)->lockForUpdate()->firstOrFail();
$case = $this->desk->case($actor, $data['case_id']);
abort_if($case->closed_at, 409);
app(InvestorPath::class)->view($actor, $case->id);
$old = DB::table('investor_navigation_preferences')->where('user_id', $actor->id)->first();
$step = $data['step_code'] ?? null;
if ($old && $old->case_id === $case->id && $old->step_code === $step) {
return $this->current($actor);
}
abort_unless((int) ($old->version ?? 0) === $data['version'], 409, 'O contexto em foco mudou noutro dispositivo; recupere-o antes de escolher novamente.');
DB::table('investor_navigation_preferences')->updateOrInsert(['user_id' => $actor->id], ['case_id' => $case->id, 'step_code' => $step, 'version' => (int) ($old->version ?? 0) + 1, 'updated_at' => now()]);
return $this->current($actor);
});
}
private function input(array $input): array
{
abort_if(array_diff(array_keys($input), ['version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', '_token']), 422, 'Campo de controlo desconhecido.');
return Validator::make($input, ['version' => 'required|integer|min:1', 'selection' => 'present|array:opportunity,sector,territory,park',
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:project_title,project_summary', 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
}
public function preview(User $actor, string $id, array $input): array
{
$data = $this->input($input);
$case = $this->desk->case($actor, $id, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão atual.');
app(InvestorPath::class)->view($actor, $id);
$old = $this->state($case);
$selection = $old['selection'];
foreach ($data['selection'] as $slot => $key) {
if ($key === null || $key === '') {
unset($selection[$slot]);
continue;
}
$ref = $this->reference($key);
$expected = $slot === 'opportunity' ? ['opportunity', 'business'] : [$slot];
abort_unless(in_array($ref['kind'], $expected, true), 422, 'Referência incompatível com a dimensão.');
$selection[$slot] = $ref;
}
// A new opportunity may propose its explicitly stored sector; it never matches names.
if (isset($data['selection']['opportunity']) && ! array_key_exists('sector', $data['selection']) && isset($selection['opportunity']['fields']['sector_id'])) {
if (Sector::where('is_active', true)->whereKey($selection['opportunity']['fields']['sector_id'])->exists()) {
$selection['sector'] = $this->reference('sector:'.$selection['opportunity']['fields']['sector_id']);
}
}
$proposed = [];
$origins = [];
foreach (['opportunity', 'sector', 'park', 'territory'] as $slot) {
if (in_array($slot, ['park', 'territory'], true) && array_intersect(array_keys($selection[$slot]['fields'] ?? []), array_keys(InvestmentGeography::FIELDS))) {
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'] as $key) {
unset($proposed[$key],$origins[$key]);
}
}
foreach ($selection[$slot]['fields'] ?? [] as $key => $value) {
$proposed[$key] = (string) $value;
$origins[$key] = Arr::except($selection[$slot], ['fields']);
}
}
$fields = $old['fields'];
$provenance = $old['provenance'];
$changed = [];
$kept = [];
$replaced = [];
foreach ($data['declarations'] ?? [] as $key => $value) {
$fields[$key] = (string) ($value ?? '');
$provenance[$key] = ['kind' => 'process_declaration', 'actor_id' => $actor->id, 'context_revision' => $old['revision'] + 1];
}
foreach ($proposed as $key => $value) {
if (($fields[$key] ?? '') === '' || (($provenance[$key]['kind'] ?? '') !== 'process_declaration' && ($provenance[$key]['kind'] ?? '') !== 'dossier') || in_array($key, $data['replace_fields'] ?? [], true)) {
if (($fields[$key] ?? null) !== $value) {
$replaced[] = ['field' => $key, 'before' => $fields[$key] ?? null, 'after' => $value];
}$fields[$key] = $value;
$provenance[$key] = $origins[$key];
} else {
$kept[] = ['field' => $key, 'value' => $fields[$key], 'proposed' => $value];
}
}
// Remove inherited subordinate geography only when its source was actually replaced.
foreach ($fields as $key => $value) {
if (! array_key_exists($key, $proposed) && in_array($key, ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'sector_id', 'sector'], true) && isset($provenance[$key]['key'])) {
unset($fields[$key],$provenance[$key]);
}
}
$replaced = [];
foreach (array_unique([...array_keys($old['fields']), ...array_keys($fields)]) as $key) {
if (($old['fields'][$key] ?? null) !== ($fields[$key] ?? null)) {
$replaced[] = ['field' => $key, 'before' => $old['fields'][$key] ?? null, 'after' => $fields[$key] ?? null];
}
}
foreach (['opportunity', 'sector', 'territory', 'park'] as $slot) {
if (($old['selection'][$slot] ?? null) !== ($selection[$slot] ?? null)) {
$changed[] = $slot;
}
}
$dependencyChanged = $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection);
$payload = $this->desk->decode($case->payload);
$results = $payload['investor_path']['results'] ?? [];
$requests = DB::table('desk_requests')->where('case_id', $id)->orderBy('id')->get(['id', 'status', 'protocol', 'version'])->all();
$steps = $dependencyChanged ? array_values(array_unique([...(array_intersect($changed, ['opportunity', 'sector']) ? ['S02', 'S03', 'S04', 'S08', 'S12', 'S13', 'S14', 'S15', 'S17'] : []), ...(array_intersect($changed, ['territory', 'park']) ? ['S08', 'S09', 'S10', 'S11', 'S17'] : [])])) : [];
$plan = ['case_id' => $id, 'version' => (int) $case->version, 'revision' => (int) $old['revision'], 'selection' => $selection, 'fields' => $fields, 'provenance' => $provenance,
'updated' => $replaced, 'maintained' => $kept, 'changed_dimensions' => $changed, 'dependent_results' => (int) $case->user_id === $actor->id && $dependencyChanged ? array_map(fn ($r) => ['id' => $r['id'], 'engine' => $r['engine']], $results) : [],
'requests' => $requests, 'review_steps' => $steps, 'dependency_changed' => $dependencyChanged, 'documents_preserved' => DB::table('desk_documents')->where('case_id', $id)->count(),
'notice' => 'Não confirma incentivos, licenças, disponibilidade de terra, reserva ou autorização. Submissões e decisões anteriores mantêm o conteúdo enviado.'];
$hash = hash_hmac('sha256', json_encode(Arr::sortRecursive([$actor->id, $data, $plan]), JSON_THROW_ON_ERROR), config('app.key'));
return [...$plan, 'preview_hash' => $hash];
}
public function commit(User $actor, string $id, array $input): array
{
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
$control = Validator::make($input, ['preview_hash' => 'required|string|size:64', 'operation_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
$this->input($input);
$requestHash = hash('sha256', json_encode(Arr::sortRecursive($input), JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $id, $input, $control, $requestHash) {
DB::select('SELECT pg_advisory_xact_lock(161026,hashtext(?))', [$control['operation_key']]);
$receipt = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $control['operation_key'])->first();
if ($receipt) {
$saved = json_decode($receipt->after_data, true);
abort_unless((int) $receipt->actor_user_id === $actor->id && ($saved['case_id'] ?? '') === $id && hash_equals($saved['request_hash'], $requestHash), 409, 'Chave de operação usada com outro conteúdo ou ator.');
$this->desk->case($actor, $id, true);
return [...$saved['result'], 'replayed' => true];
}
$case = $this->desk->case($actor, $id, true, true);
$before = $this->state($case);
$plan = $this->preview($actor, $id, $input);
abort_unless(hash_equals($plan['preview_hash'], $control['preview_hash']), 409, 'O dossier ou uma fonte mudou desde a prévia; compare novamente.');
if (! $plan['changed_dimensions'] && ! $plan['updated'] && empty($input['declarations']) && empty($input['replace_fields'])) {
$result = ['case_id' => $id, 'version' => (int) $case->version, 'revision' => $before['revision'], 'changed' => false, 'replayed' => false];
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'desk_cases', 'entity_id' => $id, 'actor_user_id' => $actor->id, 'correlation_id' => $control['operation_key'], 'action' => 'context_unchanged', 'data_classification' => 'restricted', 'after_data' => json_encode(['case_id' => $id, 'request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
return $result;
}
$payload = $this->desk->decode($case->payload);
$revision = $before['revision'] + 1;
$review = $before['review_steps'] ?? [];
foreach ($plan['review_steps'] as $step) {
$review[$step] = ['revision' => $revision, 'reason' => 'O contexto mudou; reveja os pressupostos e a evidência aplicável.'];
}
$context = ['revision' => $revision, 'selection' => $plan['selection'], 'fields' => $plan['fields'], 'provenance' => $plan['provenance'], 'review_steps' => $review,
'dependency_hash' => $this->dependencyHash($plan['selection']), 'updated_at' => now()->toIso8601String(), 'updated_by' => $actor->id];
if ($plan['dependency_changed']) {
foreach ($payload['investor_path']['results'] ?? [] as $i => $r) {
$payload['investor_path']['results'][$i] = [...$r, 'context_state' => 'review_required', 'context_invalidated_revision' => $revision, 'context_invalidated_at' => now()->toIso8601String()];
}
}
$payload['investor_path']['context'] = $context;
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'title' => $context['fields']['project_title'] ?? $case->title, 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'investment_context_changed', ['before' => $before, 'after' => $context, 'affected_result_ids' => array_column($plan['dependent_results'], 'id'), 'preserved_request_ids' => array_column($plan['requests'], 'id')]);
$result = ['case_id' => $id, 'version' => (int) $case->version + 1, 'revision' => $revision, 'replayed' => false];
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'desk_cases', 'entity_id' => $id, 'actor_user_id' => $actor->id, 'correlation_id' => $control['operation_key'], 'action' => 'context_changed', 'data_classification' => 'restricted', 'after_data' => json_encode(['case_id' => $id, 'request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
return $result;
}, 3);
}
public function view(User $actor, string $id): array
{
$case = $this->desk->case($actor, $id);
abort_unless($this->desk->owns($actor, $case, false) || $actor->can('manage-portal'), 403);
$ctx = $this->state($case);
$path = app(InvestorPath::class)->view($actor, $id);
$simulatorRevision = null;
if ((int) $case->user_id === $actor->id && $case->simulation_id) {
$draftVersion = DB::table('simulation_form_drafts')->where('id', $case->simulation_id)->where('owner_user_id', $actor->id)->whereNull('deleted_at')->value('version_no');
foreach (array_reverse($path['results']) as $result) {
if (($result['draft_id'] ?? null) === $case->simulation_id && ($result['draft_version'] ?? null) === $draftVersion) {
$simulatorRevision = $result['context_revision'] ?? null;
break;
}
}
}
return ['simulator_context_revision' => $simulatorRevision, 'case' => $path['case'], 'context' => $ctx, 'steps' => array_map(fn ($s) => Arr::only($s, ['code', 'title', 'state', 'context_review_required']), $path['steps']),
'can_write' => $path['canWrite'], 'next' => $path['next'], 'results' => $path['results'], 'requests' => $path['requests'],
'prefill' => $this->prefill($ctx), 'notice' => 'A seleção apoia a preparação e não confirma benefícios, licenças, direitos ou disponibilidade.'];
}
public function prefill(array $ctx): array
{
$f = $ctx['fields'];
$sim = Arr::only($f, ['project_title', 'project_summary', 'sector_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id']);
return ['simulator' => $sim, 'land' => array_filter(['project_reference' => $f['project_title'] ?? null, 'activity' => $f['sector'] ?? null, 'purpose' => $f['project_summary'] ?? null, 'parcels' => [Arr::only($f, array_keys(InvestmentGeography::FIELDS))]], fn ($v) => $v !== null),
'desk' => array_filter(['title' => $f['project_title'] ?? null, 'territory_id' => $f['locality_id'] ?? $f['admin_post_id'] ?? $f['district_id'] ?? $f['province_id'] ?? null, 'location_source' => isset($f['province_id']) ? 'Referência consultada no contexto v'.($ctx['revision'] ?? 0).': '.($f['location'] ?? 'território identificado').'. Não confirma disponibilidade.' : null, 'description' => $f['project_summary'] ?? null, 'sector' => $f['sector'] ?? null, ...Arr::only($f, array_keys(InvestmentGeography::FIELDS))], fn ($v) => $v !== null),
'submission' => array_filter(['sector' => $f['sector'] ?? null, 'objective' => $f['project_summary'] ?? null, 'location' => $f['location'] ?? null], fn ($v) => $v !== null)];
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final class InvestorContextConsumers
{
public function requestRevision(\stdClass $row): int
{
$desk = app(VirtualDesk::class);
if ($row->submitted_snapshot) {
return (int) ($desk->decode($row->submitted_snapshot)['investment_context']['revision'] ?? 0);
}
foreach (DB::table('desk_events')->where('request_id', $row->id)->whereIn('action', ['draft_created', 'request_context_reviewed'])->orderByDesc('event_order')->get(['payload']) as $e) {
$p = $desk->decode($e->payload);
if (isset($p['investment_context_revision'])) {
return (int) $p['investment_context_revision'];
}
}
return 0;
}
public function landRevision(string $id): int
{
foreach (DB::table('land_assistance_events')->where('case_id', $id)->orderByDesc('id')->get(['metadata']) as $e) {
$p = json_decode($e->metadata ?? '{}', true);
if (isset($p['investment_context_revision'])) {
return (int) $p['investment_context_revision'];
}
}
return 0;
}
public function submissionRevision(string $id): int
{
foreach (DB::table('audit_events')->where('source_system', 'investment-submission')->where('entity_id', $id)->orderByRaw("coalesce((after_data->>'version')::integer,0) desc")->orderByDesc('created_at')->orderByDesc('id')->get(['after_data']) as $e) {
$p = json_decode($e->after_data ?? '{}', true);
if (isset($p['investment_context_revision'])) {
return (int) $p['investment_context_revision'];
}
}
return 0;
}
public function assertReviewed(User $actor, string $id, array $input, int $bound): int
{
$case = app(VirtualDesk::class)->case($actor, $id, true, true);
$current = app(InvestorContext::class)->state($case)['revision'];
if ($current !== $bound) {
abort_unless(filter_var($input['context_reviewed'] ?? false, FILTER_VALIDATE_BOOLEAN) && (int) ($input['context_revision'] ?? -1) === $current, 422, 'O contexto do investimento mudou. Confira os campos preservados ou aplique a nova seleção e confirme a revisão antes de submeter.');
}
return $current;
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\HttpException;
/** Installation adds a navigation preference, never an investment register or permission. */
final class InvestorContextInstallation
{
public const SOURCE = 'investor-context-installation';
public function files(): array
{
return ['app/Http/Controllers/InvestmentSubmissionController.php', 'app/Http/Controllers/InvestorContextController.php', 'app/Http/Controllers/LandAssistanceController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Http/Controllers/VirtualDeskController.php', 'app/Http/Requests/StoreLandAssistanceCaseRequest.php', 'app/Services/InvestorContext.php', 'app/Services/InvestorContextConsumers.php', 'app/Services/InvestorContextInstallation.php', 'app/Services/InvestorPath.php', 'app/Services/VirtualDesk.php', 'database/migrations/2026_10_16_150000_create_investor_navigation_preferences.php', 'resources/js/app.tsx', 'resources/js/components/catalogue-navigation.tsx', 'resources/js/components/dossier-navigation-context.tsx', 'resources/js/components/dossier-prefill.tsx', 'resources/js/components/navigation-context.tsx', 'resources/js/components/portal-grouped-menu.tsx', 'resources/js/components/simulation-form.tsx', 'resources/js/layouts/app/app-sidebar-layout.tsx', 'resources/js/layouts/portal-navigation.tsx', 'resources/js/lib/investor-context.ts', 'resources/js/lib/investor-path.ts', 'resources/js/lib/portal-navigation.ts', 'resources/js/pages/desk/request.tsx', 'resources/js/pages/investment/business-opportunity.tsx', 'resources/js/pages/investment/catalogue.tsx', 'resources/js/pages/investment/detail.tsx', 'resources/js/pages/investment/submission.tsx', 'resources/js/pages/investment/zone.tsx', 'resources/js/pages/investor-path/context-installation.tsx', 'resources/js/pages/investor-path/context-start.tsx', 'resources/js/pages/investor-path/context.tsx', 'resources/js/pages/investor-path/show.tsx', 'resources/js/pages/land-assistance/form.tsx', 'resources/js/pages/portal/services.tsx', 'resources/js/pages/portal/why-invest.tsx', 'routes/investment.php', 'routes/investor-path.php', 'routes/web.php'];
}
public function fingerprint(): string
{
$files = [];
foreach ($this->files() as $p) {
$files[$p] = hash_file('sha256', base_path($p));
}
foreach (File::allFiles(public_path('build')) as $p) {
$files['public/build/'.$p->getRelativePathname()] = hash_file('sha256', $p->getPathname());
}ksort($files);
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
}
private function authorize(User $actor, bool $write = false): void
{
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'), 403);
if ($write) {
app(PortalProfileInstallation::class)->authorize($actor, true);
}
}
public function preview(User $actor): array
{
$this->authorize($actor);
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$code = $this->fingerprint();
$table = Schema::hasTable('investor_navigation_preferences');
$ledger = DB::table('migrations')->where('migration', InvestorContext::MIGRATION)->count();
$consistent = ($table && $ledger === 1) || (! $table && $ledger === 0);
$reasons = [];
if (! $consistent) {
$reasons[] = 'Esquema e registo da migration divergentes; reconciliar sem recriar dados.';
}
try {
$this->authorize($actor, true);
} catch (HttpException $e) {
$reasons[] = $e->getMessage() ?: 'Elevação existente necessária para a instalação excecional.';
}
$isolated = app()->environment('testing') && config('database.connections.pgsql.host') === '127.0.0.1' && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test') && ! config('database.connections.pgsql.url');
$proofPath = storage_path('app/private/investmoz-v2/investor-context/readiness.json');
$proof = is_file($proofPath) ? json_decode(file_get_contents($proofPath), true) : [];
$fresh = ! app()->environment('testing') && ($proof['code_hash'] ?? '') === $code && ($proof['target'] ?? []) === $target && ($proof['authorization_record'] ?? '') !== '' && ($proof['migration'] ?? '') === InvestorContext::MIGRATION
&& ($proof['restore_verified'] ?? false) && ($proof['restored_boot_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && strtotime($proof['verified_at'] ?? '') <= time();
foreach (['dump', 'files'] as $kind) {
$p = $proof[$kind.'_path'] ?? '';
$fresh = $fresh && is_file($p) && hash_equals($proof[$kind.'_sha256'] ?? '', hash_file('sha256', $p));
}
if (! $isolated && ! $fresh) {
$reasons[] = 'Autorização específica, hashes e backup/restauro/arranque frescos desta candidata necessários.';
}
$state = ['target' => $target, 'migration' => InvestorContext::MIGRATION, 'code_hash' => $code, 'installed' => $table && $ledger === 1, 'consistent' => $consistent, 'ready' => ! $reasons, 'reasons' => $reasons, 'business_records_changed' => 0];
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
}
public function apply(User $actor, array $input): array
{
$this->authorize($actor, true);
abort_if(array_diff(array_keys($input), ['hash', 'operation_key', 'confirm', '_token']), 422, 'Migration, ator ou caminho arbitrário recusado.');
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'operation_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
return DB::transaction(function () use ($actor, $data) {
DB::select('SELECT pg_advisory_xact_lock(161026,150000)');
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$old = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $data['operation_key'])->first();
if ($old) {
$saved = json_decode($old->after_data, true);
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($saved['request_hash'], $hash), 409);
return [...$saved['result'], 'replayed' => true];
}
$plan = $this->preview($actor);
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Prévia alterada.');
abort_unless($plan['ready'], 422, implode(' ', $plan['reasons']));
if (! $plan['installed']) {
config(['investor-context.authenticated_installation' => true]);
try {
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.InvestorContext::MIGRATION.'.php', '--force' => true]) === 0, 500);
} finally {
config(['investor-context.authenticated_installation' => false]);
}
}
abort_unless(Schema::hasTable('investor_navigation_preferences'), 500);
$result = ['migration' => InvestorContext::MIGRATION, 'changed' => ! $plan['installed'], 'business_records_changed' => 0, 'replayed' => false];
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'navigation-preference', 'actor_user_id' => $actor->id, 'correlation_id' => $data['operation_key'], 'action' => 'install', 'after_data' => json_encode(['request_hash' => $hash, 'result' => $result], JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
+367
View File
@@ -0,0 +1,367 @@
<?php
namespace App\Services;
use App\Models\CrmTask;
use App\Models\LandAssistanceCase;
use App\Models\SimulationFormDraft;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
final class InvestorPath
{
public function __construct(private readonly VirtualDesk $desk) {}
public function available(): bool
{
return (bool) config('investor-path.enabled') && $this->desk->installed()
&& Schema::hasColumn('investor_journeys', 'path_definition_id') && Schema::hasColumn('journey_steps', 'path_detail');
}
/** @param array<string,mixed> $input */
public function create(User $actor, array $input): string
{
abort_unless($this->available(), 404);
return DB::transaction(function () use ($actor, $input): string {
$case = $this->desk->createCase($actor, $input);
$this->initialize($actor, $case->id);
return $case->id;
});
}
public function initialize(User $actor, string $id): void
{
abort_unless($this->available(), 404);
DB::transaction(function () use ($actor, $id): void {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
if ($case->journey_id) {
$existing = DB::table('investor_journeys')->where('id', $case->journey_id)->firstOrFail();
// Never convert or renumber a saved portfolio/legacy journey implicitly.
abort_unless($existing->path_definition_id !== null, 409, 'O percurso existente foi preservado; a conversão exige uma correspondência explícita.');
return;
}
$version = DB::table('questionnaire_versions')->where('id', config('investor-path.definition_id'))
->where('code', 'investor-path-19')->where('status', 'published')->firstOrFail();
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
InvestorPathDefinition::validate($definition);
$journey = (string) Str::uuid();
DB::table('investor_journeys')->insert(['id' => $journey, 'investor_id' => $case->investor_id, 'user_id' => $actor->id,
'status' => 'started', 'path_definition_id' => $version->id, 'source_system' => 'investor-path', 'data_classification' => 'confidential']);
foreach ($definition['steps'] as $step) {
DB::table('journey_steps')->insert(['id' => (string) Str::uuid(), 'journey_id' => $journey, 'step_code' => $step['code'],
'sequence_no' => $step['sequence'], 'status' => 'pending', 'source_system' => 'investor-path', 'data_classification' => 'confidential',
'path_detail' => $this->desk->encode(['state' => 'not_started'])]);
}
DB::table('desk_cases')->where('id', $id)->update(['journey_id' => $journey, 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'investor_path_started', ['journey_id' => $journey, 'definition_id' => $version->id, 'source_sha256' => $definition['source_sha256']]);
});
}
/** @return array<string,mixed> */
public function view(User $actor, string $id): array
{
abort_unless($this->available(), 404);
$case = $this->desk->case($actor, $id);
$journey = DB::table('investor_journeys')->where('id', $case->journey_id)->whereNull('deleted_at')->firstOrFail();
abort_unless($journey->path_definition_id !== null, 409, 'Este dossier conserva o seu roteiro original.');
$version = DB::table('questionnaire_versions')->where('id', $journey->path_definition_id)->firstOrFail();
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
$payload = $this->desk->decode($case->payload);
$path = $payload['investor_path'] ?? [];
$context = app(InvestorContext::class)->state($case);
$facts = $path['facts'] ?? ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
$records = DB::table('journey_steps')->where('journey_id', $journey->id)->whereNull('deleted_at')->get()->keyBy('step_code');
$steps = [];
foreach ($definition['steps'] as $step) {
$row = $records->get($step['code']);
abort_unless($row !== null, 409, 'Etapa em falta; reparar a instalação sem reconstruir o histórico.');
$detail = $this->desk->decode($row->path_detail);
$value = $step['branch'] ? ($facts[$step['branch']] ?? 'unknown') : 'yes';
$applicable = $value === 'unknown' ? 'undetermined' : ($value === 'no' ? 'not_needed_for_preparation' : 'applicable');
$state = $value === 'no' ? 'dispensed' : $detail['state'];
$steps[] = [...$step, 'id' => $row->id, 'version' => $row->version_no, 'state' => $state, 'saved_state' => $detail['state'],
'applicability' => $applicable, 'reason' => $value === 'no' ? ($path['fact_reasons'][$step['branch']] ?? '') : ($detail['reason'] ?? ''),
'detail' => $detail, 'preparation_allowed' => $value !== 'no',
'action_gaps' => []];
}
foreach ($steps as &$contextStep) {
$contextStep['context_review_required'] = isset($context['review_steps'][$contextStep['code']]) && ($contextStep['detail']['context_dependency_hash'] ?? null) !== ($context['dependency_hash'] ?? null);
if ($contextStep['context_review_required'] && in_array($contextStep['state'], ['completed', 'approved', 'ready_to_submit'], true)) {
$contextStep['state'] = 'correction_required';
$contextStep['reason'] = 'O contexto mudou. O ato/avanço anterior foi preservado; reveja o fundamento aplicável ao novo contexto.';
}
}
unset($contextStep);
$steps = app(FintechInvestment::class)->adjustSteps($payload, $steps);
$byCode = collect($steps)->keyBy('code');
foreach ($steps as &$step) {
foreach ($step['dependencies'] as $action => $dependencies) {
$step['action_gaps'][$action] = array_values(array_filter($dependencies, function ($code) use ($byCode) {
$dependency = $byCode->get($code);
// Branch dispensation is not evidence of any legal permission.
return ! in_array($dependency['state'], ['completed', 'approved'], true);
}));
}
}
unset($step);
foreach ($steps as &$step) {
if (in_array($step['state'], ['completed', 'submitted'], true)
&& count(array_filter($step['action_gaps'])) > 0) {
$step['state'] = 'correction_required';
$step['reason'] = 'Uma dependência desta acção foi reaberta; reveja o avanço. O registo original foi preservado.';
}
}
unset($step);
$owner = $this->desk->owns($actor, $case);
$manager = $actor->can('manage-portal');
$requests = DB::table('desk_requests')->where('case_id', $id)
->when(! $owner && ! $manager, fn ($q) => $q->where('analyst_id', $actor->id))
->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'version', 'submitted_snapshot'])->map(function ($row) use ($context) {
$revision = app(InvestorContextConsumers::class)->requestRevision($row);
return ['id' => $row->id, 'status' => $row->status, 'protocol' => $row->protocol, 'version' => $row->version, 'context_revision' => $revision,
'context_state' => $context['revision'] !== $revision ? ($row->submitted_snapshot ? 'historical_submission' : 'review_required') : 'current'];
});
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.case_id', $id)->whereNull('d.deleted_at')
->when(! $owner && ! $manager, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', $requests->pluck('id'))))
->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status']);
// Only the private draft owner can receive the financial snapshot/result. Dossier access alone is insufficient.
$results = (int) $case->user_id === $actor->id ? ($path['results'] ?? []) : [];
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
$landCase = (int) $case->user_id === $actor->id
? LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id) : null;
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $path['fact_reasons'] ?? [],
'fintech' => ($owner || $manager) && (isset($path['fintech']) || collect($path['sector_contexts'] ?? [])->contains(fn ($s) => in_array($s['slug'], ['fintech', 'tecnologias-de-informacao', 'mercado-financeiro'], true)) || collect($path['content_sources'] ?? [])->contains('return_href', '/tech-fintech')) ? app(FintechInvestment::class)->view($payload, $steps) : null,
'canWrite' => $owner && ! $case->closed_at, 'canReview' => $manager && (int) $case->user_id !== $actor->id && ! $case->closed_at,
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => '#'.$next['code']] : null,
'investment_context' => ($owner || $manager) ? $context : null,
'results' => $results, 'requests' => $requests, 'documents' => $documents,
'zone_contexts' => ($owner || $manager) ? ($path['zone_contexts'] ?? []) : [],
'sector_contexts' => ($owner || $manager) ? ($path['sector_contexts'] ?? []) : [],
'content_sources' => ($owner || $manager) ? ($path['content_sources'] ?? []) : [],
'tasks' => DB::table('tasks')->where('desk_case_id', $id)
->whereNull('deleted_at')
->when(! $owner && ! $manager, fn ($q) => $q->where('assignee_user_id', $actor->id))
->get(['id', 'title', 'status', 'version_no', 'due_at', 'assignee_user_id']),
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'definition'])
->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title']]),
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '') : null,
'desk' => '/balcao-virtual/dossiers/'.$id, 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id,
'land' => (int) $case->user_id === $actor->id ? ($landCase ? '/investidor/terra-duat/'.$landCase->id : '/investidor/terra-duat/novo?context='.$id) : null]];
}
/** @param array<string,mixed> $input */
public function facts(User $actor, string $id, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1',
'land_needed' => ['required', Rule::in(['yes', 'no', 'unknown'])], 'external_funding' => ['required', Rule::in(['yes', 'no', 'unknown'])],
'viability' => ['required', Rule::in(['unknown', 'proceed', 'reformulate', 'archive'])],
'reason' => 'required|string|min:3|max:3000'])->validate();
DB::transaction(function () use ($actor, $id, $data): void {
$case = $this->writable($actor, $id, $data['version']);
$payload = $this->desk->decode($case->payload);
foreach (['land_needed', 'external_funding', 'viability'] as $key) {
$payload['investor_path']['facts'][$key] = $data[$key];
$payload['investor_path']['fact_reasons'][$key] = $data['reason'];
}
$this->savePayload($case, $payload);
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_applicability_declared', $data);
});
}
/** @param array<string,mixed> $input */
public function stage(User $actor, string $id, string $code, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'state' => ['required', Rule::in(array_diff(InvestorPathDefinition::STATES, ['dispensed']))],
'reason' => 'required|string|min:3|max:3000', 'action' => ['required', Rule::in(['prepare', 'submit', 'execute', 'operate', 'review', 'record_external'])],
'document_id' => 'nullable|uuid', 'authority' => 'nullable|string|max:200', 'reference' => 'nullable|string|max:300',
'context_revision' => 'nullable|integer|min:0', 'context_reviewed' => 'nullable|boolean', 'decision_date' => 'nullable|date_format:Y-m-d|before_or_equal:today'])->validate();
DB::transaction(function () use ($actor, $id, $code, $data): void {
$case = $this->desk->case($actor, $id, false, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão actual.');
$view = $this->view($actor, $id);
$step = $this->findStep($view, $code);
abort_unless($step !== null && $step['preparation_allowed'], 422, 'Etapa dispensada de preparação; altere os pressupostos com fundamento.');
$state = $data['state'];
abort_if($state === 'completed' && ($step['fintech_review_required'] ?? false), 422, 'Os pressupostos Fintech desta revisão mudaram; preserve a preparação e atualize a conferência antes da conclusão.');
$internal = in_array($state, ['reviewing', 'correction_required'], true);
$external = in_array($state, ['approved', 'rejected', 'expired'], true);
$scope = 'investor_preparation';
if ($internal || $external) {
abort_unless($view['canReview'], 403, 'A conferência interna exige um responsável distinto do promotor.');
abort_unless($data['action'] === ($external ? 'record_external' : 'review'), 422);
$scope = $external ? 'external_document_recorded' : 'internal_validation';
} else {
abort_unless($view['canWrite'], 403);
abort_unless(! in_array($data['action'], ['review', 'record_external'], true), 422);
if ($state === 'submitted') {
abort_unless($data['action'] === 'submit' && ! empty($data['reference']), 422, 'Registe a referência da submissão; guardar não equivale a submeter.');
}
}
if ($external || $data['action'] !== 'prepare') {
abort_unless(empty($step['action_gaps'][$data['action']] ?? []), 422,
'Dependências reais da acção: '.implode(', ', $step['action_gaps'][$data['action']] ?? []));
}
if ($external) {
abort_unless(! empty($data['document_id']) && ! empty($data['authority']) && ! empty($data['reference']) && ! empty($data['decision_date']), 422, 'Registe documento, entidade, referência e data do acto externo.');
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)
->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256']);
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento de decisão ainda não consultável.');
}
// Completion of a legal/finance/operation action requires the corresponding evidence; preparation can proceed independently.
if ($state === 'completed' && in_array($code, ['S07', 'S08', 'S10', 'S11', 'S14', 'S15', 'S17', 'S18'], true)) {
abort_unless(($step['saved_state'] ?? '') === 'approved' && in_array($data['action'], ['execute', 'operate'], true), 422, 'Conclusão operacional exige acto externo documentado; use preparação enquanto aguarda.');
}
abort_if($state === 'completed' && ($step['context_review_required'] ?? false) && (! (bool) ($data['context_reviewed'] ?? false) || ($data['context_revision'] ?? -1) !== ($view['investment_context']['revision'] ?? 0)), 422, 'O contexto desta etapa exige nova conferência fundamentada; o registo anterior permanece no histórico.');
$detail = [...$data, 'context_dependency_hash' => $view['investment_context']['dependency_hash'] ?? null, 'fintech_fingerprint' => $view['fintech']['review_fingerprints'][$code] ?? null, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($detail),
'status' => in_array($state, ['completed', 'approved'], true) ? 'completed' : ($state === 'not_started' ? 'pending' : 'active'),
'version_no' => $step['version'] + 1, 'updated_at' => now()]);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_stage_recorded', ['code' => $code, ...$detail]);
});
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function returnTool(Request $request, string $id, array $input): array
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'draft_id' => 'required|uuid', 'draft_version' => 'required|integer|min:1', 'context_revision' => 'nullable|integer|min:0', 'context_reviewed' => 'nullable|boolean'])->validate();
return DB::transaction(function () use ($request, $id, $data): array {
$actor = $request->user();
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
abort_unless($case->simulation_id === $data['draft_id'] && (int) $case->user_id === $actor->id, 403, 'Ferramenta pertencente a outro contexto.');
$draft = app(SimulationFormDrafts::class)->find($data['draft_id'], $request);
abort_unless($draft->version_no === $data['draft_version'], 409, 'O rascunho mudou; aguarde a gravação e volte a recuperar o resultado.');
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$snapshot = $economic['financial_tools_snapshot'] ?? null;
abort_unless(is_string($snapshot) && strlen($snapshot) <= 30000, 422, 'Guarde primeiro as entradas da ferramenta financeira.');
$parsed = json_decode($snapshot, true);
abort_unless(is_array($parsed) && ($parsed['version'] ?? null) === 1 && is_array($parsed['data'] ?? null), 422, 'Snapshot financeiro incompatível.');
$payload = $this->desk->decode($case->payload);
$context = app(InvestorContext::class)->state($case);
if ($context['revision'] > 0) {
abort_unless(($data['context_revision'] ?? -1) === $context['revision'], 409, 'O contexto mudou; recupere e confira os pressupostos antes de devolver o resultado.');
abort_unless($data['context_reviewed'] ?? false, 422, 'Confirme a revisão dos pressupostos financeiros para este contexto.');
}
$resultKey = hash('sha256', $draft->id.':'.$draft->version_no.':'.$snapshot.':context:'.$context['revision']);
foreach ($payload['investor_path']['results'] ?? [] as $result) {
if ($result['source_key'] === $resultKey) {
return $result;
}
}
abort_unless((int) $case->version === $data['version'], 409, 'Recupere a versão actual do dossier.');
$result = ['id' => (string) Str::uuid(), 'source_key' => $resultKey, 'draft_id' => $draft->id, 'draft_version' => $draft->version_no,
'snapshot_sha256' => $draft->snapshot_sha256, 'financial_snapshot' => $snapshot,
'currency' => $economic['currency'] ?? null, 'engine' => 'financial-calculators:v1',
'kind' => 'local_calculation_inputs', 'context_state' => 'current', 'context_revision' => $context['revision'], 'context_dependency_hash' => $context['dependency_hash'] ?? app(InvestorContext::class)->dependencyHash([]), 'recorded_at' => now()->toIso8601String()];
$payload['investor_path']['results'][] = $result;
abort_unless(count($payload['investor_path']['results']) <= 100, 422, 'Limite de evidências financeiras deste dossier atingido.');
$this->savePayload($case, $payload);
$this->desk->event($this->desk->case($actor, $id), $actor, 'tool_evidence_returned', array_diff_key($result, ['financial_snapshot' => true]));
return $result;
});
}
/** @return list<array<string,mixed>> */
public function contexts(User $actor): array
{
if (! $this->available()) {
return [];
}
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$contexts = DB::table('desk_cases as c')->join('investor_journeys as j', 'j.id', '=', 'c.journey_id')->whereNotNull('j.path_definition_id')
->whereNull('j.deleted_at')->whereNull('c.closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('c.user_id', $actor->id)->whereNull('c.organization_id'))->orWhereIn('c.organization_id', $organizations))
->orderByDesc('c.updated_at')->get(['c.id', 'c.title', 'c.version', 'c.updated_at'])
->map(fn ($row) => ['id' => $row->id, 'title' => $row->title, 'version' => $row->version, 'updated_at' => $row->updated_at])->all();
return array_values($contexts);
}
/** @param array<string,mixed> $input */
public function task(User $actor, string $id, array $input): string
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'code' => ['required', Rule::in(array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19)))],
'title' => 'required|string|min:3|max:200', 'due_at' => 'required|date|after:now', 'consent' => 'accepted'])->validate();
return DB::transaction(function () use ($actor, $id, $data): string {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$key = 'path:'.$data['code'];
$existing = DB::table('tasks')->where('desk_case_id', $id)->where('guidance_key', $key)->first();
if ($existing) {
abort_unless($existing->title === $data['title'] && (int) $existing->accepted_by === $actor->id
&& Carbon::parse($existing->due_at)->equalTo(Carbon::parse($data['due_at'])), 409, 'A tarefa desta etapa já existe com outros dados.');
return $existing->id;
}
$this->writable($actor, $id, $data['version']);
$step = $this->findStep($this->view($actor, $id), $data['code']);
abort_unless($step !== null && $step['preparation_allowed'], 422);
$task = CrmTask::create(['desk_case_id' => $id, 'guidance_key' => $key, 'title' => $data['title'], 'due_at' => $data['due_at'],
'status' => 'open', 'assignee_user_id' => $actor->id, 'accepted_by' => $actor->id, 'accepted_at' => now(),
'external_sync_status' => 'pending_authorization', 'data_classification' => 'confidential', 'source_system' => 'investor-path']);
$this->desk->event($case, $actor, 'path_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'scope' => 'internal_crm']);
return $task->id;
});
}
private function writable(User $actor, string $id, int $version): \stdClass
{
abort_unless($this->available(), 404);
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === $version, 409, 'Recupere a versão actual do dossier.');
$this->view($actor, $id);
return $case;
}
/** @param array<string,mixed> $view
* @return array<string,mixed>|null
*/
private function findStep(array $view, string $code): ?array
{
if (! is_array($view['steps'] ?? null)) {
return null;
}
foreach ($view['steps'] as $step) {
if (is_array($step) && ($step['code'] ?? null) === $code) {
return $step;
}
}
return null;
}
/** @param array<string,mixed> $payload */
private function savePayload(\stdClass $case, array $payload): void
{
DB::table('desk_cases')->where('id', $case->id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Services;
final class InvestorPathDefinition
{
public const STATES = ['not_started', 'preparing', 'ready_to_submit', 'submitted', 'reviewing', 'correction_required', 'waiting_external', 'approved', 'rejected', 'dispensed', 'completed', 'expired'];
/** @return array<string,mixed> */
public static function snapshot(): array
{
$titles = ['Sistematizar a ideia', 'Análise preliminar', 'Decisão sobre a viabilidade', 'Estruturar o investimento',
'Constituição e registo', 'Preparar o dossier', 'Submeter quando aplicável', 'Licenciamento prévio',
'Necessidade de terra', 'Regularização da terra', 'Confirmar regularização aplicável',
'Necessidade e estrutura de financiamento', 'Diligência e negociação financeira', 'Decisão do financiador',
'Fecho e desembolso', 'Implementação', 'Inspecções, testes e licença de operação', 'Início de operação', 'Acompanhamento recorrente'];
$steps = [];
foreach ($titles as $index => $title) {
$n = $index + 1;
$steps[] = ['code' => sprintf('S%02d', $n), 'sequence' => $n, 'title' => $title,
'phase' => $n <= 4 ? 1 : ($n <= 7 ? 2 : ($n <= 11 ? 3 : ($n <= 15 ? 4 : 5))),
'source_paragraph' => 21 + $n,
'branch' => $n === 10 ? 'land_needed' : (in_array($n, [13, 14, 15], true) ? 'external_funding' : null),
// Preparation has no dependencies. These only constrain the named consequential action.
'dependencies' => match ($n) {
7 => ['submit' => ['S06']],
15 => ['execute' => ['S14']],
18 => ['operate' => ['S17']],
default => [],
}];
}
return ['kind' => 'investor-path', 'version' => 1,
'source_sha256' => 'aa13c53138ec15cd808de43d9dc2fc6808da86943d09d3352c9dd0944bdae364',
'phases' => [1 => 'Ideia e viabilidade', 2 => 'Formalização e dossier', 3 => 'Licenciamento e terra', 4 => 'Financiamento', 5 => 'Execução e acompanhamento'],
'states' => self::STATES, 'steps' => $steps,
'legacy_roadmaps' => ['virtual-desk:E0-E11', 'investor-guidance:7-phases', 'investment-roadmap:14-activities']];
}
/** @param array<string,mixed> $definition */
public static function validate(array $definition): void
{
$steps = $definition['steps'] ?? [];
$expected = array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19));
if (count($definition['phases'] ?? []) !== 5 || array_column($steps, 'code') !== $expected
|| array_column($steps, 'sequence') !== range(1, 19)) {
throw new \LogicException('The five phases and nineteen source stages must remain traceable.');
}
$edges = [];
foreach ($steps as $step) {
if (! in_array($step['phase'], range(1, 5), true)
|| ! in_array($step['branch'], [null, 'land_needed', 'external_funding'], true)) {
throw new \LogicException('Unknown phase or applicability field.');
}
$edges[$step['code']] = [];
foreach ($step['dependencies'] as $action => $dependencies) {
if (! in_array($action, ['submit', 'execute', 'operate'], true)
|| array_diff($dependencies, $expected)) {
throw new \LogicException('Unknown action/dependency; preparation cannot be blocked.');
}
$edges[$step['code']] = array_merge($edges[$step['code']], $dependencies);
}
}
$visit = function (string $code, array $trail) use (&$visit, $edges): void {
if (in_array($code, $trail, true)) {
throw new \LogicException('Cyclic action dependencies.');
}
foreach ($edges[$code] as $next) {
$visit($next, [...$trail, $code]);
}
};
foreach ($expected as $code) {
$visit($code, []);
}
}
}
+346
View File
@@ -0,0 +1,346 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use DOMDocument;
use DOMElement;
use DOMNode;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
/** A reading adapter over the existing library, never a second content/opportunity register. */
final class LegacyContent
{
public function available(): bool
{
// Explicit delivery gate; document publication and access checks remain independent.
if (config('portal.legacy_content_enabled', false)) {
return true;
}
if (! config('portal.legacy_content_qa_enabled') || ! app()->environment('testing')
|| config('database.connections.pgsql.host') !== '127.0.0.1'
|| config('database.connections.pgsql.url') || (int) config('database.connections.pgsql.port') !== 55441) {
return false;
}
$actual = DB::selectOne('SELECT current_database() AS database, inet_server_port() AS port');
return $actual && str_ends_with($actual->database, '_test') && (int) $actual->port === 55441
&& $actual->database === config('database.connections.pgsql.database');
}
/** @return array<string, mixed> */
public function article(string $slug = 'agronegocio', bool $includeRelated = true): array
{
abort_unless($this->available(), 404);
$identity = config('legacy_content.articles.'.$slug);
abort_unless(is_array($identity) && ($identity['publishable'] ?? false), 404);
$row = $this->identityResources()->get($identity['external_id']);
abort_unless($row !== null, 404);
$binary = app(VerifiedDocumentBinary::class)->respond($row);
$bytes = $binary instanceof BinaryFileResponse ? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
abort_unless(is_string($bytes) && strlen($bytes) <= 10485760 && hash_equals(trim($row->sha256), hash('sha256', $bytes)), 404);
try {
$source = json_decode($bytes, true, 64, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
abort(404);
}
abort_unless(is_array($source) && ($source['format'] ?? '') === 'investmoz-legacy-article-v1'
&& ($source['source_url'] ?? '') === $row->source_url && $row->source_url === $identity['source_url']
&& is_string($source['content_html'] ?? null) && trim(strip_tags($source['content_html'])) !== '', 404);
foreach (['title', 'author', 'legacy_category', 'published_at', 'modified_at'] as $key) {
abort_unless(is_string($source[$key] ?? null), 404);
}
abort_unless(is_int($source['legacy_id'] ?? null), 404);
$image = $this->publicResources()->where('d.sha256', $source['image_sha256'] ?? '')->where('d.media_type', 'image/png')->first();
$sector = $slug === 'energia-mineracao' ? null : Sector::where('slug', $identity['sector_slug'])->where('is_active', true)->first();
$relatedSectors = $slug === 'energia-mineracao' ? Sector::whereIn('slug', ['energia-especifica', 'mineracao'])->where('is_active', true)->get(['id', 'name', 'slug']) : collect();
// These are independently published records in the same sector, not claims of article/project linkage.
$opportunities = $sector ? SectorOrganization::opportunities($sector)->latest('published_at')
->limit(12)->get(['title', 'slug', 'province', 'summary']) : [];
if ($relatedSectors->isNotEmpty()) {
$opportunities = Opportunity::published()->whereIn('sector_id', $relatedSectors->pluck('id'))->latest('published_at')->limit(12)->get(['id', 'title', 'slug', 'province', 'summary']);
}
$localHtml = $this->localLinks($this->sanitize($source['content_html']));
$editorial = \Illuminate\Support\Facades\Schema::hasColumn('portal_resources', 'editorial_content')
? DB::table('portal_resources')->where('id', $row->resource_id)->value('editorial_content') : null;
if ($editorial) {
$adaptation = json_decode($editorial, true, 64, JSON_THROW_ON_ERROR);
$localHtml = implode('', array_map(fn ($p) => '<p>'.nl2br(e($p)).'</p>', preg_split('/\n\s*\n/', $adaptation['body'])));
$source['title'] = $row->title;
if (!empty($adaptation['image_resource_id'])) {
$image = $this->publicResources()->where('r.id', $adaptation['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->first();
}
}
preg_match_all('~href="([^"]+)"~i', $localHtml, $existingLinks);
$alreadyLinked = array_map(fn ($href) => html_entity_decode($href, ENT_QUOTES | ENT_HTML5, 'UTF-8'), $existingLinks[1]);
$relatedArticles = [];
if ($includeRelated) {
foreach ($this->related($identity['group'], $slug) as $item) {
if (in_array($item['href'], $alreadyLinked, true)) continue;
try {
$relatedArticles[] = $this->article($item['slug'], false);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $error) {
if ($error->getStatusCode() !== 404) throw $error;
}
}
}
return ['id' => (int) $row->resource_id, 'document_id' => $row->id, 'version' => (int) $row->metadata_version,
'sha256' => trim($row->sha256), 'title' => $source['title'], 'author' => $source['author'],
'legacy_id' => $source['legacy_id'], 'legacy_category' => $source['legacy_category'],
'published_at' => $source['published_at'], 'modified_at' => $source['modified_at'], 'source_url' => $source['source_url'],
'href' => '/'.$slug, 'html' => $localHtml, 'summary' => self::excerpt($localHtml),
'opportunities_href' => $sector ? '/oportunidades?sector='.rawurlencode($sector->slug) : null,
'opportunities_label' => $sector ? 'Ver oportunidades de '.$sector->name : null,
'has_opportunities' => count($opportunities) > 0,
'landing_href' => '/explorar/'.$identity['group'], 'start_href' => '/investimentos/a-partir-de/'.$slug,
'group' => config('legacy_content.groups.'.$identity['group']),
'related_articles' => $relatedArticles,
'image' => $image ? ['href' => '/documentos/'.$image->resource_id.'/view', 'sha256' => trim($image->sha256),
'alt' => $slug === 'agronegocio' ? 'Campo agrícola ao pôr do sol; fotografia ilustrativa do artigo Agronegocio'
: 'Imagem ilustrativa original do artigo '.$source['title'], 'source_url' => $image->source_url] : null,
'related_sectors' => $relatedSectors, 'sector' => $sector?->only(['id', 'name', 'slug']), 'opportunities' => $opportunities,
'territorial_references' => array_values(array_filter($slug === 'agronegocio' ? ['Pemba–Lichinga', 'Nacala', 'Vale do Zambeze', 'Beira', 'Limpopo', 'Maputo'] : [],
fn ($name) => str_contains(strip_tags($source['content_html']), $name))),
'territorial_status' => 'Menções territoriais preservadas no artigo. Limites administrativos, parcelas e geometrias não associados automaticamente.',
'library_href' => '/documentos/'.$row->resource_id,
'consultation_state' => 'public', 'legal_state' => 'not_applicable', 'calculation_use' => false];
}
/** An excerpt of the displayed edition, never a claim about returns or availability. */
public static function excerpt(string $html): string
{
$plain = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
if (str_contains($plain, 'Hotelaria e resorts') && str_contains($plain, 'Ecoturismo')
&& str_contains($plain, 'Infraestruturas turísticas') && str_contains($plain, 'Oportunidades Regionais')) {
return 'Conheça os temas de turismo e hospitalidade abordados no guia: hotelaria, ecoturismo, infraestruturas de apoio e referências regionais. Use este enquadramento para preparar a sua ideia de investimento.';
}
preg_match_all('~<p\b[^>]*>(.*?)</p>~isu', $html, $paragraphs);
foreach ([...($paragraphs[1] ?? []), $html] as $paragraph) {
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($paragraph), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
if (mb_strlen($text) >= 60) return \Illuminate\Support\Str::limit($text, 320);
}
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
}
/** Resolve a library identity, preserving the already stored source URLs and versions. */
/** @return array<string, mixed> */
public function articleForResource(int $resourceId): array
{
abort_unless($this->available(), 404);
$externalId = $this->identityResources()->firstWhere('resource_id', $resourceId)?->legacy_identity;
foreach (config('legacy_content.articles', []) as $slug => $identity) {
if ($identity['external_id'] === $externalId && $identity['publishable']) {
return $this->article($slug);
}
}
abort(422, 'Escolha um artigo disponível para consulta; a referência não foi guardada.');
}
/** @return list<array<string,mixed>> */
public function articlesForGroup(string $group): array
{
abort_unless($this->available() && is_array(config('legacy_content.groups.'.$group)), 404);
$articles = [];
foreach ($this->related($group) as $item) {
$articles[] = $this->article($item['slug']);
}
abort_unless($articles !== [], 404);
return $articles;
}
/** @return list<array<string,mixed>> */
private function related(string $group, ?string $except = null): array
{
$identities = array_filter(config('legacy_content.articles', []), fn ($identity, $slug) => $identity['group'] === $group && $identity['publishable'] && $slug !== $except, ARRAY_FILTER_USE_BOTH);
$resources = $this->identityResources();
$result = [];
foreach ($identities as $slug => $identity) {
$row = $resources->get($identity['external_id']);
if ($row && $row->source_url === $identity['source_url']) {
$result[] = ['slug' => $slug, 'id' => (int) $row->resource_id, 'title' => $row->title, 'href' => '/'.$slug];
}
}
return $result;
}
private function localLinks(string $html): string
{
$public = $this->identityResources();
$links = [];
foreach (config('legacy_content.articles', []) as $slug => $identity) {
if ($identity['publishable'] && $public->get($identity['external_id'])?->source_url === $identity['source_url']) {
$links[rtrim($identity['source_url'], '/')] = '/'.$slug;
}
}
$doc = new DOMDocument;
$old = libxml_use_internal_errors(true);
try {
$doc->loadHTML('<?xml encoding="UTF-8"><html><body>'.$html.'</body></html>', LIBXML_NONET);
foreach ($doc->getElementsByTagName('a') as $anchor) {
$href = $anchor->getAttribute('href');
if (isset($links[rtrim($href, '/')])) {
$anchor->setAttribute('href', $links[rtrim($href, '/')]);
}
}
$body = $doc->getElementsByTagName('body')->item(0);
return $body ? implode('', array_map(fn ($child) => $doc->saveHTML($child), iterator_to_array($body->childNodes))) : '';
} finally {
libxml_clear_errors();
libxml_use_internal_errors($old);
}
}
/** @param array<string, mixed> $input */
public function attach(User $actor, string $caseId, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'resource_id' => 'required|integer|min:1'])->validate();
$article = $this->articleForResource((int) $data['resource_id']);
abort_unless(app(InvestorPath::class)->available(), 404);
DB::transaction(function () use ($actor, $caseId, $data, $article): void {
$desk = app(VirtualDesk::class);
$case = $desk->case($actor, $caseId, true, true);
abort_if($case->closed_at, 409);
abort_unless(DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(),
409, 'Este dossier conserva outro roteiro; não foi convertido automaticamente.');
$payload = $desk->decode($case->payload);
foreach ($payload['investor_path']['content_sources'] ?? [] as $existing) {
if ($existing['resource_id'] === $article['id'] && $existing['sha256'] === $article['sha256']) {
if ($article['sector']) {
app(SectorInvestment::class)->attach($actor, $caseId, ['version' => $data['version'], 'sector_slug' => $article['sector']['slug']]);
}
return; // Same source/version replay: neither another reference nor another event.
}
}
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi alterado; recupere a versão atual.');
$payload['investor_path']['content_sources'][] = ['resource_id' => $article['id'], 'document_id' => $article['document_id'],
'sha256' => $article['sha256'], 'metadata_version' => $article['version'], 'title' => $article['title'],
'source_url' => $article['source_url'], 'return_href' => $article['href'], 'actor_id' => $actor->id,
'saved_at' => now()->toIso8601String()];
DB::table('desk_cases')->where('id', $caseId)->update(['payload' => $desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
$desk->event($desk->case($actor, $caseId), $actor, 'legacy_content_referenced', ['resource_id' => $article['id'], 'sha256' => $article['sha256']]);
if ($article['sector']) {
app(SectorInvestment::class)->attach($actor, $caseId, ['version' => $case->version + 1, 'sector_slug' => $article['sector']['slug']]);
}
});
}
/** Resolve explicit transport aliases without changing original IDs, versions or relations. */
private function identityResources(): \Illuminate\Support\Collection
{
$identities = array_column(config('legacy_content.articles', []), 'external_id');
$aliases = config('legacy_content_aliases', []);
$rows = $this->publicResources()->where(function ($query) use ($identities, $aliases) {
$query->whereIn('d.external_id', $identities);
if ($aliases !== []) {
$query->orWhereIn('r.id', array_column($aliases, 'resource_id'));
}
})->get();
$resolved = collect();
foreach ($rows as $row) {
$identity = in_array($row->external_id, $identities, true) ? $row->external_id : null;
foreach ($aliases as $original => $alias) {
if ((int) $row->resource_id === (int) $alias['resource_id']
&& $row->external_id === $alias['external_id']
&& hash_equals($alias['sha256'], trim($row->sha256))
&& $row->source_url === $alias['source_url']) {
abort_if($identity !== null && $identity !== $original, 409, 'Correspondência de artigo em reconciliação.');
$identity = $original;
}
}
if ($identity === null) {
continue;
}
abort_if($resolved->has($identity), 409, 'Correspondência de artigo em reconciliação.');
$row->legacy_identity = $identity;
$resolved->put($identity, $row);
}
return $resolved;
}
private function publicResources(): Builder
{
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.published', true)->where('r.rights_status', 'authorized')->where('d.rights_status', 'authorized')
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
->select(['d.*', 'r.id as resource_id', 'r.metadata_version', 'r.source_url', 'r.title']);
}
/** Allow presentation markup only. No scripts, styles, events, embeds or remote image execution. */
public function sanitize(string $html): string
{
$doc = new DOMDocument;
$old = libxml_use_internal_errors(true);
try {
$doc->loadHTML('<?xml encoding="UTF-8"><html><body>'.$html.'</body></html>', LIBXML_NONET);
$body = $doc->getElementsByTagName('body')->item(0);
// Preserve the source text and relative sections, but start the displayed
// article below the page h1. Originals and their hashes remain untouched.
$sourceLevels = [];
foreach (['h1', 'h2', 'h3', 'h4'] as $heading) {
if ($doc->getElementsByTagName($heading)->length > 0) {
$sourceLevels[] = (int) substr($heading, 1);
}
}
$headingOffset = 2 - (empty($sourceLevels) ? 2 : min($sourceLevels));
$previousHeading = 1;
$clean = function (DOMNode $node) use (&$clean, $doc, $headingOffset, &$previousHeading): void {
foreach (iterator_to_array($node->childNodes) as $child) {
if (! $child instanceof DOMElement) {
continue;
}
if (preg_match('/^h([1-4])$/i', $child->tagName, $level)) {
$displayLevel = max(2, min(6, (int) $level[1] + $headingOffset, $previousHeading + 1));
$previousHeading = $displayLevel;
$section = $doc->createElement('h'.$displayLevel);
while ($child->firstChild !== null) {
$section->appendChild($child->firstChild);
}
$node->replaceChild($section, $child);
$child = $section;
}
if (! in_array(strtolower($child->tagName), ['p', 'strong', 'b', 'em', 'i', 'ul', 'ol', 'li', 'br', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'a'], true)) {
$node->removeChild($child);
continue;
}
$href = $child->tagName === 'a' ? $child->getAttribute('href') : '';
foreach (iterator_to_array($child->attributes) as $attribute) {
$child->removeAttribute($attribute->nodeName);
}
if ($href !== '') {
if (str_starts_with($href, '/') && ! str_starts_with($href, '//')) {
$href = 'https://investemoz.tempo.co.mz'.$href;
}
if (filter_var($href, FILTER_VALIDATE_URL) && strtolower((string) parse_url($href, PHP_URL_SCHEME)) === 'https') {
$child->setAttribute('href', $href);
$child->setAttribute('rel', 'noopener noreferrer');
}
}
$clean($child);
}
};
if (! $body) {
return '';
}
$clean($body);
return implode('', array_map(fn ($child) => $doc->saveHTML($child), iterator_to_array($body->childNodes)));
} finally {
libxml_clear_errors();
libxml_use_internal_errors($old);
}
}
}
+14 -5
View File
@@ -169,14 +169,23 @@ final class ClamDScanner implements MalwareScanner
throw new RuntimeException('No production scanner is configured.'); throw new RuntimeException('No production scanner is configured.');
} }
$host = (string) config('services.malware.host', '127.0.0.1'); $unix = config('services.malware.socket');
$port = (int) config('services.malware.port', 3310); if ($unix !== null && $unix !== '') {
if ($host === '' || in_array($host, ['0.0.0.0', '::'], true) || $port < 1 || $port > 65535) { if (! is_string($unix) || ! str_starts_with($unix, '/') || str_contains($unix, "\0") || strlen($unix) > 107) {
throw new RuntimeException('The ClamD endpoint is invalid.'); throw new RuntimeException('The ClamD Unix socket is invalid.');
}
$endpoint = 'unix://'.$unix;
} else {
$host = (string) config('services.malware.host', '127.0.0.1');
$port = (int) config('services.malware.port', 3310);
if ($host === '' || in_array($host, ['0.0.0.0', '::'], true) || $port < 1 || $port > 65535) {
throw new RuntimeException('The ClamD endpoint is invalid.');
}
$endpoint = "tcp://{$host}:{$port}";
} }
$timeout = max(1, (int) config('services.malware.timeout_seconds', 120)); $timeout = max(1, (int) config('services.malware.timeout_seconds', 120));
$socket = @stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage, min(10, $timeout)); $socket = @stream_socket_client($endpoint, $errorCode, $errorMessage, min(10, $timeout));
if (! is_resource($socket)) { if (! is_resource($socket)) {
throw new RuntimeException('ClamD is unavailable.'); throw new RuntimeException('ClamD is unavailable.');
} }
@@ -0,0 +1,574 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Opis\JsonSchema\CompliantValidator;
use Opis\JsonSchema\Errors\ErrorFormatter;
use Opis\JsonSchema\Errors\ValidationError;
/** Explicit adapter of §25/26 to existing IDs and resource collections; never renumbers records. */
class OpportunityCanonicalContract
{
public const BASE_CATEGORIES = ['investment_project', 'real_estate', 'land_rights', 'business_sale', 'business_partnership', 'franchise'];
/** Availability of this bounded base-category delivery, without rewriting existing contracts/data. */
public function deliveryBlockers(array $payload): array
{
$errors = [];
if (! in_array($payload['opportunity_category'] ?? '', self::BASE_CATEGORIES, true) && ! app(OpportunityModularProfiles::class)->enabled()) {
$errors['canonical.opportunity_category'] = 'Categoria fora desta entrega: concessão, financiamento, fornecimento e outros permanecem indisponíveis. Os registos anteriores são preservados.';
}
if (($payload['opportunity_category'] ?? '') === 'real_estate') {
$property = $payload['real_estate'] ?? [];
foreach (['construction_status' => ['completed'], 'occupancy_status' => ['vacant'], 'transaction_type' => ['sale', 'lease']] as $field => $values) {
if (! empty($property[$field]) && ! in_array($property[$field], $values, true)) {
$errors['canonical.real_estate.'.$field] = 'Variante indisponível para submissão nesta entrega. Pode guardar e recuperar a preparação; estão incluídas venda e arrendamento de imóvel concluído e desocupado.';
}
}
if (array_filter($property['encumbrances'] ?? [], fn ($row) => ! empty($row['type']) && $row['type'] !== 'none')) {
$errors['canonical.real_estate.encumbrances'] = 'Imóvel com encargos: pode preparar e guardar; a submissão deste ramo não está incluída nesta entrega.';
}
if (! empty($property['max_built_area']) || ! empty($property['urban_limit_document_id'])) {
$errors['canonical.real_estate.max_built_area'] = 'Limitações urbanísticas adicionais: preparação disponível; este ramo de submissão aguarda demonstração própria.';
}
}
return $errors;
}
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
/** @return array<string,mixed> */
public function schema(bool $draft = false, array $payload = []): array
{
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
if ($bytes === false) {
throw new \RuntimeException('Opportunity schema unavailable.');
}
$schema = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
// The original conditions were omitted from the extracted Create/Patch definitions.
foreach (['opportunity', 'realEstate', 'landRights', 'businessTransaction'] as $name) {
$schema['$defs'][$name.'Create']['allOf'] = $schema['$defs'][$name]['allOf'] ?? [];
}
$schema = app(OpportunityCategoryFields::class)->enrich($schema);
$schema = app(OpportunityModularProfiles::class)->extend($schema);
$schema = app(OpportunityClassification::class)->extend($schema);
$schema = app(OpportunityInitiativeApplicability::class)->schema($schema, $payload);
$schema = $this->writeSchema($schema, $draft);
$properties = &$schema['$defs']['opportunityCreate']['properties'];
unset($properties['mutation_context']); // Actor, audit reason and revision are server-owned.
$properties['sector_id'] = ['type' => 'integer', 'minimum' => 1];
if (! app(OpportunityInitiativeApplicability::class)->enabled($payload)) {
$properties['promoter_id'] = ['type' => ['string', 'integer']];
}
// References point to the existing collections; their metadata is recovered on the server.
foreach (['locations', 'documents', 'images'] as $field) {
$properties[$field]['items'] = ['type' => 'string', 'format' => 'uuid'];
}
$properties['evidences'] = ['type' => 'array', 'items' => ['$ref' => '#/$defs/evidenceCreate']];
if (! $draft) {
$properties['evidences']['minItems'] = 1;
}
$properties['evidences']['items'] = ['type' => 'object', 'additionalProperties' => false,
'properties' => ['title' => ['type' => 'string'], 'evidence_type' => ['type' => 'string'],
'document_id' => ['type' => 'string', 'format' => 'uuid'], 'description' => ['type' => 'string']],
...($draft ? [] : ['required' => ['title', 'evidence_type', 'document_id']])];
$schema['$ref'] = '#/$defs/opportunityCreate';
$schema['$id'] = 'urn:investmoz:'.self::VERSION.($draft ? ':draft' : ':submit');
return $schema;
}
/**
* @param array<string,mixed> $node
* @return array<string,mixed>
*/
private function writeSchema(array $node, bool $draft): array
{
if (isset($node['$ref']) && preg_match('~^#/\$defs/(.+)$~', $node['$ref'], $match)) {
// Collections in the normative Create still referenced response definitions.
$defs = ['product', 'asset', 'input', 'market', 'impact', 'moneyItem', 'milestone', 'license', 'risk', 'relation', 'employment', 'environmentalSocial', 'localizedPublication', 'realEstate', 'landRights', 'businessTransaction', 'parcel', 'improvement', 'community'];
if (in_array($match[1], $defs, true)) {
$node['$ref'] .= 'Create';
}
}
if ($draft) {
unset($node['required'], $node['minItems'], $node['minProperties'], $node['contains'], $node['allOf']);
if (isset($node['type'])) {
$node['type'] = array_values(array_unique([...(array) $node['type'], 'null']));
}
if (isset($node['enum']) && ! in_array(null, $node['enum'], true)) {
$node['enum'][] = null;
}
if (isset($node['minLength'])) {
$node['minLength'] = 0;
}
if (($node['const'] ?? null) === true) {
unset($node['const']);
$node['type'] = 'boolean';
}
}
foreach ($node as $key => $value) {
if (is_array($value)) {
if (in_array($key, ['properties', '$defs'], true)) {
foreach ($value as $name => $child) {
$value[$name] = $this->writeSchema($child, $draft);
}
$node[$key] = $value;
} elseif (in_array($key, ['items', 'if', 'then', 'else'], true)) {
$node[$key] = $this->writeSchema($value, $draft);
} elseif (in_array($key, ['allOf', 'oneOf', 'anyOf'], true)) {
$node[$key] = array_map(fn ($child) => $this->writeSchema($child, $draft), $value);
}
}
}
return $node;
}
/**
* @param array<string,mixed> $payload
* @return array<string,mixed>
*/
public function draft(array $payload): array
{
abort_unless(config('portal.opportunity_specialized_drafts_enabled'), 422, 'Contrato especializado indisponível.');
$this->validateSchema($payload, true);
return $payload;
}
/** @param array<string,mixed> $payload */
private function validateSchema(array $payload, bool $draft): void
{
$schema = $this->schema($draft, $payload);
$validator = new CompliantValidator(null, 100, false);
$data = $this->schemaData($payload, $schema['$defs']['opportunityCreate'], $schema['$defs']);
$result = $validator->validate($data, json_decode(json_encode($schema, JSON_THROW_ON_ERROR)));
if ($error = $result->error()) {
throw ValidationException::withMessages($this->schemaValidationErrors($error));
}
}
/** @return array<string,list<string>> */
private function schemaValidationErrors(ValidationError $error): array
{
$errors = [];
$formatter = new ErrorFormatter;
$collect = function (ValidationError $node) use (&$collect, &$errors, $formatter): void {
if ($node->subErrors() !== []) {
foreach ($node->subErrors() as $child) {
$collect($child);
}
return;
}
$prefix = rtrim('canonical.'.implode('.', $node->data()->fullPath()), '.');
$args = $node->args();
if ($node->keyword() === 'type' && in_array($prefix, ['canonical.initiative.responsible_name', 'canonical.initiative.coverage_statement'], true)) {
$errors[$prefix][] = 'Informação em falta: preencha este campo antes de submeter.';
return;
}
if ($node->keyword() === 'required') {
foreach ($args['missing'] ?? [] as $field) {
$errors[$prefix.'.'.$field][] = 'Preencha este campo antes de submeter.';
}
return;
}
if ($node->keyword() === 'additionalProperties') {
$definition = $node->schema()->info()->data();
$declared = is_object($definition) ? (array) ($definition->properties ?? []) : [];
foreach ($args['properties'] ?? [] as $field) {
// Opis can report declared properties as unchecked after a sibling field fails.
// Keep real unknown-property errors without turning valid fields into errors.
if (! array_key_exists($field, $declared)) {
$errors[$prefix.'.'.$field][] = 'Campo não previsto no contrato desta categoria.';
}
}
return;
}
if ($node->keyword() === 'minLength') {
$errors[$prefix][] = 'Preencha este campo com pelo menos '.$args['min'].' caracteres; tem '.$args['length'].'.';
return;
}
if ($node->keyword() === 'maxLength') {
$errors[$prefix][] = 'Este campo admite até '.$args['max'].' caracteres; tem '.$args['length'].'.';
return;
}
foreach ($formatter->format($node) as $path => $messages) {
$key = rtrim('canonical'.str_replace('/', '.', $path), '.');
$errors[$key] = array_values(array_unique([...($errors[$key] ?? []), ...$messages]));
}
};
$collect($error);
// Formatting must never make an invalid schema result acceptable.
return $errors ?: ['canonical' => ['Não foi possível validar o contrato. Reveja os campos preenchidos.']];
}
/** @param array<string,mixed> $node
* @param array<string,mixed> $defs
*/
private function schemaData(mixed $value, array $node, array $defs): mixed
{
if (($node['x-investmoz-classification'] ?? false) && is_array($value)) {
$node = isset($value['classification']) ? $defs['relationCreate'] : ['type' => 'object'];
}
if (isset($node['$ref'])) {
$name = basename($node['$ref']);
$node = $defs[$name] ?? $node;
}
if (! is_array($value)) {
return $value;
}
if (in_array('object', (array) ($node['type'] ?? []), true) || isset($node['properties'])) {
$result = new \stdClass;
foreach ($value as $key => $item) {
$result->{$key} = $this->schemaData($item, $node['properties'][$key] ?? [], $defs);
}
return $result;
}
return array_map(fn ($item) => $this->schemaData($item, $node['items'] ?? [], $defs), $value);
}
/** @return array<string,mixed> */
public function validateSubmission(Opportunity $record): array
{
$values = app(OpportunityManagement::class)->values($record);
$payload = $values['canonical'] ?? [];
$errors = [];
$initiative = app(OpportunityInitiativeApplicability::class);
$initiative->validate($payload, $errors);
try {
$this->validateSchema($payload, false);
} catch (ValidationException $failure) {
throw ValidationException::withMessages([...$failure->errors(), ...$errors]);
}
$check = function (bool $valid, string $path, string $message) use (&$errors): void {
if (! $valid) {
$errors['canonical.'.$path] = $message;
}
};
$check(($payload['opportunity_category'] ?? null) === $record->opportunity_category, 'opportunity_category', 'A categoria deve coincidir com o registo e a autorização.');
$check($initiative->enabled($payload) || ($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Identifique o promotor real da oportunidade; o operador do portal não o substitui.');
$previous = app(OpportunityManagement::class)->values($record)['canonical'] ?? [];
$sameTaxonomy = ($previous['sector_id'] ?? null) === ($payload['sector_id'] ?? null)
&& ($previous['subsector_id'] ?? null) === ($payload['subsector_id'] ?? null)
&& ($previous['economic_activity_id'] ?? null) === ($payload['economic_activity_id'] ?? null);
$check(app(EconomicReferenceCatalog::class)->validHierarchy((int) $payload['sector_id'], $payload['subsector_id'] ?? null, $payload['economic_activity_id'] ?? null, $sameTaxonomy),
'economic_activity_id', 'Sector, subsector e atividade devem corresponder à hierarquia/versão publicada; os cinco níveis originais são conservados.');
foreach (['internal_contact_id', 'public_contact_id'] as $field) {
if (! empty($payload[$field])) {
$contacts = DB::table('contacts')->where('contacts.id', $payload[$field])->whereNull('contacts.deleted_at');
if ($record->organization_id) {
$contacts->whereExists(fn ($q) => $q->selectRaw('1')->from('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
->whereColumn('ic.contact_id', 'contacts.id')->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at'));
} else {
$contacts->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$record->owner_user_id);
}
$check($contacts->exists(), $field, 'Contacto inexistente ou sem relação com o Promotor.');
}
}
$resources = [];
foreach (['locations', 'documents', 'images'] as $kind) {
$table = app(OpportunityResources::class)->table($kind);
foreach ($payload[$kind] ?? [] as $index => $id) {
$row = DB::table($table)->where('id', $id)->where('opportunity_id', $record->id)->whereNull('deleted_at')->first();
$check($row !== null, "$kind.$index", 'Recurso inexistente, eliminado ou de outra oportunidade.');
if (! $row) {
continue;
}
$row->payload = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
if ($kind !== 'locations') {
$file = DB::table('documents')->where('id', $row->document_id)->first();
$check($file !== null && $file->deleted_at === null && $file->status === 'active' && $file->malware_scan_status === 'clean'
&& hash_equals(trim($file->sha256), trim((string) $file->malware_scanned_sha256)), "$kind.$index", 'Original ativo com análise antimalware correspondente obrigatória.');
if ($file) {
// Verify actual bytes/cipher integrity as well as the recorded scan hash.
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($row, $file);
app(VerifiedDocumentBinary::class)->respond($file);
$row->sha256 = trim($file->sha256);
}
} else {
$location = $row->payload;
// §10.2 area/unit consistency applies at submission. Resource drafts may
// retain incomplete measurements; never invent a unit or convert values.
$hasArea = isset($location['area_value']);
$hasUnit = isset($location['area_unit']) && $location['area_unit'] !== '';
$check(! $hasArea || $hasUnit, "locations.$index.area_unit", 'Indique a unidade da área antes de submeter; a preparação incompleta continua guardada nos recursos.');
$check(! $hasUnit || $hasArea, "locations.$index.area_value", 'Indique o valor da área antes de submeter; a unidade não determina o valor.');
$check(! $hasUnit || in_array($location['area_unit'], OpportunityResources::AREA_UNITS, true), "locations.$index.area_unit", 'Use uma unidade do catálogo existente: sqm, ha ou sqkm.');
$check(! $initiative->applicable($payload, 'physical_site') || (! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location)), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
app(InvestmentGeography::class)->selection($location, true);
$country = $location['country_code'] ?? null;
$check($country === 'MZ', "locations.$index.country_code", 'A hierarquia administrativa moçambicana deve declarar MZ; outros países exigem localização própria.');
}
$resources[$kind][$id] = (array) $row;
}
}
$locations = $resources['locations'] ?? [];
$primary = array_filter($locations, fn ($l) => $l['payload']['is_primary'] ?? false);
$check(! $initiative->applicable($payload, 'physical_site') || count($primary) === 1, 'locations', 'Selecione exatamente uma localização principal.');
$check(! $initiative->applicable($payload, 'physical_site') || ($payload['location_mode'] ?? null) !== 'single' || count($locations) === 1, 'location_mode', 'Modo single exige uma localização.');
foreach ($payload['evidences'] as $i => $evidence) {
$check(isset($resources['documents'][$evidence['document_id']]), "evidences.$i.document_id", 'Evidência deve usar um documento ativo desta oportunidade incluído no contrato.');
}
$this->categoryRules($payload, $record, $resources, $errors);
app(OpportunityCategoryFields::class)->validate($payload, $record, $resources, $errors);
if ($errors) {
throw ValidationException::withMessages($errors);
}
ksort($payload);
$snapshot = ['adapter_version' => self::VERSION, 'schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
'payload' => $payload, 'resources' => $resources];
if (isset(OpportunityModularProfiles::PROFILES[$record->opportunity_category]) || ($payload['module_profile_version'] ?? '') === OpportunityModularProfiles::HISTORY_VERSION) {
$snapshot['qa_extension'] = ['version' => OpportunityModularProfiles::VERSION, 'profile_version' => $payload['module_profile_version'],
'functional_decision' => 'Experimental QA proposal; functional approval of modular contracts and SLA remains pending. Legacy integration authorization does not approve these modules.',
'gates' => $this->gates($record)];
if ($record->opportunity_category === 'other') {
$snapshot['qa_extension']['subtype'] = config('portal.opportunity_other_qa_subtypes.'.($payload['module_details']['subtype'] ?? ''), []);
}
// A documentary correction must not rewrite the checksum of an already
// signed, unchanged version. Its historical annotation is explicitly
// reconciled by the read adapter; new/changed content uses the current note.
$prior = $record->workflow_context['submission'] ?? [];
if (isset($prior['qa_extension']) && ($prior['payload'] ?? null) == $snapshot['payload'] && ($prior['resources'] ?? null) == $snapshot['resources']) {
$snapshot['qa_extension']['functional_decision'] = $prior['qa_extension']['functional_decision'];
}
}
$snapshot['hash'] = hash('sha256', json_encode($snapshot, JSON_THROW_ON_ERROR));
return $snapshot;
}
/**
* @param array<string,mixed> $p
* @param array<string,mixed> $resources
* @param array<string,string> $errors
*/
private function categoryRules(array $p, Opportunity $record, array $resources, array &$errors): void
{
$category = $p['opportunity_category'];
app(OpportunityModularProfiles::class)->validate($p, $resources, $errors);
foreach (['real_estate', 'land_rights', 'business_transaction'] as $module) {
$applicable = match ($module) {
'real_estate' => ['real_estate'], 'land_rights' => ['land_rights'], default => ['business_sale', 'business_partnership', 'franchise']
};
if (isset($p[$module]) && ! in_array($category, $applicable, true)) {
$errors['canonical.'.$module] = 'Módulo incompatível com a categoria. Preserve-o noutra versão antes de mudar de categoria.';
}
}
if ($category === 'investment_project' && app(OpportunityInitiativeApplicability::class)->applicable($p, 'unit_investment')) {
$total = $p['total_investment'];
$sum = array_sum(array_column($p['investment_breakdown'], 'amount'));
$secured = array_sum(array_column($p['secured_financing'], 'amount'));
if (abs($sum - $total) > 0.010001 || $secured > $total || abs($p['funding_sought'] - ($total - $secured)) > 0.010001) {
$errors['canonical.investment_breakdown'] = 'Rubricas e financiamento devem reconciliar com o total (tolerância normativa 0,01).';
}
if (! in_array($p['maturity_stage'], array_keys(OpportunityMaturity::STAGES), true)) {
$errors['canonical.maturity_stage'] = 'Use um código explícito do catálogo de oito etapas; não reinterpretar a escala histórica.';
}
foreach (['investment_breakdown', 'secured_financing'] as $field) {
foreach ($p[$field] as $i => $amount) {
if ($amount['currency'] !== $p['currency']) {
$errors["canonical.$field.$i.currency"] = 'Moedas distintas requerem cenário/câmbio explícito; não somar valores de moedas diferentes.';
}
}
}
foreach ($p['markets'] as $i => $market) {
if (isset($market['country_code']) && Validator::make(['country' => $market['country_code']], ['country' => app(CountryCatalogue::class)->rule()])->fails()) {
$errors["canonical.markets.$i.country_code"] = 'Use país do catálogo ISO existente.';
}
}
}
if ($category === 'real_estate') {
$re = $p['real_estate'];
if ($re['transaction_type'] === 'sale' && ($re['price'] ?? 0) <= 0) {
$errors['canonical.real_estate.price'] = 'Venda exige preço positivo.';
}
if ($re['transaction_type'] === 'lease') {
if (($re['rent'] ?? 0) <= 0) {
$errors['canonical.real_estate.rent'] = 'Arrendamento exige renda positiva.';
}
if (empty($re['rent_periodicity'])) {
$errors['canonical.real_estate.rent_periodicity'] = 'Indique a periodicidade da renda.';
}
}
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['property_condition'])) {
$errors['canonical.real_estate.property_condition'] = 'Imóvel existente exige condição identificada.';
}
if (in_array($re['construction_status'], ['planned', 'under_construction'], true) && empty($re['planning_permit_document_id'])) {
$errors['canonical.real_estate.planning_permit_document_id'] = 'Estado construtivo exige licença de construção (§25.1).';
}
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['use_license_document_id'])) {
$errors['canonical.real_estate.use_license_document_id'] = 'Imóvel existente exige licença de utilização aplicável (§25.1).';
}
foreach (['planning_permit_document_id', 'use_license_document_id'] as $field) {
if (! empty($re[$field]) && ! isset($resources['documents'][$re[$field]])) {
$errors['canonical.real_estate.'.$field] = 'Licença deve referir documento ativo desta oportunidade.';
}
}
}
if ($category === 'land_rights') {
$land = $p['land_rights'];
if (! empty($land['issuing_authority_id']) && ! DB::table('authorities')->where('id', $land['issuing_authority_id'])->where('status', 'published')->exists()) {
$errors['canonical.land_rights.issuing_authority_id'] = 'Entidade emissora deve usar autoridade canónica publicada.';
}
if (! empty($land['issue_date']) && ($land['issue_date'] > today()->toDateString() || (! empty($land['expiry_date']) && $land['expiry_date'] <= $land['issue_date']))) {
$errors['canonical.land_rights.issue_date'] = 'Emissão não futura e validade posterior à emissão.';
}
foreach ($land['parcels'] as $i => $parcel) {
if (! isset($resources['locations'][$parcel['location_id']])) {
$errors["canonical.land_rights.parcels.$i.location_id"] = 'Parcela deve usar uma localização desta oportunidade.';
}
try {
$g = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_GeometryType(g)=\'ST_MultiPolygon\' AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) s', [json_encode($parcel['geometry'])]);
if (! $g?->valid) {
throw new \RuntimeException;
}
} catch (\Throwable) {
$errors["canonical.land_rights.parcels.$i.geometry"] = 'Parcela requer MultiPolygon válido, não vazio, EPSG:4326; limite administrativo não é parcela.';
}
}
if (in_array($land['duat_status'], ['provisional', 'definitive'], true) && empty($land['duat_number'])) {
$errors['canonical.land_rights.duat_number'] = 'DUAT provisório/definitivo exige número e entidade emissora.';
}
}
if (isset($p['business_transaction'])) {
$business = $p['business_transaction'];
if ($business['legal_entity_id'] !== $record->organization_id || ! DB::table('organizations')->where('id', $business['legal_entity_id'])->whereNull('deleted_at')->exists()) {
$errors['canonical.business_transaction.legal_entity_id'] = 'Entidade ativa representada obrigatória.';
}
}
}
/** @param array<string,mixed> $snapshot */
public function validatePublication(array $snapshot): void
{
$p = $snapshot['payload'];
$errors = [];
app(OpportunityCategoryFields::class)->publication($p, $errors);
app(OpportunityModularProfiles::class)->publication($p, $errors);
foreach ($snapshot['resources']['documents'] ?? [] as $id => $document) {
if (! empty($document['payload']['valid_until']) && $document['payload']['valid_until'] < today()->toDateString()) {
$errors['documents.'.$id] = 'Documento incluído expirou; preserve o original e reveja a versão.';
}
}
if ($p['opportunity_category'] === 'land_rights') {
foreach ($p['land_rights']['required_authorizations'] as $i => $authorization) {
if (! in_array($authorization['status'] ?? '', ['approved', 'not_required'], true)
|| (($authorization['status'] ?? '') === 'approved' && ! isset($snapshot['resources']['documents'][$authorization['document_id'] ?? '']))) {
$errors['land_rights.required_authorizations.'.$i] = 'Autorização externa pendente ou sem documento. Aprovação interna não substitui esse ato.';
}
}
foreach ($p['land_rights']['overlaps_conflicts'] as $i => $conflict) {
if (($conflict['type'] ?? '') !== 'none' && ($conflict['status'] ?? '') !== 'resolved') {
$errors['land_rights.overlaps_conflicts.'.$i] = 'Conflito impeditivo deve ser resolvido com evidência antes de publicar.';
}
}
}
if ($p['visibility'] === 'public') {
$images = $snapshot['resources']['images'] ?? [];
if (count(array_filter($images, fn ($image) => $image['payload']['is_cover'] ?? false)) !== 1) {
$errors['images'] = 'Publicação pública exige uma capa explícita.';
}
foreach ($images as $id => $image) {
$meta = $image['payload'];
if (empty($meta['alt_text']) || empty($meta['caption']) || empty($meta['rights_status']) || empty($meta['derivatives'])
|| (! empty($meta['rights_valid_until']) && $meta['rights_valid_until'] < today()->toDateString())) {
$errors['images.'.$id] = 'Legenda, texto alternativo, direitos válidos e derivadas verificadas obrigatórios.';
}
foreach ($meta['derivatives'] ?? [] as $derived) {
$file = DB::table('documents')->where('id', $derived['document_id'])->whereNull('deleted_at')->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->first();
if (! $file) {
$errors['images.'.$id] = 'Scan de uma derivada ainda não demonstrado.';
} else {
app(VerifiedDocumentBinary::class)->respond($file);
}
}
}
}
if ($errors) {
throw ValidationException::withMessages($errors);
}
}
/** @return list<string> */
public function gates(Opportunity $record): array
{
return match ($record->opportunity_category) {
'investment_project' => ['technical_review', 'legal_territorial_review'],
'real_estate' => ['property_review', 'registry_urban_review', 'building_compliance_review'],
'land_rights' => ['cadastral_screening', 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'],
'business_sale' => ['corporate_screening', 'financial_review', 'legal_tax_due_diligence', 'confidentiality_clearance'],
'business_partnership' => ['corporate_screening', 'financial_review', 'partnership_governance_review', 'legal_tax_due_diligence'],
'franchise' => ['brand_license_review', 'financial_review', 'franchise_legal_review', 'confidentiality_clearance'],
default => app(OpportunityModularProfiles::class)->gates($record),
};
}
/** Same exact projection for preview and publication; never expose private business analysis.
* @param array<string,mixed> $payload
* @return array{title:string,summary:string,description:string} */
public function publicProjection(array $payload): array
{
$business = isset($payload['business_transaction']) && ($payload['visibility'] ?? '') === 'public';
$label = match ($payload['module_details']['mode'] ?? '') {
'intention_call' => 'Intenção/chamada em preparação — não é direito atribuído. ',
'awarded_right' => 'Concessão com ato competente documentado. ',
'seeking_funding' => 'Procura de financiamento. ', 'funding_offer' => 'Oferta de financiamento — sujeita a análise do beneficiário. ',
'purchase_request' => 'Pedido de compra. ', 'supply_offer' => 'Oferta de fornecimento. ', default => '',
};
if (($payload['module_details']['conditions_status'] ?? '') === 'proposed') {
$label .= 'Valores e condições propostos, sem compromisso assumido. ';
}
return ['title' => (string) ($payload['official_title'] ?? ''), 'summary' => Str::limit($label.(string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['executive_summary'] ?? '')), 499, '…'),
'description' => (string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['demand_statement'] ?? ''))];
}
/** @return array<string,mixed> */
public function options(User $actor, ?Opportunity $record): array
{
$orgs = array_values(array_unique(array_column(app(PortalProfileAccess::class)->navigation($actor)['contexts'] ?? [], 'organization_id')));
if (! $record && (app(PortalProfileAccess::class)->navigation($actor)['internalPromoter'] ?? false)) {
// A staff creation scope does not expose unrelated private contact lists.
$orgs = [];
}
if ($record?->organization_id) {
$orgs = [$record->organization_id];
}
$contacts = DB::table('contacts')->whereNull('contacts.deleted_at')->where(function ($q) use ($orgs, $actor) {
$q->where(fn ($own) => $own->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$actor->id))
->orWhereExists(fn ($i) => $i->selectRaw('1')->from('investor_contacts as ic')->join('investors as inv', 'inv.id', '=', 'ic.investor_id')->whereColumn('ic.contact_id', 'contacts.id')->whereIn('inv.organization_id', $orgs)->whereNull('inv.deleted_at'));
})->get(['id', 'full_name']);
$submissionProperties = $this->schema(false)['$defs']['opportunityCreate']['properties'];
return ['version' => self::VERSION, 'modularProfiles' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::PROFILES : [],
'historyVersion' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::HISTORY_VERSION : null,
'classification' => app(OpportunityClassification::class)->options(),
'schema' => $this->schema(true)['$defs']['opportunityCreate'],
'definitions' => $this->schema(true)['$defs'],
'submissionTextLimits' => ['demand_statement' => array_intersect_key($submissionProperties['demand_statement'], array_flip(['minLength', 'maxLength']))],
'activities' => app(EconomicReferenceCatalog::class)->activities($record ? array_values(array_filter(array_intersect_key(app(OpportunityManagement::class)->values($record)['canonical'] ?? [], array_flip(['subsector_id', 'economic_activity_id'])))) : []),
'contacts' => $contacts, 'contactInvestors' => $record?->organization_id ? DB::table('investors')->where('organization_id', $record->organization_id)->whereNull('deleted_at')->whereIn('status', ['prospect', 'active'])->get(['id', 'legal_name']) : [],
'countries' => app(CountryCatalogue::class)->all(),
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
'gates' => $record ? $this->gates($record) : [], 'resources' => $record ? array_combine(['locations', 'documents', 'images'], array_map(fn ($k) => array_values(array_filter(app(OpportunityResources::class)->listing($record->id, $k), fn ($row) => empty($row->deleted_at))), ['locations', 'documents', 'images'])) : []];
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/** Identities and mutation history inside the existing workflow JSON, never parallel tables. */
class OpportunityCanonicalMetadata
{
/** @param array<string,mixed> $payload
* @return array<string,array<string,mixed>> */
private function items(array $payload, string $path = ''): array
{
$found = [];
foreach ($payload as $key => $value) {
$pointer = ltrim($path.'.'.$key, '.');
if (! is_array($value)) {
continue;
}
if (! array_is_list($value)) {
$found[$pointer] = $value;
}
$found += $this->items($value, $pointer);
}
return $found;
}
/** @param array<string,mixed> $before
* @param array<string,mixed> $after
* @param array<string,mixed> $metadata
* @return array<string,mixed> */
public function mutate(array $before, array $after, array $metadata, User $actor, string $reason): array
{
$old = $this->items($before);
$new = $this->items($after);
$active = $metadata['active'] ?? [];
$retired = $metadata['deleted'] ?? [];
$next = [];
$used = [];
foreach ($new as $path => $value) {
$fingerprint = OpportunityCanonicalValue::hash($value);
$match = null;
// A collection reorder preserves identity by bytes, not by its new index.
foreach ($active as $previousPath => $item) {
if (! isset($used[$previousPath]) && ($item['fingerprint'] ?? '') === $fingerprint
&& preg_replace('/\.\d+(?=\.|$)/', '.*', $previousPath) === preg_replace('/\.\d+(?=\.|$)/', '.*', $path)) {
$match = $previousPath;
break;
}
}
// Named singleton modules have a stable path; list rows need an unambiguous match.
if ($match === null && ! preg_match('/\.\d+(?:\.|$)/', $path) && isset($active[$path]) && ! isset($used[$path])) {
$match = $path;
}
$item = $match !== null ? $active[$match] : null;
if ($match !== null) {
$used[$match] = true;
}
$changed = $item === null || ($item['fingerprint'] ?? '') !== $fingerprint;
$legacy = $item === null && isset($old[$path]);
$item ??= ['id' => (string) Str::uuid(), 'version' => 0, 'created_by' => $legacy ? null : $actor->id,
'created_at' => $legacy ? null : now()->toIso8601String(), 'first_observed_at' => now()->toIso8601String(),
'identity_source' => $legacy ? 'legacy_first_observation_not_creation' : 'server_generated_new_item'];
if ($changed) {
$item['version']++;
$item['updated_by'] = $actor->id;
$item['updated_at'] = now()->toIso8601String();
}
$next[$path] = [...$item, 'fingerprint' => $fingerprint, 'is_deleted' => false,
'active' => true, 'deleted_at' => null, 'deleted_by' => null, 'delete_reason' => null];
}
foreach ($active as $path => $item) {
if (isset($used[$path])) {
continue;
}
$retired[$item['id']] = [...$item, 'path' => $path, 'version' => $item['version'] + 1,
'is_deleted' => true, 'active' => false, 'deleted_at' => now()->toIso8601String(),
'deleted_by' => $actor->id, 'delete_reason' => $reason, 'last_value' => $old[$path] ?? null];
}
return ['active' => $next, 'deleted' => $retired, 'rule' => 'existing-json-identities-v1'];
}
/** @param array<string,mixed> $payload
* @param array<string,mixed> $metadata
* @return array<string,mixed> */
public function project(array $payload, array $metadata): array
{
// Deepest paths first so a parent does not overwrite the children's identities.
$paths = array_keys($metadata['active'] ?? []);
foreach ($paths as $path) {
if (! is_string($path)) {
throw new \UnexpectedValueException('Canonical item paths must be named fields.');
}
}
usort($paths, fn ($a, $b) => substr_count($b, '.') <=> substr_count($a, '.'));
foreach ($paths as $path) {
$value = Arr::get($payload, $path);
if (! is_array($value)) {
continue;
}
$item = $metadata['active'][$path];
unset($item['fingerprint']);
Arr::set($payload, $path, [...$value, ...$item]);
}
return $payload;
}
}
@@ -0,0 +1,149 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Read adapter only: preserve persisted identifiers and make unresolved metadata explicit. */
class OpportunityCanonicalResponse
{
public const VERSION = 'opportunity-response-existing-ids-20261011-4';
/** @return array<string,mixed> */
public function read(User $actor, Opportunity $record): array
{
$access = app(PortalProfileAccess::class);
$access->authorize($actor, 'view', $record);
$payload = app(OpportunityManagement::class)->values($record)['canonical'] ?? [];
$context = $record->workflow_context ?? [];
$data = [...app(OpportunityCanonicalMetadata::class)->project($payload, $context['canonical_items'] ?? []), 'id' => $record->id, 'opportunity_code' => $record->reference,
'opportunity_category' => $record->opportunity_category, 'status' => $access->state($record),
'version' => (int) $record->management_version, 'is_deleted' => $record->trashed(),
'deleted_at' => $record->deleted_at?->toIso8601String(), ...$this->rootMetadata($record)];
foreach (['submitted' => 'submission', 'approved' => 'approval', 'published' => 'publication', 'archived' => 'archive'] as $prefix => $key) {
$data[$prefix.'_by'] = $context[$key]['actor_id'] ?? null;
$data[$prefix.'_at'] = $context[$key]['at'] ?? null;
}
$completion = app(OpportunityCompleteness::class)->calculate($payload);
$data['completion_percentage'] = $completion['percentage'];
$errors = [];
try {
app(OpportunityCanonicalContract::class)->validateSubmission($record);
} catch (ValidationException $failure) {
$errors = $failure->errors();
} catch (HttpExceptionInterface $failure) {
$errors = ['canonical.resources' => ['Recurso indisponível para validação; estado HTTP '.$failure->getStatusCode().'. Preserve o original e resolva a operação afetada.']];
}
$data['classification'] = app(OpportunityClassification::class)->listing($actor, $record);
$data['validation_result'] = ['errors' => $errors, 'warnings' => [], 'rule' => OpportunityCanonicalContract::VERSION,
'evaluated_at' => now()->toIso8601String(), 'persisted_submission_hash' => $context['submission']['hash'] ?? null,
'external_decision' => 'not_inferred'];
$mutations = [];
foreach (DB::table('audit_events')->where('source_system', 'opportunity-resources')->where('after_data->opportunity_id', $record->id)->orderBy('occurred_at')->orderBy('id')->get(['actor_user_id', 'action', 'occurred_at', 'after_data']) as $event) {
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
$mutations[$detail['resource_id']][] = ['actor' => $event->actor_user_id, 'action' => $event->action, 'at' => $event->occurred_at, 'reason' => $detail['reason'] ?? null];
}
$references = [];
foreach (OpportunityResources::KINDS as $kind) {
$references[$kind] = $payload[$kind] ?? [];
$rows = [];
if (app(OpportunityResources::class)->installed()) {
foreach (app(OpportunityResources::class)->listing($record->id, $kind) as $row) {
$rows[$row->id] = $row;
}
}
$data[$kind] = array_map(function (string $id) use ($rows, $kind, $mutations): array {
$row = $rows[$id] ?? null;
if ($row === null) {
return ['id' => $id, 'availability' => 'unavailable'];
}
$value = [...$row->payload, 'id' => $row->id, 'version' => (int) $row->version,
'is_deleted' => $row->deleted_at !== null, 'deleted_at' => $row->deleted_at,
'created_by' => $row->created_by, 'created_at' => $row->created_at, 'updated_at' => $row->updated_at];
$events = $mutations[$id] ?? [];
$last = $events ? $events[array_key_last($events)] : null;
$deletion = $row->deleted_at && ($last['action'] ?? '') === 'delete' ? $last : null;
$value['updated_by'] = $last['actor'] ?? ((int) $row->version === 1 ? $row->created_by : null);
$value['deleted_by'] = $deletion['actor'] ?? null;
$value['delete_reason'] = $deletion && $deletion['reason'] ? Crypt::decryptString($deletion['reason']) : null;
$value['mutation_metadata_source'] = $last ? 'existing_audit_events' : 'creation_record_only';
if ($kind !== 'locations') {
$value['original_name'] = $row->file?->file_name;
$value['mime_type'] = $row->file?->media_type;
$value['sha256'] = $row->file?->sha256;
$value['scan_recorded_status'] = $row->file?->malware_scan_status;
}
return $value;
}, $references[$kind]);
}
return ['adapter_version' => self::VERSION,
'source_schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
'data' => $data, 'resource_references' => $references,
'completion' => $completion, 'materiality' => $context['materiality'] ?? null,
'review_conditions' => array_values($context['conditions'] ?? []),
'deleted_inline_items' => array_values($context['canonical_items']['deleted'] ?? []),
'validation_result' => ['scope' => 'current_payload_validation_and_recorded_submission_metadata', 'submission_hash' => $context['submission']['hash'] ?? null,
'submitted_content_revision' => $context['submission']['content_revision'] ?? null,
'current_content_revision' => $context['content_revision'] ?? 1,
'revalidated_on_read' => true, 'external_decision' => 'not_inferred'],
'publication' => $record->publicationPresentation(),
'compatibility' => ['normative_response_complete' => false, 'opportunity_actor_sector_ids' => 'existing bigint, not converted to UUID',
'modular_decision' => 'Functional approval of four modular contracts and SLA remains pending; legacy integration did not approve them. Historical snapshot annotations are preserved, not current approvals.',
'opportunity_code' => 'existing reference preserved; no INV-MZ code invented',
'states' => 'existing workflow values preserved; no implicit stage equivalence',
'inline_modules' => 'management_draft canonical JSON with audited revisions; no parallel specialized tables',
'state_correspondence' => ['draft' => 'draft', 'needs_information' => 'returned', 'submitted' => 'submitted', 'approved' => 'approved', 'published' => 'published', 'suspended' => 'suspended', 'archived' => 'archived', 'rejected' => 'rejected'],
'unmapped_review_states' => 'in_review/information_pending preserve parallel gates; no single normative stage inferred',
'metadata_gaps' => ['Legacy inline creation metadata can be unknown; first observation is not creation. Ambiguous changed collection rows get new identities with previous identities retained as deleted.', 'Existing bigint IDs remain explicit compatibility differences; no renumbering.']]];
}
/**
* Recover actors from existing audited versions; an imported creator must never be inferred.
*
* @return array<string,mixed>
*/
private function rootMetadata(Opportunity $record): array
{
$events = [];
foreach (DB::table('audit_events')->whereIn('source_system', ['opportunity-management', 'portal-profiles-v1'])
->where('after_data->record_id', $record->id)->get(['source_system', 'actor_user_id', 'action', 'after_data']) as $event) {
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
$version = $detail['version'] ?? $detail['after']['version'] ?? null;
if (! is_int($version)) {
continue;
}
$events[$version] = ['actor' => $event->actor_user_id, 'action' => $event->action,
'reason' => $detail['reason'] ?? null, 'encrypted_reason' => $event->source_system === 'opportunity-management'];
}
ksort($events);
$creation = null;
$deletion = null;
foreach ($events as $event) {
if ($event['action'] === 'draft_created') {
$creation = $event;
}
if ($event['action'] === 'delete') {
$deletion = $event;
}
}
$latest = $events[(int) $record->management_version] ?? null;
$deletion = $record->trashed() ? $deletion : null;
return ['created_by' => $creation['actor'] ?? null, 'created_at' => $record->created_at?->toIso8601String(),
'updated_by' => $latest['actor'] ?? null, 'updated_at' => $record->updated_at?->toIso8601String(),
'deleted_by' => $deletion['actor'] ?? null,
'delete_reason' => $deletion && $deletion['reason'] ? ($deletion['encrypted_reason'] ? Crypt::decryptString($deletion['reason']) : $deletion['reason']) : null,
'mutation_metadata_source' => 'existing_audit_events_and_record_timestamps',
'mutation_metadata_gaps' => array_values(array_filter([
$creation === null ? 'No recorded creation actor; imported ownership does not establish creation.' : null,
$latest === null ? 'No audit actor matching the current management version; no updater inferred.' : null,
]))];
}
}

Some files were not shown because too many files have changed in this diff Show More