Compare commits

..
Author SHA1 Message Date
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
nala 60784a2ed2 oportunidades 2
tests / ci (push) Canceled after 0s
2026-10-09 08:48:42 +02:00
nala 7ecfe3d543 feat: integrate opportunity draft management with audited lifecycle 2026-10-09 08:16:51 +02:00
nala ebfc188240 Confirm active opportunity classifications with read-only audit 2026-10-09 07:38:01 +02:00
nala ae789ce024 vrsao 2
tests / ci (push) Canceled after 0s
2026-10-09 02:57:39 +02:00
nala 344545430b Add audited opportunity origin review and QA separation 2026-10-09 02:46:36 +02:00
nala 6c7a9c9442 Exige motivo na reversão territorial e prepara novo plano 2026-10-09 02:15:36 +02:00
nala 6a71aa47e3 Consolida rastreabilidade territorial e plano autenticado V2 2026-10-09 02:05:44 +02:00
nala 30acdc9934 Liga acervo documental e guias a jornada do investidor 2026-10-08 18:54:24 +02:00
nala 51c7fb92b1 Corrige validacao, recuperacao e acesso ao calculo do rascunho 2026-10-08 18:07:29 +02:00
nala 1106509116 vrsao 2
tests / ci (push) Canceled after 0s
2026-10-08 14:02:01 +02:00
nala bdd766c68a resolvemos o problema dos ZEE e ZFI
tests / ci (push) Canceled after 0s
2026-10-07 19:46:35 +02:00
nala 0a086c3fa5 resolvemos o problema dos ZEE e ZFI
tests / ci (push) Canceled after 0s
2026-10-07 14:00:55 +02:00
nala 59d108a576 resolvemos o problema dos ZEE e ZFI
tests / ci (push) Canceled after 0s
2026-10-07 09:08:43 +02:00
nala e65cb26901 varias alteracoes
tests / ci (push) Canceled after 0s
2026-10-06 14:50:12 +02:00
631 changed files with 124515 additions and 16281 deletions
+26 -6
View File
@@ -20,12 +20,14 @@ LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
# Full application schema requires PostgreSQL with PostGIS; SQLite is unsupported.
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=investemoz
# Configure a least-privilege application role; provision PostGIS before migrations.
DB_USERNAME=investmoz_app
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
@@ -36,6 +38,16 @@ SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
DB_QUEUE_RETRY_AFTER=210
MALWARE_SCANNER=clamd
CLAMD_HOST=127.0.0.1
CLAMD_PORT=3310
CLAMD_TIMEOUT_SECONDS=120
CLAMD_MAX_SIGNATURE_AGE_HOURS=48
CLAMD_MAX_FILE_BYTES=20971520
CLAMD_MAX_STREAM_BYTES=26214400
CLAMD_MAX_DECOMPRESSED_BYTES=104857600
CLAMD_MAX_ARCHIVE_ENTRIES=1000
CACHE_STORE=database
# CACHE_PREFIX=
@@ -94,3 +106,11 @@ SUITECRM_BASE_URL=
SUITECRM_CLIENT_ID=
SUITECRM_CLIENT_SECRET=
SUITECRM_CACHE_STORE=database
# Tax-rule governance roles are empty by default and require named verified managers with MFA.
INVESTMOZ_TAX_RULE_EDITORS=
INVESTMOZ_TAX_RULE_REVIEWERS=
INVESTMOZ_TAX_RULE_APPROVERS=
INVESTMOZ_TAX_RULE_PUBLISHERS=
INVESTMOZ_ZONE_TERRITORY_REVIEWERS=
BIN
View File
Binary file not shown.
+4 -4
View File
@@ -20,7 +20,7 @@ jobs:
POSTGRES_USER: investmoz_test
POSTGRES_PASSWORD: test-only-password
ports:
- 5432:5432
- 55441:5432
options: >-
--health-cmd "pg_isready -U investmoz_test -d investmoz_test"
--health-interval 10s --health-timeout 5s --health-retries 5
@@ -28,7 +28,7 @@ jobs:
APP_ENV: testing
DB_CONNECTION: pgsql
DB_HOST: 127.0.0.1
DB_PORT: 5432
DB_PORT: 55441
DB_DATABASE: investmoz_test
DB_USERNAME: investmoz_test
DB_PASSWORD: test-only-password
@@ -71,5 +71,5 @@ jobs:
INVESTMOZ_SCHEMA_TESTS: '1'
run: php vendor/bin/phpunit --configuration=phpunit.investmoz.xml --do-not-cache-result
- name: Test frontend API contracts
run: node --test tests/frontend/portal-api.test.mjs
- name: Test all frontend contracts and calculators
run: node --test tests/frontend/*.test.mjs
+17
View File
@@ -0,0 +1,17 @@
# Regras do acervo documental InvestMoz
## Aceitação das fontes oficiais — decisão do responsável, 08/10/2026
- Dados e documentos com origem oficial/governamental identificada (incluindo BR, decretos e leis) são aceites pelo responsável como fontes fidedignas e válidas. Não exigir segunda ou terceira validação da autenticidade/proveniência oficial, nem certificação por outra fonte.
- Registar e recuperar origem, exemplar, versão e citação é rastreabilidade; a ausência desses campos num cadastro não revoga a aceitação nem torna o dado inválido. Preservar as validações e decisões já documentadas.
- Esta decisão tem precedência sobre pendências genéricas de revalidação de proveniência oficial em relatórios históricos. Não estender a classificação oficial a documentos de promotores ou de programação sem origem oficial identificada.
- A aceitação da fonte não substitui a identificação do âmbito, período aplicável, alterações/revogações expressas no próprio acervo oficial ou dos parâmetros necessários a uma regra/cálculo. Conferir esses elementos no documento oficial é aplicação da fonte aceite, não uma segunda validação da sua credibilidade. Não ativar cálculos por importação/publicação.
- O responsável define o acervo e a finalidade. Inventariar todos os ficheiros e anexos acessíveis antes de seleccionar documentos para consulta; não omitir por não serem usados por uma funcionalidade.
- Manter três estados independentes: disponibilidade para consulta, situação jurídica/documental e utilização numa regra ou cálculo. Importação/publicação nunca activa um cálculo fiscal.
- Não usar associação a módulo, requisito ou artigo como pré-condição para cadastrar ou consultar um documento autorizado. Relações sem citação verificada ficam pendentes e visivelmente identificadas.
- Respeitar a autorização de divulgação registada e o seu âmbito. Só bloquear por impedimento concreto (por exemplo malware, dados pessoais/confidenciais ou restrição efectiva de divulgação), registado por ficheiro. Não atribuir decisões a gestores inexistentes nem contornar autenticação.
- Importações em lote devem ter pré-visualização, cálculo de hash, detecção de duplicados por bytes e conflitos de identidade/versão, escrita privada, análise antimalware e execução idempotente. Nunca publicar automaticamente um lote.
- Preservar o ficheiro original, a proveniência, o identificador exacto, a edição/data, o hash e o histórico. Não marcar autenticidade, vigência, direitos ou scan como confirmados sem evidência.
- Para fontes fiscais, inventariar também as fontes não analisadas e os diplomas/artigos sem correspondência documental. Parâmetros ausentes ou ambiguidades permanecem indeterminados; não usar zero nem a taxa mais recente como substituto.
- Antes de aplicar mudanças em dados activos, confirmar backup/restauro e a acção autenticada que continua necessária. Testes e migrações devem usar exclusivamente uma base QA isolada com guarda contra a base activa.
+1101 -853
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,116 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Throwable;
class CheckDocumentLibrarySchema extends Command
{
protected $signature = 'portal:check-document-library-schema';
protected $description = 'Confere o esquema e as migrações da biblioteca documental antes da activação';
public function handle(): int
{
$reference = (string) Str::uuid();
try {
$required = [
'portal_resources' => [
'id', 'document_id', 'title', 'category', 'topic', 'legislation', 'essential', 'published',
'source_reference', 'rights_status', 'description', 'document_type', 'document_number',
'document_date', 'source_url', 'language', 'version_label', 'document_group_id',
'applicable_from', 'applicable_until',
'territorial_scope', 'territory_id', 'source_confirmation', 'legal_status', 'last_reviewed_at',
'document_identity_key', 'duplicate_of_resource_id', 'metadata_version', 'created_by',
'last_reviewed_by', 'independent_review',
],
'documents' => [
'id', 'status', 'data_classification', 'sha256', 'deleted_at', 'file_name', 'media_type',
'storage_key', 'size_bytes', 'version_no', 'issuer', 'issued_on', 'valid_until', 'uploaded_by',
'rights_status', 'original_source', 'malware_scan_status', 'malware_scanned_sha256',
'malware_engine', 'malware_engine_version', 'malware_signatures_at', 'malware_scanned_at',
'malware_failure_reason', 'malware_scan_attempts',
],
'portal_resource_links' => ['id', 'resource_id', 'target_type', 'target_key', 'relationship', 'applicability'],
'portal_resource_revisions' => ['id', 'resource_id', 'revision_no', 'change_type', 'snapshot'],
'document_malware_scans' => ['id', 'document_id', 'file_sha256', 'result', 'engine', 'engine_version', 'started_at'],
];
$missing = [];
foreach ($required as $table => $columns) {
if (! Schema::hasTable($table)) {
$missing[] = "tabela {$table}";
continue;
}
foreach (array_diff($columns, Schema::getColumnListing($table)) as $column) {
$missing[] = "{$table}.{$column}";
}
}
$requiredMigrations = [
'2026_10_05_120000_extend_portal_document_catalogue',
'2026_10_05_130000_add_document_malware_scanning',
];
if (! Schema::hasTable('migrations')) {
$missing[] = 'repositório de migrações';
} else {
$ran = DB::table('migrations')->whereIn('migration', $requiredMigrations)->pluck('migration')->all();
foreach (array_diff($requiredMigrations, $ran) as $migration) {
$missing[] = "migração {$migration}";
}
}
if ($missing !== []) {
$this->error('Esquema da biblioteca incompatível. Não activar o catálogo; faltam elementos de esquema ou migrações.');
foreach ($missing as $item) {
$this->line('- '.$item);
}
return self::FAILURE;
}
foreach ([
['portal_resources', 'rights_status', 'unconfirmed'],
['documents', 'rights_status', 'unconfirmed'],
['documents', 'malware_scan_status', 'pending'],
] as [$table, $column, $expectedDefault]) {
$default = DB::selectOne(
'select column_default from information_schema.columns where table_schema = current_schema() and table_name = ? and column_name = ?',
[$table, $column],
)?->column_default;
if (! is_string($default) || ! str_contains(strtolower($default), $expectedDefault)) {
$this->error("Valor predefinido inseguro ou ausente em {$table}.{$column}; preservar os registos e rever a migração.");
return self::FAILURE;
}
}
$invalidCleanRecords = DB::table('documents')->where('malware_scan_status', 'clean')
->where(function ($query): void {
$query->whereNull('malware_scanned_sha256')->orWhereColumn('malware_scanned_sha256', '!=', 'sha256');
})->count();
if ($invalidCleanRecords > 0) {
$this->error('Existem documentos marcados como limpos sem correspondência do hash analisado.');
return self::FAILURE;
}
$this->info('Esquema da biblioteca compatível; verificações de direitos e análise antimalware disponíveis.');
return self::SUCCESS;
} catch (Throwable $exception) {
Log::error('Document library schema compatibility check failed.', ['reference' => $reference, 'exception' => $exception]);
$this->error('Não foi possível verificar a compatibilidade do esquema. Consulte o registo interno. Referência: '.$reference);
return self::FAILURE;
}
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Console\Commands;
use App\Services\Malware\MalwareScanner;
use Illuminate\Console\Command;
class CheckMalwareScanner extends Command
{
protected $signature = 'malware:health';
protected $description = 'Check ClamAV availability and signature freshness';
public function handle(MalwareScanner $scanner): int
{
$health = $scanner->health();
$this->line('Scanner: '.($health['engine']));
$this->line('Available: '.($health['available'] ? 'yes' : 'no'));
$this->line('Engine version: '.($health['engine_version'] ?? 'unavailable'));
$this->line('Signatures UTC: '.($health['signatures_at']?->format(DATE_ATOM) ?? 'unavailable'));
$this->line('Signature age hours: '.($health['signature_age_hours'] === null ? 'unavailable' : number_format($health['signature_age_hours'], 2)));
if (! $health['available']) {
$this->error('Reason: '.($health['reason_code'] ?? 'scanner_unavailable'));
return self::FAILURE;
}
return self::SUCCESS;
}
}
@@ -0,0 +1,276 @@
<?php
namespace App\Console\Commands;
use App\Jobs\ScanDocumentForMalware;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
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 $description = 'Preview or idempotently import a document batch into the existing private library';
private const MAX_BYTES = 10485760;
public function handle(): int
{
$staging = storage_path('app/private/document-import-staging');
$manifestPath = realpath($staging.DIRECTORY_SEPARATOR.$this->argument('manifest'));
$stagingReal = realpath($staging);
if (! $manifestPath || ! $stagingReal || ! str_starts_with(strtolower($manifestPath), strtolower($stagingReal.DIRECTORY_SEPARATOR)) || ! is_file($manifestPath)) {
$this->error('Manifest is missing or outside the private document-import staging directory.');
return self::FAILURE;
}
foreach ([
'documents' => ['id', 'source_system', 'external_id', 'version_no', 'data_classification', 'file_name', 'media_type', 'storage_key', 'sha256', 'status', 'size_bytes', 'issuer', 'issued_on', 'uploaded_by', 'rights_status', 'original_source', 'malware_scan_status'],
'portal_resources' => ['document_id', 'title', 'category', 'topic', 'published', 'source_reference', 'approved_by', 'description', 'document_type', 'document_number', 'document_date', 'source_url', 'language', 'version_label', 'source_confirmation', 'legal_status', 'rights_status', 'document_identity_key', 'metadata_version', 'created_by'],
] as $table => $columns) {
if (! Schema::hasColumns($table, $columns)) {
$this->error('Document-library schema is incomplete; run the documented schema compatibility check before importing.');
return self::FAILURE;
}
}
try {
$manifest = json_decode((string) file_get_contents($manifestPath), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) {
$this->error('Manifest is not valid JSON.');
return self::FAILURE;
}
if (! is_array($manifest) || ! isset($manifest['documents']) || ! is_array($manifest['documents']) || count($manifest['documents']) > 100) {
$this->error('Manifest must contain at most 100 documents in a documents array.');
return self::FAILURE;
}
$apply = (bool) $this->option('apply');
$actorId = $this->option('actor');
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.');
return self::FAILURE;
}
$disk = Storage::disk('local');
$seenHashes = [];
$seenExternalIds = [];
$dispatch = [];
$failures = 0;
foreach ($manifest['documents'] as $index => $record) {
$label = is_array($record) ? (string) ($record['external_id'] ?? '#'.($index + 1)) : '#'.($index + 1);
try {
$validated = $this->validateRecord($record, $stagingReal);
$hash = $validated['sha256'];
if (isset($seenHashes[$hash])) {
$this->line($label.' | duplicate bytes within batch; references item '.$seenHashes[$hash]);
continue;
}
$seenHashes[$hash] = $label;
if (isset($seenExternalIds[$validated['external_id']])) {
$this->warn($label.' | external_id already occurs in this batch with different bytes; identity review required');
continue;
}
$seenExternalIds[$validated['external_id']] = $hash;
$existing = DB::table('documents')->where('sha256', $hash)->whereNull('deleted_at')->first();
if ($existing) {
$this->line($label.' | already imported by SHA-256; document='.$existing->id.'; no duplicate');
continue;
}
$externalMatch = DB::table('documents')->where('source_system', 'document-batch-import')
->where('external_id', $validated['external_id'])->whereNull('deleted_at')->first();
if ($externalMatch) {
$this->warn($label.' | external_id already belongs to document '.$externalMatch->id.' with different bytes; version review required');
continue;
}
$identity = $this->identity($validated);
$identityMatch = DB::table('portal_resources')->where('document_identity_key', $identity)->first();
if ($identityMatch) {
$this->warn($label.' | identity matches resource '.$identityMatch->id.' but bytes differ; version review required');
continue;
}
$this->line($label.' | '.($apply ? 'will import as private draft' : 'preview: private draft')." | bytes={$validated['size_bytes']} | sha256={$hash}");
if (! $apply) {
continue;
}
$documentId = (string) Str::uuid();
$storageKey = 'portal-documents/'.$documentId;
$source = fopen($validated['source_path'], 'rb');
if (! is_resource($source)) {
throw new RuntimeException('Source could not be opened.');
}
try {
$stored = $disk->put($storageKey, $source);
} finally {
fclose($source);
}
$storedPath = $disk->path($storageKey);
$storedHash = $stored && is_file($storedPath) ? hash_file('sha256', $storedPath) : false;
if (! $stored || ! is_string($storedHash) || ! hash_equals($hash, $storedHash)) {
$disk->delete($storageKey);
throw new RuntimeException('Private copy failed the checksum verification.');
}
try {
$resourceId = DB::transaction(function () use ($validated, $documentId, $storageKey, $hash, $identity, $actorId): int {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['document-batch:'.$hash]);
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['document-batch-identity:'.$identity]);
if (DB::table('documents')->where('sha256', $hash)->whereNull('deleted_at')->exists()) {
throw new RuntimeException('Matching bytes were registered concurrently; rerun preview.');
}
if (DB::table('portal_resources')->where('document_identity_key', $identity)->exists()) {
throw new RuntimeException('A matching document identity was registered concurrently; version review required.');
}
$now = now();
DB::table('documents')->insert([
'id' => $documentId, 'source_system' => 'document-batch-import', 'external_id' => $validated['external_id'],
'version_no' => 1, 'data_classification' => 'internal', 'file_name' => $validated['file_name'],
'media_type' => $validated['media_type'], 'storage_key' => $storageKey, 'sha256' => $hash,
'status' => 'quarantined', 'size_bytes' => $validated['size_bytes'], 'issuer' => $validated['issuer'],
'issued_on' => $validated['document_date'], 'uploaded_by' => (int) $actorId, 'rights_status' => 'unconfirmed',
'original_source' => $validated['source_url'], 'malware_scan_status' => 'pending',
'created_at' => $now, 'updated_at' => $now,
]);
$resourceId = DB::table('portal_resources')->insertGetId([
'document_id' => $documentId, 'title' => $validated['title'], 'category' => $validated['category'],
'topic' => $validated['topic'], 'legislation' => $validated['legislation'], 'essential' => false,
'published' => false, 'source_reference' => $validated['source_reference'], 'approved_by' => null,
'description' => $validated['description'], 'document_type' => $validated['document_type'],
'document_number' => $validated['document_number'], 'document_date' => $validated['document_date'],
'source_url' => $validated['source_url'], 'language' => $validated['language'],
'version_label' => $validated['version_label'], 'territorial_scope' => 'unknown',
'source_confirmation' => 'unconfirmed', 'legal_status' => 'unknown', 'rights_status' => 'unconfirmed',
'document_identity_key' => $identity, 'metadata_version' => 1, 'created_by' => (int) $actorId,
'last_reviewed_by' => null, 'independent_review' => false, 'created_at' => $now, 'updated_at' => $now,
]);
$resource = DB::table('portal_resources')->where('id', $resourceId)->first();
DB::table('portal_resource_revisions')->insert([
'resource_id' => $resourceId, 'revision_no' => 1, 'change_type' => 'created',
'snapshot' => json_encode(['resource' => $resource, 'associations' => []], JSON_THROW_ON_ERROR),
'actor_user_id' => (int) $actorId, 'created_at' => $now,
]);
DB::table('audit_events')->insert([
'id' => (string) Str::uuid(), 'source_system' => 'document-batch-import',
'external_id' => $validated['external_id'], 'data_classification' => 'internal',
'actor_user_id' => (int) $actorId, 'entity_type' => 'document', 'entity_id' => $documentId,
'action' => 'private_document_batch_imported',
'after_data' => json_encode(['sha256' => $hash, 'resource_id' => $resourceId, 'published' => false], JSON_THROW_ON_ERROR),
'occurred_at' => $now, 'created_at' => $now,
]);
return $resourceId;
});
$dispatch[] = $documentId;
$this->info($label.' | private draft created | resource='.$resourceId.'; pending scan; not published');
} catch (Throwable $exception) {
$disk->delete($storageKey);
throw $exception;
}
} catch (Throwable $exception) {
$this->error($label.' | not imported: '.$exception->getMessage());
$failures++;
}
}
foreach ($dispatch as $documentId) {
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
}
$this->line($apply ? 'New scans queued: '.count($dispatch).'.' : 'Preview only; database and storage unchanged.');
return $failures > 0 ? self::FAILURE : self::SUCCESS;
}
/** @return array<string, mixed> */
private function validateRecord(mixed $record, string $stagingRoot): array
{
if (! is_array($record)) {
throw new RuntimeException('Each documents entry must be an object.');
}
foreach (['external_id', 'relative_path', 'title', 'issuer'] as $required) {
if (! isset($record[$required]) || ! is_string($record[$required]) || trim($record[$required]) === '') {
throw new RuntimeException('Required manifest field is missing: '.$required.'.');
}
}
if (strlen($record['external_id']) > 120 || strlen($record['title']) > 250 || strlen($record['issuer']) > 180) {
throw new RuntimeException('A metadata value exceeds its permitted length.');
}
if (isset($record['file_name']) && (! is_string($record['file_name']) || strlen(basename($record['file_name'])) > 255)) {
throw new RuntimeException('File name exceeds its permitted length.');
}
if (isset($record['document_number']) && (! is_string($record['document_number']) || strlen($record['document_number']) > 120)) {
throw new RuntimeException('Document number exceeds its permitted length.');
}
if (isset($record['document_date'])) {
if (! is_string($record['document_date']) || ! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $record['document_date'], $dateParts)
|| ! checkdate((int) $dateParts[2], (int) $dateParts[3], (int) $dateParts[1])) {
throw new RuntimeException('Document date must use a valid YYYY-MM-DD value.');
}
}
if (isset($record['document_type']) && ! in_array($record['document_type'], ['legislation', 'procedure', 'official_form', 'digital_adaptation', 'guidance_template', 'guide', 'study', 'reference_data', 'unknown'], true)) {
throw new RuntimeException('Document type is not supported by the catalogue.');
}
$path = realpath($stagingRoot.DIRECTORY_SEPARATOR.$record['relative_path']);
if (! $path || ! str_starts_with(strtolower($path), strtolower($stagingRoot.DIRECTORY_SEPARATOR)) || ! is_file($path)) {
throw new RuntimeException('Source file is missing or outside the private staging directory.');
}
$size = filesize($path);
if (! is_int($size) || $size < 1 || $size > self::MAX_BYTES) {
throw new RuntimeException('File size is outside the 1 byte to 10 MiB import limit.');
}
$mime = (new \finfo(FILEINFO_MIME_TYPE))->file($path);
$allowed = ['application/pdf', 'text/plain', 'text/csv', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/png', 'image/jpeg', 'image/webp'];
if (! is_string($mime) || ! in_array($mime, $allowed, true)) {
throw new RuntimeException('Detected media type is not supported by the document library.');
}
$sha = hash_file('sha256', $path);
if (! is_string($sha)) {
throw new RuntimeException('File hash could not be calculated.');
}
$sourceUrl = $record['source_url'] ?? null;
if ($sourceUrl !== null && (! is_string($sourceUrl) || strlen($sourceUrl) > 2000 || ! filter_var($sourceUrl, FILTER_VALIDATE_URL) || strtolower((string) parse_url($sourceUrl, PHP_URL_SCHEME)) !== 'https')) {
throw new RuntimeException('Source URL, when supplied, must be a valid HTTPS URL.');
}
return [
...$record, 'source_path' => $path, 'file_name' => basename((string) ($record['file_name'] ?? $path)),
'size_bytes' => $size, 'media_type' => $mime, 'sha256' => $sha,
'category' => (string) ($record['category'] ?? 'general'), 'topic' => (string) ($record['topic'] ?? 'unclassified'),
'legislation' => (bool) ($record['legislation'] ?? false), 'document_type' => (string) ($record['document_type'] ?? 'unknown'),
'document_number' => $record['document_number'] ?? null, 'document_date' => $record['document_date'] ?? null,
'language' => (string) ($record['language'] ?? 'unknown'), 'version_label' => $record['version_label'] ?? null,
'source_url' => $record['source_url'] ?? null, 'source_reference' => $record['source_reference'] ?? 'Origem por completar.',
'description' => $record['description'] ?? 'Documento importado para revisão documental.',
];
}
/** @param array<string, mixed> $record */
private function identity(array $record): string
{
return hash('sha256', mb_strtolower(implode('|', array_map('trim', [
(string) $record['issuer'], (string) ($record['document_number'] ?? ''), (string) ($record['document_date'] ?? ''),
(string) $record['language'], (string) ($record['version_label'] ?? $record['title']),
]))));
}
}
@@ -0,0 +1,119 @@
<?php
namespace App\Console\Commands;
use App\Services\InvestmentZones;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use RuntimeException;
class ImportIndustrialParkCandidates extends Command
{
protected $signature = 'investment-zones:import-industrial-candidates {--apply : Create missing private drafts} {--actor= : Existing eligible manager user ID required with --apply}';
protected $description = 'Reconcile and optionally create source-backed industrial-park/ZFI drafts without publishing';
public function handle(): int
{
$document = json_decode($this->readSource(database_path('data/industrial-park-candidate-drafts.json')), true, flags: JSON_THROW_ON_ERROR);
if (($document['source_document_attached'] ?? null) !== true
|| ($document['source_document_reconciled'] ?? null) !== true) {
$this->error('The source document must be attached and reconciled before importing drafts. No records written.');
return self::FAILURE;
}
$rows = [];
foreach ($document['records'] as $record) {
$existing = DB::table('investment_zones')->where('code', $record['code'])->first(['id', 'name', 'publication_status']);
$territories = [];
foreach ($record['territories'] as $territory) {
$expected = $this->normalize($territory['name']);
$matches = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $territory['type'])
->get(['id', 'name'])->filter(fn ($node) => $this->normalize($node->name) === $expected);
if ($matches->count() !== 1) {
throw new RuntimeException("Territory {$territory['name']} ({$territory['type']}) matched {$matches->count()} rows; approximate matching is disabled.");
}
$territories[] = [...$territory, 'geo_location_id' => $matches->first()->id, 'resolved_name' => $matches->first()->name];
}
$rows[] = ['record' => $record, 'existing' => $existing, 'territories' => $territories];
}
$this->table(['Code', 'Action', 'Territory IDs resolved', 'Areas'], array_map(fn ($row) => [
$row['record']['code'], $row['existing'] ? 'reconcile/skip-existing' : ($this->option('apply') ? 'create-private-draft' : 'would-create-private-draft'),
implode('; ', array_map(fn ($t) => $t['resolved_name'], $row['territories'])), count($row['record']['areas']),
], $rows));
if (! $this->option('apply')) {
$this->info('Dry run only. No writes made; every created record remains a private draft, with legal regime/availability not implied by the source.');
return self::SUCCESS;
}
if (! Schema::hasColumn('investment_zones', 'source_evidence')) {
$this->error('The additive industrial-park schema is not migrated in this database. No records written.');
return self::FAILURE;
}
$actor = filter_var($this->option('actor'), FILTER_VALIDATE_INT);
$user = $actor ? DB::table('users')->where('id', $actor)->first(['id', 'email', 'email_verified_at', 'two_factor_confirmed_at']) : null;
if (! $user || ! $user->email_verified_at || ! $user->two_factor_confirmed_at
|| ! in_array(mb_strtolower($user->email), config('portal.managers', []), true)) {
$this->error('An existing verified, MFA-enabled configured manager is required. No records written.');
return self::FAILURE;
}
$created = DB::transaction(function () use ($rows, $actor, $document): array {
$created = [];
foreach ($rows as $row) {
if ($row['existing']) {
continue;
}
$record = $row['record'];
$source = $record['source'];
$sourceReference = $source['url'].' — '.$source['title'];
$locations = array_map(fn ($location) => ['geo_location_id' => $location['geo_location_id'], 'scope_type' => $location['scope_type'],
'source_reference' => $sourceReference, 'legal_source_id' => null], $row['territories']);
$first = $row['territories'][0]['geo_location_id'] ?? null;
$zone = app(InvestmentZones::class)->save(null, [
'code' => $record['code'], 'name' => $record['name'], 'category' => $record['category'],
'physical_category' => $record['physical_category'], 'legal_regime' => $record['legal_regime'],
'development_status' => $record['development_status'], 'availability_status' => $record['availability_status'],
'operational_status' => 'unknown', 'description' => $record['source']['supports'].(! empty($record['territory_note']) ? ' '.$record['territory_note'] : ''),
'source_evidence' => [[...$source, 'source_date' => null]],
'area_components' => array_map(fn ($area) => [...$area, 'source_reference' => $sourceReference.' — '.$area['source_reference'], 'source_date' => null], $record['areas']),
'area_value' => null, 'area_unit' => null, 'activities' => [], 'resources' => [], 'aliases' => [],
'sources_consulted_at' => $document['consulted_at'],
'legal_source_id' => null, 'parent_zone_id' => null, 'primary_territory_id' => $first,
'territory_version' => $first ? 1 : 0, 'locations' => $locations,
], (int) $actor);
$created[] = [$zone->code, $zone->id];
}
return $created;
});
$this->info('Private drafts created: '.count($created).'. Existing codes skipped. No legal sources were approved and no records were published.');
foreach ($created as [$code, $id]) {
$this->line($code.' '.$id);
}
return self::SUCCESS;
}
private function normalize(string $value): string
{
return Str::upper(Str::ascii(trim($value)));
}
private function readSource(string $path): string
{
$bytes = file_get_contents($path);
if ($bytes === false) {
throw new RuntimeException('Source file is unavailable: '.$path);
}
return $bytes;
}
}
@@ -5,54 +5,18 @@ namespace App\Console\Commands;
use App\Models\InvestmentDossier;
use Database\Seeders\InvestmentPortfolioSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ImportInvestmentPortfolio extends Command
{
protected $signature = 'portfolio:import {--approval= : Recorded approval from the document owner}';
protected $signature = 'portfolio:import';
protected $description = 'Import the v4 portfolio and optionally publish unchanged documentary dossiers with owner approval';
protected $description = 'Import the documentary portfolio as private drafts; publication uses the authenticated review workflow';
public function handle(): int
{
$approval = trim((string) $this->option('approval'));
if ($approval !== '' && (mb_strlen($approval) < 15 || mb_strlen($approval) > 3000)) {
$this->error('A autorização deve conter entre 15 e 3000 caracteres.');
return self::FAILURE;
}
$data = json_decode(File::get(database_path('data/investment-portfolio.json')), true, 512, JSON_THROW_ON_ERROR);
$published = 0;
$preserved = 0;
DB::transaction(function () use ($data, $approval, &$published, &$preserved) {
app(InvestmentPortfolioSeeder::class)->run();
foreach (['projects' => ['project_id', 'projects'], 'clusters' => ['cluster_id', 'economic_clusters'], 'corridors' => ['corridor_id', 'development_corridors']] as $kind => [$foreign, $table]) {
foreach ($data[$kind] as $item) {
$entity = DB::table($table)->where('code', $item['code'])->where('source_system', 'upgrade-v4')->whereNull('deleted_at')->value('id');
$dossier = InvestmentDossier::where($foreign, $entity)->lockForUpdate()->first();
// Approval of this document never approves subsequent human edits or restores archived records.
if (! $dossier || $dossier->title !== $item['name'] || $dossier->content != [...$item, 'notice' => $data['notice']] || $dossier->editor_id) {
$preserved++;
continue;
}
if ($approval === '' || $dossier->publication_status === 'published') {
continue;
}
$dossier->update(['version_no' => $dossier->version_no + 1, 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => $approval]);
DB::table('audit_events')->insert(['source_system' => 'portfolio-import', 'entity_type' => 'investment_dossiers',
'entity_id' => $dossier->id, 'action' => 'owner_approved', 'after_data' => json_encode([
'code' => $item['code'], 'approval_basis' => 'document_owner',
'approval_sha256' => hash('sha256', $approval),
'dataset_sha256' => hash_file('sha256', database_path('data/investment-portfolio.json')),
], JSON_THROW_ON_ERROR)]);
$published++;
}
}
});
$this->info("Carteira importada: 15 projectos, 8 clusters, 6 corredores. Publicados: {$published}. Fichas alteradas/arquivadas preservadas: {$preserved}.");
app(InvestmentPortfolioSeeder::class)->run();
$drafts = InvestmentDossier::where('publication_status', 'draft')->count();
$this->info("Carteira importada/actualizada. Dossiers em rascunho privado: {$drafts}. Nenhuma publicação foi realizada.");
return self::SUCCESS;
}
@@ -0,0 +1,133 @@
<?php
namespace App\Console\Commands;
use App\Services\InvestmentZones;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;
class ImportInvestmentZones extends Command
{
protected $signature = 'investment-zones:import-initial {--apply : Create missing records as private drafts} {--actor= : Existing manager user ID required with --apply}';
protected $description = 'Import documented initial ZEE, ZFI and industrial park references without overwriting or publishing existing records';
public function handle(): int
{
$path = database_path('data/investment-zones-initial.json');
$document = json_decode($this->readSource($path), true, flags: JSON_THROW_ON_ERROR);
$rows = [];
foreach ($document['records'] as $record) {
$existing = DB::table('investment_zones')->where('code', $record['code'])->first(['id', 'name', 'category', 'publication_status']);
$territories = [];
foreach ($record['territories'] as $territory) {
$expected = $this->normalize($territory['name']);
$matches = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $territory['type'])
->get(['id', 'name', 'data_classification'])->filter(fn ($node) => $this->normalize($node->name) === $expected);
if ($matches->count() !== 1) {
throw new RuntimeException("Territory reference {$territory['name']} ({$territory['type']}) matched {$matches->count()} master records; no approximate match or new territory was created.");
}
$territories[] = [...$territory, 'geo_location_id' => $matches->first()->id, 'resolved_name' => $matches->first()->name];
}
$rows[] = ['code' => $record['code'], 'name' => $record['name'], 'action' => $existing ? 'skip-existing' : ($this->option('apply') ? 'create-draft' : 'would-create-draft'), 'existing' => $existing, 'territories' => $territories];
}
if (! $this->option('apply')) {
$this->table(['Code', 'Name', 'Action', 'Territories'], array_map(fn ($row) => [$row['code'], $row['name'], $row['action'], implode('; ', array_column($row['territories'], 'resolved_name'))], $rows));
$this->info('Dry run: no records written. Sources are official references; records remain private drafts pending review.');
return self::SUCCESS;
}
$actor = filter_var($this->option('actor'), FILTER_VALIDATE_INT);
$user = $actor ? DB::table('users')->where('id', $actor)->first(['id', 'email', 'email_verified_at', 'two_factor_confirmed_at']) : null;
if (! $user || ! $user->email_verified_at || ! $user->two_factor_confirmed_at
|| ! in_array(mb_strtolower($user->email), config('portal.managers', []), true)) {
$this->error('An existing, verified, MFA-enabled portal manager is required with --apply --actor=.');
return self::FAILURE;
}
$summary = DB::transaction(function () use ($rows, $document, $actor): array {
$created = [];
$skipped = [];
foreach ($rows as $row) {
if ($row['existing']) {
$skipped[] = $row['code'];
continue;
}
$record = collect(is_array($document['records'] ?? null) ? $document['records'] : [])->firstWhere('code', $row['code']);
$requiresLegalSource = in_array($record['category'], ['zee', 'zfi'], true);
$source = $requiresLegalSource
? DB::table('investment_legal_sources')->where('url', $record['source']['url'])->where('diploma', $record['source']['diploma'])->first()
: null;
$sourceId = $requiresLegalSource ? ($source->id ?? (string) Str::uuid()) : null;
if ($requiresLegalSource && ! $source) {
DB::table('investment_legal_sources')->insert([
'id' => $sourceId, ...$record['source'], 'validation_status' => 'pending', 'owner_id' => $actor,
'version_no' => 1, 'created_at' => now(), 'updated_at' => now(),
]);
}
$parentId = null;
if (isset($record['parent_code'])) {
$parentId = DB::table('investment_zones')->where('code', $record['parent_code'])->value('id');
if (! $parentId) {
throw new RuntimeException("Parent zone {$record['parent_code']} must be imported before {$record['code']}.");
}
}
$locations = array_map(fn ($location) => [
'geo_location_id' => $location['geo_location_id'], 'scope_type' => $location['scope_type'],
'source_reference' => $record['source']['url'].' — '.($record['source']['diploma'] ?? $record['source']['title']), 'legal_source_id' => $sourceId,
], $row['territories']);
$firstLocation = $row['territories'][0]['geo_location_id'] ?? null;
$zone = app(InvestmentZones::class)->save(null, [
'code' => $record['code'], 'category' => $record['category'], 'physical_category' => $record['physical_category'],
'legal_regime' => $record['legal_regime'], 'operational_status' => $record['operational_status'],
'development_status' => $record['development_status'] ?? match ($record['operational_status']) {
'operational' => 'operational', 'implementation' => 'in_development', 'planned' => 'planned', default => 'unknown'
},
'availability_status' => $record['availability_status'] ?? 'not_informed',
'name' => $record['name'], 'name_en' => $record['name_en'], 'description' => $record['description'], 'description_en' => $record['description_en'],
'area_value' => $record['area_value'], 'area_unit' => $record['area_unit'], 'area_components' => $record['area_components'] ?? [],
'source_evidence' => [[
'title' => $record['source']['title'], 'url' => $record['source']['url'],
'source_type' => str_contains($record['source']['url'], 'inm.gov.mz') ? 'government' : (str_contains($record['source']['url'], 'apiex.gov.mz') ? 'institutional' : 'promoter'),
'supports' => $record['source']['supports'] ?? 'Referência institucional/promocional; não comprova regime jurídico, incentivos ou disponibilidade.',
'source_date' => $record['source']['source_date'] ?? null,
]], 'aliases' => $record['aliases'],
'activities' => $record['activities'], 'resources' => [], 'historical_territory' => $record['historical_territory'] ?? null,
'data_as_of' => null, 'sources_consulted_at' => $document['consulted_at'], 'operator_id' => null,
'legal_source_id' => $sourceId, 'parent_zone_id' => $parentId, 'primary_territory_id' => $firstLocation,
'territory_version' => $firstLocation ? 1 : 0, 'province' => null, 'district' => null, 'locations' => $locations,
], (int) $actor);
$created[] = ['code' => $record['code'], 'id' => $zone->id, 'source' => $source?->id ? 'reused' : 'created', 'locations_pending' => count($locations)];
}
return compact('created', 'skipped');
});
$this->table(['Code', 'ID', 'Source', 'Pending locations'], array_map(fn ($row) => [$row['code'], $row['id'], $row['source'], $row['locations_pending']], $summary['created']));
$this->info('Created drafts: '.count($summary['created']).'; skipped without overwrite: '.count($summary['skipped']).'; publication: none.');
$this->line('Skipped: '.implode(', ', $summary['skipped']));
return self::SUCCESS;
}
private function normalize(string $value): string
{
return Str::upper(Str::ascii(trim($value)));
}
private function readSource(string $path): string
{
$bytes = file_get_contents($path);
if ($bytes === false) {
throw new RuntimeException('Source file is unavailable: '.$path);
}
return $bytes;
}
}
@@ -0,0 +1,312 @@
<?php
namespace App\Console\Commands;
use App\Jobs\ScanDocumentForMalware;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
class ImportLegalSourceArchive extends Command
{
protected $signature = 'documents:import-legal-source-archive {--apply : Copy verified archive files into private storage and register draft metadata}';
protected $description = 'Idempotently imports the known local legal-source PDFs as private, unpublished library drafts';
public function handle(): int
{
$records = $this->records();
$apply = (bool) $this->option('apply');
$disk = Storage::disk('local');
$dispatch = [];
$failures = 0;
foreach ($records as $record) {
$sourcePath = base_path($record['archive_path']);
$realSource = realpath($sourcePath);
$approvedRoots = array_filter([
realpath(base_path('docs/investmoz/simulations/source-archive')),
realpath(storage_path('app/private/geo-ine-source-20260928')),
]);
if (! $realSource && ($record['optional'] ?? false)) {
$this->warn($record['external_id'].': approved local source copy is not present; skipped without changing records.');
continue;
}
$withinApprovedRoot = $realSource && collect($approvedRoots)->contains(fn (string $root) => str_starts_with(strtolower($realSource), strtolower($root.DIRECTORY_SEPARATOR)));
if (! $realSource || ! $withinApprovedRoot || ! is_file($realSource)) {
$this->error($record['external_id'].': archive file missing or outside the approved source archive.');
$failures++;
continue;
}
$hash = hash_file('sha256', $realSource);
$size = filesize($realSource);
$header = file_get_contents($realSource, false, null, 0, 5);
if (! is_string($hash) || ! hash_equals($record['expected_sha256'], strtolower($hash)) || $size !== $record['size_bytes'] || $header !== '%PDF-') {
$this->error($record['external_id'].': checksum, size, or PDF signature differs from the reviewed manifest.');
$failures++;
continue;
}
$identity = hash('sha256', mb_strtolower(implode('|', array_map('trim', [$record['issuer'], $record['document_number'], $record['document_date'], $record['language'], $record['version_label']]))));
$existing = DB::table('documents')->where('sha256', $hash)->whereNull('deleted_at')->first();
if ($existing) {
$storedPath = $disk->path($existing->storage_key);
$storedReal = realpath($storedPath);
$storageRoot = realpath($disk->path(''));
if (! $storedReal || ! $storageRoot || ! str_starts_with(strtolower($storedReal), strtolower($storageRoot.DIRECTORY_SEPARATOR))
|| ! is_file($storedReal) || ! hash_equals($hash, (string) hash_file('sha256', $storedReal))) {
$this->error($record['external_id'].': matching hash exists but the stored copy could not be verified; no changes made.');
$failures++;
continue;
}
$resource = DB::table('portal_resources')->where('document_id', $existing->id)->first();
if (! $resource) {
$this->error($record['external_id'].': document hash already exists without its expected library record; manual reconciliation required.');
$failures++;
continue;
}
if (! hash_equals($identity, (string) $resource->document_identity_key)) {
$this->error($record['external_id'].': identical bytes exist under a different document identity; manual reconciliation required.');
$failures++;
continue;
}
$missingEvidence = collect(is_array($record['associations'] ?? null) ? $record['associations'] : [])->filter(fn (array $association) => $association['target_type'] === 'requirement')
->reject(fn (array $association) => DB::table('portal_resource_links')->where('resource_id', $resource->id)
->where('target_type', 'requirement')->where('target_key', $association['target_key'])->exists())->values();
if ($apply && $missingEvidence->isNotEmpty()) {
DB::transaction(function () use ($resource, $missingEvidence): void {
$locked = DB::table('portal_resources')->where('id', $resource->id)->lockForUpdate()->first();
$now = now();
foreach ($missingEvidence as $association) {
DB::table('portal_resource_links')->insertOrIgnore(['resource_id' => $resource->id, ...$association,
'created_at' => $now, 'updated_at' => $now]);
}
$inserted = DB::table('portal_resource_links')->where('resource_id', $resource->id)->where('target_type', 'requirement')
->whereIn('target_key', $missingEvidence->pluck('target_key'))->count();
if ($inserted > 0) {
$version = (int) $locked->metadata_version + 1;
DB::table('portal_resources')->where('id', $resource->id)->update(['metadata_version' => $version, 'updated_at' => $now]);
$links = DB::table('portal_resource_links')->where('resource_id', $resource->id)->orderBy('id')->get();
$snapshot = DB::table('portal_resources')->where('id', $resource->id)->first();
DB::table('portal_resource_revisions')->insert(['resource_id' => $resource->id, 'revision_no' => $version,
'change_type' => 'evidence_linked',
'snapshot' => json_encode(['resource' => $snapshot, 'associations' => $links], JSON_THROW_ON_ERROR),
'actor_user_id' => null, 'created_at' => $now]);
}
});
}
$this->line($record['external_id'].' | reused/reconciled | document='.$existing->id.' | published='.($resource->published ? 'yes' : 'no'));
continue;
}
$identityConflict = DB::table('portal_resources')->where('document_identity_key', $identity)->exists();
if ($identityConflict) {
$this->error($record['external_id'].': document identity exists with different bytes; manual version reconciliation required.');
$failures++;
continue;
}
$this->line($record['external_id'].' | '.($apply ? 'importing private draft' : 'would import')." | sha256={$hash} | bytes={$size}");
if (! $apply) {
continue;
}
$documentId = (string) Str::uuid();
$storageKey = 'portal-documents/'.$documentId;
$sourceHandle = fopen($realSource, 'rb');
if (! is_resource($sourceHandle)) {
$this->error($record['external_id'].': source could not be opened.');
$failures++;
continue;
}
try {
$stored = $disk->put($storageKey, $sourceHandle);
} finally {
fclose($sourceHandle);
}
$storedPath = $disk->path($storageKey);
$storedHash = $stored && is_file($storedPath) ? hash_file('sha256', $storedPath) : false;
if (! $stored || ! is_string($storedHash) || ! hash_equals($hash, $storedHash)) {
$disk->delete($storageKey);
$this->error($record['external_id'].': private copy failed the post-copy checksum; no database record created.');
$failures++;
continue;
}
try {
$result = DB::transaction(function () use ($record, $documentId, $storageKey, $hash, $size, $identity): array {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['legal-source-archive:'.$hash]);
if (DB::table('documents')->where('sha256', $hash)->whereNull('deleted_at')->exists()) {
throw new RuntimeException('A matching document was registered concurrently; rerun the import to reconcile it.');
}
if (DB::table('portal_resources')->where('document_identity_key', $identity)->exists()) {
throw new RuntimeException('A matching document identity was registered concurrently; manual reconciliation required.');
}
$now = now();
DB::table('documents')->insert([
'id' => $documentId, 'source_system' => 'legal-source-archive', 'external_id' => $record['external_id'],
'version_no' => 1, 'data_classification' => 'internal', 'file_name' => $record['file_name'],
'media_type' => 'application/pdf', 'storage_key' => $storageKey, 'sha256' => $hash,
'status' => 'quarantined', 'size_bytes' => $size, 'issuer' => $record['issuer'],
'original_source' => $record['source_url'], 'issued_on' => $record['document_date'],
'uploaded_by' => null, 'rights_status' => 'unconfirmed', 'malware_scan_status' => 'pending',
'created_at' => $now, 'updated_at' => $now,
]);
$resourceId = DB::table('portal_resources')->insertGetId([
'document_id' => $documentId, 'title' => $record['title'], 'category' => $record['category'] ?? 'legislation',
'topic' => $record['topic'], 'legislation' => $record['is_legislation'] ?? true, 'essential' => false, 'published' => false,
'source_reference' => $record['source_reference'], 'approved_by' => null, 'description' => $record['description'],
'document_type' => $record['document_type'] ?? 'legislation', 'document_number' => $record['document_number'],
'document_date' => $record['document_date'], 'source_url' => $record['source_url'],
'language' => $record['language'], 'version_label' => $record['version_label'],
'territorial_scope' => 'national', 'source_confirmation' => $record['source_confirmation'],
'legal_status' => $record['legal_status'], 'rights_status' => 'unconfirmed', 'last_reviewed_at' => null,
'document_identity_key' => $identity, 'metadata_version' => 1, 'created_by' => null,
'last_reviewed_by' => null, 'independent_review' => false, 'created_at' => $now, 'updated_at' => $now,
]);
foreach ($record['associations'] as $association) {
$association['review_status'] ??= 'pending';
DB::table('portal_resource_links')->insertOrIgnore([
'resource_id' => $resourceId, ...$association, 'created_at' => $now, 'updated_at' => $now,
]);
}
$links = DB::table('portal_resource_links')->where('resource_id', $resourceId)->orderBy('id')->get();
$resource = DB::table('portal_resources')->where('id', $resourceId)->first();
DB::table('portal_resource_revisions')->insert([
'resource_id' => $resourceId, 'revision_no' => 1, 'change_type' => 'created',
'snapshot' => json_encode(['resource' => $resource, 'associations' => $links], JSON_THROW_ON_ERROR),
'actor_user_id' => null, 'created_at' => $now,
]);
return ['document_id' => $documentId, 'resource_id' => $resourceId];
});
$dispatch[] = $result['document_id'];
$this->info($record['external_id'].' | created private draft | document='.$result['document_id'].' | resource='.$result['resource_id']);
} catch (Throwable $exception) {
$disk->delete($storageKey);
$this->error($record['external_id'].': import rolled back ('.$exception->getMessage().').');
$failures++;
}
}
foreach ($dispatch as $documentId) {
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
}
$this->line($apply ? 'New malware scans queued: '.count($dispatch).'.' : 'Preview only; no files or database rows were changed.');
return $failures > 0 ? self::FAILURE : self::SUCCESS;
}
/** @return array<int, array<string, mixed>> */
private function records(): array
{
$simulatorEvidence = fn (string $basis): array => [
['target_type' => 'module', 'target_key' => 'simulator', 'relationship' => 'supports', 'applicability' => 'evidence',
'condition_text' => 'Consulta documental; a fonte não determina por si só a regra fiscal aplicável.', 'basis_reference' => $basis],
];
return [
[
'external_id' => 'inm-br250-supplement-2-law-22-2022-v1',
'archive_path' => 'docs/investmoz/simulations/source-archive/Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf',
'file_name' => 'Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf',
'expected_sha256' => 'ea1b0dc6f5cf6e595f6d9a19e7042f398999e0087caef1785f6e8fac571b5f53', 'size_bytes' => 1834284,
'title' => 'Lei n.º 22/2022, de 28 de Dezembro — alteração ao Código do IVA (republicação)',
'document_number' => 'Lei n.º 22/2022', 'document_date' => '2022-12-28', 'issuer' => 'Assembleia da República',
'language' => 'pt', 'version_label' => '2.º Suplemento do BR n.º 250/2022; diploma alterador, não consolidação integral',
'topic' => 'iva', 'legal_status' => 'amended', 'source_confirmation' => 'official_confirmed',
'source_url' => 'https://www.inm.gov.mz/pt-br/content/assembleia-da-rep%C3%BAblica-suplemento-n%C2%BA-2-de-281222-pag-2252-25-42-br-n%C2%BA-250-boletim-da',
'source_reference' => 'INM, 2.º Suplemento do BR n.º 250 e catálogo oficial AT, registo Lei 22 IVA 2022. O ficheiro local foi descarregado novamente do endpoint AT em 2026-10-06; tamanho e SHA-256 coincidem exactamente. O artigo 17(1) está citado na revisão documental.',
'description' => 'Diploma alterador do CIVA, sem afirmar consolidação ou vigência integral actual. O texto oficial está identificado; direitos de reprodução da composição PDF continuam por rever, pelo que o ficheiro permanece privado.',
'associations' => [...$simulatorEvidence('Lei n.º 22/2022, art. 17(1), conforme revisão documental em docs/investmoz/simulations/primary-text-review-2025-2026.md; consultar alterações posteriores antes de determinar o período.'),
['target_type' => 'theme', 'target_key' => 'iva', 'relationship' => 'cites', 'applicability' => 'evidence', 'condition_text' => null,
'basis_reference' => 'Lei n.º 22/2022, art. 17(1); efeito temporal e alterações posteriores devem ser considerados.'],
['target_type' => 'requirement', 'target_key' => 'fiscal.iva.lei_22_2022', 'relationship' => 'cites', 'applicability' => 'evidence', 'review_status' => 'confirmed',
'condition_text' => 'Evidência documental; a citação não activa nem determina cálculos fiscais.', 'basis_reference' => 'Lei n.º 22/2022, art. 17(1), p. 3 do PDF oficial arquivado; a redacção diz 16%. Conferência da citação concluída; aplicação temporal e aprovação fiscal continuam separadas.']],
],
[
'external_id' => 'inm-br248-supplement-1-2025-v1',
'archive_path' => 'docs/investmoz/simulations/source-archive/BR-248-I-Suplemento-1-2025.pdf',
'file_name' => 'BR-248-I-Suplemento-1-2025.pdf',
'expected_sha256' => 'ccf2a8deeca820f2dd076b4b2141b1efe3f6a806568c3a587ca59a8e92f4c251', 'size_bytes' => 440018,
'title' => 'Boletim da República n.º 248/2025 — Suplemento n.º 1',
'document_number' => 'BR n.º 248/2025, Suplemento n.º 1', 'document_date' => '2025-12-29', 'issuer' => 'Imprensa Nacional de Moçambique',
'language' => 'pt', 'version_label' => 'Suplemento n.º 1; edição arquivada com 21 páginas',
'topic' => 'fiscalidade', 'legal_status' => 'unknown', 'source_confirmation' => 'official_confirmed',
'source_url' => 'https://inm.gov.mz/pt-br/content/suplemento-n%C2%BA-1-de-291225-pag-2180-1-20-br-n%C2%BA-248-boletim-da-rep%C3%BAblica-i-serie',
'source_reference' => 'Ficha INM do Suplemento n.º 1 do BR 248 e catálogo oficial AT. O ficheiro local foi descarregado novamente do endpoint WebDAV AT em 2026-10-06; tamanho e SHA-256 coincidem exactamente. Inclui diplomas fiscais identificados no registo de fontes; artigo, vigência e situação de cada lei devem ser consultados individualmente.',
'description' => 'Edição que reúne diplomas sobre ICE, Pauta Aduaneira, ISPC, IVA, IRPS e IRPC. O estado de vigência é mantido por confirmar por diploma e dispositivo. O texto oficial está identificado; direitos de reprodução da composição PDF continuam por rever, pelo que o ficheiro permanece privado.',
'associations' => [...$simulatorEvidence('BR n.º 248/2025, Suplemento n.º 1; esta ligação é evidência documental, não confirmação de vigência ou obrigação.'),
...array_map(fn (string $theme) => ['target_type' => 'theme', 'target_key' => $theme, 'relationship' => 'cites', 'applicability' => 'evidence', 'condition_text' => null,
'review_status' => 'pending', 'basis_reference' => 'Associação temática antiga; artigo e alcance por diploma ainda não foram especificados.'],
['ice', 'aduaneiro', 'ispc', 'iva', 'irps', 'irpc']),
...array_map(fn (array $item) => ['target_type' => 'requirement', 'target_key' => $item[0], 'relationship' => 'cites',
'applicability' => 'evidence', 'review_status' => 'confirmed', 'condition_text' => 'Citação localizada no texto primário; não confirma interpretação, vigência integral, elegibilidade nem regra executável.',
'basis_reference' => $item[1].' — '.$item[2].' BR n.º 248/2025, Suplemento n.º 1, Lei de 29-12-2025.'], [
['fiscal.ice.lei_7_2025', 'Lei n.º 7/2025 (ICE)', 'arts. 1–5 e tabela anexa; pp. 1–2. Art. 1 prorroga as taxas para 2027; art. 5 indica entrada em vigor em 01-01-2026.'],
['fiscal.customs.lei_8_2025', 'Lei n.º 8/2025 (Pauta Aduaneira)', 'art. 1 altera as Instruções Preliminares, arts. 21(2), 22 e 27; arts. 2–5 e tabela anexa; pp. 2–7.'],
['fiscal.ispc.lei_9_2025', 'Lei n.º 9/2025 (ISPC)', 'arts. 1–7 e republicação anexa da Lei n.º 5/2009; pp. 8–11.'],
['fiscal.iva.lei_10_2025', 'Lei n.º 10/2025 (IVA)', 'arts. 1–4; alterações do CIVA identificadas no diploma, incluindo arts. 18, 19, 21, 23, 25-A, 27 e 32–34; pp. 12–15.'],
['fiscal.irps.lei_11_2025', 'Lei n.º 11/2025 (IRPS)', 'arts. 1–4; alterações do CIRPS, incluindo arts. 21, 22, 48, 50, 54-A, 57, 65 e 65-A; pp. 16–18.'],
['fiscal.irpc.lei_12_2025', 'Lei n.º 12/2025 (IRPC)', 'arts. 1–4; alterações do CIRPC, incluindo arts. 3, 5, 20, 62, 67, 75 e aditamento do art. 61-A; pp. 19–20.'],
]),
],
],
[
'external_id' => 'inm-br89-series-1-2017-iva-rectification-v1',
'archive_path' => 'docs/investmoz/simulations/source-archive/BR-89-I-Serie-2017-06-08.pdf',
'file_name' => 'BR-89-I-Serie-2017-06-08.pdf',
'expected_sha256' => '11f0cab15eb6e51010952203ffa24fdc533a24fd642e19525fe4f46b17a1f5e5', 'size_bytes' => 9456358,
'title' => 'Boletim da República n.º 89, I Série (08-06-2017) — aviso de rectificação da Lei n.º 13/2016',
'document_number' => 'BR n.º 89/2017', 'document_date' => '2017-06-08', 'issuer' => 'Imprensa Nacional de Moçambique',
'language' => 'pt', 'version_label' => 'Exemplar local de 16 páginas; autenticidade binária pendente',
'topic' => 'iva', 'legal_status' => 'unknown', 'source_confirmation' => 'identified',
'source_url' => 'https://www.inm.gov.mz/pt-br/content/assembleia-da-rep%C3%BAblica-br-n%C2%BA-89-de-080617-boletim-da-rep%C3%BAblica-i-serie-p%C3%A1g-569',
'source_reference' => 'Ficha oficial INM identifica o aviso de rectificação da Lei n.º 13/2016 na p. 569. O exemplar local não tem assinatura digital validável; cadeia de custódia e efeito temporal por confirmar, conforme docs/investmoz/simulations/official-source-register.md.',
'description' => 'Aviso de rectificação ligado ao CIVA de 2016. A identidade do aviso é corroborada pela ficha INM; autenticidade do ficheiro local, anexos corrigidos e efeito temporal permanecem por confirmar. Cópia mantida em privado.',
'associations' => [...$simulatorEvidence('Ficha INM: aviso de rectificação da Lei n.º 13/2016, p. 569; exemplar local e efeito temporal por confirmar.'),
['target_type' => 'theme', 'target_key' => 'iva', 'relationship' => 'cites', 'applicability' => 'evidence', 'condition_text' => null, 'review_status' => 'pending',
'basis_reference' => 'Aviso de rectificação da Lei n.º 13/2016, BR n.º 89/2017, p. 569; exemplar local, anexos corrigidos e efeito temporal ainda não autenticados.'],
['target_type' => 'requirement', 'target_key' => 'fiscal.iva.lei_13_2016_rectification_2017', 'relationship' => 'cites', 'applicability' => 'evidence', 'review_status' => 'pending',
'condition_text' => 'Relação candidata pendente de conferência da cópia e dos anexos rectificados.',
'basis_reference' => 'Aviso de rectificação da Lei n.º 13/2016, BR n.º 89/2017, p. 569; ficha INM identifica o aviso, mas a cópia local e os anexos não foram autenticados.']],
],
[
'external_id' => 'ine-codificador-divisao-politico-administrativa-2012-v1',
'optional' => true,
'archive_path' => 'storage/app/private/geo-ine-source-20260928/original.pdf',
'file_name' => 'INE-Codificador-Divisao-Politico-Administrativa-2012.pdf',
'expected_sha256' => '5c69b6f189a1d3f5307e0cf7dd8224554705158a682637d3105afad615db26e2', 'size_bytes' => 67067,
'title' => 'Codificador da Divisão Político-Administrativa (INE, 07-06-2012)',
'document_number' => 'Codificador DPA 2012', 'document_date' => '2012-06-07', 'issuer' => 'Instituto Nacional de Estatística (INE)',
'language' => 'pt', 'version_label' => 'Edição 2012; actualidade das designações por confirmar',
'topic' => 'território', 'category' => 'Dados de referência', 'document_type' => 'reference_data',
'is_legislation' => false, 'legal_status' => 'unknown', 'source_confirmation' => 'official_confirmed',
'source_url' => 'https://www.ine.gov.mz/documents/20119/44337/Codificador%20da%20Divisao%20Politico%20administrativa.pdf/14aed3d0-9296-c038-dbac-041a5cf40f1d',
'source_reference' => 'PDF disponibilizado no portal oficial do INE; download efectuado em 2026-10-06, 67.067 bytes. SHA-256 coincidente com o original privado e com a cópia oficial obtida no portal INE. A data impressa é 07-06-2012; a vigência territorial actual e os direitos de reutilização do ficheiro permanecem por confirmar.',
'description' => 'Documento de referência com códigos e designações político-administrativas na edição indicada. A extracção anterior encontrou colunas com alinhamento ambíguo, sem autorizar correspondências automáticas de postos e distritos; não usar esta edição como catálogo territorial actual nem como fonte de relações não revistas.',
'territorial_scope' => 'national', 'associations' => [],
],
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use App\Jobs\ScanDocumentForMalware;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class ScanPendingDocuments extends Command
{
protected $signature = 'documents:scan-pending {--apply : Dispatch scans to the queue} {--limit=100 : Maximum documents to process in this batch}';
protected $description = 'List or dispatch a controlled batch of document malware scans';
public function handle(): int
{
$limit = max(1, min(1000, (int) $this->option('limit')));
$ids = DB::table('documents')->whereNull('deleted_at')->where('status', '!=', 'deleted')
->where(function ($query): void {
$query->whereIn('malware_scan_status', ['pending', 'inconclusive', 'failed'])
->orWhere(fn ($stale) => $stale->where('malware_scan_status', 'scanning')->where('updated_at', '<', now()->subMinutes(15)));
})->orderBy('created_at')->limit($limit)->pluck('id');
$this->info(count($ids).' document(s) eligible for this batch.');
if (! $this->option('apply')) {
$this->comment('Dry run only. Add --apply to dispatch scans.');
return self::SUCCESS;
}
foreach ($ids as $id) {
if (DB::table('documents')->where('id', $id)->where('malware_scan_status', 'scanning')->exists()) {
DB::table('documents')->where('id', $id)->update(['malware_scan_status' => 'pending', 'status' => 'quarantined', 'updated_at' => now()]);
}
ScanDocumentForMalware::dispatch((string) $id);
}
$this->info('Queued '.$ids->count().' scan(s). No editorial publication state was changed.');
return self::SUCCESS;
}
}
+7 -1
View File
@@ -2,6 +2,7 @@
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\AiRun;
use App\Models\Opportunity;
use App\Services\Ai\AiGateway;
@@ -25,6 +26,7 @@ final class AiController extends Controller
'controls' => DB::table('ai_controls')->orderBy('capability')->get(),
'sources' => DB::table('ai_sources')->orderByDesc('created_at')->limit(50)->get(['id', 'title', 'language', 'status', 'nature', 'valid_until', 'submitted_by']),
'documents' => DB::table('documents')->where('status', 'active')->whereNull('deleted_at')->where('media_type', 'text/plain')
->where('malware_scan_status', 'clean')->whereColumn('malware_scanned_sha256', 'sha256')
->whereIn('data_classification', ['public', 'internal'])->limit(100)->get(['id', 'file_name']),
'runs' => AiRun::orderByDesc('created_at')->limit(20)->get(['id', 'capability', 'mode', 'review_status', 'review_requested', 'created_at']),
'today' => now()->toDateString(),
@@ -118,7 +120,8 @@ final class AiController extends Controller
DB::transaction(function () use ($request, $file, $text, $id, $key): void {
DB::table('documents')->insert(['id' => $id, 'file_name' => basename($file->getClientOriginalName()),
'media_type' => 'text/plain', 'storage_key' => $key, 'sha256' => hash('sha256', $text),
'status' => 'active', 'data_classification' => 'internal']);
'size_bytes' => strlen($text), 'uploaded_by' => $request->user()->id,
'status' => 'quarantined', 'data_classification' => 'internal']);
$this->audit('documents', $id, 'plain_text_registered', $request->user()->id);
});
} catch (\Throwable $exception) {
@@ -126,6 +129,8 @@ final class AiController extends Controller
throw $exception;
}
ScanDocumentForMalware::dispatch($id)->afterCommit();
return $request->expectsJson() ? response()->json(['document_id' => $id], 201)
: back()->with('success', 'Texto guardado no cadastro documental. Registe a fonte e solicite revisão antes de o pesquisar.');
}
@@ -140,6 +145,7 @@ final class AiController extends Controller
if ($data['status'] === 'approved') {
abort_if((int) $source->submitted_by === $request->user()->id, 403, 'Outra pessoa deve validar a autorização.');
$valid = DB::table('documents')->where('id', $source->document_id)->where('status', 'active')
->where('malware_scan_status', 'clean')->whereColumn('malware_scanned_sha256', 'sha256')
->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])
->where('version_no', $source->document_version)->where('sha256', $source->document_checksum)->exists();
abort_unless($valid && $source->valid_until >= now()->toDateString(), 422, 'Fonte alterada, expirada ou sem autorização.');
@@ -15,7 +15,7 @@ class ReferenceCatalogController extends Controller
public function index(Request $request, string $catalog): JsonResponse
{
abort_unless(in_array($catalog, self::CATALOGS, true), 404);
$catalog = $this->validatedCatalog($catalog);
$rules = [
'q' => ['nullable', 'string', 'max:100'],
@@ -71,7 +71,7 @@ class ReferenceCatalogController extends Controller
};
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, $row))->values();
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values();
return response()->json([
'data' => $items,
@@ -156,32 +156,47 @@ class ReferenceCatalogController extends Controller
return $query;
}
/** @param list<string> $columns */
/** @param list<literal-string> $columns */
private function search(Builder $query, string $search, array $columns): void
{
$term = '%'.addcslashes($search, '%_\\').'%';
$query->where(function (Builder $nested) use ($columns, $term): void {
foreach ($columns as $index => $column) {
$method = $index === 0 ? 'whereRaw' : 'orWhereRaw';
$nested->{$method}($column.' ILIKE ?', [$term]);
if ($index === 0) {
$nested->whereRaw($column.' ILIKE ?', [$term]);
} else {
$nested->orWhereRaw($column.' ILIKE ?', [$term]);
}
}
});
}
/** @return array<string,mixed> */
private function present(string $catalog, object $row): array
/** @return 'authorities'|'jurisdictions'|'economic-activities' */
private function validatedCatalog(string $catalog): string
{
abort_unless(in_array($catalog, self::CATALOGS, true), 404);
return $catalog;
}
/**
* @param 'authorities'|'jurisdictions'|'economic-activities' $catalog
* @param array<string, mixed> $row
* @return array<string,mixed>
*/
private function present(string $catalog, array $row): array
{
return match ($catalog) {
'jurisdictions' => ['id' => $row->id, 'value' => $row->id, 'code' => $row->code, 'name' => $row->name,
'label' => $row->name, 'locale' => 'pt-MZ', 'parent_id' => $row->parent_id, 'type' => $row->location_type,
'source_code' => $row->source_code, 'version_no' => $row->version_no],
'economic-activities' => ['id' => $row->id, 'value' => $row->code, 'code' => $row->code, 'name' => $row->name,
'label' => $row->name, 'locale' => 'pt-MZ', 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
'version_no' => $row->version_no],
'authorities' => ['id' => $row->id, 'value' => $row->code, 'code' => $row->code, 'name' => $row->name,
'label' => $row->name, 'locale' => 'pt-MZ', 'authority_type' => $row->authority_type,
'organization_id' => $row->organization_id, 'jurisdiction_id' => $row->jurisdiction_id,
'jurisdiction_name' => $row->jurisdiction_name, 'version_no' => $row->version_no],
'jurisdictions' => ['id' => $row['id'], 'value' => $row['id'], 'code' => $row['code'], 'name' => $row['name'],
'label' => $row['name'], 'locale' => 'pt-MZ', 'parent_id' => $row['parent_id'], 'type' => $row['location_type'],
'source_code' => $row['source_code'], 'version_no' => $row['version_no']],
'economic-activities' => ['id' => $row['id'], 'value' => $row['code'], 'code' => $row['code'], 'name' => $row['name'],
'label' => $row['name'], 'locale' => 'pt-MZ', 'parent_id' => $row['parent_id'], 'sector_id' => $row['sector_id'],
'version_no' => $row['version_no']],
'authorities' => ['id' => $row['id'], 'value' => $row['code'], 'code' => $row['code'], 'name' => $row['name'],
'label' => $row['name'], 'locale' => 'pt-MZ', 'authority_type' => $row['authority_type'],
'organization_id' => $row['organization_id'], 'jurisdiction_id' => $row['jurisdiction_id'],
'jurisdiction_name' => $row['jurisdiction_name'], 'version_no' => $row['version_no']],
};
}
}
@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\StoreSimulationRequest;
use App\Http\Requests\UpdateSimulationScenarioRequest;
use App\Models\QuestionnaireVersion;
use App\Models\Simulation;
use App\Models\SimulationJob;
use App\Policies\SimulationPolicy;
use App\Services\SimulationExecution;
@@ -65,6 +66,56 @@ class SimulationController extends Controller
return response()->json(['data' => $simulation])->header('ETag', $execution->etag($simulation));
}
public function history(Request $request, SimulationExecution $execution): JsonResponse
{
$user = $request->user();
abort_unless($user !== null, 401);
abort_unless($user->hasVerifiedEmail(), 403, 'Verifique o correio electrónico para consultar o histórico.');
$perPage = min(50, max(1, $request->integer('per_page', 20)));
$page = max(1, $request->integer('page', 1));
$history = DB::transaction(function () use ($execution, $user, $perPage, $page) {
$execution->setContext($user->id, null);
return Simulation::query()
->select([
'simulations.id', 'simulations.organization_id', 'visible_organization.name as organization_name',
'simulations.status', 'simulations.version_no', 'simulations.created_at', 'simulations.updated_at',
])
->leftJoin('organizations as visible_organization', 'visible_organization.id', '=', 'simulations.organization_id')
->where(function ($scope) use ($user) {
$scope->where(fn ($personal) => $personal->whereNull('simulations.organization_id')->where('simulations.owner_user_id', $user->id))
->orWhere(fn ($organization) => $organization->whereNotNull('simulations.organization_id')->whereExists(
fn ($membership) => $membership->selectRaw('1')->from('memberships')
->whereColumn('memberships.organization_id', 'simulations.organization_id')
->where('memberships.user_id', $user->id)->whereNull('memberships.deleted_at'),
));
})
->withExists(['reports as has_ready_report' => fn ($query) => $query->where('status', 'ready')])
->orderByDesc('simulations.created_at')->orderByDesc('simulations.id')
->paginate($perPage, ['*'], 'page', $page);
});
return response()->json([
'data' => $history->getCollection()->map(fn (Simulation $simulation): array => [
'id' => $simulation->id,
'scope' => $simulation->organization_id === null ? 'personal' : 'organization',
'organization_name' => $simulation->getAttribute('organization_name'),
'status' => $simulation->status,
'version_no' => $simulation->version_no,
'created_at' => $simulation->created_at?->toISOString(),
'updated_at' => $simulation->updated_at?->toISOString(),
'has_ready_report' => (bool) $simulation->getAttribute('has_ready_report'),
]),
'meta' => [
'current_page' => $history->currentPage(),
'last_page' => $history->lastPage(),
'per_page' => $history->perPage(),
'total' => $history->total(),
],
])->header('Cache-Control', 'no-store, private');
}
public function updateScenario(UpdateSimulationScenarioRequest $request, string $id, string $scenarioId, SimulationExecution $execution): JsonResponse
{
abort_unless(Str::isUuid($id) && Str::isUuid($scenarioId), 404);
@@ -3,11 +3,16 @@
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\AttachSimulationToDraftRequest;
use App\Http\Requests\ClaimSimulationFormDraftRequest;
use App\Http\Requests\LinkSimulationDraftBusinessRequest;
use App\Http\Requests\StoreSimulationFormDraftRequest;
use App\Models\SimulationFormDraft;
use App\Policies\SimulationPolicy;
use App\Services\SimulationExecution;
use App\Services\SimulationFormDrafts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SimulationFormDraftController extends Controller
@@ -16,13 +21,65 @@ class SimulationFormDraftController extends Controller
{
$key = $request->header('Idempotency-Key');
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
$result = $drafts->create($request->validated(), $request, $key);
$result = $drafts->create($request->snapshots(), $request, $key);
$draft = $result['draft'];
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no, 'replayed' => $result['replayed']]], $result['replayed'] ? 200 : 201)
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no, 'replayed' => $result['replayed']], 'expires_at' => $draft->expires_at?->toISOString()], $result['replayed'] ? 200 : 201)
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function index(Request $request, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless($request->user() !== null, 401);
return response()->json(['data' => $drafts->ownedDrafts($request->user())])->header('Cache-Control', 'no-store, private');
}
public function claimPreview(Request $request, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless($request->user() !== null, 401);
return response()->json(['data' => $drafts->claimPreview($request)])->header('Cache-Control', 'no-store, private');
}
public function claim(ClaimSimulationFormDraftRequest $request, SimulationFormDrafts $drafts): JsonResponse
{
$result = $drafts->claim($request, $request->validated('choice'), $request->validated('existing_draft_id'));
$draft = $result['draft'];
return response()->json(['data' => $drafts->present($draft, true), 'choice' => $result['choice'], 'replayed' => $result['replayed'] ?? false, 'expires_at' => $draft->expires_at?->toISOString()])
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function linkableBusinesses(Request $request, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless($request->user()?->hasVerifiedEmail(), 403);
return response()->json(['data' => $drafts->linkableBusinesses($request->user())])->header('Cache-Control', 'no-store, private');
}
public function businessLink(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id) && $request->user()?->hasVerifiedEmail(), 404);
return response()->json(['data' => $drafts->activeBusinessLink($request->user(), $id)])->header('Cache-Control', 'no-store, private');
}
public function linkBusiness(LinkSimulationDraftBusinessRequest $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id), 404);
$result = $drafts->linkBusiness($request->user(), $id, $request->validated('business_id'));
return response()->json(['data' => $result], isset($result['replayed']) ? 200 : 201)->header('Cache-Control', 'no-store, private');
}
public function unlinkBusiness(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id) && $request->user()?->hasVerifiedEmail(), 404);
return response()->json(['data' => $drafts->unlinkBusiness($request->user(), $id)])->header('Cache-Control', 'no-store, private');
}
public function current(Request $request, SimulationFormDrafts $drafts): JsonResponse
{
$draft = $drafts->current($request);
@@ -30,7 +87,14 @@ class SimulationFormDraftController extends Controller
return response()->json(['data' => null], 200)->header('Cache-Control', 'no-store, private');
}
return response()->json(['data' => $drafts->present($draft)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
return response()->json(['data' => $drafts->present($draft, $request->user() !== null)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function forgetCurrent(Request $request, SimulationFormDrafts $drafts): JsonResponse
{
$drafts->forgetCurrent($request);
return response()->json([], 204)->header('Cache-Control', 'no-store, private');
}
public function show(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
@@ -38,18 +102,82 @@ class SimulationFormDraftController extends Controller
abort_unless(Str::isUuid($id), 404);
$draft = $drafts->find($id, $request);
return response()->json(['data' => $drafts->present($draft)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
return response()->json(['data' => $drafts->present($draft, $request->user() !== null)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function update(StoreSimulationFormDraftRequest $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id), 404);
$draft = $drafts->update($id, $request->validated(), $request);
$draft = $drafts->update($id, $request->snapshots(), $request);
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no]])
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no], 'expires_at' => $draft->expires_at?->toISOString()])
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function renew(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id), 404);
$draft = $drafts->renew($id, $request);
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no], 'expires_at' => $draft->expires_at?->toISOString()])
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function attachSimulation(AttachSimulationToDraftRequest $request, string $id, SimulationFormDrafts $drafts, SimulationExecution $execution): JsonResponse
{
abort_unless(Str::isUuid($id), 404);
$validated = $request->validated();
$simulation = $execution->find($validated['simulation_id'], $request);
$tokenOwned = $simulation->anonymous_token_hash !== null
&& hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request));
if ($request->user()) {
$policy = app(SimulationPolicy::class);
$canTransfer = $simulation->organization_id === null
? $policy->view($request->user(), $simulation)
: $policy->update($request->user(), $simulation);
abort_unless($canTransfer || $tokenOwned, 404);
} else {
abort_unless($tokenOwned, 404);
}
abort_unless($simulation->status === 'completed' && is_array($simulation->result_snapshot), 409, 'Só é possível reutilizar uma simulação concluída.');
$report = $simulation->reports->where('status', 'ready')->sortByDesc('created_at')->first();
abort_unless($report !== null && is_array($report->report_snapshot), 409, 'O relatório versionado da simulação ainda não está disponível.');
abort_unless(preg_match('/^[a-f0-9]{64}$/D', $report->report_sha256) === 1, 409,
'O relatório da simulação não tem um hash verificável.');
$canonicalSnapshots = DB::selectOne('select CAST(? AS jsonb)::text as report_canonical, CAST(? AS jsonb)::text as result_canonical', [
json_encode($report->report_snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
json_encode($simulation->result_snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
]);
abort_unless(hash_equals($report->report_sha256, hash('sha256', $canonicalSnapshots->report_canonical))
&& hash_equals($canonicalSnapshots->report_canonical, $canonicalSnapshots->result_canonical), 409,
'O relatório não corresponde ao resultado versionado da simulação.');
$inputSnapshot = array_intersect_key($simulation->input_snapshot, array_flip(['base', 'rate', 'reduction']));
$sourceSnapshot = [
'simulation_id' => $simulation->id,
'source_version_no' => $simulation->version_no,
'source_created_at' => $simulation->created_at?->toISOString(),
'source_updated_at' => $simulation->updated_at?->toISOString(),
'input_snapshot' => $inputSnapshot,
'calculation_snapshot' => $simulation->calculation_snapshot,
'result_snapshot' => $simulation->result_snapshot,
'result_sha256' => $report->report_sha256,
'report_id' => $report->id,
'report_version_no' => $report->version_no,
'report_sha256' => $report->report_sha256,
'report_snapshot' => $report->report_snapshot,
'consented_at' => now()->toISOString(),
];
$attached = $drafts->attachSimulation($id, $sourceSnapshot, $request);
$draft = $attached['draft'];
return response()->json([
'data' => $drafts->present($draft, $request->user() !== null),
'replayed' => $attached['replayed'],
'expires_at' => $draft->expires_at?->toISOString(),
])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
}
public function destroy(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(Str::isUuid($id), 404);
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\ResolveSimulationTaxParametersRequest;
use App\Services\SimulationTaxParameterResolver;
use Illuminate\Http\JsonResponse;
class SimulationTaxParameterController extends Controller
{
public function resolve(ResolveSimulationTaxParametersRequest $request, SimulationTaxParameterResolver $resolver): JsonResponse
{
$input = $request->validated();
$data = $resolver->resolvePublishedForPeriod(
$input['component'],
$input['period_start'],
$input['period_end'],
$input['context'] ?? [],
);
return response()->json([
'component' => $input['component'],
'period' => ['start' => $input['period_start'], 'end' => $input['period_end']],
'assumptions' => $input['context'] ?? [],
'parameters' => $data,
])->header('Cache-Control', 'no-store');
}
}
+7 -2
View File
@@ -9,6 +9,8 @@ use App\Models\Investor;
use App\Models\Lead;
use App\Models\User;
use App\Services\ConvertInterestToLead;
use App\Services\CountryCatalogue;
use App\Services\DeclaredOriginStatistics;
use App\Services\PortalAudit;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse;
@@ -77,7 +79,8 @@ class CrmController extends Controller
{
$filters = $request->validate(['q' => ['nullable', 'string', 'max:150'],
'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'])
->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())]);
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(),
'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
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DocumentMalwareController extends Controller
{
public function retry(Request $request, string $id): RedirectResponse
{
DB::transaction(function () use ($id): void {
$document = DB::table('documents')->where('id', $id)->lockForUpdate()->first();
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
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.');
DB::table('documents')->where('id', $id)->update([
'status' => 'quarantined', 'malware_scan_status' => 'pending', 'malware_failure_reason' => null, 'updated_at' => now(),
]);
ScanDocumentForMalware::dispatch($id)->afterCommit();
});
return back()->with('success', 'Nova análise colocada na fila. O ficheiro permanece privado até haver resultado.');
}
}
+23 -5
View File
@@ -12,6 +12,7 @@ use App\Models\Skill;
use App\Models\TrainingCapacity;
use App\Models\TrainingProvider;
use App\Services\EducationGapCalculator;
use App\Services\InvestmentGeography;
use App\Services\PortalAudit;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -28,17 +29,22 @@ class EducationController extends Controller
'q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in(['submitted', 'reviewed', 'rejected', 'expired'])],
'geo_location_id' => ['nullable', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'demand_page' => ['nullable', 'integer', 'min:1'],
'capacity_page' => ['nullable', 'integer', 'min:1'],
]);
$demands = LabourDemand::query();
$capacities = TrainingCapacity::query();
$territoryIds = [];
foreach ([$demands, $capacities] as $query) {
if ($term = trim($filters['q'] ?? '')) {
$query->whereLike('qualification', '%'.addcslashes($term, '%_\\').'%');
}
if ($territory = $filters['geo_location_id'] ?? null) {
$query->where('geo_location_id', $territory);
$path = app(InvestmentGeography::class)->selection($filters);
$territory = $filters['geo_location_id'] ?? ($path !== [] ? $path[array_key_last($path)]->id : null);
if ($territory) {
$territoryIds = app(InvestmentGeography::class)->descendants($territory, includeNonPublic: true);
$query->whereIn('geo_location_id', $territoryIds);
}
if (($filters['status'] ?? null) === 'expired') {
$query->where('valid_until', '<', now()->toDateString());
@@ -47,6 +53,17 @@ class EducationController extends Controller
}
}
$territorialCapacities = clone $capacities;
$providers = TrainingProvider::where('status', '!=', 'inactive');
$courses = Course::where('status', '!=', 'retired')
->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'));
if ($territoryIds !== []) {
// Provider and course location is evidenced by their submitted training capacity.
// Do not infer locations from provider names, addresses, or unrelated records.
$courses->whereIn('id', $territorialCapacities->select('course_id'));
$providers->whereIn('id', (clone $courses)->select('provider_id'));
}
return Inertia::render('education/index', [
'demands' => $demands->latest()->orderBy('id')->paginate(20, ['*'], 'demand_page')->withQueryString(),
'capacities' => $capacities->latest()->orderBy('id')->paginate(20, ['*'], 'capacity_page')->withQueryString(),
@@ -59,8 +76,8 @@ class EducationController extends Controller
],
'skills' => Skill::orderBy('name')->get(['id', 'code', 'name']),
'occupations' => Occupation::orderBy('name')->get(['id', 'code', 'name']),
'providers' => TrainingProvider::where('status', '!=', 'inactive')->orderBy('name')->get(['id', 'name']),
'courses' => Course::where('status', '!=', 'retired')->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'))->orderBy('title')->get(['id', 'title', 'provider_id']),
'providers' => $providers->orderBy('name')->get(['id', 'name']),
'courses' => $courses->orderBy('title')->get(['id', 'title', 'provider_id']),
'projects' => Project::orderBy('name')->get(['id', 'code', 'name']),
'territories' => DB::table('geo_locations')->whereNull('deleted_at')
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
@@ -98,7 +115,8 @@ class EducationController extends Controller
$data = $request->validate([
'occupation_id' => ['required', 'uuid', Rule::exists('occupations', 'id')->whereNull('deleted_at')],
'skill_id' => ['required', 'uuid', Rule::exists('skills', 'id')->whereNull('deleted_at')],
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])],
$demand ? 'project_id' : 'course_id' => ['required', 'uuid', $demand
? Rule::exists('projects', 'id')->whereNull('deleted_at')
: Rule::exists('courses', 'id')->whereNull('deleted_at')->whereNot('status', 'retired')
@@ -12,6 +12,7 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use LogicException;
class EducationInvestmentController extends Controller
{
@@ -44,9 +45,13 @@ class EducationInvestmentController extends Controller
return;
}
$territory = app(InvestmentGeography::class)->selection($data, true);
$lastTerritoryKey = array_key_last($territory);
if ($lastTerritoryKey === null) {
throw new LogicException('A proposta educativa exige uma localização territorial.');
}
$province = $territory[0];
$district = $territory[1] ?? null;
$primaryTerritory = $territory[array_key_last($territory)];
$primaryTerritory = $territory[$lastTerritoryKey];
$reference = 'EDU-'.Str::uuid();
$opportunity = new Opportunity;
PortalAudit::save($opportunity, [
@@ -10,6 +10,7 @@ use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake;
use App\Services\ExistingBusinessObjects;
use App\Services\ExistingBusinessVerification;
use App\Services\InvestmentGeography;
use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibilityShadow;
use Illuminate\Http\JsonResponse;
@@ -100,6 +101,7 @@ class ExistingBusinessController extends Controller
'id', 'code', 'modality', 'status', 'classification', 'version_no', 'sector_id', 'public_title', 'public_slug',
'activity_code', 'stage', 'objective', 'currency', 'amount_min', 'amount_max', 'available_percentage',
'funds_use', 'submitted_at', 'published_at', 'expires_at', 'next_action', 'next_action_due_at', 'assigned_to',
]), 'payload' => $business->payload];
]), 'payload' => $business->payload,
'territory_paths' => app(InvestmentGeography::class)->displayPaths($business->payload)];
}
}
@@ -24,7 +24,7 @@ class InvestmentDiscoveryController extends Controller
$filters['education'] = true;
}
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(),
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),
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
@@ -41,11 +41,7 @@ class InvestmentDiscoveryController extends Controller
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->where(function ($query) use ($ids) {
foreach (['project_id' => 'projects', 'cluster_id' => 'economic_clusters', 'corridor_id' => 'development_corridors'] as $foreign => $table) {
$query->orWhereIn($foreign, DB::table($table)->whereNull('deleted_at')->whereIn('primary_territory_id', $ids)->select('id'));
}
});
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, $ids);
}
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
return $query->whereRaw('false')->get();
@@ -53,13 +49,16 @@ class InvestmentDiscoveryController extends Controller
if (in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
$query->whereNotNull($filters['dimension'].'_id');
}
foreach (['zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'geo_location_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) {
if (! empty($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) {
if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) {
return $query->whereRaw('false')->get();
}
}
if (! empty($filters['q'])) {
$query->where('title', 'ilike', '%'.$filters['q'].'%');
$query->where(fn ($q) => $q->where('title', 'ilike', '%'.$filters['q'].'%')->orWhereRaw('content::text ILIKE ?', ['%'.$filters['q'].'%']));
}
foreach (['cluster_id', 'corridor_id', 'project_id'] as $field) {
if (! empty($filters[$field])) {
@@ -84,7 +83,17 @@ class InvestmentDiscoveryController extends Controller
{
$record = Opportunity::published()->with('sector:id,name,slug')->where('slug', $slug)->firstOrFail();
$data = $request->validate(['zone_id' => ['nullable', 'uuid']]);
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'from_dossier' => ['nullable', 'uuid']]);
$dossierOrigin = isset($data['from_dossier']) ? InvestmentPortfolioController::visible()->whereKey($data['from_dossier'])->firstOrFail() : null;
if ($dossierOrigin) {
$linked = false;
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
if ($dossierOrigin->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $record->id)->where($foreign, $dossierOrigin->$foreign)->exists()) {
$linked = true;
}
}
abort_unless($linked, 404);
}
$origin = null;
if (! empty($data['zone_id'])) {
$origin = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
@@ -92,7 +101,12 @@ class InvestmentDiscoveryController extends Controller
abort_unless($origin !== null, 404);
}
return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin]);
$returnFilters = $request->query();
unset($returnFilters['zone_id'], $returnFilters['from_dossier']);
return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin,
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]);
}
public function detailApi(string $slug, InvestmentCatalogue $catalogue): JsonResponse
@@ -114,7 +128,24 @@ class InvestmentDiscoveryController extends Controller
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(\Illuminate\Support\Arr::only($filters, ['education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level']), 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
@@ -43,6 +43,8 @@ class InvestmentLegalSourceController extends Controller
$source = InvestmentLegalSource::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $source->version_no !== (int) $data['version_no'], 409, 'Versão alterada.');
if ($action === 'validate') {
abort_if(str_contains(mb_strtolower($source->article), 'pending') || str_contains(mb_strtolower($source->article), 'pendente')
|| str_contains(mb_strtolower($source->article), 'a rever'), 422, 'Indique o artigo e confirme o texto oficial antes da validação.');
abort_if((int) $source->owner_id === $request->user()->id, 403, 'Outra pessoa deve validar a fonte.');
abort_unless($source->validation_status === 'pending', 422, 'Crie nova referência para substituir fonte revogada.');
}
@@ -3,10 +3,15 @@
namespace App\Http\Controllers;
use App\Models\InvestmentDossier;
use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Models\Project;
use App\Services\InvestmentGeography;
use App\Services\InvestmentRelations;
use App\Services\InvestmentZones;
use App\Services\PortalAudit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -17,9 +22,15 @@ class InvestmentPortfolioController extends Controller
{
public static function related(InvestmentDossier $first, InvestmentDossier $second): bool
{
foreach ([[$first, $second], [$second, $first]] as [$cluster, $project]) {
if ($cluster->cluster_id && $project->project_id && app(InvestmentRelations::class)->memberships()
->where('cp.cluster_id', $cluster->cluster_id)->where('cp.project_id', $project->project_id)->exists()) {
return true;
}
}
foreach ([['corridor_projects', 'corridor_id', 'project_id'], ['corridor_clusters', 'corridor_id', 'cluster_id'], ['cluster_projects', 'cluster_id', 'project_id']] as [$table, $left, $right]) {
foreach ([[$first, $second], [$second, $first]] as [$a, $b]) {
if ($a->$left && $b->$right && DB::table($table)->where($left, $a->$left)->where($right, $b->$right)->whereNull('deleted_at')->exists()) {
if ($a->$left && $b->$right && self::currentRelation(DB::table($table)->where($left, $a->$left)->where($right, $b->$right))->exists()) {
return true;
}
}
@@ -28,6 +39,13 @@ class InvestmentPortfolioController extends Controller
return false;
}
private static function currentRelation(QueryBuilder $query): QueryBuilder
{
return $query->whereNull('deleted_at')->where('validation_status', 'validated')
->whereDate('valid_from', '<=', today()->toDateString())
->where(fn ($q) => $q->whereNull('valid_until')->orWhereDate('valid_until', '>=', today()->toDateString()));
}
/** @return Builder<InvestmentDossier> */
public static function visible(): Builder
{
@@ -42,17 +60,23 @@ class InvestmentPortfolioController extends Controller
public function index(Request $request): Response
{
$management = $request->routeIs('management.portfolio*');
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'kind' => ['nullable', 'in:corridor,cluster,project']]);
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'kind' => ['nullable', 'in:corridor,cluster,project'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
$query = $management ? InvestmentDossier::query() : self::visible();
if (! empty($filters['kind'])) {
$query->whereNotNull($filters['kind'].'_id');
}
if (! empty($filters['q'])) {
$query->where('title', 'ilike', '%'.$filters['q'].'%');
$query->where(fn ($q) => $q->where('title', 'ilike', '%'.$filters['q'].'%')->orWhereRaw('content::text ILIKE ?', ['%'.$filters['q'].'%']));
}
$territorySelection = app(InvestmentGeography::class)->selection($filters);
if ($territorySelection !== []) {
$territoryIds = app(InvestmentGeography::class)->descendants($territorySelection[array_key_last($territorySelection)]->id);
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, $territoryIds);
}
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(),
'management' => $management, 'filters' => $filters]);
'management' => $management, 'filters' => $filters, 'territorySelection' => $territorySelection]);
}
public function show(Request $request, string $id): Response
@@ -63,8 +87,8 @@ class InvestmentPortfolioController extends Controller
foreach ([['corridor_projects', 'corridor_id', 'project_id'], ['corridor_clusters', 'corridor_id', 'cluster_id'], ['cluster_projects', 'cluster_id', 'project_id']] as [$table, $left, $right]) {
foreach ([[$left, $right], [$right, $left]] as [$origin, $destination]) {
if ($record->$origin) {
$relatedIds[$destination] = array_merge($relatedIds[$destination] ?? [], DB::table($table)
->where($origin, $record->$origin)->whereNull('deleted_at')->pluck($destination)->all());
$relatedIds[$destination] = array_merge($relatedIds[$destination] ?? [], self::currentRelation(DB::table($table)
->where($origin, $record->$origin))->pluck($destination)->all());
}
}
}
@@ -98,7 +122,17 @@ class InvestmentPortfolioController extends Controller
}
}
$anchorProject = $record->project_id
? Project::whereKey($record->project_id)->whereNull('deleted_at')->where('status', '!=', 'draft')->first(['id', 'code', 'name', 'status', 'budget_amount', 'budget_currency', 'start_date', 'end_date'])
: null;
$existingSubmissions = ! $management && $request->user()
? InvestmentSubmission::where('user_id', $request->user()->id)->where('dossier_id', $record->id)->where('status', 'draft')
->orderByDesc('updated_at')->limit(10)->get(['id', 'version', 'updated_at'])
: collect();
return Inertia::render('portfolio/show', ['record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
}
@@ -114,7 +148,7 @@ class InvestmentPortfolioController extends Controller
'publication_status' => 'draft', 'published_at' => null, 'approval_evidence' => null, 'approval_basis' => 'manager'], $request->user()->id);
});
return back()->with('success', 'Rascunho guardado. Pode aprovar e publicar a ficha.');
return back()->with('success', 'Rascunho guardado. A publicacao aguarda um revisor diferente do editor.');
}
public function publish(Request $request, InvestmentDossier $dossier): RedirectResponse
@@ -123,6 +157,8 @@ class InvestmentPortfolioController extends Controller
DB::transaction(function () use ($request, $dossier, $data) {
$dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail();
abort_if($dossier->version_no !== (int) $data['version_no'], 409, 'A ficha foi alterada. Recarregue a página e reveja a versão actual antes de publicar.');
abort_unless($dossier->editor_id !== null, 422, 'A ficha deve ser assumida e revista antes da publicacao.');
abort_if((int) $dossier->editor_id === (int) $request->user()->id, 403, 'A publicacao exige um revisor diferente do editor.');
PortalAudit::save($dossier, [...$data, 'version_no' => $dossier->version_no + 1, 'approval_basis' => 'manager', 'reviewer_id' => $request->user()->id, 'publication_status' => 'published', 'published_at' => now()], $request->user()->id);
});
@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentRelationshipRepair;
use App\Services\InvestmentTerritorialTraceability;
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 InvestmentRelationshipRepairController extends Controller
{
public function preview(InvestmentRelationshipRepair $repair): Response
{
return Inertia::render('management/relationship-repair', [...$repair->preview(), 'traceability' => app(InvestmentTerritorialTraceability::class)->preview()]);
}
public function apply(Request $request, InvestmentRelationshipRepair $repair): RedirectResponse|JsonResponse
{
if ($request->input('operation') === 'traceability') {
$data = $request->validate(['hash' => ['required', 'string', 'size:64'], 'reverse' => ['required', 'boolean'],
'reason' => ['required_if:reverse,true', 'nullable', 'string', 'max:1000'], 'confirm_reverse' => ['accepted_if:reverse,true']]);
try {
$result = app(InvestmentTerritorialTraceability::class)->apply($data['hash'], $request->user()->id, $data['reverse'], $data['reason'] ?? null);
} catch (HttpException $exception) {
if ($request->expectsJson()) {
throw $exception;
}
return back()->withErrors(['operation' => $exception->getMessage()]);
}
return $request->expectsJson() ? response()->json($result) : back()->with('success', $data['reverse'] ? 'Rastreabilidade revertida, histórico preservado.' : 'Rastreabilidade aplicada; validações e dados territoriais preservados.');
}
$data = $request->validate(['hash' => ['required', 'string', 'size:64'], 'row_id' => ['nullable', 'string', 'size:64'],
'validation_hash' => ['required_with:row_id', 'nullable', 'string', 'size:64']]);
$result = $repair->apply($data['hash'], $request->user()->id, $data['row_id'] ?? null, $data['validation_hash'] ?? null);
return $request->expectsJson() ? response()->json($result) : back()->with('success', $result['replayed'] ? 'Este plano já foi aplicado; nenhum duplicado criado.' : 'Associações documentadas aplicadas. Registos de oportunidades permanecem preparados sem publicação automática.');
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use App\Models\ClusterProject;
use App\Models\DevelopmentCorridor;
use App\Models\EconomicCluster;
use App\Models\InvestmentGap;
use App\Models\Project;
@@ -21,7 +22,7 @@ class InvestmentStructureController extends Controller
public function index(Request $request, string $structure): Response
{
$filters = $request->validate(['q' => ['nullable', 'string', 'max:150']]);
$model = $structure === 'projects' ? Project::class : EconomicCluster::class;
$model = $this->model($structure);
$query = $model::query();
if ($term = $filters['q'] ?? null) {
$query->where(function ($q) use ($term): void {
@@ -33,9 +34,9 @@ class InvestmentStructureController extends Controller
'records' => $query->orderBy('name')->orderBy('id')->paginate(20)->withQueryString()]);
}
public function edit(string $structure, ?string $id = null): Response
public function edit(Request $request, string $structure, ?string $id = null): Response
{
$model = $structure === 'projects' ? Project::class : EconomicCluster::class;
$model = $this->model($structure);
$record = $id ? $model::findOrFail($id) : null;
return Inertia::render('structures/editor', ['structure' => $structure, 'record' => $record,
@@ -49,30 +50,36 @@ class InvestmentStructureController extends Controller
->whereNull('origins.deleted_at')->whereNull('destinations.deleted_at')->whereNull('value_chain_links.deleted_at')
->orderBy('origins.code')->orderBy('destinations.code')
->get(['value_chain_links.id', 'origins.name as origin', 'destinations.name as destination', 'link_type']) : [],
'viewerId' => $request->user()->id,
'memberships' => $structure === 'clusters' && $id ? DB::table('cluster_projects')
->join('projects', 'projects.id', '=', 'cluster_projects.project_id')
->where('cluster_id', $id)->whereNull('cluster_projects.deleted_at')->whereNull('projects.deleted_at')
->orderBy('projects.name')->get(['cluster_projects.id', 'project_id', 'role', 'projects.name']) : [],
->orderBy('projects.name')->get(['cluster_projects.id', 'cluster_projects.project_id', 'cluster_projects.role', 'cluster_projects.association_type', 'cluster_projects.source_reference', 'cluster_projects.evidence_reference', 'cluster_projects.valid_from', 'cluster_projects.valid_until', 'cluster_projects.validation_status', 'cluster_projects.version_no', 'cluster_projects.editor_id', 'projects.name']) : [],
]);
}
public function save(Request $request, string $structure, ?string $id = null): RedirectResponse
{
$isProject = $structure === 'projects';
$model = $isProject ? Project::class : EconomicCluster::class;
$isCluster = $structure === 'clusters';
$isCorridor = $structure === 'corridors';
$model = $this->model($structure);
$record = $id ? $model::findOrFail($id) : new $model;
$rules = [
'code' => ['required', 'string', 'max:100', Rule::unique($record->getTable(), 'code')->whereNull('deleted_at')->ignore($record->getKey())],
'name' => ['required', 'string', 'max:200'],
'status' => ['required', Rule::in($isProject ? ['draft', 'planned', 'active', 'suspended', 'completed', 'cancelled'] : ['planned', 'active', 'inactive'])],
'status' => ['required', Rule::in($isProject ? ['draft', 'planned', 'active', 'suspended', 'completed', 'cancelled'] : ($isCluster ? ['planned', 'active', 'inactive'] : ['proposed', 'active', 'closed']))],
];
if ($isProject || $isCorridor) {
$rules['description'] = ['nullable', 'string', 'max:10000'];
}
if ($isProject) {
$rules += ['description' => ['nullable', 'string', 'max:10000'],
$rules += [
'budget_amount' => ['nullable', 'required_with:budget_currency', 'regex:/^\d{1,18}(\.\d{1,2})?$/'],
'budget_currency' => ['nullable', 'required_with:budget_amount', 'regex:/^[A-Z]{3}$/'],
'start_date' => ['nullable', 'date_format:Y-m-d'],
'end_date' => ['nullable', 'date_format:Y-m-d', ...($request->filled('start_date') ? ['after_or_equal:start_date'] : [])]];
} else {
} elseif ($isCluster) {
$rules['sector'] = ['required', 'string', 'max:200'];
}
if (! $id) {
@@ -92,14 +99,52 @@ class InvestmentStructureController extends Controller
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Registo guardado.');
}
/** @return class-string<Project|EconomicCluster|DevelopmentCorridor> */
private function model(string $structure): string
{
return match ($structure) {
'projects' => Project::class,
'clusters' => EconomicCluster::class,
'corridors' => DevelopmentCorridor::class,
default => abort(404),
};
}
public function linkProject(Request $request, EconomicCluster $cluster): RedirectResponse
{
$data = $request->validate(['project_id' => ['required', 'uuid', Rule::exists('projects', 'id')->whereNull('deleted_at')],
'role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])]]);
'version_no' => ['required', 'integer', 'min:0'],
'role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])],
'association_type' => ['required', Rule::in(['official', 'influence', 'proximity', 'potential', 'historical'])],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'evidence_reference' => ['required', 'string', 'min:3', 'max:2000'],
'valid_from' => ['required', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from']]);
DB::transaction(function () use ($cluster, $data, $request) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
$link = ClusterProject::where('cluster_id', $cluster->id)->where('project_id', $data['project_id'])->first() ?? new ClusterProject;
PortalAudit::save($link, [...$data, 'cluster_id' => $cluster->id], $request->user()->id);
$link = ClusterProject::where('cluster_id', $cluster->id)->where('project_id', $data['project_id'])->whereNull('deleted_at')->lockForUpdate()->first();
if ($link) {
abort_if((int) $link->version_no !== (int) $data['version_no'], 409, 'Versao da associacao alterada.');
$changed = false;
foreach (['role', 'association_type', 'source_reference', 'evidence_reference', 'valid_from', 'valid_until'] as $field) {
$current = $link->getAttribute($field);
$current = $current instanceof \DateTimeInterface ? $current->format('Y-m-d') : $current;
if (($current ?: null) !== (($data[$field] ?? null) ?: null)) {
$changed = true;
break;
}
}
if (! $changed) {
return;
}
} else {
abort_if((int) $data['version_no'] !== 0, 409, 'A associacao foi alterada. Actualize a pagina.');
$link = new ClusterProject;
}
unset($data['version_no']);
$nextVersion = $link->exists ? ((int) $link->version_no + 1) : 1;
PortalAudit::save($link, [...$data, 'cluster_id' => $cluster->id, 'validation_status' => 'pending',
'editor_id' => $request->user()->id, 'validator_id' => null, 'version_no' => $nextVersion], $request->user()->id);
});
return back()->with('success', 'Associação ao projecto guardada.');
@@ -0,0 +1,85 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class InvestmentStructureRelationController extends Controller
{
private const TABLES = [
'cluster-project' => ['cluster_projects', 'cluster_id', 'project_id', 'economic_clusters', 'projects'],
'corridor-project' => ['corridor_projects', 'corridor_id', 'project_id', 'development_corridors', 'projects'],
'corridor-cluster' => ['corridor_clusters', 'corridor_id', 'cluster_id', 'development_corridors', 'economic_clusters'],
];
public function store(Request $request, string $kind): RedirectResponse
{
[$table, $left, $right, $leftTable, $rightTable] = $this->definition($kind);
$data = $request->validate([
$left => ['required', 'uuid', Rule::exists($leftTable, 'id')->whereNull('deleted_at')],
$right => ['required', 'uuid', Rule::exists($rightTable, 'id')->whereNull('deleted_at')],
'association_type' => ['required', Rule::in(['official', 'influence', 'proximity', 'potential', 'historical'])],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'evidence_reference' => ['required', 'string', 'min:3', 'max:2000'],
'valid_from' => ['required', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
...($kind === 'cluster-project' ? ['role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])]] : []),
]);
DB::transaction(function () use ($data, $table, $left, $right, $leftTable, $request): void {
DB::table($leftTable)->where('id', $data[$left])->lockForUpdate()->firstOrFail();
$existing = DB::table($table)->where($left, $data[$left])->where($right, $data[$right])->whereNull('deleted_at')->lockForUpdate()->first();
abort_if($existing !== null, 409, 'Associacao ja registada.');
$values = [...$data, 'association_type' => $data['association_type'], 'validation_status' => 'pending',
'editor_id' => $request->user()->id, 'validator_id' => null, 'version_no' => 1,
'deleted_at' => null, 'updated_at' => now()];
$id = (string) Str::uuid();
DB::table($table)->insert([...$values, 'id' => $id, 'source_system' => 'portal-management']);
$this->audit($request, $table, $id, 'submitted', 1);
});
return back()->with('success', 'Associacao submetida para revisao independente.');
}
public function review(Request $request, string $kind, string $id, string $action): RedirectResponse
{
abort_unless(in_array($action, ['validate', 'revoke'], true), 404);
[$table] = $this->definition($kind);
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
DB::transaction(function () use ($request, $table, $id, $action, $data): void {
$relation = DB::table($table)->where('id', $id)->lockForUpdate()->first();
abort_unless($relation !== null, 404);
abort_if((int) $relation->version_no !== (int) $data['version_no'], 409, 'Versao da associacao alterada.');
if ($action === 'validate') {
abort_if((int) $relation->editor_id === (int) $request->user()->id, 403, 'A associacao exige revisao independente.');
abort_unless($relation->validation_status === 'pending' && $relation->source_reference && $relation->evidence_reference && $relation->valid_from, 422, 'Fonte, evidencia ou vigencia em falta.');
}
$nextVersion = (int) $relation->version_no + 1;
DB::table($table)->where('id', $id)->update(['validation_status' => $action === 'validate' ? 'validated' : 'revoked',
'validator_id' => $request->user()->id, 'version_no' => $nextVersion, 'updated_at' => now()]);
$this->audit($request, $table, $id, $action, $nextVersion);
});
return back()->with('success', $action === 'validate' ? 'Associacao validada.' : 'Associacao revogada.');
}
/** @return array{string,string,string,string,string} */
private function definition(string $kind): array
{
abort_unless(isset(self::TABLES[$kind]), 404);
return self::TABLES[$kind];
}
private function audit(Request $request, string $table, string $id, string $action, int $version): void
{
DB::table('audit_events')->insert(['source_system' => 'investment-structure-relations', 'entity_type' => $table,
'entity_id' => $id, 'actor_user_id' => $request->user()->id, 'action' => $action,
'after_data' => json_encode(['version_no' => $version, 'validation_status' => $action === 'validate' ? 'validated' : null], JSON_THROW_ON_ERROR)]);
}
}
@@ -2,6 +2,7 @@
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\InvestmentSpecificNeed;
use App\Models\InvestmentSubmission;
@@ -48,7 +49,7 @@ class InvestmentSubmissionController extends Controller
$company = DB::table('investment_company_declarations')->where('id', $data['company_id'])->where('user_id', $request->user()->id)->first();
abort_unless($company !== null, 404);
$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];
}
unset($data['company_id']);
if (! empty($data['opportunity_id'])) {
@@ -110,7 +111,7 @@ class InvestmentSubmissionController extends Controller
$target = $row->opportunity_id ? Opportunity::published()->find($row->opportunity_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']);
$data = ['submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
$data = ['countries' => app(\App\Services\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), 'references' => [
...$catalogue->references(), 'options' => DB::table('investment_reference_options')->orderBy('label')->get()],
'needs' => InvestmentSpecificNeed::where('submission_id', $id)->get(),
@@ -143,10 +144,13 @@ class InvestmentSubmissionController extends Controller
{
$required = $submitting ? 'required' : 'nullable';
$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,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.residence_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.incorporation_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'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.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.experience' => ['nullable', 'string', 'max:2000'], 'payload.investment_capacity' => ['nullable', 'string', 'max:1000'],
'payload.profile_id' => [$required, 'integer'], 'payload.sector' => [$required, 'string', 'max:150'],
@@ -256,10 +260,13 @@ class InvestmentSubmissionController extends Controller
$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,
'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(),
'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$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,
...($zoneOrigin ? ['zone_origin' => (array) $zoneOrigin] : [])]]));
$row->update(['payload' => $p, 'version' => $row->version + 1, 'interest_request_id' => $interest->id, 'status' => 'submitted']);
InvestmentSpecificNeed::where('submission_id', $id)->delete();
@@ -293,7 +300,8 @@ class InvestmentSubmissionController extends Controller
abort_unless($key !== false, 500);
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'investor-submission', 'file_name' => basename($file->getClientOriginalName()),
'media_type' => $file->getMimeType(), 'storage_key' => $key, 'sha256' => hash_file('sha256', Storage::disk('local')->path($key)),
'status' => 'active', 'data_classification' => 'confidential']);
'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id,
'status' => 'quarantined', 'data_classification' => 'confidential']);
DB::table('investment_submission_attachments')->insert(['id' => (string) Str::uuid(), 'submission_id' => $id, 'document_id' => $documentId, 'created_at' => now(), 'updated_at' => now()]);
$row->increment('version');
$this->event($row, $request, 'attachment_added');
@@ -307,6 +315,8 @@ class InvestmentSubmissionController extends Controller
throw $e;
}
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
return $request->expectsJson() ? response()->json(['version' => $version]) : back()->with('success', 'Anexo privado guardado.');
}
@@ -314,13 +324,16 @@ class InvestmentSubmissionController extends Controller
{
$this->owned($request, $id);
$doc = DB::table('investment_submission_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.id', $attachment)->where('a.submission_id', $id)->where('d.status', 'active')->whereNull('d.deleted_at')->first(['d.file_name', 'd.storage_key', 'd.sha256']);
->where('a.id', $attachment)->where('a.submission_id', $id)->where('d.status', 'active')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
->first(['d.file_name', 'd.storage_key', 'd.sha256', 'd.malware_scanned_sha256']);
abort_unless($doc !== null, 404);
$root = realpath(Storage::disk('local')->path('investment-submissions/'.$id));
$path = realpath(Storage::disk('local')->path($doc->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$hash = hash_file('sha256', $path);
abort_unless(is_string($hash) && hash_equals($doc->sha256, $hash), 404);
abort_unless(is_string($hash) && hash_equals($doc->sha256, $hash)
&& hash_equals($doc->sha256, (string) $doc->malware_scanned_sha256), 404);
return response()->download($path, basename($doc->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
}
@@ -18,7 +18,7 @@ class InvestmentWorkspaceController extends Controller
{
public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse
{
$data = ['account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
$data = ['countries' => app(\App\Services\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) {
$company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
@@ -31,7 +31,8 @@ class InvestmentWorkspaceController extends Controller
public function saveProfile(Request $request): RedirectResponse|JsonResponse
{
$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(\App\Services\CountryCatalogue::class)->rule()],
'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.investment_capacity' => ['nullable', 'string', 'max:1000']]);
@@ -53,8 +54,9 @@ class InvestmentWorkspaceController extends Controller
public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse
{
$data = $request->validate(['version' => ['required', 'integer', 'min:0'],
'payload' => ['required', 'array:name,country,registration,sector,role,description'],
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required', 'string', 'max:100'],
'payload' => ['required', 'array:name,country,incorporation_country_code,registration,sector,role,description'],
'payload.incorporation_country_code' => ['nullable', 'string', app(\App\Services\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.role' => ['required', 'string', 'max:150'], 'payload.description' => ['nullable', 'string', 'max:2000']]);
$result = DB::transaction(function () use ($request, $id, $data) {
@@ -0,0 +1,206 @@
<?php
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InvestmentZone;
use App\Services\InvestmentZoneAccess;
use App\Services\InvestmentZones;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class InvestmentZoneAttachmentController extends Controller
{
private const ALLOWED_MIME_TYPES = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];
public function store(Request $request, string $id): JsonResponse
{
$zone = InvestmentZone::whereKey($id)->firstOrFail();
$data = $request->validate([
'file' => ['required', 'file', 'mimetypes:application/pdf,image/jpeg,image/png,image/webp', 'max:20480'],
'kind' => ['required', 'in:legal_instrument,map,photo,study,other'],
'caption' => ['required', 'string', 'max:255'],
'source_reference' => ['required', 'string', 'min:5', 'max:2000'],
'source_date' => ['nullable', 'date_format:Y-m-d'],
'rights_status' => ['required', 'in:pending,confirmed,restricted'],
'rights_basis' => ['nullable', 'string', 'max:2000'],
]);
$file = $request->file('file');
abort_unless(in_array($file->getMimeType(), self::ALLOWED_MIME_TYPES, true), 422, 'Formato de ficheiro não permitido.');
$this->validateFileContent($file->getRealPath(), $file->getMimeType());
abort_if(DB::table('investment_zone_attachments')->where('zone_id', $id)->count() >= 20, 422, 'Máximo de vinte anexos por zona.');
$attachmentId = (string) Str::uuid();
$documentId = (string) Str::uuid();
$key = null;
try {
$key = $file->storeAs('investment-zones/'.$id, $documentId, 'local');
abort_unless($key !== false, 500, 'Não foi possível guardar o ficheiro.');
$hash = hash_file('sha256', Storage::disk('local')->path($key));
abort_unless(is_string($hash), 500, 'Não foi possível verificar o ficheiro guardado.');
$attachment = DB::transaction(function () use ($request, $zone, $data, $file, $attachmentId, $documentId, $key, $hash): object {
DB::table('documents')->insert([
'id' => $documentId, 'source_system' => 'investment-zones', 'version_no' => 1,
'data_classification' => 'confidential', 'file_name' => basename($file->getClientOriginalName()),
'media_type' => $file->getMimeType(), 'storage_key' => $key, 'sha256' => $hash,
// Follow the portal's existing file policy: no antivirus engine is configured, so uploads stay quarantined.
'status' => 'quarantined', 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id,
'created_at' => now(), 'updated_at' => now(),
]);
DB::table('investment_zone_attachments')->insert([
'id' => $attachmentId, 'zone_id' => $zone->id, 'document_id' => $documentId,
'kind' => $data['kind'], 'caption' => $data['caption'], 'source_reference' => $data['source_reference'],
'source_date' => $data['source_date'] ?? null, 'rights_status' => $data['rights_status'],
'rights_basis' => $data['rights_basis'] ?? null, 'personal_data_status' => 'unknown',
'review_status' => 'pending', 'uploaded_by' => $request->user()->id, 'version_no' => 1,
'created_at' => now(), 'updated_at' => now(),
]);
$this->event($attachmentId, $request->user()->id, 'uploaded', 1, ['kind' => $data['kind'], 'sha256' => $hash]);
return DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.id', $attachmentId)->first(['a.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.sha256', 'd.malware_scan_status', 'd.malware_failure_reason']);
});
} catch (\Throwable $exception) {
if (is_string($key)) {
Storage::disk('local')->delete($key);
}
throw $exception;
}
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
return response()->json($attachment, 201);
}
public function review(Request $request, string $id, string $action): JsonResponse
{
abort_unless(in_array($action, ['review', 'select-public', 'withdraw-public'], true), 404);
$rules = ['version_no' => ['required', 'integer', 'min:1']];
if ($action === 'review') {
$rules += ['decision' => ['required', 'in:reviewed,rejected'],
'personal_data_status' => ['required', 'in:none,present,unknown'],
'rights_status' => ['required', 'in:pending,confirmed,restricted'],
'rights_basis' => ['nullable', 'string', 'max:2000']];
}
$data = $request->validate($rules);
if ($action === 'select-public' || $action === 'withdraw-public') {
InvestmentZoneAccess::requireRole($request->user(), 'publishers');
}
return DB::transaction(function () use ($request, $id, $action, $data): JsonResponse {
$attachment = DB::table('investment_zone_attachments')->where('id', $id)->lockForUpdate()->first();
abort_unless($attachment !== null, 404);
abort_if((int) $attachment->version_no !== (int) $data['version_no'], 409, 'O anexo foi alterado. Recarregue antes de continuar.');
$version = (int) $attachment->version_no + 1;
$changes = ['version_no' => $version, 'updated_at' => now()];
$metadata = [];
if ($action === 'review') {
abort_if($data['rights_status'] === 'confirmed' && trim((string) ($data['rights_basis'] ?? $attachment->rights_basis)) === '', 422, 'Registe o fundamento dos direitos antes de os confirmar.');
$changes += [
'review_status' => $data['decision'], 'reviewed_by' => $request->user()->id, 'reviewed_at' => now(),
'independent_review' => (int) $attachment->uploaded_by !== (int) $request->user()->id,
'personal_data_status' => $data['personal_data_status'], 'rights_status' => $data['rights_status'],
'rights_basis' => $data['rights_basis'] ?? $attachment->rights_basis,
'publicly_selected' => false, 'publicly_selected_at' => null, 'publicly_selected_by' => null,
];
$metadata = ['decision' => $data['decision'], 'independent_review' => $changes['independent_review'], 'personal_data_status' => $data['personal_data_status'], 'rights_status' => $data['rights_status']];
} elseif ($action === 'select-public') {
abort_unless($attachment->review_status === 'reviewed' && $attachment->rights_status === 'confirmed'
&& trim((string) $attachment->rights_basis) !== '' && $attachment->personal_data_status === 'none', 422, 'O anexo precisa de revisão registada, fundamento dos direitos, confirmação de divulgação e verificação de ausência de dados pessoais.');
abort_unless(DB::table('documents')->where('id', $attachment->document_id)->where('status', 'active')
->where('malware_scan_status', 'clean')->whereColumn('malware_scanned_sha256', 'sha256')->exists(), 422,
'A análise antimalware tem de terminar sem ameaça antes da divulgação.');
abort_unless(app(InvestmentZones::class)->visible()->whereKey($attachment->zone_id)->exists(), 422, 'A zona deve estar publicada antes da divulgação do anexo.');
$changes += ['publicly_selected' => true, 'publicly_selected_at' => now(), 'publicly_selected_by' => $request->user()->id];
} else {
$changes += ['publicly_selected' => false, 'publicly_selected_at' => null, 'publicly_selected_by' => null];
}
DB::table('investment_zone_attachments')->where('id', $id)->update($changes);
$this->event($id, $request->user()->id, $action, $version, $metadata);
return response()->json(DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.id', $id)->first(['a.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.sha256', 'd.malware_scan_status', 'd.malware_failure_reason']));
});
}
public function downloadPrivate(string $zoneId, string $id): BinaryFileResponse
{
$record = DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.id', $id)->where('a.zone_id', $zoneId)->where('d.status', 'active')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
->first(['d.file_name', 'd.storage_key', 'd.sha256', 'd.media_type', 'd.malware_scanned_sha256']);
abort_unless($record !== null, 404);
return $this->verifiedDownload($zoneId, $record);
}
public function downloadPublic(string $zoneId, string $id): BinaryFileResponse
{
abort_unless(app(InvestmentZones::class)->visible()->whereKey($zoneId)->exists(), 404);
$record = DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.id', $id)->where('a.zone_id', $zoneId)->where('a.publicly_selected', true)
->where('a.review_status', 'reviewed')->where('a.rights_status', 'confirmed')->where('a.personal_data_status', 'none')
->where('d.status', 'active')->whereNull('d.deleted_at')->where('d.malware_scan_status', 'clean')
->whereColumn('d.malware_scanned_sha256', 'd.sha256')->first(['d.file_name', 'd.storage_key', 'd.sha256', 'd.media_type', 'd.malware_scanned_sha256']);
abort_unless($record !== null, 404);
$extension = match ($record->media_type) {
'application/pdf' => 'pdf', 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', default => 'bin'
};
return $this->verifiedDownload($zoneId, $record, str_starts_with($record->media_type, 'image/'), 'zone-attachment-'.$id.'.'.$extension);
}
private function verifiedDownload(string $zoneId, \stdClass $document, bool $inline = false, ?string $downloadName = null): BinaryFileResponse
{
$root = realpath(Storage::disk('local')->path('investment-zones/'.$zoneId));
$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);
$hash = hash_file('sha256', $path);
abort_unless(is_string($hash) && hash_equals(trim($document->sha256), $hash)
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
$headers = ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff'];
$safeName = $downloadName ?? basename($document->file_name);
return $inline
? response()->file($path, $headers + ['Content-Type' => $document->media_type, 'Content-Disposition' => 'inline; filename="'.$safeName.'"'])
: response()->download($path, $safeName, $headers);
}
private function validateFileContent(string $path, string $mime): void
{
if ($mime === 'application/pdf') {
$handle = fopen($path, 'rb');
$signature = $handle ? fread($handle, 5) : false;
if (is_resource($handle)) {
fclose($handle);
}
abort_unless($signature === '%PDF-', 422, 'O conteúdo não corresponde a um PDF válido.');
return;
}
$image = @getimagesize($path);
abort_unless($image && $image[0] > 0 && $image[1] > 0 && $image[0] * $image[1] <= 40000000, 422, 'A imagem é inválida ou excede 40 megapíxeis.');
$expected = ['image/jpeg' => IMAGETYPE_JPEG, 'image/png' => IMAGETYPE_PNG, 'image/webp' => IMAGETYPE_WEBP][$mime] ?? null;
abort_unless($expected !== null && $image[2] === $expected, 422, 'O conteúdo da imagem não corresponde ao formato declarado.');
}
/** @param array<string,mixed> $metadata */
private function event(string $attachmentId, int $actor, string $action, int $version, array $metadata = []): void
{
DB::table('investment_zone_attachment_events')->insert([
'id' => (string) Str::uuid(), 'attachment_id' => $attachmentId, 'actor_id' => $actor,
'action' => $action, 'version_no' => $version, 'metadata' => json_encode($metadata, JSON_THROW_ON_ERROR), 'created_at' => now(),
]);
}
}
+157 -15
View File
@@ -7,14 +7,18 @@ use App\Models\InvestmentZone;
use App\Models\Opportunity;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\InvestmentTerritorialTraceability;
use App\Services\InvestmentZoneAccess;
use App\Services\InvestmentZones;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class InvestmentZoneController extends Controller
{
@@ -22,8 +26,15 @@ class InvestmentZoneController extends Controller
{
$management = $request->is('management/*', 'api/v2/investment/admin/*');
$zone = ($management ? InvestmentZone::query() : $zones->visible())->findOrFail($id);
$publicFields = ['id', 'code', 'category', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'validation_status', 'updated_at'];
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->first(['title', 'url', 'diploma', 'article', 'competent_entity', 'valid_from', 'valid_until', 'version_no']);
$territoryPath = app(InvestmentGeography::class)->path($zone->primary_territory_id, $management);
$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('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'];
$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'))
->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']);
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->first(['title', 'url', 'diploma', 'article', 'competent_entity', 'valid_from', 'valid_until', 'validation_status', 'version_no']);
$operator = DB::table('organizations')->where('id', $zone->operator_id)->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->value('name');
$field = ['zee' => 'zee_id', 'zfi' => 'zfi_id', 'industrial_park' => 'park_id'][$zone->category] ?? null;
@@ -33,7 +44,26 @@ class InvestmentZoneController extends Controller
$relations = $zones->links(true)->where('zl.zone_id', $id)->whereNotNull('zl.'.$foreign);
$related = $related->merge(InvestmentPortfolioController::visible()->whereIn($foreign, $relations->select('zl.'.$foreign))->get());
}
$attachmentColumns = $management
? ['a.id', 'a.kind', 'a.caption', 'a.source_reference', 'a.source_date', 'a.rights_status', 'a.rights_basis', 'a.personal_data_status',
'a.review_status', 'a.reviewed_by', 'a.reviewed_at', 'a.independent_review', 'a.publicly_selected', 'a.publicly_selected_by',
'a.version_no', 'a.uploaded_by', 'a.created_at', 'd.id as document_id', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.sha256', 'd.status as file_status',
'd.malware_scan_status', 'd.malware_failure_reason', 'd.malware_scanned_at']
: ['a.id', 'a.kind', 'a.caption', 'a.source_reference', 'a.source_date', 'd.media_type', 'd.size_bytes'];
$attachments = DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')
->where('a.zone_id', $id)->when(! $management, fn ($query) => $query->where('d.status', 'active'))
->when(! $management, fn ($query) => $query->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256'))
->whereNull('d.deleted_at')
->when(! $management, fn ($query) => $query->where('a.publicly_selected', true)->where('a.review_status', 'reviewed')
->where('a.rights_status', 'confirmed')->where('a.personal_data_status', 'none'))
->orderBy('a.created_at')->get($attachmentColumns);
$attachments->each(function ($attachment) use ($id, $management): void {
$attachment->download_url = $management
? url('/management/investment/zones/'.$id.'/attachments/'.$attachment->id)
: url('/zonas/'.$id.'/anexos/'.$attachment->id);
});
$props = ['record' => $management ? $zone : $zone->only($publicFields), 'source' => $source, 'operator' => $operator, 'management' => $management,
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence'),
'related' => $related->unique('id')->values(),
'relations' => $management ? DB::table('investment_zone_relations')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
'geometries' => $management ? DB::table('investment_zone_geometries')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
@@ -43,6 +73,9 @@ class InvestmentZoneController extends Controller
'legalSources' => $management ? DB::table('investment_legal_sources')->orderByDesc('created_at')->limit(100)->get() : [],
'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() : [],
'locations' => $locations,
'territorialSources' => app(InvestmentTerritorialTraceability::class)->sources('investment_zones', $id),
'attachments' => $attachments,
'revisions' => $management ? DB::table('investment_zone_revisions')->where('zone_id', $id)->orderByDesc('version_no')->limit(20)->get(['version_no', 'action', 'sha256', 'created_at']) : []];
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zone', $props);
@@ -50,31 +83,135 @@ class InvestmentZoneController extends Controller
public function index(Request $request, InvestmentZones $zones): Response|JsonResponse
{
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'],
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'physical_category' => ['nullable', 'in:economic_zone,industrial_park,agro_industrial_park,industrial_logistics_park,industrial_free_zone,integrated_tourism_area,other,unknown'],
'legal_regime' => ['nullable', 'in:zee,zfi,general,pending,not_applicable'], 'development_status' => ['nullable', 'in:announced,planned,in_development,partially_operational,operational,suspended,unknown'],
'availability_status' => ['nullable', 'in:confirmed,unavailable,reported_unverified,not_informed'], 'activity' => ['nullable', 'string', 'max:120'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
$management = $request->is('management/*', 'api/v2/investment/admin/*');
$query = $management ? InvestmentZone::query() : $zones->visible();
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.');
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$query->whereIn('primary_territory_id', app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
}
$rows = $query->when($filters['category'] ?? null, fn ($q, $v) => $q->where('category', $v))
->when($filters['q'] ?? null, fn ($q, $v) => $q->where(fn ($q) => $q->where('name', 'ilike', '%'.$v.'%')->orWhere('code', 'ilike', '%'.$v.'%')))
->orderBy('name')->orderBy('id')->paginate(12, $management ? ['*'] : ['id', 'code', 'name', 'name_en', 'category', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'])->withQueryString();
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path];
$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 = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString();
$rows->getCollection()->transform(function (InvestmentZone $zone) use ($management) {
$territoryPath = app(InvestmentGeography::class)->path($zone->primary_territory_id, $management);
$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('territory_path', $territoryPath);
$zone->setAttribute('locations', DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
->where('zl.zone_id', $zone->id)->whereNull('g.deleted_at')
->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']));
return $zone;
});
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path,
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence')];
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
}
public function export(Request $request, InvestmentZones $zones): StreamedResponse
{
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'physical_category' => ['nullable', 'in:economic_zone,industrial_park,agro_industrial_park,industrial_logistics_park,industrial_free_zone,integrated_tourism_area,other,unknown'],
'legal_regime' => ['nullable', 'in:zee,zfi,general,pending,not_applicable'], 'development_status' => ['nullable', 'in:announced,planned,in_development,partially_operational,operational,suspended,unknown'],
'availability_status' => ['nullable', 'in:confirmed,unavailable,reported_unverified,not_informed'], 'activity' => ['nullable', 'string', 'max:120'], 'q' => ['nullable', 'string', 'max:120'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
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.');
$query = $zones->search($filters)->orderBy('name')->orderBy('id');
return response()->streamDownload(function () use ($query): void {
$geography = app(InvestmentGeography::class);
$stream = fopen('php://output', 'wb');
if ($stream === false) {
throw new \RuntimeException('CSV output stream unavailable.');
}
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, ['Código', 'Nome', 'Categoria física', 'Regime', 'Desenvolvimento', 'Disponibilidade', 'Província', 'Distrito', 'Área declarada', 'Unidade', 'Fontes'], ';');
$query->chunk(200, function ($zones) use ($stream, $geography): void {
foreach ($zones as $zone) {
$territoryPath = $geography->path($zone->primary_territory_id);
$province = collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province;
$district = collect($territoryPath)->firstWhere('location_type', 'district')->name ?? $zone->district;
$sources = collect($zone->source_evidence ?? [])->map(fn ($source) => ($source['title'] ?? '').' — '.($source['url'] ?? '').' — '.($source['source_date'] ?? 'data não informada'))->implode(' | ');
$values = [$zone->code, $zone->name, $zone->physical_category, $zone->legal_regime, $zone->development_status,
$zone->availability_status, $province, $district, $zone->area_value, $zone->area_unit, $sources];
$values = array_map(fn ($value) => is_string($value) && preg_match('/^[=+@\-\t\r]/u', $value) ? "'".$value : $value, $values);
fputcsv($stream, $values, ';');
}
});
fclose($stream);
}, 'zonas-e-parques.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
public function save(Request $request, InvestmentZones $zones, ?string $id = null): JsonResponse
{
if ($request->has('aliases_text')) {
$request->merge(['aliases' => array_values(array_unique(array_filter(preg_split('/[\r\n,;]+/u', (string) $request->input('aliases_text')) ?: [], fn ($value) => trim($value) !== '')))]);
}
if ($request->filled('historical_name')) {
$request->merge(['historical_territory' => [
'name' => $request->input('historical_name'), 'district' => $request->input('historical_district'),
'province' => $request->input('historical_province'), 'source_reference' => $request->input('historical_source_reference'),
]]);
}
if ($request->filled('activity_name')) {
$request->merge(['activities' => [['name' => $request->input('activity_name'), 'status' => $request->input('activity_status', 'potential')]]]);
}
$data = $request->validate(['version_no' => [$id ? 'required' : 'nullable', 'integer', 'min:1'],
'code' => ['required', 'string', 'max:80', Rule::unique('investment_zones')->ignore($id)],
'category' => ['required', 'in:zee,zfi,industrial_park,pending'], 'name' => ['required', 'string', 'max:255'],
'name_en' => ['nullable', 'string', 'max:255'], 'description' => ['nullable', 'string', 'max:15000'],
'description_en' => ['nullable', 'string', 'max:15000'], 'province' => ['nullable', 'string', 'max:100'], 'district' => ['nullable', 'string', 'max:100'],
'operator_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
'legal_source_id' => ['nullable', 'uuid', 'exists:investment_legal_sources,id']]);
'legal_source_id' => ['nullable', 'uuid', 'exists:investment_legal_sources,id'],
'physical_category' => ['nullable', 'in:economic_zone,industrial_park,agro_industrial_park,industrial_logistics_park,industrial_free_zone,integrated_tourism_area,other,unknown'],
'legal_regime' => ['nullable', 'in:zee,zfi,general,pending,not_applicable'],
'operational_status' => ['nullable', 'in:operational,implementation,planned,suspended,unknown'],
'development_status' => ['nullable', 'in:announced,planned,in_development,partially_operational,operational,suspended,unknown'],
'availability_status' => ['nullable', 'in:confirmed,unavailable,reported_unverified,not_informed'],
'area_components' => ['sometimes', 'array', 'max:30'], 'area_components.*' => ['array:type,value,unit,source_reference,source_date,status'],
'area_components.*.type' => ['required', 'in:total,legal,developed,pilot,available'], 'area_components.*.value' => ['nullable', 'numeric', 'min:0'],
'area_components.*.unit' => ['required', 'in:ha,km2,m2'], 'area_components.*.source_reference' => ['required', 'string', 'min:5', 'max:2000'],
'area_components.*.source_date' => ['nullable', 'date_format:Y-m-d'], 'area_components.*.status' => ['required', 'in:reported,confirmed,disputed'],
'source_evidence' => ['sometimes', 'array', 'max:30'], 'source_evidence.*' => ['array:title,url,source_type,supports,source_date'],
'source_evidence.*.title' => ['required', 'string', 'max:255'], 'source_evidence.*.url' => ['required', 'url:https', 'max:2000'],
'source_evidence.*.source_type' => ['required', 'in:government,institutional,promoter,other'], 'source_evidence.*.supports' => ['required', 'string', 'max:500'],
'source_evidence.*.source_date' => ['nullable', 'date_format:Y-m-d'],
'area_value' => ['nullable', 'numeric', 'min:0'], 'area_unit' => ['nullable', 'string', 'max:24'],
'aliases' => ['sometimes', 'array', 'max:20'], 'aliases.*' => ['string', 'max:120'],
'activities' => ['sometimes', 'array', 'max:50'], 'activities.*' => ['array:name,status,source_reference'],
'activities.*.name' => ['required', 'string', 'max:300'], 'activities.*.status' => ['required', 'in:proposed,authorized,conditional,excluded,potential'],
'activities.*.source_reference' => ['nullable', 'string', 'max:2000'],
'resources' => ['sometimes', 'array', 'max:50'], 'resources.*' => ['array:name,status,source_reference'],
'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'],
'sources_consulted_at' => ['nullable', 'date_format:Y-m-d'], 'parent_zone_id' => ['nullable', 'uuid', 'exists:investment_zones,id'],
'historical_territory' => ['nullable', 'array:name,district,province,source_reference'],
'historical_territory.name' => ['required_with:historical_territory', 'string', 'max:255'],
'historical_territory.district' => ['nullable', 'string', 'max:120'], 'historical_territory.province' => ['nullable', 'string', 'max:120'],
'historical_territory.source_reference' => ['nullable', 'string', 'max:2000'],
'locations' => ['sometimes', 'array', 'max:20'], 'locations.*.geo_location_id' => ['required', 'uuid', 'exists:geo_locations,id'],
'locations.*.scope_type' => ['required', 'in:legal_scope,administrative,site,influence'],
'locations.*.source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'locations.*.legal_source_id' => ['nullable', 'uuid', 'exists:investment_legal_sources,id']]);
foreach (['development_status', 'availability_status', 'area_components', 'source_evidence'] as $column) {
if (! Schema::hasColumn('investment_zones', $column)) {
unset($data[$column]);
}
}
foreach ($data['activities'] ?? [] as $index => $activity) {
if (! in_array($activity['status'], ['potential', 'proposed'], true) && trim((string) ($activity['source_reference'] ?? '')) === '') {
throw ValidationException::withMessages([
'activities.'.$index.'.source_reference' => 'Indique a fonte da actividade documentada antes de a classificar como autorizada, condicionada ou excluída.',
]);
}
}
if (! $id && $request->has('province_id')) {
$geo = $request->validate(['province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
@@ -90,9 +227,6 @@ class InvestmentZoneController extends Controller
public function transition(Request $request, InvestmentZones $zones, string $id, string $action): JsonResponse
{
if ($action === 'publish') {
InvestmentZoneAccess::requireRole($request->user(), 'publishers');
}
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
return response()->json($action === 'publish' ? $zones->publish($id, $data['version_no'], $request->user()->id)
@@ -105,4 +239,12 @@ class InvestmentZoneController extends Controller
return response()->json(DB::table('investment_zone_revisions')->where('zone_id', $id)->orderByDesc('version_no')->paginate(20, ['id', 'version_no', 'actor_id', 'action', 'sha256', 'created_at']));
}
public function validateLocation(Request $request, InvestmentZones $zones, string $id): JsonResponse
{
InvestmentZoneAccess::requireRole($request->user(), 'territory_reviewers');
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
return response()->json($zones->validateLocation($id, $data['version_no'], $request->user()->id));
}
}
@@ -9,6 +9,7 @@ use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -98,9 +99,15 @@ class InvestmentZoneGeometryController extends Controller
public function map(Request $request, InvestmentZones $zones): JsonResponse
{
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'bbox' => ['nullable', 'array', 'size:4'], 'bbox.*' => ['required', 'numeric']]);
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'bbox' => ['nullable', 'array', 'size:4'], 'bbox.*' => ['required', 'numeric'],
'category' => ['nullable', 'in:zee,zfi,industrial_park'], 'physical_category' => ['nullable', 'string', 'max:40'], 'legal_regime' => ['nullable', 'string', 'max:30'],
'development_status' => ['nullable', 'string', 'max:32'], 'availability_status' => ['nullable', 'string', 'max:32'], 'activity' => ['nullable', 'string', 'max:120'], 'q' => ['nullable', 'string', 'max:120'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
abort_if((! empty($data['development_status']) || ! empty($data['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.');
$eligibleZones = $zones->search($data)->select('investment_zones.id');
$query = DB::table('investment_zone_geometries as l')->join('geo_geometries as g', 'g.id', '=', 'l.geometry_id')
->whereIn('l.zone_id', $zones->visible()->select('investment_zones.id'))->where('l.publication_authorized', true)->where('l.validation_status', 'validated')
->whereIn('l.zone_id', $eligibleZones)->where('l.publication_authorized', true)->where('l.validation_status', 'validated')
->whereNull('g.deleted_at')->where('g.data_classification', 'public')->when($data['zone_id'] ?? null, fn ($q, $v) => $q->where('l.zone_id', $v))
->where(fn ($q) => $q->whereNull('l.legal_source_id')->orWhereExists(fn ($s) => $s->selectRaw('1')->from('investment_legal_sources as ls')
->whereColumn('ls.id', 'l.legal_source_id')->where('ls.validation_status', 'validated')->whereDate('ls.valid_from', '<=', today())
@@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers;
use App\Services\Ai\EvidenceRepository;
use App\Services\Ai\InvestorGuidance;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class InvestorGuidanceController extends Controller
{
public function contexts(Request $request, VirtualDesk $desk): JsonResponse
{
$actor = $request->user();
$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))
->orderByDesc('updated_at')->get(['id', 'title']);
return response()->json(['cases' => $cases]);
}
public function show(Request $request, string $id, InvestorGuidance $guidance): JsonResponse
{
return response()->json($guidance->view($request->user(), $id));
}
public function assumptions(Request $request, string $id, InvestorGuidance $guidance): JsonResponse|RedirectResponse
{
$guidance->assumptions($request->user(), $id, $request->all());
return $this->completed($request, 'Pressupostos corrigidos; os dados dos módulos de origem foram preservados.');
}
public function feedback(Request $request, string $id, InvestorGuidance $guidance): JsonResponse|RedirectResponse
{
$guidance->feedback($request->user(), $id, $request->all());
return $this->completed($request, 'Revisão registada. Assumir uma tarefa continua a ser uma acção separada.');
}
public function task(Request $request, string $id, InvestorGuidance $guidance): JsonResponse|RedirectResponse
{
$task = $guidance->acceptTask($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['id' => $task->id], 201) : back()->with('success', 'Tarefa assumida no CRM interno. Sincronização externa pendente de finalidade e autorização.');
}
public function updateTask(Request $request, string $id, string $task, InvestorGuidance $guidance): JsonResponse|RedirectResponse
{
$guidance->updateTask($request->user(), $id, $task, $request->all());
return $this->completed($request, 'Resultado da tarefa registado no mesmo histórico do dossier.');
}
public function search(Request $request, string $id, VirtualDesk $desk, EvidenceRepository $evidence): JsonResponse
{
$desk->case($request->user(), $id);
$data = $request->validate(['query' => 'required|string|min:3|max:300']);
$enabled = config('investmoz_ai.enabled') && Schema::hasTable('ai_controls') && DB::table('ai_controls')->where('capability', 'search')->where('suspended', false)->exists();
$items = $enabled ? $evidence->search($data['query'], 'pt', ['public_only' => true]) : [];
return response()->json(['mode' => 'lexical_evidence', 'model' => null, 'status' => ! $enabled ? 'unavailable' : ($items ? 'evidence_found' : 'no_evidence'),
'consulted' => $items, 'limitations' => ['Apenas excertos das fontes públicas autorizadas indexadas; não é uma consulta exaustiva nem validação jurídica.']]);
}
private function completed(Request $request, string $message): JsonResponse|RedirectResponse
{
return $request->expectsJson() ? response()->json(['message' => $message]) : back()->with('success', $message);
}
}
@@ -0,0 +1,402 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Requests\StoreLandAssistanceCaseRequest;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\LandAssistanceCase;
use App\Services\InterestSubmission;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class LandAssistanceController extends Controller
{
private const DISCLAIMER = 'Este documento apoia a preparação e o acompanhamento. Não constitui requerimento oficialmente recebido, título de DUAT, confirmação de disponibilidade da terra ou decisão da autoridade competente.';
public function guide(): Response
{
return Inertia::render('land-assistance/guide', ['disclaimer' => self::DISCLAIMER]);
}
public function blank(): Response
{
return Inertia::render('land-assistance/blank', ['disclaimer' => self::DISCLAIMER]);
}
public function index(Request $request): Response
{
$cases = LandAssistanceCase::where('user_id', $request->user()->id)
->latest('updated_at')->paginate(20)->through(fn (LandAssistanceCase $case): array => [
'id' => $case->id,
'reference' => $case->reference,
'status' => $case->status,
'version' => $case->version,
'updated_at' => $case->updated_at,
]);
return Inertia::render('land-assistance/workspace', ['cases' => $cases]);
}
public function create(Request $request): Response
{
return Inertia::render('land-assistance/form', [
'case' => null,
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1',
]);
}
public function edit(Request $request, string $id): Response
{
$case = $this->owned($request, $id);
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', [
'case' => $case->only(['id', 'reference', 'version', 'status', 'payload']),
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1',
]);
}
public function store(StoreLandAssistanceCaseRequest $request): RedirectResponse|JsonResponse
{
$payload = $request->payload();
$payload['full_name'] = $payload['full_name'] ?? $request->user()->name;
$payload['email'] = $payload['email'] ?? $request->user()->email;
$case = DB::transaction(function () use ($request, $payload): LandAssistanceCase {
$case = LandAssistanceCase::create([
'user_id' => $request->user()->id,
'reference' => 'TERRA-'.now()->format('Y').'-'.Str::upper(Str::random(8)),
'status' => 'draft',
'version' => 1,
'payload' => $payload,
'crm_submission_key' => (string) Str::uuid(),
]);
$this->revision($case);
$this->event($case, $request, 'draft_created');
return $case;
});
return $request->expectsJson()
? response()->json(['id' => $case->id, 'reference' => $case->reference, 'version' => $case->version], 201)
: redirect()->route('land-assistance.show', $case->id);
}
public function show(Request $request, string $id): Response|JsonResponse
{
$case = $this->owned($request, $id);
$data = [
'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')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')
->get(['link.id', 'link.category', 'document.file_name', 'document.status']),
'events' => DB::table('land_assistance_events')->where('case_id', $id)->orderBy('created_at')
->get(['action', 'version', 'metadata', 'created_at']),
'supportTicket' => $case->interest_request_id
? InterestRequest::query()->whereKey($case->interest_request_id)->first(['reference', 'status', 'created_at'])
: null,
'disclaimer' => self::DISCLAIMER,
'management' => false,
];
return $request->expectsJson() ? response()->json($data) : Inertia::render('land-assistance/case', $data);
}
public function save(StoreLandAssistanceCaseRequest $request, string $id): RedirectResponse|JsonResponse
{
$data = $request->validated();
$payload = $request->payload();
$case = DB::transaction(function () use ($request, $id, $data, $payload): LandAssistanceCase {
$case = $this->owned($request, $id, true);
abort_unless(in_array($case->status, ['draft', 'waiting_applicant'], true), 409, 'Este pedido está bloqueado para edição pelo requerente.');
$this->checkVersion($case, (int) $data['version']);
$payload['full_name'] = $payload['full_name'] ?? $case->payload['full_name'] ?? $request->user()->name;
$payload['email'] = $payload['email'] ?? $case->payload['email'] ?? $request->user()->email;
$case->forceFill(['payload' => $payload, 'version' => $case->version + 1])->save();
$this->revision($case);
$this->event($case, $request, 'draft_updated');
return $case;
});
return $request->expectsJson()
? response()->json(['id' => $case->id, 'reference' => $case->reference, 'version' => $case->version])
: redirect()->route('land-assistance.show', $case->id)->with('status', 'Rascunho guardado.');
}
public function requestSupport(StoreLandAssistanceCaseRequest $request, string $id, InterestSubmission $submission): RedirectResponse|JsonResponse
{
$data = $request->validated();
$submittedPayload = $request->payload();
$case = DB::transaction(function () use ($request, $id, $data, $submission, $submittedPayload): LandAssistanceCase {
$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.');
$this->checkVersion($case, (int) $data['version']);
$payload = [...$case->payload, ...$submittedPayload];
$payload['full_name'] = $payload['full_name'] ?? $request->user()->name;
if (! array_key_exists('email', $payload)) {
$payload['email'] = $request->user()->email;
}
$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.');
$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([
'kind' => 'support', 'fullName' => $payload['full_name'], 'email' => $payload['email'],
'phone' => $payload['phone'] ?? null, 'country' => $payload['country'] ?? 'Não indicado',
'sectorInterest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacyConsent' => true, 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
], $case->crm_submission_key, fn () => InterestRequest::create([
'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $payload['full_name'],
'email' => $payload['email'], 'phone' => $payload['phone'] ?? null,
'country' => $payload['country'] ?? 'Não indicado', 'investor_type' => 'individual',
'sector_interest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/terra-duat',
'metadata' => ['kind' => 'support', 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference],
]));
$case->forceFill([
'payload' => $payload,
'status' => 'support_requested',
'support_requested_at' => now(),
'version' => $case->version + 1,
'interest_request_id' => $interest->id,
])->save();
$this->revision($case);
$this->event($case, $request, 'support_requested');
return $case;
});
return $request->expectsJson()
? response()->json(['id' => $case->id, 'reference' => $case->reference, 'status' => $case->status, 'version' => $case->version], 202)
: redirect()->route('land-assistance.show', $case->id)->with('status', 'Pedido de apoio registado no InvestMoz. Isto não é submissão oficial de DUAT.');
}
public function reportUpdate(Request $request, string $id): RedirectResponse|JsonResponse
{
$data = $request->validate([
'version' => ['required', 'integer', 'min:1'],
'reported_status' => ['required', 'string', 'max:1000'],
'official_reference' => ['nullable', 'string', 'max:160'],
'receiving_entity' => ['nullable', 'string', 'max:200'],
'reported_at' => ['nullable', 'date_format:Y-m-d'],
]);
$case = DB::transaction(function () use ($request, $id, $data): LandAssistanceCase {
$case = $this->owned($request, $id, true);
abort_unless(in_array($case->status, ['support_requested', 'internal_review', 'waiting_applicant', 'referral_prepared'], true), 409);
$this->checkVersion($case, (int) $data['version']);
$payload = $case->payload;
$updates = $payload['reported_updates'] ?? [];
$updates[] = ['reported_status' => $data['reported_status'], 'official_reference' => $data['official_reference'] ?? null,
'receiving_entity' => $data['receiving_entity'] ?? null, 'reported_at' => $data['reported_at'] ?? null, 'recorded_at' => now()->toIso8601String()];
$payload['reported_updates'] = array_slice($updates, -20);
$case->forceFill(['payload' => $payload, 'version' => $case->version + 1])->save();
$this->revision($case);
$this->event($case, $request, 'applicant_update_recorded');
return $case;
});
return $request->expectsJson()
? response()->json(['version' => $case->version, 'reported_by_applicant' => true])
: redirect()->route('land-assistance.show', $case->id)->with('status', 'Actualização registada como informação comunicada por si.');
}
public function attach(Request $request, string $id): RedirectResponse|JsonResponse
{
$data = $request->validate([
'version' => ['required', 'integer', 'min:1'],
'category' => ['required', Rule::in(['sketch', 'prior_right', 'exploration_plan', 'official_receipt', 'consultation_minutes', 'photo', 'other'])],
'file' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png', 'max:10240'],
]);
$case = $this->owned($request, $id, true);
$this->checkVersion($case, (int) $data['version']);
abort_unless(! in_array($case->status, ['closed'], true), 409);
abort_if(DB::table('land_assistance_documents')->where('case_id', $id)->count() >= 20, 422, 'Máximo de vinte documentos por pedido.');
$file = $request->file('file');
$documentId = (string) Str::uuid();
$key = 'land-assistance/'.$id.'/'.$documentId;
$stored = $file->storeAs('land-assistance/'.$id, $documentId, 'local');
if (! is_string($stored) || $stored === '') {
throw ValidationException::withMessages(['file' => 'Não foi possível guardar o ficheiro em armazenamento privado.']);
}
try {
DB::transaction(function () use ($request, $case, $data, $file, $documentId, $stored): void {
$locked = $this->owned($request, $case->id, true);
$this->checkVersion($locked, (int) $data['version']);
DB::table('documents')->insert([
'id' => $documentId,
'source_system' => 'land-assistance',
'data_classification' => 'restricted',
'file_name' => basename($file->getClientOriginalName()),
'media_type' => (string) $file->getMimeType(),
'storage_key' => $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.
'status' => 'quarantined',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('land_assistance_documents')->insert([
'id' => (string) Str::uuid(), 'case_id' => $locked->id, 'document_id' => $documentId,
'category' => $data['category'], 'created_at' => now(),
]);
$locked->forceFill(['version' => $locked->version + 1])->save();
$this->revision($locked);
$this->event($locked, $request, 'attachment_added', ['document_id' => $documentId, 'category' => $data['category']]);
});
} catch (\Throwable $exception) {
Storage::disk('local')->delete($stored);
throw $exception;
}
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
return $request->expectsJson()
? response()->json(['uploaded' => true], 201)
: back()->with('status', 'Documento privado anexado; a revisão ainda está pendente.');
}
public function download(Request $request, string $id, string $attachment): BinaryFileResponse
{
$this->owned($request, $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('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']);
abort_if($document === null, 404);
$root = realpath(Storage::disk('local')->path(''));
$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)
&& 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']);
}
public function print(Request $request, string $id): Response
{
$case = $this->owned($request, $id);
return Inertia::render('land-assistance/print', [
'case' => $case->only(['reference', 'version', 'payload', 'updated_at']),
'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1',
]);
}
public function manage(Request $request): Response
{
$cases = LandAssistanceCase::query()->latest('updated_at')->paginate(30)->through(fn (LandAssistanceCase $case): array => [
'id' => $case->id, 'reference' => $case->reference, 'status' => $case->status,
'version' => $case->version, 'updated_at' => $case->updated_at,
'applicant' => $case->payload['full_name'] ?? null,
]);
return Inertia::render('land-assistance/management', ['cases' => $cases]);
}
public function manageShow(Request $request, string $id): Response
{
$case = LandAssistanceCase::findOrFail($id);
$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', [
'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')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')->get(['link.id', 'link.category', 'document.file_name', 'document.status']),
'events' => $events,
'supportTicket' => $case->interest_request_id
? InterestRequest::query()->whereKey($case->interest_request_id)->first(['reference', 'status', 'created_at'])
: null,
'disclaimer' => self::DISCLAIMER,
'management' => true,
]);
}
public function changeStatus(Request $request, string $id): RedirectResponse|JsonResponse
{
$data = $request->validate([
'version' => ['required', 'integer', 'min:1'],
'status' => ['required', Rule::in(['internal_review', 'waiting_applicant', 'referral_prepared', 'closed'])],
'evidence_reference' => ['nullable', 'string', 'max:300'],
]);
$case = DB::transaction(function () use ($request, $id, $data): LandAssistanceCase {
$case = LandAssistanceCase::whereKey($id)->lockForUpdate()->firstOrFail();
$this->checkVersion($case, (int) $data['version']);
$allowed = [
'support_requested' => ['internal_review', 'waiting_applicant', 'referral_prepared', 'closed'],
'internal_review' => ['waiting_applicant', 'referral_prepared', 'closed'],
'waiting_applicant' => ['internal_review', 'referral_prepared', 'closed'],
'referral_prepared' => ['internal_review', 'waiting_applicant', 'closed'],
];
abort_unless(in_array($data['status'], $allowed[$case->status] ?? [], true), 409, 'Transição de estado não permitida.');
if ($data['status'] === 'referral_prepared' && empty($data['evidence_reference'])) {
throw ValidationException::withMessages(['evidence_reference' => 'Registe a referência interna do material preparado para encaminhamento.']);
}
$previousStatus = $case->status;
$case->forceFill(['status' => $data['status'], 'version' => $case->version + 1])->save();
$this->revision($case);
$this->event($case, $request, 'status_changed', [
'from' => $previousStatus, 'to' => $data['status'],
'evidence_reference' => $data['evidence_reference'] ?? null,
'external_submission_confirmed' => false,
]);
return $case;
});
return $request->expectsJson()
? response()->json(['status' => $case->status, 'version' => $case->version])
: redirect()->route('land-assistance.manage.show', $case->id)->with('status', 'Estado interno actualizado. Nenhuma recepção pública foi presumida.');
}
private function owned(Request $request, string $id, bool $lock = false): LandAssistanceCase
{
$query = LandAssistanceCase::whereKey($id)->where('user_id', $request->user()->id);
return ($lock ? $query->lockForUpdate() : $query)->firstOrFail();
}
private function checkVersion(LandAssistanceCase $case, int $expected): void
{
abort_unless($case->version === $expected, 412, 'Este rascunho foi alterado. Recarregue antes de continuar.');
}
/** @param array<string,mixed> $metadata */
private function event(LandAssistanceCase $case, Request $request, string $action, array $metadata = []): void
{
DB::table('land_assistance_events')->insert([
'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(),
]);
}
private function revision(LandAssistanceCase $case): void
{
DB::table('land_assistance_revisions')->insert([
'case_id' => $case->id, 'version' => $case->version,
'snapshot' => Crypt::encryptString(json_encode(['status' => $case->status, 'payload' => $case->payload], JSON_THROW_ON_ERROR)),
'created_at' => now(),
]);
}
}
@@ -0,0 +1,95 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Opportunities\Enums\OpportunityStatus;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\InvestmentGeography;
use App\Services\OpportunityManagement;
use App\Services\OpportunityManagementInstallation;
use App\Services\OpportunityResources;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class OpportunityManagementController extends Controller
{
public function installation(Request $request, OpportunityManagementInstallation $service): JsonResponse|Response
{
return $request->expectsJson() ? response()->json($service->preview()) : Inertia::render('management/opportunity-install', $service->preview());
}
public function applyInstallation(Request $request, OpportunityManagementInstallation $service): RedirectResponse
{
$data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'required|accepted']);
$service->apply($request->user(), $data['hash']);
return back()->with('success', 'Gestão instalada; nenhuma oportunidade foi submetida ou publicada.');
}
public function index(Request $request, OpportunityManagement $service): Response
{
if (! $service->installed()) {
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']);
$query = Opportunity::query();
if ($filters['deleted'] ?? false) {
$query->onlyTrashed();
}
if ($filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%'));
}
if ($filters['status'] ?? null) {
$query->where('status', $filters['status']);
}
if ($filters['category'] ?? null) {
$query->where('opportunity_category', $filters['category']);
}
if ($filters['sector_id'] ?? null) {
$query->where('sector_id', $filters['sector_id']);
}
if ($filters['geography_scope'] ?? null) {
$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'])]);
}
public function edit(Request $request, OpportunityManagement $service, ?int $id = null): Response
{
if (! $service->installed()) {
return app(PortalManagementController::class)->edit('opportunities', $id);
}
$record = $id ? Opportunity::withTrashed()->findOrFail($id) : null;
$values = $record ? ($record->management_draft ? json_decode($record->management_draft, true) : $record->only(OpportunityManagement::FIELDS)) : [];
$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', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), '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,
'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']) : []]);
}
public function save(Request $request, OpportunityManagement $service, ?int $id = null): JsonResponse
{
$record = $service->save($request->user(), $request->all(), $id);
if (! $id) {
$request->session()->flash('success', 'Rascunho guardado no servidor. Pode continuar o preenchimento; não foi submetido.');
}
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 lifecycle(Request $request, int $id, OpportunityManagement $service): JsonResponse
{
abort_unless($service->installed(), 503);
$record = $service->lifecycle($request->user(), $id, $request->all());
return response()->json(['id' => $record->id, 'message' => $request->input('action') === 'restore' ? 'Restaurado como rascunho; nova revisão necessária antes de publicar.' : 'Exclusão lógica/arquivo registado; histórico e relações preservados.']);
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\OpportunityOriginReview;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class OpportunityOriginReviewController extends Controller
{
public function index(OpportunityOriginReview $review): Response
{
return Inertia::render('management/opportunity-origin', ['records' => Opportunity::whereIn('reference', ['INV-MZ-AGR-001', 'INV-MZ-ENE-002', 'INV-MZ-TUR-003', 'INV-MZ-INF-004', 'INV-MZ-BLUE-005', 'INV-MZ-FIN-006'])->orderBy('id')->pluck('id')->map(fn ($id) => $review->state($id))->all(), 'ready' => $review->ready()]);
}
public function preview(Request $request, OpportunityOriginReview $review): JsonResponse
{
$data = $request->validate(['id' => ['required', 'integer', 'exists:opportunities,id'], 'classification' => ['required', 'in:real,example,undetermined'], 'reason' => ['required', 'string', 'max:2000']]);
return response()->json($review->preview($data['id'], $data['classification'], $data['reason']));
}
public function apply(Request $request, OpportunityOriginReview $review): JsonResponse
{
$data = $request->validate(['id' => ['required', 'integer', 'exists:opportunities,id'], 'classification' => ['required', 'in:real,example,undetermined'], 'reason' => ['required', 'string', 'max:2000'], 'snapshot_hash' => ['required', 'string', 'size:64'], 'confirm' => ['required', 'accepted']]);
return response()->json($review->apply($data['id'], $data['classification'], $data['reason'], $data['snapshot_hash'], $request->user()->id));
}
}
@@ -0,0 +1,211 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\InvestmentGeography;
use App\Services\OpportunityImageProcessor;
use App\Services\OpportunityManagement;
use App\Services\OpportunityResourceInstallation;
use App\Services\OpportunityResources;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\HeaderUtils;
class OpportunityResourceController extends Controller
{
public function installation(Request $request, OpportunityResourceInstallation $service): JsonResponse|Response
{
$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);
}
public function applyInstallation(Request $request, OpportunityResourceInstallation $service): RedirectResponse
{
$data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'required|accepted']);
$service->apply($request->user(), $data['hash']);
return back()->with('success', 'Recursos instalados; nenhum ficheiro publicado ou oportunidade submetida.');
}
public function index(int $id, OpportunityResources $service): Response
{
$opportunity = Opportunity::withTrashed()->findOrFail($id);
abort_unless($service->installed(), 503, 'Recursos ainda não instalados; consulte o plano autenticado.');
$resources = [];
Inertia::share('imageProcessingAvailable', app(OpportunityImageProcessor::class)->available());
foreach (OpportunityResources::KINDS as $kind) {
$resources[$kind] = $service->listing($id, $kind);
}
foreach ($resources['locations'] as $location) {
$p = $location->payload;
$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('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)]);
}
public function save(Request $request, int $id, string $kind, OpportunityResources $service, ?string $resourceId = null): JsonResponse
{
$input = $request->all();
if (is_string($input['payload'] ?? null)) {
$input['payload'] = json_decode($input['payload'], true);
}
$record = $service->save($request->user(), $id, $kind, $input, $request->file('file'), $resourceId);
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): JsonResponse
{
$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.']);
}
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
{
$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.');
$bytes = Crypt::decryptString(Storage::disk('local')->get($doc->storage_key));
abort_unless(hash_equals(trim($doc->sha256), hash('sha256', $bytes)), 409, 'Integridade divergente.');
return response($bytes)->header('Content-Type', 'image/webp')->header('X-Content-Type-Options', 'nosniff')->header('Cache-Control', 'private,no-store');
}
public function download(int $id, string $kind, string $resourceId, OpportunityResources $service): \Illuminate\Http\Response
{
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
$opportunity = Opportunity::findOrFail($id);
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.*']);
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.');
$disk = Storage::disk('local');
$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');
}
/** @param array<string,list<\stdClass>> $resources
* @return list<string>
*/
private function assessment(array $resources): array
{
$issues = [];
$locations = array_values(array_filter($resources['locations'], fn ($r) => ! $r->deleted_at));
if (count($locations) < 1) {
$issues[] = 'Localização operacional ainda não preparada; ligações históricas não são convertidas automaticamente.';
}
if (count(array_filter($locations, fn ($r) => $r->payload['is_primary'] ?? false)) !== 1) {
$issues[] = 'Escolha exatamente uma localização principal.';
}
$allocated = array_filter($locations, fn ($r) => isset($r->payload['allocation_percentage']));
if ($allocated && (count($allocated) !== count($locations) || abs(array_sum(array_map(fn ($r) => (float) $r->payload['allocation_percentage'], $allocated)) - 100) > 0.01)) {
$issues[] = 'A distribuição deve abranger todas as localizações e somar 100% (tolerância 0,01).';
}
$provinces = [];
$districts = [];
foreach ($locations as $location) {
$p = $location->payload;
if (empty($p['province_id']) || empty($p['district_id']) || empty($p['role'])) {
$issues[] = 'Uma localização tem província, distrito ou papel pendente.';
}
if (! empty($p['district_id'])) {
$districts[$p['district_id']] = true;
}
if (! empty($p['province_id'])) {
$provinces[$p['province_id']] = true;
}
if (($p['role'] ?? null) === 'other' && empty($p['role_description'])) {
$issues[] = 'Papel outro exige descrição.';
}
if (empty($p['source_reference'])) {
$issues[] = 'Localização com rastreabilidade por recuperar; aceitação oficial anterior preservada.';
}
if (! empty($p['geometry'])) {
$issues[] = 'Compatibilidade espacial depende de limite oficial correspondente; geometria não confirma disponibilidade.';
}
if (isset($p['area_value']) !== isset($p['area_unit'])) {
$issues[] = 'Área exige valor e unidade juntos.';
}
}
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.';
}
if ($locations) {
$issues[] = 'Modo preparado: '.(count($locations) > 1 ? 'multiple' : 'single').'; âmbito derivado: '.(count($provinces) > 1 ? 'interprovincial' : (count($districts) > 1 ? 'multi_district' : 'district')).'. Sem conversão de contexto em implantação.';
}
foreach (['images', 'documents'] as $kind) {
foreach ($resources[$kind] as $r) {
if ($r->deleted_at) {
continue;
}
if ($r->file->malware_scan_status !== 'clean') {
$issues[] = 'Anexo '.$r->file->file_name.': scan '.$r->file->malware_scan_status.'; não é evidência de segurança.';
}
$required = $kind === 'images' ? ['title', 'caption', 'alt_text', 'author_source', 'rights_status'] : ['category', 'issuer', 'edition', 'classification'];
foreach ($required as $field) {
if (empty($r->payload[$field])) {
$issues[] = 'Anexo '.$r->file->file_name.': '.$field.' pendente.';
}
}
if ($kind === 'images') {
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'])) {
$issues[] = 'Imagem licenciada/autorizada exige comprovativo.';
}
}
}
}
$issues[] = 'Esta conferência não submete nem publica; workflow final, revisão humana e derivados seguros permanecem separados.';
return array_values(array_unique($issues));
}
}
@@ -0,0 +1,401 @@
<?php
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\ExistingBusiness;
use App\Models\User;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\InvestmentRelations;
use App\Services\PartnershipExchange;
use App\Services\PartnershipMatching;
use App\Services\PartnershipSources;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class PartnershipExchangeController extends Controller
{
public function source(Request $request, string $type, string $id): JsonResponse
{
if (! Schema::hasTable('partnership_origins')) {
return response()->json(['available' => false, 'items' => []]);
}
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')
->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');
}
public function index(Request $request): Response|JsonResponse
{
$filters = $request->validate(['q' => 'nullable|string|max:120', 'sector_id' => 'nullable|integer', 'partnership_type' => 'nullable|string|max:40',
'kind' => 'nullable|in:offering,seeking', 'territory_id' => 'nullable|uuid', 'origin_type' => 'nullable|string|max:40', 'origin_id' => 'nullable|string|max:100']);
$query = DB::table('portal_partnerships as p')->where('p.status', 'published');
foreach (['sector_id', 'partnership_type', 'kind'] as $field) {
if (! empty($filters[$field])) {
$query->where('p.'.$field, $filters[$field]);
}
}
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('p.title', 'ilike', $term)->orWhere('p.sector', 'ilike', $term)
->orWhereRaw("p.payload->>'summary' ILIKE ?", [$term])->orWhere(fn ($details) => $details->whereRaw("COALESCE(p.payload->>'confidentiality','public')='public'")->where(fn ($body) => $body->where('p.offer', 'ilike', $term)->orWhere('p.seeking', 'ilike', $term))));
}
if (! empty($filters['origin_type']) && ! empty($filters['origin_id'])) {
// Authenticate access to a private master before exposing a backlink query.
app(PartnershipSources::class)->resolve($filters['origin_type'], $filters['origin_id'], $request->user());
$query->whereExists(fn ($q) => $q->selectRaw('1')->from('partnership_origins')->whereColumn('partnership_id', 'p.id')->where('type', $filters['origin_type'])->where('target_id', $filters['origin_id']));
}
if (! empty($filters['territory_id'])) {
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $filters['territory_id'])->exists(), 422);
$ids = app(InvestmentGeography::class)->descendants($filters['territory_id']);
$investmentIds = app(InvestmentCatalogue::class)->query(['geo_location_id' => $filters['territory_id']])->pluck('id')->map(fn ($id) => (string) $id)->all();
$query->where(fn ($q) => $q->whereExists(fn ($places) => $places->selectRaw('1')->from('partnership_locations')->whereColumn('partnership_id', 'p.id')->whereIn('geo_location_id', $ids))
->orWhereExists(fn ($origins) => $origins->selectRaw('1')->from('partnership_origins as origin')->join('project_locations as pl', DB::raw('pl.project_id::text'), '=', 'origin.target_id')
->whereColumn('origin.partnership_id', 'p.id')->where('origin.type', 'project')->whereNull('pl.deleted_at')->where('pl.data_classification', 'public')->whereIn('pl.geo_location_id', $ids))
->orWhereExists(fn ($origins) => $origins->selectRaw('1')->from('partnership_origins')->whereColumn('partnership_id', 'p.id')->where('type', 'investment')->whereIn('target_id', $investmentIds))
->orWhereExists(fn ($members) => $members->selectRaw('1')->from('partnership_origins as origin')
->joinSub(app(InvestmentRelations::class)->memberships()->select(['cp.cluster_id', 'cp.project_id']), 'member', DB::raw('member.cluster_id::text'), '=', 'origin.target_id')
->join('project_locations as pl', 'pl.project_id', '=', 'member.project_id')->whereColumn('origin.partnership_id', 'p.id')->where('origin.type', 'cluster')
->whereNull('pl.deleted_at')->where('pl.data_classification', 'public')->whereIn('pl.geo_location_id', $ids))
->orWhereExists(fn ($zones) => $zones->selectRaw('1')->from('partnership_origins as origin')->join('investment_zone_locations as zl', DB::raw('zl.zone_id::text'), '=', 'origin.target_id')
->join('investment_zones as zone', 'zone.id', '=', 'zl.zone_id')->whereColumn('origin.partnership_id', 'p.id')->where('origin.type', 'zone')->where('zone.publication_status', 'published')
->whereNull('zone.deleted_at')->where('zl.validation_status', 'validated')->whereIn('zl.geo_location_id', $ids)));
}
$results = $query->orderByDesc('p.id')->select(['p.id', 'p.title', 'p.sector', 'p.province', 'p.kind', 'p.partnership_type', 'p.sector_id', 'p.deadline', 'p.published_at'])
->selectRaw("p.payload->>'summary' as summary")->paginate(12)->withQueryString();
if ($request->expectsJson()) {
return response()->json($results);
}
$mapPoints = [];
foreach ($results as $partnership) {
$locations = app(InvestmentRelations::class)->locations(array_values(DB::table('partnership_locations')->where('partnership_id', $partnership->id)->get()
->map(fn ($location) => ['id' => $location->geo_location_id, 'role' => $location->role, 'source_reference' => $location->source_reference])->all()));
foreach ($locations as $location) {
if ($location['location_type'] !== 'site') {
continue;
}
foreach ($location['coordinates'] as $coordinate) {
$mapPoints[] = ['geometry' => $coordinate['geometry'], 'properties' => ['id' => count($mapPoints), 'title' => $partnership->title,
'location' => $location['name'].' · '.$location['role'].' · '.$location['source_reference'], 'url' => '/parcerias/'.$partnership->id]];
}
}
foreach (app(PartnershipSources::class)->forPartnership($partnership->id) as $source) {
$context = $source['geography']['locations'] ?? [];
foreach ($source['geography']['members'] ?? [] as $member) {
$context = [...$context, ...$member['locations']];
}
foreach ($context as $location) {
foreach ($location['coordinates'] as $coordinate) {
$mapPoints[] = ['geometry' => $coordinate['geometry'], 'properties' => ['id' => count($mapPoints), 'title' => $partnership->title,
'location' => 'Contexto da origem: '.$location['name'].'; implantação da parceria não confirmada', 'url' => '/parcerias/'.$partnership->id]];
}
}
}
}
return Inertia::render('partnerships/catalogue', ['results' => $results, 'filters' => $filters, 'mapPoints' => $mapPoints, ...$this->catalogues($request)]);
}
public function dashboard(Request $request): Response
{
$actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$mine = DB::table('portal_partnerships')->where(fn ($q) => $q->where(fn ($own) => $own->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->latest()->limit(100)->get();
$interests = DB::table('partnership_interests as i')->join('portal_partnerships as p', 'p.id', '=', 'i.partnership_id')
->leftJoin('partnership_rooms as room', 'room.interest_id', '=', 'i.id')
->where(fn ($q) => $q->where(fn ($own) => $own->where('i.user_id', $actor->id)->whereNull('i.organization_id'))->orWhereIn('i.organization_id', $organizations))
->select(['i.id', 'i.partnership_id', 'i.status', 'i.decision_reason', 'p.title', 'room.id as room_id'])->orderByDesc('i.id')->limit(100)->get();
$moderation = Gate::forUser($actor)->allows('manage-portal') ? DB::table('portal_partnerships')->whereIn('status', ['submitted', 'pending'])->orderBy('updated_at')->get(['id', 'title', 'status', 'version']) : [];
return Inertia::render('partnerships/dashboard', ['mine' => $mine->map(fn ($p) => ['id' => $p->id, 'title' => $p->title, 'status' => $p->status, 'version' => $p->version]), 'interests' => $interests, 'moderation' => $moderation,
'notifications' => DB::table('partnership_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(50)->get()]);
}
public function edit(Request $request, ?int $id = null): Response
{
$record = $id ? app(PartnershipExchange::class)->find($id) : null;
abort_if($record && ! app(PartnershipExchange::class)->owns($request->user(), $record), 403);
$origins = $record ? DB::table('partnership_origins')->where('partnership_id', $id)->get() : [];
if (! $record && $request->filled('origin_type') && $request->filled('origin_id')) {
$source = app(PartnershipSources::class)->resolve($request->string('origin_type')->toString(), $request->string('origin_id')->toString(), $request->user());
$origins = [['type' => $source['type'], 'target_id' => $source['target_id']]];
}
return Inertia::render('partnerships/editor', ['record' => $record ? [...(array) $record, 'payload' => json_decode($record->payload, true)] : null, 'origins' => $origins,
'locations' => $record ? DB::table('partnership_locations')->where('partnership_id', $id)->get() : [], ...$this->catalogues($request)]);
}
public function save(Request $request, ?int $id = null): RedirectResponse|JsonResponse
{
$record = app(PartnershipExchange::class)->save($request->user(), $request->all(), $id);
return $request->expectsJson() ? response()->json(['id' => $record->id, 'version' => $record->version, 'status' => $record->status]) : redirect('/parcerias/'.$record->id.'/editar')->with('success', 'Rascunho guardado.');
}
public function show(Request $request, int $id): Response|JsonResponse
{
$record = app(PartnershipExchange::class)->find($id);
$owner = $request->user() && app(PartnershipExchange::class)->owns($request->user(), $record, false);
$moderator = $request->user() && Gate::forUser($request->user())->allows('manage-portal');
abort_unless($record->status === 'published' || $owner || $moderator, 404);
$payload = json_decode($record->payload, true);
unset($payload['_creation_hash']);
$privateDetails = ($payload['confidentiality'] ?? 'public') === 'private' && ! $owner && ! $moderator;
$mine = $request->user() ? DB::table('partnership_interests')->where('partnership_id', $id)->get()->filter(fn ($i) => app(PartnershipExchange::class)->owns($request->user(), $i, false))->values() : collect();
$interests = $owner ? DB::table('partnership_interests')->where('partnership_id', $id)->orderBy('id')->get() : $mine;
$interestData = $interests->map(function ($interest) use ($record) {
return [...(array) $interest, 'payload' => json_decode($interest->payload, true), 'assessment' => json_decode($interest->assessment, true),
'match' => app(PartnershipMatching::class)->explain($record, $interest), 'room_id' => DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id')];
});
$props = ['record' => ['id' => $record->id, 'title' => $record->title, 'status' => $record->status, 'version' => $record->version, 'kind' => $record->kind,
'partnership_type' => $record->partnership_type, 'sector' => $record->sector, 'province' => $record->province, 'sector_id' => $record->sector_id, 'deadline' => $record->deadline,
'offer' => $privateDetails ? null : $record->offer, 'seeking' => $privateDetails ? null : $record->seeking, 'payload' => $privateDetails ? ['summary' => $payload['summary'] ?? '', 'confidentiality' => 'private'] : $payload],
'owner' => (bool) $owner, 'canEdit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $record), 'moderator' => (bool) $moderator,
'origins' => app(PartnershipSources::class)->forPartnership($id, $owner ? $request->user() : null), 'interests' => $interestData,
'locations' => app(InvestmentRelations::class)->locations(array_values(DB::table('partnership_locations')->where('partnership_id', $id)->get()->map(fn ($l) => ['id' => $l->geo_location_id, 'role' => $l->role, 'source_reference' => $l->source_reference])->all())),
'history' => ($owner || $moderator) ? DB::table('partnership_events')->where('partnership_id', $id)->where('event_type', 'like', 'partnership_opportunity.%')->orderBy('occurred_at')->get(['event_type', 'actor_id', 'occurred_at', 'payload']) : [],
...$this->catalogues($request)];
if ($request->user()) {
Inertia::encryptHistory();
}
return $request->expectsJson() ? response()->json($props)->header('Cache-Control', 'private, no-store') : Inertia::render('partnerships/detail', $props);
}
public function transition(Request $request, int $id): RedirectResponse|JsonResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000']);
$record = app(PartnershipExchange::class)->transition($request->user(), $id, $data['version'], $data['action'], $data['reason']);
return $request->expectsJson() ? response()->json(['status' => $record->status, 'version' => $record->version]) : back()->with('success', 'Decisão registada.');
}
public function interest(Request $request, int $id): RedirectResponse|JsonResponse
{
$interest = app(PartnershipExchange::class)->interest($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['id' => $interest->id, 'version' => $interest->version]) : back()->with('success', 'Interesse guardado.');
}
public function decide(Request $request, int $id): RedirectResponse|JsonResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000', 'assessment' => 'array|max:7']);
$interest = app(PartnershipExchange::class)->decideInterest($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['assessment'] ?? []);
return $request->expectsJson() ? response()->json(['status' => $interest->status, 'version' => $interest->version]) : back()->with('success', 'Candidatura atualizada.');
}
public function room(Request $request, int $id): Response|JsonResponse
{
$context = app(PartnershipExchange::class)->room($request->user(), $id);
$props = [...$context, 'room' => [...(array) $context['room'], 'agreement' => $context['room']->agreement ? json_decode($context['room']->agreement, true) : null],
'messages' => DB::table('partnership_messages as m')->join('users as u', 'u.id', '=', 'm.author_id')->where('room_id', $id)->orderBy('m.id')->get(['m.id', 'm.body', 'm.created_at', 'm.author_id', 'u.name']),
'documents' => DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('room_id', $id)
->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))
->get(['link.id', 'link.shared', 'link.owner_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.id as document_id']),
'milestones' => DB::table('partnership_milestones')->where('room_id', $id)->orderBy('id')->get(),
'canWrite' => app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest'])];
return $request->expectsJson() ? response()->json($props) : Inertia::render('partnerships/room', $props);
}
public function message(Request $request, int $id): RedirectResponse|JsonResponse
{
$data = $request->validate(['client_key' => 'required|uuid', 'body' => 'required|string|max:15000']);
DB::transaction(function () use ($request, $id, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.');
$key = ['room_id' => $id, 'author_id' => $request->user()->id, 'client_key' => $data['client_key']];
$existing = DB::table('partnership_messages')->where($key)->first();
if ($existing) {
abort_unless($existing->body === $data['body'], 409, 'Chave já utilizada com outro conteúdo.');
return;
}
DB::table('partnership_messages')->insert([...$key, 'body' => $data['body']]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.message_created.v1', ['room_id' => $id], 'Nova mensagem privada', [$context['partnership']->user_id, $context['interest']->user_id]);
});
return $request->expectsJson() ? response()->json(['sent' => true]) : back()->with('success', 'Mensagem registada.');
}
public function agreement(Request $request, int $id): RedirectResponse|JsonResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|in:record,confirm,start,complete,cancel,renew', 'title' => 'required_if:action,record|nullable|string|max:200',
'terms' => 'required_if:action,record|nullable|string|max:20000', 'reason' => 'required|string|max:2000']);
DB::transaction(function () use ($request, $id, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$room = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless((int) $room->version === (int) $data['version'], 409, 'Acordo alterado.');
$agreement = $room->agreement ? json_decode($room->agreement, true) : null;
$status = $room->status;
if ($data['action'] === 'record') {
abort_unless(in_array($status, ['negotiation', 'agreement_recorded'], true), 409);
$previous = $agreement['previous_versions'] ?? [];
if ($agreement) {
$previous[] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations'], 'recorded_at' => $agreement['recorded_at']];
}
$agreement = ['title' => $data['title'], 'terms' => $data['terms'], 'recorded_by' => $request->user()->id, 'recorded_at' => now()->toIso8601String(), 'confirmations' => [],
'parties' => [$context['partnership']->user_id, $context['interest']->user_id], 'legal_signature_status' => 'not_verified', 'previous_versions' => $previous];
$status = 'agreement_recorded';
} elseif ($data['action'] === 'confirm') {
abort_unless($status === 'agreement_recorded' && $agreement, 409);
$party = app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) ? 'proponent' : 'candidate';
$agreement['confirmations'][$party] = ['actor_id' => $request->user()->id, 'date' => now()->toIso8601String(), 'reason' => $data['reason']];
if (count($agreement['confirmations']) === 2) {
$status = 'agreed';
}
} else {
$allowed = ['start' => ['agreed'], 'complete' => ['execution'], 'cancel' => ['negotiation', 'agreement_recorded', 'agreed', 'execution'], 'renew' => ['agreed', 'execution']];
abort_unless(in_array($status, $allowed[$data['action']] ?? [], true), 409);
if ($data['action'] === 'complete') {
abort_if(DB::table('partnership_milestones')->where('room_id', $id)->where('status', '!=', 'completed')->exists(), 409, 'Existem marcos pendentes.');
}
$status = ['start' => 'execution', 'complete' => 'closed', 'cancel' => 'cancelled', 'renew' => 'negotiation'][$data['action']];
if ($data['action'] === 'renew') {
$agreement['previous_versions'][] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations']];
$agreement['confirmations'] = [];
}
}
DB::table('partnership_rooms')->where('id', $id)->update(['agreement' => $agreement ? json_encode($agreement) : null, 'status' => $status, 'version' => $room->version + 1, 'updated_at' => now()]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_agreement.changed.v1', ['room_id' => $id, 'status' => $status, 'version' => $room->version + 1, 'reason' => $data['reason']], 'Acordo: '.$status, [$context['partnership']->user_id, $context['interest']->user_id]);
});
return $request->expectsJson() ? response()->json(['recorded' => true]) : back()->with('success', 'Acordo atualizado; assinatura jurídica não verificada.');
}
public function milestone(Request $request, int $id, ?int $milestone = null): RedirectResponse|JsonResponse
{
$data = $request->validate(['title' => 'required|string|max:200', 'responsible_id' => 'required|integer', 'due_date' => 'nullable|date_format:Y-m-d', 'status' => 'required|in:pending,progress,completed',
'evidence' => 'required_if:status,completed|nullable|string|max:10000', 'version' => ($milestone ? 'required' : 'nullable').'|integer|min:1']);
DB::transaction(function () use ($request, $id, $milestone, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless($locked !== null && in_array($locked->status, ['agreement_recorded', 'agreed', 'execution'], true), 409);
$responsible = User::query()->whereKey($data['responsible_id'])->first();
abort_unless($responsible !== null && (app(PartnershipExchange::class)->owns($responsible, $context['partnership']) || app(PartnershipExchange::class)->owns($responsible, $context['interest'])), 422, 'Responsável deve ser participante identificado.');
if ($milestone) {
$existing = DB::table('partnership_milestones')->where('room_id', $id)->where('id', $milestone)->lockForUpdate()->first();
abort_unless($existing !== null, 404);
abort_unless((int) $existing->version === (int) $data['version'], 409);
DB::table('partnership_milestones')->where('id', $milestone)->update([...$data, 'version' => $existing->version + 1, 'updated_at' => now()]);
} else {
unset($data['version']);
$milestone = DB::table('partnership_milestones')->insertGetId([...$data, 'room_id' => $id, 'created_at' => now(), 'updated_at' => now()]);
}
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_milestone.changed.v1', ['milestone_id' => $milestone, 'status' => $data['status']], 'Marco atualizado', [$context['partnership']->user_id, $context['interest']->user_id]);
});
return $request->expectsJson() ? response()->json(['saved' => true]) : back()->with('success', 'Marco guardado.');
}
public function upload(Request $request, int $id): RedirectResponse|JsonResponse
{
$data = $request->validate(['file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', 'shared' => 'required|boolean']);
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$file = $request->file('file');
$documentId = (string) Str::uuid();
$stored = $file->storeAs('partnerships/'.$id, $documentId, 'local');
abort_unless(is_string($stored) && $stored !== '', 503);
try {
DB::transaction(function () use ($request, $id, $data, $file, $documentId, $stored, $context) {
app(PartnershipExchange::class)->room($request->user(), $id, true);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
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',
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored,
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined']);
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');
});
} catch (\Throwable $e) {
Storage::disk('local')->delete($stored);
throw $e;
}
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
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
{
$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)
->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']);
abort_unless($document !== null, 404);
$root = realpath(Storage::disk('local')->path(''));
$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');
return response()->download($path, basename($document->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
}
public function share(Request $request, int $id, int $attachment): RedirectResponse|JsonResponse
{
$data = $request->validate(['shared' => 'required|boolean']);
DB::transaction(function () use ($request, $id, $attachment, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, (bool) $data['shared']);
$link = DB::table('partnership_documents')->where('room_id', $id)->where('id', $attachment)->lockForUpdate()->first();
abort_unless($link !== null && (int) $link->owner_id === $request->user()->id, 403, 'Só o autor pode autorizar ou retirar a partilha.');
DB::table('partnership_documents')->where('id', $attachment)->update(['shared' => $data['shared']]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_sharing_changed.v1', ['room_id' => $id, 'attachment_id' => $attachment, 'shared' => $data['shared']], 'Autorização documental atualizada');
});
return $request->expectsJson() ? response()->json(['saved' => true]) : back()->with('success', 'Autorização de partilha atualizada.');
}
public function notification(Request $request, int $id): RedirectResponse
{
abort_unless(DB::table('partnership_notifications')->where('id', $id)->where('user_id', $request->user()->id)->update(['read_at' => now()]) > 0, 404);
return back();
}
/** @return array<string,mixed> */
private function catalogues(Request $request): array
{
$sources = [];
foreach (InvestmentPortfolioController::visible()->where(fn ($q) => $q->whereNotNull('project_id')->orWhereNotNull('cluster_id'))->get(['id', 'title', 'project_id', 'cluster_id']) as $dossier) {
$sources[] = ['type' => $dossier->project_id ? 'project' : 'cluster', 'target_id' => $dossier->project_id ?? $dossier->cluster_id, 'title' => $dossier->title, 'href' => '/carteira/'.$dossier->id];
}
foreach (DB::table('opportunities')->where('status', 'published')->whereNotNull('published_at')->get(['id', 'title', 'slug']) as $investment) {
$sources[] = ['type' => 'investment', 'target_id' => (string) $investment->id, 'title' => $investment->title, 'href' => '/oportunidades/'.$investment->slug];
}
foreach (DB::table('investment_zones')->where('publication_status', 'published')->whereNull('deleted_at')->get(['id', 'name']) as $zone) {
$sources[] = ['type' => 'zone', 'target_id' => $zone->id, 'title' => $zone->name, 'href' => '/zonas/'.$zone->id];
}
foreach (ExistingBusiness::query()->published()->get(['id', 'public_title', 'public_slug']) as $business) {
$sources[] = ['type' => 'business', 'target_id' => $business->id, 'title' => $business->public_title, 'href' => '/negocios/'.$business->public_slug];
}
if ($request->user()) {
foreach (DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->get(['id']) as $company) {
$sources[] = ['type' => 'company', 'target_id' => $company->id, 'title' => 'Declaração empresarial existente', 'href' => '/investidor/profile'];
}
foreach (DB::table('simulation_form_drafts')->where('owner_user_id', $request->user()->id)->whereNull('deleted_at')->get(['id', 'created_at']) as $draft) {
$sources[] = ['type' => 'simulation', 'target_id' => $draft->id, 'title' => 'Ficha de projeto · '.$draft->created_at, 'href' => '/simulador-fiscal?draft='.$draft->id];
}
}
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']),
'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)
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']) : []];
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers;
use App\Services\PartnershipInstallation;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class PartnershipInstallationController extends Controller
{
public function preview(PartnershipInstallation $installation): Response
{
return Inertia::render('partnerships/installation', $installation->preview());
}
public function apply(Request $request, PartnershipInstallation $installation): RedirectResponse
{
$data = $request->validate(['hash' => 'required|string|size:64']);
$installation->apply($data['hash'], $request->user());
return back()->with('success', 'Bolsa de Parcerias instalada. Registos antigos preservados.');
}
}
@@ -10,6 +10,7 @@ use App\Models\User;
use App\Services\InterestWorkflow;
use App\Services\InvestmentGeography;
use App\Services\InvestmentWorkspace;
use App\Services\OpportunityManagement;
use App\Services\PortalAudit;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
@@ -133,21 +134,41 @@ class PortalManagementController extends Controller
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
{
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
DB::transaction(function () use ($request, $interest, $data) {
$consent = DB::table('consents')->where('interest_request_id', $interest->id)
->where('purpose', 'share_contact_with_proponent')->where('status', 'granted')->lockForUpdate()->first();
$this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent');
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'sharing_consent' => 'withdrawn'])
: back()->with('success', 'Consentimento de partilha revogado.');
}
public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
{
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
$this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest');
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'contact_consent' => 'withdrawn'])
: back()->with('success', 'Consentimento de contacto revogado.');
}
private function withdrawConsent(Request $request, InterestRequest $interest, string $reason, string $purpose): void
{
DB::transaction(function () use ($request, $interest, $reason, $purpose) {
$lockedInterest = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
$consent = DB::table('consents')->where('interest_request_id', $lockedInterest->id)
->where('purpose', $purpose)->where('status', 'granted')->whereNull('deleted_at')
->lockForUpdate()->first();
if (! $consent) {
return;
}
DB::table('consents')->where('id', $consent->id)->update(['status' => 'withdrawn', 'withdrawn_at' => now(), 'updated_at' => now()]);
$correlationId = (string) Str::uuid();
DB::table('business_workflow_transitions')->insert([
'id' => (string) Str::uuid(), 'interest_request_id' => $interest->id,
'from_status' => $interest->status, 'to_status' => $interest->status,
'actor_id' => $request->user()->id, 'reason' => Crypt::encryptString($data['reason']),
'id' => (string) Str::uuid(), 'interest_request_id' => $lockedInterest->id,
'from_status' => $lockedInterest->status, 'to_status' => $lockedInterest->status,
'actor_id' => $request->user()->id, 'reason' => Crypt::encryptString($reason),
'correlation_id' => $correlationId,
'metadata' => json_encode(['source' => 'management-interest', 'action' => 'consent_withdrawn',
'purpose' => 'share_contact_with_proponent'], JSON_THROW_ON_ERROR),
'purpose' => $purpose], JSON_THROW_ON_ERROR),
'created_at' => now(),
]);
DB::table('outbox_events')->insertOrIgnore([
@@ -156,14 +177,12 @@ class PortalManagementController extends Controller
'event_type' => 'InterestConsentWithdrawn', 'data_classification' => 'confidential',
'correlation_id' => $correlationId, 'status' => 'pending',
'payload' => json_encode(['schema_version' => 1, 'consent_id' => $consent->id,
'interest_id' => $interest->integration_id, 'purpose' => 'share_contact_with_proponent'], JSON_THROW_ON_ERROR),
'interest_id' => $lockedInterest->integration_id, 'purpose' => $purpose], JSON_THROW_ON_ERROR),
]);
});
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'sharing_consent' => 'withdrawn'])
: back()->with('success', 'Consentimento de partilha revogado.');
}
/** @return Builder<User> */
private function interestAssignees(): Builder
{
$emails = array_unique(array_merge(config('portal.managers', []), ...array_map(
@@ -181,9 +200,16 @@ class PortalManagementController extends Controller
'q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in($resource === 'sectors' ? ['active', 'inactive'] : ['draft', 'published', 'archived'])],
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')],
'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])],
'page' => ['nullable', 'integer', 'min:1'],
]);
$query = $model::query();
if ($resource === 'opportunities') {
$query->with('primaryTerritory:id,name,location_type,source_system,source_code');
if (isset($filters['geography_scope'])) {
$query->where('geography_scope', $filters['geography_scope']);
}
}
if ($term = trim($filters['q'] ?? '')) {
$query->where(function ($query) use ($term, $resource) {
$query->whereLike($resource === 'sectors' ? 'name' : 'title', "%{$term}%")
@@ -211,6 +237,9 @@ class PortalManagementController extends Controller
'records' => $query->orderByDesc('id')->paginate(20)->withQueryString(),
'filters' => $filters,
'sectors' => $resource === 'opportunities' ? Sector::orderBy('name')->get(['id', 'name']) : [],
'geographyReviewCount' => $resource === 'opportunities'
? Opportunity::where('geography_scope', 'unspecified')->count()
: 0,
]);
}
@@ -229,6 +258,9 @@ class PortalManagementController extends Controller
public function save(Request $request, string $resource, ?int $id = null): RedirectResponse
{
if ($resource === 'opportunities' && app(OpportunityManagement::class)->installed()) {
throw ValidationException::withMessages(['status' => 'Use Gestão de Oportunidades para guardar uma versão de rascunho; publicação não é uma edição.']);
}
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
$record = $id ? $model::findOrFail($id) : new $model;
$rules = $resource === 'sectors' ? [
@@ -258,6 +290,7 @@ class PortalManagementController extends Controller
'is_featured' => ['required', 'boolean'],
];
if ($resource === 'opportunities') {
$rules['geography_scope'] = ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])];
foreach (InvestmentGeography::FIELDS as $field => $type) {
$rules[$field] = ['nullable', 'uuid'];
}
@@ -285,8 +318,14 @@ class PortalManagementController extends Controller
abort_unless((int) $current->territory_version === (int) $data['territory_version'], 409, 'Localização alterada. Recarregue a ficha.');
}
$path = app(InvestmentGeography::class)->selection($data, true);
if (($data['geography_scope'] ?? null) === 'national' && $path !== []) {
throw ValidationException::withMessages(['geography_scope' => 'O âmbito nacional não pode ter uma localização territorial específica.']);
}
$data = array_diff_key($data, InvestmentGeography::FIELDS);
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
if ($path !== [] && empty($data['geography_scope'])) {
$data['geography_scope'] = 'specific';
}
$data['territory_version'] = (int) ($data['territory_version'] ?? 0) + 1;
$data['province'] = $path[0]->name ?? null;
$data['district'] = $path[1]->name ?? null;
+670 -32
View File
@@ -2,16 +2,23 @@
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\Sector;
use App\Services\IdempotencyConflict;
use App\Services\InterestSubmission;
use App\Services\Malware\MalwareScanner;
use App\Services\VirtualDesk;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -20,21 +27,43 @@ class PortalServicesController extends Controller
{
public function home(): Response
{
return Inertia::render('PortalInvestidor', ['essentialResources' => $this->resources()->where('r.essential', true)
->orderBy('r.title')->limit(6)->get(['r.id', 'r.title'])]);
try {
$essentialResources = $this->resources()->where('r.essential', true)
->orderBy('r.title')->limit(6)->get(['r.id', 'r.title']);
} catch (QueryException $exception) {
// A catalogue schema mismatch must not take down unrelated home content.
// Keep the document list empty and retain the full exception in internal logs.
report($exception);
$essentialResources = collect();
}
return Inertia::render('PortalInvestidor', ['essentialResources' => $essentialResources]);
}
private function resources(): Builder
{
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.published', true)->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at');
->where('r.published', true)->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256');
}
public function page(Request $request): Response
public function page(Request $request): Response|JsonResponse|RedirectResponse
{
$page = $request->route()->defaults['page'];
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'category' => ['nullable', 'string', 'max:80'],
'topic' => ['nullable', 'string', 'max:80'], 'sector' => ['nullable', 'string', 'max:150'], 'province' => ['nullable', 'string', 'max:100']]);
if ($page === 'partnerships' && Schema::hasColumn('portal_partnerships', 'partnership_type')) {
return app(PartnershipExchangeController::class)->index($request);
}
$filters = $request->validate([
'q' => ['nullable', 'string', 'max:120'], 'category' => ['nullable', 'string', 'max:80'],
'topic' => ['nullable', 'string', 'max:80'], 'sector' => ['nullable', 'string', 'max:150'], 'province' => ['nullable', 'string', 'max:100'],
'document_type' => ['nullable', 'string', 'max:40'], 'language' => ['nullable', 'string', 'max:12'],
'issuer' => ['nullable', 'string', 'max:180'], 'legal_status' => ['nullable', 'string', 'max:24'],
'source_confirmation' => ['nullable', 'string', 'max:24'], 'territory_id' => ['nullable', 'uuid'],
'activity' => ['nullable', 'array', 'max:10'], 'activity.*' => ['string', 'max:180'],
'stage' => ['nullable', 'array', 'max:10'], 'stage.*' => ['string', 'max:80'],
'module' => ['nullable', 'array', 'max:10'], 'module.*' => ['string', 'max:80'],
]);
$props = ['section' => $page, 'filters' => $filters];
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']);
@@ -46,15 +75,71 @@ class PortalServicesController extends Controller
}
$props['categories'] = (clone $query)->distinct()->orderBy('r.category')->pluck('r.category');
$props['topics'] = (clone $query)->distinct()->orderBy('r.topic')->pluck('r.topic');
foreach (['category', 'topic'] as $field) {
foreach (['category', 'topic', 'document_type', 'language', 'legal_status', 'source_confirmation'] as $field) {
if (! empty($filters[$field])) {
$query->where('r.'.$field, $filters[$field]);
}
}
if (! empty($filters['q'])) {
$query->where('r.title', 'ilike', '%'.$filters['q'].'%');
if (! empty($filters['issuer'])) {
$query->where('d.issuer', 'ilike', '%'.$filters['issuer'].'%');
}
if (! empty($filters['territory_id'])) {
$territoryIds = $this->territoryScopeIds($filters['territory_id']);
$query->where(function (Builder $territorial) use ($territoryIds): void {
$territorial->where('r.territorial_scope', 'national')->orWhereIn('r.territory_id', $territoryIds)
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as l')
->whereColumn('l.resource_id', 'r.id')->where('l.target_type', 'territory')->whereIn('l.target_key', $territoryIds));
});
}
foreach (['activity', 'stage', 'module'] as $dimension) {
if (! empty($filters[$dimension])) {
$query->whereExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as l')
->whereColumn('l.resource_id', 'r.id')->where('l.target_type', $dimension)
->whereIn('l.target_key', array_values($filters[$dimension])));
}
}
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn (Builder $search) => $search->where('r.title', 'ilike', $term)->orWhere('r.description', 'ilike', $term)
->orWhere('r.document_number', 'ilike', $term)->orWhere('d.issuer', 'ilike', $term)
->orWhere('r.source_reference', 'ilike', $term)->orWhere('r.category', 'ilike', $term)->orWhere('r.topic', 'ilike', $term));
}
$pageResult = $query->orderByRaw("CASE WHEN r.document_type IN ('official_form','digital_adaptation','guidance_template') THEN 1 ELSE 0 END")
->orderByDesc('r.essential')->orderBy('r.title')->select([
'r.id', 'r.document_id', 'r.title', 'r.description', 'r.category', 'r.topic', 'r.document_type', 'r.document_number', 'r.document_date',
'r.applicable_from', 'r.applicable_until',
'r.source_url', 'r.language', 'r.version_label', 'r.document_group_id', 'r.territorial_scope', 'r.territory_id',
'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',
])->paginate(20)->withQueryString();
$pageResult->getCollection()->transform(function ($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['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['issuers'] = (clone $this->resources())->whereNotNull('d.issuer')->distinct()->orderBy('d.issuer')->pluck('d.issuer');
$props['legalStatuses'] = (clone $this->resources())->distinct()->orderBy('r.legal_status')->pluck('r.legal_status');
$props['territories'] = DB::table('geo_locations')->where('data_classification', 'public')->whereNull('deleted_at')
->whereIn('location_type', ['province', 'district', 'municipality', 'site'])->orderBy('name')->get(['id', 'name', 'location_type', 'parent_id']);
foreach (['activities' => 'activity', 'stages' => 'stage', 'modules' => 'module'] as $key => $type) {
$props[$key] = DB::table('portal_resource_links as l')->join('portal_resources as r', 'r.id', '=', 'l.resource_id')
->join('documents as d', 'd.id', '=', 'r.document_id')->where('l.target_type', $type)->where('r.published', true)
->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
->distinct()->orderBy('l.target_key')->pluck('l.target_key');
}
$props['resources'] = $query->orderByDesc('r.essential')->orderBy('r.title')->select(['r.id', 'r.title', 'r.category', 'r.topic', 'r.source_reference', 'r.essential'])->paginate(20)->withQueryString();
}
if ($page === 'partnerships') {
$query = DB::table('portal_partnerships')->where('status', 'published');
@@ -69,6 +154,9 @@ class PortalServicesController extends Controller
$props['partnerships'] = $query->orderByDesc('id')->select(['id', 'title', 'sector', 'province', 'offer', 'seeking'])->paginate(20)->withQueryString();
}
if ($page === 'desk') {
if (app(VirtualDesk::class)->installed()) {
return redirect('/balcao-virtual/painel');
}
$props['requests'] = InterestRequest::where('metadata->portal_user_id', $request->user()->id)->latest()->limit(100)->get(['reference', 'status', 'created_at', 'metadata']);
$props['myPartnerships'] = DB::table('portal_partnerships')->where('user_id', $request->user()->id)->latest()->limit(100)->get(['id', 'title', 'status']);
}
@@ -77,6 +165,58 @@ class PortalServicesController extends Controller
return Inertia::render('portal/services', $props);
}
public function recommendations(Request $request): JsonResponse
{
$data = $request->validate([
'activity_id' => ['nullable', 'string', 'max:180'], 'province_id' => ['nullable', 'uuid'],
'stage' => ['nullable', 'string', 'max:80'], 'module' => ['nullable', 'string', 'max:80'],
]);
$module = $data['module'] ?? 'simulator';
$query = $this->resources()->whereExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as l')
->whereColumn('l.resource_id', 'r.id')->where('l.target_type', 'module')->where('l.target_key', $module));
$matches = [['type' => 'module', 'key' => $module]];
foreach (['activity_id' => 'activity', 'stage' => 'stage'] as $input => $type) {
if (! empty($data[$input])) {
$key = $data[$input];
$query->where(function (Builder $contextual) use ($type, $key): void {
$contextual->whereNotExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as general')
->whereColumn('general.resource_id', 'r.id')->where('general.target_type', $type))
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as matching')
->whereColumn('matching.resource_id', 'r.id')->where('matching.target_type', $type)->where('matching.target_key', $key));
});
$matches[] = ['type' => $type, 'key' => $data[$input]];
}
}
if (! empty($data['province_id'])) {
$ids = $this->territoryScopeIds($data['province_id']);
$query->where(fn (Builder $territorial) => $territorial->where('r.territorial_scope', 'national')->orWhereIn('r.territory_id', $ids)
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('portal_resource_links as l')->whereColumn('l.resource_id', 'r.id')
->where('l.target_type', 'territory')->whereIn('l.target_key', $ids)));
$matches = [...$matches, ...array_map(fn ($id) => ['type' => 'territory', 'key' => $id], $ids)];
}
$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']);
$resources->transform(function ($resource) use ($matches): array {
$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]);
}
public function submit(Request $request, InterestSubmission $submission): RedirectResponse
{
$data = $request->validate([
@@ -133,69 +273,567 @@ class PortalServicesController extends Controller
return response()->download($path, basename($resource->file_name), ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store']);
}
public function manage(): Response
public function showDocument(Request $request, int $id): Response
{
return Inertia::render('portal/manage', ['resources' => DB::table('portal_resources')->latest()->limit(100)->get(),
$resource = $this->resources()->where('r.id', $id)->first([
'r.id', 'r.document_id', 'r.title', 'r.description', 'r.category', 'r.topic', 'r.document_type',
'r.document_number', 'r.document_date', 'r.applicable_from', 'r.applicable_until', 'r.source_url', 'r.language', 'r.version_label',
'r.territorial_scope', 'r.territory_id', 'r.source_confirmation', 'r.legal_status', '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',
]);
abort_unless($resource !== null, 404);
$resource->links = DB::table('portal_resource_links')->where('resource_id', $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]);
$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');
$backUrl = is_string($back) && (str_starts_with($back, '/documentos') || str_starts_with($back, '/legislacao')) && ! str_starts_with($back, '//')
? $back : '/documentos';
return Inertia::render('portal/document', [
'resource' => $resource,
'backUrl' => $backUrl,
'downloadUrl' => route('services.download', ['id' => $id]),
]);
}
public function viewDocument(int $id): BinaryFileResponse
{
$document = $this->resources()->where('r.id', $id)->first([
'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);
$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, [
'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
{
$document = DB::table('documents')->where('id', $id)->whereNull('deleted_at')->first([
'storage_key', 'file_name', 'sha256', 'status', 'malware_scan_status', 'malware_scanned_sha256',
]);
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
&& 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), [
'X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store',
]);
}
public function manage(MalwareScanner $scanner): Response
{
$disclosureAuthorization = DB::table('audit_events')->where('source_system', 'user-instruction')
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
$disclosureAuthorizationData = $disclosureAuthorization ? json_decode($disclosureAuthorization->after_data, true) : null;
$resources = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->orderByDesc('r.updated_at')->limit(200)
->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']);
$links = DB::table('portal_resource_links')->whereIn('resource_id', $resources->pluck('id'))->orderBy('id')->get()->groupBy('resource_id');
$resources->each(fn ($resource) => $resource->links = $links->get($resource->id, collect())->values());
$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(fn ($resource) => $resource->revisions = $revisions->get($resource->id, collect())->values());
$malwareHealth = $scanner->health();
$malwareHealth['signatures_at'] = $malwareHealth['signatures_at']?->format(DATE_ATOM);
return Inertia::render('portal/manage', ['resources' => $resources,
'requirementCatalogue' => $this->requirementEvidenceEnabled()
? collect(is_array($catalogue = config('document-requirements.catalogue', [])) ? $catalogue : [])->map(fn ($item, $key) => ['key' => $key, ...$item])->values()
: collect(),
'requirementAssociationsEnabled' => $this->requirementEvidenceEnabled(),
'partnerships' => DB::table('portal_partnerships')->latest()->limit(100)->get(),
'documents' => DB::table('documents')->where('status', 'active')->where('data_classification', 'public')->whereNull('deleted_at')->get(['id', 'file_name'])]);
'documents' => DB::table('documents')->where('status', '!=', 'deleted')->whereNull('deleted_at')->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']),
'malwareHealth' => $malwareHealth,
'disclosureAuthorization' => $disclosureAuthorizationData ? [
'external_id' => $disclosureAuthorization->external_id,
'occurred_at' => $disclosureAuthorization->occurred_at,
'resources' => DB::table('portal_resources')->whereIn('id', $disclosureAuthorizationData['resource_ids'] ?? [])
->orderBy('id')->get(['id', 'title', 'published', 'rights_status']),
] : null,
'malwareCounts' => DB::table('documents')->whereNull('deleted_at')->where('status', '!=', 'deleted')
->select('malware_scan_status', DB::raw('count(*) as total'))->groupBy('malware_scan_status')->pluck('total', 'malware_scan_status'),
'territories' => DB::table('geo_locations')->where('data_classification', 'public')->whereNull('deleted_at')
->whereIn('location_type', ['country', 'province', 'district', 'municipality', 'site'])->orderBy('name')->get(['id', 'name', 'location_type']),
'incompleteCount' => DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where(fn ($q) => $q->whereNull('r.description')->orWhereNull('d.issuer')->orWhereNull('r.source_url')
->orWhere('r.source_confirmation', 'unconfirmed')->orWhere('r.legal_status', 'unknown')->orWhere('r.rights_status', 'unconfirmed'))
->count(),
'possibleDuplicates' => DB::table('portal_resources')->whereNotNull('duplicate_of_resource_id')->count()]);
}
public function upload(Request $request): RedirectResponse
{
$request->validate(['file' => ['required', 'file', 'mimetypes:application/pdf,text/plain', 'max:10240'], 'publication_consent' => ['accepted']]);
$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'],
'original_source' => ['nullable', 'url:https', 'max:2000'], 'issuer' => ['nullable', 'string', 'max:180']]);
$file = $request->file('file');
$checksum = hash_file('sha256', $file->getRealPath());
if (DB::table('documents')->where('sha256', $checksum)->whereNull('deleted_at')->exists()) {
return to_route('services.manage')->withErrors(['file' => 'Já existe um ficheiro com o mesmo conteúdo. Verifique se corresponde a uma nova versão ou a um duplicado.']);
}
$id = (string) Str::uuid();
$key = $file->storeAs('portal-documents', $id, 'local');
abort_unless($key !== false, 500);
try {
DB::transaction(function () use ($file, $id, $key, $request) {
DB::transaction(function () use ($file, $id, $key, $request, $checksum) {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['investmoz-document-content:'.$checksum]);
abort_unless(! DB::table('documents')->where('sha256', $checksum)->whereNull('deleted_at')->exists(), 409,
'Já existe um ficheiro com o mesmo conteúdo. Verifique se corresponde a uma nova versão ou a um duplicado.');
DB::table('documents')->insert(['id' => $id, 'source_system' => 'portal-services',
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $key,
'sha256' => hash_file('sha256', Storage::disk('local')->path($key)), 'status' => 'active', 'data_classification' => 'public']);
'sha256' => $checksum, 'size_bytes' => $file->getSize(), 'issuer' => $request->input('issuer'),
'original_source' => $request->input('original_source'), 'uploaded_by' => $request->user()->id,
'status' => 'quarantined', 'data_classification' => 'internal', 'rights_status' => 'unconfirmed']);
DB::table('audit_events')->insert(['source_system' => 'portal-services', 'entity_type' => 'documents', 'entity_id' => $id,
'actor_user_id' => $request->user()->id, 'action' => 'public_document_uploaded']);
'actor_user_id' => $request->user()->id, 'action' => 'document_uploaded_to_quarantine']);
});
} catch (\Throwable $exception) {
Storage::disk('local')->delete($key);
throw $exception;
}
return back()->with('success', 'Documento carregado. Seleccione-o no catálogo e registe a fonte para publicar.');
ScanDocumentForMalware::dispatch($id)->afterCommit();
return to_route('services.manage')->with('success', 'Documento recebido em armazenamento privado e quarentena. Não aparece na biblioteca pública até validação e publicação explícitas.');
}
public function resource(Request $request): RedirectResponse
{
$data = $request->validate(['document_id' => ['required', 'uuid'], 'title' => ['required', 'string', 'max:200'],
'category' => ['required', 'string', 'max:80'], 'topic' => ['required', 'string', 'max:80'],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'legislation' => ['required', 'boolean'], 'essential' => ['required', 'boolean'], 'published' => ['required', 'boolean']]);
DB::transaction(function () use ($data, $request) {
abort_unless(DB::table('documents')->where('id', $data['document_id'])->where('status', 'active')->where('data_classification', 'public')->whereNull('deleted_at')->lockForUpdate()->exists(), 422, 'Seleccione um documento público activo.');
$id = DB::table('portal_resources')->insertGetId([...$data, 'approved_by' => $request->user()->id, 'created_at' => now(), 'updated_at' => now()]);
$this->audit($request, 'resource_registered', 'portal_resources', $id);
$data = $this->validateResource($request);
$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();
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
$identity = $this->identityKey($data);
if ($identity) {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
}
$duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->value('id') : null;
$fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, true);
$this->assertPublicClassificationEligible($data, $document);
$id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]);
$this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'created', $request->user()->id, 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, $duplicate ? 'resource_registered_possible_duplicate' : 'resource_registered', 'portal_resources', $id);
return $id;
});
return back()->with('success', 'Documento catalogado.');
return to_route('services.manage')->with('success', 'Documento registado como rascunho privado da biblioteca. A publicação requer uma acção separada.');
}
public function updateResource(Request $request, int $id): RedirectResponse
{
$data = $this->validateResource($request);
$expectedVersion = (int) $request->validate(['metadata_version' => ['required', 'integer', 'min:1']])['metadata_version'];
DB::transaction(function () use ($data, $request, $id, $expectedVersion): void {
$resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
abort_unless($resource !== null, 404);
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();
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
$identity = $this->identityKey($data);
if ($identity) {
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
}
$duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->where('id', '!=', $id)->value('id') : null;
$fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, false);
$this->assertPublicClassificationEligible($data, $document);
$retainPublication = (bool) $resource->published && $data['rights_status'] === 'authorized'
&& $data['source_confirmation'] !== 'unconfirmed' && ! empty($data['source_url'])
&& (! ($data['legislation'] || $data['document_type'] === 'legislation') || $data['source_confirmation'] === 'official_confirmed')
&& $document->status === 'active' && ($data['data_classification'] ?? $document->data_classification) === 'public' && $document->rights_status === 'authorized'
&& $document->malware_scan_status === 'clean' && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256));
DB::table('portal_resources')->where('id', $id)->update([...$fields, 'approved_by' => $retainPublication ? $resource->approved_by : null, 'published' => $retainPublication,
'metadata_version' => $expectedVersion + 1, 'updated_at' => now()]);
DB::table('portal_resource_links')->where('resource_id', $id)->delete();
$this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'metadata_updated', $request->user()->id, $expectedVersion + 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, 'resource_metadata_updated', 'portal_resources', $id);
});
return to_route('services.manage')->with('success', 'Metadados e relações actualizados; o estado de publicação foi preservado.');
}
public function moderate(Request $request, string $type, int $id): RedirectResponse
{
$data = $request->validate(['published' => ['required', 'boolean']]);
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.');
}
$data = $this->validateManagement($request, ['published' => ['required', 'boolean']]);
$table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships';
DB::transaction(function () use ($request, $data, $table, $type, $id) {
abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404);
if ($type === 'resources' && $data['published']) {
$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',
'r.source_url', 'd.status', 'd.data_classification', 'd.deleted_at', 'd.rights_status as file_rights_status',
'd.malware_scan_status', 'd.malware_scanned_sha256', 'd.sha256']);
abort_unless($resource !== null && $resource->deleted_at === null, 404);
if ($resource->status !== 'active') {
throw $this->managementValidationException(['published' => 'A análise técnica ainda não libertou o ficheiro da quarentena. Aguarde a análise antimalware antes de publicar.']);
}
if ($resource->data_classification !== 'public') {
throw $this->managementValidationException(['published' => 'O ficheiro já saiu da quarentena técnica, mas continua classificado como interno. Reveja os direitos e a possibilidade de divulgação; só então altere explicitamente a classificação para pública.']);
}
if ($resource->rights_status !== 'authorized' || $resource->file_rights_status !== 'authorized') {
throw $this->managementValidationException(['published' => 'Confirme e registe os direitos de utilização antes de publicar.']);
}
if ($resource->source_confirmation === 'unconfirmed' || ! $resource->source_url) {
throw $this->managementValidationException(['published' => 'Identifique e confirme a fonte documental antes de publicar.']);
}
if ($resource->malware_scan_status !== 'clean'
|| ! hash_equals(trim($resource->sha256), trim((string) $resource->malware_scanned_sha256))) {
throw $this->managementValidationException(['published' => 'A análise antimalware tem de terminar antes da publicação.']);
}
}
DB::table($table)->where('id', $id)->update($type === 'resources'
? ['published' => $data['published'], 'approved_by' => $request->user()->id, 'updated_at' => now()]
? ['published' => $data['published'], 'approved_by' => $data['published'] ? $request->user()->id : null,
'last_reviewed_by' => $request->user()->id, 'last_reviewed_at' => now(), 'metadata_version' => DB::raw('metadata_version + 1'), 'updated_at' => now()]
: ['status' => $data['published'] ? 'published' : 'withdrawn', 'reviewed_by' => $request->user()->id, 'updated_at' => now()]);
if ($type === 'resources') {
$this->recordResourceRevision($id, $data['published'] ? 'published' : 'unpublished', $request->user()->id,
(int) DB::table('portal_resources')->where('id', $id)->value('metadata_version'));
}
$this->audit($request, $data['published'] ? 'published' : 'withdrawn', $table, $id);
});
return back()->with('success', 'Publicação actualizada.');
return to_route('services.manage')->with('success', 'Publicação actualizada.');
}
private function audit(Request $request, string $action, string $table, int $id): void
public function applyDocumentDisclosureAuthorization(Request $request): RedirectResponse
{
$event = DB::table('audit_events')->where('source_system', 'user-instruction')
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
->where('action', 'public_disclosure_authorized')->first();
abort_unless($event !== null, 404);
$authorization = json_decode($event->after_data, true);
$resourceIds = array_values(array_unique(array_map('intval', $authorization['resource_ids'] ?? [])));
abort_unless(count($resourceIds) === 4, 409, 'O âmbito da autorização registada foi alterado; interrompida a publicação.');
$published = [];
$skipped = [];
DB::transaction(function () use ($request, $event, $resourceIds, &$published, &$skipped): void {
foreach ($resourceIds as $resourceId) {
$resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.id', $resourceId)->lockForUpdate()->first([
'r.id', 'r.title', 'r.document_type', 'r.legislation', 'r.source_url', 'r.source_confirmation',
'r.rights_status as resource_rights', 'r.published', 'r.approved_by', 'r.metadata_version',
'd.id as document_id', 'd.storage_key', 'd.sha256', 'd.status', 'd.deleted_at', 'd.rights_status as file_rights',
'd.malware_scan_status', 'd.malware_scanned_sha256', 'd.data_classification',
]);
if ($resource === null) {
$skipped[$resourceId] = 'Registo ou ficheiro inexistente.';
continue;
}
if ($resource->published && $resource->data_classification === 'public' && $resource->resource_rights === 'authorized' && $resource->file_rights === 'authorized') {
$published[$resourceId] = 'Já publicado.';
continue;
}
$path = Storage::disk('local')->path($resource->storage_key);
$root = realpath(Storage::disk('local')->path(''));
$realPath = realpath($path);
$actualHash = $realPath && is_file($realPath) && $root
&& str_starts_with(strtolower($realPath), strtolower($root.DIRECTORY_SEPARATOR))
? hash_file('sha256', $realPath) : false;
if ($resource->deleted_at !== null || $resource->status !== 'active'
|| $resource->malware_scan_status !== 'clean' || ! is_string($actualHash)
|| ! hash_equals((string) $resource->sha256, $actualHash)
|| ! hash_equals((string) $resource->sha256, (string) $resource->malware_scanned_sha256)) {
$skipped[$resourceId] = 'Ficheiro indisponível, não limpo ou diferente dos bytes analisados.';
continue;
}
if (in_array($resource->resource_rights, ['restricted'], true) || in_array($resource->file_rights, ['restricted'], true)
|| $resource->source_confirmation === 'unconfirmed' || ! filter_var($resource->source_url, FILTER_VALIDATE_URL)
|| parse_url($resource->source_url, PHP_URL_SCHEME) !== 'https') {
$skipped[$resourceId] = 'Restrição de divulgação ou origem identificada em falta.';
continue;
}
$now = now();
$nextVersion = (int) $resource->metadata_version + 1;
DB::table('documents')->where('id', $resource->document_id)->update([
'rights_status' => 'authorized', 'data_classification' => 'public', 'updated_at' => $now,
]);
DB::table('portal_resources')->where('id', $resourceId)->update([
'rights_status' => 'authorized', 'published' => true, 'approved_by' => $request->user()->id,
'last_reviewed_by' => $request->user()->id, 'last_reviewed_at' => $now,
'metadata_version' => $nextVersion, 'updated_at' => $now,
]);
$this->attachAuthorizedDocumentaryEvidence($resourceId, $resource->title);
$this->recordResourceRevision($resourceId, 'published', $request->user()->id, $nextVersion);
$this->audit($request, 'published_under_user_authorization', 'portal_resources', $resourceId, [
'authorization_source_system' => $event->source_system,
'authorization_external_id' => $event->external_id,
'source_confirmation' => $resource->source_confirmation,
'legal_status_preserved' => true,
]);
$published[$resourceId] = 'Publicado com a situação de fonte e vigência já registada.';
}
});
return to_route('services.manage')->with('success', count($published).' documento(s) disponibilizado(s); '.count($skipped).' pendência(s) individual(is).')
->with('disclosureResults', ['published' => $published, 'skipped' => $skipped]);
}
/** @param array<string,mixed> $additional */
private function audit(Request $request, string $action, string $table, int $id, array $additional = []): void
{
DB::table('audit_events')->insert(['source_system' => 'portal-services', 'entity_type' => $table,
'actor_user_id' => $request->user()->id, 'action' => $action, 'after_data' => json_encode(['record_id' => $id], JSON_THROW_ON_ERROR)]);
'actor_user_id' => $request->user()->id, 'action' => $action,
'after_data' => json_encode(['record_id' => $id, ...$additional], JSON_THROW_ON_ERROR)]);
}
private function attachAuthorizedDocumentaryEvidence(int $resourceId, string $title): void
{
if (! $this->requirementEvidenceEnabled()) {
return;
}
$evidence = match (true) {
str_contains($title, 'Lei n.º 22/2022') => [['fiscal.iva.lei_22_2022', 'confirmed', 'Lei n.º 22/2022, art. 17(1); citação conferida no exemplar cujo SHA-256 coincide com o ficheiro oficial. Isto é evidência documental, não valida vigência ou cálculo.']],
str_contains($title, 'BR 248/2025') || str_contains($title, 'n.º 248/2025') => array_map(fn (array $law) => ['fiscal.'.$law[0].'.'.$law[1], 'pending', 'BR n.º 248/2025, Suplemento n.º 1, '.$law[2].'; artigo/dispositivo específico não conferido nesta associação. Evidência identificada, não fundamento confirmado.'], [
['ice', 'lei_7_2025', 'Lei n.º 7/2025'], ['customs', 'lei_8_2025', 'Lei n.º 8/2025'],
['ispc', 'lei_9_2025', 'Lei n.º 9/2025'], ['iva', 'lei_10_2025', 'Lei n.º 10/2025'],
['irps', 'lei_11_2025', 'Lei n.º 11/2025'], ['irpc', 'lei_12_2025', 'Lei n.º 12/2025'],
]),
str_contains($title, 'Lei n.º 13/2016') || str_contains($title, 'BR n.º 89') => [['fiscal.iva.lei_13_2016_rectification_2017', 'pending', 'BR n.º 89/2017, I Série, p. 569, aviso relativo à Lei n.º 13/2016; a correspondência do exemplar local e os dispositivos rectificados aguardam conferência. Evidência identificada, não fundamento confirmado.']],
default => [],
};
foreach ($evidence as [$key, $reviewStatus, $basis]) {
if (! array_key_exists($key, config('document-requirements.catalogue', []))) {
continue;
}
$exists = DB::table('portal_resource_links')->where('resource_id', $resourceId)
->where('target_type', 'requirement')->where('target_key', $key)->exists();
if ($exists) {
continue;
}
DB::table('portal_resource_links')->insert([
'resource_id' => $resourceId, 'target_type' => 'requirement', 'target_key' => $key,
'relationship' => 'cites', 'applicability' => 'evidence', 'basis_reference' => $basis,
'review_status' => $reviewStatus, 'created_at' => now(), 'updated_at' => now(),
]);
}
}
/** @return array<string,mixed> */
private function validateResource(Request $request): array
{
$data = $this->validateManagement($request, [
'document_id' => ['required', 'uuid'], 'title' => ['required', 'string', 'max:200'],
'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'],
'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'],
'applicable_from' => ['nullable', 'date_format:Y-m-d'],
'applicable_until' => ['nullable', 'date_format:Y-m-d'],
'language' => ['required', 'string', 'max:12'], 'version_label' => ['nullable', 'string', 'max:120'],
'document_group_id' => ['nullable', 'uuid'], 'territorial_scope' => ['required', 'in:national,provincial,district,locality,multiple,unknown'],
'territory_id' => ['nullable', 'uuid', 'exists:geo_locations,id'],
'source_confirmation' => ['required', 'in:unconfirmed,identified,official_confirmed'],
'legal_status' => ['required', 'in:not_applicable,in_force,historical,proposed,repealed,amended,unknown'],
'rights_status' => ['required', 'in:unconfirmed,authorized,restricted'], 'independent_review' => ['required', 'boolean'],
'data_classification' => ['nullable', 'in:internal,public'],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'legislation' => ['required', 'boolean'], 'essential' => ['required', 'boolean'],
'associations' => ['nullable', 'array', 'max:40'], 'associations.*.target_type' => ['required', 'in:theme,module,activity,stage,procedure,entity,territory,document,investment_type,legal_source'.($this->requirementEvidenceEnabled() ? ',requirement' : '')],
'associations.*.target_key' => ['required', 'string', 'max:180'],
'associations.*.review_status' => ['nullable', 'in:pending,confirmed'],
'associations.*.relationship' => ['required', 'in:applies_to,supports,version_of,translation_of,amends,repeals,implements,cites,related_to'],
'associations.*.applicability' => ['required', 'in:required,conditional,support,optional_template,evidence'],
'associations.*.condition_text' => ['nullable', 'string', 'max:2000'], 'associations.*.basis_reference' => ['nullable', 'string', 'max:2000'],
]);
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.']);
}
foreach ($data['associations'] ?? [] as $index => $association) {
if (($association['target_type'] ?? null) === 'requirement' && ! $this->requirementEvidenceEnabled()) {
throw $this->managementValidationException(["associations.$index.target_type" => 'As associações documentais a requisitos ainda aguardam a migração do catálogo.']);
}
if (($association['target_type'] ?? null) === 'requirement'
&& ! array_key_exists($association['target_key'], config('document-requirements.catalogue', []))) {
throw $this->managementValidationException(["associations.$index.target_key" => 'Seleccione um identificador técnico de requisito existente.']);
}
if (mb_strlen(trim($association['basis_reference'] ?? '')) < 5) {
throw $this->managementValidationException(["associations.$index.basis_reference" => 'Indique o artigo, secção, página ou outro trecho que esta associação sustenta.']);
}
if ($association['applicability'] === 'conditional' && mb_strlen(trim($association['condition_text'] ?? '')) < 5) {
throw $this->managementValidationException(["associations.$index.condition_text" => 'Descreva a condição de aplicação.']);
}
}
return $data;
}
/** Keep validation redirects on the management GET page even if the request
* arrived with a stale Referer pointing at a write-only resource endpoint.
*
* @param array<string,mixed> $rules
* @return array<string,mixed>
*/
private function validateManagement(Request $request, array $rules): array
{
try {
return $request->validate($rules);
} catch (ValidationException $exception) {
throw $this->managementValidationException($exception->errors());
}
}
/** @param array<string,string|list<string>> $errors */
private function managementValidationException(array $errors): ValidationException
{
$exception = ValidationException::withMessages($errors);
$exception->redirectTo = route('services.manage');
return $exception;
}
/** @param array<string,mixed> $data
* @return array<string,mixed> */
private function resourceFields(array $data, int $actor, ?string $identity, ?int $duplicate, bool $creating): array
{
unset($data['associations'], $data['issuer'], $data['data_classification']);
$data['document_identity_key'] = $identity;
$data['duplicate_of_resource_id'] = $duplicate;
$data['last_reviewed_at'] = $data['source_confirmation'] !== 'unconfirmed' || $data['rights_status'] === 'authorized' ? now() : null;
$data['last_reviewed_by'] = $actor;
if ($creating) {
$data['created_by'] = $actor;
} else {
unset($data['metadata_version']);
}
return $data;
}
/** @param list<array<string,mixed>> $links */
private function syncResourceLinks(int $resourceId, array $links): void
{
foreach ($links as $link) {
if ($link['target_type'] === 'document') {
abort_unless(DB::table('portal_resources')->where('id', $link['target_key'])->exists(), 422, 'A relação documental seleccionada não existe.');
}
DB::table('portal_resource_links')->insert([
'resource_id' => $resourceId, 'target_type' => $link['target_type'], 'target_key' => $link['target_key'],
'relationship' => $link['relationship'], 'applicability' => $link['applicability'],
'condition_text' => $link['condition_text'] ?? null, 'basis_reference' => $link['basis_reference'] ?? null,
...($this->requirementEvidenceEnabled() ? ['review_status' => $link['review_status'] ?? 'pending'] : []),
'created_at' => now(), 'updated_at' => now(),
]);
}
}
/** @param array<string,mixed> $data */
private function assertPublicClassificationEligible(array $data, \stdClass $document): void
{
if (($data['data_classification'] ?? $document->data_classification) !== 'public') {
return;
}
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean'
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 422,
'A análise antimalware e a integridade do ficheiro têm de estar confirmadas antes de o classificar como público.');
abort_unless($data['rights_status'] === 'authorized', 422,
'Registe a autorização de utilização antes de classificar o ficheiro como público.');
abort_unless($data['source_confirmation'] !== 'unconfirmed' && ! empty($data['source_url']), 422,
'Identifique e confirme a fonte antes de classificar o ficheiro como público.');
}
/** @param array<string,mixed> $data */
private function identityKey(array $data): ?string
{
if (empty($data['issuer']) || empty($data['document_number'])) {
return null;
}
return hash('sha256', mb_strtolower(implode('|', [trim($data['issuer']), trim($data['document_number']),
$data['document_date'] ?? '', $data['language'], $data['version_label'] ?? ''])));
}
private function recordResourceRevision(int $id, string $changeType, int $actor, int $revision): void
{
$resource = DB::table('portal_resources')->where('id', $id)->first();
$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' => $changeType,
'snapshot' => json_encode(['resource' => $resource, 'associations' => $links], JSON_THROW_ON_ERROR),
'actor_user_id' => $actor, 'created_at' => now()]);
}
private function requirementEvidenceEnabled(): bool
{
return Schema::hasColumn('portal_resource_links', 'review_status')
&& Schema::hasTable('migrations')
&& DB::table('migrations')->where('migration', '2026_10_06_200000_add_document_requirement_evidence_links')->exists();
}
/** @return list<string> */
private function resourceLinkColumns(): array
{
$columns = ['target_type', 'target_key', 'relationship', 'applicability', 'condition_text', 'basis_reference'];
if (Schema::hasColumn('portal_resource_links', 'review_status')) {
$columns[] = 'review_status';
}
return $columns;
}
/** @return list<string> */
private function territoryScopeIds(string $id): array
{
$rows = DB::select(<<<'SQL'
WITH RECURSIVE territory_tree AS (
SELECT id FROM geo_locations WHERE id = ? AND deleted_at IS NULL AND data_classification = 'public'
UNION ALL
SELECT child.id FROM geo_locations child
INNER JOIN territory_tree parent ON child.parent_id = parent.id
WHERE child.deleted_at IS NULL AND child.data_classification = 'public'
)
SELECT id FROM territory_tree
SQL, [$id]);
$ids = [];
foreach ($rows as $row) {
if (! is_string($row->id)) {
throw new \RuntimeException('Territory identifier must be a string.');
}
$ids[] = $row->id;
}
return $ids ?: [$id];
}
}
@@ -5,10 +5,12 @@ namespace App\Http\Controllers;
use App\Http\Resources\PublicBusinessOpportunityResource;
use App\Models\ExistingBusiness;
use App\Services\ExistingBusinessDrafts;
use App\Services\InvestmentGeography;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
@@ -18,11 +20,25 @@ class PublicBusinessOpportunityController extends Controller
{
$filters = $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'],
]);
$query = $this->publishedQuery();
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->whereExists(fn ($locations) => $locations->selectRaw('1')->from('existing_business_locations as matching_location')
->whereColumn('matching_location.existing_business_id', 'existing_businesses.id')->where('matching_location.is_public', true)
->where(function ($match) use ($territoryIds): void {
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id'] as $field) {
$match->orWhereIn('matching_location.'.$field, $territoryIds);
}
}));
}
if (! empty($filters['q'])) {
$term = trim($filters['q']);
$query->where(fn (Builder $builder) => $builder->whereLike('existing_businesses.public_title', '%'.$term.'%')
@@ -32,13 +48,16 @@ class PublicBusinessOpportunityController extends Controller
if (! empty($filters['sector'])) {
$query->where('existing_businesses.sector_id', $filters['sector']);
}
if (! empty($filters['modality'])) {
$query->where('existing_businesses.modality', $filters['modality']);
}
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->withQueryString());
if ($request->expectsJson()) {
return $results->response();
}
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters]);
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path]);
}
public function show(Request $request, string $slug): Response|JsonResponse
@@ -49,16 +68,23 @@ class PublicBusinessOpportunityController extends Controller
return $resource->response();
}
return Inertia::render('investment/business-opportunity', ['record' => $resource]);
$returnFilters = $request->query();
return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request),
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
'interestUrl' => '/negocios/'.rawurlencode($slug).'/manifestar-interesse'.($returnFilters === [] ? '' : '?'.http_build_query($returnFilters))]);
}
public function interest(Request $request, string $slug): Response
{
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
$returnFilters = $request->query();
return Inertia::render('investment/business-interest', [
'record' => (new PublicBusinessOpportunityResource($record))->resolve($request),
'modalities' => ExistingBusinessDrafts::MODALITIES,
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
]);
}
@@ -77,7 +103,7 @@ class PublicBusinessOpportunityController extends Controller
return ExistingBusiness::query()->published()->with('sector:id,name,slug')
->leftJoinSub($publicLocations, 'public_location', 'public_location.existing_business_id', '=', 'existing_businesses.id')
->select(['existing_businesses.id', 'existing_businesses.public_slug', 'existing_businesses.public_title',
->select(['existing_businesses.id', 'existing_businesses.public_slug', 'existing_businesses.public_title', 'existing_businesses.modality',
'existing_businesses.activity_code', 'existing_businesses.stage', 'existing_businesses.objective',
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
@@ -5,21 +5,28 @@ namespace App\Http\Controllers;
use App\Services\InvestmentGeography;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class PublicGeographyController extends Controller
{
public function options(Request $request, InvestmentGeography $geography): JsonResponse
{
$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'], 'id' => ['nullable', 'uuid'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
$query = $geography->publicReferences()->where('location_type', $data['type']);
if (! empty($data['id'])) {
$query->where('id', $data['id']);
}
if ($data['type'] !== 'province') {
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']];
$parent = $geography->publicReferences()->where('id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000')->where('location_type', $parentType)->value('id');
$query->where('parent_id', $parent ?? '00000000-0000-0000-0000-000000000000');
}
if (! empty($data['q'])) {
$term = '%'.addcslashes($data['q'], '%_\\').'%';
$query->where(fn ($q) => $q->whereRaw('name ILIKE ?', [$term])->orWhereRaw('code ILIKE ?', [$term])->orWhereRaw('source_code ILIKE ?', [$term]));
$term = '%'.addcslashes(Str::ascii($data['q']), '%_\\').'%';
$query->where(fn ($q) => $q
->whereRaw("translate(lower(name), 'áàâãäåéèêëíìîïóòôõöúùûüçýÿ', 'aaaaaaeeeeiiiiooooouuuucyy') ILIKE ?", [$term])
->orWhereRaw('code ILIKE ?', [$term])
->orWhereRaw('source_code ILIKE ?', [$term]));
}
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
@@ -0,0 +1,95 @@
<?php
namespace App\Http\Controllers;
use App\Services\SimulationTaxParameterResolver;
use App\Services\SimulationTaxRuleExpression;
use App\Services\SimulationTaxRuleGovernance;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
class SimulationTaxRuleGovernanceController extends Controller
{
public function index(Request $request, SimulationTaxRuleGovernance $governance): JsonResponse
{
$filters = $request->validate([
'rule_code' => ['nullable', 'string', 'max:64'],
'component' => ['nullable', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
'scope_key' => ['nullable', 'string', 'max:160'],
'status' => ['nullable', 'in:draft,submitted,reviewed,rejected,approved,published,suspended,archived'],
'per_page' => ['nullable', 'integer', 'between:1,100'],
]);
return response()->json($governance->listing($request->user(), $filters));
}
public function store(Request $request, SimulationTaxRuleGovernance $governance): JsonResponse
{
$rule = $governance->create($request->user(), $this->validatedRule($request));
return response()->json($rule, 201)->header('Location', url('/api/v2/investment/admin/tax-rules/'.$rule->id));
}
public function show(Request $request, SimulationTaxRuleGovernance $governance, string $id): JsonResponse
{
return response()->json($governance->show($request->user(), $id));
}
public function update(Request $request, SimulationTaxRuleGovernance $governance, string $id): JsonResponse
{
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
return response()->json($governance->update($request->user(), $id, (int) $data['version_no'], $this->validatedRule($request)));
}
public function transition(Request $request, SimulationTaxRuleGovernance $governance, string $id, string $action): JsonResponse
{
$data = $request->validate([
'version_no' => ['required', 'integer', 'min:1'],
'evidence' => ['required', 'string', 'min:20', 'max:2000'],
]);
return response()->json($governance->transition($request->user(), $id, (int) $data['version_no'], $action, $data['evidence']));
}
/** @return array<string,mixed> */
private function validatedRule(Request $request): array
{
$data = $request->validate([
'rule_code' => ['required', 'string', 'regex:/^[A-Z0-9][A-Z0-9._-]{2,63}$/'],
'rule_version' => ['required', 'integer', 'min:1'],
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
'scope_key' => ['required', 'string', 'min:2', 'max:160'],
'valid_from' => ['required', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
'legal_source_id' => ['required', 'uuid', 'exists:investment_legal_sources,id'],
'source_sha256' => ['required', 'regex:/^[a-f0-9]{64}$/'],
'rule_definition' => ['required', 'array'],
'parameters' => ['required', 'array'],
'rounding_policy' => ['required', 'array'],
]);
foreach (['rule_definition', 'parameters', 'rounding_policy'] as $key) {
$json = json_encode($data[$key], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
Validator::make(['json' => $json], ['json' => ['max:50000']])->validate();
}
if (($data['rule_definition']['language'] ?? null) === 'investmoz.tax.v1') {
try {
app(SimulationTaxRuleExpression::class)->validate($data['rule_definition']);
} catch (InvalidArgumentException $exception) {
throw ValidationException::withMessages(['rule_definition' => $exception->getMessage()]);
}
try {
app(SimulationTaxParameterResolver::class)->validateParameters($data['parameters']);
} catch (InvalidArgumentException $exception) {
throw ValidationException::withMessages(['parameters' => $exception->getMessage()]);
}
}
return $data;
}
}
@@ -0,0 +1,320 @@
<?php
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\User;
use App\Services\Ai\InvestorGuidance;
use App\Services\InstitutionalLinkMonitor;
use App\Services\InvestmentGeography;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
class VirtualDeskController extends Controller
{
public function catalogue(Request $request, VirtualDesk $desk): JsonResponse|Response
{
$filters = $request->validate(['q' => 'nullable|string|max:120', 'theme' => 'nullable|string|max:80', 'profile' => 'nullable|string|max:100']);
$installed = $desk->installed();
$services = $installed ? DB::table('desk_service_versions')->where('status', 'published')->orderBy('code')->orderByDesc('version')->get()->unique('code')->map(fn ($s) => ['id' => $s->id, 'version' => $s->version, 'definition' => json_decode($s->definition, true), 'source' => json_decode($s->source, true)])->values() : collect();
$services = $services->filter(fn ($s) => (! ($filters['q'] ?? '') || str_contains(mb_strtolower(json_encode($s['definition'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), mb_strtolower($filters['q'])))
&& (! ($filters['theme'] ?? '') || $s['definition']['theme'] === $filters['theme']) && (! ($filters['profile'] ?? '') || $s['definition']['profile'] === $filters['profile']))->values();
$page = max(1, (int) $request->query('page', 1));
$data = ['installed' => $installed, 'services' => $services->slice(($page - 1) * 12, 12)->values(), 'total' => $services->count(), 'page' => $page, 'filters' => $filters,
'prepared' => $installed ? [] : config('virtual-desk.services'), 'source' => config('virtual-desk.source'), 'authenticated' => (bool) $request->user(), 'support' => config('portal.support')];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/catalogue', $data);
}
public function panel(Request $request, VirtualDesk $desk): JsonResponse|Response
{
$actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$cases = DB::table('desk_cases')->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', 'version', 'updated_at']);
$queue = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')->whereNotIn('r.status', ['draft', 'cancelled'])->when(! $actor->can('manage-portal'), fn ($q) => $q->where('r.analyst_id', $actor->id))
->orderByRaw('r.due_at ASC NULLS LAST')->get(['r.id', 'r.protocol', 'r.status', 'r.version', 'r.analyst_id', 'r.due_at', 'c.title']);
$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']),
'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' => \App\Models\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 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']),
'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)))
->orderByRaw('t.due_at ASC NULLS LAST')->get(['t.id', 't.title', 't.status', 't.due_at', 'c.id as case_id', 'c.title as case_title']) : [],
'organizations' => DB::table('organizations')->whereIn('id', $organizations)->get(['id', 'name']), 'manager' => $actor->can('manage-portal'), 'states' => config('virtual-desk.request_states')];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/panel', $data);
}
public function createCase(Request $request, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$case = $desk->createCase($request->user(), $request->all());
return $request->expectsJson() ? response()->json(['id' => $case->id, 'version' => $case->version], 201) : redirect('/balcao-virtual/dossiers/'.$case->id)
->with('success', 'Dossier guardado e disponível para continuar. Próxima ação: escolha um serviço publicado e prepare o rascunho de apoio. Nenhum pedido foi submetido.');
}
public function showCase(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response
{
$case = $desk->case($request->user(), $id);
$owner = $desk->owns($request->user(), $case, false);
$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)],
'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))
->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null,
'owner' => $owner, 'canWrite' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'),
'requests' => DB::table('desk_requests')->where('case_id', $id)->when(! $owner && ! $request->user()->can('manage-portal'), fn ($q) => $q->where('analyst_id', $request->user()->id))->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'service_version_id', 'version']),
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'version', 'definition'])->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'version' => $s->version]),
'documents' => $this->documents($id, $request->user()), 'events' => $this->events($id, $desk, $request->user()), 'stepStates' => config('virtual-desk.step_states'), 'states' => config('virtual-desk.request_states'),
'links' => DB::table('desk_institutional_links')->get()->map(fn ($link) => [...(array) $link, 'monitor' => app(InstitutionalLinkMonitor::class)->status($link)]), 'source' => config('virtual-desk.source'), 'support' => config('portal.support'),
'guidance' => app(InvestorGuidance::class)->installed() ? app(InvestorGuidance::class)->view($request->user(), $id) : null];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/case', $data);
}
/** @return Collection<int,\stdClass> */
private function documents(string $case, User $actor): Collection
{
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case)->whereNull('d.deleted_at')
->when(! app(VirtualDesk::class)->owns($actor, app(VirtualDesk::class)->case($actor, $case), false) && ! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->get(['l.id', 'l.document_id', 'l.request_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.sha256']);
}
/** @return Collection<int,array{id:mixed,request_id:mixed,action:mixed,version:mixed,created_at:mixed,name:mixed,payload:array<string,mixed>}> */
private function events(string $case, VirtualDesk $desk, User $actor): Collection
{
return DB::table('desk_events as e')->join('users as u', 'u.id', '=', 'e.actor_id')->where('e.case_id', $case)
->when(! $desk->owns($actor, $desk->case($actor, $case), false) && ! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->whereNull('e.request_id')->orWhereIn('e.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->orderBy('e.event_order')->get(['e.id', 'e.request_id', 'e.action', 'e.payload', 'e.version', 'e.created_at', 'u.name'])->map(fn ($e) => ['id' => $e->id, 'request_id' => $e->request_id, 'action' => $e->action, 'version' => $e->version, 'created_at' => $e->created_at, 'name' => $e->name, 'payload' => $desk->decode($e->payload)]);
}
public function stage(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$case = $desk->stage($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['version' => $case->version]) : back()->with('success', 'Etapa e evidência registadas.');
}
public function createRequest(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['service_version_id' => 'required|uuid', 'client_key' => 'required|uuid']);
$row = $desk->createRequest($request->user(), $id, $data['service_version_id'], $data['client_key']);
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version], 201) : redirect('/balcao-virtual/pedidos/'.$row->id);
}
public function showRequest(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response
{
$row = $desk->request($request->user(), $id);
$case = $desk->case($request->user(), $row->case_id);
$payload = $desk->decode($row->payload);
$messageKinds = [];
foreach (DB::table('desk_events')->where('request_id', $id)->where('action', 'message_added')->get() as $event) {
$original = $desk->decode($event->payload);
if (isset($original['message_id'], $original['kind'])) {
$messageKinds[$original['message_id']] = $original['kind'];
}
}
$this->auditRead($request, 'desk_requests', $id);
$data = ['countries' => app(\App\Services\CountryCatalogue::class)->all(), '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),
'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,
'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(),
'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),
'kind' => $messageKinds[$m->id] ?? 'historical_unclassified']),
'events' => $this->events($case->id, $desk, $request->user())->filter(fn ($e) => $e['request_id'] === $id)->values(),
'revisions' => DB::table('desk_revisions')->where('request_id', $id)->orderByDesc('version')->get(['version', 'snapshot', 'created_at'])->map(fn ($r) => [...(array) $r, 'snapshot' => $desk->decode($r->snapshot)]),
'payments' => DB::table('desk_payments')->where('request_id', $id)->get(),
'analysts' => $request->user()->can('manage-portal') ? User::orderBy('name')->get(['id', 'name']) : [],
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type'])];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/request', $data);
}
public function save(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$row = $desk->save($request->user(), $id, $request->all(), $request->boolean('submit'));
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version, 'status' => $row->status, 'protocol' => $row->protocol]) : back()->with('success', $request->boolean('submit') ? 'Pedido submetido; protocolo disponível.' : 'Rascunho guardado.');
}
public function transition(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$row = $desk->transition($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['version' => $row->version, 'status' => $row->status]) : back()->with('success', 'Decisão interna registada.');
}
public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
abort_unless($request->user()->can('manage-portal'), 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']);
DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id);
abort_unless((int) $row->version === (int) $data['version'] && ! in_array($row->status, ['draft', 'cancelled', 'closed'], true), 409);
$analyst = User::where('id', $data['analyst_id'])->firstOrFail();
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.');
DB::table('desk_requests')->where('id', $id)->update(['analyst_id' => $analyst->id, 'due_at' => $data['due_at'] ?? null, 'version' => $row->version + 1, 'updated_at' => now()]);
$desk->event($case, $request->user(), 'analyst_assigned', [...$data, 'deadline_basis' => 'internal_target_not_legal_deadline'], DB::table('desk_requests')->where('id', $id)->first());
});
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Analista e meta interna atribuídos.');
}
public function message(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['body' => 'required|string|min:1|max:10000', 'client_key' => 'required|uuid']);
DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409, 'Pedido encerrado.');
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
$existing = DB::table('desk_messages')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('client_key', $data['client_key'])->first();
if ($existing) {
abort_unless(Crypt::decryptString($existing->body) === $data['body'], 409);
return;
}
$messageId = (string) Str::uuid();
DB::table('desk_messages')->insert(['id' => $messageId, 'request_id' => $id, 'actor_id' => $request->user()->id, 'client_key' => $data['client_key'], 'body' => Crypt::encryptString($data['body'])]);
$desk->event($case, $request->user(), 'message_added', ['message_id' => $messageId,
'kind' => $desk->owns($request->user(), $case) ? 'investor_message' : 'responsible_response'], $row);
});
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Mensagem privada guardada.');
}
public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse
{
$row = $desk->request($request->user(), $id);
abort_unless($row->protocol && $row->submitted_snapshot, 404);
$snapshot = $desk->decode($row->submitted_snapshot);
$this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded');
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 json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
}, $row->protocol.'.txt', ['Content-Type' => 'text/plain; charset=utf-8', 'Cache-Control' => 'private, no-store']);
}
public function attach(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['version' => 'required|integer', 'file' => 'nullable|required_without:document_id|file|mimetypes:application/pdf,image/png,image/jpeg,text/plain|max:10240',
'document_id' => 'nullable|required_without:file|uuid', 'category' => 'required|string|max:80', 'stage' => 'nullable|string|max:3', 'request_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'source_reference' => 'required|string|max:3000', 'consent' => 'accepted']);
$key = null;
$newId = null;
try {
DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId) {
$case = $desk->case($request->user(), $id, true, true);
abort_if($case->closed_at, 409, 'Dossier encerrado.');
abort_unless((int) $case->version === (int) $data['version'], 409);
if ($data['stage'] ?? null) {
abort_unless(array_key_exists($data['stage'], config('virtual-desk.steps')), 422);
}
if ($data['request_id'] ?? null) {
$row = $desk->request($request->user(), $data['request_id'], true, true);
abort_unless($row->case_id === $id && in_array($row->status, ['draft', 'returned'], true), 409, 'Anexos de pedidos submetidos são imutáveis; use a devolução para corrigir.');
}
abort_if(DB::table('desk_documents')->where('case_id', $id)->count() >= 100, 422, 'Limite de anexos do dossier atingido.');
if ($request->hasFile('file')) {
$file = $request->file('file');
$hash = hash_file('sha256', $file->getRealPath());
$duplicate = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.sha256', $hash)->first();
if ($duplicate) {
return;
}
$newId = (string) Str::uuid();
$key = $file->storeAs('virtual-desk/'.$id, $newId, 'local');
abort_unless(is_string($key) && $key !== '', 500);
DB::table('documents')->insert(['id' => $newId, 'source_system' => 'virtual-desk', 'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $key,
'sha256' => $hash, 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id, 'status' => 'quarantined', 'data_classification' => 'confidential']);
$documentId = $newId;
} else {
$documentId = $data['document_id'];
$document = DB::table('documents')->where('id', $documentId)->whereNull('deleted_at')->first();
abort_unless($document !== null, 404);
$owned = (int) $document->uploaded_by === $request->user()->id || DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $documentId)->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')->exists();
abort_unless($owned, 403, 'Não há autorização para reutilizar este documento.');
if (DB::table('desk_documents')->where('case_id', $id)->where('document_id', $documentId)->exists()) {
return;
}
}
DB::table('desk_documents')->insert(['id' => (string) Str::uuid(), 'case_id' => $id, 'document_id' => $documentId, 'request_id' => $data['request_id'] ?? null,
'category' => $data['category'], 'stage' => $data['stage'] ?? null, 'valid_until' => $data['valid_until'] ?? null, 'source_reference' => $data['source_reference'], 'linked_by' => $request->user()->id]);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$desk->event(DB::table('desk_cases')->where('id', $id)->first(), $request->user(), 'document_linked', ['document_id' => $documentId, 'source' => $data['source_reference'], 'consent' => true]);
});
} catch (\Throwable $e) {
if ($key) {
Storage::disk('local')->delete($key);
} throw $e;
}
if ($newId) {
ScanDocumentForMalware::dispatch($newId)->afterCommit();
}
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
{
$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']);
if ($doc && $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);
$path = realpath(Storage::disk('local')->path($doc->storage_key));
$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');
return response()->download($path, $doc->file_name, ['Cache-Control' => 'private, no-store']);
}
public function notification(Request $request, int $id): RedirectResponse
{
DB::table('desk_notifications')->where('id', $id)->where('user_id', $request->user()->id)->update(['read_at' => now()]);
return back();
}
public function redirectLink(Request $request, string $id, VirtualDesk $desk): RedirectResponse
{
$case = $desk->case($request->user(), $request->validate(['case_id' => 'required|uuid'])['case_id']);
$link = DB::table('desk_institutional_links')->where('id', $id)->first();
if (! $link || ! app(InstitutionalLinkMonitor::class)->status($link)['available'] || $request->boolean('unavailable')) {
$desk->event($case, $request->user(), 'institutional_link_unavailable', ['link_id' => $id, 'contact' => $link?->contact, 'scope' => 'internal_services_remain_available']);
return redirect('/balcao-virtual/dossiers/'.$case->id)->with('warning', 'Ligação indisponível ou por verificar. Contacto alternativo: '.($link?->contact ?: (config('portal.support.email') ?: 'utilize o pedido de apoio neste dossier')).'. Pode continuar a preparação e os serviços internos.');
}
abort_unless(filter_var($link->url, FILTER_VALIDATE_URL) && parse_url($link->url, PHP_URL_SCHEME) === 'https', 422);
$desk->event($case, $request->user(), 'institutional_referral', ['link_id' => $id, 'version' => $link->version, 'purpose' => $link->purpose]);
// No personal data, case ID or protocol appended to the external URL.
return redirect()->away($link->url)->withHeaders(['Referrer-Policy' => 'no-referrer']);
}
private function auditRead(Request $request, string $type, string $id, string $action = 'consulted'): void
{
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => $type, 'entity_id' => $id, 'actor_user_id' => $request->user()->id, 'action' => $action]);
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers;
use App\Services\VirtualDeskInstallation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class VirtualDeskInstallationController extends Controller
{
public function reviewLink(Request $request, string $id): JsonResponse|RedirectResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'available' => 'required|boolean',
'evidence' => 'required|string|min:10|max:3000', 'contact' => 'nullable|string|max:255']);
DB::transaction(function () use ($request, $id, $data) {
$link = DB::table('desk_institutional_links')->where('id', $id)->lockForUpdate()->first();
abort_unless($link !== null, 404);
abort_unless((int) $link->version === (int) $data['version'], 409);
abort_unless(filter_var($link->url, FILTER_VALIDATE_URL) && parse_url($link->url, PHP_URL_SCHEME) === 'https', 422);
DB::table('desk_institutional_links')->where('id', $id)->update(['status' => $data['available'] ? 'active' : 'unavailable',
'contact' => $data['contact'] ?? $link->contact, 'verified_at' => now(), 'verified_by' => $request->user()->id,
'version' => $link->version + 1, 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_institutional_links', 'entity_id' => $id,
'actor_user_id' => $request->user()->id, 'action' => 'institutional_link_checked',
'after_data' => json_encode(['url' => $link->url, 'prior_version' => $link->version, ...$data, 'scope' => 'availability_only_not_legal_approval'])]);
});
return $request->expectsJson() ? response()->json(['checked' => true]) : back()->with('success', 'Conferência de disponibilidade registada por sete dias.');
}
public function sources(Request $request): JsonResponse|Response
{
$read = function (string $name): array {
$file = storage_path('app/private/virtual-desk/'.$name.'.json');
if (! is_file($file)) {
return [];
}
$bytes = file_get_contents($file);
abort_unless(is_string($bytes), 503);
return json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
};
$inventory = $read('source-inventory');
$forms = $read('form-register');
$data = ['total' => count($inventory), 'attachmentCount' => array_sum(array_map(fn ($item) => count($item['attachments'] ?? []), $inventory)),
'forms' => array_map(fn ($item) => ['identifier' => $item['identifier'], 'sha256' => $item['sha256'], 'size' => $item['size'], 'edition' => $item['edition'],
'provenance' => str_contains($item['path'], DIRECTORY_SEPARATOR.'Scan'.DIRECTORY_SEPARATOR) ? 'Acervo disponibilizado — digitalização' : 'Acervo disponibilizado — fonte de desenho ou template',
'consultation' => $item['consultation'], 'legal_documentary_status' => $item['legal_documentary_status'], 'rule_use' => $item['rule_use'], 'official_confirmation' => $item['official_confirmation'], 'fields_status' => $item['fields_status']], $forms),
'source' => config('virtual-desk.source')];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/sources', $data);
}
public function preview(Request $request, VirtualDeskInstallation $installation): JsonResponse|Response
{
$data = $installation->preview();
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/install', $data);
}
public function apply(Request $request, VirtualDeskInstallation $installation): JsonResponse|RedirectResponse
{
$data = $request->validate(['hash' => 'required|string|size:64', 'confirm' => 'accepted']);
$installation->apply($data['hash'], $request->user());
return $request->expectsJson() ? response()->json(['installed' => true]) : back()->with('success', 'Instalação concluída; serviços ainda exigem publicação explícita.');
}
public function publishService(Request $request): JsonResponse|RedirectResponse
{
$data = $request->validate(['code' => ['required', Rule::in(array_keys(config('virtual-desk.services')))], 'confirm' => 'accepted']);
$row = DB::transaction(function () use ($request, $data) {
DB::select('select pg_advisory_xact_lock(261008, 2)');
$definition = config('virtual-desk.services.'.$data['code']);
$existing = DB::table('desk_service_versions')->where('code', $data['code'])->orderByDesc('version')->first();
if ($existing && $existing->status === 'published' && json_decode($existing->definition, true) === $definition) {
return $existing;
}
$id = (string) Str::uuid();
DB::table('desk_service_versions')->insert(['id' => $id, 'code' => $data['code'], 'version' => ($existing->version ?? 0) + 1, 'status' => 'published',
'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $request->user()->id,
'published_by' => $request->user()->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $request->user()->id,
'action' => 'internal_service_published', 'after_data' => json_encode(['code' => $data['code'], 'nature' => 'digital_preparation_not_official_form'])]);
return DB::table('desk_service_versions')->where('id', $id)->first();
});
return $request->expectsJson() ? response()->json(['id' => $row->id], 201) : back()->with('success', 'Serviço de preparação interna publicado.');
}
}
@@ -0,0 +1,136 @@
<?php
namespace App\Http\Controllers;
use App\Services\Ai\InvestorGuidanceEvidence;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
/** Manual operations use the same requests, documents and encrypted audit history. */
class VirtualDeskOperationsController extends Controller
{
private function result(Request $request): JsonResponse|RedirectResponse
{
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Registo interno guardado; não constitui confirmação de uma instituição externa.');
}
private function reviewer(Request $request, VirtualDesk $desk, \stdClass $case, ?\stdClass $row): void
{
abort_unless(! $desk->owns($request->user(), $case, false) && ($request->user()->can('manage-portal') || ($row && (int) $row->analyst_id === $request->user()->id)), 403);
}
private function cleanDocument(string $caseId, string $documentId, ?string $requestId): \stdClass
{
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.case_id', $caseId)->where('d.id', $documentId)->whereNull('d.deleted_at')
->where(fn ($q) => $q->whereNull('l.request_id')->when($requestId, fn ($p) => $p->orWhere('l.request_id', $requestId)))
->first(['d.*', 'l.id as link_id']);
abort_unless($doc !== null && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento indisponível para conferência: verifique autorização, integridade e análise antimalware.');
$path = realpath(Storage::disk('local')->path($doc->storage_key));
$root = realpath(Storage::disk('local')->path(''));
abort_unless($path && $root && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path) && is_string($hash = hash_file('sha256', $path)) && hash_equals(trim($doc->sha256), $hash), 422, 'O ficheiro original ou a sua integridade não pôde ser confirmado.');
return $doc;
}
public function documentReview(Request $request, string $id, string $document, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'request_id' => 'nullable|uuid', 'outcome' => 'required|in:internal_verified,internal_issue,contradiction_identified', 'what_checked' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000', 'supports' => 'nullable|array|max:4', 'supports.*' => ['string', Rule::in(InvestorGuidanceEvidence::FIELDS)]]);
DB::transaction(function () use ($request, $id, $document, $desk, $data) {
$case = $desk->case($request->user(), $id, false, true);
abort_unless(! $case->closed_at && (int) $case->version === (int) $data['version'], 409);
$link = DB::table('desk_documents')->where('case_id', $id)->where('id', $document)->first();
abort_unless($link !== null, 404);
$requestId = $link->request_id ?: ($data['request_id'] ?? null);
$row = $requestId ? $desk->request($request->user(), $requestId, false, true) : null;
abort_if($row && $row->case_id !== $id, 422);
$this->reviewer($request, $desk, $case, $row);
$doc = $this->cleanDocument($id, $link->document_id, $requestId);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$desk->event(DB::table('desk_cases')->where('id', $id)->firstOrFail(), $request->user(), 'document_reviewed', [
...$data, 'document_id' => $doc->id, 'link_id' => $link->id, 'sha256' => trim($doc->sha256), 'document_version' => (int) $doc->version_no, 'reviewer_id' => $request->user()->id,
'scope' => 'internal_documentary_check_not_official_approval_registration_or_license',
], $row);
});
return $this->result($request);
}
public function payment(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['reference' => 'required|string|max:255', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/', 'numeric', 'gt:0'], 'currency' => 'required|in:MZN,USD,EUR', 'source_reference' => 'required|string|min:3|max:3000', 'document_id' => 'nullable|uuid', 'consent' => 'accepted']);
DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, true, true);
$case = $desk->case($request->user(), $row->case_id);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
if ($data['document_id'] ?? null) {
abort_unless(DB::table('desk_documents')->where('case_id', $case->id)->where('document_id', $data['document_id'])->where(fn ($q) => $q->whereNull('request_id')->orWhere('request_id', $id))->exists(), 422);
}
// References are supplied by the investor; no bank reference or fee is generated.
$existing = DB::table('desk_payments')->where('reference', $data['reference'])->first();
if ($existing) {
$parts = explode('.', (string) $data['amount']);
$amount = (ltrim($parts[0], '0') ?: '0').'.'.str_pad($parts[1] ?? '', 2, '0');
abort_unless($existing->request_id === $id && (string) $existing->amount === $amount && $existing->currency === $data['currency'] && $existing->source_reference === $data['source_reference'] && $existing->document_id === ($data['document_id'] ?? null), 409);
return;
}
$payment = (string) Str::uuid();
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $id, 'reference' => $data['reference'], 'amount' => $data['amount'], 'currency' => $data['currency'], 'source_reference' => $data['source_reference'], 'document_id' => $data['document_id'] ?? null, 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]);
$desk->event($case, $request->user(), 'payment_declared', ['payment_id' => $payment, 'consent' => true, 'scope' => 'manual_declaration_no_bank_confirmation'], $row);
});
return $this->result($request);
}
public function paymentReview(Request $request, string $id, string $payment, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'status' => 'required|in:internal_verified,internal_issue', 'reason' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000']);
DB::transaction(function () use ($request, $id, $payment, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id);
$this->reviewer($request, $desk, $case, $row);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
$record = DB::table('desk_payments')->where('request_id', $id)->where('id', $payment)->lockForUpdate()->first();
abort_unless($record !== null, 404);
abort_unless((int) $record->version === (int) $data['version'], 409);
$doc = null;
if ($data['status'] === 'internal_verified') {
abort_unless($record->document_id, 422, 'A conferência exige um comprovativo autorizado.');
$doc = $this->cleanDocument($case->id, $record->document_id, $id);
}
DB::table('desk_payments')->where('id', $payment)->update(['status' => $data['status'], 'reason' => $data['reason'], 'verified_by' => $request->user()->id, 'version' => $record->version + 1, 'updated_at' => now()]);
$desk->event($case, $request->user(), 'payment_reviewed', [...$data, 'payment_id' => $payment, 'document_id' => $doc?->id, 'sha256' => $doc ? trim($doc->sha256) : null, 'reviewer_id' => $request->user()->id, 'scope' => 'internal_proof_check_no_bank_confirmation'], $row);
});
return $this->result($request);
}
public function communication(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['channel' => 'required|in:phone,email,sms,whatsapp,in_person', 'direction' => 'required|in:received,sent', 'occurred_at' => 'required|date|before_or_equal:now', 'summary' => 'required|string|min:3|max:5000', 'evidence' => 'required|string|min:3|max:3000', 'client_key' => 'required|uuid']);
DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id);
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409);
foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'manual_communication_recorded')->get(['payload']) as $event) {
$saved = $desk->decode($event->payload);
if (($saved['client_key'] ?? null) === $data['client_key']) {
abort_unless(array_intersect_key($saved, $data) === $data, 409);
return;
}
}
$desk->event($case, $request->user(), 'manual_communication_recorded', [...$data, 'scope' => 'manual_record_not_portal_delivery_confirmation'], $row);
});
return $this->result($request);
}
}
@@ -0,0 +1,93 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
final class EnsureSimulationRecoveryCookie
{
public const NAME = 'investmoz_simulation_recovery';
public const DAYS = 30;
public function handle(Request $request, Closure $next): Response
{
$token = $request->cookie(self::NAME);
$issued = ! is_string($token) || strlen($token) < 32 || strlen($token) > 256;
if (! is_string($token) || strlen($token) < 32 || strlen($token) > 256) {
$provided = $request->header('X-Simulation-Token');
$token = is_string($provided) && strlen($provided) >= 32 && strlen($provided) <= 256
? $provided
: Str::random(96);
}
$request->headers->set('X-Simulation-Token', $token);
$response = $next($request);
$forget = $request->isMethod('DELETE')
&& $request->path() === 'api/v1/simulation-drafts/current'
&& $response->getStatusCode() === 204;
$activity = $response->isSuccessful() && $this->isExplicitDraftActivity($request, $response);
$replay = $response->isSuccessful() && $this->isDraftActivityReplay($request, $response);
if (! $issued && ! $activity && ! $replay && ! $forget) {
return $response;
}
// Successful draft writes reset the server deadline to now + DAYS, so
// refresh the cookie by the same duration. Routine reads never refresh it.
$minutes = $forget ? 0 : self::DAYS * 24 * 60;
if ($replay) {
$payload = json_decode((string) $response->getContent(), true);
$expiry = is_array($payload) ? ($payload['expires_at'] ?? null) : null;
if (is_string($expiry)) {
try {
$secondsLeft = Carbon::parse($expiry)->getTimestamp() - now()->getTimestamp();
$minutes = max(1, (int) ceil($secondsLeft / 60));
} catch (\Throwable) {
// Preserve the standard cookie lifetime if the response has no valid deadline.
}
}
}
return $response->withCookie(cookie(
self::NAME,
$forget ? '' : $token,
$minutes,
'/api/v1',
null,
$request->isSecure(),
true,
false,
'lax',
));
}
private function isExplicitDraftActivity(Request $request, Response $response): bool
{
if ($request->isMethod('POST') && $request->path() === 'api/v1/simulation-drafts') {
return $response->getStatusCode() === 201;
}
return ($request->isMethod('PUT') && preg_match('#^api/v1/simulation-drafts/[0-9a-f-]{36}$#i', $request->path()) === 1)
|| ($request->isMethod('POST') && preg_match('#^api/v1/simulation-drafts/[0-9a-f-]{36}/(?:conversions|touch)$#i', $request->path()) === 1);
}
private function isDraftActivityReplay(Request $request, Response $response): bool
{
if (! $request->isMethod('POST') || $response->getStatusCode() !== 200) {
return false;
}
if ($request->path() !== 'api/v1/simulation-drafts'
&& preg_match('#^api/v1/simulation-drafts/[0-9a-f-]{36}/conversions$#i', $request->path()) !== 1) {
return false;
}
$payload = json_decode((string) $response->getContent(), true);
return is_array($payload) && ($payload['data']['replayed'] ?? $payload['replayed'] ?? false) === true;
}
}
@@ -38,10 +38,11 @@ class HandleInertiaRequests extends Middleware
return [
...parent::share($request),
'name' => config('app.name'),
'portalOperator' => config('portal.operator_name'),
'educationEnabled' => (bool) config('education.enabled', false),
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
'flash' => ['success' => fn () => $request->session()->get('success')],
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
'auth' => [
'user' => $request->user(),
'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response;
class PartnershipInstalled
{
/** @param Closure(Request):Response $next */
public function handle(Request $request, Closure $next): Response
{
if (! Schema::hasTable('partnership_interests')) {
if ($request->expectsJson()) {
return response()->json(['code' => 'partnership_installation_pending', 'message' => 'A extensão da Bolsa aguarda aplicação autenticada; o catálogo existente continua disponível.'], 503);
}
return redirect('/parcerias')->with('success', 'A extensão da Bolsa aguarda aplicação pela gestão. As propostas existentes continuam preservadas.');
}
return $next($request);
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use App\Services\VirtualDesk;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class VirtualDeskInstalled
{
/** @param Closure(Request): Response $next */
public function handle(Request $request, Closure $next): Response
{
abort_unless(app(VirtualDesk::class)->installed(), 503, 'Balcão em preparação. A instalação autenticada exige backup/restauro e QA verificados. Os pedidos existentes continuam no painel anterior.');
return $next($request);
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AttachSimulationToDraftRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, list<mixed>> */
public function rules(): array
{
return [
'simulation_id' => ['required', 'uuid'],
'consent_reuse' => ['required', 'accepted'],
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ClaimSimulationFormDraftRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->hasVerifiedEmail() === true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return [
'choice' => ['required', Rule::in(['continue_existing', 'save_as_new'])],
'existing_draft_id' => ['required_if:choice,continue_existing', 'nullable', 'uuid'],
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LinkSimulationDraftBusinessRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->hasVerifiedEmail() === true;
}
/** @return array<string, mixed> */
public function rules(): array
{
return ['business_id' => ['required', 'uuid']];
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
class ResolveSimulationTaxParametersRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string,list<mixed>> */
public function rules(): array
{
return [
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
'period_start' => ['required', 'date_format:Y-m-d'],
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
'context' => ['sometimes', 'array:fiscal_periodicity,fiscal_operation,fiscal_residency_assessment,fiscal_residency_country,fiscal_income_category,fiscal_establishments,fiscal_documentation,fiscal_customs_code,fiscal_vat_refund_state'],
'context.*' => ['string', 'max:160'],
];
}
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator): void {
$start = $this->parseEffectiveDate('period_start');
$end = $this->parseEffectiveDate('period_end');
if ($start !== null && $end !== null && ($start->diff($end)->days ?? 0) > 365) {
$validator->errors()->add('period_end', 'O período de resolução não pode exceder 366 dias.');
}
});
}
private function parseEffectiveDate(string $key): ?\DateTimeImmutable
{
$value = $this->input($key);
if (! is_string($value) || preg_match('/^\d{4}-\d{2}-\d{2}$/D', $value) !== 1) {
return null;
}
$date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value);
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
}
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use App\Services\InvestmentGeography;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
class StoreLandAssistanceCaseRequest extends FormRequest
{
/** @return array<string, mixed> */
public function payload(): array
{
$payload = $this->validated('payload');
return is_array($payload) ? $payload : [];
}
public function authorize(): bool
{
return true;
}
/** @return array<string,list<mixed>> */
public function rules(): array
{
return [
'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'],
'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.project_reference' => ['nullable', 'string', 'max:160'],
'payload.applicant_category' => ['nullable', 'in:individual,entity,community,other'],
'payload.full_name' => ['nullable', 'string', 'max:150'],
'payload.contact_person' => ['nullable', 'string', 'max:200'],
'payload.email' => ['nullable', 'email:rfc', 'max:150'],
'payload.phone' => ['nullable', 'string', 'max:30'],
'payload.preferred_contact' => ['nullable', 'in:email,phone,any'],
'payload.country' => ['nullable', 'string', 'max:100'],
'payload.nationality' => ['nullable', 'string', 'max:120'],
'payload.representative_name' => ['nullable', 'string', 'max:200'],
'payload.representative_role' => ['nullable', 'string', 'max:120'],
'payload.representation_basis' => ['nullable', 'string', 'max:500'],
'payload.nuit' => ['nullable', 'string', 'max:40'],
'payload.constitution_or_residency_note' => ['nullable', 'string', 'max:1000'],
'payload.area_status' => ['nullable', 'in:identified,seeking,location_support,unknown'],
'payload.parcels' => ['nullable', 'array', 'max:10'],
'payload.parcels.*' => ['array:province_id,district_id,admin_post_id,locality_id,place_description,area,area_unit,cadastral_reference,coordinates,geometry_confidence'],
'payload.parcels.*.province_id' => ['nullable', 'uuid', 'exists:geo_locations,id'],
'payload.parcels.*.district_id' => ['nullable', 'uuid', 'exists:geo_locations,id'],
'payload.parcels.*.admin_post_id' => ['nullable', 'uuid', 'exists:geo_locations,id'],
'payload.parcels.*.locality_id' => ['nullable', 'uuid', 'exists:geo_locations,id'],
'payload.parcels.*.place_description' => ['nullable', 'string', 'max:1000'],
'payload.parcels.*.area' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
'payload.parcels.*.area_unit' => ['nullable', 'in:m2,hectares,other,unknown'],
'payload.parcels.*.cadastral_reference' => ['nullable', 'string', 'max:160'],
'payload.parcels.*.coordinates' => ['nullable', 'string', 'max:500'],
'payload.parcels.*.geometry_confidence' => ['nullable', 'in:declared,approximate,confirmed_by_authority,unknown'],
'payload.purpose' => ['nullable', 'string', 'max:1000'],
'payload.activity' => ['nullable', 'string', 'max:500'],
'payload.known_occupants' => ['nullable', 'in:yes,no_as_far_as_known,unknown'],
'payload.occupant_description' => ['nullable', 'string', 'max:2000'],
'payload.known_improvements' => ['nullable', 'in:yes,unknown,none_identified'],
'payload.improvements_description' => ['nullable', 'string', 'max:2000'],
'payload.prior_right_status' => ['nullable', 'in:yes,unknown,no_documents'],
'payload.prior_right_description' => ['nullable', 'string', 'max:2000'],
'payload.conflict_status' => ['nullable', 'in:yes,unknown,no_knowledge'],
'payload.conflict_description' => ['nullable', 'string', 'max:2000'],
'payload.official_process' => ['nullable', 'array:official_reference,receiving_entity,presented_at,reported_status,pending_items,proof_available'],
'payload.official_process.official_reference' => ['nullable', 'string', 'max:160'],
'payload.official_process.receiving_entity' => ['nullable', 'string', 'max:200'],
'payload.official_process.presented_at' => ['nullable', 'date_format:Y-m-d'],
'payload.official_process.reported_status' => ['nullable', 'string', 'max:1000'],
'payload.official_process.pending_items' => ['nullable', 'string', 'max:2000'],
'payload.official_process.proof_available' => ['nullable', 'in:yes,no,unknown'],
'payload.attachments_to_follow' => ['nullable', 'array', 'max:10'],
'payload.attachments_to_follow.*' => ['string', 'in:sketch,prior_right,exploration_plan,official_receipt,consultation_minutes,photo,other'],
'payload.exploration_plan' => ['nullable', 'array:activity_rows,notes'],
'payload.exploration_plan.activity_rows' => ['nullable', 'array', 'max:30'],
'payload.exploration_plan.activity_rows.*' => ['array:period,activity,area,area_unit,stage,targets,structures,investment'],
'payload.exploration_plan.activity_rows.*.period' => ['nullable', 'string', 'max:80'],
'payload.exploration_plan.activity_rows.*.activity' => ['nullable', 'string', 'max:300'],
'payload.exploration_plan.activity_rows.*.area' => ['nullable', 'numeric', 'min:0'],
'payload.exploration_plan.activity_rows.*.area_unit' => ['nullable', 'in:m2,hectares,other,unknown'],
'payload.exploration_plan.activity_rows.*.stage' => ['nullable', 'in:existing,planned,unknown'],
'payload.exploration_plan.activity_rows.*.targets' => ['nullable', 'string', 'max:1000'],
'payload.exploration_plan.activity_rows.*.structures' => ['nullable', 'string', 'max:1000'],
'payload.exploration_plan.activity_rows.*.investment' => ['nullable', 'numeric', 'min:0'],
'payload.exploration_plan.notes' => ['nullable', 'string', 'max:2000'],
'payload.consultation' => ['nullable', 'array:status,community,location,date,facilitators,language,participants,interventions,opposition,agreements,minutes_reference,opinions_received'],
'payload.consultation.status' => ['nullable', 'in:not_started,preparing,reported_completed,unknown'],
'payload.consultation.community' => ['nullable', 'string', 'max:200'],
'payload.consultation.location' => ['nullable', 'string', 'max:500'],
'payload.consultation.date' => ['nullable', 'date_format:Y-m-d'],
'payload.consultation.facilitators' => ['nullable', 'string', 'max:1000'],
'payload.consultation.language' => ['nullable', 'string', 'max:100'],
'payload.consultation.participants' => ['nullable', 'array', 'max:200'],
'payload.consultation.participants.*' => ['array:name,role'],
'payload.consultation.participants.*.name' => ['nullable', 'string', 'max:200'],
'payload.consultation.participants.*.role' => ['nullable', 'string', 'max:120'],
'payload.consultation.interventions' => ['nullable', 'string', 'max:4000'],
'payload.consultation.opposition' => ['nullable', 'string', 'max:2000'],
'payload.consultation.agreements' => ['nullable', 'string', 'max:2000'],
'payload.consultation.minutes_reference' => ['nullable', 'string', 'max:500'],
'payload.consultation.opinions_received' => ['nullable', 'string', 'max:2000'],
'payload.additional_information' => ['nullable', 'string', 'max:4000'],
'payload.truth_declaration' => ['nullable', 'boolean'],
'payload.contact_consent' => ['nullable', 'boolean'],
];
}
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator): void {
$payload = $this->input('payload', []);
if (is_array($payload) && is_array($payload['parcels'] ?? null)) {
$geography = app(InvestmentGeography::class);
$levels = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
foreach ($payload['parcels'] as $index => $parcel) {
if (! is_array($parcel)) {
continue;
}
$parent = null;
$gap = false;
foreach ($levels as $field => $expectedType) {
$id = $parcel[$field] ?? null;
if (! is_string($id) || $id === '') {
$gap = true;
continue;
}
$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)) {
$validator->errors()->add("payload.parcels.$index.$field", 'A hierarquia territorial declarada é incoerente ou não está publicada.');
$gap = true;
}
$parent = (string) $id;
}
}
}
if (! $this->routeIs('land-assistance.support')) {
return;
}
if (! is_array($payload)) {
return;
}
foreach (['support_kind', 'request_description', 'applicant_category', 'full_name', 'preferred_contact', 'area_status', 'purpose'] as $required) {
if (! isset($payload[$required]) || trim((string) $payload[$required]) === '') {
$validator->errors()->add('payload.'.$required, 'Este campo é necessário para solicitar apoio.');
}
}
if (empty($payload['email']) && empty($payload['phone'])) {
$validator->errors()->add('payload.email', 'Indique pelo menos um contacto utilizável.');
}
if (! empty($payload['email']) && ! filter_var($payload['email'], FILTER_VALIDATE_EMAIL)) {
$validator->errors()->add('payload.email', 'Indique um email válido para registar o pedido no balcão de apoio.');
}
if (($payload['applicant_category'] ?? null) === 'community' && empty($payload['contact_person'])) {
$validator->errors()->add('payload.contact_person', 'Indique um contacto para a comunidade, se conhecido.');
}
if (($payload['applicant_category'] ?? null) === 'entity' && empty($payload['representative_role'])) {
$validator->errors()->add('payload.representative_role', 'Indique a qualidade da representação conhecida.');
}
if (empty($payload['contact_consent'])) {
$validator->errors()->add('payload.contact_consent', 'A autorização de contacto é necessária para solicitar apoio.');
}
if (empty($payload['truth_declaration'])) {
$validator->errors()->add('payload.truth_declaration', 'Confirme que as respostas refletem a informação de que dispõe.');
}
});
}
}
@@ -3,11 +3,24 @@
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;
class StoreSimulationFormDraftRequest extends FormRequest
{
/** @return array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>} */
public function snapshots(): array
{
$validated = $this->validated();
$personal = $validated['personal_snapshot'] ?? null;
$economic = $validated['economic_snapshot'] ?? null;
if (! is_array($personal) || ! is_array($economic)) {
throw new \LogicException('Validated simulation snapshots must be arrays.');
}
return ['personal_snapshot' => $personal, 'economic_snapshot' => $economic];
}
public function authorize(): bool
{
return true;
@@ -17,13 +30,15 @@ class StoreSimulationFormDraftRequest extends FormRequest
public function rules(): array
{
$personal = [
'person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'nuit',
'person_type', 'investor_origin', 'tax_residency_country', 'fiscal_residency_country', 'entity_stage', 'legal_form', 'nuit',
'investor_profile_id', 'profile_confirmation', 'legal_name', 'commercial_name', 'registration_number',
'representative_name', 'representative_capacity', 'email', 'phone', 'address', 'contact_country', 'selection_labels',
'contact_province', 'contact_district', 'preferred_channel',
];
$economic = [
'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'selection_labels', 'project_type',
'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'location_rationale', 'project_risk_responses_snapshot', 'project_questionnaire_version',
'customer_validation_status', 'cost_estimate_status', 'location_assessment_status', 'funding_status', 'receivables_timing_status',
'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date',
'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id',
'site_known', 'latitude', 'longitude', 'area_required', 'area_unit', 'special_zone_id', 'land_status',
@@ -31,9 +46,12 @@ class StoreSimulationFormDraftRequest extends FormRequest
'grants', 'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit',
'financing_term_months', 'funds_origin_countries', 'direct_jobs', 'indirect_jobs', 'national_jobs',
'foreign_jobs', 'skills_needed', 'local_content_percentage', 'exports_value', 'import_substitution_value',
'environmental_category', 'community_benefits', 'tax_calculation', 'base', 'rate', 'reduction',
'environmental_category', 'community_benefits', 'tax_calculation', 'fiscal_scenario_mode', 'base', 'rate', 'reduction',
'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs', 'non_deductible_costs',
'carried_losses', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'reference_date',
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment',
'fiscal_operation', 'fiscal_activity', 'fiscal_establishments', 'fiscal_documentation',
'fiscal_customs_code', 'fiscal_vat_refund_state',
'offer_or_demand', 'opportunity_type', 'opportunity_type_other', 'opportunity_description',
'opportunity_value', 'opportunity_currency', 'opportunity_conditions', 'opportunity_deadline',
'required_documents', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration', 'reuse_simulation',
@@ -42,9 +60,24 @@ class StoreSimulationFormDraftRequest extends FormRequest
];
$rules = [
'personal_snapshot' => ['required', 'array:'.implode(',', $personal)],
// Anonymous clients must send an empty snapshot; `required` rejects
// an empty array before the privacy policy can enforce that shape.
'personal_snapshot' => ['present', 'array:'.implode(',', $personal)],
'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.journey_type' => ['nullable', 'in:personal,small_business,company,investor'],
'economic_snapshot.detail_level' => ['nullable', 'in:simple,advanced'],
'economic_snapshot.business_plan_snapshot' => ['nullable', 'string', 'max:60000'],
'economic_snapshot.financial_tools_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_team_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_execution_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_risk_responses_snapshot' => ['nullable', 'string', 'max:30000'],
'economic_snapshot.project_questionnaire_version' => ['nullable', 'string', 'max:100'],
'economic_snapshot.customer_validation_status' => ['nullable', 'in:yes,no,partial,unknown,not_applicable'],
'economic_snapshot.cost_estimate_status' => ['nullable', 'in:yes,no,partial,unknown,not_applicable'],
'economic_snapshot.location_assessment_status' => ['nullable', 'in:yes,no,partial,unknown,not_applicable'],
'economic_snapshot.receivables_timing_status' => ['nullable', 'in:yes,no,partial,unknown,not_applicable'],
'economic_snapshot.funding_status' => ['nullable', 'in:confirmed,in_process,not_started,unknown,not_applicable'],
'economic_snapshot.manifestation_type' => ['nullable', 'in:investment,business'],
'economic_snapshot.preferred_language' => ['nullable', 'in:pt-MZ,en'],
'economic_snapshot.project_type' => ['nullable', 'in:new,expansion,acquisition,partnership,concession,supplier,buyer,other'],
@@ -55,6 +88,19 @@ class StoreSimulationFormDraftRequest extends FormRequest
'economic_snapshot.confidentiality' => ['nullable', 'in:public,registered_users,restricted,confidential'],
'economic_snapshot.site_known' => ['nullable', 'in:yes,no'],
'economic_snapshot.tax_calculation' => ['nullable', 'in:yes,no'],
'economic_snapshot.fiscal_scenario_mode' => ['nullable', 'in:approved_parameters,custom_planning,no_calculation'],
'economic_snapshot.fiscal_period' => ['nullable', 'integer', 'in:'.implode(',', range(2000, today()->year + 1))],
'economic_snapshot.fiscal_periodicity' => ['nullable', 'in:monthly,quarterly,annual,one_off,unknown'],
'economic_snapshot.fiscal_month' => ['nullable', 'regex:/^(0[1-9]|1[0-2])$/'],
'economic_snapshot.fiscal_quarter' => ['nullable', 'in:Q1,Q2,Q3,Q4'],
'economic_snapshot.fiscal_reference_date' => ['nullable', 'date_format:Y-m-d'],
'economic_snapshot.irps_salary_view' => ['nullable', 'in:monthly_net_estimate,monthly_withholding,annual_assessment'],
'economic_snapshot.fiscal_component' => ['nullable', 'in:irpc,iva,ispc,irps,inss,withholding,customs_ice'],
'economic_snapshot.fiscal_income_category' => ['nullable', 'in:employment,rental,digital,capital_gain,business,other,unknown'],
'economic_snapshot.fiscal_residency_assessment' => ['nullable', 'in:self_reported_resident,self_reported_non_resident,unknown'],
'economic_snapshot.fiscal_operation' => ['nullable', 'in:domestic,non_resident,import,export,refund,other,unknown'],
'economic_snapshot.fiscal_documentation' => ['nullable', 'in:documented,partly_documented,not_documented,unknown'],
'economic_snapshot.fiscal_vat_refund_state' => ['nullable', 'in:estimate_only,request_filed,recognized,received,unknown'],
'economic_snapshot.publish_requested' => ['nullable', 'in:yes,no'],
'economic_snapshot.terms_accepted' => ['nullable', 'in:yes,no'],
'economic_snapshot.truth_declaration' => ['nullable', 'in:yes,no'],
@@ -85,17 +131,21 @@ class StoreSimulationFormDraftRequest extends FormRequest
foreach (['direct_jobs', 'indirect_jobs', 'national_jobs', 'foreign_jobs', 'financing_term_months', 'project_duration_years'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'integer', 'min:0'];
}
$rules['economic_snapshot.fiscal_establishments'] = ['nullable', 'integer', 'min:1'];
foreach (['fiscal_activity', 'fiscal_customs_code'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:300'];
}
foreach (['infrastructure_needs', 'funds_origin_countries', 'required_documents'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'array', 'max:100'];
$rules['economic_snapshot.'.$field.'.*'] = ['nullable', 'string', 'max:3000'];
}
$rules['economic_snapshot.infrastructure_needs.*'] = ['nullable', 'in:energia,água,estrada,porto,ferrovia,telecomunicações,armazenamento'];
$rules['economic_snapshot.infrastructure_needs.*'] = ['nullable', 'in:energia,água,estrada,porto,ferrovia,telecomunicações,armazenamento,customers,raw_materials,workers,facilities,costs,legal_requirements'];
$rules['economic_snapshot.required_documents.*'] = ['nullable', 'in:identity_document,company_registration,nuit_certificate,company_profile,business_plan,feasibility_study,proof_of_funds,special_zone_certificate,licence,site_map'];
foreach (['skills_needed', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'opportunity_conditions'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
}
$rules['economic_snapshot.selection_labels'] = ['nullable', 'array'];
foreach (['project_summary', 'opportunity_description', 'products_services', 'community_benefits'] as $field) {
foreach (['project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'opportunity_description', 'products_services', 'community_benefits', 'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'location_rationale'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
}
$rules['personal_snapshot.email'] = ['nullable', 'email:rfc', 'max:254'];
@@ -114,7 +164,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id'] as $field) {
$rules['economic_snapshot.'.$field] = ['nullable', 'uuid', 'exists:geo_locations,id'];
}
foreach (['person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'commercial_name',
foreach (['person_type', 'investor_origin', 'tax_residency_country', 'fiscal_residency_country', 'entity_stage', 'legal_form', 'commercial_name',
'registration_number', 'representative_name', 'representative_capacity', 'phone', 'address', 'contact_country',
'contact_province', 'contact_district', 'preferred_channel'] as $field) {
$rules['personal_snapshot.'.$field] = ['nullable', 'string', 'max:3000'];
@@ -131,14 +181,100 @@ class StoreSimulationFormDraftRequest extends FormRequest
return;
}
foreach ([
'project_team_snapshot' => [
'keys' => ['competency', 'state', 'action', 'estimated_cost', 'due_date'],
'states' => ['available', 'gap', 'unknown'],
'amounts' => ['estimated_cost'],
],
'project_execution_snapshot' => [
'keys' => ['title', 'due_date', 'status', 'planned_amount', 'actual_amount'],
'states' => ['planned', 'in_progress', 'completed'],
'amounts' => ['planned_amount', 'actual_amount'],
],
] as $field => $schema) {
if (! isset($economic[$field]) || $economic[$field] === '') {
continue;
}
$rows = json_decode((string) $economic[$field], true);
$valid = is_array($rows) && count($rows) <= 100;
foreach (is_array($rows) ? $rows : [] as $row) {
if (! is_array($row) || array_diff(array_keys($row), $schema['keys']) !== []
|| array_diff($schema['keys'], array_keys($row)) !== []
|| array_filter($row, fn ($value) => ! is_string($value) || mb_strlen($value) > 500) !== []) {
$valid = false;
break;
}
$stateKey = $field === 'project_team_snapshot' ? 'state' : 'status';
if (! in_array($row[$stateKey], $schema['states'], true)) {
$valid = false;
break;
}
foreach ($schema['amounts'] as $amountKey) {
if ($row[$amountKey] !== '' && (! is_numeric($row[$amountKey]) || (float) $row[$amountKey] < 0)) {
$valid = false;
}
}
foreach (['due_date'] as $dateKey) {
if ($row[$dateKey] !== '' && ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $row[$dateKey])) {
$valid = false;
}
}
}
if (! $valid) {
$validator->errors()->add('economic_snapshot.'.$field, 'O plano estruturado contém linhas ou valores inválidos.');
}
}
if (isset($economic['project_risk_responses_snapshot']) && $economic['project_risk_responses_snapshot'] !== '') {
$responses = json_decode((string) $economic['project_risk_responses_snapshot'], true);
$validResponses = is_array($responses) && array_is_list($responses) && count($responses) <= 30;
foreach (is_array($responses) ? $responses : [] as $response) {
if (! is_array($response)
|| array_diff(array_keys($response), ['risk_id', 'action', 'owner', 'estimated_cost', 'due_date']) !== []
|| array_diff(['risk_id', 'action', 'owner', 'estimated_cost', 'due_date'], array_keys($response)) !== []
|| array_filter($response, fn ($value) => ! is_string($value) || mb_strlen($value) > 500) !== []
|| ! preg_match('/^[a-z0-9-]{1,80}$/', $response['risk_id'])
|| ($response['estimated_cost'] !== '' && (! is_numeric($response['estimated_cost']) || (float) $response['estimated_cost'] < 0))
|| ($response['due_date'] !== '' && ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $response['due_date']))) {
$validResponses = false;
break;
}
}
if (! $validResponses) {
$validator->errors()->add('economic_snapshot.project_risk_responses_snapshot', 'As respostas planeadas para lacunas ou riscos não são válidas.');
}
}
if (isset($economic['fiscal_scenario_mode'])) {
$custom = $economic['fiscal_scenario_mode'] === 'custom_planning';
$providedCount = 0;
foreach (['base', 'rate', 'reduction'] as $field) {
$present = isset($economic[$field]) && $economic[$field] !== '';
$providedCount += $present ? 1 : 0;
if (! $custom && $present) {
$validator->errors()->add('economic_snapshot.'.$field, 'Valores hipotéticos só podem ser enviados no cenário personalizado.');
}
}
if ($custom && $providedCount > 0 && $providedCount < 3) {
foreach (['base', 'rate', 'reduction'] as $field) {
if (! isset($economic[$field]) || $economic[$field] === '') {
$validator->errors()->add('economic_snapshot.'.$field, 'Preencha todos os pressupostos se começar um cenário personalizado.');
}
}
}
}
$allowedLabels = [
'economic_snapshot.selection_labels' => ['purpose', 'manifestation_type', 'preferred_language', 'project_type', 'sector_id', 'activity_id',
'economic_snapshot.selection_labels' => ['journey_type', 'detail_level', 'purpose', 'manifestation_type', 'preferred_language', 'project_type', 'maturity_stage', 'sector_id', 'activity_id',
'province_id', 'district_id', 'admin_post_id', 'locality_id', 'site_known', 'land_status', 'infrastructure_needs',
'area_unit', 'required_documents', 'opportunity_currency',
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'offer_or_demand',
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'fiscal_scenario_mode', 'offer_or_demand',
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged'],
'personal_snapshot.selection_labels' => ['person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'preferred_channel'],
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment', 'fiscal_operation',
'fiscal_documentation', 'fiscal_vat_refund_state'],
'personal_snapshot.selection_labels' => ['person_type', 'investor_origin', 'tax_residency_country', 'fiscal_residency_country', 'entity_stage', 'legal_form', 'preferred_channel'],
];
foreach ($allowedLabels as $path => $allowedFields) {
$snapshot = str_starts_with($path, 'personal_') ? $this->input('personal_snapshot.selection_labels', []) : ($economic['selection_labels'] ?? []);
@@ -11,21 +11,22 @@ class PublicBusinessOpportunityResource extends JsonResource
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'slug' => $this->public_slug,
'title' => $this->public_title,
'activity_code' => $this->activity_code,
'stage' => $this->stage,
'objective' => $this->objective,
'currency' => $this->currency,
'amount_min' => $this->amount_min,
'amount_max' => $this->amount_max,
'available_percentage' => $this->available_percentage,
'published_at' => $this->published_at,
'sector' => $this->whenLoaded('sector', fn () => $this->sector?->only(['name', 'slug'])),
'province' => $this->province,
'district' => $this->district,
'locality' => $this->locality,
'id' => data_get($this->resource, 'id'),
'slug' => data_get($this->resource, 'public_slug'),
'title' => data_get($this->resource, 'public_title'),
'modality' => data_get($this->resource, 'modality'),
'activity_code' => data_get($this->resource, 'activity_code'),
'stage' => data_get($this->resource, 'stage'),
'objective' => data_get($this->resource, 'objective'),
'currency' => data_get($this->resource, 'currency'),
'amount_min' => data_get($this->resource, 'amount_min'),
'amount_max' => data_get($this->resource, 'amount_max'),
'available_percentage' => data_get($this->resource, 'available_percentage'),
'published_at' => data_get($this->resource, 'published_at'),
'sector' => $this->whenLoaded('sector', fn () => data_get($this->resource, 'sector')?->only(['name', 'slug'])),
'province' => $this->resource->getAttribute('province'),
'district' => $this->resource->getAttribute('district'),
'locality' => $this->resource->getAttribute('locality'),
];
}
}
+22 -4
View File
@@ -63,13 +63,31 @@ class RunSimulation implements ShouldQueue
}
$input = json_decode($scenario->parameters, true, flags: JSON_THROW_ON_ERROR);
$row = DB::selectOne('select (CAST(? AS numeric) * CAST(? AS numeric) / 100 * (1 - CAST(? AS numeric) / 100))::text as value', [$input['base'], $input['rate'], $input['reduction']]);
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'indicative_total' => $row->value,
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-tax-arithmetic-v1'];
$resultId = (string) Str::uuid();
$engineVersion = 'portal-arithmetic-v1+simulation-v'.$simulation->version_no;
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'scenario_kind' => 'custom_planning', 'indicative_total' => $row->value,
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
'contract_version' => 1,
'context' => [
'reference_date' => substr((string) $scenario->created_at, 0, 10),
'currency' => null,
'currency_fraction_digits' => null,
'scenario_id' => (string) $scenario->id,
'scenario_version' => (int) $scenario->version_no,
'engine_version' => $engineVersion,
'ruleset_version' => null,
],
'result' => [
'status' => 'calculated',
'value' => (string) $row->value,
'unit' => null,
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
'missing_inputs' => [],
'source_ids' => [],
]];
$json = json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
$resultHash = hash('sha256', $canonicalResult);
$resultId = (string) Str::uuid();
$engineVersion = 'portal-tax-arithmetic-v1+simulation-v'.$simulation->version_no;
DB::table('simulation_results')->insert([
'id' => $resultId, 'simulation_id' => $simulation->id, 'scenario_id' => $scenario->id, 'engine_version' => $engineVersion,
'result_snapshot' => $json, 'result_sha256' => $resultHash, 'created_at' => now(),
+172
View File
@@ -0,0 +1,172 @@
<?php
namespace App\Jobs;
use App\Services\Malware\MalwareScanner;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;
class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 150;
public int $uniqueFor = 600;
public function __construct(public readonly string $documentId) {}
public function uniqueId(): string
{
return $this->documentId;
}
/** @return list<int> */
public function backoff(): array
{
return [15, 60];
}
public function handle(MalwareScanner $scanner): void
{
$document = DB::transaction(function (): ?\stdClass {
$row = DB::table('documents')->where('id', $this->documentId)->lockForUpdate()->first();
if (! $row || $row->status === 'deleted' || $row->deleted_at !== null) {
return null;
}
if ($row->malware_scan_status === 'clean' && hash_equals(trim($row->sha256), (string) $row->malware_scanned_sha256)) {
return null;
}
if ($row->malware_scan_status === 'infected') {
return null;
}
DB::table('documents')->where('id', $this->documentId)->update([
'status' => 'quarantined', 'malware_scan_status' => 'scanning', 'malware_failure_reason' => null,
'malware_scan_attempts' => DB::raw('malware_scan_attempts + 1'), 'updated_at' => now(),
]);
return $row;
});
if (! $document) {
return;
}
$startedAt = now();
$disk = Storage::disk('local');
$root = $disk->path('');
$path = $disk->path($document->storage_key);
$temporary = null;
try {
if (($document->storage_encryption ?? null) === 'laravel') {
$temporary = tempnam($root, 'scan-private-');
if ($temporary === false) {
throw new \RuntimeException('Private scan workspace unavailable');
}
chmod($temporary, 0600);
file_put_contents($temporary, Crypt::decryptString($disk->get($document->storage_key)));
$path = $temporary;
}
$beforeHash = $this->fileHash($path);
if ($beforeHash === null || ! hash_equals(trim($document->sha256), $beforeHash)) {
$this->record($document, [
'result' => 'inconclusive', 'reason_code' => 'file_hash_mismatch', 'engine' => 'ClamAV',
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => 0, 'detail' => null,
], $startedAt, 'inconclusive');
return;
}
$result = $scanner->scan($path, (int) ($document->size_bytes ?? filesize($path)), $root);
$afterHash = $this->fileHash($path);
if ($afterHash === null || ! hash_equals(trim($document->sha256), $afterHash)) {
$result['result'] = 'inconclusive';
$result['reason_code'] = 'file_changed_during_scan';
$result['detail'] = null;
}
$result['file_sha256'] = $afterHash;
$this->record($document, $result, $startedAt, $result['result']);
} finally {
if (is_string($temporary) && is_file($temporary)) {
unlink($temporary);
}
}
}
public function failed(Throwable $exception): void
{
$document = DB::table('documents')->where('id', $this->documentId)->first();
if (! $document || $document->status === 'deleted' || $document->deleted_at !== null) {
return;
}
$this->record($document, [
'result' => 'failed', 'reason_code' => 'scanner_unavailable_after_retries', 'engine' => 'ClamAV',
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => null, 'detail' => null,
], now(), 'failed');
}
private function fileHash(string $path): ?string
{
// Re-read the filesystem after the scanner; files may change meanwhile.
clearstatcache(true, $path);
$hash = is_file($path) ? hash_file('sha256', $path) : false;
return is_string($hash) ? $hash : null;
}
/** @param array<string,mixed> $result */
private function record(\stdClass $document, array $result, \DateTimeInterface $startedAt, string $state): void
{
DB::transaction(function () use ($document, $result, $startedAt, $state): void {
$locked = DB::table('documents')->where('id', $this->documentId)->lockForUpdate()->first();
if (! $locked || $locked->status === 'deleted' || $locked->deleted_at !== null) {
return;
}
$sameBytes = hash_equals(trim($document->sha256), trim((string) $locked->sha256));
$finalState = $sameBytes ? $state : 'inconclusive';
$reason = $sameBytes ? $result['reason_code'] : 'document_record_changed_during_scan';
$release = $finalState === 'clean' && hash_equals(trim($locked->sha256), trim((string) ($result['file_sha256'] ?? '')));
$finishedAt = now();
$scanId = (string) Str::uuid();
DB::table('documents')->where('id', $this->documentId)->update([
'status' => $release ? 'active' : 'quarantined',
'malware_scan_status' => $finalState,
'malware_scanned_sha256' => $sameBytes
&& hash_equals(trim($locked->sha256), trim((string) ($result['file_sha256'] ?? '')))
? trim($locked->sha256)
: null,
'malware_engine' => $result['engine'] ?? 'ClamAV',
'malware_engine_version' => $result['engine_version'] ?? 'unknown',
'malware_signatures_at' => $result['signatures_at'] ?? null,
'malware_scanned_at' => $finishedAt,
'malware_failure_reason' => $reason,
'updated_at' => $finishedAt,
]);
DB::table('document_malware_scans')->insert([
'id' => $scanId, 'document_id' => $this->documentId, 'file_sha256' => trim($locked->sha256),
'result' => $finalState, 'reason_code' => $reason,
'engine' => $result['engine'] ?? 'ClamAV', 'engine_version' => $result['engine_version'] ?? 'unknown',
'signatures_at' => $result['signatures_at'] ?? null, 'started_at' => $startedAt,
'finished_at' => $finishedAt, 'duration_ms' => $result['duration_ms'] ?? null,
'file_size_bytes' => $locked->size_bytes ?? null, 'created_at' => $finishedAt, 'updated_at' => $finishedAt,
]);
});
}
}
+1
View File
@@ -2,4 +2,5 @@
namespace App\Models;
/** @property int $version_no */
class ClusterProject extends DomainRecord {}
+6 -1
View File
@@ -2,7 +2,12 @@
namespace App\Models;
/** @property string|null $lead_id */
use Carbon\CarbonImmutable;
/**
* @property string|null $lead_id
* @property CarbonImmutable|null $due_at
*/
class CrmTask extends CrmRecord
{
protected $table = 'tasks';
+14
View File
@@ -2,9 +2,23 @@
namespace App\Models;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* @property string|null $public_slug
* @property string|null $public_title
* @property string|null $activity_code
* @property string|null $stage
* @property string|null $objective
* @property string|null $currency
* @property string|null $amount_min
* @property string|null $amount_max
* @property string|null $available_percentage
* @property CarbonImmutable|null $published_at
* @property-read Sector|null $sector
*/
class ExistingBusiness extends DomainRecord
{
protected $hidden = ['payload'];
+6
View File
@@ -5,6 +5,12 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $version_no
* @property string $validation_status
* @property string $valid_from
* @property string|null $valid_until
*/
class InvestmentLegalSource extends Model
{
use HasUuids;
+1
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
/** @property array<string,mixed> $payload */
class InvestmentSubmission extends Model
{
use HasUuids;
+33 -1
View File
@@ -2,7 +2,39 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* @property string $id
* @property string $code
* @property string $name
* @property ?string $primary_territory_id
* @property ?string $province
* @property ?string $district
* @property ?string $physical_category
* @property ?string $legal_regime
* @property ?string $development_status
* @property ?string $availability_status
* @property ?string $area_value
* @property ?string $area_unit
* @property array<int,array<string,mixed>>|null $source_evidence
*/
class InvestmentZone extends DomainRecord
{
protected $casts = ['version_no' => 'integer', 'published_at' => 'datetime'];
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'];
/** @return BelongsTo<GeoLocation, $this> */
public function primaryTerritory(): BelongsTo
{
return $this->belongsTo(GeoLocation::class, 'primary_territory_id');
}
/** @return BelongsToMany<GeoLocation, $this> */
public function documentedLocations(): BelongsToMany
{
return $this->belongsToMany(GeoLocation::class, 'investment_zone_locations', 'zone_id', 'geo_location_id')
->withPivot(['id', 'scope_type', 'source_reference', 'legal_source_id', 'valid_from', 'valid_until', 'validation_status', 'editor_id', 'reviewer_id', 'version_no'])
->withTimestamps();
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
/**
* @property array<string, mixed> $payload
* @property string $crm_submission_key
* @property int|null $interest_request_id
* @property string $status
* @property string $reference
* @property int $version
*/
class LandAssistanceCase extends Model
{
use HasUuids;
protected $guarded = ['id'];
protected function casts(): array
{
return [
'payload' => 'encrypted:array',
'version' => 'integer',
'support_requested_at' => 'immutable_datetime',
];
}
}
+19 -1
View File
@@ -5,16 +5,26 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property string|null $primary_territory_id
* @property int $territory_version
* @property int $management_version
* @property string|null $management_draft
* @property string|null $management_creation_key
* @property string|null $first_submitted_at
* @property bool $management_closed_once
* @property string|null $opportunity_category
* @property string|null $estimated_investment_currency
*/
class Opportunity extends Model
{
use SoftDeletes;
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once'];
protected $fillable = [
'sector_id', 'reference', 'title', 'slug', 'summary', 'description',
'province', 'district', 'promoter_name', 'promoter_type',
@@ -23,6 +33,7 @@ class Opportunity extends Model
'expected_impact', 'status', 'is_featured', 'published_at',
'last_validated_at',
'primary_territory_id', 'territory_version',
'geography_scope',
];
protected $casts = [
@@ -45,11 +56,18 @@ class Opportunity extends Model
return $this->belongsTo(GeoLocation::class, 'primary_territory_id');
}
/** @return BelongsToMany<GeoLocation, $this> */
public function additionalTerritories(): BelongsToMany
{
return $this->belongsToMany(GeoLocation::class, 'opportunity_locations', 'opportunity_id', 'geo_location_id');
}
/** @param Builder<Opportunity> $query
* @return Builder<Opportunity>
*/
public function scopePublished(Builder $query): Builder
{
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'");
}
}
+4
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
/**
* @property string $id
@@ -14,7 +15,10 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property string $status
* @property int $version_no
* @property array<string, mixed> $input_snapshot
* @property array<string, mixed> $calculation_snapshot
* @property array<string, mixed>|null $result_snapshot
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
class Simulation extends Model
{
+23 -2
View File
@@ -3,20 +3,41 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Crypt;
/**
* @property string $id
* @property int|null $owner_user_id
* @property string|null $anonymous_token_hash
* @property int $version_no
* @property string $create_key_hash
* @property string $create_payload_hash
* @property string $snapshot_sha256
* @property string $personal_snapshot
* @property string $economic_snapshot
* @property Carbon|null $deleted_at
* @property Carbon|null $expires_at
* @property string|null $claimed_token_hash
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
class SimulationFormDraft extends Model
{
public $incrementing = false;
protected $table = 'simulation_form_drafts';
protected $keyType = 'string';
protected $fillable = [
'id', 'owner_user_id', 'anonymous_token_hash', 'version_no', 'create_key_hash', 'create_payload_hash', 'snapshot_sha256',
'personal_snapshot', 'economic_snapshot', 'deleted_at',
'personal_snapshot', 'economic_snapshot', 'deleted_at', 'expires_at', 'claimed_token_hash',
];
protected function casts(): array
{
return ['version_no' => 'integer', 'deleted_at' => 'immutable_datetime'];
return ['version_no' => 'integer', 'deleted_at' => 'immutable_datetime', 'expires_at' => 'immutable_datetime'];
}
/** @param array<string,mixed> $snapshot */
+9
View File
@@ -3,7 +3,16 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property string $id
* @property int $version_no
* @property string $status
* @property mixed $report_snapshot
* @property string $report_sha256
* @property Carbon|null $created_at
*/
class SimulationReport extends Model
{
public $incrementing = false;
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property string $rule_code
* @property string $component
* @property string $scope_key
* @property string $status
* @property int $author_id
* @property int|null $reviewer_id
* @property int|null $approver_id
* @property Carbon $valid_from
* @property Carbon|null $valid_until
*/
class SimulationTaxRuleVersion extends Model
{
use HasUuids;
protected $guarded = ['id'];
protected function casts(): array
{
return [
'rule_definition' => 'array',
'parameters' => 'array',
'rounding_policy' => 'array',
'valid_from' => 'date:Y-m-d',
'valid_until' => 'date:Y-m-d',
'reviewed_at' => 'immutable_datetime',
'approved_at' => 'immutable_datetime',
'published_at' => 'immutable_datetime',
'suspended_at' => 'immutable_datetime',
'archived_at' => 'immutable_datetime',
];
}
}
+4
View File
@@ -5,6 +5,8 @@ namespace App\Providers;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\Malware\ClamDScanner;
use App\Services\Malware\MalwareScanner;
use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibleBusinessRepository;
use Carbon\CarbonImmutable;
@@ -25,6 +27,8 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
$this->app->bind(MalwareScanner::class, ClamDScanner::class);
$this->app->bind(BusinessRepository::class, CompatibleBusinessRepository::class);
}
+5
View File
@@ -13,6 +13,7 @@ final class EvidenceRepository
->where('s.status', 'approved')->where('s.purpose', 'investment_information')
->where('s.valid_until', '>=', now()->toDateString())->where('s.source_date', '<=', now()->toDateString())
->where('d.status', 'active')->whereNull('d.deleted_at')->whereIn('d.data_classification', ['public', 'internal'])
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
->whereColumn('s.document_version', 'd.version_no')->whereColumn('s.document_checksum', 'd.sha256');
}
@@ -33,6 +34,10 @@ final class EvidenceRepository
if (! empty($filters['nature'])) {
$builder->where('s.nature', $filters['nature']);
}
if ($filters['public_only'] ?? false) {
$builder->where('d.data_classification', 'public')->where('d.rights_status', '!=', 'restricted')
->whereExists(fn ($q) => $q->selectRaw('1')->from('portal_resources as r')->whereColumn('r.document_id', 'd.id')->where('r.published', true)->where('r.rights_status', '!=', 'restricted'));
}
return array_values($builder->orderByDesc('rank')->orderBy('c.id')->limit((int) config('investmoz_ai.retrieval_limit', 5))
->get()->map(fn ($row) => (array) $row)->all());
+255
View File
@@ -0,0 +1,255 @@
<?php
namespace App\Services\Ai;
use App\Models\CrmTask;
use App\Models\InvestmentSubmission;
use App\Models\SimulationFormDraft;
use App\Models\User;
use App\Services\InvestmentGeography;
use App\Services\VirtualDesk;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class InvestorGuidance
{
public function __construct(private VirtualDesk $desk, private InvestorGuidanceRules $rules) {}
public function installed(): bool
{
return Schema::hasColumn('tasks', 'desk_case_id');
}
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator. */
/** @return array<string,mixed> */
public function context(User $actor, \stdClass $case): array
{
$base = $this->desk->decode($case->payload);
$facts = Arr::only($base['guidance']['assumptions'] ?? [], InvestorGuidanceRules::FIELDS);
$consulted = [];
$unavailable = [];
$financialDraft = null;
$checks = [];
$revision = ['case' => (int) $case->version];
$submission = $case->submission_id ? InvestmentSubmission::where('id', $case->submission_id)->where('user_id', $actor->id)->first() : null;
if ($submission) {
$input = $submission->payload;
$mapped = ['project_title' => $input['title'] ?? $case->title, 'project_summary' => $input['objective'] ?? '',
'activity' => $input['activity_description'] ?? '', 'schedule' => $input['schedule'] ?? ''];
$facts = [...$mapped, ...$facts];
$consulted[] = ['module' => 'investment_submission', 'id' => $submission->id, 'version' => $submission->version, 'date' => $submission->updated_at?->toIso8601String(), 'status' => 'investor_declaration'];
$revision['submission'] = $submission->version;
} elseif ($case->submission_id) {
$unavailable[] = 'investment_submission_permission_or_availability';
}
if ($case->simulation_id) {
$draft = SimulationFormDraft::where('id', $case->simulation_id)->where('owner_user_id', $actor->id)->whereNull('deleted_at')
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->first();
if ($draft) {
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$mapped = Arr::only($economic, InvestorGuidanceRules::FIELDS);
$mapped['activity'] = $economic['selection_labels']['activity_id'] ?? $economic['products_services'] ?? '';
// A market assumption is not evidence of demand.
if (! empty($economic['market_source'])) {
$mapped['market_evidence'] = $economic['market_source'];
}
$mapped['location'] = $economic['selection_labels']['province_id'] ?? '';
$mapped['location_evidence'] = $economic['location_rationale'] ?? '';
if (! empty($economic['skills_needed'])) {
$mapped['resource_plan'] = $economic['skills_needed'];
}
$checks = $this->catalogueChecks($economic);
$facts = [...$mapped, ...$facts];
// Only economic fields needed by existing deterministic calculators, never personal_snapshot.
$financialDraft = Arr::only($economic, ['business_plan_snapshot', 'financial_tools_snapshot', 'currency']);
$consulted[] = ['module' => 'simulation_form_draft', 'id' => $draft->id, 'version' => $draft->version_no, 'hash' => $draft->snapshot_sha256,
'date' => $draft->updated_at?->toIso8601String(), 'status' => 'declared_assumptions_and_versioned_snapshots'];
$revision['simulation'] = [$draft->version_no, $draft->snapshot_sha256];
} else {
$unavailable[] = 'simulation_draft_permission_or_availability';
}
}
$facts['project_title'] = $facts['project_title'] ?? $case->title;
$evidence = app(InvestorGuidanceEvidence::class)->forCase($actor, $case, $this->desk);
$fingerprint = hash('sha256', json_encode([InvestorGuidanceRules::VERSION, $revision, Arr::sortRecursive($facts), $checks, $evidence], JSON_THROW_ON_ERROR));
return ['facts' => $facts, 'consulted' => $consulted, 'unavailable' => $unavailable, 'financial_draft' => $financialDraft, 'fingerprint' => $fingerprint, 'catalogue_checks' => $checks, 'evidence' => $evidence];
}
/** @param array<string,mixed> $economic
* @return list<array<string,mixed>> */
private function catalogueChecks(array $economic): array
{
$checks = [];
if (! empty($economic['activity_id'])) {
$activity = DB::table('economic_activities as a')->join('reference_catalog_versions as v', 'v.id', '=', 'a.catalog_version_id')
->where('a.id', $economic['activity_id'])->where('a.status', 'published')->where('v.status', 'published')
->whereDate('a.valid_from', '<=', today())->where(fn ($q) => $q->whereNull('a.valid_to')->orWhereDate('a.valid_to', '>', today()))
->first(['a.id', 'a.sector_id', 'a.catalog_version_id']);
$classification = ! $activity || empty($economic['sector_id']) ? 'insufficient_information'
: ((int) $activity->sector_id === (int) $economic['sector_id'] ? 'catalogue_consistent' : 'documented_incompatibility');
$checks[] = ['code' => 'activity_sector', 'classification' => $classification, 'restriction' => false,
'explanation' => match ($classification) {
'documented_incompatibility' => 'A actividade e o sector seleccionados não correspondem no catálogo publicado consultado.',
'catalogue_consistent' => 'Actividade e sector correspondem no catálogo consultado; isto não prova mercado ou elegibilidade.',
default => 'Sem referência actual autorizada suficiente para verificar actividade e sector.',
}, 'source' => $activity ? ['module' => 'economic_activities', 'id' => $activity->id, 'version_id' => $activity->catalog_version_id] : null];
}
$parents = ['district_id' => 'province_id', 'admin_post_id' => 'district_id', 'locality_id' => 'admin_post_id'];
foreach ($parents as $child => $parent) {
if (empty($economic[$child])) {
continue;
}
$location = app(InvestmentGeography::class)->publicReferences()->where('id', $economic[$child])->first(['id', 'parent_id']);
$classification = ! $location || empty($economic[$parent]) ? 'insufficient_information'
: ($location->parent_id === $economic[$parent] ? 'catalogue_consistent' : 'documented_incompatibility');
$checks[] = ['code' => 'territory_'.$child, 'classification' => $classification, 'restriction' => false,
'explanation' => match ($classification) {
'documented_incompatibility' => 'A hierarquia territorial declarada contradiz a referência publicada consultada.',
'catalogue_consistent' => 'Hierarquia territorial coerente na referência consultada; disponibilidade e infraestrutura continuam por confirmar.',
default => 'Referência territorial insuficiente ou indisponível para esta verificação.',
}, 'source' => $location ? ['module' => 'geo_locations', 'id' => $location->id, 'parent_id' => $location->parent_id] : null];
}
return $checks;
}
/** @return array<string,mixed> */
public function view(User $actor, string $id): array
{
$case = $this->desk->case($actor, $id);
abort_unless($this->installed(), 503, 'A extensão do acompanhamento aguarda instalação autenticada.');
$context = $this->context($actor, $case);
$choices = [];
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', 'recommendation_reviewed')->orderBy('event_order')->get() as $event) {
$data = $this->desk->decode($event->payload);
$choices[$data['code']] = [...$data, 'actor_id' => $event->actor_id, 'date' => $event->created_at, 'stale' => $data['context_hash'] !== $context['fingerprint']];
}
$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,
'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id];
// The simulator recovers its current owner-scoped draft; do not pass private payload in URLs.
if ($case->simulation_id && $context['financial_draft'] !== null) {
$actions['plan'] = '/simulador-fiscal';
}
$phases = $this->rules->evaluate($context['facts'], $context['evidence']);
foreach ($phases as &$phase) {
foreach ($phase['recommendations'] as &$recommendation) {
$recommendation['review'] = $choices[$recommendation['code']] ?? null;
$recommendation['href'] = $actions[$recommendation['action']];
}
unset($recommendation);
}
unset($phase);
$tasks = DB::table('tasks as t')->leftJoin('users as u', 'u.id', '=', 't.assignee_user_id')->where('t.desk_case_id', $id)->whereNull('t.deleted_at')
->when(! $this->desk->owns($actor, $case, false) && ! $actor->can('manage-portal'), fn ($q) => $q->where('t.assignee_user_id', $actor->id))
->get(['t.id', 't.title', 't.status', 't.due_at', 't.version_no', 't.desk_request_id', 't.accepted_by', 't.accepted_at', 't.assignee_user_id', 'u.name as assignee_name', 't.external_sync_status']);
return ['version' => $case->version, 'rules_version' => InvestorGuidanceRules::VERSION, 'computed_at' => now()->toIso8601String(),
...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => $this->desk->owns($actor, $case),
'external_ai' => ['status' => 'not_configured', 'model' => null, 'consulted' => []],
'calculator_versions' => ['business_financial_plan' => hash_file('sha256', resource_path('js/lib/business-financial-plan.ts')), 'financial_calculators' => hash_file('sha256', resource_path('js/lib/financial-calculators.ts')), 'project_dossier' => hash_file('sha256', resource_path('js/lib/project-dossier.ts'))],
'crm' => ['internal' => 'available', 'external' => 'out_of_scope', 'reason' => 'O acompanhamento usa o CRM interno existente. A sincronização externa está fora desta fase; nenhum contacto, mensagem ou documento é transmitido.']];
}
/** @param array<string,mixed> $input */
public function assumptions(User $actor, string $id, array $input): void
{
$rules = ['version' => 'required|integer|min:1', 'assumptions' => ['required', 'array:'.implode(',', InvestorGuidanceRules::FIELDS)]];
foreach (InvestorGuidanceRules::FIELDS as $field) {
$rules['assumptions.'.$field] = in_array($field, ['expected_start_date', 'ready_date', 'funding_ready_date', 'completion_date'], true) ? 'nullable|date_format:Y-m-d' : 'nullable|string|max:3000';
}
$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);
abort_unless((int) $case->version === (int) $data['version'], 409, 'Dossier alterado; recarregue antes de corrigir.');
$base = $this->desk->decode($case->payload);
$base['guidance']['assumptions'] = $data['assumptions'];
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($base), 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event(DB::table('desk_cases')->where('id', $id)->first(), $actor, 'assumptions_corrected', ['assumptions' => $data['assumptions'], 'origin' => 'investor_correction_not_official_data']);
});
}
/** @param array<string,mixed> $input */
public function feedback(User $actor, string $id, array $input): void
{
$data = Validator::make($input, ['code' => 'required|string|max:100', 'context_hash' => 'required|string|size:64',
'decision' => ['required', Rule::in(['accepted', 'rejected', 'corrected'])], 'reason' => 'required|string|min:3|max:3000'])->validate();
DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$view = $this->view($actor, $id);
abort_unless(hash_equals($view['fingerprint'], $data['context_hash']), 409, 'Pressupostos alterados; reveja a recomendação actual.');
$recommendations = array_merge(...array_column($view['phases'], 'recommendations'));
abort_unless(in_array($data['code'], array_column($recommendations, 'code'), true), 422);
$this->desk->event($case, $actor, 'recommendation_reviewed', [...$data, 'rules_version' => InvestorGuidanceRules::VERSION, 'creates_task' => false]);
});
}
/** @param array<string,mixed> $input */
public function acceptTask(User $actor, string $id, array $input): CrmTask
{
$data = Validator::make($input, ['code' => 'required|string|max:100', 'context_hash' => 'required|string|size:64', 'consent' => 'accepted',
'due_at' => 'required|date|after:now', 'request_id' => 'nullable|uuid'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$view = $this->view($actor, $id);
abort_unless(hash_equals($view['fingerprint'], $data['context_hash']), 409);
$recommendations = array_merge(...array_column($view['phases'], 'recommendations'));
$suggestion = collect($recommendations)->firstWhere('code', $data['code']);
abort_unless($suggestion && ($suggestion['review']['decision'] ?? null) === 'accepted' && ! $suggestion['review']['stale'], 422, 'Aceite a recomendação actual antes de assumir a tarefa.');
if ($data['request_id'] ?? null) {
$request = $this->desk->request($actor, $data['request_id'], true);
abort_unless($request->case_id === $id, 422);
}
// One accepted action per suggestion, even after corrections or retries.
$existing = CrmTask::where('desk_case_id', $id)->where('guidance_key', $data['code'])->first();
if ($existing) {
abort_unless($existing->getAttribute('desk_request_id') === ($data['request_id'] ?? null)
&& (int) $existing->getAttribute('accepted_by') === $actor->id && $existing->due_at !== null && $existing->due_at->equalTo(Carbon::parse($data['due_at'])), 409, 'A tarefa já foi assumida com outros dados; reveja o registo existente.');
return $existing;
}
$task = CrmTask::create(['desk_case_id' => $id, 'desk_request_id' => $data['request_id'] ?? null, 'guidance_key' => $data['code'],
'title' => $suggestion['explanation'], 'status' => 'open', 'due_at' => $data['due_at'], 'assignee_user_id' => $actor->id,
'accepted_by' => $actor->id, 'accepted_at' => now(), 'external_sync_status' => 'pending_authorization',
'source_system' => 'investor-guidance', 'data_classification' => 'confidential']);
$this->desk->event($case, $actor, 'guidance_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'context_hash' => $data['context_hash'], 'due_at' => $data['due_at'], 'scope' => 'internal_crm']);
return $task;
});
}
/** @param array<string,mixed> $input */
public function updateTask(User $actor, string $id, string $taskId, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])],
'reason' => 'required|string|min:3|max:3000', 'assignee_user_id' => 'nullable|integer|exists:users,id', 'due_at' => 'nullable|date|after:now'])->validate();
DB::transaction(function () use ($actor, $id, $taskId, $data) {
$case = $this->desk->case($actor, $id);
$task = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->lockForUpdate()->firstOrFail();
abort_unless($actor->can('manage-portal') || (int) $task->getAttribute('assignee_user_id') === $actor->id, 403);
abort_unless((int) $task->getAttribute('version_no') === (int) $data['version'], 409);
$updates = ['status' => $data['status'], 'version_no' => $data['version'] + 1];
if ($data['assignee_user_id'] ?? null) {
abort_unless($actor->can('manage-portal'), 403);
$assignee = User::where('id', $data['assignee_user_id'])->firstOrFail();
abort_unless($assignee->hasVerifiedEmail(), 422, 'Responsável sem conta verificada.');
abort_unless($assignee->can('manage-portal') || DB::table('desk_requests')->where('case_id', $id)->where('analyst_id', $assignee->id)->exists() || $this->desk->owns($assignee, $case), 422, 'Responsável sem acesso ao dossier.');
$updates['assignee_user_id'] = $assignee->id;
}
if ($data['due_at'] ?? null) {
$updates['due_at'] = $data['due_at'];
}
$task->update($updates);
$this->desk->event($case, $actor, 'guidance_task_updated', ['task_id' => $task->id, ...$data, 'kind' => $actor->can('manage-portal') ? 'responsible_response' : 'investor_action']);
});
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Services\Ai;
use App\Models\User;
use App\Services\VirtualDesk;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class InvestorGuidanceEvidence
{
public const FIELDS = ['market_evidence', 'location_evidence', 'resource_evidence', 'funding_evidence'];
/** @return array<string,array<string,mixed>> */
public function forCase(User $actor, \stdClass $case, VirtualDesk $desk): array
{
$privateScope = ! $desk->owns($actor, $case, false) && ! $actor->can('manage-portal');
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case->id)->whereNull('d.deleted_at')
->when($privateScope, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->get(['l.id as link_id', 'l.document_id', 'l.category', 'l.valid_until', 'd.file_name', 'd.version_no', 'd.sha256', 'd.status', 'd.malware_scan_status', 'd.malware_scanned_sha256', 'd.storage_key']);
$reviews = DB::table('desk_events as e')->join('users as u', 'u.id', '=', 'e.actor_id')->where('e.case_id', $case->id)->where('e.action', 'document_reviewed')
->when($privateScope, fn ($q) => $q->where(fn ($p) => $p->whereNull('e.request_id')->orWhereIn('e.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->orderByDesc('e.event_order')->get(['e.id', 'e.payload', 'e.created_at', 'e.actor_id', 'u.name']);
$result = [];
foreach (self::FIELDS as $field) {
$records = [];
foreach ($documents as $doc) {
$latest = null;
foreach ($reviews as $review) {
$payload = $desk->decode($review->payload);
if (($payload['link_id'] ?? null) === $doc->link_id) {
$latest = ['id' => $review->id, 'author_id' => $review->actor_id, 'author' => $review->name, 'date' => $review->created_at, 'payload' => $payload];
break;
}
}
if ($doc->category !== $field && ! ($latest && in_array($field, $latest['payload']['supports'] ?? [], true))) {
continue;
}
// A later review replaces the earlier scope. Merely choosing a
// document category does not verify a preparation assumption.
if ($latest && ! in_array($field, $latest['payload']['supports'] ?? [], true)) {
$latest = null;
}
$state = 'attached_unchecked';
if ($doc->valid_until && $doc->valid_until < now()->toDateString()) {
$state = 'expired';
} elseif ($latest && (($latest['payload']['sha256'] ?? null) !== trim($doc->sha256) || ($latest['payload']['document_version'] ?? null) !== (int) $doc->version_no)) {
$state = 'superseded';
} elseif ($latest) {
$path = realpath(Storage::disk('local')->path($doc->storage_key));
$root = realpath(Storage::disk('local')->path(''));
if (! $path || ! $root || ! str_starts_with($path, $root.DIRECTORY_SEPARATOR) || ! is_file($path) || ! is_string($hash = hash_file('sha256', $path)) || ! hash_equals(trim($doc->sha256), $hash)) {
$state = 'superseded';
} elseif ($doc->status !== 'active' || $doc->malware_scan_status !== 'clean' || trim($doc->sha256) !== $doc->malware_scanned_sha256) {
$state = 'technical_unavailable';
} else {
$state = match ($latest['payload']['outcome'] ?? '') {
'internal_verified' => 'internally_verified',
'contradiction_identified' => 'contradiction',
default => 'issue_identified',
};
}
}
$records[] = ['document_id' => $doc->document_id, 'link_id' => $doc->link_id, 'name' => $doc->file_name, 'state' => $state, 'version' => (int) $doc->version_no, 'hash' => trim($doc->sha256), 'valid_until' => $doc->valid_until,
'review' => $latest ? ['event_id' => $latest['id'], 'author_id' => $latest['author_id'], 'author' => $latest['author'], 'date' => $latest['date'], 'what_checked' => $latest['payload']['what_checked'], 'evidence' => $latest['payload']['evidence'], 'scope' => $latest['payload']['scope']] : null];
}
if ($records) {
// A specific current contradiction takes precedence; other valid evidence
// remains visible instead of erasing expired or replaced originals.
$states = array_column($records, 'state');
$state = 'attached_unchecked';
foreach (['contradiction', 'internally_verified', 'issue_identified', 'superseded', 'expired', 'technical_unavailable'] as $candidate) {
if (in_array($candidate, $states, true)) {
$state = $candidate;
break;
}
}
$result[$field] = ['state' => $state, 'documents' => $records];
}
}
return $result;
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Services\Ai;
/** Internal preparation rules; never calculate tax, returns or eligibility. */
class InvestorGuidanceRules
{
public const VERSION = 'investor-guidance-2026-10-08-v3';
public const FIELDS = ['project_title', 'project_summary', 'activity', 'target_customers', 'market_evidence', 'location',
'location_evidence', 'resource_plan', 'resource_evidence', 'funding_evidence', 'expected_start_date', 'ready_date', 'schedule',
'demand_quantity', 'capacity_quantity', 'quantity_unit', 'quantity_period', 'resources_required', 'resources_available', 'resource_unit',
'funding_required', 'funding_committed', 'funding_currency', 'funding_ready_date', 'completion_date'];
/** @param array<string,mixed> $facts
* @param array<string,array<string,mixed>> $evidence
* @return list<array<string,mixed>> */
public function evaluate(array $facts, array $evidence = []): array
{
$phases = [
'idea' => ['Definir a actividade e o objectivo', ['project_title', 'project_summary', 'activity'], 'Confirme o que pretende produzir ou prestar.', 'plan'],
'market' => ['Documentar clientes e hipóteses de mercado', ['target_customers', 'market_evidence'], 'Reúna evidência de clientes; uma hipótese não demonstra procura.', 'opportunities'],
'location' => ['Comparar locais e requisitos da actividade', ['location', 'location_evidence'], 'Confirme terreno, acesso, infraestrutura e licenciamento para cada alternativa.', 'locations'],
'resources' => ['Preparar recursos e equipa', ['resource_plan', 'resource_evidence'], 'Distinga recursos declarados de disponibilidade comprovada.', 'partners'],
'finance' => ['Explorar financiamento e cenários', ['funding_evidence'], 'Reveja os pressupostos e os cenários no simulador determinístico.', 'simulator'],
'execution' => ['Reconciliar calendário e dependências', ['expected_start_date', 'ready_date', 'schedule'], 'Confirme datas, dependências e responsáveis antes de assumir marcos.', 'plan'],
'support' => ['Preparar o pedido e acompanhar a resposta', [], 'Prepare um rascunho no Balcão; reveja e submeta pessoalmente.', 'support'],
];
$result = [];
foreach ($phases as $code => [$objective, $fields, $explanation, $action]) {
$known = [];
$unknown = [];
$phaseEvidence = [];
$risks = [];
foreach ($fields as $field) {
$value = trim((string) ($facts[$field] ?? ''));
$record = $evidence[$field] ?? null;
$state = $record['state'] ?? ($value !== '' ? 'investor_declared_not_verified' : 'absent');
if (in_array($field, InvestorGuidanceEvidence::FIELDS, true)) {
$phaseEvidence[] = ['field' => $field, 'state' => $state, 'documents' => $record['documents'] ?? []];
if ($state !== 'internally_verified') {
$message = match ($state) {
'absent' => 'Ainda não existe informação ou documento para este pressuposto.',
'investor_declared_not_verified' => 'A declaração do investidor ainda não foi conferida.',
'attached_unchecked' => 'Existe um documento associado, sem conferência interna deste pressuposto.',
'expired' => 'A validade documental registada terminou; actualize a evidência.',
'superseded' => 'O ficheiro ou a versão mudou depois da conferência; é necessária nova análise.',
'contradiction' => 'Uma conferência interna identificou contradição no âmbito descrito.',
'issue_identified' => 'Uma conferência interna identificou um problema no âmbito descrito.',
default => 'A evidência não está disponível para utilização; consulte o motivo documental.',
};
$risks[] = ['code' => $field.'_'.$state, 'classification' => $state === 'contradiction' ? 'documented_contradiction' : 'insufficient_information', 'explanation' => $message, 'field' => $field, 'restriction' => false];
}
}
if ($value !== '') {
$known[] = ['field' => $field, 'value' => $value, 'status' => 'investor_declared_not_verified'];
} elseif (! $record) {
$unknown[] = $field;
}
}
$result[] = ['id' => $code, 'objective' => $objective, 'known' => $known, 'questions' => $unknown,
'recommendations' => [[
'code' => $code.'_preparation', 'kind' => 'automatic_recommendation', 'classification' => $unknown ? 'insufficient_information' : 'verification_required',
'explanation' => $explanation, 'action' => $action, 'assumptions' => $known,
'source' => ['identifier' => self::VERSION, 'reference' => 'app/Services/Ai/InvestorGuidanceRules.php#'.$code, 'date' => '2026-10-08', 'nature' => 'internal_preparation_rule'],
'limitations' => ['Uma conferência interna só sustenta o âmbito descrito pelo verificador; não aprova procura, infraestrutura, financiamento, registo ou licença institucional.', 'Sem previsão de sucesso, taxa fiscal ou elegibilidade inferida.'],
]], 'evidence' => $phaseEvidence, 'risks' => $risks];
}
if (($facts['expected_start_date'] ?? '') && ($facts['ready_date'] ?? '') && $facts['expected_start_date'] < $facts['ready_date']) {
$result[5]['risks'][] = ['code' => 'schedule_contradiction', 'classification' => 'declared_contradiction',
'explanation' => 'O início indicado antecede a disponibilidade declarada dos recursos.', 'basis' => ['expected_start_date' => $facts['expected_start_date'], 'ready_date' => $facts['ready_date']],
'restriction' => false];
}
$result[4]['risks'][] = ['code' => 'tax_eligibility_not_inferred', 'classification' => 'insufficient_information', 'explanation' => 'A evidência do financiamento não determina taxas fiscais ou elegibilidade. Consulte os pressupostos, fontes e versões no simulador.', 'restriction' => false];
foreach ([
[1, 'demand_quantity', 'capacity_quantity', ['quantity_unit', 'quantity_period'], 'A procura declarada excede a capacidade declarada para a mesma unidade e período.'],
[3, 'resources_required', 'resources_available', ['resource_unit'], 'Os recursos disponíveis declarados são inferiores aos necessários declarados.'],
[4, 'funding_required', 'funding_committed', ['funding_currency'], 'O financiamento comprometido declarado é inferior ao necessário declarado na mesma moeda.'],
] as [$phase, $required, $available, $scope, $explanation]) {
$values = array_intersect_key($facts, array_flip([$required, $available, ...$scope]));
if (! array_filter($values, fn ($value) => $value !== null && $value !== '')) {
continue;
}
$complete = true;
foreach ([$required, $available, ...$scope] as $field) {
if (! isset($facts[$field]) || trim((string) $facts[$field]) === '') {
$complete = false;
}
}
// Compare declared magnitudes only: this is no forecast, valuation or financial calculation.
$left = $facts[$required] ?? null;
$right = $facts[$available] ?? null;
$valid = is_scalar($left) && is_scalar($right)
&& preg_match('/^\d{1,12}(\.\d{1,2})?$/', (string) $left)
&& preg_match('/^\d{1,12}(\.\d{1,2})?$/', (string) $right);
if (! $complete || ! $valid) {
$result[$phase]['risks'][] = ['code' => $required.'_comparison_incomplete', 'classification' => 'insufficient_information',
'explanation' => 'Faltam valores comparáveis, unidade, período ou moeda para esta comparação.', 'basis' => $values, 'restriction' => false];
} elseif ($this->declaredMagnitude((string) $left) > $this->declaredMagnitude((string) $right)) {
$result[$phase]['risks'][] = ['code' => $required.'_declared_gap', 'classification' => 'declared_contradiction',
'explanation' => $explanation.' Estes valores são declarações, não disponibilidade comprovada.', 'basis' => $values, 'restriction' => false];
}
}
foreach ([['completion_date', 'expected_start_date', 'A conclusão declarada antecede o início.'],
['expected_start_date', 'funding_ready_date', 'O início declarado antecede a disponibilidade declarada do financiamento.']] as [$first, $second, $explanation]) {
if (! empty($facts[$first]) && ! empty($facts[$second]) && $facts[$first] < $facts[$second]) {
$result[5]['risks'][] = ['code' => $first.'_'.$second.'_contradiction', 'classification' => 'declared_contradiction',
'explanation' => $explanation, 'basis' => [$first => $facts[$first], $second => $facts[$second]], 'restriction' => false];
}
}
return $result;
}
private function declaredMagnitude(string $value): int
{
$parts = explode('.', $value);
return (int) $parts[0] * 100 + (int) str_pad($parts[1] ?? '', 2, '0');
}
}
+2 -1
View File
@@ -14,7 +14,8 @@ final class SourceIngestion
{
return DB::transaction(function () use ($data, $actor): string {
$document = DB::table('documents')->where('id', $data['document_id'])->whereNull('deleted_at')->lockForUpdate()->first();
if (! $document || $document->status !== 'active' || $document->media_type !== 'text/plain'
if (! $document || $document->status !== 'active' || $document->malware_scan_status !== 'clean'
|| ! hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)) || $document->media_type !== 'text/plain'
|| ! in_array($document->data_classification, ['public', 'internal'], true)) {
throw ValidationException::withMessages(['document_id' => 'Documento activo de texto autorizado necessário; fontes confidenciais/restritas não são admitidas.']);
}
+136 -22
View File
@@ -3,37 +3,77 @@
namespace App\Services;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
final class BusinessFormSchema
{
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>}> */
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>,when?:array<string,list<string>>}> */
public static function fields(): array
{
return [
'proponent_type' => ['step' => 1, 'pt' => 'Tipo de proponente', 'en' => 'Applicant type', 'type' => 'select', 'max' => 30, 'options' => ['person' => 'Pessoa / Person', 'organization' => 'Organização / Organization']],
'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],
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador', 'en' => 'Tax identifier', 'type' => 'text', 'max' => 50],
'contact_email' => ['step' => 1, 'pt' => 'Email de contacto', 'en' => 'Contact email', 'type' => 'email', 'max' => 254],
'contact_phone' => ['step' => 1, 'pt' => 'Telefone', 'en' => 'Phone', 'type' => 'tel', 'max' => 40],
'country' => ['step' => 1, 'pt' => 'País (código de duas letras)', 'en' => 'Country (two-letter code)', 'type' => 'text', 'max' => 2],
'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],
'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_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
'contact_phone' => ['step' => 1, 'pt' => 'Telefone (indique telefone ou email)', 'en' => 'Phone (provide phone or email)', 'type' => 'tel', 'max' => 40],
'contact_preference' => ['step' => 1, 'pt' => 'Preferência de contacto', 'en' => 'Contact preference', 'type' => 'select', 'max' => 30, 'options' => ['through_portal' => 'Receber pedidos através da InvestMoz', 'approved_business_contact' => 'Mostrar contacto empresarial aprovado']],
'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']],
'declared_holder' => ['step' => 2, 'pt' => 'Titular declarado', 'en' => 'Declared holder', 'type' => 'text', 'max' => 200],
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do mandato', 'en' => 'Mandate reference', 'type' => 'text', 'max' => 500],
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10],
'declared_holder' => ['step' => 2, 'pt' => 'Entidade ou pessoa representada', 'en' => 'Entity or person represented', 'type' => 'text', 'max' => 200],
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do documento de autorização', 'en' => 'Authorization document reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência interna do documento de autorização (não carregue aqui)', 'en' => 'Internal authorization document reference (do not upload here)', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10, 'when' => ['acting_capacity' => ['representative']]],
'disclosure_scope' => ['step' => 2, 'pt' => 'Limites da autorização de divulgação', 'en' => 'Limits of disclosure authorization', 'type' => 'textarea', 'max' => 2000, 'when' => ['acting_capacity' => ['representative']]],
'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']],
'title' => ['step' => 3, 'pt' => 'Título proposto', 'en' => 'Proposed title', 'type' => 'text', 'max' => 200],
'description' => ['step' => 3, 'pt' => 'Descrição reservada', 'en' => 'Private description', 'type' => 'textarea', 'max' => 10000],
'opportunity_type' => ['step' => 3, 'pt' => 'Tipo de oportunidade', 'en' => 'Opportunity type', 'type' => 'select', 'max' => 40, 'options' => ['investment_project' => 'Projecto de investimento', 'company_sale' => 'Venda de negócio existente', 'asset_sale' => 'Activo disponível', 'business_partnership' => 'Parceria empresarial', 'financing_request' => 'Procura de financiamento', 'concession_opportunity' => 'Concessão', 'supply_opportunity' => 'Oportunidade de fornecimento']],
'description' => ['step' => 3, 'pt' => 'Descrição resumida: o que está disponível, procura e condições principais', 'en' => 'Summary: what is available, sought and key conditions', 'type' => 'textarea', 'max' => 10000],
'subsector_activity' => ['step' => 3, 'pt' => 'Subsector e actividade (por designação)', 'en' => 'Subsector and activity (by name)', 'type' => 'text', 'max' => 500],
'declared_reason' => ['step' => 3, 'pt' => 'Motivo e objectivo', 'en' => 'Reason and objective', 'type' => 'textarea', 'max' => 2000],
'valid_until' => ['step' => 3, 'pt' => 'Validade declarada', 'en' => 'Declared expiry', 'type' => 'date', 'max' => 10],
'asking_value' => ['step' => 4, 'pt' => 'Valor pedido', 'en' => 'Asking value', 'type' => 'decimal', 'max' => 24],
'currency' => ['step' => 4, 'pt' => 'Moeda (código de três letras)', 'en' => 'Currency (three-letter code)', 'type' => 'text', 'max' => 3],
'value_nature' => ['step' => 4, 'pt' => 'Natureza do valor', 'en' => 'Value basis', 'type' => 'select', 'max' => 30, 'options' => ['asking' => 'Pedido / Asking', 'indicative' => 'Indicativo / Indicative', 'appraised' => 'Avaliado, sujeito a prova / Appraised, evidence required']],
'project_stage' => ['step' => 3, 'pt' => 'Situação do projecto ou negócio', 'en' => 'Project or business status', 'type' => 'select', 'max' => 40, 'options' => ['idea' => 'Ideia ou conceito', 'study' => 'Em estudo', 'preparation' => 'Em preparação', 'implementation' => 'Em implementação', 'operating' => 'Em funcionamento', 'suspended' => 'Actividade suspensa', 'other' => 'Outra situação']],
'project_stage_other' => ['step' => 3, 'pt' => 'Especifique a situação', 'en' => 'Specify the status', 'type' => 'text', 'max' => 200, 'when' => ['project_stage' => ['other']]],
'availability' => ['step' => 3, 'pt' => 'Disponibilidade', 'en' => 'Availability', 'type' => 'select', 'max' => 40, 'options' => ['available' => 'Disponível', 'from_date' => 'Disponível a partir de uma data', 'negotiating' => 'Em negociação; aceita manifestações de interesse']],
'available_from' => ['step' => 3, 'pt' => 'Disponível a partir de', 'en' => 'Available from', 'type' => 'date', 'max' => 10, 'when' => ['availability' => ['from_date']]],
'valid_until' => ['step' => 3, 'pt' => 'Prazo para manifestações de interesse (opcional)', 'en' => 'Interest deadline (optional)', 'type' => 'date', 'max' => 10],
'asking_value' => ['step' => 4, 'pt' => 'Valor', 'en' => 'Value', 'type' => 'decimal', 'max' => 24, 'when' => ['value_status' => ['defined', 'indicative']]],
'value_status' => ['step' => 4, 'pt' => 'O valor está definido?', 'en' => 'Is the value defined?', 'type' => 'select', 'max' => 30, 'options' => ['defined' => 'Sim', 'indicative' => 'Valor indicativo', 'consultation' => 'Sob consulta', 'unknown' => 'Ainda não definido']],
'value_meaning' => ['step' => 4, 'pt' => 'Significado do valor', 'en' => 'Meaning of the value', 'type' => 'select', 'max' => 30, 'options' => ['asking_price' => 'Preço pedido', 'investment_estimate' => 'Investimento estimado', 'financing_sought' => 'Financiamento procurado'], 'when' => ['value_status' => ['defined', 'indicative']]],
'value_nature' => ['step' => 4, 'pt' => 'Natureza do valor', 'en' => 'Value basis', 'type' => 'select', 'max' => 30, 'options' => ['asking' => 'Pedido', 'indicative' => 'Indicativo', 'appraised' => 'Avaliado, sujeito a prova'], 'when' => ['value_status' => ['defined', 'indicative']]],
'currency' => ['step' => 4, 'pt' => 'Moeda (código de três letras)', 'en' => 'Currency (three-letter code)', 'type' => 'text', 'max' => 3, 'when' => ['value_status' => ['defined', 'indicative']]],
'amount_secured' => ['step' => 4, 'pt' => 'Montante assegurado (projectos)', 'en' => 'Secured amount (projects)', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project']]],
'investment_total' => ['step' => 4, 'pt' => 'Investimento total estimado (projectos)', 'en' => 'Estimated total investment (projects)', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project']]],
'amount_sought' => ['step' => 4, 'pt' => 'Montante de financiamento procurado', 'en' => 'Financing sought', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project', 'financing_request']]],
'equity_percentage' => ['step' => 4, 'pt' => 'Participação disponível (%)', 'en' => 'Available equity (%)', 'type' => 'decimal', 'max' => 8],
'funds_use' => ['step' => 4, 'pt' => 'Utilização dos fundos', 'en' => 'Use of funds', 'type' => 'textarea', 'max' => 2000],
'location_notes' => ['step' => 5, 'pt' => 'Localização declarada (reservada)', 'en' => 'Declared location (private)', 'type' => 'textarea', 'max' => 2000],
'asset_deal_kind' => ['step' => 4, 'pt' => 'Tipo de venda', 'en' => 'Type of sale', 'type' => 'select', 'max' => 30, 'options' => ['whole_business' => 'Venda total', 'participation' => 'Participação', 'assets' => 'Activos'], 'when' => ['opportunity_type' => ['company_sale', 'asset_sale']]],
'partnership_contribution' => ['step' => 4, 'pt' => 'Contribuição pretendida', 'en' => 'Contribution sought', 'type' => 'select', 'max' => 30, 'options' => ['capital' => 'Capital', 'technology' => 'Tecnologia', 'management' => 'Gestão', 'equipment' => 'Equipamento', 'distribution' => 'Distribuição', 'other' => 'Outra'], 'when' => ['opportunity_type' => ['business_partnership']]],
'asset_modality' => ['step' => 4, 'pt' => 'Modalidade do activo', 'en' => 'Asset arrangement', 'type' => 'select', 'max' => 30, 'options' => ['sale' => 'Venda', 'lease' => 'Arrendamento', 'other' => 'Outra'], 'when' => ['opportunity_type' => ['asset_sale']]],
'concession_entity' => ['step' => 4, 'pt' => 'Entidade responsável pela concessão', 'en' => 'Concession authority', 'type' => 'text', 'max' => 300, 'when' => ['opportunity_type' => ['concession_opportunity']]],
'concession_reference' => ['step' => 4, 'pt' => 'Referência oficial, procedimento e prazo', 'en' => 'Official reference, procedure and deadline', 'type' => 'textarea', 'max' => 2000, 'when' => ['opportunity_type' => ['concession_opportunity']]],
'supply_description' => ['step' => 4, 'pt' => 'Bem ou serviço, quantidade/capacidade, destino e prazo', 'en' => 'Good or service, quantity/capacity, destination and timing', 'type' => 'textarea', 'max' => 2000, 'when' => ['opportunity_type' => ['supply_opportunity']]],
'conditions' => ['step' => 4, 'pt' => 'Condições adicionais', 'en' => 'Additional conditions', 'type' => 'textarea', 'max' => 4000],
'geography_scope' => ['step' => 5, 'pt' => 'Âmbito geográfico', 'en' => 'Geographic scope', 'type' => 'select', 'max' => 30, 'options' => ['specific' => 'Localização específica', 'multiple' => 'Várias localizações', 'national' => 'Âmbito nacional', 'digital' => 'Digital/sem instalação definida']],
'province_id' => ['step' => 5, 'pt' => 'Província ou Cidade de Maputo', 'en' => 'Province or Maputo City', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
'district_id' => ['step' => 5, 'pt' => 'Distrito', 'en' => 'District', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
'admin_post_id' => ['step' => 5, 'pt' => 'Posto administrativo', 'en' => 'Administrative post', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
'locality_id' => ['step' => 5, 'pt' => 'Localidade', 'en' => 'Locality', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
'locations_json' => ['step' => 5, 'pt' => 'Localizações administrativas (várias)', 'en' => 'Administrative locations (multiple)', 'type' => 'location_list', 'max' => 16000, 'when' => ['geography_scope' => ['multiple']]],
'location_notes' => ['step' => 5, 'pt' => 'Endereço ou referência (interno)', 'en' => 'Address or reference (internal)', 'type' => 'textarea', 'max' => 2000],
'location_unknown' => ['step' => 5, 'pt' => 'Não conheço a localização exacta', 'en' => 'I do not know the exact location', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim', 'no' => 'Não'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
'disclosure_precision' => ['step' => 5, 'pt' => 'Precisão de divulgação', 'en' => 'Disclosure precision', 'type' => 'select', 'max' => 30, 'options' => ['exact' => 'Localização exacta (sujeita a aprovação)', 'approximate' => 'Localização aproximada', 'administrative' => 'Apenas território administrativo'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000],
'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000],
'source_provider' => ['step' => 7, 'pt' => 'Quem forneceu os dados?', 'en' => 'Who supplied the information?', 'type' => 'text', 'max' => 500],
'source_date' => ['step' => 7, 'pt' => 'Data da fonte/informação', 'en' => 'Source/information date', 'type' => 'date', 'max' => 10],
'official_source_entity' => ['step' => 7, 'pt' => 'Entidade da fonte oficial (se existir)', 'en' => 'Official source authority (if any)', 'type' => 'text', 'max' => 500],
'official_source_document' => ['step' => 7, 'pt' => 'Documento oficial associado', 'en' => 'Related official document', 'type' => 'text', 'max' => 500],
'official_source_url' => ['step' => 7, 'pt' => 'Ligação da fonte oficial', 'en' => 'Official source link', 'type' => 'url', 'max' => 2000],
'official_source_period' => ['step' => 7, 'pt' => 'Período da fonte oficial', 'en' => 'Official source period', 'type' => 'text', 'max' => 200],
'document_reference' => ['step' => 7, 'pt' => 'Referências documentais (não são ficheiros validados)', 'en' => 'Document references (not validated files)', 'type' => 'textarea', 'max' => 2000],
'confirm_information' => ['step' => 8, 'pt' => 'Confirmo que a informação corresponde ao que conheço e identifiquei estimativas ou pendências.', 'en' => 'I confirm the information reflects what I know and identify estimates or pending items.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
'confirm_disclosure_authority' => ['step' => 8, 'pt' => 'Confirmo que tenho autorização para apresentar a oportunidade e divulgar os conteúdos seleccionados.', 'en' => 'I confirm I am authorized to submit the opportunity and disclose selected content.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
'confirm_no_publication_guarantee' => ['step' => 8, 'pt' => 'Compreendo que a submissão não constitui publicação, aprovação oficial ou garantia de investimento.', 'en' => 'I understand submission is not publication, official approval or an investment guarantee.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
];
}
@@ -47,34 +87,108 @@ final class BusinessFormSchema
$rules['payload.'.$key][] = 'in:'.implode(',', array_keys($field['options']));
}
}
$rules['payload.contact_email'][] = 'nullable';
$rules['payload.contact_email'][] = 'email';
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/';
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.investment_total'][] = '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.official_source_url'][] = 'url';
$rules['payload.equity_percentage'][] = 'numeric';
$rules['payload.equity_percentage'][] = 'between:0,100';
foreach (['valid_until', 'mandate_valid_until'] as $date) {
$rules['payload.'.$date][] = 'date_format:Y-m-d';
}
$rules['payload.wizard_version'] = ['nullable', 'in:1'];
$rules['payload.wizard_version'] = ['nullable', 'in:1,2'];
$rules['payload.wizard_step'] = ['nullable', 'integer', 'between:1,8'];
$rules['payload.locations_json'][] = 'json';
$rules['payload.title'] = ['required', 'string', 'max:200'];
return $rules;
}
/** @param array<string,mixed> $payload */
public static function validateSubmission(array $payload): void
public static function validateSubmission(array $payload, ?int $sectorId, string $modality): void
{
if (($payload['opportunity_type'] ?? null) !== $modality) {
throw ValidationException::withMessages(['opportunity_type' => 'O tipo da oportunidade não corresponde à classificação guardada.']);
}
$rules = [];
foreach (['proponent_type', 'proponent_name', 'tax_identifier', 'contact_email', 'country', 'acting_capacity', 'declared_holder', 'location_notes'] as $field) {
foreach (['proponent_type', 'proponent_name', 'contact_name', 'country', 'acting_capacity', 'title', 'opportunity_type', 'description', 'project_stage', 'availability', 'geography_scope', 'source_reference', 'source_provider', 'source_date'] as $field) {
$rules[$field] = ['required'];
}
$rules['sector_id'] = ['required'];
$rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email'];
$rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/'];
$rules['legitimacy_declaration'] = ['required', 'in:yes'];
foreach (['confirm_information', 'confirm_disclosure_authority', 'confirm_no_publication_guarantee'] as $confirmation) {
$rules[$confirmation] = ['required', 'in:yes'];
}
$rules['mandate_reference'] = ['required_if:acting_capacity,representative'];
$rules['mandate_valid_until'] = ['required_if:acting_capacity,representative', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
$rules['currency'] = ['required_with:asking_value'];
$rules['value_nature'] = ['required_with:asking_value'];
Validator::make($payload, $rules)->validate();
$rules['declared_holder'] = ['required_if:acting_capacity,representative'];
$rules['disclosure_scope'] = ['required_if:acting_capacity,representative'];
$rules['mandate_valid_until'] = ['nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
$rules['mandate_document_reference'] = ['required_if:acting_capacity,representative'];
$rules['project_stage_other'] = ['required_if:project_stage,other'];
$rules['available_from'] = ['required_if:availability,from_date', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
$rules['value_status'] = ['required', 'in:defined,indicative,consultation,unknown'];
$rules['province_id'] = ['required_if:geography_scope,specific', 'nullable', 'uuid'];
foreach (['district_id', 'admin_post_id', 'locality_id'] as $locationField) {
$rules[$locationField] = ['nullable', 'uuid'];
}
$rules['locations_json'] = ['required_if:geography_scope,multiple', 'nullable', 'json', 'max:16000'];
$rules['asking_value'] = ['required_if:value_status,defined,indicative', 'nullable', 'numeric', 'min:0'];
$rules['currency'] = ['required_if:value_status,defined,indicative', 'nullable', 'regex:/^[A-Z]{3}$/'];
$rules['value_meaning'] = ['required_if:value_status,defined,indicative'];
$rules['amount_secured'] = ['nullable', 'numeric', 'min:0'];
$rules['investment_total'] = ['required_if:opportunity_type,investment_project', 'nullable', 'numeric', 'gt:0'];
$rules['amount_sought'] = ['nullable', 'numeric', 'min:0'];
$rules['equity_percentage'] = ['nullable', 'numeric', 'between:0,100'];
$rules['asset_deal_kind'] = ['required_if:opportunity_type,company_sale,asset_sale'];
$rules['equity_percentage'] = ['required_if:asset_deal_kind,participation', 'nullable', 'numeric', 'between:0,100'];
$rules['partnership_contribution'] = ['required_if:opportunity_type,business_partnership'];
$rules['amount_sought'] = ['required_if:opportunity_type,financing_request', 'nullable', 'numeric', 'min:0'];
$rules['asset_modality'] = ['required_if:opportunity_type,asset_sale'];
$rules['concession_entity'] = ['required_if:opportunity_type,concession_opportunity'];
$rules['concession_reference'] = ['required_if:opportunity_type,concession_opportunity'];
$rules['supply_description'] = ['required_if:opportunity_type,supply_opportunity'];
Validator::make([...$payload, 'sector_id' => $sectorId, 'modality' => $modality], $rules)->validate();
$geography = app(InvestmentGeography::class);
if (($payload['geography_scope'] ?? null) === 'specific') {
$geography->selection(array_intersect_key($payload, array_flip(InvestmentGeography::FIELDS)));
} elseif (($payload['geography_scope'] ?? null) === 'multiple') {
$locations = json_decode($payload['locations_json'], true, 512, JSON_THROW_ON_ERROR);
Validator::make(['locations' => $locations], [
'locations' => ['required', 'array', 'min:2', 'max:20'],
'locations.*' => ['required', 'array:province_id,district_id,admin_post_id,locality_id'],
'locations.*.province_id' => ['required', 'uuid'],
'locations.*.district_id' => ['nullable', 'uuid'],
'locations.*.admin_post_id' => ['nullable', 'uuid'],
'locations.*.locality_id' => ['nullable', 'uuid'],
])->validate();
$paths = [];
foreach ($locations as $index => $location) {
$path = array_map(fn ($node) => (string) $node->id, $geography->selection($location));
foreach ($paths as $existingPath) {
$sharedPrefixLength = 0;
while (isset($path[$sharedPrefixLength], $existingPath[$sharedPrefixLength])
&& $path[$sharedPrefixLength] === $existingPath[$sharedPrefixLength]) {
$sharedPrefixLength++;
}
if ($sharedPrefixLength === min(count($path), count($existingPath))) {
throw ValidationException::withMessages([
'locations_json' => 'As localizações devem ser distintas e não podem repetir ou conter o mesmo percurso administrativo.',
]);
}
}
$paths[] = $path;
}
}
}
}
+9 -2
View File
@@ -17,6 +17,13 @@ class ConvertInterestToLead
{
return DB::transaction(function () use ($interest, $data, $actor) {
$interest = InterestRequest::lockForUpdate()->findOrFail($interest->id);
$contactConsentIsCurrent = DB::table('consents')->where('interest_request_id', $interest->id)
->where('subject_ref', $interest->reference)->where('purpose', 'respond_to_interest')
->where('status', 'granted')->whereNotNull('granted_at')->where('granted_at', '<=', now())
->whereNull('withdrawn_at')->whereNull('deleted_at')->lockForUpdate()->exists();
if (! $interest->privacy_consent || ! $contactConsentIsCurrent) {
throw ValidationException::withMessages(['investor_id' => 'O pedido não tem consentimento de contacto activo.']);
}
$existing = Lead::withTrashed()->where('interest_request_id', $interest->id)->first();
if ($existing) {
if ($existing->trashed()) {
@@ -25,8 +32,8 @@ class ConvertInterestToLead
return $existing;
}
if (! $interest->privacy_consent) {
throw ValidationException::withMessages(['investor_id' => 'O pedido não tem consentimento de contacto registado.']);
if (! is_string($interest->email) || trim($interest->email) === '') {
throw ValidationException::withMessages(['investor_id' => 'Confirme um email antes de converter este pedido telefonico num contacto/lead CRM.']);
}
$email = strtolower(trim($interest->email));
$journeyInvestor = DB::table('investor_journeys')->where('interest_request_id', $interest->id)->whereNull('deleted_at')->value('investor_id');
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Services;
use Illuminate\Validation\Rule;
/** 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(): \Illuminate\Validation\Rules\In
{
return Rule::in(array_column($this->all(), 'code'));
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Services;
use App\Models\User;
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($actor->can('manage-portal'), 403);
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
$groups = [];
foreach (DB::table('interest_requests')->whereNull('deleted_at')->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 (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;
}
}
// 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]);
}
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $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));
}
}
+1 -4
View File
@@ -15,7 +15,7 @@ use Illuminate\Validation\Rule;
final class ExistingBusinessDrafts
{
public const MODALITIES = ['company_sale', 'participation_sale', 'capital_increase', 'financial_investor', 'strategic_partner', 'buyer_search', 'position_assignment', 'franchise', 'asset_sale', 'asset_lease', 'business_unit_transfer', 'joint_venture', 'succession', 'recovery', 'expansion', 'internationalization', 'real_estate', 'agricultural_investment', 'land_right', 'mining_license', 'forestry_license'];
public const MODALITIES = ['company_sale', 'company_purchase', 'participation_sale', 'capital_increase', 'financial_investor', 'strategic_partner', 'buyer_search', 'position_assignment', 'franchise', 'asset_sale', 'asset_lease', 'business_unit_transfer', 'joint_venture', 'succession', 'recovery', 'expansion', 'internationalization', 'real_estate', 'agricultural_investment', 'land_right', 'mining_license', 'forestry_license', 'investment_project', 'business_partnership', 'financing_request', 'concession_opportunity', 'supply_opportunity'];
/** @param array<string,mixed> $input */
public function save(User $actor, array $input, ?string $id = null): ExistingBusiness
@@ -47,9 +47,6 @@ final class ExistingBusinessDrafts
return DB::transaction(function () use ($actor, $id, $data) {
if ($id) {
$business = app(BusinessRepository::class)->find($id, true);
if (($business->payload['wizard_version'] ?? null) === '1') {
$data['payload']['wizard_version'] = '1';
}
Gate::forUser($actor)->authorize('update', $business);
abort_unless($business->version_no === $data['version_no'], 409, 'O rascunho foi alterado. Recarregue antes de gravar.');
$business->version_no++;
+35 -6
View File
@@ -65,8 +65,8 @@ final class ExistingBusinessIntake
];
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
if ($action === 'submitted') {
if (($business->payload['wizard_version'] ?? null) === '1') {
BusinessFormSchema::validateSubmission($business->payload);
if (($business->payload['wizard_version'] ?? null) === '2') {
BusinessFormSchema::validateSubmission($business->payload, $business->sector_id, $business->modality);
$requiredKind = ['asset_sale' => 'asset', 'asset_lease' => 'asset', 'real_estate' => 'property',
'agricultural_investment' => 'agricultural_investment', 'land_right' => 'land_right',
'mining_license' => 'license', 'forestry_license' => 'license', 'capital_increase' => 'capital_request',
@@ -78,11 +78,40 @@ final class ExistingBusinessIntake
'confirmation_code' => ['required', Rule::in([$business->code])],
'sector_id' => ['required', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
])->validate();
} elseif (($business->payload['wizard_version'] ?? null) === '1') {
Validator::make($business->payload, [
'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'],
'contact_email' => ['required', 'email'], 'country' => ['required', 'regex:/^[A-Z]{2}$/'],
'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'],
'legitimacy_declaration' => ['required', 'in:yes'],
'mandate_reference' => ['required_if:acting_capacity,representative'],
'mandate_valid_until' => ['required_if:acting_capacity,representative', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
])->validate();
Validator::make(['confirmation_code' => $confirmationCode], [
'confirmation_code' => ['required', Rule::in([$business->code])],
])->validate();
}
Validator::make([...$business->payload, 'consent' => $consent], [
'description' => ['required', 'string', 'min:30'], 'source_reference' => ['required', 'string', 'min:10'],
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'consent' => ['accepted'],
])->validate();
if (($business->payload['wizard_version'] ?? null) === '1') {
$requiredKind = ['asset_sale' => 'asset', 'asset_lease' => 'asset', 'real_estate' => 'property',
'agricultural_investment' => 'agricultural_investment', 'land_right' => 'land_right',
'mining_license' => 'license', 'forestry_license' => 'license', 'capital_increase' => 'capital_request',
'participation_sale' => 'participation'][$business->modality] ?? null;
if ($requiredKind !== null && ! ExistingBusinessObject::where('business_id', $business->id)->where('kind', $requiredKind)->exists()) {
throw ValidationException::withMessages(['objects' => 'Declare the applicable object in step 6: '.$requiredKind]);
}
}
$submissionRules = [
'description' => ['required', 'string', 'min:30'],
'source_reference' => ['required', 'string', 'min:10'],
'consent' => ['accepted'],
// Deadlines are optional for newer and legacy payloads, but
// an explicitly supplied deadline must never be expired.
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
];
if (($business->payload['wizard_version'] ?? null) === '1') {
$submissionRules['valid_until'][0] = 'required';
}
Validator::make([...$business->payload, 'consent' => $consent], $submissionRules)->validate();
}
if ($action === OpportunityStatus::Approved->value) {
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
+2
View File
@@ -21,6 +21,8 @@ final class ExistingBusinessObjects
'declared_holder' => ['nullable', 'string', 'max:500'],
'document_reference' => ['nullable', 'string', 'max:1000'],
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'source_date' => ['nullable', 'date_format:Y-m-d'],
'resource_status' => ['nullable', 'in:available,contracted,planned,unconfirmed'],
'competent_entity' => ['nullable', 'string', 'max:500'],
'purpose' => ['nullable', 'string', 'max:2000'],
'location_description' => ['nullable', 'string', 'max:2000'],
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Services;
use Illuminate\Support\Carbon;
/** Availability evidence is distinct from legal validity or institutional endorsement. */
class InstitutionalLinkMonitor
{
/** @return array{available:bool,reason:string,contact:string} */
public function status(\stdClass $link): array
{
$valid = filter_var($link->url, FILTER_VALIDATE_URL) && parse_url($link->url, PHP_URL_SCHEME) === 'https';
$fresh = $link->verified_at && Carbon::parse($link->verified_at)->between(now()->subDays(7), now());
return ['available' => (bool) ($valid && $fresh && $link->status === 'active'),
'reason' => ! $valid ? 'invalid_url' : (! $fresh ? 'verification_missing_or_expired' : ($link->status === 'active' ? 'recent_internal_check' : 'reported_unavailable')),
'contact' => $link->contact ?: (config('portal.support.email') ?: 'Utilize o pedido de apoio no mesmo dossier.')];
}
}
+3 -1
View File
@@ -18,7 +18,9 @@ final class InterestSubmission
{
$canonical = array_replace(['phone' => null, 'opportunityReference' => null, 'existingBusinessId' => null,
'modality' => null, 'investmentRange' => null, 'shareWithProponent' => false], $payload);
$canonical['email'] = strtolower(trim($canonical['email']));
$canonical['email'] = isset($canonical['email']) && trim((string) $canonical['email']) !== ''
? strtolower(trim((string) $canonical['email']))
: null;
$canonical['fullName'] = trim($canonical['fullName']);
$canonical['message'] = trim($canonical['message']);
$canonical['privacyConsent'] = true; // FormRequest requires acceptance.
+146 -20
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
@@ -19,6 +20,7 @@ class InvestmentCatalogue
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
'opportunity_id' => ['nullable', 'integer', 'min:1'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
'province' => ['nullable', 'string', 'max:100'], 'district' => ['nullable', 'string', 'max:100'],
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
@@ -42,13 +44,33 @@ class InvestmentCatalogue
public function query(array $filters): Builder
{
$query = Opportunity::published()->with('sector:id,name,slug');
if (($filters['territory_basis'] ?? 'all') === 'direct') {
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
} elseif (($filters['territory_basis'] ?? 'all') === 'context') {
$query->whereNull('opportunities.primary_territory_id')->whereNotExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'));
$query->where(fn ($q) => $q->whereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_projects')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('project_id', app(InvestmentRelations::class)->projectIds()))
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_clusters')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('cluster_id', $this->publicStructureIds('clusters', 'cluster_id'))));
}
if (! empty($filters['opportunity_id'])) {
$query->whereKey($filters['opportunity_id']);
}
$path = app(InvestmentGeography::class)->selection($filters);
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
if ($path !== []) {
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->whereIn('primary_territory_id', $ids);
$query->where(function ($territory) use ($ids, $includeNational, $filters): void {
$territory->whereIn('opportunities.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
}
if ($includeNational) {
$territory->orWhere('opportunities.geography_scope', 'national');
}
});
} elseif (! $includeNational) {
$query->where('opportunities.geography_scope', '!=', 'national');
}
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
@@ -57,7 +79,8 @@ class InvestmentCatalogue
foreach (['cluster' => 'clusters', 'corridor' => 'corridors'] as $dimension => $relation) {
if (($filters['dimension'] ?? null) === $dimension) {
$foreign = $dimension.'_id';
$query->whereIn('opportunities.id', DB::table('opportunity_'.$relation)->whereIn($foreign, InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign))->select('opportunity_id'));
$query->whereIn('opportunities.id', DB::table('opportunity_'.$relation.' as linked')
->whereIn('linked.'.$foreign, $this->publicStructureIds($relation, $foreign))->select('linked.opportunity_id'));
}
}
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) {
@@ -71,7 +94,17 @@ class InvestmentCatalogue
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('title', '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')
->where('search_location.name', 'ilike', $term)->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
->where(fn ($direct) => $direct->whereColumn('search_location.id', 'opportunities.primary_territory_id')
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations as search_link')->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereColumn('search_link.geo_location_id', 'search_location.id'))))
->orWhereExists(fn ($d) => $d->selectRaw('1')->from('investment_dossiers as searchable_dossier')
->whereNull('searchable_dossier.deleted_at')->where('searchable_dossier.publication_status', 'published')
->where(fn ($text) => $text->where('searchable_dossier.title', 'ilike', $term)->orWhereRaw('searchable_dossier.content::text ILIKE ?', [$term]))
->where(fn ($relation) => $relation
->whereExists(fn ($p) => $p->selectRaw('1')->from('opportunity_projects as search_project')->whereColumn('search_project.opportunity_id', 'opportunities.id')->whereColumn('search_project.project_id', 'searchable_dossier.project_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'])) {
$query->whereHas('sector', fn ($s) => $s->where('slug', $filters['sector']));
@@ -83,18 +116,42 @@ class InvestmentCatalogue
}
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
if (! empty($filters[$foreign])) {
$query->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')
->when($relation === 'locations', fn ($q) => $q->where('target.data_classification', 'public'),
fn ($q) => $q->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign))));
$locationIds = $relation === 'locations'
? app(InvestmentGeography::class)->descendants((string) $filters[$foreign])
: null;
if ($relation === 'locations') {
$query->where(function ($matches) use ($locationIds, $filters) {
$matches->whereIn('opportunities.primary_territory_id', $locationIds ?? [])
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_locations as link')
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
}
});
continue;
}
if (in_array($relation, ['clusters', 'corridors'], true)) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])
->whereIn('link.'.$foreign, $this->publicStructureIds($relation, $foreign)));
} else {
$query->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')
->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign)));
}
}
}
if (! empty($filters['education'])) {
$query->where(fn ($q) => $q->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('is_education', true))
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('education_investment_proposals')->whereColumn('opportunity_id', 'opportunities.id')->whereNull('deleted_at')));
}
foreach ($filters['facets'] ?? [] as $option) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_facets')->whereColumn('opportunity_id', 'opportunities.id')->where('option_id', $option));
$facetGroups = DB::table('investment_reference_options')->whereIn('id', $filters['facets'] ?? [])->get(['id', 'group'])->groupBy('group');
foreach ($facetGroups as $options) {
$optionIds = $options->pluck('id')->all();
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_facets')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('option_id', $optionIds));
}
foreach (['min_amount' => '>=', 'max_amount' => '<='] as $field => $operator) {
if (isset($filters[$field])) {
@@ -117,8 +174,9 @@ class InvestmentCatalogue
};
}
/** @return array<string,mixed> */
public function references(bool $management = false): array
/** @param array<string,mixed> $territoryFilters
* @return array<string,mixed> */
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(),
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug'])];
@@ -127,6 +185,8 @@ class InvestmentCatalogue
if (! $management) {
if ($relation === 'locations') {
$query->where('data_classification', 'public');
} elseif (in_array($relation, ['clusters', 'corridors'], true)) {
$query->whereIn('id', $this->publicStructureIds($relation, $foreign));
} else {
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
}
@@ -134,11 +194,25 @@ class InvestmentCatalogue
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
}
$result['zones'] = app(InvestmentZones::class)->visible()->orderBy('name')->get(['id', 'name', 'category']);
$zones = app(InvestmentZones::class)->visible();
if (! $management && $territoryFilters !== []) {
$zones = app(InvestmentZones::class)->search($territoryFilters);
}
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
return $result;
}
private function publicStructureIds(string $relation, string $foreign): \Illuminate\Database\Query\Builder
{
$table = self::RELATIONS[$relation][1];
return DB::table($table)->whereNull('deleted_at')->where(function ($query) use ($foreign): void {
$query->where('data_classification', 'public')
->orWhereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign));
})->select('id');
}
/** @return array<string,mixed> */
public function context(int $id, bool $management = false): array
{
@@ -155,12 +229,23 @@ class InvestmentCatalogue
}
}
$result[$relation] = $query->get(['t.id', 't.name']);
if (in_array($relation, ['projects', 'clusters'], true)) {
$result[$relation] = $result[$relation]->map(function ($entity) use ($foreign, $management) {
$dossiers = ($management ? InvestmentDossier::query() : InvestmentPortfolioController::visible())->where($foreign, $entity->id)->get();
$entity->dossiers = $dossiers->map(fn ($dossier) => ['id' => $dossier->id, 'title' => $dossier->title, 'source' => $dossier->source]);
$entity->geography = $dossiers->first() ? app(InvestmentRelations::class)->dossier($dossiers->first(), $management) : null;
return $entity;
});
}
}
$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)
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
$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['source_evidence'] = app(InvestmentTerritorialTraceability::class)->sources('opportunities', $id);
return $result;
}
@@ -174,19 +259,46 @@ class InvestmentCatalogue
$records = $this->query($filters)->limit(1000)->get();
$total = $this->query($filters)->reorder()->count();
$ids = $records->pluck('id');
$points = DB::table('opportunities as o')->join('geo_locations as g', function ($join) {
$spatial = DB::table('opportunities as o')->join('geo_locations as g', function ($join) use ($filters) {
$join->on('g.id', '=', 'o.primary_territory_id')->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_locations as l')->whereColumn('l.opportunity_id', 'o.id')->whereColumn('l.geo_location_id', 'g.id'));
if (($filters['territory_basis'] ?? 'all') === 'direct') {
return;
}
$join->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_projects as map_project')
->join('projects as p', 'p.id', '=', 'map_project.project_id')->whereColumn('map_project.opportunity_id', 'o.id')->whereNull('p.deleted_at')
->whereNotIn('p.data_classification', ['confidential', 'restricted'])->whereIn('p.id', app(InvestmentRelations::class)->projectIds())
->where(fn ($site) => $site->whereColumn('p.primary_territory_id', 'g.id')
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as map_location')
->whereColumn('map_location.project_id', 'p.id')->whereColumn('map_location.geo_location_id', 'g.id')
->whereNull('map_location.deleted_at')->where('map_location.data_classification', 'public')->where('map_location.role', '!=', 'impact'))));
})->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')
->whereIn('o.id', $ids)->where('g.data_classification', 'public')->where('shape.data_classification', 'public')
->where('g.location_type', 'site')->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')
->whereNull('g.deleted_at')->whereNull('shape.deleted_at')
->whereRaw("NOT EXISTS (WITH RECURSIVE parents AS (
SELECT id,parent_id,deleted_at,data_classification,ARRAY[id] AS visited,false AS cycle FROM geo_locations WHERE id=g.id
UNION ALL SELECT p.id,p.parent_id,p.deleted_at,p.data_classification,a.visited||p.id,p.id=ANY(a.visited)
FROM geo_locations p JOIN parents a ON p.id=a.parent_id WHERE NOT a.cycle
) SELECT 1 FROM parents WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
->whereRaw('ST_IsValid(shape.geom) AND NOT ST_IsEmpty(shape.geom) AND ST_SRID(shape.geom)=4326')
->whereRaw('ST_IsValid(shape.geom) AND NOT ST_IsEmpty(shape.geom) AND ST_SRID(shape.geom)=4326');
$points = (clone $spatial)->where('g.location_type', 'site')->where('shape.geometry_type', 'point')
->whereRaw('ST_X(shape.geom) BETWEEN -180 AND 180 AND ST_Y(shape.geom) BETWEEN -90 AND 90')
->orderBy('o.id')->orderByRaw("CASE WHEN g.source_system='investment-site-editor' THEN 0 ELSE 1 END")->orderBy('g.id')->orderBy('shape.id')
->get(['o.id', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')])->unique('id')->keyBy('id');
->get(['o.id', 'g.name', 'g.id as location_id', 'shape.source_system', 'shape.properties', DB::raw('ST_AsGeoJSON(shape.geom) as geometry'),
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 'opportunity_site' ELSE 'linked_project_site' END as location_basis")])
->groupBy('id')->map(function ($candidates) {
// Several sites are legitimate; only conflicting coordinates for the same site are withheld.
$sites = [];
foreach ($candidates->groupBy('location_id') as $site) {
if ($site->unique('geometry')->count() === 1) {
foreach ($site as $candidate) {
$sites[] = $candidate;
break;
}
}
}
return $sites;
})->filter();
$relations = [];
foreach (['clusters', 'corridors', 'projects'] as $relation) {
[$foreign, $table] = self::RELATIONS[$relation];
@@ -196,21 +308,35 @@ class InvestmentCatalogue
->get(['l.opportunity_id', 't.name'])->groupBy('opportunity_id');
}
$features = $missing = [];
$areas = (clone $spatial)->whereIn('shape.geometry_type', ['polygon', 'multipolygon'])->orderBy('shape.id')
->get(['o.id', 'o.title', 'o.slug', 'g.name', 'shape.source_system', 'shape.properties', DB::raw('ST_AsGeoJSON(shape.geom) as geometry'),
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.')',
'source_reference' => $area->source_system, 'source_date' => json_decode($area->properties ?? '{}', true)['source_date'] ?? null,
'url' => '/oportunidades/'.$area->slug])->all();
$located = 0;
foreach ($records as $record) {
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug];
foreach ($relations as $relation => $groups) {
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
}
if ($point = $points->get($record->id)) {
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties, 'location' => trim($properties['location'].' — '.$point->name)]];
$sites = collect($points->get($record->id) ?? []);
if ($sites->isNotEmpty()) {
$located++;
foreach ($sites as $point) {
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties,
'location_id' => $point->location_id, 'source_reference' => $point->source_system,
'source_date' => json_decode($point->properties ?? '{}', true)['source_date'] ?? null,
'location_basis' => $point->location_basis, 'location' => $point->name.($point->location_basis === 'linked_project_site' ? ' (local do projecto associado; contexto territorial)' : ' (implantação cadastrada da oportunidade)')]];
}
} else {
$missing[] = [...$properties, 'reason' => 'missing_public_site_coordinates'];
}
}
return ['type' => 'FeatureCollection', 'limit' => 1000, 'matched_count' => $total, 'truncated' => $total > $records->count(),
'georeferenced_count' => count($features), 'unlocated' => $missing, 'features' => $features,
'complete' => $total === count($features)];
'georeferenced_count' => $located, 'marker_count' => count($features), 'unlocated' => $missing, 'features' => $features,
'areas' => $areas, 'complete' => $total === $located];
}
}
+135 -2
View File
@@ -2,6 +2,8 @@
namespace App\Services;
use App\Models\InvestmentDossier;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
@@ -10,6 +12,55 @@ final class InvestmentGeography
{
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
/**
* Restrict published dossier searches using direct territories and public, validated structure links.
*
* @param EloquentBuilder<InvestmentDossier> $query
* @param list<string> $territoryIds
* @return EloquentBuilder<InvestmentDossier>
*/
public function constrainDossiersToTerritories(EloquentBuilder $query, array $territoryIds): EloquentBuilder
{
return $query->where(function ($matches) use ($territoryIds): void {
$matches->orWhereExists(fn ($coverage) => $coverage->selectRaw('1')->from('economic_clusters as coverage_cluster')
->whereColumn('coverage_cluster.id', 'investment_dossiers.cluster_id')->whereNull('coverage_cluster.deleted_at')
->whereRaw(app(InvestmentRelations::class)->coverageSql('coverage_cluster.metadata', $territoryIds), $territoryIds));
$matches->orWhereExists(fn ($member) => $member->selectRaw('1')->fromSub(app(InvestmentRelations::class)->memberships()->select(['cp.cluster_id', 'cp.project_id']), 'documented_member')
->join('projects as member_project', 'member_project.id', '=', 'documented_member.project_id')
->whereColumn('documented_member.cluster_id', 'investment_dossiers.cluster_id')
->where(fn ($area) => $area->whereIn('member_project.primary_territory_id', $territoryIds)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as member_location')
->whereColumn('member_location.project_id', 'member_project.id')->whereNull('member_location.deleted_at')
->where('member_location.data_classification', 'public')->whereIn('member_location.geo_location_id', $territoryIds))));
$matches->orWhereIn('project_id', DB::table('projects')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as pl')
->whereColumn('pl.project_id', 'investment_dossiers.project_id')->whereNull('pl.deleted_at')
->where('pl.data_classification', 'public')->whereIn('pl.geo_location_id', $territoryIds))
->orWhereIn('cluster_id', DB::table('economic_clusters')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
->orWhereIn('corridor_id', DB::table('development_corridors')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('corridor_locations as cl')
->whereColumn('cl.corridor_id', 'investment_dossiers.corridor_id')->whereNull('cl.deleted_at')
->where('cl.data_classification', 'public')->whereIn('cl.geo_location_id', $territoryIds));
foreach ([['cluster_projects', 'cluster_id'], ['corridor_projects', 'corridor_id']] as [$linkTable, $ownerColumn]) {
$matches->orWhereExists(fn ($links) => $links->selectRaw('1')->from($linkTable.' as territorial_link')
->join('projects as linked_project', 'linked_project.id', '=', 'territorial_link.project_id')
->whereColumn('territorial_link.'.$ownerColumn, 'investment_dossiers.'.$ownerColumn)
->whereNull('territorial_link.deleted_at')->where('territorial_link.data_classification', 'public')
->where('territorial_link.validation_status', 'validated')
->whereDate('territorial_link.valid_from', '<=', today()->toDateString())
->where(fn ($validity) => $validity->whereNull('territorial_link.valid_until')->orWhereDate('territorial_link.valid_until', '>=', today()->toDateString()))
->whereNull('linked_project.deleted_at')->where('linked_project.status', '!=', 'draft')
->where(function ($projectArea) use ($territoryIds): void {
$projectArea->whereIn('linked_project.primary_territory_id', $territoryIds)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as linked_location')
->whereColumn('linked_location.project_id', 'linked_project.id')->whereNull('linked_location.deleted_at')
->where('linked_location.data_classification', 'public')->whereIn('linked_location.geo_location_id', $territoryIds));
}));
}
});
}
public function publicReferences(): Builder
{
return DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification', 'public')
@@ -33,6 +84,73 @@ final class InvestmentGeography
: $this->publicReferences();
}
/** @param array<string,mixed> $payload
* @return list<list<string>>
*/
public function displayPaths(array $payload): array
{
$locations = [];
if (($payload['geography_scope'] ?? null) === 'multiple') {
$decoded = json_decode((string) ($payload['locations_json'] ?? ''), true);
$locations = is_array($decoded) ? $decoded : [];
} elseif (($payload['geography_scope'] ?? null) === 'specific') {
$locations = [array_intersect_key($payload, array_flip(array_keys(self::FIELDS)))];
} else {
return [];
}
$leafIds = [];
foreach ($locations as $location) {
$leafIds[] = is_array($location)
? ($location['locality_id'] ?? $location['admin_post_id'] ?? $location['district_id'] ?? $location['province_id'] ?? null)
: null;
}
$selected = array_filter($leafIds, fn ($id) => is_string($id) && $id !== '');
if (! $selected) {
return array_fill(0, count($locations), []);
}
$values = [];
$bindings = [];
foreach ($selected as $index => $id) {
$values[] = '(?, ?::uuid)';
$bindings[] = $index;
$bindings[] = $id;
}
$rows = DB::select('WITH RECURSIVE selected(location_index, id) AS (VALUES '.implode(',', $values).'),
tree AS (
SELECT s.location_index, g.id, g.name, g.location_type, g.parent_id, ARRAY[g.id] AS visited, 0 AS depth
FROM selected s JOIN geo_locations g ON g.id=s.id
UNION ALL
SELECT tree.location_index, parent.id, parent.name, parent.location_type, parent.parent_id,
tree.visited||parent.id, tree.depth+1
FROM tree JOIN geo_locations parent ON parent.id=tree.parent_id
WHERE tree.depth<4 AND NOT parent.id=ANY(tree.visited)
)
SELECT location_index, id, name, location_type FROM tree ORDER BY location_index, depth DESC', $bindings);
$nodeIds = array_values(array_unique(array_map(fn ($row) => (string) $row->id, $rows)));
$trustedIds = $this->publicReferences()->whereIn('id', $nodeIds)->pluck('id')->map(fn ($id) => (string) $id)->all();
$trusted = array_fill_keys($trustedIds, true);
$grouped = [];
foreach ($rows as $row) {
$grouped[(int) $row->location_index][] = $row;
}
$display = [];
foreach ($locations as $index => $_location) {
$path = $grouped[$index] ?? [];
if (! $path || array_filter($path, fn ($node) => ! isset($trusted[(string) $node->id]))) {
$display[] = [];
continue;
}
$display[] = array_values(array_map(fn ($node) => (string) $node->name,
array_filter($path, fn ($node) => $node->location_type !== 'country')));
}
return $display;
}
/** @param array<string,mixed> $input
* @return list<\stdClass>
*/
@@ -59,7 +177,7 @@ final class InvestmentGeography
}
/** @return list<string> */
public function descendants(string $id): array
public function descendants(string $id, bool $includeNonPublic = false): array
{
$rows = DB::select('WITH RECURSIVE tree AS (
SELECT id, ARRAY[id] AS visited FROM geo_locations WHERE id=? AND deleted_at IS NULL
@@ -67,7 +185,22 @@ final class InvestmentGeography
WHERE g.deleted_at IS NULL AND NOT g.id=ANY(tree.visited) AND cardinality(tree.visited)<5
) SELECT id FROM tree', [$id]);
return array_values($this->publicReferences()->whereIn('id', array_map(fn ($row) => $row->id, $rows))->pluck('id')->map(fn ($id) => (string) $id)->all());
$query = $includeNonPublic
? DB::table('geo_locations')->whereNull('deleted_at')
: $this->publicReferences();
$treeIds = array_map(fn ($row) => $row->id, $rows);
$ids = $query->whereIn('id', $treeIds)->pluck('id')->map(fn ($id) => (string) $id)->all();
if (! $includeNonPublic) {
// Documented sites need not be administrative registry entries themselves.
// Their parent must belong to the same public, trusted administrative hierarchy.
$sites = DB::table('geo_locations')->whereIn('id', $treeIds)->where('location_type', 'site')
->whereNull('deleted_at')->where('data_classification', 'public')
->whereIn('parent_id', $this->publicReferences()->select('id'))->pluck('id')->all();
$ids = array_merge($ids, $sites);
}
return array_values(array_unique($ids));
}
/** @return list<\stdClass> */
+202
View File
@@ -0,0 +1,202 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
/** Resolve documented relationships without generating geography or spreading opportunity memberships. */
class InvestmentRelations
{
/** Directly declared opportunity territories; a link does not certify implantation.
* @return list<array<string,mixed>>
*/
public function opportunityLocations(int $id, bool $management = false): array
{
$record = DB::table('opportunities')->where('id', $id)->first();
$items = DB::table('opportunity_locations')->where('opportunity_id', $id)->pluck('geo_location_id')
->map(fn ($location) => ['id' => $location, 'role' => 'opportunity', 'source_reference' => null, 'source_date' => null])->values()->all();
if ($record?->primary_territory_id && ! collect($items)->contains('id', $record->primary_territory_id)) {
$items[] = ['id' => $record->primary_territory_id, 'role' => 'opportunity', 'source_reference' => null, 'source_date' => null];
}
return $this->locations(array_values($items), $management);
}
public function projectIds(): Builder
{
return InvestmentPortfolioController::visible()->whereNotNull('project_id')->select('project_id')->toBase();
}
public function memberships(): Builder
{
// Legacy proposal links are consultable when both dossiers disclose the exact project code.
// Their pending/legal status remains independent from permission to consult the source.
return DB::table('cluster_projects as cp')->join('projects as member', 'member.id', '=', 'cp.project_id')
->whereNull('cp.deleted_at')->whereNull('member.deleted_at')->whereNotIn('member.data_classification', ['confidential', 'restricted'])
->where('cp.validation_status', '!=', 'revoked')
->where(fn ($q) => $q->whereNull('cp.valid_from')->orWhereDate('cp.valid_from', '<=', today()))
->where(fn ($q) => $q->whereNull('cp.valid_until')->orWhereDate('cp.valid_until', '>=', today()))
->whereIn('cp.project_id', $this->projectIds())
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_dossiers as disclosed_cluster')
->whereColumn('disclosed_cluster.cluster_id', 'cp.cluster_id')->where('disclosed_cluster.publication_status', 'published')->whereNull('disclosed_cluster.deleted_at')
->where(fn ($authorized) => $authorized->where('cp.data_classification', 'public')
->orWhere(fn ($legacy) => $legacy->where('cp.source_system', 'upgrade-v4')
->whereRaw("(disclosed_cluster.content->>'anchors') ~ ('\\m' || member.code || '\\M')"))));
}
/** @return list<array<string,mixed>> */
public function projectLocations(string $id, bool $management = false): array
{
$project = DB::table('projects')->where('id', $id)->whereNull('deleted_at')->first();
if (! $project || (! $management && (in_array($project->data_classification, ['confidential', 'restricted'], true)
|| ! InvestmentPortfolioController::visible()->where('project_id', $id)->exists()))) {
return [];
}
$links = DB::table('project_locations')->where('project_id', $id)->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->orderBy('role')->get();
$items = [];
$metadata = json_decode($project->metadata, true);
foreach ($links as $link) {
$items[] = ['id' => $link->geo_location_id, 'role' => $link->role, 'relation_id' => $link->id,
'source_reference' => $metadata['documented_location_sources'][$link->geo_location_id.':'.$link->role]['source_reference'] ?? $link->source_system,
'source_quote' => $metadata['documented_location_sources'][$link->geo_location_id.':'.$link->role]['source_quote'] ?? null,
'external_id' => $link->external_id];
}
if ($project->primary_territory_id && ! collect($items)->contains(fn ($item) => $item['id'] === $project->primary_territory_id && $item['role'] === 'primary')) {
$items[] = ['id' => $project->primary_territory_id, 'role' => 'primary', 'source_reference' => $project->source_system, 'relation_id' => null];
}
return $this->locations($items, $management);
}
/** @param list<array<string,mixed>> $items
* @return list<array<string,mixed>> */
public function locations(array $items, bool $management = false): array
{
$result = [];
foreach ($items as $item) {
$path = app(InvestmentGeography::class)->path($item['id'], $management);
// Site nodes are not administrative references; use their documented parent path.
$site = DB::table('geo_locations')->where('id', $item['id'])->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->first();
if (! $site) {
continue;
}
if ($site->location_type === 'site') {
$path = app(InvestmentGeography::class)->path($site->parent_id, $management);
if ($site->parent_id && ! $path) {
continue;
}
} elseif (! $path) {
continue;
}
$shapes = DB::table('geo_geometries')->where('geo_location_id', $item['id'])->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))
->where('geometry_type', 'point')->whereRaw('ST_IsValid(geom) AND NOT ST_IsEmpty(geom) AND ST_SRID(geom)=4326')
->whereRaw('ST_X(geom) BETWEEN -180 AND 180 AND ST_Y(geom) BETWEEN -90 AND 90')
->orderBy('id')->get(['id', 'source_system', 'properties', DB::raw('ST_AsGeoJSON(geom) as geometry')]);
$coordinates = $shapes->map(fn ($shape) => ['geometry_id' => $shape->id, 'source_reference' => $shape->source_system,
'source_date' => json_decode($shape->properties ?? '{}', true)['source_date'] ?? null,
'geometry' => json_decode($shape->geometry, true)])->all();
$boundaries = DB::table('geo_geometries')->where('geo_location_id', $item['id'])->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))
->whereIn('geometry_type', ['polygon', 'multipolygon'])->whereRaw('ST_IsValid(geom) AND NOT ST_IsEmpty(geom) AND ST_SRID(geom)=4326')
->get(['id', 'source_system', 'properties', DB::raw('ST_AsGeoJSON(geom) as geometry')])
->map(fn ($shape) => ['geometry_id' => $shape->id, 'source_reference' => $shape->source_system,
'source_date' => json_decode($shape->properties ?? '{}', true)['source_date'] ?? null, 'geometry' => json_decode($shape->geometry, true)])->all();
$result[] = [...$item, 'name' => $site->name, 'location_type' => $site->location_type, 'path' => $path, 'coordinates' => $coordinates, 'boundaries' => $boundaries];
}
return $result;
}
/** @return array<string,mixed> */
public function dossier(InvestmentDossier $dossier, bool $management = false): array
{
$result = ['locations' => [], 'members' => [], 'clusters' => [], 'chainLinks' => [], 'chains' => [],
'source_evidence' => app(InvestmentTerritorialTraceability::class)->sources($dossier->project_id ? 'projects' : 'economic_clusters', $dossier->project_id ?? $dossier->cluster_id ?? '')];
if ($dossier->project_id) {
$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']);
foreach ($memberships as $membership) {
foreach (InvestmentPortfolioController::visible()->where('cluster_id', $membership->cluster_id)->get() as $cluster) {
$result['clusters'][] = ['id' => $cluster->cluster_id, 'dossier_id' => $cluster->id, 'title' => $cluster->title,
'role' => $membership->role, 'validation_status' => $membership->validation_status, 'source_reference' => $membership->source_reference ?? $cluster->source];
}
}
}
if ($dossier->cluster_id) {
$result['chains'] = DB::table('value_chains')->where('cluster_id', $dossier->cluster_id)->whereNull('deleted_at')
->when(! $management, fn ($q) => $q->where('data_classification', 'public'))->orderBy('code')->get(['id', 'code', 'name', 'stage'])->all();
$cluster = DB::table('economic_clusters')->where('id', $dossier->cluster_id)->first();
$metadata = json_decode($cluster->metadata ?? '{}', true);
$coverage = array_values(array_filter($metadata['documented_coverage'] ?? [], fn ($item) => isset($item['id'], $item['source_reference']) && ($management || ($item['data_classification'] ?? '') === 'public')));
if ($cluster?->primary_territory_id) {
$coverage[] = ['id' => $cluster->primary_territory_id, 'role' => 'coverage', 'source_reference' => $cluster->source_system];
}
$result['locations'] = $this->locations($coverage, $management);
foreach ($this->memberships()->where('cp.cluster_id', $dossier->cluster_id)->get(['cp.project_id', 'member.code', 'member.name', 'cp.role', 'cp.validation_status', 'cp.source_reference']) as $member) {
$projectDossier = InvestmentPortfolioController::visible()->where('project_id', $member->project_id)->first();
if ($projectDossier) {
$result['members'][] = ['id' => $member->project_id, 'dossier_id' => $projectDossier->id, 'title' => $projectDossier->title,
'code' => $member->code, 'role' => $member->role, 'validation_status' => $member->validation_status,
'source_reference' => $member->source_reference ?? $dossier->source, 'locations' => $this->projectLocations($member->project_id, $management)];
}
}
$result['chainLinks'] = DB::table('value_chain_links as link')->join('value_chains as origin', 'origin.id', '=', 'link.from_value_chain_id')
->join('value_chains as destination', 'destination.id', '=', 'link.to_value_chain_id')
->where('origin.cluster_id', $dossier->cluster_id)->where('destination.cluster_id', $dossier->cluster_id)
->whereNull('link.deleted_at')->whereNull('origin.deleted_at')->whereNull('destination.deleted_at')
->when(! $management, fn ($q) => $q->where('link.data_classification', 'public')->where('origin.data_classification', 'public')->where('destination.data_classification', 'public'))
->get(['link.id', 'origin.name as origin', 'destination.name as destination', 'link.link_type'])->all();
}
return $result;
}
/** Add explicitly linked project and cluster member territories without creating opportunity-project links.
* @param Builder|\Illuminate\Database\Eloquent\Builder<Opportunity> $query
* @param list<string> $ids */
public function opportunityTerritories(Builder|\Illuminate\Database\Eloquent\Builder $query, array $ids): void
{
$query->orWhereExists(fn ($links) => $links->selectRaw('1')->from('opportunity_projects as geographic_project')
->join('projects as documented_project', 'documented_project.id', '=', 'geographic_project.project_id')
->whereColumn('geographic_project.opportunity_id', 'opportunities.id')->whereNull('documented_project.deleted_at')
->whereIn('documented_project.id', $this->projectIds())
->where(fn ($area) => $area->whereIn('documented_project.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as documented_location')
->whereColumn('documented_location.project_id', 'documented_project.id')->whereNull('documented_location.deleted_at')
->where('documented_location.data_classification', 'public')->whereIn('documented_location.geo_location_id', $ids))));
$query->orWhereExists(fn ($links) => $links->selectRaw('1')->from('opportunity_clusters as geographic_cluster')
->join('economic_clusters as documented_cluster', 'documented_cluster.id', '=', 'geographic_cluster.cluster_id')
->whereColumn('geographic_cluster.opportunity_id', 'opportunities.id')->whereNull('documented_cluster.deleted_at')
->whereIn('documented_cluster.id', InvestmentPortfolioController::visible()->whereNotNull('cluster_id')->select('cluster_id'))
->where(fn ($area) => $area->whereIn('documented_cluster.primary_territory_id', $ids)
->orWhereRaw($this->coverageSql('documented_cluster.metadata', $ids), $ids)
->orWhereExists(fn ($members) => $members->selectRaw('1')->fromSub($this->memberships()->select(['cp.cluster_id', 'cp.project_id']), 'territorial_member')
->join('projects as member_project', 'member_project.id', '=', 'territorial_member.project_id')->whereColumn('territorial_member.cluster_id', 'documented_cluster.id')
->where(fn ($territory) => $territory->whereIn('member_project.primary_territory_id', $ids)
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as member_location')
->whereColumn('member_location.project_id', 'member_project.id')->whereNull('member_location.deleted_at')
->where('member_location.data_classification', 'public')->whereIn('member_location.geo_location_id', $ids))))));
}
/** @param list<string> $ids */
public function coverageSql(string $column, array $ids): string
{
if (! in_array($column, ['documented_cluster.metadata', 'coverage_cluster.metadata'], true)) {
throw new \InvalidArgumentException('Unsupported coverage column');
}
if (! $ids) {
return 'false';
}
return "EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof({$column}->'documented_coverage')='array' THEN {$column}->'documented_coverage' ELSE '[]'::jsonb END) AS coverage_entry
WHERE coverage_entry->>'data_classification'='public' AND NULLIF(coverage_entry->>'source_reference','') IS NOT NULL
AND coverage_entry->>'id' IN (".implode(',', array_fill(0, count($ids), '?')).'))';
}
}
@@ -0,0 +1,213 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** @phpstan-type RepairPlan array{target:array<string,mixed>,locations:list<array<string,mixed>>,memberships:list<array<string,mixed>>,pending:list<array<string,mixed>>,prepared_opportunities:list<array<string,mixed>>} */
class InvestmentRelationshipRepair
{
public function directory(): string
{
return config('investment.repair_directory', storage_path('app/private/anchor-project-reconciliation'));
}
/** @return array{hash:string,plan:RepairPlan,territorial:list<array<string,mixed>>,history:list<array<string,mixed>>,unproposed:list<array<string,mixed>>} */
public function preview(): array
{
$file = $this->directory().'/preview.json';
abort_unless(is_file($file), 404, 'Pré-visualização não preparada.');
$contents = file_get_contents($file);
abort_if($contents === false, 503, 'Pré-visualização não pode ser lida.');
$hash = hash('sha256', $contents);
$plan = $this->decodePlan($contents);
$history = $this->history($hash);
$validation = app(InvestmentTerritorialValidation::class);
$territorial = [];
foreach ($plan['locations'] as $row) {
$result = $validation->validate($row);
$result['applied'] = $this->wasApplied($history, $result['row_id']);
$result['validation_hash'] = hash('sha256', json_encode($result, JSON_THROW_ON_ERROR));
$territorial[] = $result;
}
$unproposed = [];
foreach (array_unique(array_column($plan['pending'], 'code')) as $code) {
if (! preg_match('/^A\d{2}$/', $code) || collect($plan['locations'])->contains('code', $code)) {
continue;
}
$project = DB::table('projects')->where('code', $code)->whereNull('deleted_at')->first();
if (! $project) {
continue;
}
$dossier = DB::table('investment_dossiers')->where('project_id', $project->id)->whereNull('deleted_at')->first();
$unproposed[] = ['code' => $code, 'current' => app(InvestmentRelations::class)->projectLocations($project->id, true),
'source' => $dossier?->source, 'location_text' => $dossier ? (json_decode($dossier->content, true)['location'] ?? null) : null,
'reasons' => collect($plan['pending'])->where('code', $code)->pluck('reason')->all()];
}
return ['hash' => $hash, 'plan' => $plan, 'territorial' => $territorial, 'history' => $history, 'unproposed' => $unproposed];
}
/** @return RepairPlan */
private function decodePlan(string $contents): array
{
$plan = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
abort_unless(is_array($plan) && is_array($plan['target'] ?? null) && is_array($plan['locations'] ?? null) && is_array($plan['memberships'] ?? null), 422, 'Plano de associações inválido.');
$target = [];
foreach ($plan['target'] as $key => $value) {
abort_unless(is_string($key), 422, 'Destino inválido.');
$target[$key] = $value;
}
return ['target' => $target, 'locations' => $this->decodeRows($plan['locations']), 'memberships' => $this->decodeRows($plan['memberships']),
'pending' => $this->decodeRows($plan['pending'] ?? []), 'prepared_opportunities' => $this->decodeRows($plan['prepared_opportunities'] ?? [])];
}
/** @return list<array<string,mixed>> */
private function decodeRows(mixed $rows): array
{
abort_unless(is_array($rows), 422, 'Linhas do plano inválidas.');
$result = [];
foreach ($rows as $row) {
abort_unless(is_array($row), 422, 'Linha do plano inválida.');
$item = [];
foreach ($row as $key => $value) {
abort_unless(is_string($key), 422, 'Campo do plano inválido.');
$item[$key] = $value;
}
$result[] = $item;
}
return $result;
}
/** @return list<array<string,mixed>> */
private function history(string $hash): array
{
return array_values(DB::table('audit_events as event')->leftJoin('users as actor', 'actor.id', '=', 'event.actor_user_id')
->where('event.source_system', 'documented-relations-repair')->whereRaw("event.after_data->>'plan_hash' = ?", [$hash])
->orderBy('event.created_at')->orderBy('event.id')->get(['event.id', 'event.created_at', 'event.actor_user_id', 'actor.name as actor_name', 'event.after_data'])
->map(fn ($event) => ['id' => $event->id, 'date' => $event->created_at, 'actor_id' => $event->actor_user_id, 'actor' => $event->actor_name,
'data' => json_decode($event->after_data, true)])->all());
}
/** @param list<array<string,mixed>> $history */
private function wasApplied(array $history, string $rowId): bool
{
foreach ($history as $event) {
if (! isset($event['data']['location_row_ids']) || in_array($rowId, $event['data']['location_row_ids'], true)) {
return true;
}
}
return false;
}
/** @return array<string,mixed> */
public function apply(string $hash, int $actor, ?string $rowId = null, ?string $validationHash = null): array
{
$preview = $this->preview();
abort_unless(hash_equals($preview['hash'], $hash), 409, 'Pré-visualização alterada. Reveja as associações.');
$proofFile = $this->directory().'/backup-proof.json';
abort_unless(is_file($proofFile), 422, 'Backup e restauro isolado ainda não verificados.');
$contents = file_get_contents($proofFile);
abort_if($contents === false, 503, 'Evidência de restauro não pode ser lida.');
$proof = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
$dumpHash = is_file($proof['dump_path'] ?? '') ? hash_file('sha256', $proof['dump_path']) : false;
abort_unless(($proof['restore_verified'] ?? false) && is_file($proof['dump_path'] ?? '')
&& $dumpHash !== false && hash_equals($proof['sha256'], $dumpHash), 422, 'Evidência de backup/restauro inválida.');
$plan = $preview['plan'];
$validation = app(InvestmentTerritorialValidation::class);
if ($rowId !== null) {
abort_unless(collect($plan['locations'])->contains(fn ($row) => $validation->rowId($row) === $rowId), 422, 'Associação não pertence ao plano.');
}
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
abort_unless($identity->database === $plan['target']['database'] && (int) $identity->port === (int) $plan['target']['port']
&& ($proof['target'] ?? null) === $plan['target'], 409, 'Base de destino diferente da pré-visualização e do backup.');
if (app()->environment('testing')) {
abort_unless(str_ends_with($identity->database, '_test') && (int) $identity->port === 55441, 409, 'QA exige base *_test isolada na porta 55441.');
}
return DB::transaction(function () use ($plan, $hash, $actor, $rowId, $validation, $validationHash): array {
DB::select('select pg_advisory_xact_lock(71026, 150000)');
$history = $this->history($hash);
if (($rowId !== null && $this->wasApplied($history, $rowId)) || ($rowId === null && collect($history)->contains(fn ($event) => ! isset($event['data']['location_row_ids']) || ($event['data']['batch_complete'] ?? false)))) {
return ['replayed' => true, 'locations_created' => 0, 'memberships_created' => 0];
}
DB::statement('LOCK TABLE geo_locations, geo_geometries IN SHARE MODE');
$created = $memberships = 0;
$projects = $appliedRows = $sources = $before = [];
foreach ($plan['locations'] as $row) {
$id = $validation->rowId($row);
if (($rowId !== null && $rowId !== $id) || $this->wasApplied($history, $id)) {
continue;
}
$territory = $validation->validate($row);
if ($rowId !== null) {
$territory['applied'] = false;
abort_unless($validationHash !== null && hash_equals(hash('sha256', json_encode($territory, JSON_THROW_ON_ERROR)), $validationHash), 409, 'Validação territorial alterada. Reveja a proposta.');
}
if ($territory['status'] !== 'grounded') {
abort_if($rowId !== null, 409, 'Associação pendente ou contraditória; não pode ser aplicada.');
continue;
}
$project = $projects[$row['project_id']] ?? DB::table('projects')->where('id', $row['project_id'])->whereNull('deleted_at')->lockForUpdate()->first();
$increments = collect($history)->filter(fn ($event) => in_array($row['project_id'], $event['data']['project_ids'] ?? [], true))->count();
abort_unless($project && (int) $project->version_no === (int) $row['expected_project_version'] + $increments, 409, 'Projecto alterado desde a pré-visualização.');
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($dossier && $dossier->project_id === $project->id && (int) $dossier->version_no === (int) $row['dossier_version'], 409, 'Dossier alterado.');
$content = json_decode($dossier->content, true);
abort_unless(($content['location'] ?? null) === $row['source_quote'] && $dossier->source === $row['source_reference'], 409, 'Citação documental alterada.');
abort_unless($row['data_classification'] !== 'public' || $dossier->publication_status === 'published', 409, 'Autorização de divulgação alterada.');
abort_unless(app(InvestmentGeography::class)->references(true)->where('id', $row['geo_location_id'])->exists(), 409, 'Referência territorial indisponível.');
$appliedRows[] = $id;
$before[] = ['row_id' => $id, 'project_id' => $project->id, 'current' => $territory['current']];
$sources[] = ['row_id' => $id, 'project_id' => $project->id, 'geo_location_id' => $row['geo_location_id'], 'role' => $row['role'],
'source_reference' => $row['source_reference'], 'source_quote' => $row['source_quote'], 'dossier_id' => $dossier->id, 'reason' => $row['reason']];
$key = ['project_id' => $project->id, 'geo_location_id' => $row['geo_location_id'], 'role' => $row['role']];
if (! DB::table('project_locations')->where($key)->whereNull('deleted_at')->exists()) {
DB::table('project_locations')->insert([...$key, 'id' => (string) Str::uuid(), 'source_system' => 'documented-relations-repair',
'external_id' => $row['dossier_id'].':'.$row['geo_location_id'].':'.$row['role'], 'data_classification' => $row['data_classification']]);
$metadata = json_decode($project->metadata, true);
$metadata['documented_location_sources'][$row['geo_location_id'].':'.$row['role']] = ['source_reference' => $row['source_reference'], 'source_quote' => $row['source_quote'], 'dossier_id' => $dossier->id, 'plan_hash' => $hash, 'reason' => $row['reason'], 'actor_user_id' => $actor, 'applied_at' => now()->toIso8601String()];
$project->metadata = json_encode($metadata, JSON_THROW_ON_ERROR);
$projects[$project->id] = $project;
$created++;
}
}
foreach ($projects as $project) {
DB::table('projects')->where('id', $project->id)->update(['metadata' => $project->metadata, 'version_no' => $project->version_no + 1]);
}
foreach ($rowId === null ? $plan['memberships'] : [] as $row) {
if ($row['existing_id']) {
continue;
}
$key = ['cluster_id' => $row['cluster_id'], 'project_id' => $row['project_id']];
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($dossier && $dossier->cluster_id === $row['cluster_id'] && (int) $dossier->version_no === (int) $row['dossier_version']
&& (json_decode($dossier->content, true)['anchors'] ?? null) === $row['source_quote'], 409, 'Fonte da relação do cluster alterada.');
abort_unless(DB::table('projects')->where('id', $row['project_id'])->where('code', $row['project_code'])->whereNull('deleted_at')->exists(), 409, 'Identidade do projecto alterada.');
if (! DB::table('cluster_projects')->where($key)->whereNull('deleted_at')->exists()) {
DB::table('cluster_projects')->insert([...$key, 'id' => (string) Str::uuid(), 'role' => $row['role'], 'source_system' => 'documented-relations-repair',
'source_reference' => $row['source_reference'], 'evidence_reference' => $row['dossier_id'], 'editor_id' => $actor,
'data_classification' => $dossier->publication_status === 'published' ? 'public' : 'internal', 'validation_status' => 'pending', 'association_type' => 'potential']);
$memberships++;
}
}
if (! $appliedRows && ! $memberships) {
return ['replayed' => true, 'locations_created' => 0, 'memberships_created' => 0];
}
DB::table('audit_events')->insert(['source_system' => 'documented-relations-repair', 'entity_type' => 'project_locations',
'actor_user_id' => $actor, 'action' => 'documented_relations_applied', 'before_data' => json_encode($before, JSON_THROW_ON_ERROR), 'after_data' => json_encode(['plan_hash' => $hash,
'locations_created' => $created, 'memberships_created' => $memberships, 'project_ids' => array_keys($projects),
'location_row_ids' => $appliedRows, 'sources' => $sources,
'batch_complete' => $rowId === null && count(array_filter($plan['locations'], fn ($row) => ! in_array($validation->rowId($row), $appliedRows, true) && ! $this->wasApplied($history, $validation->rowId($row)))) === 0], JSON_THROW_ON_ERROR)]);
return ['replayed' => false, 'locations_created' => $created, 'memberships_created' => $memberships];
});
}
}
@@ -0,0 +1,166 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\Opportunity;
use Illuminate\Support\Facades\DB;
/** Attach evidence to existing relationships; never grant legal approval or infer new geography. */
class InvestmentTerritorialTraceability
{
public function directory(): string
{
return config('investment.traceability_directory', storage_path('app/private/investmoz-v2'));
}
public function fingerprint(): string
{
return hash('sha256', implode('', array_map(fn ($file) => hash_file('sha256', base_path($file)), [
'app/Services/InvestmentTerritorialTraceability.php', 'app/Http/Controllers/InvestmentRelationshipRepairController.php',
'resources/js/components/territorial-traceability-plan.tsx', 'tools/investmoz-v2-prepare-territorial-plan.cjs',
])));
}
/** @return array<string,mixed>|null */
public function preview(): ?array
{
$file = $this->directory().'/territory-activation-plan.json';
if (! is_file($file)) {
return null;
}
$bytes = file_get_contents($file);
abort_if($bytes === false, 503, 'Plano não pode ser lido.');
$plan = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
abort_unless(is_array($plan) && ($plan['schema'] ?? null) === 1 && is_array($plan['rows'] ?? null), 422, 'Plano inválido.');
$hash = hash('sha256', $bytes);
$last = DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->where('after_data->plan_hash', $hash)->orderByDesc('occurred_at')->orderByDesc('id')->first();
return ['hash' => $hash, 'plan' => $plan, 'code_matches' => ($plan['code_hash'] ?? '') === $this->fingerprint(),
'applied' => $last?->action === 'traceability_applied', 'reversed' => $last?->action === 'traceability_reversed',
'history' => DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->orderByDesc('occurred_at')->limit(20)->get(['id', 'action', 'actor_user_id', 'occurred_at', 'after_data'])->map(function ($event) {
$data = json_decode($event->after_data, true);
return ['id' => $event->id, 'action' => $event->action, 'actor_user_id' => $event->actor_user_id, 'occurred_at' => $event->occurred_at, 'reason' => $data['reason'] ?? null];
})->all(), 'backup_ready' => $this->backupReady($plan['target'], $hash)];
}
/** @param array<string,mixed> $target */
private function backupReady(array $target, string $hash): bool
{
$file = $this->directory().'/territory-backup-proof.json';
if (! is_file($file)) {
return false;
}
$proof = json_decode(file_get_contents($file) ?: '{}', true);
return ($proof['restore_verified'] ?? false) === true && ($proof['reversal_verified'] ?? false) === true
&& ($proof['plan_hash'] ?? '') === $hash && ($proof['code_hash'] ?? '') === $this->fingerprint()
&& ($proof['target'] ?? []) === $target && strtotime($proof['verified_at'] ?? '') >= time() - 86400
&& is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
}
/** @param array<string,mixed> $guard */
private function checkGuard(array $guard): void
{
abort_unless(in_array($guard['table'] ?? '', ['projects', 'economic_clusters', 'investment_zones', 'opportunities', 'investment_dossiers', 'cluster_projects', 'project_locations', 'investment_zone_locations', 'investment_legal_sources'], true), 422, 'Tabela fora do plano permitido.');
$row = DB::table($guard['table'])->where('id', $guard['id'])->lockForUpdate()->first();
abort_unless($row !== null, 409, 'Registo do plano já não existe.');
foreach ($guard['expected'] as $field => $value) {
abort_unless(property_exists($row, $field) && ($row->$field === null ? $value === null : $value !== null && (string) $row->$field === (string) $value), 409, 'Registo alterado desde a pré-visualização: '.$guard['table'].'.'.$field);
}
}
/** @return array<string,mixed> */
public function apply(string $hash, int $actor, bool $reverse = false, ?string $reason = null): array
{
abort_if($reverse && trim($reason ?? '') === '', 422, 'Indique o motivo da reversão.');
$preview = $this->preview();
abort_unless($preview && hash_equals($preview['hash'], $hash) && $preview['code_matches'], 409, 'Plano ou código alterado. Reveja a pré-visualização.');
$plan = $preview['plan'];
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
abort_unless($identity->database === $plan['target']['database'] && (int) $identity->port === (int) $plan['target']['port'], 409, 'Destino diferente do plano.');
if (app()->environment('testing')) {
abort_unless(str_ends_with($identity->database, '_test') && (int) $identity->port === 55441, 409, 'QA exige base isolada.');
}
abort_unless($preview['backup_ready'], 422, 'Backup/restauro/reversão verificados e atualizados são necessários.');
return DB::transaction(function () use ($plan, $hash, $actor, $reverse, $reason) {
DB::select('SELECT pg_advisory_xact_lock(81026, 160000)');
$last = DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->where('after_data->plan_hash', $hash)->orderByDesc('occurred_at')->orderByDesc('id')->lockForUpdate()->first();
if ((! $reverse && $last?->action === 'traceability_applied') || ($reverse && $last?->action === 'traceability_reversed')) {
return ['replayed' => true, 'changed' => 0];
}
abort_if(! $reverse && $last?->action === 'traceability_reversed', 409, 'Plano revertido; prepare um novo plano com o estado atual.');
$before = [];
$applied = ['updates' => []];
if ($reverse) {
abort_unless($last?->action === 'traceability_applied', 409, 'Não há aplicação para reverter.');
$applied = json_decode($last->after_data, true);
foreach ($applied['updates'] as $update) {
$this->checkGuard(['table' => 'cluster_projects', 'id' => $update['id'], 'expected' => $update['after']]);
$values = $update['before'];
$values['version_no'] = $update['after']['version_no'] + 1;
DB::table('cluster_projects')->where('id', $update['id'])->update($values);
$before[] = ['id' => $update['id'], 'before' => $update['after'], 'after' => $values];
}
} else {
foreach ($plan['guards'] as $guard) {
$this->checkGuard($guard);
}
foreach ($plan['updates'] as $update) {
abort_unless($update['table'] === 'cluster_projects' && array_diff(array_keys($update['values']), ['source_reference', 'evidence_reference']) === [], 422, 'Alteração fora do âmbito da rastreabilidade.');
$row = DB::table('cluster_projects')->where('id', $update['id'])->first();
$after = [...$update['values'], 'version_no' => $row->version_no + 1];
$before[] = ['id' => $row->id, 'before' => ['source_reference' => $row->source_reference, 'evidence_reference' => $row->evidence_reference, 'version_no' => $row->version_no], 'after' => $after];
DB::table('cluster_projects')->where('id', $row->id)->update($after);
}
}
DB::table('audit_events')->insert(['source_system' => 'territory-traceability-v2', 'entity_type' => 'territorial_sources', 'actor_user_id' => $actor,
'action' => $reverse ? 'traceability_reversed' : 'traceability_applied', 'data_classification' => 'internal', 'occurred_at' => DB::raw('clock_timestamp()'),
'after_data' => json_encode(['plan_hash' => $hash, 'rows' => $plan['rows'], 'updates' => $before, 'reason' => $reverse ? trim($reason) : null, 'no_new_geography' => true, 'official_policy' => 'accepted_without_revalidation'], JSON_THROW_ON_ERROR)]);
return ['replayed' => false, 'changed' => $reverse ? count($applied['updates']) : count($before), 'associations' => count($plan['rows'])];
});
}
/** @return list<array<string,mixed>> */
public function sources(string $kind, string|int $id): array
{
$visible = match ($kind) {
'projects' => InvestmentPortfolioController::visible()->where('project_id', $id)->exists(),
'economic_clusters' => InvestmentPortfolioController::visible()->where('cluster_id', $id)->exists(),
'investment_zones' => app(InvestmentZones::class)->visible()->whereKey($id)->exists(),
'opportunities' => Opportunity::published()->whereKey($id)->exists(),
default => false,
};
if (! $visible) {
return [];
}
$events = DB::table('audit_events')->where('source_system', 'territory-traceability-v2')->orderBy('occurred_at')->orderBy('id')->get(['action', 'after_data']);
$plans = [];
foreach ($events as $event) {
$data = json_decode($event->after_data, true);
$plans[$data['plan_hash']] = $event->action === 'traceability_applied' ? $data['rows'] : [];
}
$sources = [];
foreach ($plans as $rows) {
foreach ($rows as $row) {
if ($row['kind'] === $kind && (string) $row['record_id'] === (string) $id && ($row['public'] ?? false)) {
if (! empty($row['dossier_id']) && ! InvestmentPortfolioController::visible()->whereKey($row['dossier_id'])->exists()) {
continue;
}
if (! empty($row['public_location_id']) && ! app(InvestmentRelations::class)->locations([['id' => $row['public_location_id'], 'role' => $row['role']]])) {
continue;
}
if (! empty($row['association_id']) && ! app(InvestmentRelations::class)->memberships()->where('cp.id', $row['association_id'])->exists()) {
continue;
}
$sources[] = array_intersect_key($row, array_flip(['association', 'role', 'source_reference', 'source_quote', 'supports', 'traceability', 'official_source_accepted', 'existing_validation']));
}
}
}
return $sources;
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
/** Validate only the territory explicitly proposed in the documentary plan. */
class InvestmentTerritorialValidation
{
/** @param array<string,mixed> $row */
public function rowId(array $row): string
{
return hash('sha256', json_encode($row, JSON_THROW_ON_ERROR));
}
/** @param array<string,mixed> $row
* @return array<string,mixed>
*/
public function validate(array $row): array
{
$issues = $warnings = $path = $visited = [];
$pending = false;
$project = DB::table('projects')->where('id', $row['project_id'])->whereNull('deleted_at')->first();
$dossier = DB::table('investment_dossiers')->where('id', $row['dossier_id'])->whereNull('deleted_at')->first();
if (! $project || ! $dossier || $dossier->project_id !== $row['project_id']) {
$issues[] = 'Projeto ou documento de origem indisponível ou de outra identidade.';
} elseif (($row['source_reference'] ?? '') === '' || ($row['source_quote'] ?? '') === '') {
$pending = true;
$warnings[] = 'Falta referência ou citação documental da localização.';
} elseif ($dossier->source !== $row['source_reference'] || (json_decode($dossier->content, true)['location'] ?? null) !== $row['source_quote']
|| (int) $dossier->version_no !== (int) $row['dossier_version']) {
$issues[] = 'Fonte, citação ou versão do dossier diverge da proposta.';
}
if (($row['data_classification'] ?? null) === 'public' && $dossier && $dossier->publication_status !== 'published') {
$issues[] = 'A autorização de divulgação do dossier já não corresponde à proposta pública.';
}
if (! in_array($row['role'] ?? null, ['primary', 'secondary', 'impact'], true)) {
$issues[] = 'Papel territorial inválido.';
}
$id = $row['geo_location_id'];
while ($id) {
if (isset($visited[$id])) {
$issues[] = 'Ciclo na hierarquia territorial.';
break;
}
$visited[$id] = true;
$node = DB::table('geo_locations')->where('id', $id)->first();
if (! $node || $node->deleted_at || ! in_array($node->data_classification, ['public', 'internal'], true)) {
$issues[] = 'Território ou antepassado indisponível para esta associação.';
break;
}
array_unshift($path, ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type]);
$id = $node->parent_id;
}
$levels = ['country' => 0, 'province' => 1, 'district' => 2, 'admin_post' => 3, 'locality' => 4, 'site' => 5];
$previous = null;
foreach ($path as $node) {
$level = $levels[$node['type']] ?? null;
if ($level === null || ($previous !== null && $level !== $previous + 1 && $node['type'] !== 'site')) {
$issues[] = 'Hierarquia incompatível: província → distrito → posto administrativo → localidade.';
}
$previous = $level;
}
if (! collect($path)->contains('type', 'province')) {
$pending = true;
$warnings[] = 'A hierarquia não identifica uma província.';
}
foreach (InvestmentGeography::FIELDS as $field => $type) {
if (isset($row[$field]) && ! collect($path)->contains(fn ($node) => $node['type'] === $type && $node['id'] === $row[$field])) {
$issues[] = 'O nível indicado em '.$field.' não pertence à hierarquia proposta.';
}
}
$points = DB::table('geo_geometries')->where('geo_location_id', $row['geo_location_id'])->whereNull('deleted_at')
->whereIn('data_classification', ['public', 'internal'])->where('geometry_type', 'point')
->get(['id', 'source_system', DB::raw('ST_AsGeoJSON(geom) as geometry'), DB::raw('ST_SRID(geom) as srid')]);
$coordinates = [];
foreach ($points as $point) {
$geometry = json_decode($point->geometry, true);
$coordinates[] = ['geometry_id' => $point->id, 'source' => $point->source_system, 'coordinates' => $geometry['coordinates'] ?? [], 'srid' => $point->srid];
}
if (isset($row['coordinates'])) {
$coordinates[] = ['geometry_id' => null, 'source' => $row['source_reference'], 'coordinates' => $row['coordinates'], 'srid' => 4326];
}
$checks = [];
foreach ($coordinates as $point) {
$xy = $point['coordinates'];
if (count($xy) < 2 || ! is_numeric($xy[0]) || ! is_numeric($xy[1]) || ! is_finite((float) $xy[0]) || ! is_finite((float) $xy[1])
|| abs((float) $xy[0]) > 180 || abs((float) $xy[1]) > 90 || (int) $point['srid'] !== 4326) {
$issues[] = 'Coordenadas inválidas ou sistema de referência incompatível com WGS84.';
continue;
}
$boundaries = DB::table('geo_geometries')->whereIn('geo_location_id', array_column($path, 'id'))->whereNull('deleted_at')
->whereIn('data_classification', ['public', 'internal'])->whereIn('geometry_type', ['polygon', 'multipolygon'])
->whereRaw('ST_IsValid(geom) AND NOT ST_IsEmpty(geom) AND ST_SRID(geom)=4326')
->select(['id', 'geo_location_id', 'source_system'])
->selectRaw('ST_Covers(geom, ST_SetSRID(ST_MakePoint(?, ?),4326)) as compatible', [(float) $xy[0], (float) $xy[1]])->get();
if ($boundaries->isEmpty()) {
$warnings[] = 'Coordenadas com formato válido; sem limites cartográficos documentados para confirmar inclusão territorial.';
}
foreach ($boundaries as $boundary) {
$checks[] = ['geometry_id' => $point['geometry_id'], 'territory_id' => $boundary->geo_location_id, 'source' => $boundary->source_system, 'compatible' => (bool) $boundary->compatible];
if (! $boundary->compatible) {
$issues[] = 'Coordenadas fora do território '.(collect($path)->firstWhere('id', $boundary->geo_location_id)['name'] ?? $boundary->geo_location_id).'.';
}
}
}
if (! $coordinates) {
$warnings[] = 'Sem coordenadas; a ausência não impede validar a localização documental.';
}
$current = [];
if ($project) {
$links = DB::table('project_locations')->where('project_id', $project->id)->whereNull('deleted_at')->get();
foreach ($links as $link) {
$location = DB::table('geo_locations')->where('id', $link->geo_location_id)->first();
$current[] = ['id' => $link->geo_location_id, 'name' => $location->name ?? 'Território indisponível', 'role' => $link->role,
'path' => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($link->geo_location_id, true))];
}
if ($project->primary_territory_id && ! collect($current)->contains(fn ($item) => $item['id'] === $project->primary_territory_id && $item['role'] === 'primary')) {
$location = DB::table('geo_locations')->where('id', $project->primary_territory_id)->first();
$current[] = ['id' => $project->primary_territory_id, 'name' => $location->name ?? 'Território indisponível', 'role' => 'primary',
'path' => array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($project->primary_territory_id, true))];
}
}
return ['row_id' => $this->rowId($row), 'status' => $issues ? 'contradictory' : ($pending ? 'pending' : 'grounded'),
'issues' => array_values(array_unique($issues)), 'warnings' => array_values(array_unique($warnings)), 'current' => $current,
'proposed' => ['id' => $row['geo_location_id'], 'name' => collect($path)->last()['name'] ?? ($row['name'] ?? 'Território indisponível'), 'role' => $row['role'], 'path' => $path],
'coordinates' => $coordinates, 'coordinate_checks' => $checks];
}
}
+118 -12
View File
@@ -6,6 +6,7 @@ use App\Models\InvestmentZone;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class InvestmentZones
@@ -25,12 +26,66 @@ class InvestmentZones
/** @return Builder<InvestmentZone> */
public function visible(): Builder
{
if (! Schema::hasColumn('investment_zones', 'source_evidence')) {
return InvestmentZone::query()->where('publication_status', 'published')->where('validation_status', 'validated')
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
->whereDate('source.valid_from', '<=', today())
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())));
}
return InvestmentZone::query()->where('publication_status', 'published')->where('validation_status', 'validated')
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
->whereDate('source.valid_from', '<=', today())
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())))
->whereExists(fn ($q) => $q->selectRaw('1')->from('organizations')->whereColumn('organizations.id', 'investment_zones.operator_id')->whereNull('organizations.deleted_at'));
->where(function (Builder $query): void {
$query->where(function (Builder $evidence): void {
$evidence->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(source_evidence) AS evidence WHERE evidence->>'source_type' IN ('government','institutional') AND evidence->>'url' LIKE 'https://%' AND length(trim(COALESCE(evidence->>'supports',''))) > 0)")
->orWhere(function (Builder $promoterEvidence): void {
// Industrial parks may be listed as informational projects on the promoter's own site.
// Their promoter source must remain visibly identified and does not validate legal status,
// authorized activities, operation, incentives, or land availability.
$promoterEvidence->where('category', 'industrial_park')
->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(source_evidence) AS evidence WHERE evidence->>'source_type' = 'promoter' AND evidence->>'url' LIKE 'https://%' AND length(trim(COALESCE(evidence->>'supports',''))) > 0)");
});
})->orWhereExists(fn ($source) => $source->selectRaw('1')->from('investment_legal_sources as source')
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
->whereDate('source.valid_from', '<=', today())
->where(fn ($valid) => $valid->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())));
});
}
/** @param array<string, mixed> $filters
* @return Builder<InvestmentZone> */
public function search(array $filters, bool $management = false): Builder
{
$query = $management ? InvestmentZone::query() : $this->visible();
if (! Schema::hasColumn('investment_zones', 'source_evidence')) {
unset($filters['physical_category'], $filters['legal_regime'], $filters['development_status'], $filters['availability_status']);
}
$path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) {
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->where(function ($matches) use ($territoryIds, $management): void {
$matches->whereIn('primary_territory_id', $territoryIds)
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('investment_zone_locations as zl')
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.geo_location_id', $territoryIds)
->where('zl.validation_status', 'validated')->where(fn ($valid) => $valid->whereNull('zl.valid_from')->orWhereDate('zl.valid_from', '<=', today()))
->where(fn ($valid) => $valid->whereNull('zl.valid_until')->orWhereDate('zl.valid_until', '>=', today())));
if (! $management) {
$matches->orWhereExists(fn ($geometry) => $geometry->selectRaw('1')->from('investment_zone_geometries as zg')
->join('geo_geometries as shape', 'shape.id', '=', 'zg.geometry_id')
->whereColumn('zg.zone_id', 'investment_zones.id')->where('zg.publication_authorized', true)
->where('zg.validation_status', 'validated')->whereNull('shape.deleted_at')
->where('shape.data_classification', 'public')->whereIn('shape.geo_location_id', $territoryIds));
}
});
}
return $query->when($filters['category'] ?? null, fn ($q, $value) => $q->where('category', $value))
->when($filters['physical_category'] ?? null, fn ($q, $value) => $q->where('physical_category', $value))
->when($filters['legal_regime'] ?? null, fn ($q, $value) => $q->where('legal_regime', $value))
->when($filters['development_status'] ?? null, fn ($q, $value) => $q->where('development_status', $value))
->when($filters['availability_status'] ?? null, fn ($q, $value) => $q->where('availability_status', $value))
->when($filters['activity'] ?? null, fn ($q, $value) => $q->whereRaw('activities @> ?::jsonb', [json_encode([['name' => $value]], JSON_THROW_ON_ERROR)]))
->when($filters['q'] ?? null, fn ($q, $value) => $q->where(fn ($q) => $q->where('name', 'ilike', '%'.$value.'%')->orWhere('code', 'ilike', '%'.$value.'%')));
}
/** @param array<string,mixed> $data */
@@ -40,9 +95,18 @@ class InvestmentZones
$zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone;
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;
unset($data['version_no']);
$locations = $data['locations'] ?? [];
unset($data['locations'], $data['version_no']);
$zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null,
'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save();
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(),
]);
}
$this->snapshot($zone, $actor, 'saved');
return $zone;
@@ -54,13 +118,31 @@ class InvestmentZones
return DB::transaction(function () use ($id, $version, $actor) {
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.');
abort_if((int) $zone->editor_id === $actor, 403, 'A revisão exige outro gestor autorizado.');
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Fonte jurídica válida e revista em falta.');
abort_unless($zone->category !== 'pending' && $zone->operator_id && trim((string) $zone->name_en) !== ''
&& trim((string) $zone->description) !== '' && trim((string) $zone->description_en) !== '', 422, 'Categoria, operador e conteúdo PT/EN são obrigatórios.');
abort_unless(DB::table('organizations')->where('id', $zone->operator_id)->whereNull('deleted_at')->exists(), 422, 'Operador indisponível.');
$evidence = $zone->source_evidence ?? [];
$officialEvidence = collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional'], true)
&& str_starts_with((string) ($item['url'] ?? ''), 'https://') && trim((string) ($item['supports'] ?? '')) !== '');
$promoterEvidence = $zone->category === 'industrial_park' && collect($evidence)->contains(fn ($item) => ($item['source_type'] ?? null) === 'promoter'
&& str_starts_with((string) ($item['url'] ?? ''), 'https://') && trim((string) ($item['supports'] ?? '')) !== '');
if (in_array($zone->category, ['zee', 'zfi'], true)) {
$legalSourceCurrent = $source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
&& (! $source->valid_until || $source->valid_until >= today()->toDateString());
abort_unless($officialEvidence || $legalSourceCurrent, 422, 'Registe uma fonte oficial ou institucional HTTPS que sustente a identidade e o enquadramento informativo.');
} else {
abort_unless($officialEvidence || $promoterEvidence, 422, 'Registe uma fonte HTTPS identificada que sustente a identidade e a localização informativa.');
}
abort_unless($zone->category !== 'pending' && trim((string) $zone->name) !== ''
&& trim((string) $zone->description) !== '', 422, 'Identidade, categoria e descrição são obrigatórias.');
abort_unless($zone->physical_category && $zone->physical_category !== 'unknown', 422, 'Categoria física por confirmar.');
if (in_array($zone->category, ['zee', 'zfi'], true)) {
abort_unless($zone->legal_regime === $zone->category, 422, 'O regime jurídico da ZEE/ZFI deve estar confirmado.');
}
$publicLocation = $zone->primary_territory_id
&& app(InvestmentGeography::class)->publicReferences()->where('id', $zone->primary_territory_id)->exists();
$publicLocation = $publicLocation || DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
->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();
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',
'validation_status' => 'validated', 'published_at' => now()])->save();
$this->snapshot($zone, $actor, 'published');
@@ -81,6 +163,30 @@ class InvestmentZones
});
}
public function validateLocation(string $id, int $version, int $actor): object
{
return DB::transaction(function () use ($id, $version, $actor) {
$location = DB::table('investment_zone_locations')->where('id', $id)->lockForUpdate()->first();
abort_unless($location !== null, 404);
abort_if((int) $location->version_no !== $version, 409, 'Version changed.');
abort_if((int) $location->editor_id === $actor, 403, 'Independent review required.');
abort_unless($location->validation_status === 'pending', 422, 'Territorial association already reviewed.');
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $location->geo_location_id)->exists(), 422, 'Territory is not a public reference location.');
if ($location->legal_source_id) {
$source = DB::table('investment_legal_sources')->where('id', $location->legal_source_id)->first();
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Location source is not valid.');
}
DB::table('investment_zone_locations')->where('id', $id)->update(['validation_status' => 'validated', 'reviewer_id' => $actor,
'version_no' => $version + 1, 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'investment-zones', 'entity_type' => 'investment_zone_locations',
'entity_id' => $id, 'actor_user_id' => $actor, 'action' => 'validated',
'after_data' => json_encode(['version_no' => $version + 1], JSON_THROW_ON_ERROR)]);
return DB::table('investment_zone_locations')->where('id', $id)->first();
});
}
private function snapshot(InvestmentZone $zone, int $actor, string $action): void
{
$json = $zone->toJson(JSON_THROW_ON_ERROR);
@@ -0,0 +1,54 @@
<?php
namespace App\Services\Malware;
final class ArchiveLimitInspector
{
public function inspect(string $path): ?string
{
$stream = @fopen($path, 'rb');
if (! is_resource($stream)) {
return 'archive_inspection_failed';
}
$signature = fread($stream, 4);
fclose($stream);
if (! is_string($signature) || ! in_array($signature, ["PK\x03\x04", "PK\x05\x06", "PK\x07\x08"], true)) {
return null;
}
if (! class_exists(\ZipArchive::class)) {
return 'archive_inspector_unavailable';
}
$archive = new \ZipArchive;
if ($archive->open($path, \ZipArchive::RDONLY) !== true) {
return 'archive_inspection_failed';
}
try {
$maxEntries = max(1, (int) config('services.malware.max_archive_entries', 1000));
$maxExpandedBytes = max(1, (int) config('services.malware.max_decompressed_bytes', 104857600));
if ($archive->numFiles > $maxEntries) {
return 'archive_entry_limit_exceeded';
}
$expandedBytes = 0;
for ($index = 0; $index < $archive->numFiles; $index++) {
$entry = $archive->statIndex($index);
if (! is_array($entry) || $entry['size'] < 0) {
return 'archive_inspection_failed';
}
if ($entry['size'] > $maxExpandedBytes - $expandedBytes) {
return 'archive_decompression_limit';
}
$expandedBytes += $entry['size'];
}
return null;
} finally {
$archive->close();
}
}
}
+234
View File
@@ -0,0 +1,234 @@
<?php
namespace App\Services\Malware;
use DateTimeImmutable;
use DateTimeZone;
use RuntimeException;
use Throwable;
final class ClamDScanner implements MalwareScanner
{
private string $engineVersion = '';
private ?DateTimeImmutable $signaturesAt = null;
public function health(): array
{
try {
$pong = $this->command('PING');
if ($pong !== 'PONG') {
return $this->unavailable('clamd_protocol_error');
}
$version = $this->command('VERSION');
if (! preg_match('/^ClamAV\s+([^\/\s]+)\/(\d+)\/(.+)$/', $version, $matches)) {
return $this->unavailable('signature_version_unavailable');
}
$dateText = preg_replace('/\s+/', ' ', trim($matches[3]));
$date = DateTimeImmutable::createFromFormat('D M j H:i:s Y', (string) $dateText, new DateTimeZone('UTC'));
if (! $date || $date->getTimestamp() > time() + 3600) {
return $this->unavailable('signature_date_invalid');
}
$ageHours = max(0, (time() - $date->getTimestamp()) / 3600);
$this->engineVersion = $matches[1];
$this->signaturesAt = $date;
if ($ageHours > (float) config('services.malware.max_signature_age_hours', 48)) {
return [
'available' => false, 'engine' => 'ClamAV', 'engine_version' => $this->engineVersion,
'signatures_at' => $date, 'signature_age_hours' => $ageHours, 'reason_code' => 'signatures_stale',
];
}
return [
'available' => true, 'engine' => 'ClamAV', 'engine_version' => $this->engineVersion,
'signatures_at' => $date, 'signature_age_hours' => $ageHours, 'reason_code' => null,
];
} catch (Throwable $exception) {
$reason = str_contains(strtolower($exception->getMessage()), 'timed out')
? 'scanner_timeout'
: 'scanner_unavailable';
return $this->unavailable($reason);
}
}
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
{
$startedAt = hrtime(true);
$health = $this->health();
if (! $health['available']) {
return $this->result('inconclusive', $health['reason_code'], $startedAt, null);
}
$root = realpath($storageRoot);
$resolved = realpath($path);
if (! $root || ! $resolved || ! is_file($resolved)
|| ! str_starts_with(strtolower($resolved), strtolower($root.DIRECTORY_SEPARATOR))) {
return $this->result('inconclusive', 'private_file_unavailable', $startedAt, null);
}
$actualSize = filesize($resolved);
if (! is_int($actualSize) || $actualSize !== $fileSizeBytes) {
return $this->result('inconclusive', 'file_size_changed', $startedAt, null);
}
if ($actualSize > (int) config('services.malware.max_file_bytes', 20 * 1024 * 1024)
|| $actualSize > (int) config('services.malware.max_stream_bytes', 25 * 1024 * 1024)) {
return $this->result('inconclusive', 'file_scan_limit_exceeded', $startedAt, null);
}
$archiveFailure = app(ArchiveLimitInspector::class)->inspect($resolved);
if ($archiveFailure !== null) {
return $this->result('inconclusive', $archiveFailure, $startedAt, null);
}
$socket = null;
$file = fopen($resolved, 'rb');
if (! is_resource($file)) {
return $this->result('inconclusive', 'private_file_unavailable', $startedAt, null);
}
try {
$socket = $this->connect();
$this->writeAll($socket, "zINSTREAM\0");
$sent = 0;
while (! feof($file)) {
$chunk = fread($file, 65536);
if ($chunk === false) {
throw new RuntimeException('The private file could not be streamed to clamd.');
}
if ($chunk === '') {
break;
}
$sent += strlen($chunk);
if ($sent > $actualSize || $sent > (int) config('services.malware.max_stream_bytes', 25 * 1024 * 1024)) {
return $this->result('inconclusive', 'stream_limit_exceeded', $startedAt, null);
}
$this->writeAll($socket, pack('N', strlen($chunk)).$chunk);
}
if ($sent !== $actualSize) {
return $this->result('inconclusive', 'file_size_changed', $startedAt, null);
}
$this->writeAll($socket, pack('N', 0));
$reply = $this->readReply($socket);
if (str_ends_with($reply, ': OK')) {
return $this->result('clean', null, $startedAt, null);
}
if (preg_match('/:\s(.+) FOUND$/', $reply, $matches)) {
$signature = $matches[1];
if (preg_match('/encrypted|password|limits?\.exceeded|oversized/i', $signature)) {
$reason = preg_match('/encrypted|password/i', $signature)
? 'encrypted_or_password_protected'
: 'scanner_decompression_limit';
return $this->result('inconclusive', $reason, $startedAt, $signature);
}
return $this->result('infected', 'threat_detected', $startedAt, $signature);
}
if (stripos($reply, 'size limit exceeded') !== false || stripos($reply, 'limit exceeded') !== false) {
return $this->result('inconclusive', 'scanner_decompression_limit', $startedAt, $reply);
}
throw new RuntimeException('ClamD returned an unrecognized scan response.');
} catch (Throwable $exception) {
$reason = str_contains(strtolower($exception->getMessage()), 'timed out')
? 'scanner_timeout'
: 'scanner_unavailable';
return $this->result('inconclusive', $reason, $startedAt, null);
} finally {
fclose($file);
if (is_resource($socket)) {
fclose($socket);
}
}
}
private function command(string $command): string
{
$socket = $this->connect();
try {
$this->writeAll($socket, 'z'.$command."\0");
return $this->readReply($socket);
} finally {
fclose($socket);
}
}
/** @return resource */
private function connect()
{
if (config('services.malware.scanner') !== 'clamd') {
throw new RuntimeException('No production scanner is configured.');
}
$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.');
}
$timeout = max(1, (int) config('services.malware.timeout_seconds', 120));
$socket = @stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage, min(10, $timeout));
if (! is_resource($socket)) {
throw new RuntimeException('ClamD is unavailable.');
}
stream_set_timeout($socket, $timeout);
return $socket;
}
/** @param resource $socket */
private function writeAll($socket, string $data): void
{
$offset = 0;
$length = strlen($data);
while ($offset < $length) {
$written = fwrite($socket, substr($data, $offset, 1024 * 1024));
if ($written === false || $written === 0) {
throw new RuntimeException('ClamD connection stopped accepting scan data.');
}
$offset += $written;
$meta = stream_get_meta_data($socket);
if ($meta['timed_out']) {
throw new RuntimeException('ClamD scan timed out while sending data.');
}
}
}
/** @param resource $socket */
private function readReply($socket): string
{
$reply = stream_get_line($socket, 65536, "\0");
$meta = stream_get_meta_data($socket);
if ($reply === false || $meta['timed_out']) {
throw new RuntimeException($meta['timed_out'] ? 'ClamD scan timed out.' : 'ClamD returned no scan result.');
}
return trim($reply);
}
/** @return array{available:bool,engine:string,engine_version:?string,signatures_at:?DateTimeImmutable,signature_age_hours:?float,reason_code:?string} */
private function unavailable(string $reason): array
{
return ['available' => false, 'engine' => 'ClamAV', 'engine_version' => null, 'signatures_at' => null,
'signature_age_hours' => null, 'reason_code' => $reason];
}
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:?DateTimeImmutable,duration_ms:int,detail:?string} */
private function result(string $result, ?string $reason, int $startedAt, ?string $detail): array
{
return [
'result' => $result, 'reason_code' => $reason, 'engine' => 'ClamAV',
'engine_version' => $this->engineVersion, 'signatures_at' => $this->signaturesAt,
'duration_ms' => (int) ((hrtime(true) - $startedAt) / 1_000_000), 'detail' => $detail,
];
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace App\Services\Malware;
interface MalwareScanner
{
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:?\DateTimeImmutable,duration_ms:int,detail:?string} */
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array;
/** @return array{available:bool,engine:string,engine_version:?string,signatures_at:?\DateTimeImmutable,signature_age_hours:?float,reason_code:?string} */
public function health(): array;
}
@@ -0,0 +1,94 @@
<?php
namespace App\Services;
use App\Jobs\ScanDocumentForMalware;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class OpportunityImageProcessor
{
public function available(): bool
{
return function_exists('imagecreatefromstring') && function_exists('imagewebp');
}
/** @param array<string,mixed> $input */
public function prepare(User $actor, int $opportunityId, string $id, array $input): void
{
abort_unless($actor->can('manage-portal'), 403);
abort_unless($this->available(), 423, 'GD/WebP não disponível neste processo. Original e metadados preservados; processamento pendente.');
$data = validator($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:20|max:1000'])->validate();
$stored = [];
$documents = [];
try {
DB::transaction(function () use ($actor, $opportunityId, $id, $data, &$stored, &$documents) {
$o = Opportunity::withTrashed()->whereKey($opportunityId)->lockForUpdate()->firstOrFail();
abort_if($o->trashed() || $o->status === 'archived', 409, 'Restaure antes de processar.');
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($o), $data['etag']), 409, 'Conflito de versão; preserve os dados.');
$image = DB::table('opportunity_images')->where('opportunity_id', $opportunityId)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($image !== null, 404);
abort_unless((int) $image->version === (int) $data['version'], 409, 'Imagem alterada.');
$doc = DB::table('documents')->where('id', $image->document_id)->first();
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && hash_equals(trim($doc->sha256), (string) $doc->malware_scanned_sha256), 423, 'Scan do original pendente ou inseguro.');
$disk = Storage::disk('local');
$bytes = $doc->storage_encryption === 'laravel' ? Crypt::decryptString($disk->get($doc->storage_key)) : $disk->get($doc->storage_key);
abort_unless(hash_equals(trim($doc->sha256), hash('sha256', $bytes)), 409, 'Integridade divergente.');
$size = @getimagesizefromstring($bytes);
abort_unless($size && $size[0] >= 400 && $size[1] >= 400 && $size[0] * $size[1] <= 40000000, 422, 'Dimensões inválidas ou imagem excessiva para processamento seguro.');
$decoded = @imagecreatefromstring($bytes);
abort_unless($decoded !== false, 422, 'Não foi possível descodificar a imagem.');
$derivatives = [];
try {
foreach (array_unique(array_map(fn ($width) => min($width, $size[0]), [320, 640, 1280])) as $width) {
$w = min($width, $size[0]);
$h = max(1, (int) round($size[1] * $w / $size[0]));
$canvas = imagecreatetruecolor($w, $h);
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
imagecopyresampled($canvas, $decoded, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);
ob_start();
$encoded = imagewebp($canvas, null, 85);
$webp = ob_get_clean();
imagedestroy($canvas);
abort_unless($encoded && is_string($webp), 500, 'Falha ao gerar WebP.');
$documentId = (string) Str::uuid();
$key = 'opportunity-resources/'.$documentId;
abort_unless($disk->put($key, Crypt::encryptString($webp)) === true, 500, 'Falha ao guardar derivada cifrada.');
$stored[] = $key;
$documents[] = $documentId;
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'opportunity-image-derivatives', 'file_name' => 'image-'.$width.'.webp', 'media_type' => 'image/webp', 'storage_key' => $key, 'storage_encryption' => 'laravel', 'sha256' => hash('sha256', $webp), 'status' => 'quarantined', 'data_classification' => 'restricted', 'size_bytes' => strlen($webp), 'uploaded_by' => $actor->id]);
$derivatives[] = ['document_id' => $documentId, 'width' => $w, 'height' => $h];
}
} finally {
imagedestroy($decoded);
}
$payload = json_decode($image->payload, true);
$payload['derivatives'] = $derivatives;
$payload['derived_from_sha256'] = trim($doc->sha256);
$payload['processing_status'] = 'generated_without_original_metadata';
DB::table('opportunity_images')->where('id', $id)->update(['payload' => json_encode($payload), 'version' => $image->version + 1, 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'opportunity-resources', 'entity_type' => 'images', 'action' => 'derivatives_prepared', 'actor_user_id' => $actor->id, 'data_classification' => 'restricted', 'before_data' => json_encode(['snapshot' => Crypt::encryptString(json_encode($image, JSON_THROW_ON_ERROR))]), 'after_data' => json_encode(['opportunity_id' => $opportunityId, 'resource_id' => $id, 'version' => $image->version + 1, 'reason' => Crypt::encryptString($data['reason']), 'snapshot' => Crypt::encryptString(json_encode(DB::table('opportunity_images')->where('id', $id)->first(), JSON_THROW_ON_ERROR))])]);
$o->management_version++;
$o->save();
});
} catch (\Throwable $error) {
foreach ($stored as $key) {
Storage::disk('local')->delete($key);
}
throw $error;
}
// Each new byte stream receives its own scan; no automatic clean result inherited from the original.
foreach ($documents as $documentId) {
try {
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
} catch (\Throwable) {
DB::table('documents')->where('id', $documentId)->update(['malware_scan_status' => 'failed', 'malware_failure_reason' => 'queue_dispatch_failed']);
}
}
}
}

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