Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60784a2ed2 | ||
|
|
7ecfe3d543 | ||
|
|
ebfc188240 | ||
|
|
ae789ce024 | ||
|
|
344545430b | ||
|
|
6c7a9c9442 | ||
|
|
6a71aa47e3 | ||
|
|
30acdc9934 | ||
|
|
51c7fb92b1 | ||
|
|
1106509116 | ||
|
|
bdd766c68a | ||
|
|
0a086c3fa5 | ||
|
|
59d108a576 | ||
|
|
e65cb26901 | ||
|
|
4f35313d06 | ||
|
|
a6afb4e97a | ||
|
|
cbae1ce77b | ||
|
|
5e6b32b493 | ||
|
|
3395424d82 | ||
|
|
3dc7c5c649 | ||
|
|
67dad461d9 |
+35
-6
@@ -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=
|
||||
@@ -66,6 +78,15 @@ VITE_APP_NAME="${APP_NAME}"
|
||||
|
||||
# Comma-separated emails of verified accounts authorised to manage the portal.
|
||||
PORTAL_MANAGER_EMAILS=
|
||||
# Explicit, separate application workflow designations. Empty means no access.
|
||||
INVESTMOZ_MNE_TRIAGERS=
|
||||
INVESTMOZ_MNE_REVIEWERS=
|
||||
INVESTMOZ_MNE_APPROVERS_L1=
|
||||
INVESTMOZ_MNE_APPROVERS_L2=
|
||||
INVESTMOZ_MNE_PUBLISHERS=
|
||||
INVESTMOZ_CONSENT_POLICY_VERSION=2026-09-30
|
||||
INVESTMOZ_SHARING_POLICY_VERSION=2026-09-30
|
||||
INVESTMOZ_SLA_ESCALATION_ENABLED=false
|
||||
PORTAL_NOTIFICATIONS_ENABLED=false
|
||||
PORTAL_NOTIFICATION_RECIPIENTS=
|
||||
PORTAL_SUPPORT_EMAIL=
|
||||
@@ -85,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=
|
||||
|
||||
Binary file not shown.
@@ -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
|
||||
@@ -66,5 +66,10 @@ jobs:
|
||||
- name: Run CI Checks
|
||||
run: composer ci:check
|
||||
|
||||
- name: Test frontend API contracts
|
||||
run: node --test tests/frontend/portal-api.test.mjs
|
||||
- name: Validate PostgreSQL/PostGIS schema lifecycle
|
||||
env:
|
||||
INVESTMOZ_SCHEMA_TESTS: '1'
|
||||
run: php vendor/bin/phpunit --configuration=phpunit.investmoz.xml --do-not-cache-result
|
||||
|
||||
- name: Test all frontend contracts and calculators
|
||||
run: node --test tests/frontend/*.test.mjs
|
||||
|
||||
@@ -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.
|
||||
+1112
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Mne\CompatibilityBackfill;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class BackfillMneCompatibility extends Command
|
||||
{
|
||||
protected $signature = 'mne:backfill-compatibility {--batch=100} {--dry-run : Execute validation and roll back all changes}';
|
||||
|
||||
protected $description = 'Reconcile compatibility identifiers without copying canonical business records';
|
||||
|
||||
public function handle(CompatibilityBackfill $backfill): int
|
||||
{
|
||||
$batch = filter_var($this->option('batch'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
|
||||
if ($batch === false) {
|
||||
$this->error('Batch must be between 1 and 1000');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($this->option('dry-run')) {
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$counts = $backfill->run($batch);
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
$this->line(json_encode(['dry_run' => true, 'rolled_back' => true, 'counts' => $counts], JSON_THROW_ON_ERROR));
|
||||
} else {
|
||||
$this->line(json_encode($backfill->run($batch), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -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,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class EscalateOverdueInvestmentTasks extends Command
|
||||
{
|
||||
protected $signature = 'investmoz:escalate-overdue-tasks';
|
||||
|
||||
protected $description = 'Eleva a prioridade de tarefas operacionais vencidas, quando activado.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! config('existing-business.sla_escalation_enabled')) {
|
||||
$this->components->info('Escalada SLA desactivada.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$count = DB::table('tasks')->whereIn('task_type', ['triage', 'interest_follow_up'])
|
||||
->whereIn('status', ['open', 'in_progress'])->whereNotNull('due_at')->where('due_at', '<', now())
|
||||
->where('priority', '>', 1)->update(['priority' => 1, 'outcome' => 'sla_overdue', 'updated_at' => now()]);
|
||||
|
||||
$this->components->info("Tarefas elevadas para prioridade máxima: {$count}.");
|
||||
|
||||
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,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class ImportTerritoryWorkbook extends Command
|
||||
{
|
||||
protected $signature = 'geo:import-workbook {--inspect : Inspect the authorised workbook without database writes} {--python=python : Python executable}';
|
||||
|
||||
protected $description = 'Inspect and idempotently import the authorised cartography workbook, preserving existing IDs';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! app()->environment('local', 'testing')) {
|
||||
$this->error('Local/testing only.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
foreach ([[strval($this->option('python')), base_path('tools/prepare-territory-workbook.py')],
|
||||
...($this->option('inspect') ? [] : [[PHP_BINARY, base_path('tools/import-territory-workbook.php')]])] as $command) {
|
||||
$process = new Process($command, base_path());
|
||||
$process->setTimeout(300);
|
||||
$process->run();
|
||||
$this->output->write($process->getOutput());
|
||||
if (! $process->isSuccessful()) {
|
||||
$this->error($process->getErrorOutput());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class ReconcileMneCompatibility extends Command
|
||||
{
|
||||
protected $signature = 'mne:reconcile-compatibility {--fail-on-difference : Return failure while any reconciliation or activation gate remains open}';
|
||||
|
||||
protected $description = 'Read-only compatibility counts, fingerprints and activation blockers';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$report = DB::transaction(function (): array {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
$domains = [];
|
||||
foreach (['identity' => ['users', 'identity_links', 'user_id'], 'sector' => ['sectors', 'sector_links', 'sector_id'],
|
||||
'business' => ['existing_businesses', 'business_links', 'legacy_business_id']] as $domain => [$source, $target, $key]) {
|
||||
$checksums = [];
|
||||
$stale = 0;
|
||||
$missing = 0;
|
||||
foreach (DB::table('public.'.$source)->orderBy('id')->cursor() as $row) {
|
||||
$checksum = hash('sha256', json_encode((array) $row, JSON_THROW_ON_ERROR));
|
||||
$checksums[] = $checksum;
|
||||
$link = DB::table('mne.'.$target)->where($key, $row->id)->first();
|
||||
$missing += $link === null ? 1 : 0;
|
||||
$stale += $link !== null && $link->source_checksum !== $checksum ? 1 : 0;
|
||||
}
|
||||
$domains[$domain] = ['source_count' => count($checksums), 'link_count' => DB::table('mne.'.$target)->count(),
|
||||
'pending_count' => DB::table('mne.'.$target)->where('status', '<>', 'active')->count(),
|
||||
'missing' => $missing, 'stale_checksums' => $stale, 'checksum' => hash('sha256', implode('', $checksums))];
|
||||
}
|
||||
$role = DB::selectOne('SELECT rolsuper,rolcreaterole FROM pg_roles WHERE rolname=current_user');
|
||||
|
||||
return ['domains' => $domains, 'unresolved_rejections' => DB::table('mne.compatibility_rejections')->whereNull('resolved_at')->count(),
|
||||
'runtime_is_superuser' => (bool) $role->rolsuper, 'runtime_can_create_roles' => (bool) $role->rolcreaterole,
|
||||
'canonical_reads_ready' => false, 'canonical_writes_ready' => false,
|
||||
'blockers' => ['Full canonical response mapping and authorization parity not certified',
|
||||
'Legacy intake does not capture a sector', 'Runtime privilege separation requires verification with deployment credentials']];
|
||||
});
|
||||
$this->line(json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
|
||||
// This release has no certified canonical adapter: strict gate checks cannot succeed yet.
|
||||
return $this->option('fail-on-difference') ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Interests\Enums;
|
||||
|
||||
enum InterestStatus: string
|
||||
{
|
||||
case Received = 'received';
|
||||
case Submitted = 'submitted';
|
||||
case InReview = 'in_review';
|
||||
case Reviewed = 'reviewed';
|
||||
case Qualification = 'qualification';
|
||||
case Qualified = 'qualified';
|
||||
case Contacted = 'contacted';
|
||||
case ContactAccepted = 'contact_accepted';
|
||||
case Referred = 'referred';
|
||||
case DueDiligence = 'due_diligence';
|
||||
case Negotiation = 'negotiation';
|
||||
case Pending = 'pending';
|
||||
case Refused = 'refused';
|
||||
case Converted = 'converted';
|
||||
case Cancelled = 'cancelled';
|
||||
case Closed = 'closed';
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Opportunities\Enums;
|
||||
|
||||
enum OpportunityStatus: string
|
||||
{
|
||||
case Draft = 'draft';
|
||||
case Submitted = 'submitted';
|
||||
case Triage = 'triage';
|
||||
case InformationPending = 'information_pending';
|
||||
case InReview = 'in_review';
|
||||
case Review = 'review';
|
||||
case ApprovalL1 = 'approval_l1';
|
||||
case ApprovalL2 = 'approval_l2';
|
||||
case Approved = 'approved';
|
||||
case Published = 'published';
|
||||
case NeedsInformation = 'needs_information';
|
||||
case Suspended = 'suspended';
|
||||
case Rejected = 'rejected';
|
||||
case Withdrawn = 'withdrawn';
|
||||
case Cancelled = 'cancelled';
|
||||
case Archived = 'archived';
|
||||
}
|
||||
@@ -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.');
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Domain\Interests\Enums\InterestStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreInterestRequestRequest;
|
||||
use App\Jobs\NotifyInterestReceived;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\IdempotencyConflict;
|
||||
use App\Services\InterestSubmission;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
@@ -33,8 +36,17 @@ class InterestRequestController extends Controller
|
||||
throw ValidationException::withMessages(['opportunityReference' => 'A oportunidade seleccionada já não está disponível.']);
|
||||
}
|
||||
|
||||
$business = ! empty($validated['existingBusinessId'])
|
||||
? ExistingBusiness::published()->whereKey($validated['existingBusinessId'])->first()
|
||||
: null;
|
||||
if (! empty($validated['existingBusinessId']) && ! $business) {
|
||||
throw ValidationException::withMessages(['existingBusinessId' => 'A oportunidade seleccionada já não está disponível.']);
|
||||
}
|
||||
|
||||
$interest = InterestRequest::create([
|
||||
'opportunity_id' => $opportunity?->id,
|
||||
'existing_business_id' => $business?->id,
|
||||
'modality' => $business ? $validated['modality'] : null,
|
||||
'reference' => $this->generateReference(),
|
||||
'full_name' => trim($validated['fullName']),
|
||||
'email' => strtolower(trim($validated['email'])),
|
||||
@@ -47,7 +59,7 @@ class InterestRequestController extends Controller
|
||||
'message' => trim($validated['message']),
|
||||
'privacy_consent' => (bool) $validated['privacyConsent'],
|
||||
'consented_at' => now(),
|
||||
'status' => 'received',
|
||||
'status' => InterestStatus::Received->value,
|
||||
'source_page' => Str::limit($request->headers->get('referer', ''), 255, ''),
|
||||
'ip_address' => $request->ip(),
|
||||
'user_agent' => $request->userAgent(),
|
||||
@@ -78,6 +90,12 @@ class InterestRequestController extends Controller
|
||||
} catch (IdempotencyConflict) {
|
||||
return response()->json(['success' => false, 'message' => 'A chave de envio já foi usada com dados diferentes.'], 409);
|
||||
} catch (ValidationException $exception) {
|
||||
throw $exception;
|
||||
} catch (QueryException $exception) {
|
||||
if ($exception->getCode() === '23505') {
|
||||
return response()->json(['success' => false, 'message' => 'Já existe uma manifestação activa para esta oportunidade e modalidade.'], 409);
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
} catch (\Throwable $exception) {
|
||||
Log::error('Erro ao registar manifestação de interesse', [
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LegislationSourceController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
]);
|
||||
|
||||
$today = today()->toDateString();
|
||||
$query = InvestmentLegalSource::query()
|
||||
->where('validation_status', 'validated')
|
||||
->whereDate('valid_from', '<=', $today)
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhereDate('valid_until', '>=', $today));
|
||||
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.addcslashes($filters['q'], '%_\\').'%';
|
||||
$query->where(fn ($query) => $query
|
||||
->whereRaw('title ILIKE ?', [$term])
|
||||
->orWhereRaw('diploma ILIKE ?', [$term])
|
||||
->orWhereRaw('article ILIKE ?', [$term])
|
||||
->orWhereRaw('competent_entity ILIKE ?', [$term]));
|
||||
}
|
||||
|
||||
$page = $query->orderBy('title')->orderBy('id')->paginate($filters['per_page'] ?? 25)->withQueryString();
|
||||
$data = collect($page->items())->map(fn (InvestmentLegalSource $source): array => [
|
||||
'id' => $source->id,
|
||||
'title' => $source->title,
|
||||
'url' => $source->url,
|
||||
'diploma' => $source->diploma,
|
||||
'article' => $source->article,
|
||||
'competent_entity' => $source->competent_entity,
|
||||
'validation_status' => $source->validation_status,
|
||||
'version_no' => (int) $source->version_no,
|
||||
'valid_from' => $source->valid_from,
|
||||
'valid_until' => $source->valid_until,
|
||||
'validator_id' => $source->validator_id === null ? null : (int) $source->validator_id,
|
||||
'validated_at' => $source->validated_at,
|
||||
])->values();
|
||||
$body = [
|
||||
'data' => $data,
|
||||
'meta' => [
|
||||
'current_page' => $page->currentPage(),
|
||||
'per_page' => $page->perPage(),
|
||||
'total' => $page->total(),
|
||||
],
|
||||
];
|
||||
$etag = 'W/"legal-sources-'.hash('sha256', json_encode([
|
||||
'filters' => $filters,
|
||||
'data' => $data,
|
||||
'total' => $page->total(),
|
||||
], JSON_THROW_ON_ERROR)).'"';
|
||||
|
||||
return response()->json($body)
|
||||
->header('ETag', $etag)
|
||||
->header('Cache-Control', 'public, max-age=300');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ReferenceCatalogController extends Controller
|
||||
{
|
||||
private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities'];
|
||||
|
||||
public function index(Request $request, string $catalog): JsonResponse
|
||||
{
|
||||
$catalog = $this->validatedCatalog($catalog);
|
||||
|
||||
$rules = [
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'version' => ['nullable', 'integer', 'min:1'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'parent_id' => ['nullable', 'uuid'],
|
||||
'jurisdiction_id' => ['nullable', 'uuid'],
|
||||
];
|
||||
if ($catalog === 'jurisdictions') {
|
||||
$rules['type'] = ['required', 'in:country,province,district,admin_post,locality'];
|
||||
$rules['parent_id'][] = 'prohibited_if:type,country';
|
||||
$rules['parent_id'][] = 'required_if:type,district,admin_post,locality';
|
||||
}
|
||||
if ($catalog === 'economic-activities') {
|
||||
$rules['sector_id'] = ['nullable', 'integer', 'exists:sectors,id'];
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
|
||||
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $catalog)->where('locale', 'pt-MZ');
|
||||
if (isset($data['version'])) {
|
||||
$versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']);
|
||||
} else {
|
||||
$versionQuery->where('status', 'published')
|
||||
->where(fn (Builder $query) => $query->whereNull('valid_from')->orWhere('valid_from', '<=', today()->toDateString()))
|
||||
->where(fn (Builder $query) => $query->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()));
|
||||
}
|
||||
$version = $versionQuery->orderByDesc('version_no')->first();
|
||||
|
||||
if (isset($data['version']) && ! $version) {
|
||||
abort(404, 'Versão publicada do catálogo não encontrada.');
|
||||
}
|
||||
|
||||
if (! $version) {
|
||||
return response()->json([
|
||||
'data' => [],
|
||||
'links' => ['next' => null, 'previous' => null],
|
||||
'next_page_url' => null,
|
||||
'prev_page_url' => null,
|
||||
'current_page' => 1,
|
||||
'per_page' => $data['per_page'] ?? 20,
|
||||
'total' => 0,
|
||||
'last_page' => 1,
|
||||
'meta' => ['catalog' => $catalog, 'version' => null, 'locale' => 'pt-MZ', 'status' => 'not_published',
|
||||
'current_page' => 1, 'per_page' => $data['per_page'] ?? 20, 'total' => 0, 'last_page' => 1],
|
||||
])->header('Cache-Control', 'public, max-age=60');
|
||||
}
|
||||
|
||||
$query = match ($catalog) {
|
||||
'authorities' => $this->authorities((string) $version->id, $data),
|
||||
'jurisdictions' => $this->jurisdictions($data),
|
||||
'economic-activities' => $this->economicActivities((string) $version->id, $data),
|
||||
};
|
||||
|
||||
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
|
||||
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values();
|
||||
|
||||
return response()->json([
|
||||
'data' => $items,
|
||||
'links' => ['next' => $page->nextPageUrl(), 'previous' => $page->previousPageUrl()],
|
||||
'next_page_url' => $page->nextPageUrl(),
|
||||
'prev_page_url' => $page->previousPageUrl(),
|
||||
'current_page' => $page->currentPage(),
|
||||
'per_page' => $page->perPage(),
|
||||
'total' => $page->total(),
|
||||
'last_page' => $page->lastPage(),
|
||||
'meta' => ['catalog' => $catalog, 'version' => (int) $version->version_no, 'locale' => $version->locale,
|
||||
'source_version' => $version->source_version, 'valid_from' => $version->valid_from, 'valid_to' => $version->valid_to,
|
||||
'current_page' => $page->currentPage(), 'per_page' => $page->perPage(), 'total' => $page->total(), 'last_page' => $page->lastPage()],
|
||||
])->header('Cache-Control', 'public, max-age=300')
|
||||
->header('ETag', 'W/"catalog-'.substr(hash('sha256', $catalog.'|'.$version->version_no.'|'.json_encode($data, JSON_THROW_ON_ERROR)), 0, 32).'"');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function authorities(string $versionId, array $data): Builder
|
||||
{
|
||||
$query = DB::table('authorities as a')->join('organizations as o', 'o.id', '=', 'a.organization_id')
|
||||
->leftJoin('geo_locations as g', 'g.id', '=', 'a.jurisdiction_id')
|
||||
->where('a.catalog_version_id', $versionId)->where('a.status', 'published')
|
||||
->where('o.data_classification', 'public')->whereNull('o.deleted_at')
|
||||
->where('a.valid_from', '<=', today()->toDateString())
|
||||
->where(fn (Builder $builder) => $builder->whereNull('a.valid_to')->orWhere('a.valid_to', '>', today()->toDateString()))
|
||||
->select(['a.id', 'a.code', 'a.authority_type', 'a.label_pt_mz as name', 'a.organization_id', 'a.jurisdiction_id',
|
||||
'g.name as jurisdiction_name', 'a.version_no']);
|
||||
if (! empty($data['jurisdiction_id'])) {
|
||||
$query->where('a.jurisdiction_id', $data['jurisdiction_id']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['a.code', 'a.label_pt_mz', 'o.name']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function jurisdictions(array $data): Builder
|
||||
{
|
||||
$query = DB::table('geo_locations')->where('source_system', 'cartografia-workbook')
|
||||
->where('data_classification', 'public')->whereNull('deleted_at')->where('location_type', $data['type'])
|
||||
->select(['id', 'code', 'name', 'parent_id', 'location_type', 'source_code', 'version_no']);
|
||||
$parentType = ['province' => 'country', 'district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']] ?? null;
|
||||
if ($data['type'] !== 'country' && ! empty($data['parent_id'])) {
|
||||
$validParent = DB::table('geo_locations')->where('id', $data['parent_id'])->where('location_type', $parentType)
|
||||
->where('source_system', 'cartografia-workbook')->where('data_classification', 'public')->whereNull('deleted_at')->exists();
|
||||
if (! $validParent) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione um território pai activo do nível anterior.']);
|
||||
}
|
||||
$query->where('parent_id', $data['parent_id']);
|
||||
} elseif (in_array($data['type'], ['district', 'admin_post', 'locality'], true)) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione primeiro o território pai.']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['code', 'name', 'source_code']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function economicActivities(string $versionId, array $data): Builder
|
||||
{
|
||||
$query = DB::table('economic_activities')->where('catalog_version_id', $versionId)->where('status', 'published')
|
||||
->where('valid_from', '<=', today()->toDateString())
|
||||
->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()))
|
||||
->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']);
|
||||
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) {
|
||||
$query->where('parent_id', $data['parent_id']);
|
||||
} else {
|
||||
$query->whereNull('parent_id');
|
||||
}
|
||||
if (! empty($data['sector_id'])) {
|
||||
$query->where('sector_id', $data['sector_id']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['code', 'label_pt_mz']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @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) {
|
||||
if ($index === 0) {
|
||||
$nested->whereRaw($column.' ILIKE ?', [$term]);
|
||||
} else {
|
||||
$nested->orWhereRaw($column.' ILIKE ?', [$term]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @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']],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
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;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SimulationController extends Controller
|
||||
{
|
||||
public function questionnaire(string $code): JsonResponse
|
||||
{
|
||||
abort_unless(preg_match('/^[a-z0-9][a-z0-9-]{0,79}$/', $code) === 1, 404);
|
||||
$version = QuestionnaireVersion::query()->where('code', $code)->where('locale', 'pt-MZ')->where('status', 'published')
|
||||
->where(fn ($query) => $query->whereNull('valid_from')->orWhereDate('valid_from', '<=', today()))
|
||||
->where(fn ($query) => $query->whereNull('valid_to')->orWhereDate('valid_to', '>', today()))
|
||||
->orderByDesc('version_no')->firstOrFail();
|
||||
$etag = '"questionnaire-'.$version->id.'-v'.$version->version_no.'"';
|
||||
|
||||
return response()->json(['data' => $version])->header('ETag', $etag)->header('Cache-Control', 'private, max-age=60');
|
||||
}
|
||||
|
||||
public function store(StoreSimulationRequest $request, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
$key = $request->header('Idempotency-Key');
|
||||
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
|
||||
$actorId = $request->user()?->id;
|
||||
$token = $actorId === null ? $request->header('X-Simulation-Token') : null;
|
||||
abort_if($actorId === null && (! is_string($token) || strlen($token) < 32 || strlen($token) > 256), 422, 'X-Simulation-Token opaco gerado pelo cliente é obrigatório para execução anónima.');
|
||||
$validated = $request->validated();
|
||||
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
||||
'reduction' => (string) ($validated['reduction'] ?? '0'), 'organization_id' => $validated['organization_id'] ?? null];
|
||||
$organizationId = $data['organization_id'] ?? null;
|
||||
$execution->authorizeOrganization($actorId, $organizationId);
|
||||
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
|
||||
$simulation = $result['simulation'];
|
||||
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
|
||||
if ($actorId === null) {
|
||||
$body['access_token'] = $token;
|
||||
}
|
||||
|
||||
return response()->json($body, $result['replayed'] ? 200 : 202)
|
||||
->header('ETag', $execution->etag($simulation))
|
||||
->header('Location', url('/api/v1/simulations/'.$simulation->id));
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
|
||||
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);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->update($request->user(), $simulation), 403);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
$validated = $request->validated();
|
||||
$data = ['label' => (string) $validated['label'], 'base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
||||
'reduction' => (string) ($validated['reduction'] ?? '0')];
|
||||
$updated = $execution->updateScenario($id, $scenarioId, $data, $request);
|
||||
|
||||
return response()->json(['data' => $updated], 202)->header('ETag', $execution->etag($updated));
|
||||
}
|
||||
|
||||
public function report(Request $request, string $id, string $reportId, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id) && Str::isUuid($reportId), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
$report = $simulation->reports->firstWhere('id', $reportId);
|
||||
abort_if($report === null, 404);
|
||||
|
||||
return response()->json(['data' => $report]);
|
||||
}
|
||||
|
||||
public function jobs(Request $request, string $id, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
|
||||
$jobs = DB::transaction(function () use ($request, $id, $execution) {
|
||||
$execution->setContext($request->user()?->id, $execution->tokenHash($request));
|
||||
|
||||
return SimulationJob::query()->where('simulation_id', $id)
|
||||
->orderBy('created_at')->orderBy('id')->get();
|
||||
});
|
||||
|
||||
return response()->json(['data' => $jobs]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
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\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
|
||||
{
|
||||
public function store(StoreSimulationFormDraftRequest $request, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
$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->snapshots(), $request, $key);
|
||||
$draft = $result['draft'];
|
||||
|
||||
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);
|
||||
if (! $draft) {
|
||||
return response()->json(['data' => null], 200)->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
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$draft = $drafts->find($id, $request);
|
||||
|
||||
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->snapshots(), $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 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);
|
||||
$drafts->delete($id, $request);
|
||||
|
||||
return response()->json([], 204)->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
@@ -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,10 +76,12 @@ 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')->orderBy('name')->get(['id', 'name', 'code']),
|
||||
'territories' => DB::table('geo_locations')->whereNull('deleted_at')
|
||||
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
|
||||
->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']),
|
||||
'today' => now()->toDateString(),
|
||||
]);
|
||||
}
|
||||
@@ -96,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')
|
||||
@@ -148,6 +168,7 @@ class EducationController extends Controller
|
||||
return Inertia::render('education/analysis', ['demand' => $demand, 'candidates' => $candidates,
|
||||
'proposal' => EducationInvestmentProposal::where('labour_demand_id', $id)->first(),
|
||||
'sectors' => Sector::orderBy('name')->get(['id', 'name']),
|
||||
'territoryPath' => app(InvestmentGeography::class)->path($demand->getAttribute('geo_location_id'), true),
|
||||
'eligible' => $eligible, 'gap' => $calculator->observed((int) $demand->getAttribute('quantity'), null, $eligible, $current)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,14 @@ namespace App\Http\Controllers;
|
||||
use App\Models\EducationInvestmentProposal;
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use LogicException;
|
||||
|
||||
class EducationInvestmentController extends Controller
|
||||
{
|
||||
@@ -27,6 +29,10 @@ class EducationInvestmentController extends Controller
|
||||
'risks' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
'source' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
'currency' => ['required', Rule::in(['MZN', 'USD', 'EUR', 'ZAR'])],
|
||||
'province_id' => ['required', 'uuid'],
|
||||
'district_id' => ['nullable', 'uuid'],
|
||||
'admin_post_id' => ['nullable', 'uuid'],
|
||||
'locality_id' => ['nullable', 'uuid'],
|
||||
]);
|
||||
|
||||
DB::transaction(function () use ($request, $id, $data): void {
|
||||
@@ -38,6 +44,14 @@ class EducationInvestmentController extends Controller
|
||||
if (EducationInvestmentProposal::withTrashed()->where('labour_demand_id', $id)->exists()) {
|
||||
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[$lastTerritoryKey];
|
||||
$reference = 'EDU-'.Str::uuid();
|
||||
$opportunity = new Opportunity;
|
||||
PortalAudit::save($opportunity, [
|
||||
@@ -45,6 +59,8 @@ class EducationInvestmentController extends Controller
|
||||
'slug' => strtolower($reference), 'title' => $data['title'],
|
||||
'summary' => 'Proposta educativa em preparação. Lacuna e viabilidade pendentes de validação institucional.',
|
||||
'description' => $data['intervention'], 'estimated_investment_currency' => $data['currency'],
|
||||
'province' => $province->name, 'district' => $district?->name,
|
||||
'primary_territory_id' => $primaryTerritory->id, 'territory_version' => 1,
|
||||
'status' => 'draft', 'is_featured' => false,
|
||||
], $request->user()->id);
|
||||
PortalAudit::save(new EducationInvestmentProposal, [
|
||||
|
||||
@@ -4,10 +4,15 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\Sector;
|
||||
use App\Services\BusinessFormSchema;
|
||||
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;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
@@ -21,10 +26,12 @@ class ExistingBusinessController extends Controller
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$management = $request->is('management/*', 'api/v1/existing-business/review*');
|
||||
$query = ExistingBusiness::query();
|
||||
$query = app(BusinessRepository::class)->query();
|
||||
if ($management) {
|
||||
Gate::authorize('reviewQueue', ExistingBusiness::class);
|
||||
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', ['submitted', 'in_review', 'needs_information']);
|
||||
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', [
|
||||
'submitted', 'triage', 'in_review', 'needs_information', 'approval_l1', 'approval_l2', 'approved',
|
||||
]);
|
||||
} else {
|
||||
$query->where('owner_user_id', $request->user()->id);
|
||||
}
|
||||
@@ -36,10 +43,15 @@ class ExistingBusinessController extends Controller
|
||||
|
||||
public function show(Request $request, string $id): Response|JsonResponse
|
||||
{
|
||||
$business = ExistingBusiness::findOrFail($id);
|
||||
$business = app(BusinessRepository::class)->find($id);
|
||||
Gate::authorize('view', $business);
|
||||
$props = ['record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
app(CompatibilityShadow::class)->schedule($id);
|
||||
$props = ['sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||
'canTriage' => $request->user()->can('triage', $business),
|
||||
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
||||
'canApproveLevelTwo' => $request->user()->can('approveLevelTwo', $business),
|
||||
'canPublish' => $request->user()->can('publish', $business),
|
||||
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
||||
'objectKinds' => ExistingBusinessObjects::KINDS,
|
||||
'verificationChecks' => ExistingBusinessVerification::CHECKS,
|
||||
@@ -63,8 +75,8 @@ class ExistingBusinessController extends Controller
|
||||
public function transition(Request $request, ExistingBusinessIntake $intake, string $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'action' => ['required', 'string'],
|
||||
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean']]);
|
||||
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false));
|
||||
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean'], 'confirmation_code' => ['nullable', 'string', 'max:100']]);
|
||||
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false), $data['confirmation_code'] ?? null);
|
||||
|
||||
return response()->json($this->record($business));
|
||||
}
|
||||
@@ -79,12 +91,17 @@ class ExistingBusinessController extends Controller
|
||||
$saved = $objects->save($request->user(), $id, $request->all(), $object);
|
||||
|
||||
return response()->json(['id' => $saved->id, 'verification_status' => 'pending',
|
||||
'version_no' => ExistingBusiness::findOrFail($id)->version_no], $object ? 200 : 201);
|
||||
'version_no' => app(BusinessRepository::class)->find($id)->version_no], $object ? 200 : 201);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function record(ExistingBusiness $business): array
|
||||
{
|
||||
return [...$business->only(['id', 'code', 'modality', 'status', 'classification', 'version_no']), 'payload' => $business->payload];
|
||||
return [...$business->only([
|
||||
'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,
|
||||
'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, '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
|
||||
|
||||
@@ -27,7 +27,8 @@ class InvestmentLegalSourceController extends Controller
|
||||
$source->refresh();
|
||||
$this->audit($source, $request->user()->id, 'created');
|
||||
|
||||
return response()->json($source->fresh(), 201);
|
||||
return response()->json($source->fresh(), 201)
|
||||
->header('Location', url('/api/v2/investment/admin/legal-sources/'.$source->id));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,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) {
|
||||
@@ -82,7 +89,7 @@ class InvestmentStructureController extends Controller
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
if (! $id && $request->has('province_id')) {
|
||||
$path = app(InvestmentGeography::class)->selection($data);
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$data = array_diff_key($data, InvestmentGeography::FIELDS);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = $path === [] ? 0 : 1;
|
||||
@@ -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;
|
||||
@@ -293,7 +294,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 +309,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 +318,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']);
|
||||
}
|
||||
|
||||
@@ -30,13 +30,18 @@ class InvestmentTerritoryController extends Controller
|
||||
$query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type'])
|
||||
->whereIn('data_classification', ['public', 'internal']);
|
||||
if ($data['type'] !== 'province') {
|
||||
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']];
|
||||
if (! DB::table('geo_locations')->where('id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000')->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])->where('location_type', $parentType)->exists()) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione um pai activo do nível anterior.']);
|
||||
}
|
||||
$query->where('parent_id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000');
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$query->whereRaw('name ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
|
||||
$term = '%'.addcslashes($data['q'], '%_\\').'%';
|
||||
$query->where(fn ($q) => $q->whereRaw('name 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']));
|
||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
|
||||
}
|
||||
|
||||
public function show(string $kind, string $id): JsonResponse
|
||||
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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,35 +83,139 @@ 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']]);
|
||||
$path = app(InvestmentGeography::class)->selection($geo);
|
||||
$path = app(InvestmentGeography::class)->selection($geo, true);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = $path === [] ? 0 : 1;
|
||||
$data['province'] = $path[0]->name ?? null;
|
||||
@@ -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,94 @@
|
||||
<?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 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', ['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,156 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityResourceInstallation;
|
||||
use App\Services\OpportunityResources;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
|
||||
class OpportunityResourceController extends Controller
|
||||
{
|
||||
public function installation(Request $request, OpportunityResourceInstallation $service)
|
||||
{
|
||||
$preview = [...$service->preview(), 'actionUrl' => '/management/opportunity-resources-install'];
|
||||
|
||||
return $request->expectsJson() ? response()->json($preview) : Inertia::render('management/opportunity-install', $preview);
|
||||
}
|
||||
|
||||
public function applyInstallation(Request $request, OpportunityResourceInstallation $service)
|
||||
{
|
||||
$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)
|
||||
{
|
||||
$opportunity = Opportunity::withTrashed()->findOrFail($id);
|
||||
abort_unless($service->installed(), 503, 'Recursos ainda não instalados; consulte o plano autenticado.');
|
||||
$resources = [];
|
||||
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);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
$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)
|
||||
{
|
||||
$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 download(int $id, string $kind, string $resourceId, OpportunityResources $service)
|
||||
{
|
||||
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<object>> $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.';
|
||||
}
|
||||
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') {
|
||||
$issues[] = 'Imagem '.$r->file->file_name.': revisão, derivadas sem EXIF e aprovação de divulgação 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.');
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,17 @@ use App\Models\InterestRequest;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
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;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -22,7 +27,7 @@ use Inertia\Response;
|
||||
|
||||
class PortalManagementController extends Controller
|
||||
{
|
||||
private const STATES = ['received', 'in_review', 'contacted', 'closed'];
|
||||
private const STATES = ['received', 'submitted', 'in_review', 'reviewed', 'qualification', 'qualified', 'contacted', 'contact_accepted', 'referred', 'due_diligence', 'negotiation', 'pending', 'refused', 'converted', 'cancelled', 'closed'];
|
||||
|
||||
public function history(): Response
|
||||
{
|
||||
@@ -50,9 +55,10 @@ class PortalManagementController extends Controller
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:150'],
|
||||
'status' => ['nullable', Rule::in(self::STATES)],
|
||||
'follow_up' => ['nullable', Rule::in(['overdue', 'upcoming', 'unassigned'])],
|
||||
]);
|
||||
$query = InterestRequest::query()->select([
|
||||
'id', 'reference', 'full_name', 'email', 'sector_interest', 'status', 'created_at',
|
||||
$query = InterestRequest::query()->with('assignee:id,name')->select([
|
||||
'id', 'reference', 'full_name', 'email', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
||||
]);
|
||||
if ($term = $filters['q'] ?? null) {
|
||||
$query->where(fn ($q) => $q->whereLike('reference', "%{$term}%")
|
||||
@@ -61,6 +67,15 @@ class PortalManagementController extends Controller
|
||||
if ($status = $filters['status'] ?? null) {
|
||||
$query->where('status', $status);
|
||||
}
|
||||
if (($filters['follow_up'] ?? null) === 'overdue') {
|
||||
$query->whereNotNull('next_action_due_at')->where('next_action_due_at', '<', now())
|
||||
->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
} elseif (($filters['follow_up'] ?? null) === 'upcoming') {
|
||||
$query->whereNotNull('next_action_due_at')->where('next_action_due_at', '>=', now())
|
||||
->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
} elseif (($filters['follow_up'] ?? null) === 'unassigned') {
|
||||
$query->whereNull('assigned_to')->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
}
|
||||
|
||||
return Inertia::render('management/interests', [
|
||||
'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString(),
|
||||
@@ -70,31 +85,112 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function interest(InterestRequest $interest): Response
|
||||
{
|
||||
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
|
||||
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
|
||||
->map(function ($row) {
|
||||
$row->note = $row->reason ? Crypt::decryptString($row->reason) : null;
|
||||
unset($row->reason);
|
||||
|
||||
return $row;
|
||||
});
|
||||
$consents = DB::table('consents')->where('interest_request_id', $interest->id)
|
||||
->orderBy('created_at')->get(['purpose', 'policy_version', 'status', 'granted_at', 'withdrawn_at']);
|
||||
|
||||
return Inertia::render('management/interest', [
|
||||
'interest' => $interest->only([
|
||||
'id', 'reference', 'full_name', 'email', 'phone', 'investor_type', 'country',
|
||||
'sector_interest', 'opportunity_reference', 'investment_range', 'message',
|
||||
'privacy_consent', 'consented_at', 'status', 'created_at', 'reviewed_at', 'reviewed_by', 'metadata',
|
||||
'existing_business_id', 'modality', 'assigned_to', 'next_action', 'next_action_due_at',
|
||||
]),
|
||||
'history' => $history,
|
||||
'consents' => $consents,
|
||||
'assignees' => $this->interestAssignees()->get(['id', 'name']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function review(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
|
||||
{
|
||||
$validated = $request->validate(['status' => ['required', Rule::in(self::STATES)]]);
|
||||
DB::transaction(function () use ($request, $interest, $validated) {
|
||||
$locked = InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
|
||||
$changed = $locked->status !== $validated['status'];
|
||||
PortalAudit::save($locked, [
|
||||
...$validated, 'reviewed_at' => now(), 'reviewed_by' => $request->user()->id,
|
||||
], $request->user()->id);
|
||||
$submission = InvestmentSubmission::where('interest_request_id', $interest->id)->first();
|
||||
if ($changed && $submission) {
|
||||
app(InvestmentWorkspace::class)->notify($submission->user_id, $submission, 'status', (string) Str::uuid(), ['status' => $validated['status']]);
|
||||
}
|
||||
});
|
||||
$validated = $request->validate([
|
||||
'status' => ['required', Rule::in(self::STATES)],
|
||||
'note' => ['nullable', 'string', 'min:10', 'max:2000'],
|
||||
'next_action' => ['nullable', 'required_with:next_action_due_at', 'string', 'max:180'],
|
||||
'next_action_due_at' => ['nullable', 'required_with:next_action', 'date', 'after_or_equal:today'],
|
||||
'assigned_to' => ['nullable', 'integer', Rule::in($this->interestAssignees()->pluck('id'))],
|
||||
]);
|
||||
$before = $interest->status;
|
||||
$updated = $workflow->transition($request->user(), $interest, $validated['status'], $validated['note'] ?? null,
|
||||
$validated['next_action'] ?? null, $validated['next_action_due_at'] ?? null, isset($validated['assigned_to']) ? (int) $validated['assigned_to'] : null,
|
||||
$request->exists('assigned_to'), $request->exists('next_action') || $request->exists('next_action_due_at'));
|
||||
PortalAudit::save($updated, ['status' => $updated->status, 'reviewed_at' => $updated->reviewed_at, 'reviewed_by' => $updated->reviewed_by], $request->user()->id);
|
||||
$submission = InvestmentSubmission::where('interest_request_id', $interest->id)->first();
|
||||
if ($before !== $updated->status && $submission) {
|
||||
app(InvestmentWorkspace::class)->notify($submission->user_id, $submission, 'status', (string) Str::uuid(), ['status' => $updated->status]);
|
||||
}
|
||||
|
||||
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'status' => $validated['status']]) : back()->with('success', 'Estado do pedido actualizado.');
|
||||
return $request->expectsJson() ? response()->json(['reference' => $updated->reference, 'status' => $updated->status]) : back()->with('success', 'Estado do pedido actualizado.');
|
||||
}
|
||||
|
||||
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
$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' => $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' => $purpose], JSON_THROW_ON_ERROR),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
DB::table('outbox_events')->insertOrIgnore([
|
||||
'source_system' => 'portal-intake', 'external_id' => 'InterestConsentWithdrawn:'.$consent->id,
|
||||
'aggregate_type' => 'interest_consent', 'aggregate_id' => $consent->id,
|
||||
'event_type' => 'InterestConsentWithdrawn', 'data_classification' => 'confidential',
|
||||
'correlation_id' => $correlationId, 'status' => 'pending',
|
||||
'payload' => json_encode(['schema_version' => 1, 'consent_id' => $consent->id,
|
||||
'interest_id' => $lockedInterest->integration_id, 'purpose' => $purpose], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return Builder<User> */
|
||||
private function interestAssignees(): Builder
|
||||
{
|
||||
$emails = array_unique(array_merge(config('portal.managers', []), ...array_map(
|
||||
fn (string $designation) => config('existing-business.'.$designation, []),
|
||||
['triagers', 'reviewers', 'approvers_l1', 'approvers_l2', 'publishers'],
|
||||
)));
|
||||
|
||||
return User::query()->whereNotNull('email_verified_at')->whereIn(DB::raw('lower(email)'), $emails)->orderBy('name');
|
||||
}
|
||||
|
||||
public function catalog(Request $request, string $resource): Response
|
||||
@@ -104,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}%")
|
||||
@@ -134,22 +237,30 @@ 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,
|
||||
]);
|
||||
}
|
||||
|
||||
public function edit(string $resource, ?int $id = null): Response
|
||||
{
|
||||
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
||||
$record = $id ? $model::findOrFail($id) : null;
|
||||
|
||||
return Inertia::render('management/editor', [
|
||||
'resource' => $resource,
|
||||
'record' => $id ? $model::findOrFail($id) : null,
|
||||
'record' => $record,
|
||||
'territoryPath' => $record instanceof Opportunity ? app(InvestmentGeography::class)->path($record->primary_territory_id, true) : [],
|
||||
'sectors' => Sector::orderBy('name')->get(['id', 'name']),
|
||||
]);
|
||||
}
|
||||
|
||||
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' ? [
|
||||
@@ -178,20 +289,14 @@ class PortalManagementController extends Controller
|
||||
'status' => ['required', Rule::in(['draft', 'published', 'archived'])],
|
||||
'is_featured' => ['required', 'boolean'],
|
||||
];
|
||||
if ($resource === 'opportunities' && ! $id) {
|
||||
if ($resource === 'opportunities') {
|
||||
$rules['geography_scope'] = ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])];
|
||||
foreach (InvestmentGeography::FIELDS as $field => $type) {
|
||||
$rules[$field] = ['nullable', 'uuid'];
|
||||
}
|
||||
$rules['territory_version'] = [$id && $request->hasAny(array_keys(InvestmentGeography::FIELDS)) ? 'required' : 'nullable', 'integer', 'min:0'];
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
if ($resource === 'opportunities' && ! $id && $request->has('province_id')) {
|
||||
$path = app(InvestmentGeography::class)->selection($data);
|
||||
$data = array_diff_key($data, InvestmentGeography::FIELDS);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = $path === [] ? 0 : 1;
|
||||
$data['province'] = $path[0]->name ?? null;
|
||||
$data['district'] = $path[1]->name ?? null;
|
||||
}
|
||||
if ($resource === 'opportunities' && $data['status'] === 'published' && $record->exists
|
||||
&& Schema::hasTable('education_investment_proposals')
|
||||
&& DB::table('education_investment_proposals')->where('opportunity_id', $record->id)->exists()) {
|
||||
@@ -205,7 +310,30 @@ class PortalManagementController extends Controller
|
||||
$data['maturity_label'] = $labels[$data['maturity_level'] ?? 0] ?? null;
|
||||
$data['published_at'] = $data['status'] === 'published' ? ($record->published_at ?? now()) : null;
|
||||
}
|
||||
PortalAudit::save($record, $data, $request->user()->id);
|
||||
DB::transaction(function () use ($record, $data, $request, $resource) {
|
||||
if ($resource === 'opportunities' && $request->hasAny(array_keys(InvestmentGeography::FIELDS))) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
if ($record->exists) {
|
||||
$current = Opportunity::whereKey($record->id)->lockForUpdate()->firstOrFail();
|
||||
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;
|
||||
} else {
|
||||
unset($data['territory_version']);
|
||||
}
|
||||
PortalAudit::save($record, $data, $request->user()->id);
|
||||
});
|
||||
|
||||
return redirect('/management/'.$resource)->with('success', 'Registo guardado.');
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
|
||||
class PublicBusinessOpportunityController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$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.'%')
|
||||
->orWhereLike('existing_businesses.activity_code', '%'.$term.'%')
|
||||
->orWhereLike('existing_businesses.objective', '%'.$term.'%'));
|
||||
}
|
||||
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, 'territorySelection' => $path]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $slug): Response|JsonResponse
|
||||
{
|
||||
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
|
||||
$resource = new PublicBusinessOpportunityResource($record);
|
||||
if ($request->expectsJson()) {
|
||||
return $resource->response();
|
||||
}
|
||||
|
||||
$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),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
private function publishedQuery(): Builder
|
||||
{
|
||||
$publicLocations = DB::table('existing_business_locations as locations')
|
||||
->leftJoin('geo_locations as province', 'province.id', '=', 'locations.province_id')
|
||||
->leftJoin('geo_locations as district', 'district.id', '=', 'locations.district_id')
|
||||
->leftJoin('geo_locations as locality', 'locality.id', '=', 'locations.locality_id')
|
||||
->where('locations.is_public', true)->where('locations.is_primary', true)
|
||||
->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at')
|
||||
->select('locations.existing_business_id', 'province.name as province')
|
||||
->selectRaw("CASE WHEN locations.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
|
||||
->selectRaw('NULL::text AS locality');
|
||||
|
||||
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', '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',
|
||||
'public_location.province', 'public_location.district', 'public_location.locality']);
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,30 @@ 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'])) {
|
||||
$query->whereRaw('name ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
|
||||
$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']));
|
||||
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' => DB::table('investment_submissions')->where('user_id', $actor->id)->get(['id', 'status']),
|
||||
'journeys' => DB::table('investor_journeys')->where('user_id', $actor->id)->whereNull('deleted_at')->get(['id', 'dossier_id', 'status']),
|
||||
'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 = ['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,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CorrelationId
|
||||
{
|
||||
/** @param Closure(Request): Response $next */
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$provided = $request->header('X-Correlation-ID');
|
||||
$correlationId = is_string($provided) && Str::isUuid($provided)
|
||||
? $provided
|
||||
: (string) Str::uuid();
|
||||
|
||||
if ($provided !== null && ! Str::isUuid($provided)) {
|
||||
return response()->json([
|
||||
'message' => 'O identificador de correlação deve ser um UUID válido.',
|
||||
'code' => 'invalid_correlation_id',
|
||||
'correlation_id' => $correlationId,
|
||||
], 422)->header('X-Correlation-ID', $correlationId);
|
||||
}
|
||||
|
||||
$request->attributes->set('correlation_id', $correlationId);
|
||||
$response = $next($request);
|
||||
$response->headers->set('X-Correlation-ID', $correlationId);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -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,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class PreserveFormFeedback
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Auxiliary JSON reads must not consume feedback intended for the next Inertia page.
|
||||
if ($request->isMethod('GET') && $request->expectsJson() && ! $request->header('X-Inertia') && $request->hasSession()) {
|
||||
$request->session()->keep(['errors', '_old_input', 'success']);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class StoreInterestRequestRequest extends FormRequest
|
||||
{
|
||||
@@ -36,12 +38,28 @@ class StoreInterestRequestRequest extends FormRequest
|
||||
->where('status', 'published')->whereNotNull('published_at')
|
||||
->where('published_at', '<=', now())->whereNull('deleted_at')),
|
||||
])],
|
||||
'existingBusinessId' => ['nullable', 'uuid', ...($knownKey ? [] : [
|
||||
Rule::exists('existing_businesses', 'id')->where(fn ($query) => $query
|
||||
->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())->whereNull('deleted_at')),
|
||||
])],
|
||||
'modality' => ['nullable', 'required_with:existingBusinessId', 'string', 'max:50', Rule::in(ExistingBusinessDrafts::MODALITIES)],
|
||||
'investmentRange' => ['nullable', 'string', 'max:80'],
|
||||
'message' => ['required', 'string', 'min:20', 'max:2000'],
|
||||
'privacyConsent' => ['required', 'accepted'],
|
||||
'shareWithProponent' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<callable(Validator): void> */
|
||||
public function after(): array
|
||||
{
|
||||
return [function (Validator $validator): void {
|
||||
if ($this->filled('existingBusinessId') && $this->filled('opportunityReference')) {
|
||||
$validator->errors()->add('existingBusinessId', 'Seleccione apenas uma oportunidade.');
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -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.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
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;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
$personal = [
|
||||
'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 = [
|
||||
'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',
|
||||
'infrastructure_needs', 'currency', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt',
|
||||
'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', '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',
|
||||
'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
|
||||
'final_declaration_name',
|
||||
];
|
||||
|
||||
$rules = [
|
||||
// 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'],
|
||||
'economic_snapshot.maturity_stage' => ['nullable', 'in:idea,concept,pre_feasibility,feasibility,financing,implementation,operation'],
|
||||
'economic_snapshot.land_status' => ['nullable', 'in:owned,duat,leased,requested,unknown'],
|
||||
'economic_snapshot.offer_or_demand' => ['nullable', 'in:offer,demand,both'],
|
||||
'economic_snapshot.opportunity_type' => ['nullable', 'in:capital,partner,buyer,supplier,land,technology,licence,services,other'],
|
||||
'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'],
|
||||
'economic_snapshot.reuse_simulation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.contact_authorisation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.publication_authorisation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.reduction' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.local_content_percentage' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.latitude' => ['nullable', 'numeric', 'between:-90,90'],
|
||||
'economic_snapshot.longitude' => ['nullable', 'numeric', 'between:-180,180'],
|
||||
'economic_snapshot.expected_start_date' => ['nullable', 'date'],
|
||||
'economic_snapshot.opportunity_deadline' => ['nullable', 'date'],
|
||||
'economic_snapshot.reference_date' => ['nullable', 'date'],
|
||||
'economic_snapshot.*' => ['nullable'],
|
||||
];
|
||||
|
||||
foreach (['base', 'area_required', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt', 'grants',
|
||||
'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit', 'exports_value',
|
||||
'import_substitution_value', 'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs',
|
||||
'non_deductible_costs', 'carried_losses', 'opportunity_value'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'numeric', 'min:0'];
|
||||
}
|
||||
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,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', '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'];
|
||||
$rules['personal_snapshot.nuit'] = ['nullable', 'string', 'max:32'];
|
||||
$rules['personal_snapshot.investor_profile_id'] = ['nullable', 'uuid'];
|
||||
$rules['personal_snapshot.profile_confirmation'] = ['nullable', 'boolean'];
|
||||
$rules['personal_snapshot.selection_labels'] = ['nullable', 'array'];
|
||||
$rules['personal_snapshot.person_type'] = ['nullable', 'in:singular,collective,sole_trader,consortium'];
|
||||
$rules['personal_snapshot.investor_origin'] = ['nullable', 'in:national,foreign,mixed'];
|
||||
$rules['personal_snapshot.entity_stage'] = ['nullable', 'in:existing,being_formed'];
|
||||
$rules['economic_snapshot.sector_id'] = ['nullable', 'integer', 'exists:sectors,id'];
|
||||
$rules['economic_snapshot.activity_id'] = ['nullable', 'uuid', 'exists:economic_activities,id'];
|
||||
foreach (['existing_project_id', 'special_zone_id'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:100'];
|
||||
}
|
||||
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', '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'];
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator): void {
|
||||
$economic = $this->input('economic_snapshot', []);
|
||||
if (! is_array($economic)) {
|
||||
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' => ['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', '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',
|
||||
'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'] ?? []);
|
||||
foreach (is_array($snapshot) ? $snapshot : [] as $field => $label) {
|
||||
$labels = is_array($label) ? $label : [$label];
|
||||
if (! is_string($field) || ! in_array($field, $allowedFields, true) || count($labels) > 100
|
||||
|| collect($labels)->contains(fn ($value) => ! is_string($value) || mb_strlen($value) > 255)) {
|
||||
$validator->errors()->add($path, 'Os rótulos de selecção não são válidos.');
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($economic['activity_id'], $economic['sector_id'])) {
|
||||
$matchesSector = 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.sector_id', $economic['sector_id'])
|
||||
->where('a.status', 'published')->where('v.status', 'published')
|
||||
->whereDate('a.valid_from', '<=', today())
|
||||
->where(fn ($query) => $query->whereNull('a.valid_to')->orWhereDate('a.valid_to', '>', today()))->exists();
|
||||
if (! $matchesSector) {
|
||||
$validator->errors()->add('economic_snapshot.activity_id', 'A actividade não pertence ao sector seleccionado ou já não está publicada.');
|
||||
}
|
||||
} elseif (! empty($economic['activity_id'])) {
|
||||
$validator->errors()->add('economic_snapshot.sector_id', 'Seleccione o sector antes da actividade económica.');
|
||||
}
|
||||
|
||||
$parents = ['district_id' => ['province_id', 'district'], 'admin_post_id' => ['district_id', 'admin_post'], 'locality_id' => ['admin_post_id', 'locality']];
|
||||
foreach ($parents as $child => [$parentField, $type]) {
|
||||
if (empty($economic[$child])) {
|
||||
continue;
|
||||
}
|
||||
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$type];
|
||||
$valid = ! empty($economic[$parentField]) && DB::table('geo_locations as child')
|
||||
->join('geo_locations as parent', 'parent.id', '=', 'child.parent_id')
|
||||
->where('child.id', $economic[$child])->where('child.location_type', $type)
|
||||
->where('child.source_system', 'cartografia-workbook')->where('child.data_classification', 'public')->whereNull('child.deleted_at')
|
||||
->where('parent.id', $economic[$parentField])->where('parent.location_type', $parentType)
|
||||
->where('parent.source_system', 'cartografia-workbook')->where('parent.data_classification', 'public')->whereNull('parent.deleted_at')->exists();
|
||||
if (! $valid) {
|
||||
$validator->errors()->add('economic_snapshot.'.$child, 'Seleccione uma opção publicada dependente do nível territorial anterior.');
|
||||
}
|
||||
}
|
||||
|
||||
$financeKeys = ['total_investment', 'own_capital', 'domestic_debt', 'foreign_debt', 'grants'];
|
||||
if (collect($financeKeys)->every(fn (string $key) => array_key_exists($key, $economic) && $economic[$key] !== null && $economic[$key] !== '')) {
|
||||
$funding = (float) $economic['own_capital'] + (float) $economic['domestic_debt'] + (float) $economic['foreign_debt'] + (float) $economic['grants'];
|
||||
if (abs($funding - (float) $economic['total_investment']) > 0.01) {
|
||||
$validator->errors()->add('economic_snapshot.total_investment', 'A soma do capital, dívida e subvenções deve reconciliar com o investimento total.');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreSimulationRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'base' => ['required', 'numeric', 'min:0'],
|
||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||
'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateSimulationScenarioRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'label' => ['required', 'string', 'min:1', 'max:100'],
|
||||
'base' => ['required', 'numeric', 'min:0'],
|
||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PublicBusinessOpportunityResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Services\Mne\LegacyBusinessRepository;
|
||||
use App\Services\Mne\MneBusinessRepository;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
final class CompareMneBusiness implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public int $tries = 1;
|
||||
|
||||
public function __construct(public string $businessId) {}
|
||||
|
||||
public function handle(LegacyBusinessRepository $legacy, MneBusinessRepository $canonical): void
|
||||
{
|
||||
$start = hrtime(true);
|
||||
try {
|
||||
$source = $legacy->find($this->businessId);
|
||||
$comparison = $canonical->comparison($this->businessId);
|
||||
$expected = $source->only(['code', 'modality', 'status', 'classification', 'version_no']);
|
||||
$outcome = $comparison === null ? 'unmapped' : ($expected == $comparison ? 'core_match' : 'divergence');
|
||||
} catch (\Throwable) {
|
||||
$outcome = 'comparison_error';
|
||||
}
|
||||
// No payloads, query parameters, identifiers or exception messages in telemetry.
|
||||
Log::info('mne.compatibility.shadow', ['outcome' => $outcome, 'latency_ms' => (hrtime(true) - $start) / 1000000]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Simulation;
|
||||
use App\Services\SimulationExecution;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RunSimulation implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
public int $timeout = 30;
|
||||
|
||||
public function __construct(public string $simulationId, public ?int $actorId, public ?string $tokenHash) {}
|
||||
|
||||
/** @return list<int> */
|
||||
public function backoff(): array
|
||||
{
|
||||
return [10, 60];
|
||||
}
|
||||
|
||||
public function handle(SimulationExecution $execution): void
|
||||
{
|
||||
$shouldRun = DB::transaction(function () use ($execution): bool {
|
||||
$execution->setContext($this->actorId, $this->tokenHash);
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || in_array($job->status, ['succeeded', 'failed'], true)) {
|
||||
return false;
|
||||
}
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update([
|
||||
'status' => 'running', 'attempts' => min(3, max((int) $job->attempts + 1, (int) $this->attempts())),
|
||||
'started_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
if (! $shouldRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($execution): void {
|
||||
$execution->setContext($this->actorId, $this->tokenHash);
|
||||
$simulation = Simulation::whereNull('deleted_at')->lockForUpdate()->find($this->simulationId);
|
||||
if (! $simulation || $simulation->status === 'completed') {
|
||||
return;
|
||||
}
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || in_array($job->status, ['succeeded', 'failed'], true)) {
|
||||
return;
|
||||
}
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $simulation->id)->orderBy('code')->first();
|
||||
if (! $scenario) {
|
||||
throw new \RuntimeException('Simulation has no scenario.');
|
||||
}
|
||||
$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']]);
|
||||
$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);
|
||||
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(),
|
||||
]);
|
||||
$simulation->update(['status' => 'completed', 'version_no' => $simulation->version_no + 1, 'result_snapshot' => $result, 'error_code' => null]);
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update(['status' => 'succeeded', 'finished_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('simulation_reports')->insert(['id' => (string) Str::uuid(), 'simulation_id' => $simulation->id, 'version_no' => $scenario->version_no,
|
||||
'status' => 'ready', 'report_snapshot' => $json, 'report_sha256' => $resultHash, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$sourceJson = json_encode($input, JSON_THROW_ON_ERROR);
|
||||
$canonicalSource = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$sourceJson])->canonical;
|
||||
DB::table('simulation_result_sources')->insertOrIgnore(['id' => (string) Str::uuid(), 'result_id' => $resultId,
|
||||
'source_type' => 'user_input', 'source_id' => $scenario->id, 'source_version' => (string) $scenario->version_no,
|
||||
'source_snapshot' => $sourceJson, 'source_sha256' => hash('sha256', $canonicalSource), 'created_at' => now()]);
|
||||
DB::table('simulation_audit_events')->insert(['simulation_id' => $simulation->id, 'actor_user_id' => $simulation->owner_user_id,
|
||||
'action' => 'simulation.completed', 'correlation_id' => $simulation->id, 'data' => json_encode(['result_sha256' => hash('sha256', $json), 'attempt' => $job->attempts + 1], JSON_THROW_ON_ERROR), 'occurred_at' => now()]);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function failed(\Throwable $exception): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
app(SimulationExecution::class)->setContext($this->actorId, $this->tokenHash);
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || $job->status === 'succeeded') {
|
||||
return;
|
||||
}
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update(['status' => 'failed', 'attempts' => 3, 'finished_at' => now(), 'error_code' => 'execution_failed', 'updated_at' => now()]);
|
||||
$simulation = Simulation::where('id', $this->simulationId)->lockForUpdate()->first();
|
||||
if ($simulation) {
|
||||
if ($simulation->status !== 'failed') {
|
||||
$simulation->update(['status' => 'failed', 'version_no' => $simulation->version_no + 1, 'error_code' => 'execution_failed']);
|
||||
}
|
||||
DB::table('simulation_audit_events')->insert(['simulation_id' => $simulation->id, 'actor_user_id' => $this->actorId,
|
||||
'action' => 'simulation.failed', 'correlation_id' => $simulation->id, 'data' => json_encode(['error_code' => 'execution_failed'], JSON_THROW_ON_ERROR), 'occurred_at' => now()]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,5 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/** @property int $version_no */
|
||||
class ClusterProject extends DomainRecord {}
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -2,9 +2,51 @@
|
||||
|
||||
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'];
|
||||
|
||||
protected $casts = ['payload' => 'encrypted:array', 'version_no' => 'integer'];
|
||||
protected $casts = [
|
||||
'payload' => 'encrypted:array',
|
||||
'version_no' => 'integer',
|
||||
'amount_min' => 'decimal:2',
|
||||
'amount_max' => 'decimal:2',
|
||||
'available_percentage' => 'decimal:2',
|
||||
'submitted_at' => 'immutable_datetime',
|
||||
'published_at' => 'immutable_datetime',
|
||||
'expires_at' => 'immutable_datetime',
|
||||
'next_action_due_at' => 'immutable_datetime',
|
||||
];
|
||||
|
||||
/** @return BelongsTo<Sector, $this> */
|
||||
public function sector(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Sector::class);
|
||||
}
|
||||
|
||||
/** @param Builder<ExistingBusiness> $query
|
||||
* @return Builder<ExistingBusiness>
|
||||
*/
|
||||
public function scopePublished(Builder $query): Builder
|
||||
{
|
||||
return $query->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())
|
||||
->where(fn (Builder $q) => $q->whereNull('expires_at')->orWhere('expires_at', '>=', today()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class GeoLocation extends DomainRecord
|
||||
{
|
||||
protected $fillable = ['name', 'location_type', 'parent_id', 'code'];
|
||||
|
||||
/** @return BelongsTo<GeoLocation, $this> */
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<GeoLocation, $this> */
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Opportunity, $this> */
|
||||
public function opportunities(): HasMany
|
||||
{
|
||||
return $this->hasMany(Opportunity::class, 'primary_territory_id');
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,8 @@ class InterestRequest extends Model
|
||||
'investor_type', 'country', 'sector_interest',
|
||||
'opportunity_reference', 'investment_range', 'message',
|
||||
'privacy_consent', 'consented_at', 'status', 'source_page',
|
||||
'ip_address', 'user_agent', 'metadata', 'reviewed_at', 'reviewed_by',
|
||||
'ip_address', 'user_agent', 'metadata', 'reviewed_at', 'reviewed_by', 'existing_business_id', 'investor_id',
|
||||
'modality', 'requested_percentage', 'ticket_min', 'ticket_max', 'ticket_currency', 'assigned_to', 'next_action', 'next_action_due_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
@@ -23,6 +24,10 @@ class InterestRequest extends Model
|
||||
'consented_at' => 'datetime',
|
||||
'metadata' => 'array',
|
||||
'reviewed_at' => 'datetime',
|
||||
'requested_percentage' => 'decimal:2',
|
||||
'ticket_min' => 'decimal:2',
|
||||
'ticket_max' => 'decimal:2',
|
||||
'next_action_due_at' => 'immutable_datetime',
|
||||
];
|
||||
|
||||
/** @return BelongsTo<Opportunity, $this> */
|
||||
@@ -30,4 +35,22 @@ class InterestRequest extends Model
|
||||
{
|
||||
return $this->belongsTo(Opportunity::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ExistingBusiness, $this> */
|
||||
public function existingBusiness(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ExistingBusiness::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Investor, $this> */
|
||||
public function investor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Investor::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function assignee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'assigned_to');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,11 @@ class Investor extends Model
|
||||
'created_at' => 'immutable_datetime',
|
||||
'updated_at' => 'immutable_datetime',
|
||||
'deleted_at' => 'immutable_datetime',
|
||||
'investment_sectors' => 'array',
|
||||
'investment_geographies' => 'array',
|
||||
'investment_horizon_months' => 'integer',
|
||||
'ticket_min' => 'decimal:2',
|
||||
'ticket_max' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -5,13 +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 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',
|
||||
@@ -20,10 +33,12 @@ class Opportunity extends Model
|
||||
'expected_impact', 'status', 'is_featured', 'published_at',
|
||||
'last_validated_at',
|
||||
'primary_territory_id', 'territory_version',
|
||||
'geography_scope',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_featured' => 'boolean',
|
||||
'territory_version' => 'integer',
|
||||
'published_at' => 'datetime',
|
||||
'last_validated_at' => 'datetime',
|
||||
'estimated_investment_amount' => 'decimal:2',
|
||||
@@ -35,11 +50,24 @@ class Opportunity extends Model
|
||||
return $this->belongsTo(Sector::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<GeoLocation, $this> */
|
||||
public function primaryTerritory(): BelongsTo
|
||||
{
|
||||
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'");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $version_no */
|
||||
class QuestionnaireVersion extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['schema_snapshot' => 'array', 'valid_from' => 'date', 'valid_to' => 'date'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
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
|
||||
* @property int|null $owner_user_id
|
||||
* @property string|null $organization_id
|
||||
* @property string|null $anonymous_token_hash
|
||||
* @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
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['input_snapshot' => 'array', 'result_snapshot' => 'array', 'calculation_snapshot' => 'array'];
|
||||
|
||||
/** @return HasMany<SimulationScenario, $this> */
|
||||
public function scenarios(): HasMany
|
||||
{
|
||||
return $this->hasMany(SimulationScenario::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<SimulationReport, $this> */
|
||||
public function reports(): HasMany
|
||||
{
|
||||
return $this->hasMany(SimulationReport::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
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', 'expires_at', 'claimed_token_hash',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['version_no' => 'integer', 'deleted_at' => 'immutable_datetime', 'expires_at' => 'immutable_datetime'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot */
|
||||
public static function encryptSnapshot(array $snapshot): string
|
||||
{
|
||||
return Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function decryptSnapshot(string $snapshot): array
|
||||
{
|
||||
$decoded = json_decode(Crypt::decryptString($snapshot), true, 32, JSON_THROW_ON_ERROR);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationJob extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationObligation extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['report_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationResult extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['result_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationResultSource extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['source_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationScenario extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['parameters' => 'array'];
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,14 @@ class ExistingBusinessPolicy
|
||||
|
||||
public function view(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->owns($user, $business) || $this->review($user, $business);
|
||||
if ($this->owns($user, $business) || $this->review($user, $business) || $this->triage($user, $business)
|
||||
|| $this->approveLevelOne($user, $business) || $this->approveLevelTwo($user, $business) || $this->publish($user, $business)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['rejected', 'published', 'suspended', 'cancelled', 'archived'], true)
|
||||
&& $this->reviewQueue($user);
|
||||
}
|
||||
|
||||
public function delete(User $user, ExistingBusiness $business): bool
|
||||
@@ -35,13 +42,53 @@ class ExistingBusinessPolicy
|
||||
public function review(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['submitted', 'in_review', 'needs_information'], true)
|
||||
&& $this->reviewQueue($user);
|
||||
&& in_array($business->status, ['triage', 'in_review', 'needs_information'], true)
|
||||
&& $this->designated($user, 'reviewers');
|
||||
}
|
||||
|
||||
public function triage(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['submitted', 'triage'], true)
|
||||
&& $this->designated($user, 'triagers');
|
||||
}
|
||||
|
||||
public function approveLevelOne(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l1'
|
||||
&& $this->designated($user, 'approvers_l1');
|
||||
}
|
||||
|
||||
public function approveLevelTwo(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l2'
|
||||
&& $this->designated($user, 'approvers_l2');
|
||||
}
|
||||
|
||||
public function publish(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approved'
|
||||
&& $this->designated($user, 'publishers');
|
||||
}
|
||||
|
||||
public function reviewQueue(User $user): bool
|
||||
{
|
||||
return $user->can('manage-portal') && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
|
||||
foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) {
|
||||
if ($this->designated($user, $designation)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function designated(User $user, string $designation): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $user->can('manage-portal')
|
||||
&& (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.'.$designation, []), true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\Simulation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SimulationPolicy
|
||||
{
|
||||
public function view(User $user, Simulation $simulation): bool
|
||||
{
|
||||
if ($simulation->organization_id === null && $simulation->owner_user_id === $user->id && $user->hasVerifiedEmail()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $simulation->organization_id !== null && $user->hasVerifiedEmail()
|
||||
&& DB::table('memberships')->where('user_id', $user->id)
|
||||
->where('organization_id', $simulation->organization_id)->whereNull('deleted_at')->exists();
|
||||
}
|
||||
|
||||
public function update(User $user, Simulation $simulation): bool
|
||||
{
|
||||
if (! $user->hasVerifiedEmail() || ! in_array($simulation->status, ['queued', 'completed', 'failed'], true)) {
|
||||
return false;
|
||||
}
|
||||
if ($simulation->organization_id === null) {
|
||||
return $simulation->owner_user_id === $user->id;
|
||||
}
|
||||
|
||||
return DB::table('memberships')->where('user_id', $user->id)->where('organization_id', $simulation->organization_id)
|
||||
->whereNull('deleted_at')->whereIn('role', ['admin', 'manager', 'officer'])->exists();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ 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;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -23,7 +27,9 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
$this->app->bind(MalwareScanner::class, ClamDScanner::class);
|
||||
|
||||
$this->app->bind(BusinessRepository::class, CompatibleBusinessRepository::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +53,45 @@ class AppServiceProvider extends ServiceProvider
|
||||
$model::deleted($invalidate);
|
||||
}
|
||||
|
||||
RateLimiter::for('api', fn (Request $request) => Limit::perMinute(60)->by($request->ip()));
|
||||
$requestLimitKey = static function (Request $request): string {
|
||||
if ($user = $request->user()) {
|
||||
return 'user:'.$user->getAuthIdentifier();
|
||||
}
|
||||
|
||||
$token = $request->header('X-Simulation-Token');
|
||||
|
||||
return is_string($token) && $token !== ''
|
||||
? 'anonymous:'.hash('sha256', $token)
|
||||
: 'ip:'.$request->ip();
|
||||
};
|
||||
|
||||
RateLimiter::for('api', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(60)->by($requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Demasiadas solicitações. Aguarde um pouco e tente novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-draft-writes', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(30)->by('simulation-draft:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram guardadas demasiadas alterações em pouco tempo. Aguarde um minuto e tente novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-calculations', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(10)->by('simulation-calculation:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram solicitados demasiados cálculos em pouco tempo. Aguarde antes de tentar novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-scenario-updates', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(10)->by('simulation-scenario-update:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram solicitadas demasiadas alterações de cenário em pouco tempo. Aguarde antes de tentar novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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());
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user