vrsao 2
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-08 14:02:01 +02:00
parent bdd766c68a
commit 1106509116
354 changed files with 48275 additions and 24635 deletions
@@ -46,6 +46,7 @@ class CheckDocumentLibrarySchema extends Command
foreach ($required as $table => $columns) {
if (! Schema::hasTable($table)) {
$missing[] = "tabela {$table}";
continue;
}
+1 -1
View File
@@ -14,7 +14,7 @@ class CheckMalwareScanner extends Command
public function handle(MalwareScanner $scanner): int
{
$health = $scanner->health();
$this->line('Scanner: '.($health['engine'] ?? 'ClamAV'));
$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'));
+1 -1
View File
@@ -131,7 +131,7 @@ class ImportDocumentBatch extends Command
}
try {
$resourceId = DB::transaction(function () use ($validated, $documentId, $storageKey, $hash, $identity, $disk, $actorId): int {
$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()) {
@@ -17,7 +17,7 @@ class ImportIndustrialParkCandidates extends Command
public function handle(): int
{
$document = json_decode(file_get_contents(database_path('data/industrial-park-candidate-drafts.json')), true, flags: JSON_THROW_ON_ERROR);
$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.');
@@ -106,4 +106,14 @@ class ImportIndustrialParkCandidates extends Command
{
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;
}
}
+13 -3
View File
@@ -17,7 +17,7 @@ class ImportInvestmentZones extends Command
public function handle(): int
{
$path = database_path('data/investment-zones-initial.json');
$document = json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);
$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']);
@@ -59,12 +59,12 @@ class ImportInvestmentZones extends Command
continue;
}
$record = collect($document['records'])->firstWhere('code', $row['code']);
$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;
$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,
@@ -120,4 +120,14 @@ class ImportInvestmentZones extends Command
{
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;
}
}
@@ -36,8 +36,7 @@ class ImportLegalSourceArchive extends Command
continue;
}
$withinApprovedRoot = $realSource && collect($approvedRoots)->contains(fn (string $root) =>
str_starts_with(strtolower($realSource), strtolower($root.DIRECTORY_SEPARATOR)));
$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++;
@@ -83,7 +82,7 @@ class ImportLegalSourceArchive extends Command
continue;
}
$missingEvidence = collect($record['associations'])->filter(fn (array $association) => $association['target_type'] === 'requirement')
$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()) {
@@ -110,6 +109,7 @@ class ImportLegalSourceArchive extends Command
}
$this->line($record['external_id'].' | reused/reconciled | document='.$existing->id.' | published='.($resource->published ? 'yes' : 'no'));
continue;
}
@@ -263,13 +263,13 @@ class ImportLegalSourceArchive extends Command
...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.'],
]),
['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.'],
]),
],
],
[
@@ -310,4 +310,3 @@ class ImportLegalSourceArchive extends Command
];
}
}
@@ -95,7 +95,7 @@ class InvestmentZoneAttachmentController extends Controller
return DB::transaction(function () use ($request, $id, $action, $data): JsonResponse {
$attachment = DB::table('investment_zone_attachments')->where('id', $id)->lockForUpdate()->first();
abort_unless($attachment, 404);
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()];
@@ -137,7 +137,7 @@ class InvestmentZoneAttachmentController extends Controller
->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, 404);
abort_unless($record !== null, 404);
return $this->verifiedDownload($zoneId, $record);
}
@@ -150,7 +150,7 @@ class InvestmentZoneAttachmentController extends Controller
->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, 404);
abort_unless($record !== null, 404);
$extension = match ($record->media_type) {
'application/pdf' => 'pdf', 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', default => 'bin'
@@ -159,7 +159,7 @@ class InvestmentZoneAttachmentController extends Controller
return $this->verifiedDownload($zoneId, $record, str_starts_with($record->media_type, 'image/'), 'zone-attachment-'.$id.'.'.$extension);
}
private function verifiedDownload(string $zoneId, object $document, bool $inline = false, ?string $downloadName = null): BinaryFileResponse
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));
@@ -195,6 +195,7 @@ class InvestmentZoneAttachmentController extends Controller
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([
@@ -17,6 +17,7 @@ use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class InvestmentZoneController extends Controller
{
@@ -92,7 +93,7 @@ class InvestmentZoneController extends Controller
$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 ($zone) use ($management) {
$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);
@@ -110,7 +111,7 @@ class InvestmentZoneController extends Controller
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
}
public function export(Request $request, InvestmentZones $zones)
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'],
@@ -123,6 +124,9 @@ class InvestmentZoneController extends Controller
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 {
@@ -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);
}
}
@@ -4,8 +4,8 @@ declare(strict_types=1);
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Http\Requests\StoreLandAssistanceCaseRequest;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\LandAssistanceCase;
use App\Services\InterestSubmission;
@@ -8,10 +8,11 @@ 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\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@@ -47,7 +48,7 @@ class PortalServicesController extends Controller
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256');
}
public function page(Request $request): Response|JsonResponse
public function page(Request $request): Response|JsonResponse|RedirectResponse
{
$page = $request->route()->defaults['page'];
if ($page === 'partnerships' && Schema::hasColumn('portal_partnerships', 'partnership_type')) {
@@ -105,12 +106,12 @@ class PortalServicesController extends Controller
}
$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();
'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());
@@ -153,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']);
}
@@ -161,7 +165,7 @@ class PortalServicesController extends Controller
return Inertia::render('portal/services', $props);
}
public function recommendations(Request $request)
public function recommendations(Request $request): JsonResponse
{
$data = $request->validate([
'activity_id' => ['nullable', 'string', 'max:180'], 'province_id' => ['nullable', 'uuid'],
@@ -199,10 +203,11 @@ class PortalServicesController extends Controller
? 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',
'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),
@@ -357,7 +362,7 @@ class PortalServicesController extends Controller
return Inertia::render('portal/manage', ['resources' => $resources,
'requirementCatalogue' => $this->requirementEvidenceEnabled()
? collect(config('document-requirements.catalogue'))->map(fn ($item, $key) => ['key' => $key, ...$item])->values()
? 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(),
@@ -548,10 +553,12 @@ class PortalServicesController extends Controller
]);
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);
@@ -565,12 +572,14 @@ class PortalServicesController extends Controller
|| ! 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;
}
@@ -600,6 +609,7 @@ class PortalServicesController extends Controller
->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,
@@ -641,6 +651,7 @@ class PortalServicesController extends Controller
}
}
/** @return array<string,mixed> */
private function validateResource(Request $request): array
{
$data = $this->validateManagement($request, [
@@ -691,6 +702,9 @@ class PortalServicesController extends Controller
/** 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
{
@@ -701,6 +715,7 @@ class PortalServicesController extends Controller
}
}
/** @param array<string,string|list<string>> $errors */
private function managementValidationException(array $errors): ValidationException
{
$exception = ValidationException::withMessages($errors);
@@ -709,6 +724,8 @@ class PortalServicesController extends Controller
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']);
@@ -725,6 +742,7 @@ class PortalServicesController extends Controller
return $data;
}
/** @param list<array<string,mixed>> $links */
private function syncResourceLinks(int $resourceId, array $links): void
{
foreach ($links as $link) {
@@ -741,7 +759,8 @@ class PortalServicesController extends Controller
}
}
private function assertPublicClassificationEligible(array $data, object $document): void
/** @param array<string,mixed> $data */
private function assertPublicClassificationEligible(array $data, \stdClass $document): void
{
if (($data['data_classification'] ?? $document->data_classification) !== 'public') {
return;
@@ -756,6 +775,7 @@ class PortalServicesController extends Controller
'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'])) {
@@ -782,6 +802,7 @@ class PortalServicesController extends Controller
&& 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'];
@@ -792,9 +813,10 @@ class PortalServicesController extends Controller
return $columns;
}
/** @return list<string> */
private function territoryScopeIds(string $id): array
{
return collect(DB::select(<<<'SQL'
$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
@@ -803,6 +825,15 @@ WITH RECURSIVE territory_tree AS (
WHERE child.deleted_at IS NULL AND child.data_classification = 'public'
)
SELECT id FROM territory_tree
SQL, [$id]))->pluck('id')->all() ?: [$id];
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];
}
}
+146 -53
View File
@@ -4,29 +4,41 @@ 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)
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)), mb_strtolower($filters['q'])))
$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)
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');
@@ -34,188 +46,269 @@ class VirtualDeskController extends Controller
$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)->orderByDesc('created_at')->get(['reference', 'status', 'created_at']),
'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']),
'companies' => DB::table('investment_company_declarations')->where('user_id', $actor->id)->get(['id', 'payload'])->map(fn ($c) => ['id' => $c->id, 'name' => $desk->decode($c->payload)['name'] ?? 'Declaração empresarial']),
'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)
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);
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)
public function showCase(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response
{
$case = $desk->case($request->user(), $id); $owner = $desk->owns($request->user(), $case, false);
$case = $desk->case($request->user(), $id);
$owner = $desk->owns($request->user(), $case, false);
$this->auditRead($request, 'desk_cases', $id);
$data = ['case' => [...(array) $case, 'payload' => \Illuminate\Support\Arr::except($desk->decode($case->payload), ['_creation_hash']), 'workflow' => json_decode($case->workflow, true)],
$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), 'events' => $this->events($id, $desk), 'stepStates' => config('virtual-desk.step_states'), 'states' => config('virtual-desk.request_states'),
'links' => DB::table('desk_institutional_links')->where('status', 'active')->whereNotNull('verified_at')->get(['id', 'stage', 'entity', 'purpose', 'contact', 'verified_at']), 'source' => config('virtual-desk.source')];
'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);
}
private function documents(string $case)
/** @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']);
}
private function events(string $case, VirtualDesk $desk)
/** @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)->orderBy('e.created_at')->get(['e.id', 'e.request_id', 'e.action', 'e.payload', 'e.version', 'e.created_at', 'u.name'])->map(fn ($e) => [...(array) $e, 'payload' => $desk->decode($e->payload)]);
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)
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)
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)
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);
$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], 'definition' => $desk->definition($row),
'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)->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.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => \Illuminate\Support\Facades\Crypt::decryptString($m->body)]),
'events' => $this->events($case->id, $desk)->filter(fn ($e) => $e['request_id'] === $id)->values(),
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
'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(\App\Services\InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type'])];
'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)
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)
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)
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);
$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::findOrFail($data['analyst_id']); abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.');
$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)
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);
$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(\Illuminate\Support\Facades\Crypt::decryptString($existing->body) === $data['body'], 409); return; }
DB::table('desk_messages')->insert(['id' => (string) Str::uuid(), 'request_id' => $id, 'actor_id' => $request->user()->id, 'client_key' => $data['client_key'], 'body' => \Illuminate\Support\Facades\Crypt::encryptString($data['body'])]);
$desk->event($case, $request->user(), 'message_added', [], $row);
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)
public function receipt(Request $request, string $id, VirtualDesk $desk): StreamedResponse
{
$row = $desk->request($request->user(), $id); abort_unless($row->protocol && $row->submitted_snapshot, 404);
$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)
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;
$key = null;
$newId = null;
try {
DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId) {
$case = $desk->case($request->user(), $id, true, true); 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);
$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());
$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($key, 500);
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, 404);
$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;
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();
} 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)
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.*']);
$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) && hash_equals(trim($doc->sha256), hash_file('sha256', $path)), 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)
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)
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)->where('status', 'active')->whereNotNull('verified_at')->first(); abort_unless($link, 404);
$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']);
}
@@ -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);
}
}
@@ -4,6 +4,7 @@ namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
@@ -44,7 +45,7 @@ final class EnsureSimulationRecoveryCookie
$expiry = is_array($payload) ? ($payload['expires_at'] ?? null) : null;
if (is_string($expiry)) {
try {
$secondsLeft = \Illuminate\Support\Carbon::parse($expiry)->getTimestamp() - now()->getTimestamp();
$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.
@@ -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,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);
}
}
@@ -68,16 +68,16 @@ class StoreSimulationFormDraftRequest extends FormRequest
'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.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'],
+18 -7
View File
@@ -14,7 +14,7 @@ use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;
class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@@ -31,6 +31,7 @@ class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
return $this->documentId;
}
/** @return list<int> */
public function backoff(): array
{
return [15, 60];
@@ -38,7 +39,7 @@ class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
public function handle(MalwareScanner $scanner): void
{
$document = DB::transaction(function (): ?object {
$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;
@@ -66,8 +67,8 @@ class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
$disk = Storage::disk('local');
$root = $disk->path('');
$path = $disk->path($document->storage_key);
$beforeHash = is_file($path) ? hash_file('sha256', $path) : false;
if (! is_string($beforeHash) || ! hash_equals(trim($document->sha256), $beforeHash)) {
$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,
@@ -78,8 +79,8 @@ class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
$result = $scanner->scan($path, (int) ($document->size_bytes ?? filesize($path)), $root);
$afterHash = is_file($path) ? hash_file('sha256', $path) : false;
if (! is_string($afterHash) || ! hash_equals(trim($document->sha256), $afterHash)) {
$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;
@@ -102,7 +103,17 @@ class ScanDocumentForMalware implements ShouldQueue, ShouldBeUnique
], now(), 'failed');
}
private function record(object $document, array $result, \DateTimeInterface $startedAt, string $state): void
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();
+6 -1
View File
@@ -2,7 +2,12 @@
namespace App\Models;
/** @property string|null $lead_id */
use Carbon\CarbonImmutable;
/**
* @property string|null $lead_id
* @property CarbonImmutable|null $due_at
*/
class CrmTask extends CrmRecord
{
protected $table = 'tasks';
+1
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
/** @property array<string,mixed> $payload */
class InvestmentSubmission extends Model
{
use HasUuids;
+15
View File
@@ -5,6 +5,21 @@ 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', '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'];
+2 -2
View File
@@ -5,10 +5,10 @@ namespace App\Providers;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibleBusinessRepository;
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;
+4
View File
@@ -34,6 +34,10 @@ final class EvidenceRepository
if (! empty($filters['nature'])) {
$builder->where('s.nature', $filters['nature']);
}
if ($filters['public_only'] ?? false) {
$builder->where('d.data_classification', 'public')->where('d.rights_status', '!=', 'restricted')
->whereExists(fn ($q) => $q->selectRaw('1')->from('portal_resources as r')->whereColumn('r.document_id', 'd.id')->where('r.published', true)->where('r.rights_status', '!=', 'restricted'));
}
return array_values($builder->orderByDesc('rank')->orderBy('c.id')->limit((int) config('investmoz_ai.retrieval_limit', 5))
->get()->map(fn ($row) => (array) $row)->all());
+255
View File
@@ -0,0 +1,255 @@
<?php
namespace App\Services\Ai;
use App\Models\CrmTask;
use App\Models\InvestmentSubmission;
use App\Models\SimulationFormDraft;
use App\Models\User;
use App\Services\InvestmentGeography;
use App\Services\VirtualDesk;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class InvestorGuidance
{
public function __construct(private VirtualDesk $desk, private InvestorGuidanceRules $rules) {}
public function installed(): bool
{
return Schema::hasColumn('tasks', 'desk_case_id');
}
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator. */
/** @return array<string,mixed> */
public function context(User $actor, \stdClass $case): array
{
$base = $this->desk->decode($case->payload);
$facts = Arr::only($base['guidance']['assumptions'] ?? [], InvestorGuidanceRules::FIELDS);
$consulted = [];
$unavailable = [];
$financialDraft = null;
$checks = [];
$revision = ['case' => (int) $case->version];
$submission = $case->submission_id ? InvestmentSubmission::where('id', $case->submission_id)->where('user_id', $actor->id)->first() : null;
if ($submission) {
$input = $submission->payload;
$mapped = ['project_title' => $input['title'] ?? $case->title, 'project_summary' => $input['objective'] ?? '',
'activity' => $input['activity_description'] ?? '', 'schedule' => $input['schedule'] ?? ''];
$facts = [...$mapped, ...$facts];
$consulted[] = ['module' => 'investment_submission', 'id' => $submission->id, 'version' => $submission->version, 'date' => $submission->updated_at?->toIso8601String(), 'status' => 'investor_declaration'];
$revision['submission'] = $submission->version;
} elseif ($case->submission_id) {
$unavailable[] = 'investment_submission_permission_or_availability';
}
if ($case->simulation_id) {
$draft = SimulationFormDraft::where('id', $case->simulation_id)->where('owner_user_id', $actor->id)->whereNull('deleted_at')
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->first();
if ($draft) {
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$mapped = Arr::only($economic, InvestorGuidanceRules::FIELDS);
$mapped['activity'] = $economic['selection_labels']['activity_id'] ?? $economic['products_services'] ?? '';
// A market assumption is not evidence of demand.
if (! empty($economic['market_source'])) {
$mapped['market_evidence'] = $economic['market_source'];
}
$mapped['location'] = $economic['selection_labels']['province_id'] ?? '';
$mapped['location_evidence'] = $economic['location_rationale'] ?? '';
if (! empty($economic['skills_needed'])) {
$mapped['resource_plan'] = $economic['skills_needed'];
}
$checks = $this->catalogueChecks($economic);
$facts = [...$mapped, ...$facts];
// Only economic fields needed by existing deterministic calculators, never personal_snapshot.
$financialDraft = Arr::only($economic, ['business_plan_snapshot', 'financial_tools_snapshot', 'currency']);
$consulted[] = ['module' => 'simulation_form_draft', 'id' => $draft->id, 'version' => $draft->version_no, 'hash' => $draft->snapshot_sha256,
'date' => $draft->updated_at?->toIso8601String(), 'status' => 'declared_assumptions_and_versioned_snapshots'];
$revision['simulation'] = [$draft->version_no, $draft->snapshot_sha256];
} else {
$unavailable[] = 'simulation_draft_permission_or_availability';
}
}
$facts['project_title'] = $facts['project_title'] ?? $case->title;
$evidence = app(InvestorGuidanceEvidence::class)->forCase($actor, $case, $this->desk);
$fingerprint = hash('sha256', json_encode([InvestorGuidanceRules::VERSION, $revision, Arr::sortRecursive($facts), $checks, $evidence], JSON_THROW_ON_ERROR));
return ['facts' => $facts, 'consulted' => $consulted, 'unavailable' => $unavailable, 'financial_draft' => $financialDraft, 'fingerprint' => $fingerprint, 'catalogue_checks' => $checks, 'evidence' => $evidence];
}
/** @param array<string,mixed> $economic
* @return list<array<string,mixed>> */
private function catalogueChecks(array $economic): array
{
$checks = [];
if (! empty($economic['activity_id'])) {
$activity = DB::table('economic_activities as a')->join('reference_catalog_versions as v', 'v.id', '=', 'a.catalog_version_id')
->where('a.id', $economic['activity_id'])->where('a.status', 'published')->where('v.status', 'published')
->whereDate('a.valid_from', '<=', today())->where(fn ($q) => $q->whereNull('a.valid_to')->orWhereDate('a.valid_to', '>', today()))
->first(['a.id', 'a.sector_id', 'a.catalog_version_id']);
$classification = ! $activity || empty($economic['sector_id']) ? 'insufficient_information'
: ((int) $activity->sector_id === (int) $economic['sector_id'] ? 'catalogue_consistent' : 'documented_incompatibility');
$checks[] = ['code' => 'activity_sector', 'classification' => $classification, 'restriction' => false,
'explanation' => match ($classification) {
'documented_incompatibility' => 'A actividade e o sector seleccionados não correspondem no catálogo publicado consultado.',
'catalogue_consistent' => 'Actividade e sector correspondem no catálogo consultado; isto não prova mercado ou elegibilidade.',
default => 'Sem referência actual autorizada suficiente para verificar actividade e sector.',
}, 'source' => $activity ? ['module' => 'economic_activities', 'id' => $activity->id, 'version_id' => $activity->catalog_version_id] : null];
}
$parents = ['district_id' => 'province_id', 'admin_post_id' => 'district_id', 'locality_id' => 'admin_post_id'];
foreach ($parents as $child => $parent) {
if (empty($economic[$child])) {
continue;
}
$location = app(InvestmentGeography::class)->publicReferences()->where('id', $economic[$child])->first(['id', 'parent_id']);
$classification = ! $location || empty($economic[$parent]) ? 'insufficient_information'
: ($location->parent_id === $economic[$parent] ? 'catalogue_consistent' : 'documented_incompatibility');
$checks[] = ['code' => 'territory_'.$child, 'classification' => $classification, 'restriction' => false,
'explanation' => match ($classification) {
'documented_incompatibility' => 'A hierarquia territorial declarada contradiz a referência publicada consultada.',
'catalogue_consistent' => 'Hierarquia territorial coerente na referência consultada; disponibilidade e infraestrutura continuam por confirmar.',
default => 'Referência territorial insuficiente ou indisponível para esta verificação.',
}, 'source' => $location ? ['module' => 'geo_locations', 'id' => $location->id, 'parent_id' => $location->parent_id] : null];
}
return $checks;
}
/** @return array<string,mixed> */
public function view(User $actor, string $id): array
{
$case = $this->desk->case($actor, $id);
abort_unless($this->installed(), 503, 'A extensão do acompanhamento aguarda instalação autenticada.');
$context = $this->context($actor, $case);
$choices = [];
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', 'recommendation_reviewed')->orderBy('event_order')->get() as $event) {
$data = $this->desk->decode($event->payload);
$choices[$data['code']] = [...$data, 'actor_id' => $event->actor_id, 'date' => $event->created_at, 'stale' => $data['context_hash'] !== $context['fingerprint']];
}
$actions = ['opportunities' => '/oportunidades', 'locations' => '/oportunidades?view=map', 'partners' => '/parcerias',
'documents' => '/documentos', 'plan' => $case->submission_id && (int) $case->user_id === $actor->id ? '/investidor/manifestacoes/'.$case->submission_id : '/balcao-virtual/dossiers/'.$id,
'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id];
// The simulator recovers its current owner-scoped draft; do not pass private payload in URLs.
if ($case->simulation_id && $context['financial_draft'] !== null) {
$actions['plan'] = '/simulador-fiscal';
}
$phases = $this->rules->evaluate($context['facts'], $context['evidence']);
foreach ($phases as &$phase) {
foreach ($phase['recommendations'] as &$recommendation) {
$recommendation['review'] = $choices[$recommendation['code']] ?? null;
$recommendation['href'] = $actions[$recommendation['action']];
}
unset($recommendation);
}
unset($phase);
$tasks = DB::table('tasks as t')->leftJoin('users as u', 'u.id', '=', 't.assignee_user_id')->where('t.desk_case_id', $id)->whereNull('t.deleted_at')
->when(! $this->desk->owns($actor, $case, false) && ! $actor->can('manage-portal'), fn ($q) => $q->where('t.assignee_user_id', $actor->id))
->get(['t.id', 't.title', 't.status', 't.due_at', 't.version_no', 't.desk_request_id', 't.accepted_by', 't.accepted_at', 't.assignee_user_id', 'u.name as assignee_name', 't.external_sync_status']);
return ['version' => $case->version, 'rules_version' => InvestorGuidanceRules::VERSION, 'computed_at' => now()->toIso8601String(),
...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => $this->desk->owns($actor, $case),
'external_ai' => ['status' => 'not_configured', 'model' => null, 'consulted' => []],
'calculator_versions' => ['business_financial_plan' => hash_file('sha256', resource_path('js/lib/business-financial-plan.ts')), 'financial_calculators' => hash_file('sha256', resource_path('js/lib/financial-calculators.ts')), 'project_dossier' => hash_file('sha256', resource_path('js/lib/project-dossier.ts'))],
'crm' => ['internal' => 'available', 'external' => 'out_of_scope', 'reason' => 'O acompanhamento usa o CRM interno existente. A sincronização externa está fora desta fase; nenhum contacto, mensagem ou documento é transmitido.']];
}
/** @param array<string,mixed> $input */
public function assumptions(User $actor, string $id, array $input): void
{
$rules = ['version' => 'required|integer|min:1', 'assumptions' => ['required', 'array:'.implode(',', InvestorGuidanceRules::FIELDS)]];
foreach (InvestorGuidanceRules::FIELDS as $field) {
$rules['assumptions.'.$field] = in_array($field, ['expected_start_date', 'ready_date', 'funding_ready_date', 'completion_date'], true) ? 'nullable|date_format:Y-m-d' : 'nullable|string|max:3000';
}
$data = Validator::make($input, $rules)->validate();
DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === (int) $data['version'], 409, 'Dossier alterado; recarregue antes de corrigir.');
$base = $this->desk->decode($case->payload);
$base['guidance']['assumptions'] = $data['assumptions'];
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($base), 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event(DB::table('desk_cases')->where('id', $id)->first(), $actor, 'assumptions_corrected', ['assumptions' => $data['assumptions'], 'origin' => 'investor_correction_not_official_data']);
});
}
/** @param array<string,mixed> $input */
public function feedback(User $actor, string $id, array $input): void
{
$data = Validator::make($input, ['code' => 'required|string|max:100', 'context_hash' => 'required|string|size:64',
'decision' => ['required', Rule::in(['accepted', 'rejected', 'corrected'])], 'reason' => 'required|string|min:3|max:3000'])->validate();
DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$view = $this->view($actor, $id);
abort_unless(hash_equals($view['fingerprint'], $data['context_hash']), 409, 'Pressupostos alterados; reveja a recomendação actual.');
$recommendations = array_merge(...array_column($view['phases'], 'recommendations'));
abort_unless(in_array($data['code'], array_column($recommendations, 'code'), true), 422);
$this->desk->event($case, $actor, 'recommendation_reviewed', [...$data, 'rules_version' => InvestorGuidanceRules::VERSION, 'creates_task' => false]);
});
}
/** @param array<string,mixed> $input */
public function acceptTask(User $actor, string $id, array $input): CrmTask
{
$data = Validator::make($input, ['code' => 'required|string|max:100', 'context_hash' => 'required|string|size:64', 'consent' => 'accepted',
'due_at' => 'required|date|after:now', 'request_id' => 'nullable|uuid'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$view = $this->view($actor, $id);
abort_unless(hash_equals($view['fingerprint'], $data['context_hash']), 409);
$recommendations = array_merge(...array_column($view['phases'], 'recommendations'));
$suggestion = collect($recommendations)->firstWhere('code', $data['code']);
abort_unless($suggestion && ($suggestion['review']['decision'] ?? null) === 'accepted' && ! $suggestion['review']['stale'], 422, 'Aceite a recomendação actual antes de assumir a tarefa.');
if ($data['request_id'] ?? null) {
$request = $this->desk->request($actor, $data['request_id'], true);
abort_unless($request->case_id === $id, 422);
}
// One accepted action per suggestion, even after corrections or retries.
$existing = CrmTask::where('desk_case_id', $id)->where('guidance_key', $data['code'])->first();
if ($existing) {
abort_unless($existing->getAttribute('desk_request_id') === ($data['request_id'] ?? null)
&& (int) $existing->getAttribute('accepted_by') === $actor->id && $existing->due_at !== null && $existing->due_at->equalTo(Carbon::parse($data['due_at'])), 409, 'A tarefa já foi assumida com outros dados; reveja o registo existente.');
return $existing;
}
$task = CrmTask::create(['desk_case_id' => $id, 'desk_request_id' => $data['request_id'] ?? null, 'guidance_key' => $data['code'],
'title' => $suggestion['explanation'], 'status' => 'open', 'due_at' => $data['due_at'], 'assignee_user_id' => $actor->id,
'accepted_by' => $actor->id, 'accepted_at' => now(), 'external_sync_status' => 'pending_authorization',
'source_system' => 'investor-guidance', 'data_classification' => 'confidential']);
$this->desk->event($case, $actor, 'guidance_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'context_hash' => $data['context_hash'], 'due_at' => $data['due_at'], 'scope' => 'internal_crm']);
return $task;
});
}
/** @param array<string,mixed> $input */
public function updateTask(User $actor, string $id, string $taskId, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])],
'reason' => 'required|string|min:3|max:3000', 'assignee_user_id' => 'nullable|integer|exists:users,id', 'due_at' => 'nullable|date|after:now'])->validate();
DB::transaction(function () use ($actor, $id, $taskId, $data) {
$case = $this->desk->case($actor, $id);
$task = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->lockForUpdate()->firstOrFail();
abort_unless($actor->can('manage-portal') || (int) $task->getAttribute('assignee_user_id') === $actor->id, 403);
abort_unless((int) $task->getAttribute('version_no') === (int) $data['version'], 409);
$updates = ['status' => $data['status'], 'version_no' => $data['version'] + 1];
if ($data['assignee_user_id'] ?? null) {
abort_unless($actor->can('manage-portal'), 403);
$assignee = User::where('id', $data['assignee_user_id'])->firstOrFail();
abort_unless($assignee->hasVerifiedEmail(), 422, 'Responsável sem conta verificada.');
abort_unless($assignee->can('manage-portal') || DB::table('desk_requests')->where('case_id', $id)->where('analyst_id', $assignee->id)->exists() || $this->desk->owns($assignee, $case), 422, 'Responsável sem acesso ao dossier.');
$updates['assignee_user_id'] = $assignee->id;
}
if ($data['due_at'] ?? null) {
$updates['due_at'] = $data['due_at'];
}
$task->update($updates);
$this->desk->event($case, $actor, 'guidance_task_updated', ['task_id' => $task->id, ...$data, 'kind' => $actor->can('manage-portal') ? 'responsible_response' : 'investor_action']);
});
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Services\Ai;
use App\Models\User;
use App\Services\VirtualDesk;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class InvestorGuidanceEvidence
{
public const FIELDS = ['market_evidence', 'location_evidence', 'resource_evidence', 'funding_evidence'];
/** @return array<string,array<string,mixed>> */
public function forCase(User $actor, \stdClass $case, VirtualDesk $desk): array
{
$privateScope = ! $desk->owns($actor, $case, false) && ! $actor->can('manage-portal');
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case->id)->whereNull('d.deleted_at')
->when($privateScope, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->get(['l.id as link_id', 'l.document_id', 'l.category', 'l.valid_until', 'd.file_name', 'd.version_no', 'd.sha256', 'd.status', 'd.malware_scan_status', 'd.malware_scanned_sha256', 'd.storage_key']);
$reviews = DB::table('desk_events as e')->join('users as u', 'u.id', '=', 'e.actor_id')->where('e.case_id', $case->id)->where('e.action', 'document_reviewed')
->when($privateScope, fn ($q) => $q->where(fn ($p) => $p->whereNull('e.request_id')->orWhereIn('e.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->orderByDesc('e.event_order')->get(['e.id', 'e.payload', 'e.created_at', 'e.actor_id', 'u.name']);
$result = [];
foreach (self::FIELDS as $field) {
$records = [];
foreach ($documents as $doc) {
$latest = null;
foreach ($reviews as $review) {
$payload = $desk->decode($review->payload);
if (($payload['link_id'] ?? null) === $doc->link_id) {
$latest = ['id' => $review->id, 'author_id' => $review->actor_id, 'author' => $review->name, 'date' => $review->created_at, 'payload' => $payload];
break;
}
}
if ($doc->category !== $field && ! ($latest && in_array($field, $latest['payload']['supports'] ?? [], true))) {
continue;
}
// A later review replaces the earlier scope. Merely choosing a
// document category does not verify a preparation assumption.
if ($latest && ! in_array($field, $latest['payload']['supports'] ?? [], true)) {
$latest = null;
}
$state = 'attached_unchecked';
if ($doc->valid_until && $doc->valid_until < now()->toDateString()) {
$state = 'expired';
} elseif ($latest && (($latest['payload']['sha256'] ?? null) !== trim($doc->sha256) || ($latest['payload']['document_version'] ?? null) !== (int) $doc->version_no)) {
$state = 'superseded';
} elseif ($latest) {
$path = realpath(Storage::disk('local')->path($doc->storage_key));
$root = realpath(Storage::disk('local')->path(''));
if (! $path || ! $root || ! str_starts_with($path, $root.DIRECTORY_SEPARATOR) || ! is_file($path) || ! is_string($hash = hash_file('sha256', $path)) || ! hash_equals(trim($doc->sha256), $hash)) {
$state = 'superseded';
} elseif ($doc->status !== 'active' || $doc->malware_scan_status !== 'clean' || trim($doc->sha256) !== $doc->malware_scanned_sha256) {
$state = 'technical_unavailable';
} else {
$state = match ($latest['payload']['outcome'] ?? '') {
'internal_verified' => 'internally_verified',
'contradiction_identified' => 'contradiction',
default => 'issue_identified',
};
}
}
$records[] = ['document_id' => $doc->document_id, 'link_id' => $doc->link_id, 'name' => $doc->file_name, 'state' => $state, 'version' => (int) $doc->version_no, 'hash' => trim($doc->sha256), 'valid_until' => $doc->valid_until,
'review' => $latest ? ['event_id' => $latest['id'], 'author_id' => $latest['author_id'], 'author' => $latest['author'], 'date' => $latest['date'], 'what_checked' => $latest['payload']['what_checked'], 'evidence' => $latest['payload']['evidence'], 'scope' => $latest['payload']['scope']] : null];
}
if ($records) {
// A specific current contradiction takes precedence; other valid evidence
// remains visible instead of erasing expired or replaced originals.
$states = array_column($records, 'state');
$state = 'attached_unchecked';
foreach (['contradiction', 'internally_verified', 'issue_identified', 'superseded', 'expired', 'technical_unavailable'] as $candidate) {
if (in_array($candidate, $states, true)) {
$state = $candidate;
break;
}
}
$result[$field] = ['state' => $state, 'documents' => $records];
}
}
return $result;
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Services\Ai;
/** Internal preparation rules; never calculate tax, returns or eligibility. */
class InvestorGuidanceRules
{
public const VERSION = 'investor-guidance-2026-10-08-v3';
public const FIELDS = ['project_title', 'project_summary', 'activity', 'target_customers', 'market_evidence', 'location',
'location_evidence', 'resource_plan', 'resource_evidence', 'funding_evidence', 'expected_start_date', 'ready_date', 'schedule',
'demand_quantity', 'capacity_quantity', 'quantity_unit', 'quantity_period', 'resources_required', 'resources_available', 'resource_unit',
'funding_required', 'funding_committed', 'funding_currency', 'funding_ready_date', 'completion_date'];
/** @param array<string,mixed> $facts
* @param array<string,array<string,mixed>> $evidence
* @return list<array<string,mixed>> */
public function evaluate(array $facts, array $evidence = []): array
{
$phases = [
'idea' => ['Definir a actividade e o objectivo', ['project_title', 'project_summary', 'activity'], 'Confirme o que pretende produzir ou prestar.', 'plan'],
'market' => ['Documentar clientes e hipóteses de mercado', ['target_customers', 'market_evidence'], 'Reúna evidência de clientes; uma hipótese não demonstra procura.', 'opportunities'],
'location' => ['Comparar locais e requisitos da actividade', ['location', 'location_evidence'], 'Confirme terreno, acesso, infraestrutura e licenciamento para cada alternativa.', 'locations'],
'resources' => ['Preparar recursos e equipa', ['resource_plan', 'resource_evidence'], 'Distinga recursos declarados de disponibilidade comprovada.', 'partners'],
'finance' => ['Explorar financiamento e cenários', ['funding_evidence'], 'Reveja os pressupostos e os cenários no simulador determinístico.', 'simulator'],
'execution' => ['Reconciliar calendário e dependências', ['expected_start_date', 'ready_date', 'schedule'], 'Confirme datas, dependências e responsáveis antes de assumir marcos.', 'plan'],
'support' => ['Preparar o pedido e acompanhar a resposta', [], 'Prepare um rascunho no Balcão; reveja e submeta pessoalmente.', 'support'],
];
$result = [];
foreach ($phases as $code => [$objective, $fields, $explanation, $action]) {
$known = [];
$unknown = [];
$phaseEvidence = [];
$risks = [];
foreach ($fields as $field) {
$value = trim((string) ($facts[$field] ?? ''));
$record = $evidence[$field] ?? null;
$state = $record['state'] ?? ($value !== '' ? 'investor_declared_not_verified' : 'absent');
if (in_array($field, InvestorGuidanceEvidence::FIELDS, true)) {
$phaseEvidence[] = ['field' => $field, 'state' => $state, 'documents' => $record['documents'] ?? []];
if ($state !== 'internally_verified') {
$message = match ($state) {
'absent' => 'Ainda não existe informação ou documento para este pressuposto.',
'investor_declared_not_verified' => 'A declaração do investidor ainda não foi conferida.',
'attached_unchecked' => 'Existe um documento associado, sem conferência interna deste pressuposto.',
'expired' => 'A validade documental registada terminou; actualize a evidência.',
'superseded' => 'O ficheiro ou a versão mudou depois da conferência; é necessária nova análise.',
'contradiction' => 'Uma conferência interna identificou contradição no âmbito descrito.',
'issue_identified' => 'Uma conferência interna identificou um problema no âmbito descrito.',
default => 'A evidência não está disponível para utilização; consulte o motivo documental.',
};
$risks[] = ['code' => $field.'_'.$state, 'classification' => $state === 'contradiction' ? 'documented_contradiction' : 'insufficient_information', 'explanation' => $message, 'field' => $field, 'restriction' => false];
}
}
if ($value !== '') {
$known[] = ['field' => $field, 'value' => $value, 'status' => 'investor_declared_not_verified'];
} elseif (! $record) {
$unknown[] = $field;
}
}
$result[] = ['id' => $code, 'objective' => $objective, 'known' => $known, 'questions' => $unknown,
'recommendations' => [[
'code' => $code.'_preparation', 'kind' => 'automatic_recommendation', 'classification' => $unknown ? 'insufficient_information' : 'verification_required',
'explanation' => $explanation, 'action' => $action, 'assumptions' => $known,
'source' => ['identifier' => self::VERSION, 'reference' => 'app/Services/Ai/InvestorGuidanceRules.php#'.$code, 'date' => '2026-10-08', 'nature' => 'internal_preparation_rule'],
'limitations' => ['Uma conferência interna só sustenta o âmbito descrito pelo verificador; não aprova procura, infraestrutura, financiamento, registo ou licença institucional.', 'Sem previsão de sucesso, taxa fiscal ou elegibilidade inferida.'],
]], 'evidence' => $phaseEvidence, 'risks' => $risks];
}
if (($facts['expected_start_date'] ?? '') && ($facts['ready_date'] ?? '') && $facts['expected_start_date'] < $facts['ready_date']) {
$result[5]['risks'][] = ['code' => 'schedule_contradiction', 'classification' => 'declared_contradiction',
'explanation' => 'O início indicado antecede a disponibilidade declarada dos recursos.', 'basis' => ['expected_start_date' => $facts['expected_start_date'], 'ready_date' => $facts['ready_date']],
'restriction' => false];
}
$result[4]['risks'][] = ['code' => 'tax_eligibility_not_inferred', 'classification' => 'insufficient_information', 'explanation' => 'A evidência do financiamento não determina taxas fiscais ou elegibilidade. Consulte os pressupostos, fontes e versões no simulador.', 'restriction' => false];
foreach ([
[1, 'demand_quantity', 'capacity_quantity', ['quantity_unit', 'quantity_period'], 'A procura declarada excede a capacidade declarada para a mesma unidade e período.'],
[3, 'resources_required', 'resources_available', ['resource_unit'], 'Os recursos disponíveis declarados são inferiores aos necessários declarados.'],
[4, 'funding_required', 'funding_committed', ['funding_currency'], 'O financiamento comprometido declarado é inferior ao necessário declarado na mesma moeda.'],
] as [$phase, $required, $available, $scope, $explanation]) {
$values = array_intersect_key($facts, array_flip([$required, $available, ...$scope]));
if (! array_filter($values, fn ($value) => $value !== null && $value !== '')) {
continue;
}
$complete = true;
foreach ([$required, $available, ...$scope] as $field) {
if (! isset($facts[$field]) || trim((string) $facts[$field]) === '') {
$complete = false;
}
}
// Compare declared magnitudes only: this is no forecast, valuation or financial calculation.
$left = $facts[$required] ?? null;
$right = $facts[$available] ?? null;
$valid = is_scalar($left) && is_scalar($right)
&& preg_match('/^\d{1,12}(\.\d{1,2})?$/', (string) $left)
&& preg_match('/^\d{1,12}(\.\d{1,2})?$/', (string) $right);
if (! $complete || ! $valid) {
$result[$phase]['risks'][] = ['code' => $required.'_comparison_incomplete', 'classification' => 'insufficient_information',
'explanation' => 'Faltam valores comparáveis, unidade, período ou moeda para esta comparação.', 'basis' => $values, 'restriction' => false];
} elseif ($this->declaredMagnitude((string) $left) > $this->declaredMagnitude((string) $right)) {
$result[$phase]['risks'][] = ['code' => $required.'_declared_gap', 'classification' => 'declared_contradiction',
'explanation' => $explanation.' Estes valores são declarações, não disponibilidade comprovada.', 'basis' => $values, 'restriction' => false];
}
}
foreach ([['completion_date', 'expected_start_date', 'A conclusão declarada antecede o início.'],
['expected_start_date', 'funding_ready_date', 'O início declarado antecede a disponibilidade declarada do financiamento.']] as [$first, $second, $explanation]) {
if (! empty($facts[$first]) && ! empty($facts[$second]) && $facts[$first] < $facts[$second]) {
$result[5]['risks'][] = ['code' => $first.'_'.$second.'_contradiction', 'classification' => 'declared_contradiction',
'explanation' => $explanation, 'basis' => [$first => $facts[$first], $second => $facts[$second]], 'restriction' => false];
}
}
return $result;
}
private function declaredMagnitude(string $value): int
{
$parts = explode('.', $value);
return (int) $parts[0] * 100 + (int) str_pad($parts[1] ?? '', 2, '0');
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Services;
use Illuminate\Support\Carbon;
/** Availability evidence is distinct from legal validity or institutional endorsement. */
class InstitutionalLinkMonitor
{
/** @return array{available:bool,reason:string,contact:string} */
public function status(\stdClass $link): array
{
$valid = filter_var($link->url, FILTER_VALIDATE_URL) && parse_url($link->url, PHP_URL_SCHEME) === 'https';
$fresh = $link->verified_at && Carbon::parse($link->verified_at)->between(now()->subDays(7), now());
return ['available' => (bool) ($valid && $fresh && $link->status === 'active'),
'reason' => ! $valid ? 'invalid_url' : (! $fresh ? 'verification_missing_or_expired' : ($link->status === 'active' ? 'recent_internal_check' : 'reported_unavailable')),
'contact' => $link->contact ?: (config('portal.support.email') ?: 'Utilize o pedido de apoio no mesmo dossier.')];
}
}
+4 -3
View File
@@ -52,7 +52,8 @@ class InvestmentZones
});
}
/** @param array<string, mixed> $filters */
/** @param array<string, mixed> $filters
* @return Builder<InvestmentZone> */
public function search(array $filters, bool $management = false): Builder
{
$query = $management ? InvestmentZone::query() : $this->visible();
@@ -118,7 +119,7 @@ class InvestmentZones
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.');
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
$evidence = is_array($zone->source_evidence) ? $zone->source_evidence : [];
$evidence = $zone->source_evidence ?? [];
$officialEvidence = collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional'], true)
&& str_starts_with((string) ($item['url'] ?? ''), 'https://') && trim((string) ($item['supports'] ?? '')) !== '');
$promoterEvidence = $zone->category === 'industrial_park' && collect($evidence)->contains(fn ($item) => ($item['source_type'] ?? null) === 'promoter'
@@ -166,7 +167,7 @@ class InvestmentZones
{
return DB::transaction(function () use ($id, $version, $actor) {
$location = DB::table('investment_zone_locations')->where('id', $id)->lockForUpdate()->first();
abort_unless($location, 404);
abort_unless($location !== null, 404);
abort_if((int) $location->version_no !== $version, 409, 'Version changed.');
abort_if((int) $location->editor_id === $actor, 403, 'Independent review required.');
abort_unless($location->validation_status === 'pending', 422, 'Territorial association already reviewed.');
@@ -36,7 +36,7 @@ final class ArchiveLimitInspector
$expandedBytes = 0;
for ($index = 0; $index < $archive->numFiles; $index++) {
$entry = $archive->statIndex($index);
if (! is_array($entry) || ! isset($entry['size']) || ! is_int($entry['size']) || $entry['size'] < 0) {
if (! is_array($entry) || $entry['size'] < 0) {
return 'archive_inspection_failed';
}
+5 -3
View File
@@ -197,7 +197,7 @@ final class ClamDScanner implements MalwareScanner
}
$offset += $written;
$meta = stream_get_meta_data($socket);
if ($meta['timed_out'] ?? false) {
if ($meta['timed_out']) {
throw new RuntimeException('ClamD scan timed out while sending data.');
}
}
@@ -208,19 +208,21 @@ final class ClamDScanner implements MalwareScanner
{
$reply = stream_get_line($socket, 65536, "\0");
$meta = stream_get_meta_data($socket);
if ($reply === false || ($meta['timed_out'] ?? false)) {
throw new RuntimeException(($meta['timed_out'] ?? false) ? 'ClamD scan timed out.' : 'ClamD returned no scan result.');
if ($reply === false || $meta['timed_out']) {
throw new RuntimeException($meta['timed_out'] ? 'ClamD scan timed out.' : 'ClamD returned no scan result.');
}
return trim($reply);
}
/** @return array{available:bool,engine:string,engine_version:?string,signatures_at:?DateTimeImmutable,signature_age_hours:?float,reason_code:?string} */
private function unavailable(string $reason): array
{
return ['available' => false, 'engine' => 'ClamAV', 'engine_version' => null, 'signatures_at' => null,
'signature_age_hours' => null, 'reason_code' => $reason];
}
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:?DateTimeImmutable,duration_ms:int,detail:?string} */
private function result(string $result, ?string $reason, int $startedAt, ?string $detail): array
{
return [
+1 -1
View File
@@ -4,7 +4,7 @@ namespace App\Services\Malware;
interface MalwareScanner
{
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:\DateTimeImmutable,duration_ms:int,detail:?string} */
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:?\DateTimeImmutable,duration_ms:int,detail:?string} */
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array;
/** @return array{available:bool,engine:string,engine_version:?string,signatures_at:?\DateTimeImmutable,signature_age_hours:?float,reason_code:?string} */
+2 -1
View File
@@ -2,8 +2,8 @@
namespace App\Services;
use App\Models\SimulationFormDraft;
use App\Models\ExistingBusiness;
use App\Models\SimulationFormDraft;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Database\Eloquent\Builder;
@@ -164,6 +164,7 @@ final class SimulationFormDrafts
return DB::transaction(function () use ($actorId, $tokenHash): ?SimulationFormDraft {
$this->setContext($actorId, $tokenHash);
return $this->ownedQuery($actorId, $tokenHash)->orderByDesc('updated_at')->first();
});
}
+214 -58
View File
@@ -2,26 +2,33 @@
namespace App\Services;
use App\Models\InvestmentSubmission;
use App\Models\Investor;
use App\Models\InvestorJourney;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class VirtualDesk
{
public function installed(): bool
{
return \Illuminate\Support\Facades\Schema::hasTable('desk_cases');
return Schema::hasTable('desk_cases') && Schema::hasColumn('desk_events', 'event_order') && Schema::hasColumn('tasks', 'desk_case_id');
}
/** @param array<string,mixed> $data */
public function encode(array $data): string
{
return Crypt::encryptString(json_encode($data, JSON_THROW_ON_ERROR));
}
/** @return array<string,mixed> */
public function decode(?string $data): array
{
return $data ? json_decode(Crypt::decryptString($data), true, 512, JSON_THROW_ON_ERROR) : [];
@@ -33,32 +40,36 @@ class VirtualDesk
->when($write, fn ($q) => $q->whereIn('role', ['admin', 'manager', 'officer']))->exists();
}
public function owns(User $actor, object $case, bool $write = true): bool
public function owns(User $actor, \stdClass $case, bool $write = true): bool
{
return $case->organization_id ? $this->represents($actor, $case->organization_id, $write) : (int) $case->user_id === $actor->id;
}
public function case(User $actor, string $id, bool $write = false, bool $lock = false): object
public function case(User $actor, string $id, bool $write = false, bool $lock = false): \stdClass
{
$case = DB::table('desk_cases')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
abort_unless($case, 404);
abort_unless($case !== null, 404);
abort_unless($this->owns($actor, $case, $write) || (! $write && ($actor->can('manage-portal') || DB::table('desk_requests')->where('case_id', $id)->where('analyst_id', $actor->id)->exists())), 403);
return $case;
}
public function request(User $actor, string $id, bool $ownerOnly = false, bool $lock = false): object
public function request(User $actor, string $id, bool $ownerOnly = false, bool $lock = false): \stdClass
{
$request = DB::table('desk_requests')->where('id', $id)->when($lock, fn ($q) => $q->lockForUpdate())->first();
abort_unless($request, 404);
abort_unless($request !== null, 404);
$case = $this->case($actor, $request->case_id, $ownerOnly);
abort_unless($this->owns($actor, $case, $ownerOnly) || (! $ownerOnly && ($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id)), 403);
return $request;
}
public function createCase(User $actor, array $input): object
/** @param array<string,mixed> $input */
public function createCase(User $actor, array $input): \stdClass
{
$data = Validator::make($input, ['title' => 'required|string|max:200', 'client_key' => 'required|uuid', 'reuse_consent' => 'accepted',
'organization_id' => 'nullable|uuid', 'company_id' => 'nullable|uuid', 'submission_id' => 'nullable|uuid', 'simulation_id' => 'nullable|uuid'])->validate();
'organization_id' => 'nullable|uuid', 'company_id' => 'nullable|uuid', 'submission_id' => 'nullable|uuid', 'simulation_id' => 'nullable|uuid', 'journey_id' => 'nullable|uuid', 'interest_request_id' => 'nullable|integer|min:1'])->validate();
return DB::transaction(function () use ($actor, $data) {
DB::table('users')->where('id', $actor->id)->lockForUpdate()->first();
$existing = DB::table('desk_cases')->where('user_id', $actor->id)->where('client_key', $data['client_key'])->first();
@@ -66,58 +77,132 @@ class VirtualDesk
if ($existing) {
abort_unless(($this->decode($existing->payload)['_creation_hash'] ?? '') === $inputHash, 409, 'Chave de criação usada com outro conteúdo.');
abort_unless($this->owns($actor, $existing), 403);
return $existing;
}
abort_if(($data['organization_id'] ?? null) && ! $this->represents($actor, $data['organization_id']), 403);
$interest = null;
if ($data['interest_request_id'] ?? null) {
$interest = DB::table('interest_requests')->where('id', $data['interest_request_id'])->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->firstOrFail();
$linkedInterest = DB::table('desk_cases')->where('interest_request_id', $data['interest_request_id'])->where('user_id', $actor->id)->first();
if ($linkedInterest) {
abort_unless($this->owns($actor, $linkedInterest), 403);
foreach (['organization_id', 'submission_id', 'simulation_id', 'company_id', 'journey_id'] as $anchor) {
abort_if(($data[$anchor] ?? null) && ($linkedInterest->{$anchor} ?? null) !== $data[$anchor], 409, 'Pedido existente já associado a um dossier; continue nesse contexto.');
}
return $linkedInterest;
}
}
if (($data['journey_id'] ?? null) && Schema::hasColumn('desk_cases', 'journey_id')) {
InvestorJourney::whereKey($data['journey_id'])->where('user_id', $actor->id)->firstOrFail();
$linkedJourney = DB::table('desk_cases')->where('journey_id', $data['journey_id'])->where('user_id', $actor->id)->first();
if ($linkedJourney) {
abort_unless($this->owns($actor, $linkedJourney), 403);
foreach (['organization_id', 'submission_id', 'simulation_id', 'company_id'] as $anchor) {
abort_if(($data[$anchor] ?? null) && $linkedJourney->{$anchor} !== $data[$anchor], 409, 'Este percurso já tem um dossier; associe novos elementos no contexto existente.');
}
return $linkedJourney;
}
}
$payload = ['profile' => app(InvestmentWorkspace::class)->account($actor->id)['payload'], 'name' => $actor->name, 'email' => $actor->email, '_creation_hash' => $inputHash, 'reuse_consent' => ['actor_id' => $actor->id, 'date' => now()->toIso8601String()]];
if ($data['company_id'] ?? null) {
$company = DB::table('investment_company_declarations')->where('id', $data['company_id'])->where('user_id', $actor->id)->first();
abort_unless($company, 404);
$payload['company'] = $this->decode($company->payload); $payload['company_version'] = $company->version;
abort_unless($company !== null, 404);
$payload['company'] = $this->decode($company->payload);
$payload['company_version'] = $company->version;
}
if ($data['submission_id'] ?? null) {
$submission = \App\Models\InvestmentSubmission::where('id', $data['submission_id'])->where('user_id', $actor->id)->firstOrFail();
$payload['investment'] = $submission->payload; $payload['investment_version'] = $submission->version;
$submission = InvestmentSubmission::where('id', $data['submission_id'])->where('user_id', $actor->id)->firstOrFail();
$payload['investment'] = $submission->payload;
$payload['investment_version'] = $submission->version;
}
if ($data['simulation_id'] ?? null) {
app(PartnershipSources::class)->resolve('simulation', $data['simulation_id'], $actor);
}
if ($data['simulation_id'] ?? null) app(PartnershipSources::class)->resolve('simulation', $data['simulation_id'], $actor);
// One case per explicitly reused investment; retries never create parallel dossiers.
if ($data['submission_id'] ?? null) {
$linked = DB::table('desk_cases')->where('submission_id', $data['submission_id'])->where('user_id', $actor->id)->first();
if ($linked) { abort_unless($this->owns($actor, $linked), 403); return $linked; }
if ($linked) {
abort_unless($this->owns($actor, $linked), 403);
foreach (['organization_id', 'simulation_id', 'company_id', 'journey_id'] as $anchor) {
abort_if(($data[$anchor] ?? null) && ($linked->{$anchor} ?? null) !== $data[$anchor], 409, 'Contexto já associado a outro dossier; não foi criado um dossier paralelo.');
}
return $linked;
}
}
if ($data['simulation_id'] ?? null) {
$linked = DB::table('desk_cases')->where('simulation_id', $data['simulation_id'])->where('user_id', $actor->id)->first();
if ($linked) {
abort_unless($this->owns($actor, $linked), 403);
foreach (['organization_id', 'submission_id', 'company_id', 'journey_id'] as $anchor) {
abort_if(($data[$anchor] ?? null) && ($linked->{$anchor} ?? null) !== $data[$anchor], 409, 'Contexto já associado a outro dossier; não foi criado um dossier paralelo.');
}
return $linked;
}
}
$identity = [];
if (Schema::hasColumn('desk_cases', 'investor_id')) {
$journey = ($data['journey_id'] ?? null) ? InvestorJourney::whereKey($data['journey_id'])->where('user_id', $actor->id)->firstOrFail() : null;
$account = DB::table('investor_accounts')->where('user_id', $actor->id)->first();
if (! $account) {
$investor = ($interest->investor_id ?? null) ? Investor::whereKey($interest->investor_id)->firstOrFail() : Investor::create(['legal_name' => $actor->name, 'investor_type' => 'individual', 'status' => 'prospect', 'source_system' => 'portal-account', 'data_classification' => 'confidential']);
DB::table('investor_accounts')->insert(['user_id' => $actor->id, 'investor_id' => $investor->id, 'created_at' => now(), 'updated_at' => now()]);
$account = DB::table('investor_accounts')->where('user_id', $actor->id)->first();
}
$dossierId = $journey->dossier_id ?? ($submission->dossier_id ?? null);
$projectId = $dossierId ? DB::table('investment_dossiers')->where('id', $dossierId)->whereNull('deleted_at')->value('project_id') : null;
$identity = ['investor_id' => $account->investor_id, 'journey_id' => $journey?->id, 'project_id' => $projectId, 'interest_request_id' => $data['interest_request_id'] ?? null];
}
$id = (string) Str::uuid();
DB::table('desk_cases')->insert(['id' => $id, 'user_id' => $actor->id, 'organization_id' => $data['organization_id'] ?? null, 'company_id' => $data['company_id'] ?? null,
'submission_id' => $data['submission_id'] ?? null, 'simulation_id' => $data['simulation_id'] ?? null, 'title' => $data['title'], 'client_key' => $data['client_key'],
'payload' => $this->encode($payload), 'workflow' => json_encode(array_map(fn ($s) => [...$s, 'status' => 'not_started', 'evidence' => null], config('virtual-desk.steps'))), 'created_at' => now(), 'updated_at' => now()]);
$case = DB::table('desk_cases')->where('id', $id)->first();
'payload' => $this->encode($payload), 'workflow' => json_encode(array_map(fn ($s) => [...$s, 'status' => 'not_started', 'evidence' => null], config('virtual-desk.steps'))), 'created_at' => now(), 'updated_at' => now(), ...$identity]);
$case = DB::table('desk_cases')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'case_created', ['reuse_consent' => true]);
return $case;
});
}
public function createRequest(User $actor, string $caseId, string $serviceId, string $clientKey): object
public function createRequest(User $actor, string $caseId, string $serviceId, string $clientKey): \stdClass
{
abort_unless(Str::isUuid($serviceId) && Str::isUuid($clientKey), 422);
return DB::transaction(function () use ($actor, $caseId, $serviceId, $clientKey) {
$case = $this->case($actor, $caseId, true, true);
abort_if($case->closed_at, 409, 'Dossier encerrado.');
$service = DB::table('desk_service_versions')->where('id', $serviceId)->where('status', 'published')->first();
abort_unless($service, 422, 'Versão do serviço indisponível para novos pedidos.');
abort_unless($service !== null, 422, 'Versão do serviço indisponível para novos pedidos.');
$existing = DB::table('desk_requests')->where('case_id', $caseId)->where('client_key', $clientKey)->first();
if ($existing) { abort_unless($existing->service_version_id === $serviceId, 409); return $existing; }
$id = (string) Str::uuid(); $base = $this->decode($case->payload);
if ($existing) {
abort_unless($existing->service_version_id === $serviceId, 409);
return $existing;
}
$id = (string) Str::uuid();
$base = $this->decode($case->payload);
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
DB::table('desk_requests')->insert(['id' => $id, 'case_id' => $caseId, 'service_version_id' => $serviceId, 'client_key' => $clientKey, 'payload' => $this->encode($payload), 'created_at' => now(), 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->first(); $this->event($case, $actor, 'draft_created', [], $request);
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'draft_created', [], $request);
return $request;
});
}
public function definition(object $request): array
/** @return array<string,mixed> */
public function definition(\stdClass $request): array
{
return json_decode(DB::table('desk_service_versions')->where('id', $request->service_version_id)->value('definition'), true, 512, JSON_THROW_ON_ERROR);
}
/** @param array<string,mixed> $payload
* @param array<string,mixed> $definition
* @return array<string,mixed> */
public function validateFields(array $payload, array $definition, bool $submitting): array
{
$rules = ['payload' => ['required', 'array:'.implode(',', array_keys($definition['fields']))]];
@@ -126,8 +211,8 @@ class VirtualDesk
$required = $submitting && ($field['required'] ?? false) && $active;
$rule = [$required ? 'required' : 'nullable'];
$rule = [...$rule, ...match ($field['type']) {
'number' => ['numeric', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
'select' => [\Illuminate\Validation\Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
'number' => ['numeric', 'decimal:0,2', 'min:'.($field['min'] ?? 0), 'max:999999999999'], 'date' => ['date_format:Y-m-d'],
'select' => [Rule::in(array_keys($field['options']))], 'territory' => ['uuid'],
default => ['string', 'max:'.($field['type'] === 'textarea' ? 15000 : 1000)],
}];
$rules['payload.'.$key] = $rule;
@@ -135,83 +220,127 @@ class VirtualDesk
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
if ($validated['territory_id'] ?? null) {
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $validated['territory_id'])->exists(), 422, 'Localização indisponível.');
if ($submitting && trim($validated['location_source'] ?? '') === '') throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
if ($submitting && trim($validated['location_source'] ?? '') === '') {
throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
}
}
return $validated;
}
/** @param array<string,mixed> $payload
* @return list<array<string,mixed>> */
public function findings(array $payload): array
{
$findings = [];
if (isset($payload['investment_amount'], $payload['own_finance'], $payload['other_finance']) && abs((float) $payload['investment_amount'] - (float) $payload['own_finance'] - (float) $payload['other_finance']) > 0.01) {
$amounts = array_map(function ($key) use ($payload) {
$value = (string) ($payload[$key] ?? '');
if (! preg_match('/^\d{1,12}(?:\.\d{1,2})?$/', $value)) {
return null;
}
[$whole, $fraction] = array_pad(explode('.', $value), 2, '');
return (int) $whole * 100 + (int) str_pad($fraction, 2, '0');
}, ['investment_amount', 'own_finance', 'other_finance']);
if (! in_array(null, $amounts, true) && $amounts[0] !== $amounts[1] + $amounts[2]) {
$findings[] = ['code' => 'finance_difference', 'severity' => 'error', 'field' => 'investment_amount', 'explanation' => 'A soma do financiamento difere do valor do investimento.', 'recommendation' => 'Confirme valores e moeda.', 'method' => 'deterministic', 'confidence' => null];
}
if (! ($payload['territory_id'] ?? null)) $findings[] = ['code' => 'location_unknown', 'severity' => 'warning', 'field' => 'territory_id', 'explanation' => 'Localização ainda não documentada.', 'recommendation' => 'Complete quando houver fonte.', 'method' => 'deterministic', 'confidence' => null];
if (in_array(null, $amounts, true)) {
$findings[] = ['code' => 'finance_unknown', 'severity' => 'warning', 'field' => 'investment_amount', 'explanation' => 'A coerência do financiamento permanece indeterminada sem os três valores válidos na mesma moeda.', 'recommendation' => 'Complete as fontes de financiamento; valores ausentes não são zero.', 'method' => 'deterministic', 'confidence' => null];
}
if (! ($payload['territory_id'] ?? null)) {
$findings[] = ['code' => 'location_unknown', 'severity' => 'warning', 'field' => 'territory_id', 'explanation' => 'Localização ainda não documentada.', 'recommendation' => 'Complete quando houver fonte.', 'method' => 'deterministic', 'confidence' => null];
}
$findings[] = ['code' => 'official_form_pending', 'severity' => 'warning', 'field' => null, 'explanation' => 'Adaptação digital do plano; não foi identificada uma versão oficial homologada do formulário APIEX no acervo.', 'recommendation' => 'A preparação e análise interna continuam disponíveis; confirme a versão exigida pela entidade para o ato oficial.', 'method' => 'documentary', 'confidence' => null];
return $findings;
}
public function save(User $actor, string $id, array $input, bool $submit = false): object
/** @param array<string,mixed> $input */
public function save(User $actor, string $id, array $input, bool $submit = false): \stdClass
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'payload' => 'required|array', 'consent' => $submit ? 'accepted' : 'nullable|boolean', 'reason' => 'nullable|string|max:3000'])->validate();
return DB::transaction(function () use ($actor, $id, $data, $submit) {
$request = $this->request($actor, $id, true, true);
if ($submit && $request->status === 'submitted' && $request->version === (int) $data['version'] + 1 && hash_equals(hash('sha256', json_encode(Arr::sortRecursive($this->decode($request->payload)))), hash('sha256', json_encode(Arr::sortRecursive($data['payload']))))) return $request;
if ($submit && $request->status === 'submitted' && $request->version === (int) $data['version'] + 1 && hash_equals(hash('sha256', json_encode(Arr::sortRecursive($this->decode($request->payload)), JSON_THROW_ON_ERROR)), hash('sha256', json_encode(Arr::sortRecursive($this->validateFields($data['payload'], $this->definition($request), false)), JSON_THROW_ON_ERROR)))) {
return $request;
}
abort_unless(in_array($request->status, ['draft', 'returned'], true) && $request->version === (int) $data['version'], 409, 'Pedido alterado ou já submetido.');
$payload = $this->validateFields($data['payload'], $this->definition($request), $submit);
if ($request->status === 'returned') {
$editable = json_decode($request->editable_fields ?? '[]', true); $previous = $this->decode($request->payload);
$editable = json_decode($request->editable_fields ?? '[]', true);
$previous = $this->decode($request->payload);
foreach (array_unique([...array_keys($previous), ...array_keys($payload)]) as $key) {
if (! in_array($key, $editable, true) && ($previous[$key] ?? null) !== ($payload[$key] ?? null)) throw ValidationException::withMessages(['payload.'.$key => 'Campo não autorizado para esta correção.']);
if (! in_array($key, $editable, true) && ($previous[$key] ?? null) !== ($payload[$key] ?? null)) {
throw ValidationException::withMessages(['payload.'.$key => 'Campo não autorizado para esta correção.']);
}
}
abort_if($submit && trim($data['reason'] ?? '') === '', 422, 'Justifique a correção.');
}
$findings = $this->findings($payload);
if ($submit && array_filter($findings, fn ($f) => $f['severity'] === 'error')) throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
if ($submit && array_filter($findings, fn ($f) => $f['severity'] === 'error')) {
throw ValidationException::withMessages(['payload.investment_amount' => $findings[0]['explanation']]);
}
$case = $this->case($actor, $request->case_id, true);
$snapshot = ['payload' => $payload, 'service_version_id' => $request->service_version_id, 'documents' => DB::table('desk_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.case_id', $case->id)->where(fn ($q) => $q->whereNull('link.request_id')->orWhere('link.request_id', $id))->get(['link.document_id', 'd.sha256', 'd.version_no', 'link.source_reference'])->all(), 'findings' => $findings, 'consent' => $submit, 'source' => config('virtual-desk.source')];
DB::table('desk_revisions')->insert(['request_id' => $id, 'version' => $request->version, 'snapshot' => $this->encode(['payload' => $this->decode($request->payload), 'status' => $request->status, 'submitted_snapshot' => $request->submitted_snapshot ? $this->decode($request->submitted_snapshot) : null])]);
$updates = ['payload' => $this->encode($payload), 'version' => $request->version + 1, 'updated_at' => now()];
if ($submit) $updates = [...$updates, 'status' => 'submitted', 'protocol' => $request->protocol ?? 'BV-'.date('Y').'-'.strtoupper(str_replace('-', '', $id)), 'submitted_at' => now(), 'submitted_snapshot' => $this->encode($snapshot)];
DB::table('desk_requests')->where('id', $id)->update($updates); $request = DB::table('desk_requests')->where('id', $id)->first();
if ($submit) {
$updates = [...$updates, 'status' => 'submitted', 'protocol' => $request->protocol ?? 'BV-'.date('Y').'-'.strtoupper(str_replace('-', '', $id)), 'submitted_at' => now(), 'submitted_snapshot' => $this->encode($snapshot)];
}
DB::table('desk_requests')->where('id', $id)->update($updates);
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
$this->event($case, $actor, $submit ? 'submitted' : 'draft_saved', ['reason' => $data['reason'] ?? '', 'findings' => $findings], $request);
return $request;
});
}
public function transition(User $actor, string $id, array $data): object
/** @param array<string,mixed> $data */
public function transition(User $actor, string $id, array $data): \stdClass
{
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'status' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.request_states')))], 'reason' => 'required|string|min:3|max:5000', 'editable_fields' => 'nullable|array', 'editable_fields.*' => 'string|max:100'])->validate();
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(array_keys(config('virtual-desk.request_states')))], 'reason' => 'required|string|min:3|max:5000', 'editable_fields' => 'nullable|array', 'editable_fields.*' => 'string|max:100'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$request = $this->request($actor, $id, false, true); $case = $this->case($actor, $request->case_id);
$request = $this->request($actor, $id, false, true);
$case = $this->case($actor, $request->case_id);
abort_unless($request->version === (int) $data['version'], 409);
$cancel = $data['status'] === 'cancelled';
if ($cancel) { abort_unless($this->owns($actor, $case) && in_array($request->status, ['draft', 'returned'], true), 403); }
else {
if ($cancel) {
abort_unless($this->owns($actor, $case) && in_array($request->status, ['draft', 'returned'], true), 403);
} else {
abort_if($this->owns($actor, $case, false), 403, 'O proponente não pode analisar ou decidir o seu próprio pedido.');
abort_unless($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id, 403);
if (in_array($data['status'], ['accepted', 'rejected', 'closed'], true)) abort_unless($actor->can('manage-portal'), 403);
if (in_array($data['status'], ['accepted', 'rejected', 'closed'], true)) {
abort_unless($actor->can('manage-portal'), 403);
}
abort_unless(in_array($data['status'], config('virtual-desk.transitions.'.$request->status, []), true), 409, 'Transição inválida.');
}
$editable = $data['editable_fields'] ?? [];
abort_if($data['status'] === 'returned' && ! $editable, 422, 'Indique os campos autorizados para correção.');
abort_if(array_diff($editable, array_keys($this->definition($request)['fields'])), 422);
abort_if(array_diff($editable, array_keys($this->definition($request)['fields'])) !== [], 422);
DB::table('desk_requests')->where('id', $id)->update(['status' => $data['status'], 'version' => $request->version + 1, 'editable_fields' => json_encode($editable), 'closed_at' => in_array($data['status'], ['closed', 'cancelled'], true) ? now() : null, 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->first(); $this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
return $request;
});
}
public function stage(User $actor, string $id, array $data): object
/** @param array<string,mixed> $data */
public function stage(User $actor, string $id, array $data): \stdClass
{
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'stage' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.steps')))],
'status' => ['required', \Illuminate\Validation\Rule::in(array_keys(config('virtual-desk.step_states')))], 'reason' => 'required|string|min:3|max:3000',
$data = Validator::make($data, ['version' => 'required|integer|min:1', 'stage' => ['required', Rule::in(array_keys(config('virtual-desk.steps')))],
'status' => ['required', Rule::in(array_keys(config('virtual-desk.step_states')))], 'reason' => 'required|string|min:3|max:3000',
'evidence' => 'nullable|string|max:5000', 'document_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'exception' => 'nullable|boolean'])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
$case = $this->case($actor, $id, false, true);
abort_unless($this->owns($actor, $case) || $actor->can('manage-portal'), 403);
abort_unless((int) $case->version === (int) $data['version'], 409);
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR); $current = $workflow[$data['stage']];
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR);
$current = $workflow[$data['stage']];
$decision = in_array($data['status'], ['completed', 'not_applicable'], true);
if ($decision) {
abort_unless($actor->can('manage-portal') && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
@@ -219,36 +348,63 @@ class VirtualDesk
foreach ($current['dependencies'] as $dependency) {
abort_unless(in_array($workflow[$dependency]['status'], ['completed', 'not_applicable'], true) || (($data['exception'] ?? false) && ($data['document_id'] ?? null)), 422, 'Dependência '.$dependency.' pendente; uma exceção exige evidência própria.');
}
if ($data['stage'] !== 'E0') abort_unless($data['document_id'] ?? null, 422, 'Ligue o documento de suporte ou de não aplicabilidade.');
if ($data['stage'] !== 'E0') {
abort_unless($data['document_id'] ?? null, 422, 'Ligue o documento de suporte ou de não aplicabilidade.');
}
}
if ($data['document_id'] ?? null) {
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256', 'l.valid_until']);
abort_unless($document, 422);
if ($decision) abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean' && trim($document->sha256) === $document->malware_scanned_sha256 && (! $document->valid_until || $document->valid_until >= now()->toDateString()), 422, 'Documento ainda não consultável ou expirado.');
abort_unless($document !== null, 422);
if ($decision) {
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean' && trim($document->sha256) === $document->malware_scanned_sha256 && (! $document->valid_until || $document->valid_until >= now()->toDateString()), 422, 'Documento ainda não consultável ou expirado.');
}
}
if (in_array($data['status'], ['referred', 'waiting'], true)) {
abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Registe referência e canal do encaminhamento.');
}
if (in_array($data['status'], ['referred', 'waiting'], true)) abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Registe referência e canal do encaminhamento.');
// Reopening an upstream step must never leave dependent conclusions falsely valid.
if (! in_array($data['status'], ['completed', 'not_applicable'], true)) {
$affected = [$data['stage']];
do { $changed = false; foreach ($workflow as $code => &$step) { if (! in_array($code, $affected, true) && array_intersect($step['dependencies'], $affected)) { $affected[] = $code; $changed = true; if ($step['status'] === 'completed') $step['status'] = 'pending'; } } unset($step); } while ($changed);
do {
$changed = false;
foreach ($workflow as $code => &$step) {
if (! in_array($code, $affected, true) && array_intersect($step['dependencies'], $affected)) {
$affected[] = $code;
$changed = true;
if (in_array($step['status'], ['completed', 'not_applicable'], true)) {
$step['status'] = 'pending';
}
}
} unset($step);
} while ($changed);
}
$workflow[$data['stage']] = [...$current, 'status' => $data['status'], 'evidence' => $data['evidence'] ?? null, 'document_id' => $data['document_id'] ?? null,
'valid_until' => $data['valid_until'] ?? null, 'reason' => $data['reason'], 'reviewed_by' => $actor->id, 'updated_at' => now()->toIso8601String()];
DB::table('desk_cases')->where('id', $id)->update(['workflow' => json_encode($workflow), 'version' => $case->version + 1, 'updated_at' => now()]);
$case = DB::table('desk_cases')->where('id', $id)->first(); $this->event($case, $actor, 'stage_updated', $data);
$case = DB::table('desk_cases')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'stage_updated', $data);
return $case;
});
}
public function event(object $case, User $actor, string $action, array $payload, ?object $request = null): void
/** @param array<string,mixed> $payload */
public function event(\stdClass $case, User $actor, string $action, array $payload, ?\stdClass $request = null): void
{
$id = (string) Str::uuid(); $version = $request->version ?? $case->version;
$id = (string) Str::uuid();
$version = $request->version ?? $case->version;
DB::table('desk_events')->insert(['id' => $id, 'case_id' => $case->id, 'request_id' => $request->id ?? null, 'actor_id' => $actor->id, 'action' => $action, 'version' => $version, 'payload' => $this->encode($payload)]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => $request ? 'desk_requests' : 'desk_cases', 'entity_id' => $request->id ?? $case->id, 'actor_user_id' => $actor->id, 'action' => $action,
'after_data' => json_encode(['event_id' => $id, 'event_version' => 1, 'version' => $version, 'case_id' => $case->id, 'source_hash' => config('virtual-desk.source.sha256')])]);
$recipients = [(int) $case->user_id];
if ($case->organization_id) $recipients = [...$recipients, ...DB::table('memberships')->where('organization_id', $case->organization_id)->whereNull('deleted_at')->pluck('user_id')->all()];
if ($request?->analyst_id) $recipients[] = (int) $request->analyst_id;
foreach (array_unique($recipients) as $user) DB::table('desk_notifications')->insert(['event_id' => $id, 'user_id' => $user, 'title' => config('virtual-desk.request_states.'.$request?->status, 'Dossier atualizado'), 'href' => $request ? '/balcao-virtual/pedidos/'.$request->id : '/balcao-virtual/dossiers/'.$case->id]);
if ($case->organization_id) {
$recipients = [...DB::table('memberships')->where('organization_id', $case->organization_id)->whereNull('deleted_at')->pluck('user_id')->all()];
}
if ($request?->analyst_id) {
$recipients[] = (int) $request->analyst_id;
}
foreach (array_unique($recipients) as $user) {
DB::table('desk_notifications')->insert(['event_id' => $id, 'user_id' => $user, 'title' => config('virtual-desk.request_states.'.$request?->status, 'Dossier atualizado'), 'href' => $request ? '/balcao-virtual/pedidos/'.$request->id : '/balcao-virtual/dossiers/'.$case->id]);
}
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class VirtualDeskInstallation
{
public const MIGRATIONS = ['2026_10_07_190000_create_internal_virtual_desk', '2026_10_08_120000_extend_desk_investor_guidance'];
public function fingerprint(): string
{
$files = [...(glob(app_path('Services/Ai/InvestorGuidance*.php')) ?: []), app_path('Services/VirtualDesk.php'), __FILE__,
app_path('Http/Controllers/VirtualDeskController.php'), app_path('Http/Controllers/VirtualDeskOperationsController.php'), app_path('Http/Controllers/InvestorGuidanceController.php'),
app_path('Http/Controllers/VirtualDeskInstallationController.php'), app_path('Http/Middleware/VirtualDeskInstalled.php'), app_path('Services/InstitutionalLinkMonitor.php'),
app_path('Services/Ai/EvidenceRepository.php'), base_path('routes/virtual-desk.php'), config_path('virtual-desk.php'), app_path('Http/Controllers/PortalServicesController.php'), app_path('Http/Middleware/HandleInertiaRequests.php'), resource_path('js/app.tsx'),
resource_path('js/lib/business-financial-plan.ts'), resource_path('js/lib/financial-calculators.ts'), resource_path('js/lib/project-dossier.ts'),
...array_map(fn ($name) => database_path('migrations/'.$name.'.php'), self::MIGRATIONS),
...(glob(resource_path('js/pages/desk/*.tsx')) ?: []), resource_path('js/components/investor-guidance.tsx'), resource_path('js/components/journey-companion.tsx'), resource_path('js/components/desk-internal-operations.tsx'), resource_path('js/layouts/portal-navigation.tsx'), resource_path('js/layouts/app/app-sidebar-layout.tsx'), resource_path('js/pages/investment/shared.tsx'), resource_path('js/lib/investor-guidance-finance.ts')];
sort($files);
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}
/** @return array<string,mixed> */
public function preview(): array
{
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
$directory = config('virtual-desk.proof_directory', storage_path('app/private/virtual-desk'));
$read = function ($file) use ($directory) {
if (! is_file($directory.'/'.$file)) {
return [];
}
$contents = file_get_contents($directory.'/'.$file);
abort_unless(is_string($contents), 503, 'Evidência privada indisponível.');
return json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
};
$backup = $read('backup-proof.json');
$qa = $read('guidance-qa-evidence.json');
$compatibility = $read('activation-compatibility.json');
$code = $this->fingerprint();
$backupVerified = ($backup['restore_verified'] ?? false) && ($backup['target']['database'] ?? null) === $identity->database
&& (int) ($backup['target']['port'] ?? 0) === (int) $identity->port && is_file($backup['dump_path'] ?? '')
&& hash_file('sha256', $backup['dump_path']) === ($backup['sha256'] ?? null)
&& ($backup['files_verified'] ?? false) && is_file($backup['files_path'] ?? '')
&& hash_file('sha256', $backup['files_path']) === ($backup['files_sha256'] ?? null)
&& strtotime($backup['verified_at'] ?? '') >= time() - 86400;
$qaVerified = ($qa['passed'] ?? false) && ($qa['code_hash'] ?? null) === $code && str_ends_with($qa['database'] ?? '', '_test') && (int) ($qa['port'] ?? 0) === 55441;
$compatibilityVerified = $backupVerified && ($compatibility['passed'] ?? false) && ($compatibility['code_hash'] ?? null) === $code
&& ($compatibility['dump_sha256'] ?? null) === ($backup['sha256'] ?? null)
&& ($compatibility['empty_rollback_verified'] ?? false) && (int) ($compatibility['port'] ?? 0) === 55441;
$counts = [];
foreach (['desk_cases', 'desk_requests', 'desk_documents', 'desk_messages', 'tasks', 'investor_accounts', 'investment_submissions'] as $table) {
$counts[$table] = Schema::hasTable($table) ? DB::table($table)->count() : null;
}
$installed = app(VirtualDesk::class)->installed();
$privileges = DB::selectOne("select has_schema_privilege(current_user, 'public', 'CREATE') as can_create,
pg_has_role(current_user, (select tableowner from pg_tables where schemaname='public' and tablename='tasks'), 'USAGE') as can_alter_tasks");
$databaseReady = (bool) ($privileges->can_create && $privileges->can_alter_tasks);
return ['hash' => hash('sha256', json_encode([$identity, $code, $counts, $backupVerified, $qaVerified, $compatibilityVerified, $databaseReady], JSON_THROW_ON_ERROR)), 'code_hash' => $code,
'installed' => $installed, 'target' => $identity, 'counts' => $counts, 'backupVerified' => $backupVerified, 'qaVerified' => $qaVerified,
'compatibilityVerified' => $compatibilityVerified, 'backupDate' => $backup['verified_at'] ?? null,
'databaseReady' => $databaseReady,
'scanner' => app(MalwareScanner::class)->health(),
'pendingMigrations' => array_values(array_filter(self::MIGRATIONS, fn ($name) => ! DB::table('migrations')->where('migration', $name)->exists())),
'rollback' => 'Reversão vazia ensaiada em cópia isolada. Com dados novos, preservar/exportar pedidos e tarefas; o down recusa eliminar dados. Restauro integral só numa janela autorizada, após reconciliar alterações posteriores ao backup.',
'changes' => ['Completar o Balcão Virtual existente, preservando pedidos anteriores.', 'Acrescentar associações opcionais ao investidor, projecto e percurso existentes.',
'Reutilizar tasks do CRM para acções expressamente assumidas; sem envio externo.', 'Nenhuma publicação de serviço, documento ou candidatura automática.']];
}
public function apply(string $hash, User $actor): void
{
abort_unless($actor->can('manage-portal'), 403);
DB::transaction(function () use ($hash, $actor) {
DB::select('select pg_advisory_xact_lock(261008, 1)');
$preview = $this->preview();
abort_unless(hash_equals($preview['hash'], $hash), 409, 'Pré-visualização alterada.');
if ($preview['installed']) {
return;
}
abort_unless($preview['backupVerified'] && $preview['qaVerified'] && $preview['compatibilityVerified'] && $preview['databaseReady'], 422, 'Backup/restauro atualizado, compatibilidade/reversão, permissões da base e QA desta versão continuam necessários.');
config(['virtual-desk.installation_authorized' => true]);
try {
foreach (self::MIGRATIONS as $name) {
if (! DB::table('migrations')->where('migration', $name)->exists()) {
(require database_path('migrations/'.$name.'.php'))->up();
DB::table('migrations')->insert(['migration' => $name, 'batch' => (DB::table('migrations')->max('batch') ?? 0) + 1]);
}
}
} finally {
config(['virtual-desk.installation_authorized' => false]);
}
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_cases', 'actor_user_id' => $actor->id,
'action' => 'desk_installed', 'after_data' => json_encode(['preview_hash' => $hash, 'code_hash' => $preview['code_hash'], 'prior_counts' => $preview['counts']])]);
});
}
}