@@ -3,6 +3,7 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -56,11 +57,26 @@ class ImportDocumentBatch extends Command
|
||||
|
||||
$apply = (bool) $this->option('apply');
|
||||
$actorId = $this->option('actor');
|
||||
if ($apply) {
|
||||
// CLI attribution is not an authenticated active installation. Rehearsals stay isolated.
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
if (! app()->environment('testing') || ! str_ends_with($target->database, '_test') || (int) $target->port !== 55441
|
||||
|| config('database.connections.pgsql.host') !== '127.0.0.1' || config('database.connections.pgsql.url')) {
|
||||
$this->error('CLI apply is restricted to isolated QA. Active imports require the authenticated activation mechanism; --actor is attribution only.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
if ($apply && (! is_numeric($actorId) || ! DB::table('users')->where('id', (int) $actorId)->exists())) {
|
||||
$this->error('Apply requires --actor=<existing-user-id>; no author identity will be fabricated.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($apply && ! User::findOrFail((int) $actorId)->can('manage-portal')) {
|
||||
$this->error('QA import requires an authorized library manager; no permission is granted by naming an account.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$disk = Storage::disk('local');
|
||||
$seenHashes = [];
|
||||
$seenExternalIds = [];
|
||||
|
||||
@@ -6,7 +6,9 @@ use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
@@ -29,12 +31,17 @@ class DashboardController extends Controller
|
||||
|
||||
$counts = InterestRequest::query()->selectRaw('status, count(*) as total')
|
||||
->groupBy('status')->pluck('total', 'status');
|
||||
$drafts = Opportunity::where('status', 'draft');
|
||||
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$drafts = app(PortalProfileAccess::class)->scope($drafts, $request->user());
|
||||
}
|
||||
|
||||
return Inertia::render('dashboard', ['summary' => [
|
||||
'canCreateOpportunity' => app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
|
||||
'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed'])
|
||||
->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]),
|
||||
'publishedOpportunities' => Opportunity::published()->count(),
|
||||
'draftOpportunities' => Opportunity::where('status', 'draft')->count(),
|
||||
'draftOpportunities' => $drafts->count(),
|
||||
'activeSectors' => Sector::where('is_active', true)->count(),
|
||||
'recentRequests' => InterestRequest::orderByDesc('id')->limit(5)
|
||||
->get(['id', 'reference', 'sector_interest', 'status', 'created_at']),
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentZones;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\TerritoryGeometry;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class InvestmentTerritoryController extends Controller
|
||||
@@ -14,9 +17,11 @@ class InvestmentTerritoryController extends Controller
|
||||
public function geometries(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
||||
$management = $request->is('management/*');
|
||||
$profile = $request->is('minhas-oportunidades/*');
|
||||
$management = $request->is('management/*') || $profile;
|
||||
if ($management) {
|
||||
abort_unless($request->user()?->can('manage-portal'), 403);
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($profile ? ($access->grants($request->user()) !== [] || $access->superuser($request->user())) : $request->user()?->can('manage-portal'), 403);
|
||||
}
|
||||
|
||||
return response()->json(app(TerritoryGeometry::class)->context($data['territory_id'], $management));
|
||||
@@ -29,6 +34,9 @@ class InvestmentTerritoryController extends Controller
|
||||
$data = $request->validate(['kind' => ['required', 'in:'.implode(',', array_keys(self::TABLES))], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$column = $data['kind'] === 'opportunities' ? 'title' : 'name';
|
||||
$query = DB::table(self::TABLES[$data['kind']])->whereNull('deleted_at');
|
||||
if ($data['kind'] === 'opportunities' && Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$query->whereIn('id', app(PortalProfileAccess::class)->scope(Opportunity::query(), $request->user())->select('id'));
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$query->whereRaw($column.' ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
|
||||
}
|
||||
@@ -38,6 +46,10 @@ class InvestmentTerritoryController extends Controller
|
||||
|
||||
public function options(Request $request): JsonResponse
|
||||
{
|
||||
if ($request->is('minhas-oportunidades/*')) {
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($access->grants($request->user()) !== [] || $access->superuser($request->user()), 403);
|
||||
}
|
||||
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type'])
|
||||
->whereIn('data_classification', ['public', 'internal']);
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Models\LandAssistanceCase;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\InterestSubmission;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -257,7 +258,9 @@ class LandAssistanceController extends Controller
|
||||
'media_type' => (string) $file->getMimeType(),
|
||||
'storage_key' => $stored,
|
||||
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)),
|
||||
// No antivirus engine is configured in this project; fail closed until an operator scans it.
|
||||
'size_bytes' => $file->getSize(),
|
||||
'uploaded_by' => $request->user()->id,
|
||||
// The configured scanner releases only the exact original hash after a clean result.
|
||||
'status' => 'quarantined',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
@@ -282,22 +285,20 @@ class LandAssistanceController extends Controller
|
||||
: back()->with('status', 'Documento privado anexado; a revisão ainda está pendente.');
|
||||
}
|
||||
|
||||
public function download(Request $request, string $id, string $attachment): BinaryFileResponse
|
||||
public function download(Request $request, string $id, string $attachment): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
$this->owned($request, $id);
|
||||
$case = $this->owned($request, $id);
|
||||
$document = DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
|
||||
->where('link.case_id', $id)->where('link.id', $attachment)->where('document.status', 'active')->whereNull('document.deleted_at')
|
||||
->where('document.malware_scan_status', 'clean')->whereColumn('document.malware_scanned_sha256', 'document.sha256')
|
||||
->first(['document.file_name', 'document.storage_key', 'document.sha256', 'document.malware_scanned_sha256']);
|
||||
->first(['document.*']);
|
||||
abort_if($document === null, 404);
|
||||
$root = realpath(Storage::disk('local')->path(''));
|
||||
$path = realpath(Storage::disk('local')->path($document->storage_key));
|
||||
abort_unless($root && $path && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path), 404);
|
||||
$checksum = hash_file('sha256', $path);
|
||||
abort_unless(is_string($checksum) && hash_equals($document->sha256, $checksum)
|
||||
&& hash_equals($document->sha256, (string) $document->malware_scanned_sha256), 404);
|
||||
$response = app(VerifiedDocumentBinary::class)->respond($document);
|
||||
DB::table('audit_events')->insert(['source_system' => 'land-assistance', 'entity_type' => 'documents', 'entity_id' => $document->id,
|
||||
'actor_user_id' => $request->user()->id, 'action' => 'document_downloaded', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['case_id' => $case->id, 'attachment_id' => $attachment], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return response()->download($path, basename($document->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function print(Request $request, string $id): Response
|
||||
|
||||
@@ -6,14 +6,20 @@ use App\Domain\Opportunities\Enums\OpportunityStatus;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityManagementInstallation;
|
||||
use App\Services\OpportunityMaturity;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\OpportunityWorkflowTasks;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Database\Eloquent\SoftDeletingScope;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
@@ -38,16 +44,32 @@ class OpportunityManagementController extends Controller
|
||||
if (! $service->installed()) {
|
||||
return app(PortalManagementController::class)->catalog($request, 'opportunities');
|
||||
}
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'status' => ['nullable', Rule::in([...array_column(OpportunityStatus::cases(), 'value'), 'returned', 'auto_validation_failed', 'technical_review', 'legal_territorial_review', 'approval_pending', 'publication_pending'])], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])], 'category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)], 'deleted' => 'nullable|boolean', 'page' => 'nullable|integer|min:1']);
|
||||
$filters = $request->validate(['queue' => 'nullable|in:review,publication,appeal,assigned', 'q' => 'nullable|string|max:150', 'status' => ['nullable', Rule::in([...array_column(OpportunityStatus::cases(), 'value'), 'returned', 'auto_validation_failed', 'technical_review', 'legal_territorial_review', 'approval_pending', 'publication_pending'])], 'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')], 'geography_scope' => ['nullable', Rule::in(['unspecified', 'specific', 'multiple', 'national', 'digital'])], 'category' => ['nullable', Rule::in(OpportunityManagement::CATEGORIES)], 'deleted' => 'nullable|boolean', 'page' => 'nullable|integer|min:1']);
|
||||
$query = Opportunity::query();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$query = $access->scope($query, $request->user());
|
||||
if (str_starts_with($request->path(), 'minhas-oportunidades')) {
|
||||
$query->whereNotNull('owner_user_id');
|
||||
}
|
||||
}
|
||||
if ($filters['deleted'] ?? false) {
|
||||
$query->onlyTrashed();
|
||||
$query->withoutGlobalScope(SoftDeletingScope::class)->whereNotNull('opportunities.deleted_at');
|
||||
}
|
||||
if ($filters['q'] ?? null) {
|
||||
$query->where(fn ($q) => $q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%'));
|
||||
$query->where(function ($q) use ($filters) {
|
||||
$q->whereLike('title', '%'.$filters['q'].'%')->orWhereLike('reference', '%'.$filters['q'].'%');
|
||||
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$q->orWhere(fn ($draft) => $draft->whereNotNull('owner_user_id')->whereRaw("management_draft::jsonb->'canonical'->>'official_title' ILIKE ?", ['%'.$filters['q'].'%']));
|
||||
}
|
||||
});
|
||||
}
|
||||
if ($filters['status'] ?? null) {
|
||||
$query->where('status', $filters['status']);
|
||||
if (Schema::hasColumn('opportunities', 'workflow_context')) {
|
||||
$query->whereRaw("COALESCE(workflow_context->>'working_state',status)=?", [$filters['status']]);
|
||||
} else {
|
||||
$query->where('status', $filters['status']);
|
||||
}
|
||||
}
|
||||
if ($filters['category'] ?? null) {
|
||||
$query->where('opportunity_category', $filters['category']);
|
||||
@@ -59,7 +81,32 @@ class OpportunityManagementController extends Controller
|
||||
$query->where('geography_scope', $filters['geography_scope']);
|
||||
}
|
||||
|
||||
return Inertia::render('management/opportunities', ['records' => $query->orderByDesc('id')->paginate(20)->withQueryString(), 'filters' => $filters, 'counts' => Opportunity::selectRaw('status,count(*) AS total')->groupBy('status')->pluck('total', 'status'), 'categories' => OpportunityManagement::CATEGORIES, 'geographyReviewCount' => Opportunity::where('geography_scope', 'unspecified')->count(), 'sectors' => Sector::orderBy('name')->get(['id', 'name'])]);
|
||||
if ($filters['queue'] ?? null) {
|
||||
$queue = $filters['queue'];
|
||||
if ($queue === 'review') {
|
||||
$query->whereRaw("COALESCE(workflow_context->>'working_state',status) IN ('submitted','in_review','information_pending')");
|
||||
} elseif ($queue === 'publication') {
|
||||
$query->whereRaw("COALESCE(workflow_context->>'working_state',status)='approved'");
|
||||
} elseif ($queue === 'appeal') {
|
||||
$query->whereRaw("workflow_context->'appeal'->>'pending'='true'");
|
||||
} else {
|
||||
$query->whereExists(fn ($q) => $q->selectRaw('1')->from('tasks')->where('tasks.source_system', 'opportunity-workflow')->where('tasks.assignee_user_id', $request->user()->id)->whereIn('tasks.status', ['open', 'in_progress'])->whereRaw("tasks.external_id LIKE 'portal-opportunity:' || opportunities.id::text || ':%'"));
|
||||
}
|
||||
}
|
||||
|
||||
$base = str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities';
|
||||
$stateSql = Schema::hasColumn('opportunities', 'workflow_context') ? "COALESCE(workflow_context->>'working_state',status)" : 'status';
|
||||
$counts = (clone $query)->selectRaw($stateSql.' AS working_status,count(*) AS total')->groupByRaw($stateSql)->pluck('total', 'working_status');
|
||||
$geographyReviewCount = (clone $query)->where('geography_scope', 'unspecified')->count();
|
||||
$records = $query->orderByDesc('id')->paginate(20)->withQueryString();
|
||||
$records->getCollection()->each(function (Opportunity $r) use ($access, $service, $request) {
|
||||
$r->setAttribute('can_edit', $access->canEdit($request->user(), $r));
|
||||
$r->setAttribute('working_status', $access->state($r));
|
||||
$r->setAttribute('publication', $r->publicationPresentation());
|
||||
$r->setAttribute('draft_title', $service->values($r)['canonical']['official_title'] ?? $r->title);
|
||||
});
|
||||
|
||||
return Inertia::render('management/opportunities', ['basePath' => $base, 'canCreate' => $base === '/management/opportunities' ? $access->legacyWriteAllowed($request->user()) : (bool) ($access->navigation($request->user())['contexts'] ?? []), 'records' => $records, 'filters' => $filters, 'counts' => $counts, 'categories' => OpportunityManagement::CATEGORIES, 'geographyReviewCount' => $geographyReviewCount, 'sectors' => Sector::orderBy('name')->get(['id', 'name'])]);
|
||||
}
|
||||
|
||||
public function edit(Request $request, OpportunityManagement $service, ?int $id = null): Response
|
||||
@@ -68,10 +115,27 @@ class OpportunityManagementController extends Controller
|
||||
return app(PortalManagementController::class)->edit('opportunities', $id);
|
||||
}
|
||||
$record = $id ? Opportunity::withTrashed()->findOrFail($id) : null;
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (! $record && ! str_starts_with($request->path(), 'minhas-oportunidades')) {
|
||||
abort_unless($access->legacyWriteAllowed($request->user()), 403);
|
||||
}
|
||||
if ($record) {
|
||||
$access->authorize($request->user(), 'view', $record);
|
||||
}
|
||||
Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities',
|
||||
'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null,
|
||||
'workflowState' => $record ? $access->state($record) : null,
|
||||
'publicationState' => $record?->publicationPresentation(),
|
||||
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
||||
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
|
||||
'workflowTasks' => $record && $record->owner_user_id !== null ? app(OpportunityWorkflowTasks::class)->listing($record) : [],
|
||||
'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'),
|
||||
'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]);
|
||||
$values = $record ? $service->values($record) : [];
|
||||
Inertia::share('publicationPreview', app(OpportunityCanonicalContract::class)->publicProjection($values['canonical'] ?? []));
|
||||
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
|
||||
|
||||
return Inertia::render('management/opportunity-draft', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view'), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'categories' => OpportunityManagement::CATEGORIES,
|
||||
return Inertia::render('management/opportunity-draft', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view') || ($record && ! $access->canEdit($request->user(), $record)), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'categories' => OpportunityManagement::CATEGORIES,
|
||||
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES, 'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS],
|
||||
'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true),
|
||||
'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]);
|
||||
|
||||
@@ -3,21 +3,22 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\OpportunityImageProcessor;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityResourceInstallation;
|
||||
use App\Services\OpportunityResources;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
class OpportunityResourceController extends Controller
|
||||
{
|
||||
@@ -40,9 +41,12 @@ class OpportunityResourceController extends Controller
|
||||
public function index(int $id, OpportunityResources $service): Response
|
||||
{
|
||||
$opportunity = Opportunity::withTrashed()->findOrFail($id);
|
||||
app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
|
||||
Inertia::share(['basePath' => str_starts_with(request()->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities', 'readOnly' => ! app(PortalProfileAccess::class)->canEdit(request()->user(), $opportunity)]);
|
||||
abort_unless($service->installed(), 503, 'Recursos ainda não instalados; consulte o plano autenticado.');
|
||||
$resources = [];
|
||||
Inertia::share('imageProcessingAvailable', app(OpportunityImageProcessor::class)->available());
|
||||
Inertia::share('countries', app(CountryCatalogue::class)->all());
|
||||
foreach (OpportunityResources::KINDS as $kind) {
|
||||
$resources[$kind] = $service->listing($id, $kind);
|
||||
}
|
||||
@@ -54,7 +58,7 @@ class OpportunityResourceController extends Controller
|
||||
$image->derivativePreviews = [];
|
||||
foreach ($image->payload['derivatives'] ?? [] as $derived) {
|
||||
if (DB::table('documents')->where('id', $derived['document_id'])->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->exists()) {
|
||||
$image->derivativePreviews[] = [...$derived, 'url' => URL::temporarySignedRoute('management.opportunity-image-preview', now()->addMinutes(10), ['id' => $id, 'resourceId' => $image->id, 'documentId' => $derived['document_id']])];
|
||||
$image->derivativePreviews[] = [...$derived, 'url' => URL::temporarySignedRoute(str_starts_with(request()->path(), 'minhas-oportunidades') ? 'promoter.opportunity-image-preview' : 'management.opportunity-image-preview', now()->addMinutes(10), ['id' => $id, 'resourceId' => $image->id, 'documentId' => $derived['document_id']])];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,7 +91,7 @@ class OpportunityResourceController extends Controller
|
||||
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']);
|
||||
}
|
||||
|
||||
public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response
|
||||
public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
$o = Opportunity::findOrFail($id);
|
||||
abort_if($o->status === 'archived', 404);
|
||||
@@ -97,26 +101,20 @@ class OpportunityResourceController extends Controller
|
||||
abort_unless(in_array($documentId, array_column($metadata['derivatives'] ?? [], 'document_id'), true), 404);
|
||||
$doc = DB::table('documents')->where('id', $documentId)->whereNull('deleted_at')->first();
|
||||
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && hash_equals(trim($doc->sha256), (string) $doc->malware_scanned_sha256), 423, 'Scan da derivada pendente.');
|
||||
$bytes = Crypt::decryptString(Storage::disk('local')->get($doc->storage_key));
|
||||
abort_unless(hash_equals(trim($doc->sha256), hash('sha256', $bytes)), 409, 'Integridade divergente.');
|
||||
|
||||
return response($bytes)->header('Content-Type', 'image/webp')->header('X-Content-Type-Options', 'nosniff')->header('Cache-Control', 'private,no-store');
|
||||
return app(VerifiedDocumentBinary::class)->respond($doc, true);
|
||||
}
|
||||
|
||||
public function download(int $id, string $kind, string $resourceId, OpportunityResources $service): \Illuminate\Http\Response
|
||||
public function download(int $id, string $kind, string $resourceId, OpportunityResources $service): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
|
||||
$opportunity = Opportunity::findOrFail($id);
|
||||
abort_if($opportunity->status === 'archived', 404);
|
||||
$record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']);
|
||||
abort_unless($record && $record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
|
||||
$disk = Storage::disk('local');
|
||||
$path = $disk->path($record->storage_key);
|
||||
abort_unless($disk->exists($record->storage_key), 409, 'Ficheiro indisponível.');
|
||||
$bytes = $record->storage_encryption === 'laravel' ? Crypt::decryptString($disk->get($record->storage_key)) : $disk->get($record->storage_key);
|
||||
abort_unless(hash_equals(trim($record->sha256), hash('sha256', $bytes)), 409, 'Integridade do ficheiro divergente.');
|
||||
abort_unless($record !== null, 404, 'Recurso indisponível ou excluído logicamente.');
|
||||
abort_unless($record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
|
||||
|
||||
return response($bytes)->header('Content-Type', $record->media_type)->header('Content-Disposition', HeaderUtils::makeDisposition('attachment', $record->file_name, 'document'))->header('X-Content-Type-Options', 'nosniff')->header('Cache-Control', 'no-store');
|
||||
return app(VerifiedDocumentBinary::class)->respond($record);
|
||||
}
|
||||
|
||||
/** @param array<string,list<\stdClass>> $resources
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Services\InvestmentRelations;
|
||||
use App\Services\PartnershipExchange;
|
||||
use App\Services\PartnershipMatching;
|
||||
use App\Services\PartnershipSources;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -317,7 +318,7 @@ class PartnershipExchangeController extends Controller
|
||||
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409);
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'partnership-exchange', 'data_classification' => 'restricted',
|
||||
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored,
|
||||
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined']);
|
||||
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined', 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id]);
|
||||
DB::table('partnership_documents')->insert(['room_id' => $id, 'document_id' => $documentId, 'owner_id' => $request->user()->id, 'shared' => $data['shared']]);
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_added.v1', ['room_id' => $id, 'document_id' => $documentId, 'shared' => $data['shared']], 'Documento privado anexado');
|
||||
});
|
||||
@@ -330,21 +331,17 @@ class PartnershipExchangeController extends Controller
|
||||
return $request->expectsJson() ? response()->json(['uploaded' => true]) : back()->with('success', 'Documento privado guardado; análise antimalware pendente.');
|
||||
}
|
||||
|
||||
public function download(Request $request, int $id, int $attachment): BinaryFileResponse
|
||||
public function download(Request $request, int $id, int $attachment): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
$context = app(PartnershipExchange::class)->room($request->user(), $id);
|
||||
$document = DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('link.room_id', $id)->where('link.id', $attachment)
|
||||
->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))->where('d.status', 'active')->whereNull('d.deleted_at')
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')->first(['d.storage_key', 'd.file_name', 'd.sha256']);
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')->first(['d.*']);
|
||||
abort_unless($document !== null, 404);
|
||||
$root = realpath(Storage::disk('local')->path(''));
|
||||
$path = realpath(Storage::disk('local')->path($document->storage_key));
|
||||
abort_unless($root && $path && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path), 404);
|
||||
$checksum = hash_file('sha256', $path);
|
||||
abort_unless(is_string($checksum) && hash_equals($document->sha256, $checksum), 404);
|
||||
$response = app(VerifiedDocumentBinary::class)->respond($document);
|
||||
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_accessed.v1', ['room_id' => $id, 'attachment_id' => $attachment], 'Documento consultado');
|
||||
|
||||
return response()->download($path, basename($document->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function share(Request $request, int $id, int $attachment): RedirectResponse|JsonResponse
|
||||
|
||||
@@ -230,6 +230,9 @@ class PortalManagementController extends Controller
|
||||
]);
|
||||
$query = $model::query();
|
||||
if ($resource === 'opportunities') {
|
||||
if (Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$query = app(\App\Services\PortalProfileAccess::class)->scope(Opportunity::query(), $request->user());
|
||||
}
|
||||
$query->with('primaryTerritory:id,name,location_type,source_system,source_code');
|
||||
if (isset($filters['geography_scope'])) {
|
||||
$query->where('geography_scope', $filters['geography_scope']);
|
||||
@@ -263,7 +266,7 @@ class PortalManagementController extends Controller
|
||||
'filters' => $filters,
|
||||
'sectors' => $resource === 'opportunities' ? Sector::orderBy('name')->get(['id', 'name']) : [],
|
||||
'geographyReviewCount' => $resource === 'opportunities'
|
||||
? Opportunity::where('geography_scope', 'unspecified')->count()
|
||||
? (clone $query)->where('geography_scope', 'unspecified')->count()
|
||||
: 0,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityProfileWorkflow;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use App\Services\PortalSuperusers;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
class PortalProfileController extends Controller
|
||||
{
|
||||
public function requests(Request $request, PortalProfileAccess $access): Response
|
||||
{
|
||||
return Inertia::render('profiles/request', ['requests' => DB::table('portal_profile_requests')->where('user_id', $request->user()->id)->latest()->get(),
|
||||
'types' => OpportunityManagement::CATEGORIES,
|
||||
'organizations' => DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id)
|
||||
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']),
|
||||
'documents' => DB::table('documents')->where('uploaded_by', $request->user()->id)->whereNull('deleted_at')->where('status', 'active')->where('malware_scan_status', 'clean')
|
||||
->whereColumn('sha256', 'malware_scanned_sha256')->get(['id', 'file_name']), 'grants' => $access->grants($request->user(), 'promoter')]);
|
||||
}
|
||||
|
||||
public function requestProfile(Request $request, PortalProfileAdministration $service): JsonResponse
|
||||
{
|
||||
return response()->json(['id' => $service->request($request->user(), $request->all()), 'message' => 'Pedido recebido; perfil ainda não ativado.'], 201);
|
||||
}
|
||||
|
||||
public function requestStatus(Request $request, string $id): JsonResponse
|
||||
{
|
||||
$row = DB::table('portal_profile_requests')->where('id', $id)->where('user_id', $request->user()->id)->first();
|
||||
abort_unless($row !== null, 403);
|
||||
|
||||
return response()->json($row);
|
||||
}
|
||||
|
||||
public function administration(Request $request, PortalProfileAdministration $service): Response
|
||||
{
|
||||
$service->administrative($request->user());
|
||||
|
||||
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(),
|
||||
'assignments' => DB::table('portal_role_assignments')->get(), 'pair' => DB::table('portal_superuser_pair')->first(),
|
||||
'actorId' => $request->user()->id, 'types' => OpportunityManagement::CATEGORIES,
|
||||
'organizations' => DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']),
|
||||
'securityRequests' => DB::table('portal_security_approvals')->latest()->limit(30)->get(),
|
||||
'securityAlerts' => DB::table('audit_events')->where('source_system', 'portal-profiles-v1')->whereIn('action', ['superuser_pair_initialized', 'superuser_replaced', 'role_revoked'])->latest('occurred_at')->limit(20)->get(['id', 'action', 'actor_user_id', 'occurred_at'])]);
|
||||
}
|
||||
|
||||
public function decide(Request $request, string $id, PortalProfileAdministration $service): JsonResponse
|
||||
{
|
||||
$service->decide($request->user(), $id, $request->all());
|
||||
|
||||
return response()->json(['message' => 'Decisão registada; somente os tipos aprovados ficam autorizados.']);
|
||||
}
|
||||
|
||||
public function audit(Request $request, PortalProfileAccess $access): Response|JsonResponse
|
||||
{
|
||||
abort_unless($access->has($request->user(), 'auditor') || ($access->superuser($request->user()) && $access->mfa($request->user())), 403);
|
||||
$filters = $request->validate(['actor_id' => 'nullable|integer|min:1', 'action' => 'nullable|string|max:100', 'record_id' => 'nullable|integer|min:1', 'from' => 'nullable|date', 'until' => 'nullable|date|after_or_equal:from', 'format' => 'nullable|in:json']);
|
||||
$query = DB::table('audit_events')->when($filters['actor_id'] ?? null, fn ($q, $v) => $q->where('actor_user_id', $v))
|
||||
->when($filters['action'] ?? null, fn ($q, $v) => $q->where('action', $v))
|
||||
->when($filters['record_id'] ?? null, fn ($q, $v) => $q->where('after_data->record_id', $v))
|
||||
->when($filters['from'] ?? null, fn ($q, $v) => $q->where('occurred_at', '>=', $v))
|
||||
->when($filters['until'] ?? null, fn ($q, $v) => $q->where('occurred_at', '<=', $v));
|
||||
// Minimized metadata: never decrypt private snapshots or export authentication bodies.
|
||||
$query->select(['id', 'source_system', 'action', 'actor_user_id', 'entity_type', 'occurred_at', 'correlation_id']);
|
||||
if (($filters['format'] ?? null) === 'json') {
|
||||
$records = $query->orderByDesc('occurred_at')->limit(1000)->get();
|
||||
$access->audit($request->user(), 'audit_metadata_exported', ['filters' => $filters, 'count' => $records->count()]);
|
||||
|
||||
return response()->json(['filters' => $filters, 'records' => $records, 'limit' => 1000])->header('Content-Disposition', 'attachment; filename="audit-metadata.json"')->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
$records = $query->orderByDesc('occurred_at')->paginate(30)->withQueryString();
|
||||
$access->audit($request->user(), 'audit_metadata_read', ['filters' => $filters, 'count' => $records->count()]);
|
||||
|
||||
return Inertia::render('profiles/audit', ['records' => $records, 'filters' => $filters]);
|
||||
}
|
||||
|
||||
public function grant(Request $request, PortalProfileAdministration $service): JsonResponse
|
||||
{
|
||||
return response()->json(['id' => $service->grant($request->user(), $request->all())], 201);
|
||||
}
|
||||
|
||||
public function requestDocument(Request $request, string $id, string $documentId, PortalProfileAdministration $service): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
$service->administrative($request->user());
|
||||
$row = DB::table('portal_profile_requests')->where('id', $id)->first();
|
||||
abort_unless($row && in_array($documentId, json_decode($row->document_ids, true), true), 404);
|
||||
$document = DB::table('documents')->where('id', $documentId)->first();
|
||||
abort_unless($document !== null, 404);
|
||||
|
||||
return app(VerifiedDocumentBinary::class)->respond($document, true);
|
||||
}
|
||||
|
||||
public function revoke(Request $request, string $id, PortalProfileAdministration $service): JsonResponse
|
||||
{
|
||||
$service->revoke($request->user(), $id, (string) $request->input('reason'));
|
||||
|
||||
return response()->json(['message' => 'Papel revogado; sessões e tokens anteriores invalidados.']);
|
||||
}
|
||||
|
||||
public function opportunities(Request $request, PortalProfileAccess $access): Response
|
||||
{
|
||||
abort_unless($access->grants($request->user()) !== [] || $access->superuser($request->user()), 403);
|
||||
|
||||
return app(OpportunityManagementController::class)->index($request, app(OpportunityManagement::class));
|
||||
}
|
||||
|
||||
public function edit(Request $request, PortalProfileAccess $access, ?int $id = null): Response
|
||||
{
|
||||
if ($id) {
|
||||
$access->authorize($request->user(), str_ends_with($request->path(), '/view') ? 'view' : 'edit', Opportunity::withTrashed()->findOrFail($id));
|
||||
} else {
|
||||
abort_unless($access->navigation($request->user())['contexts'] ?? [], 403);
|
||||
}
|
||||
|
||||
return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id);
|
||||
}
|
||||
|
||||
public function workflow(Request $request, int $id, OpportunityProfileWorkflow $service): JsonResponse
|
||||
{
|
||||
$record = $service->transition($request->user(), $id, $request->all());
|
||||
|
||||
return response()->json(['id' => $id, 'status' => app(PortalProfileAccess::class)->state($record), 'publication_status' => $record->status, 'etag' => app(OpportunityManagement::class)->etag($record), 'message' => 'Ação interna registada; não representa decisão externa.']);
|
||||
}
|
||||
|
||||
public function replacement(Request $request, PortalSuperusers $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['old_user_id' => 'required|integer', 'new_user_id' => 'required|integer', 'reason' => 'required|string|min:20|max:1000']);
|
||||
|
||||
return response()->json(['id' => $service->requestReplacement($request->user(), $data['old_user_id'], $data['new_user_id'], $data['reason'])], 201);
|
||||
}
|
||||
|
||||
public function approveSecurity(Request $request, string $id, PortalSuperusers $service): JsonResponse
|
||||
{
|
||||
$service->approve($request->user(), $id);
|
||||
|
||||
return response()->json(['message' => 'Aprovação independente registada.']);
|
||||
}
|
||||
|
||||
public function replace(Request $request, string $id, PortalSuperusers $service): JsonResponse
|
||||
{
|
||||
$service->applyReplacement($request->user(), $id);
|
||||
|
||||
return response()->json(['message' => 'Titular substituído atomicamente; continuam dois titulares.']);
|
||||
}
|
||||
|
||||
public function elevation(Request $request, PortalSuperusers $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['action' => 'required|string', 'record_id' => 'nullable|integer|exists:opportunities,id', 'reason' => 'required|string|min:20|max:1000']);
|
||||
|
||||
return response()->json(['id' => $service->requestElevation($request->user(), $data['action'], $data['record_id'] ?? null, $data['reason'])], 201);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\PortalProfileInstallation;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class PortalProfileInstallationController extends Controller
|
||||
{
|
||||
public function preview(Request $request, PortalProfileInstallation $installation): JsonResponse|Response
|
||||
{
|
||||
$plan = $installation->preview($request->user());
|
||||
|
||||
return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/installation', $plan);
|
||||
}
|
||||
|
||||
public function apply(Request $request, PortalProfileInstallation $installation): JsonResponse
|
||||
{
|
||||
return response()->json($installation->apply($request->user(), $request->all()));
|
||||
}
|
||||
|
||||
public function bootstrap(Request $request, PortalProfileInstallation $installation): JsonResponse
|
||||
{
|
||||
return response()->json($installation->bootstrap($request->user(), $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
class AuditProfileDecision
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (! $request->user() || ! $access->available() || ! preg_match('#^(perfil/|perfis/|minhas-oportunidades)#', $request->path())) {
|
||||
return $next($request);
|
||||
}
|
||||
try {
|
||||
$response = $next($request);
|
||||
} catch (\Throwable $error) {
|
||||
$status = $error instanceof HttpExceptionInterface ? $error->getStatusCode() : ($error instanceof ValidationException ? 422 : 500);
|
||||
$this->record($request, $access, $status);
|
||||
throw $error;
|
||||
}
|
||||
if ($response->getStatusCode() >= 400) {
|
||||
$this->record($request, $access, $response->getStatusCode());
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function record(Request $request, PortalProfileAccess $access, int $status): void
|
||||
{
|
||||
$access->audit($request->user(), 'request_denied', ['method' => $request->method(), 'path' => $request->path(), 'status' => $status]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsurePortalProfiles
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
abort_unless(config('portal.profile_access_enabled'), 404);
|
||||
abort_unless(app(PortalProfileAccess::class)->available(), 503, 'Autorização por perfis ainda não instalada.');
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Middleware;
|
||||
|
||||
@@ -24,6 +26,14 @@ class HandleInertiaRequests extends Middleware
|
||||
*/
|
||||
public function version(Request $request): ?string
|
||||
{
|
||||
if (app()->environment('testing') && config('portal.qa_build_directory')) {
|
||||
$manifest = public_path(config('portal.qa_build_directory').'/manifest.json');
|
||||
|
||||
$version = is_file($manifest) ? hash_file('xxh128', $manifest) : false;
|
||||
|
||||
return $version === false ? null : $version;
|
||||
}
|
||||
|
||||
return parent::version($request);
|
||||
}
|
||||
|
||||
@@ -39,11 +49,18 @@ class HandleInertiaRequests extends Middleware
|
||||
return [
|
||||
...parent::share($request),
|
||||
'name' => config('app.name'),
|
||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||
'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),
|
||||
'investorPathEnabled' => app(InvestorPath::class)->available(),
|
||||
'opportunityManagement' => config('portal.opportunity_dashboard_access_enabled') && $request->user() && app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()) ? [
|
||||
'installed' => app(OpportunityManagement::class)->installed(),
|
||||
'manage' => ['label' => 'Gestão de Oportunidades', 'href' => '/management/opportunities'],
|
||||
'create' => ['label' => 'Nova oportunidade', 'href' => '/management/opportunities/create'],
|
||||
'installationHref' => '/management/opportunity-management-install',
|
||||
] : null,
|
||||
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class PortalProfileSession
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$available = $access->available();
|
||||
if ($request->user() && config('portal.profile_access_enabled') && ! $available) {
|
||||
$recovery = $request->is('management/profile-install', 'management/profile-install/bootstrap')
|
||||
|| ($request->is('logout') && $request->isMethod('POST'));
|
||||
abort_if(! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && ! $recovery, 503,
|
||||
'Autorizações indisponíveis: recuperar a consistência dos perfis antes de gravar. Pode terminar a sessão ou consultar o instalador.');
|
||||
}
|
||||
if ($request->user() && $available) {
|
||||
$revision = (int) DB::table('users')->where('id', $request->user()->id)->value('portal_access_revision');
|
||||
$bound = $request->session()->get('portal.access_revision');
|
||||
if (($bound === null && $revision > 0) || ($bound !== null && (int) $bound !== $revision)) {
|
||||
Auth::guard('web')->logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return $request->expectsJson() ? response()->json(['message' => 'A autorização foi alterada. Inicie uma nova sessão.'], 401)
|
||||
: redirect('/login')->withErrors(['email' => 'A autorização foi alterada. Inicie uma nova sessão.']);
|
||||
}
|
||||
$request->session()->put('portal.access_revision', $revision);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ProtectPrivilegedIdentity
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (! $actor || ! $access->available()) {
|
||||
return $next($request);
|
||||
}
|
||||
if (! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && $access->has($actor, 'auditor')
|
||||
&& $request->is('management/*', 'api/v1/investment/admin/*', 'api/v2/investment/admin/*')) {
|
||||
$access->audit($actor, 'auditor_administrative_write_denied', ['method' => $request->method(), 'path' => $request->path()]);
|
||||
abort(403, 'Auditor só permite leitura administrativa, mesmo com outro papel ou permissão legada.');
|
||||
}
|
||||
$mandatoryMfa = $access->superuser($actor) || $access->has($actor, 'validator') || $access->has($actor, 'publisher');
|
||||
$denied = $request->isMethod('DELETE') && $request->is('user/two-factor-authentication') && $mandatoryMfa;
|
||||
$denied = $denied || ($access->superuser($actor) && $request->is('settings/profile') && $request->isMethod('PATCH')
|
||||
&& $request->has('email') && $request->input('email') !== $actor->email);
|
||||
if ($request->isMethod('DELETE') && $request->is('settings/profile')) {
|
||||
$denied = $denied || $access->superuser($actor)
|
||||
|| DB::table('portal_role_assignments')->where('user_id', $actor->id)->orWhere('approved_by', $actor->id)->exists()
|
||||
|| DB::table('portal_profile_requests')->where('user_id', $actor->id)->orWhere('decided_by', $actor->id)->exists();
|
||||
}
|
||||
if ($denied) {
|
||||
$access->audit($actor, 'privileged_identity_change_denied', ['method' => $request->method(), 'path' => $request->path()]);
|
||||
abort(403, 'Esta alteração removeria MFA obrigatório, um titular ou histórico de autorização. Use revogação ou substituição controlada; não desative MFA para recuperar acesso.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ProtectProfileOpportunity
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$id = null;
|
||||
if (preg_match('#^(?:(?:management|api/v1)/opportunities|api/v1/investment/admin/opportunities|minhas-oportunidades|management/territories/opportunities)/(\d+)(?:/|$)#', $request->path(), $match)) {
|
||||
$id = (int) $match[1];
|
||||
} elseif ($request->is('management/opportunity-origin/preview', 'management/opportunity-origin/apply')) {
|
||||
$id = filter_var($request->input('id'), FILTER_VALIDATE_INT) ?: null;
|
||||
} elseif ($request->is('api/v2/investment/admin/zones/*/links')) {
|
||||
$id = filter_var($request->input('opportunity_id'), FILTER_VALIDATE_INT) ?: null;
|
||||
}
|
||||
if ($request->user() && $id !== null && Schema::hasColumn('opportunities', 'owner_user_id')) {
|
||||
$record = Opportunity::withTrashed()->find($id);
|
||||
if ($record && $record->owner_user_id === null && ! $request->isMethod('GET')) {
|
||||
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 403, 'O papel v1 não contorna os controlos através de um registo legado.');
|
||||
}
|
||||
if ($record && ($record->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades'))) {
|
||||
abort_if($record->owner_user_id === null && str_starts_with($request->path(), 'minhas-oportunidades'), 403, 'Registo legado não convertido para a política v1.');
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') ? 'view' : 'edit', $record);
|
||||
abort_if($request->is('management/opportunity-origin/apply'), 403, 'O cadastro privado v1 não usa a classificação editorial dos exemplos legados.');
|
||||
abort_if($request->isMethod('POST') && str_ends_with($request->path(), '/lifecycle') && ! str_contains($request->path(), '/resources/'), 403, 'Use o workflow com decisões segregadas; o perfil não concede exclusão.');
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,12 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* @property int|null $owner_user_id
|
||||
* @property string|null $organization_id
|
||||
* @property array<string,mixed>|null $workflow_context
|
||||
* @property string|null $primary_territory_id
|
||||
* @property int $territory_version
|
||||
* @property int $management_version
|
||||
@@ -23,7 +27,7 @@ class Opportunity extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once'];
|
||||
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context'];
|
||||
|
||||
protected $fillable = [
|
||||
'sector_id', 'reference', 'title', 'slug', 'summary', 'description',
|
||||
@@ -37,6 +41,7 @@ class Opportunity extends Model
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'workflow_context' => 'array',
|
||||
'is_featured' => 'boolean',
|
||||
'territory_version' => 'integer',
|
||||
'published_at' => 'datetime',
|
||||
@@ -44,6 +49,20 @@ class Opportunity extends Model
|
||||
'estimated_investment_amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
/** @return array{scope:string,label:string,public_catalog:bool} */
|
||||
public function publicationPresentation(): array
|
||||
{
|
||||
$public = $this->exists && self::query()->whereKey($this->id)->published()->exists();
|
||||
$visible = ! $this->trashed() && $this->status === 'published' && $this->published_at !== null && $this->published_at->lte(now());
|
||||
$scope = $public ? 'public' : ($visible && $this->owner_user_id !== null ? 'restricted' : 'unpublished');
|
||||
|
||||
return ['scope' => $scope, 'public_catalog' => $public, 'label' => match ($scope) {
|
||||
'public' => 'Publicada no catálogo público',
|
||||
'restricted' => 'Disponibilizada com acesso restrito — perfis e organização autorizados',
|
||||
default => 'Sem versão disponibilizada; aprovação interna é uma etapa distinta',
|
||||
}];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Sector, $this> */
|
||||
public function sector(): BelongsTo
|
||||
{
|
||||
@@ -67,6 +86,10 @@ class Opportunity extends Model
|
||||
*/
|
||||
public function scopePublished(Builder $query): Builder
|
||||
{
|
||||
if (Schema::hasColumn('opportunities', 'workflow_context')) {
|
||||
$query->where(fn ($q) => $q->whereNull('owner_user_id')->orWhere('workflow_context->publication->visibility', 'public'));
|
||||
}
|
||||
|
||||
return $query->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())
|
||||
->whereRaw("COALESCE((SELECT origin.after_data->>'classification' FROM audit_events origin WHERE origin.source_system='opportunity-origin-review' AND origin.after_data->>'opportunity_id'=opportunities.id::text ORDER BY origin.occurred_at DESC,origin.id DESC LIMIT 1),'undetermined') <> 'example'");
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||
* @property string $name
|
||||
* @property string $email
|
||||
* @property Carbon|null $email_verified_at
|
||||
* @property int $portal_access_revision
|
||||
* @property string $password
|
||||
* @property string|null $two_factor_secret
|
||||
* @property string|null $two_factor_recovery_codes
|
||||
|
||||
@@ -9,16 +9,20 @@ use App\Services\Malware\ClamDScanner;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use App\Services\Mne\CompatibleBusinessRepository;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Auth\Events\Login;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -39,6 +43,17 @@ class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
$this->configureDefaults();
|
||||
|
||||
Event::listen(ValidTwoFactorAuthenticationCodeProvided::class, function ($event): void {
|
||||
if (app(PortalProfileAccess::class)->available()) {
|
||||
session()->put(['portal.mfa_actor' => $event->user->id, 'portal.mfa_at' => time()]);
|
||||
}
|
||||
});
|
||||
Event::listen(Login::class, function ($event): void {
|
||||
if (app(PortalProfileAccess::class)->available()) {
|
||||
session()->put('portal.access_revision', (int) DB::table('users')->where('id', $event->user->id)->value('portal_access_revision'));
|
||||
}
|
||||
});
|
||||
|
||||
Gate::define('manage-portal', fn (User $user) => $user->hasVerifiedEmail()
|
||||
&& in_array(strtolower($user->email), config('portal.managers', []), true));
|
||||
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Opis\JsonSchema\CompliantValidator;
|
||||
use Opis\JsonSchema\Errors\ErrorFormatter;
|
||||
use Opis\JsonSchema\Errors\ValidationError;
|
||||
|
||||
/** Explicit adapter of §25/26 to existing IDs and resource collections; never renumbers records. */
|
||||
class OpportunityCanonicalContract
|
||||
{
|
||||
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function schema(bool $draft = false): array
|
||||
{
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
if ($bytes === false) {
|
||||
throw new \RuntimeException('Opportunity schema unavailable.');
|
||||
}
|
||||
$schema = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
// The original conditions were omitted from the extracted Create/Patch definitions.
|
||||
foreach (['opportunity', 'realEstate', 'landRights', 'businessTransaction'] as $name) {
|
||||
$schema['$defs'][$name.'Create']['allOf'] = $schema['$defs'][$name]['allOf'] ?? [];
|
||||
}
|
||||
$schema = app(OpportunityCategoryFields::class)->enrich($schema);
|
||||
$schema = $this->writeSchema($schema, $draft);
|
||||
$properties = &$schema['$defs']['opportunityCreate']['properties'];
|
||||
unset($properties['mutation_context']); // Actor, audit reason and revision are server-owned.
|
||||
$properties['sector_id'] = ['type' => 'integer', 'minimum' => 1];
|
||||
$properties['promoter_id'] = ['type' => ['string', 'integer']];
|
||||
// References point to the existing collections; their metadata is recovered on the server.
|
||||
foreach (['locations', 'documents', 'images'] as $field) {
|
||||
$properties[$field]['items'] = ['type' => 'string', 'format' => 'uuid'];
|
||||
}
|
||||
$properties['evidences'] = ['type' => 'array', 'items' => ['$ref' => '#/$defs/evidenceCreate']];
|
||||
if (! $draft) {
|
||||
$properties['evidences']['minItems'] = 1;
|
||||
}
|
||||
$properties['evidences']['items'] = ['type' => 'object', 'additionalProperties' => false,
|
||||
'properties' => ['title' => ['type' => 'string'], 'evidence_type' => ['type' => 'string'],
|
||||
'document_id' => ['type' => 'string', 'format' => 'uuid'], 'description' => ['type' => 'string']],
|
||||
...($draft ? [] : ['required' => ['title', 'evidence_type', 'document_id']])];
|
||||
$schema['$ref'] = '#/$defs/opportunityCreate';
|
||||
$schema['$id'] = 'urn:investmoz:'.self::VERSION.($draft ? ':draft' : ':submit');
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $node
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function writeSchema(array $node, bool $draft): array
|
||||
{
|
||||
if (isset($node['$ref']) && preg_match('~^#/\$defs/(.+)$~', $node['$ref'], $match)) {
|
||||
// Collections in the normative Create still referenced response definitions.
|
||||
$defs = ['product', 'asset', 'input', 'market', 'impact', 'moneyItem', 'milestone', 'license', 'risk', 'relation', 'employment', 'environmentalSocial', 'localizedPublication', 'realEstate', 'landRights', 'businessTransaction', 'parcel', 'improvement', 'community'];
|
||||
if (in_array($match[1], $defs, true)) {
|
||||
$node['$ref'] .= 'Create';
|
||||
}
|
||||
}
|
||||
if ($draft) {
|
||||
unset($node['required'], $node['minItems'], $node['minProperties'], $node['contains'], $node['allOf']);
|
||||
if (isset($node['type'])) {
|
||||
$node['type'] = array_values(array_unique([...(array) $node['type'], 'null']));
|
||||
}
|
||||
if (isset($node['enum']) && ! in_array(null, $node['enum'], true)) {
|
||||
$node['enum'][] = null;
|
||||
}
|
||||
if (isset($node['minLength'])) {
|
||||
$node['minLength'] = 0;
|
||||
}
|
||||
if (($node['const'] ?? null) === true) {
|
||||
unset($node['const']);
|
||||
$node['type'] = 'boolean';
|
||||
}
|
||||
}
|
||||
foreach ($node as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
if (in_array($key, ['properties', '$defs'], true)) {
|
||||
foreach ($value as $name => $child) {
|
||||
$value[$name] = $this->writeSchema($child, $draft);
|
||||
}
|
||||
$node[$key] = $value;
|
||||
} elseif (in_array($key, ['items', 'if', 'then', 'else'], true)) {
|
||||
$node[$key] = $this->writeSchema($value, $draft);
|
||||
} elseif (in_array($key, ['allOf', 'oneOf', 'anyOf'], true)) {
|
||||
$node[$key] = array_map(fn ($child) => $this->writeSchema($child, $draft), $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $payload
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function draft(array $payload): array
|
||||
{
|
||||
abort_unless(config('portal.opportunity_specialized_drafts_enabled'), 422, 'Contrato especializado indisponível.');
|
||||
$this->validateSchema($payload, true);
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
private function validateSchema(array $payload, bool $draft): void
|
||||
{
|
||||
$schema = $this->schema($draft);
|
||||
$validator = new CompliantValidator(null, 100, false);
|
||||
$data = $this->schemaData($payload, $schema['$defs']['opportunityCreate'], $schema['$defs']);
|
||||
$result = $validator->validate($data, json_decode(json_encode($schema, JSON_THROW_ON_ERROR)));
|
||||
if ($error = $result->error()) {
|
||||
$errors = [];
|
||||
foreach ((new ErrorFormatter)->format($error) as $path => $messages) {
|
||||
$errors['canonical'.str_replace('/', '.', $path)] = $messages;
|
||||
}
|
||||
$required = function (ValidationError $node) use (&$required, &$errors): void {
|
||||
if ($node->keyword() === 'required') {
|
||||
$prefix = 'canonical.'.implode('.', $node->data()->fullPath());
|
||||
foreach ($node->args()['missing'] ?? [] as $field) {
|
||||
$errors[rtrim($prefix, '.').'.'.$field] = ['Preencha este campo antes de submeter.'];
|
||||
}
|
||||
}
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$required($child);
|
||||
}
|
||||
};
|
||||
$required($error);
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $node
|
||||
* @param array<string,mixed> $defs
|
||||
*/
|
||||
private function schemaData(mixed $value, array $node, array $defs): mixed
|
||||
{
|
||||
if (isset($node['$ref'])) {
|
||||
$name = basename($node['$ref']);
|
||||
$node = $defs[$name] ?? $node;
|
||||
}
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (in_array('object', (array) ($node['type'] ?? []), true) || isset($node['properties'])) {
|
||||
$result = new \stdClass;
|
||||
foreach ($value as $key => $item) {
|
||||
$result->{$key} = $this->schemaData($item, $node['properties'][$key] ?? [], $defs);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
return array_map(fn ($item) => $this->schemaData($item, $node['items'] ?? [], $defs), $value);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function validateSubmission(Opportunity $record): array
|
||||
{
|
||||
$values = app(OpportunityManagement::class)->values($record);
|
||||
$payload = $values['canonical'] ?? [];
|
||||
$this->validateSchema($payload, false);
|
||||
$errors = [];
|
||||
$check = function (bool $valid, string $path, string $message) use (&$errors): void {
|
||||
if (! $valid) {
|
||||
$errors['canonical.'.$path] = $message;
|
||||
}
|
||||
};
|
||||
$check(($payload['opportunity_category'] ?? null) === $record->opportunity_category, 'opportunity_category', 'A categoria deve coincidir com o registo e a autorização.');
|
||||
$check(($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Use a organização representada ou o autor individual; não outra identidade.');
|
||||
$sector = DB::table('sectors')->where('id', $payload['sector_id'])->whereNull('deleted_at')->where('is_active', true)->first();
|
||||
$subsector = DB::table('economic_activities')->where('id', $payload['subsector_id'])->where('status', 'published')->first();
|
||||
$activity = DB::table('economic_activities')->where('id', $payload['economic_activity_id'])->where('status', 'published')->first();
|
||||
$root = $subsector?->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
|
||||
$check($sector !== null && $root !== null && (int) $root->sector_id === (int) $sector->id
|
||||
&& $activity !== null && $activity->parent_id === $subsector->id && $activity->catalog_version_id === $root->catalog_version_id,
|
||||
'economic_activity_id', 'Sector → subsector → atividade requer referências publicadas da mesma versão e hierarquia.');
|
||||
foreach (['internal_contact_id', 'public_contact_id'] as $field) {
|
||||
if (! empty($payload[$field])) {
|
||||
$contacts = DB::table('contacts')->where('contacts.id', $payload[$field])->whereNull('contacts.deleted_at');
|
||||
if ($record->organization_id) {
|
||||
$contacts->whereExists(fn ($q) => $q->selectRaw('1')->from('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
|
||||
->whereColumn('ic.contact_id', 'contacts.id')->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at'));
|
||||
} else {
|
||||
$contacts->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$record->owner_user_id);
|
||||
}
|
||||
$check($contacts->exists(), $field, 'Contacto inexistente ou sem relação com o Promotor.');
|
||||
}
|
||||
}
|
||||
$resources = [];
|
||||
foreach (['locations', 'documents', 'images'] as $kind) {
|
||||
$table = app(OpportunityResources::class)->table($kind);
|
||||
foreach ($payload[$kind] ?? [] as $index => $id) {
|
||||
$row = DB::table($table)->where('id', $id)->where('opportunity_id', $record->id)->whereNull('deleted_at')->first();
|
||||
$check($row !== null, "$kind.$index", 'Recurso inexistente, eliminado ou de outra oportunidade.');
|
||||
if (! $row) {
|
||||
continue;
|
||||
}
|
||||
$row->payload = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($kind !== 'locations') {
|
||||
$file = DB::table('documents')->where('id', $row->document_id)->first();
|
||||
$check($file !== null && $file->deleted_at === null && $file->status === 'active' && $file->malware_scan_status === 'clean'
|
||||
&& hash_equals(trim($file->sha256), trim((string) $file->malware_scanned_sha256)), "$kind.$index", 'Original ativo com análise antimalware correspondente obrigatória.');
|
||||
if ($file) {
|
||||
// Verify actual bytes/cipher integrity as well as the recorded scan hash.
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
$row->sha256 = trim($file->sha256);
|
||||
}
|
||||
} else {
|
||||
$location = $row->payload;
|
||||
$check(! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
|
||||
app(InvestmentGeography::class)->selection($location, true);
|
||||
$country = $location['country_code'] ?? null;
|
||||
$check($country === 'MZ', "locations.$index.country_code", 'A hierarquia administrativa moçambicana deve declarar MZ; outros países exigem localização própria.');
|
||||
}
|
||||
$resources[$kind][$id] = (array) $row;
|
||||
}
|
||||
}
|
||||
$locations = $resources['locations'] ?? [];
|
||||
$primary = array_filter($locations, fn ($l) => $l['payload']['is_primary'] ?? false);
|
||||
$check(count($primary) === 1, 'locations', 'Selecione exatamente uma localização principal.');
|
||||
$check($payload['location_mode'] !== 'single' || count($locations) === 1, 'location_mode', 'Modo single exige uma localização.');
|
||||
foreach ($payload['evidences'] as $i => $evidence) {
|
||||
$check(isset($resources['documents'][$evidence['document_id']]), "evidences.$i.document_id", 'Evidência deve usar um documento ativo desta oportunidade incluído no contrato.');
|
||||
}
|
||||
$this->categoryRules($payload, $record, $resources, $errors);
|
||||
app(OpportunityCategoryFields::class)->validate($payload, $record, $resources, $errors);
|
||||
if ($errors) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
ksort($payload);
|
||||
$snapshot = ['adapter_version' => self::VERSION, 'schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
|
||||
'payload' => $payload, 'resources' => $resources];
|
||||
$snapshot['hash'] = hash('sha256', json_encode($snapshot, JSON_THROW_ON_ERROR));
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $p
|
||||
* @param array<string,mixed> $resources
|
||||
* @param array<string,string> $errors
|
||||
*/
|
||||
private function categoryRules(array $p, Opportunity $record, array $resources, array &$errors): void
|
||||
{
|
||||
$category = $p['opportunity_category'];
|
||||
if (in_array($category, ['concession', 'financing', 'supply', 'other'], true)) {
|
||||
$errors['canonical.module_profile_version'] = '§25.4: não existe perfil modular aprovado/configurado. O rascunho permanece disponível; não inventar regras.';
|
||||
}
|
||||
foreach (['real_estate', 'land_rights', 'business_transaction'] as $module) {
|
||||
$applicable = match ($module) {
|
||||
'real_estate' => ['real_estate'], 'land_rights' => ['land_rights'], default => ['business_sale', 'business_partnership', 'franchise']
|
||||
};
|
||||
if (isset($p[$module]) && ! in_array($category, $applicable, true)) {
|
||||
$errors['canonical.'.$module] = 'Módulo incompatível com a categoria. Preserve-o noutra versão antes de mudar de categoria.';
|
||||
}
|
||||
}
|
||||
if ($category === 'investment_project') {
|
||||
$total = $p['total_investment'];
|
||||
$sum = array_sum(array_column($p['investment_breakdown'], 'amount'));
|
||||
$secured = array_sum(array_column($p['secured_financing'], 'amount'));
|
||||
if (abs($sum - $total) > 0.010001 || $secured > $total || abs($p['funding_sought'] - ($total - $secured)) > 0.010001) {
|
||||
$errors['canonical.investment_breakdown'] = 'Rubricas e financiamento devem reconciliar com o total (tolerância normativa 0,01).';
|
||||
}
|
||||
if (! in_array($p['maturity_stage'], array_keys(OpportunityMaturity::STAGES), true)) {
|
||||
$errors['canonical.maturity_stage'] = 'Use um código explícito do catálogo de oito etapas; não reinterpretar a escala histórica.';
|
||||
}
|
||||
foreach (['investment_breakdown', 'secured_financing'] as $field) {
|
||||
foreach ($p[$field] as $i => $amount) {
|
||||
if ($amount['currency'] !== $p['currency']) {
|
||||
$errors["canonical.$field.$i.currency"] = 'Moedas distintas requerem cenário/câmbio explícito; não somar valores de moedas diferentes.';
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($p['markets'] as $i => $market) {
|
||||
if (isset($market['country_code']) && Validator::make(['country' => $market['country_code']], ['country' => app(CountryCatalogue::class)->rule()])->fails()) {
|
||||
$errors["canonical.markets.$i.country_code"] = 'Use país do catálogo ISO existente.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($category === 'real_estate') {
|
||||
$re = $p['real_estate'];
|
||||
if (($re['transaction_type'] === 'sale' && ($re['price'] ?? 0) <= 0) || ($re['transaction_type'] === 'lease' && (($re['rent'] ?? 0) <= 0 || empty($re['rent_periodicity'])))) {
|
||||
$errors['canonical.real_estate.price'] = 'Venda exige preço positivo; arrendamento exige renda positiva e periodicidade.';
|
||||
}
|
||||
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['property_condition'])) {
|
||||
$errors['canonical.real_estate.property_condition'] = 'Imóvel existente exige condição identificada.';
|
||||
}
|
||||
if (in_array($re['construction_status'], ['planned', 'under_construction'], true) && empty($re['planning_permit_document_id'])) {
|
||||
$errors['canonical.real_estate.planning_permit_document_id'] = 'Estado construtivo exige licença de construção (§25.1).';
|
||||
}
|
||||
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['use_license_document_id'])) {
|
||||
$errors['canonical.real_estate.use_license_document_id'] = 'Imóvel existente exige licença de utilização aplicável (§25.1).';
|
||||
}
|
||||
foreach (['planning_permit_document_id', 'use_license_document_id'] as $field) {
|
||||
if (! empty($re[$field]) && ! isset($resources['documents'][$re[$field]])) {
|
||||
$errors['canonical.real_estate.'.$field] = 'Licença deve referir documento ativo desta oportunidade.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($category === 'land_rights') {
|
||||
$land = $p['land_rights'];
|
||||
if (! empty($land['issuing_authority_id']) && ! DB::table('authorities')->where('id', $land['issuing_authority_id'])->where('status', 'published')->exists()) {
|
||||
$errors['canonical.land_rights.issuing_authority_id'] = 'Entidade emissora deve usar autoridade canónica publicada.';
|
||||
}
|
||||
if (! empty($land['issue_date']) && ($land['issue_date'] > today()->toDateString() || (! empty($land['expiry_date']) && $land['expiry_date'] <= $land['issue_date']))) {
|
||||
$errors['canonical.land_rights.issue_date'] = 'Emissão não futura e validade posterior à emissão.';
|
||||
}
|
||||
foreach ($land['parcels'] as $i => $parcel) {
|
||||
if (! isset($resources['locations'][$parcel['location_id']])) {
|
||||
$errors["canonical.land_rights.parcels.$i.location_id"] = 'Parcela deve usar uma localização desta oportunidade.';
|
||||
}
|
||||
try {
|
||||
$g = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_GeometryType(g)=\'ST_MultiPolygon\' AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) s', [json_encode($parcel['geometry'])]);
|
||||
if (! $g?->valid) {
|
||||
throw new \RuntimeException;
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
$errors["canonical.land_rights.parcels.$i.geometry"] = 'Parcela requer MultiPolygon válido, não vazio, EPSG:4326; limite administrativo não é parcela.';
|
||||
}
|
||||
}
|
||||
if (in_array($land['duat_status'], ['provisional', 'definitive'], true) && empty($land['duat_number'])) {
|
||||
$errors['canonical.land_rights.duat_number'] = 'DUAT provisório/definitivo exige número e entidade emissora.';
|
||||
}
|
||||
}
|
||||
if (isset($p['business_transaction'])) {
|
||||
$business = $p['business_transaction'];
|
||||
if ($business['legal_entity_id'] !== $record->organization_id || ! DB::table('organizations')->where('id', $business['legal_entity_id'])->whereNull('deleted_at')->exists()) {
|
||||
$errors['canonical.business_transaction.legal_entity_id'] = 'Entidade ativa representada obrigatória.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot */
|
||||
public function validatePublication(array $snapshot): void
|
||||
{
|
||||
$p = $snapshot['payload'];
|
||||
$errors = [];
|
||||
app(OpportunityCategoryFields::class)->publication($p, $errors);
|
||||
foreach ($snapshot['resources']['documents'] ?? [] as $id => $document) {
|
||||
if (! empty($document['payload']['valid_until']) && $document['payload']['valid_until'] < today()->toDateString()) {
|
||||
$errors['documents.'.$id] = 'Documento incluído expirou; preserve o original e reveja a versão.';
|
||||
}
|
||||
}
|
||||
if ($p['opportunity_category'] === 'land_rights') {
|
||||
foreach ($p['land_rights']['required_authorizations'] as $i => $authorization) {
|
||||
if (! in_array($authorization['status'] ?? '', ['approved', 'not_required'], true)
|
||||
|| (($authorization['status'] ?? '') === 'approved' && ! isset($snapshot['resources']['documents'][$authorization['document_id'] ?? '']))) {
|
||||
$errors['land_rights.required_authorizations.'.$i] = 'Autorização externa pendente ou sem documento. Aprovação interna não substitui esse ato.';
|
||||
}
|
||||
}
|
||||
foreach ($p['land_rights']['overlaps_conflicts'] as $i => $conflict) {
|
||||
if (($conflict['type'] ?? '') !== 'none' && ($conflict['status'] ?? '') !== 'resolved') {
|
||||
$errors['land_rights.overlaps_conflicts.'.$i] = 'Conflito impeditivo deve ser resolvido com evidência antes de publicar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($p['visibility'] === 'public') {
|
||||
$images = $snapshot['resources']['images'] ?? [];
|
||||
if (count(array_filter($images, fn ($image) => $image['payload']['is_cover'] ?? false)) !== 1) {
|
||||
$errors['images'] = 'Publicação pública exige uma capa explícita.';
|
||||
}
|
||||
foreach ($images as $id => $image) {
|
||||
$meta = $image['payload'];
|
||||
if (empty($meta['alt_text']) || empty($meta['caption']) || empty($meta['rights_status']) || empty($meta['derivatives'])
|
||||
|| (! empty($meta['rights_valid_until']) && $meta['rights_valid_until'] < today()->toDateString())) {
|
||||
$errors['images.'.$id] = 'Legenda, texto alternativo, direitos válidos e derivadas verificadas obrigatórios.';
|
||||
}
|
||||
foreach ($meta['derivatives'] ?? [] as $derived) {
|
||||
$file = DB::table('documents')->where('id', $derived['document_id'])->whereNull('deleted_at')->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->first();
|
||||
if (! $file) {
|
||||
$errors['images.'.$id] = 'Scan de uma derivada ainda não demonstrado.';
|
||||
} else {
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($errors) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function gates(Opportunity $record): array
|
||||
{
|
||||
return match ($record->opportunity_category) {
|
||||
'investment_project' => ['technical_review', 'legal_territorial_review'],
|
||||
'real_estate' => ['property_review', 'registry_urban_review', 'building_compliance_review'],
|
||||
'land_rights' => ['cadastral_screening', 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'],
|
||||
'business_sale' => ['corporate_screening', 'financial_review', 'legal_tax_due_diligence', 'confidentiality_clearance'],
|
||||
'business_partnership' => ['corporate_screening', 'financial_review', 'partnership_governance_review', 'legal_tax_due_diligence'],
|
||||
'franchise' => ['brand_license_review', 'financial_review', 'franchise_legal_review', 'confidentiality_clearance'],
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Same exact projection for preview and publication; never expose private business analysis.
|
||||
* @param array<string,mixed> $payload
|
||||
* @return array{title:string,summary:string,description:string} */
|
||||
public function publicProjection(array $payload): array
|
||||
{
|
||||
$business = isset($payload['business_transaction']) && ($payload['visibility'] ?? '') === 'public';
|
||||
|
||||
return ['title' => (string) ($payload['official_title'] ?? ''), 'summary' => (string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['executive_summary'] ?? '')),
|
||||
'description' => (string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['demand_statement'] ?? ''))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function options(User $actor, ?Opportunity $record): array
|
||||
{
|
||||
$orgs = array_values(array_unique(array_column(app(PortalProfileAccess::class)->navigation($actor)['contexts'] ?? [], 'organization_id')));
|
||||
if ($record?->organization_id) {
|
||||
$orgs = [$record->organization_id];
|
||||
}
|
||||
$contacts = DB::table('contacts')->whereNull('contacts.deleted_at')->where(function ($q) use ($orgs, $actor) {
|
||||
$q->where(fn ($own) => $own->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$actor->id))
|
||||
->orWhereExists(fn ($i) => $i->selectRaw('1')->from('investor_contacts as ic')->join('investors as inv', 'inv.id', '=', 'ic.investor_id')->whereColumn('ic.contact_id', 'contacts.id')->whereIn('inv.organization_id', $orgs)->whereNull('inv.deleted_at'));
|
||||
})->get(['id', 'full_name']);
|
||||
|
||||
return ['version' => self::VERSION, 'schema' => $this->schema(true)['$defs']['opportunityCreate'],
|
||||
'definitions' => $this->schema(true)['$defs'],
|
||||
'activities' => DB::table('economic_activities')->where('status', 'published')->get(['id', 'parent_id', 'sector_id', 'label_pt_mz', 'catalog_version_id']),
|
||||
'contacts' => $contacts, 'countries' => app(CountryCatalogue::class)->all(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||
'gates' => $record ? $this->gates($record) : [], 'resources' => $record ? array_combine(['locations', 'documents', 'images'], array_map(fn ($k) => array_values(array_filter(app(OpportunityResources::class)->listing($record->id, $k), fn ($row) => empty($row->deleted_at))), ['locations', 'documents', 'images'])) : []];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** §25 and common fields 415–422: explicit elaboration of opaque objects, shared by API and editor. */
|
||||
class OpportunityCategoryFields
|
||||
{
|
||||
public const VERSION = 'semantic-fields-20261010-1';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function text(): array
|
||||
{
|
||||
return ['type' => 'string', 'minLength' => 1, 'maxLength' => 1000];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function doc(): array
|
||||
{
|
||||
return ['type' => 'string', 'format' => 'uuid'];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function money(): array
|
||||
{
|
||||
return ['type' => 'number', 'minimum' => 0];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $properties
|
||||
* @param list<string> $required
|
||||
* @return array<string,mixed> */
|
||||
private function object(array $properties, array $required = []): array
|
||||
{
|
||||
return ['type' => 'object', 'properties' => $properties, 'required' => $required, 'additionalProperties' => true];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $properties
|
||||
* @param list<string> $required
|
||||
* @return array<string,mixed> */
|
||||
private function rows(array $properties, array $required = []): array
|
||||
{
|
||||
return ['type' => 'array', 'items' => $this->object($properties, $required)];
|
||||
}
|
||||
|
||||
/** Preserve normative artifact and legacy keys; enrich its runtime adapter explicitly.
|
||||
* @param array<string,mixed> $schema
|
||||
* @return array<string,mixed> */
|
||||
public function enrich(array $schema): array
|
||||
{
|
||||
$s = $this->text();
|
||||
$d = $this->doc();
|
||||
$n = $this->money();
|
||||
$date = ['type' => 'string', 'format' => 'date'];
|
||||
$strings = ['type' => 'array', 'items' => $s];
|
||||
$bool = ['type' => 'boolean'];
|
||||
$valuation = $this->object(['value' => $n, 'date' => $date, 'method' => $s, 'appraiser' => $s, 'document_id' => $d, 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'], 'divergence_justification' => $s], ['value', 'date', 'method', 'appraiser', 'document_id']);
|
||||
$defs = &$schema['$defs'];
|
||||
$common = &$defs['opportunityCreate']['properties'];
|
||||
foreach (['markets' => 'marketCreate', 'risks' => 'riskCreate', 'licenses' => 'licenseCreate', 'milestones' => 'milestoneCreate'] as $field => $def) {
|
||||
$common[$field]['items'] = ['$ref' => '#/$defs/'.$def];
|
||||
}
|
||||
$common['maturity_stage']['enum'] = [...array_keys(OpportunityMaturity::STAGES), null];
|
||||
$common['financial_indicators'] = $this->object(['npv' => ['type' => 'number'], 'irr' => ['type' => 'number'], 'payback_years' => $n, 'scenario' => $s, 'horizon_years' => ['type' => 'integer', 'minimum' => 1], 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'], 'discount_rate' => $n, 'model_document_id' => $d], ['npv', 'irr', 'payback_years', 'scenario', 'horizon_years', 'currency', 'discount_rate', 'model_document_id']);
|
||||
$defs['milestoneCreate']['properties'] += ['start_date' => $date, 'end_date' => $date, 'responsible_name' => $s, 'dependencies' => $strings];
|
||||
$defs['milestoneCreate']['required'] = array_values(array_unique([...$defs['milestoneCreate']['required'], 'start_date', 'end_date', 'responsible_name']));
|
||||
$defs['riskCreate']['properties']['mitigation']['minLength'] = 1;
|
||||
$re = &$defs['realEstateCreate']['properties'];
|
||||
$re['valuation'] = $valuation;
|
||||
$re['utilities'] = $this->rows(['type' => ['enum' => ['electricity', 'water', 'sanitation', 'telecommunications', 'access']], 'status' => ['enum' => ['existing', 'planned', 'unavailable']]], ['type', 'status']);
|
||||
$re['encumbrances'] = $this->rows(['type' => $s, 'details' => $s, 'document_id' => $d], ['type']);
|
||||
$re += ['title_document_id' => $d, 'title_holder_name' => $s, 'issuing_authority_id' => $d, 'expected_completion_date' => $date, 'occupancy_details' => $s, 'occupancy_document_id' => $d, 'amenities_other' => $s, 'urban_limit_document_id' => $d, 'max_built_area' => ['type' => 'number', 'exclusiveMinimum' => 0]];
|
||||
$re['viewing'] = $this->object(['mode' => $s, 'contact_id' => $d, 'window' => $s, 'instructions' => $s]);
|
||||
$defs['realEstateCreate']['required'] = [...$defs['realEstateCreate']['required'], 'title_document_id', 'title_holder_name', 'issuing_authority_id'];
|
||||
$lr = &$defs['landRightsCreate']['properties'];
|
||||
$lr['overlaps_conflicts'] = $this->rows(['type' => $s, 'status' => $s, 'details' => $s, 'resolution_document_id' => $d], ['type', 'status']);
|
||||
$lr['required_authorizations'] = $this->rows(['name' => $s, 'authority_id' => $d, 'status' => ['enum' => ['pending', 'approved', 'rejected', 'not_required']], 'document_id' => $d, 'condition' => $s], ['name', 'status']);
|
||||
$lr['community_consultation'] = $this->object(['status' => $s, 'minutes_document_id' => $d, 'participants' => $strings, 'map_document_id' => $d, 'commitments' => $s, 'date' => $date], ['status', 'minutes_document_id', 'participants', 'map_document_id', 'commitments', 'date']);
|
||||
$lr['consideration'] = $this->object(['object' => ['enum' => ['improvements', 'assets', 'operation', 'partnership']], 'amount' => $n, 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$']], ['object', 'amount', 'currency']);
|
||||
$lr += ['holder_document_id' => $d, 'communities_affected' => $bool, 'exploitation_plan_required' => $bool];
|
||||
$defs['landRightsCreate']['required'] = [...$defs['landRightsCreate']['required'], 'holder_document_id', 'communities_affected', 'exploitation_plan_required'];
|
||||
$bt = &$defs['businessTransactionCreate']['properties'];
|
||||
$bt['valuation'] = $valuation;
|
||||
$bt['entity_registration'] = $this->object(['tax_identifier' => $s, 'registration_number' => $s, 'legal_document_id' => $d, 'beneficial_owner_document_id' => $d], ['tax_identifier', 'registration_number', 'legal_document_id', 'beneficial_owner_document_id']);
|
||||
$bt['financial_periods'] = $this->rows(['year' => ['type' => 'integer', 'minimum' => 1900], 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$'], 'revenue' => $n, 'profit' => ['type' => 'number'], 'ebitda' => ['type' => 'number'], 'assets' => $n, 'liabilities' => $n, 'cash_flow' => ['type' => 'number'], 'document_id' => $d], ['year', 'currency', 'revenue', 'profit', 'assets', 'liabilities', 'cash_flow', 'document_id']);
|
||||
$bt['assets_liabilities'] = $this->object(['assets' => $s, 'excluded_assets' => $s, 'liabilities' => $s, 'guarantees' => $s, 'reconciliation_document_id' => $d], ['assets', 'excluded_assets', 'liabilities', 'guarantees', 'reconciliation_document_id']);
|
||||
$bt['employees'] = $this->object(['total' => ['type' => 'integer', 'minimum' => 0], 'contracts' => $s, 'obligations' => $s, 'labor_liabilities' => $s], ['total', 'contracts', 'obligations', 'labor_liabilities']);
|
||||
$bt['contracts_licenses'] = $this->rows(['name' => $s, 'transferability' => ['enum' => ['transferable', 'consent_required', 'not_transferable']], 'expiry_date' => $date, 'consent_document_id' => $d, 'document_id' => $d], ['name', 'transferability', 'expiry_date', 'document_id']);
|
||||
$bt['litigation_contingencies'] = $this->rows(['type' => $s, 'details' => $s, 'value' => $n, 'status' => $s, 'probability' => ['type' => 'number', 'minimum' => 0, 'maximum' => 100], 'entity' => $s, 'document_id' => $d], ['type']);
|
||||
$bt['partner_contribution'] = $this->object(['capital' => $n, 'assets' => $s, 'technology' => $s, 'market' => $s, 'management' => $s, 'calendar' => $s], ['capital', 'assets', 'technology', 'market', 'management', 'calendar']);
|
||||
$bt['governance_rights'] = $this->object(['voting' => $s, 'board' => $s, 'reserved_matters' => $s, 'dividends' => $s, 'exit' => $s, 'deadlock' => $s], ['voting', 'board', 'reserved_matters', 'dividends', 'exit', 'deadlock']);
|
||||
$bt['franchise_terms'] = $this->object(['brand' => $s, 'territory' => $s, 'term' => $s, 'initial_fee' => $n, 'royalties' => $s, 'support' => $s, 'exclusivity' => $s, 'renewal' => $s, 'termination' => $s, 'brand_license_document_id' => $d], ['brand', 'territory', 'term', 'initial_fee', 'royalties', 'support', 'exclusivity', 'renewal', 'termination', 'brand_license_document_id']);
|
||||
$bt += ['available_financial_years' => ['type' => 'integer', 'minimum' => 1], 'nda_document_id' => $d, 'teaser' => $s];
|
||||
$defs['businessTransactionCreate']['required'] = [...$defs['businessTransactionCreate']['required'], 'entity_registration', 'available_financial_years'];
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $p
|
||||
* @param array<string,mixed> $resources
|
||||
* @param array<string,string> $errors */
|
||||
public function validate(array $p, Opportunity $record, array $resources, array &$errors): void
|
||||
{
|
||||
$fail = function (bool $ok, string $path, string $message) use (&$errors) {
|
||||
if (! $ok) {
|
||||
$errors['canonical.'.$path] = $message;
|
||||
}
|
||||
};
|
||||
// Every nested reference belongs to this record, not merely to an existing document.
|
||||
$walk = function (array $node, string $path = '') use (&$walk, $resources, $fail) {
|
||||
foreach ($node as $key => $value) {
|
||||
$here = ltrim($path.'.'.$key, '.');
|
||||
if (is_array($value)) {
|
||||
$walk($value, $here);
|
||||
} elseif (is_string($key) && (str_ends_with($key, 'document_id') || in_array($key, ['image_id', 'location_id'], true)) && $value !== null && $value !== '') {
|
||||
$kind = $key === 'image_id' ? 'images' : ($key === 'location_id' ? 'locations' : 'documents');
|
||||
$fail(isset($resources[$kind][$value]), $here, 'Selecione um recurso ativo desta oportunidade, incluído no contrato.');
|
||||
}
|
||||
if ($key === 'authority_id' || $key === 'issuing_authority_id') {
|
||||
$fail($value === null || DB::table('authorities')->where('id', $value)->where('status', 'published')->where('valid_from', '<=', today())->where(fn ($q) => $q->whereNull('valid_to')->orWhere('valid_to', '>=', today()))->exists(), $here, 'Selecione uma entidade emissora publicada e aplicável nesta data.');
|
||||
}
|
||||
}
|
||||
};
|
||||
$walk($p);
|
||||
if (isset($p['real_estate']) || isset($p['business_transaction'])) {
|
||||
$fail(isset($p['currency']) && is_string($p['currency']) && preg_match('/^[A-Z]{3}$/D', $p['currency']) === 1, 'currency', 'Indique a moeda de todos os valores desta versão.');
|
||||
}
|
||||
if ($p['opportunity_category'] === 'investment_project') {
|
||||
$milestones = $p['milestones'];
|
||||
$fail(count($milestones) >= 2, 'milestones', 'Indique pelo menos dois marcos.');
|
||||
$titles = array_column($milestones, 'title');
|
||||
$fail(count($titles) === count(array_unique($titles)), 'milestones', 'Os nomes dos marcos devem identificar cada dependência sem ambiguidade.');
|
||||
$edges = [];
|
||||
foreach ($milestones as $i => $m) {
|
||||
$fail($m['end_date'] >= $m['start_date'], "milestones.$i.end_date", 'O fim não pode anteceder o início.');
|
||||
$edges[$m['title']] = $m['dependencies'] ?? [];
|
||||
$fail(array_diff($edges[$m['title']], $titles) === [], "milestones.$i.dependencies", 'Uma dependência deve indicar outro marco deste cronograma.');
|
||||
}
|
||||
$seen = [];
|
||||
$active = [];
|
||||
$visit = function ($title) use (&$visit, &$seen, &$active, $edges): bool {
|
||||
if (isset($active[$title])) {
|
||||
return false;
|
||||
}if (isset($seen[$title])) {
|
||||
return true;
|
||||
}$active[$title] = true;
|
||||
foreach ($edges[$title] ?? [] as $parent) {
|
||||
if (! $visit($parent)) {
|
||||
return false;
|
||||
}
|
||||
}unset($active[$title]);
|
||||
$seen[$title] = true;
|
||||
|
||||
return true;
|
||||
};
|
||||
foreach ($titles as $title) {
|
||||
$fail($visit($title), 'milestones', 'As dependências não podem formar um ciclo.');
|
||||
}
|
||||
foreach ($p['risks'] as $i => $risk) {
|
||||
$fail(($risk['likelihood'] < 4 && $risk['severity'] < 4) || ! empty($risk['mitigation']), "risks.$i.mitigation", 'Risco com probabilidade ou gravidade alta exige mitigação.');
|
||||
}
|
||||
if (in_array($p['maturity_stage'], ['feasibility', 'structured', 'investment_ready', 'implementation', 'operational'], true)) {
|
||||
$fail(! empty($p['financial_indicators']), 'financial_indicators', 'A partir de viabilidade, indique cenário, indicadores e modelo financeiro.');
|
||||
$fail(count(array_filter($p['evidences'], fn ($e) => in_array($e['evidence_type'], ['feasibility_study', 'feasibility'], true))) > 0, 'evidences', 'Associe o estudo de viabilidade desta etapa.');
|
||||
}
|
||||
}
|
||||
if (isset($p['real_estate'])) {
|
||||
$re = $p['real_estate'];
|
||||
$types = array_column($re['utilities'], 'type');
|
||||
$fail(count($types) === 5 && count(array_unique($types)) === 5, 'real_estate.utilities', 'Declare os cinco serviços: eletricidade, água, saneamento, telecomunicações e acesso.');
|
||||
if ($re['occupancy_status'] !== 'vacant') {
|
||||
foreach (['occupancy_details', 'occupancy_document_id'] as $field) {
|
||||
$fail(! empty($re[$field]), 'real_estate.'.$field, 'Ocupação exige detalhe contratual restrito e documento.');
|
||||
}
|
||||
}
|
||||
if (in_array($re['construction_status'], ['planned', 'under_construction'], true)) {
|
||||
$fail(! empty($re['expected_completion_date']) && $re['expected_completion_date'] >= today()->toDateString(), 'real_estate.expected_completion_date', 'Indique prazo de conclusão futuro ou atual.');
|
||||
}
|
||||
if (in_array('other', $re['amenities'] ?? [], true)) {
|
||||
$fail(! empty($re['amenities_other']), 'real_estate.amenities_other', 'Descreva a comodidade indicada como outra.');
|
||||
}
|
||||
if (isset($re['max_built_area'])) {
|
||||
$fail($re['built_area'] <= $re['max_built_area'], 'real_estate.built_area', 'A área excede o limite urbanístico declarado.');
|
||||
$fail(! empty($re['urban_limit_document_id']), 'real_estate.urban_limit_document_id', 'Associe a fonte do limite urbanístico.');
|
||||
}
|
||||
foreach ($re['encumbrances'] as $i => $row) {
|
||||
if ($row['type'] !== 'none') {
|
||||
foreach (['details', 'document_id'] as $field) {
|
||||
$fail(! empty($row[$field]), "real_estate.encumbrances.$i.$field", 'Ónus ou restrição exige descrição e documento.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($p['land_rights'])) {
|
||||
$lr = $p['land_rights'];
|
||||
if (in_array($lr['duat_status'], ['provisional', 'definitive'], true)) {
|
||||
$fail(! empty($lr['issuing_authority_id']), 'land_rights.issuing_authority_id', 'DUAT provisório/definitivo exige entidade emissora.');
|
||||
if (! empty($lr['duat_number']) && ! empty($lr['issuing_authority_id'])) {
|
||||
$fail(! Opportunity::whereKeyNot($record->id)->whereNotNull('owner_user_id')->whereRaw("management_draft->'canonical'->'land_rights'->>'duat_number'=?", [$lr['duat_number']])->whereRaw("management_draft->'canonical'->'land_rights'->>'issuing_authority_id'=?", [$lr['issuing_authority_id']])->whereNotIn('status', ['archived', 'rejected'])->exists(), 'land_rights.duat_number', 'Este número já está associado à mesma entidade emissora; reconciliar antes de submeter.');
|
||||
}
|
||||
}
|
||||
if (in_array($lr['operation_type'], ['transfer_of_improvements', 'lease_of_improvements'], true)) {
|
||||
$fail(! empty($lr['improvements']), 'land_rights.improvements', 'A operação sobre benfeitorias exige a respetiva descrição/evidência.');
|
||||
}
|
||||
foreach ($lr['improvements'] ?? [] as $i => $row) {
|
||||
foreach (['assessed_value', 'currency', 'valuation_date', 'document_id', 'image_id'] as $field) {
|
||||
$fail(isset($row[$field]), "land_rights.improvements.$i.$field", 'Benfeitoria exige valor, data, moeda, documento e fotografia.');
|
||||
}
|
||||
}
|
||||
$fail(! $lr['exploitation_plan_required'] || ! empty($lr['exploitation_plan_document_id']), 'land_rights.exploitation_plan_document_id', 'Plano de exploração aplicável exige documento.');
|
||||
$fail(! $lr['communities_affected'] || (! empty($lr['communities']) && ! empty($lr['community_consultation'])), 'land_rights.community_consultation', 'Comunidade afetada exige comunidade, representantes e consulta documentada.');
|
||||
foreach ($lr['communities'] ?? [] as $i => $row) {
|
||||
foreach (['representative_name', 'consultation_date', 'location_id'] as $field) {
|
||||
$fail(! empty($row[$field]), "land_rights.communities.$i.$field", 'Identifique representante, data e localização da comunidade.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($p['business_transaction'])) {
|
||||
$bt = $p['business_transaction'];
|
||||
$type = $bt['transaction_type'];
|
||||
$allowed = match ($p['opportunity_category']) {
|
||||
'business_sale' => ['full_sale', 'partial_sale'],'business_partnership' => ['partnership', 'joint_venture'],'franchise' => ['franchise'],default => []
|
||||
};
|
||||
$fail(in_array($type, $allowed, true), 'business_transaction.transaction_type', 'Modalidade incompatível com esta categoria.');
|
||||
$years = array_column($bt['financial_periods'], 'year');
|
||||
$fail(count($years) >= min(3, $bt['available_financial_years']) && count($years) === count(array_unique($years)), 'business_transaction.financial_periods', 'Inclua pelo menos três exercícios quando existentes, sem repetir anos.');
|
||||
foreach ($years as $i => $year) {
|
||||
$fail($year <= (int) today()->format('Y'), "business_transaction.financial_periods.$i.year", 'Não apresente um exercício futuro como demonstração realizada.');
|
||||
}
|
||||
$fail($bt['litigation_contingencies'] !== [], 'business_transaction.litigation_contingencies', 'Declare contingências, incluindo explicitamente a ausência.');
|
||||
foreach ($bt['litigation_contingencies'] as $i => $row) {
|
||||
if ($row['type'] !== 'none') {
|
||||
foreach (['value', 'status', 'probability', 'entity', 'document_id'] as $field) {
|
||||
$fail(isset($row[$field]), "business_transaction.litigation_contingencies.$i.$field", 'Contingência exige valor, estado, probabilidade, responsável/evidência restrita.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($bt['confidentiality_level'] === 'nda_required') {
|
||||
$fail(! empty($bt['nda_document_id']), 'business_transaction.nda_document_id', 'Associe o acordo de confidencialidade aplicável.');
|
||||
}
|
||||
if ($p['visibility'] === 'public') {
|
||||
$fail(! empty($bt['teaser']), 'business_transaction.teaser', 'Prepare o texto público sem informação confidencial.');
|
||||
}
|
||||
}
|
||||
foreach (['real_estate', 'business_transaction'] as $module) {
|
||||
if (isset($p[$module])) {
|
||||
$v = $p[$module]['valuation'];
|
||||
$fail($v['value'] > 0, "$module.valuation.value", 'Avaliação deve ter valor positivo.');
|
||||
$fail($v['date'] <= today()->toDateString(), "$module.valuation.date", 'A data da avaliação não pode ser futura.');
|
||||
// No arbitrary materiality threshold: reviewer determines divergence and its evidence.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $p
|
||||
* @param array<string,string> $errors */
|
||||
public function publication(array $p, array &$errors): void
|
||||
{
|
||||
if (isset($p['business_transaction'])) {
|
||||
foreach ($p['business_transaction']['contracts_licenses'] as $i => $row) {
|
||||
if ($row['expiry_date'] < today()->toDateString() || $row['transferability'] === 'not_transferable' || ($row['transferability'] === 'consent_required' && empty($row['consent_document_id']))) {
|
||||
$errors["business_transaction.contracts_licenses.$i"] = 'Contrato/licença vencido, intransmissível ou sem consentimento exigido.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($p['land_rights'])) {
|
||||
$lr = $p['land_rights'];
|
||||
if (! empty($lr['expiry_date']) && $lr['expiry_date'] < today()->toDateString()) {
|
||||
$errors['land_rights.expiry_date'] = 'Direito expirado; decisão interna não renova o ato externo.';
|
||||
}
|
||||
if ($lr['communities_affected'] && ! in_array($lr['community_consultation']['status'] ?? '', ['completed', 'approved'], true)) {
|
||||
$errors['land_rights.community_consultation'] = 'Consulta necessária ainda não concluída/documentada.';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ class OpportunityImageProcessor
|
||||
/** @param array<string,mixed> $input */
|
||||
public function prepare(User $actor, int $opportunityId, string $id, array $input): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', Opportunity::withTrashed()->findOrFail($opportunityId));
|
||||
abort_unless($this->available(), 423, 'GD/WebP não disponível neste processo. Original e metadados preservados; processamento pendente.');
|
||||
$data = validator($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$stored = [];
|
||||
@@ -28,6 +28,7 @@ class OpportunityImageProcessor
|
||||
try {
|
||||
DB::transaction(function () use ($actor, $opportunityId, $id, $data, &$stored, &$documents) {
|
||||
$o = Opportunity::withTrashed()->whereKey($opportunityId)->lockForUpdate()->firstOrFail();
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $o);
|
||||
abort_if($o->trashed() || $o->status === 'archived', 409, 'Restaure antes de processar.');
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($o), $data['etag']), 409, 'Conflito de versão; preserve os dados.');
|
||||
$image = DB::table('opportunity_images')->where('opportunity_id', $opportunityId)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
|
||||
@@ -20,13 +20,15 @@ class OpportunityManagement
|
||||
|
||||
public const MATURITY_FIELDS = ['maturity_level', 'maturity_label', 'maturity_stage', 'maturity_catalogue_version'];
|
||||
|
||||
public const PRIVATE_DRAFT_FIELDS = [...self::MATURITY_FIELDS, 'real_estate', 'canonical'];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function values(Opportunity $record): array
|
||||
{
|
||||
$base = $record->only(self::FIELDS);
|
||||
$draft = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::MATURITY_FIELDS)))];
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::PRIVATE_DRAFT_FIELDS)))];
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
@@ -47,7 +49,20 @@ class OpportunityManagement
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?int $id = null): Opportunity
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$profileCreation = $id === null && str_starts_with(request()->path(), 'minhas-oportunidades');
|
||||
if ($id !== null) {
|
||||
$existingRecord = Opportunity::withTrashed()->findOrFail($id);
|
||||
$access->authorize($actor, 'edit', $existingRecord);
|
||||
if ($existingRecord->owner_user_id !== null) {
|
||||
abort_unless($access->canEdit($actor, $existingRecord, $input['opportunity_category'] ?? null), 403);
|
||||
abort_if(array_key_exists('organization_id', $input) && $input['organization_id'] !== $existingRecord->organization_id, 403, 'A organização não pode ser alterada por edição.');
|
||||
}
|
||||
} elseif ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? ''), 403);
|
||||
} else {
|
||||
abort_unless($access->legacyWriteAllowed($actor), 403, 'O papel v1 não usa a criação legada para contornar o seu âmbito.');
|
||||
}
|
||||
abort_unless($this->installed(), 503, 'Instalação autenticada ainda necessária.');
|
||||
$data = Validator::make($input, [
|
||||
'etag' => [$id ? 'required' : 'nullable', 'string', 'size:64'],
|
||||
@@ -62,18 +77,30 @@ class OpportunityManagement
|
||||
'expected_impact' => ['nullable', 'string', 'max:10000'],
|
||||
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
'opportunity_category' => ['nullable', Rule::in(self::CATEGORIES)],
|
||||
'real_estate' => ['sometimes', 'array'],
|
||||
'canonical' => ['sometimes', 'array'],
|
||||
'estimated_investment_amount' => ['nullable', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
|
||||
'estimated_investment_currency' => ['nullable', 'in:MZN,USD,EUR,ZAR'],
|
||||
'reason' => ['required', 'string', 'min:20', 'max:1000'],
|
||||
'organization_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
|
||||
'owner_user_id' => 'prohibited', 'workflow_context' => 'prohibited', 'status' => 'prohibited', 'first_submitted_at' => 'prohibited',
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
])->validate();
|
||||
$data = app(OpportunityMaturity::class)->normalize($data);
|
||||
if (array_key_exists('real_estate', $data)) {
|
||||
$data['real_estate'] = app(OpportunityRealEstateDraft::class)->validate($data['real_estate']);
|
||||
}
|
||||
if (array_key_exists('canonical', $data)) {
|
||||
$data['canonical'] = app(OpportunityCanonicalContract::class)->draft($data['canonical']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $id) {
|
||||
return DB::transaction(function () use ($actor, $data, $id, $profileCreation, $access) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
|
||||
if (! $id && ($existing = Opportunity::withTrashed()->where('management_creation_key', $data['creation_key'])->first())) {
|
||||
$access->authorize($actor, 'view', $existing);
|
||||
abort_unless($profileCreation === ($existing->owner_user_id !== null) && (! $profileCreation || $existing->organization_id === ($data['organization_id'] ?? null)), 409);
|
||||
$snapshot = $this->values($existing);
|
||||
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS])) as $key => $value) {
|
||||
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS])) as $key => $value) {
|
||||
if (($snapshot[$key] ?? null) != $value) {
|
||||
throw ValidationException::withMessages(['creation_key' => 'Esta chave já foi utilizada com dados diferentes.']);
|
||||
}
|
||||
@@ -83,11 +110,33 @@ class OpportunityManagement
|
||||
}
|
||||
$record = $id ? Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail() : new Opportunity;
|
||||
if ($id) {
|
||||
$access->authorize($actor, 'edit', $record);
|
||||
$this->check($record, $data['etag']);
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
$before = $record->getAttributes();
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS]));
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS]));
|
||||
if (array_key_exists('canonical', $changes)) {
|
||||
$previous = $record->exists ? $this->values($record) : [];
|
||||
$changes['canonical'] = [...($previous['canonical'] ?? []), ...$changes['canonical']];
|
||||
if (($changes['canonical']['opportunity_category'] ?? ($changes['opportunity_category'] ?? $record->opportunity_category)) !== ($changes['opportunity_category'] ?? $record->opportunity_category)) {
|
||||
throw ValidationException::withMessages(['canonical.opportunity_category' => 'Contrato e registo devem usar a mesma categoria.']);
|
||||
}
|
||||
// One entry of common data feeds the existing fields; a closed/public version stays untouched.
|
||||
foreach (['official_title' => 'title', 'executive_summary' => 'summary', 'demand_statement' => 'description', 'sector_id' => 'sector_id', 'promoter_type' => 'promoter_type'] as $source => $target) {
|
||||
if (array_key_exists($source, $changes['canonical'])) {
|
||||
$changes[$target] = $changes['canonical'][$source];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (array_key_exists('real_estate', $changes)) {
|
||||
$previousValues = $record->exists ? $this->values($record) : [];
|
||||
$category = array_key_exists('opportunity_category', $data) ? $data['opportunity_category'] : ($previousValues['opportunity_category'] ?? null);
|
||||
if ($category !== 'real_estate') {
|
||||
throw ValidationException::withMessages(['real_estate' => 'O contrato imobiliário pertence à categoria real_estate.']);
|
||||
}
|
||||
$changes['real_estate'] = [...($previousValues['real_estate'] ?? []), ...$changes['real_estate']];
|
||||
}
|
||||
if (array_intersect_key($data, InvestmentGeography::FIELDS) !== []) {
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$changes['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
@@ -102,6 +151,12 @@ class OpportunityManagement
|
||||
$record->management_creation_key = $data['creation_key'];
|
||||
$record->management_version = 1;
|
||||
$record->estimated_investment_currency = null;
|
||||
if ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? ''), 403);
|
||||
$record->owner_user_id = $actor->id;
|
||||
$record->organization_id = $data['organization_id'] ?? null;
|
||||
$record->workflow_context = ['policy_version' => PortalProfileAccess::VERSION, 'contributors' => [$actor->id]];
|
||||
}
|
||||
} else {
|
||||
$record->management_version++;
|
||||
}
|
||||
@@ -111,17 +166,24 @@ class OpportunityManagement
|
||||
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
|
||||
} else {
|
||||
foreach ($changes as $key => $value) {
|
||||
if (in_array($key, ['maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
if (in_array($key, ['real_estate', 'canonical', 'maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
continue;
|
||||
}
|
||||
$record->{$key} = $value;
|
||||
}
|
||||
if (isset($changes['maturity_catalogue_version'])) {
|
||||
if (isset($changes['maturity_catalogue_version']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes)) {
|
||||
// The existing draft JSON holds the versioned catalogue; legacy columns stay intact.
|
||||
$previous = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::MATURITY_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::PRIVATE_DRAFT_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
}
|
||||
if ($record->owner_user_id !== null) {
|
||||
$context = $record->workflow_context ?? [];
|
||||
unset($context['approval'], $context['reviews']);
|
||||
$context['content_revision'] = ($context['content_revision'] ?? 0) + 1;
|
||||
$context['contributors'] = array_values(array_unique([...($context['contributors'] ?? []), $actor->id]));
|
||||
$record->workflow_context = $context;
|
||||
}
|
||||
$record->save();
|
||||
$this->audit($record, $actor, $before, $id ? 'draft_updated' : 'draft_created', $data['reason']);
|
||||
|
||||
@@ -132,11 +194,13 @@ class OpportunityManagement
|
||||
/** @param array<string,mixed> $input */
|
||||
public function lifecycle(User $actor, int $id, array $input): Opportunity
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
$data = Validator::make($input, ['etag' => ['required', 'string', 'size:64'], 'action' => ['required', 'in:delete,restore'], 'reason' => ['required', 'string', 'min:20', 'max:1000'], 'confirm' => ['required', 'accepted']])->validate();
|
||||
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($actor), 403);
|
||||
$actions = config('portal.opportunity_dashboard_access_enabled') ? 'in:delete,archive,restore' : 'in:delete,restore';
|
||||
$data = Validator::make($input, ['etag' => ['required', 'string', 'size:64'], 'action' => ['required', $actions], 'reason' => ['required', 'string', 'min:20', 'max:1000'], 'confirm' => ['required', 'accepted']])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->owner_user_id !== null, 403, 'A v1 exige pedido e decisão de arquivo; não concede exclusão ou restauro ao Promotor.');
|
||||
$this->check($record, $data['etag']);
|
||||
$before = $record->getAttributes();
|
||||
if ($data['action'] === 'restore') {
|
||||
@@ -152,8 +216,10 @@ class OpportunityManagement
|
||||
}
|
||||
} else {
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Registo já eliminado/arquivado.');
|
||||
if ($this->closed($record)) {
|
||||
$record->management_closed_once = true;
|
||||
if ($data['action'] === 'archive' || $this->closed($record)) {
|
||||
if ($this->closed($record)) {
|
||||
$record->management_closed_once = true;
|
||||
}
|
||||
$record->status = 'archived';
|
||||
} else {
|
||||
$record->deleted_at = now();
|
||||
|
||||
@@ -15,7 +15,12 @@ class OpportunityManagementInstallation
|
||||
$files = [__FILE__, app_path('Models/Opportunity.php'), app_path('Services/OpportunityManagement.php'), app_path('Http/Controllers/OpportunityManagementController.php'), app_path('Http/Controllers/PortalManagementController.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunities.tsx')];
|
||||
|
||||
$files[] = app_path('Services/OpportunityMaturity.php');
|
||||
$files = [...$files, app_path('Services/OpportunityRealEstateDraft.php'), app_path('Http/Middleware/HandleInertiaRequests.php'), config_path('portal.php'),
|
||||
resource_path('data/investmoz-opportunity-modular.schema.json'), resource_path('js/pages/dashboard.tsx'), resource_path('js/components/app-sidebar.tsx'), resource_path('js/types/opportunity-management.ts'), base_path('vite.config.ts')];
|
||||
|
||||
$files = [...$files, resource_path('js/lib/portal-navigation.ts'), resource_path('js/components/portal-grouped-menu.tsx')];
|
||||
|
||||
$files = [...$files, ...PortalProfileAccess::fingerprintFiles()];
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class OpportunityProfileWorkflow
|
||||
{
|
||||
public function __construct(private PortalProfileAccess $access, private OpportunityManagement $management,
|
||||
private OpportunityCanonicalContract $contract, private OpportunityWorkflowTasks $tasks) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function actions(User $actor, Opportunity $record): array
|
||||
{
|
||||
if ($record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
|
||||
return [];
|
||||
}
|
||||
$actions = [];
|
||||
$state = $this->access->state($record);
|
||||
if ($this->access->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id)
|
||||
&& $this->access->operational($actor, 'edit', $record->id)) {
|
||||
if (in_array($state, ['draft', 'needs_information'], true)) {
|
||||
$actions[] = 'submit';
|
||||
}
|
||||
if (in_array($state, ['approved', 'published', 'suspended'], true)) {
|
||||
$actions[] = 'request_revision';
|
||||
}
|
||||
if (! in_array($state, ['archived', 'rejected'], true)) {
|
||||
$actions[] = 'request_archive';
|
||||
}
|
||||
if ($state === 'rejected' && empty($record->workflow_context['appeal']['pending'])) {
|
||||
$actions[] = 'appeal';
|
||||
}
|
||||
}
|
||||
if ($this->access->mfa($actor) && ! $this->access->conflict($actor, $record)) {
|
||||
if ($this->access->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category) && $this->access->operational($actor, 'validate', $record->id)) {
|
||||
if ($state === 'submitted') {
|
||||
$actions[] = 'start_review';
|
||||
}
|
||||
if (in_array($state, ['submitted', 'in_review', 'information_pending'], true)) {
|
||||
array_push($actions, 'request_correction', 'pending_opinion', 'reject', 'review_gate', 'approve');
|
||||
if ($this->responsibility($actor, $record, 'validation_coordinator')) {
|
||||
$actions[] = 'assign_review';
|
||||
}
|
||||
}
|
||||
if ($state === 'rejected' && ($record->workflow_context['appeal']['pending'] ?? false)
|
||||
&& $this->responsibility($actor, $record, 'appeal_reviewer')
|
||||
&& (int) ($record->workflow_context['rejection']['actor_id'] ?? 0) !== $actor->id) {
|
||||
array_push($actions, 'appeal_uphold', 'appeal_reopen');
|
||||
}
|
||||
if (count(array_filter($record->workflow_context['opinions'] ?? [], fn ($opinion) => ($opinion['recipient_id'] ?? 0) === $actor->id && ($opinion['status'] ?? '') === 'pending')) > 0) {
|
||||
$actions[] = 'respond_opinion';
|
||||
}
|
||||
}
|
||||
if ($this->access->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category)) {
|
||||
if ($state === 'approved' && $this->access->operational($actor, 'publish', $record->id)
|
||||
&& (int) ($record->workflow_context['approval']['actor_id'] ?? 0) !== $actor->id) {
|
||||
$actions[] = 'publish';
|
||||
if ($this->responsibility($actor, $record, 'publication_coordinator')) {
|
||||
$actions[] = 'assign_publication';
|
||||
}
|
||||
}
|
||||
if ($this->access->operational($actor, 'archive', $record->id)) {
|
||||
if ($record->status === 'published') {
|
||||
$actions[] = 'suspend';
|
||||
}
|
||||
if ($state !== 'archived') {
|
||||
$actions[] = 'archive';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($record->workflow_context['assignment']['assignee_user_id']) && (int) $record->workflow_context['assignment']['assignee_user_id'] !== $actor->id) {
|
||||
$actions = array_values(array_diff($actions, ['start_review', 'request_correction', 'pending_opinion', 'reject', 'review_gate', 'approve']));
|
||||
}
|
||||
if (isset($record->workflow_context['publication_assignment']['assignee_user_id']) && (int) $record->workflow_context['publication_assignment']['assignee_user_id'] !== $actor->id) {
|
||||
$actions = array_values(array_diff($actions, ['publish']));
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/** Scoped names/IDs only; no secrets or implicit assignees.
|
||||
* @return array<string,mixed> */
|
||||
public function participants(User $actor, Opportunity $record): array
|
||||
{
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
if (! $this->access->has($actor, 'validator') && ! $this->access->has($actor, 'publisher')) {
|
||||
return ['validators' => [], 'publishers' => []];
|
||||
}
|
||||
$result = ['validators' => [], 'publishers' => []];
|
||||
foreach (User::whereNotNull('email_verified_at')->whereNotNull('two_factor_confirmed_at')->get() as $candidate) {
|
||||
if ($this->access->conflict($candidate, $record)) {
|
||||
continue;
|
||||
}
|
||||
foreach (['validator' => 'validators', 'publisher' => 'publishers'] as $role => $list) {
|
||||
if ($this->access->scoped($candidate, $role, $record->organization_id, $record->opportunity_category) && $this->access->operational($candidate, $role === 'validator' ? 'validate' : 'publish', $record->id)) {
|
||||
if ($role === 'publisher' && (int) ($record->workflow_context['approval']['actor_id'] ?? 0) === $candidate->id) {
|
||||
continue;
|
||||
}
|
||||
$result[$list][] = ['id' => $candidate->id, 'name' => $candidate->name, 'technical' => $this->responsibility($candidate, $record, 'technical_reviewer'), 'legal' => $this->responsibility($candidate, $record, 'legal_reviewer')];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function submissionGaps(Opportunity $record): array
|
||||
{
|
||||
try {
|
||||
$this->contract->validateSubmission($record);
|
||||
|
||||
return [];
|
||||
} catch (ValidationException $error) {
|
||||
return array_keys($error->errors());
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function transition(User $actor, int $id, array $input): Opportunity
|
||||
{
|
||||
$record = Opportunity::withTrashed()->findOrFail($id);
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
abort_unless($record->owner_user_id !== null && ! $record->trashed(), 409, 'Workflow apenas para registos explicitamente sujeitos à política.');
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64',
|
||||
'action' => 'required|in:submit,start_review,request_correction,pending_opinion,respond_opinion,reject,approve,publish,suspend,archive,request_archive,appeal,request_revision,review_gate,assign_review,assign_publication,appeal_uphold,appeal_reopen',
|
||||
'reason' => 'required|string|min:20|max:1000', 'correction_items' => 'sometimes|array', 'correction_items.*' => 'required|string|max:250',
|
||||
'gate' => 'sometimes|string|max:80', 'gate_decision' => 'sometimes|in:approved,rejected', 'assignee_user_id' => 'sometimes|integer|min:1',
|
||||
'opinion_id' => 'sometimes|uuid', 'recipient_user_id' => 'sometimes|integer|min:1',
|
||||
'evidence_document_ids' => 'sometimes|array', 'evidence_document_ids.*' => 'uuid', 'due_at' => 'prohibited',
|
||||
'confirm_publication' => 'sometimes|boolean', 'preview_hash' => 'sometimes|string|size:64',
|
||||
])->validate();
|
||||
$action = $data['action'];
|
||||
$this->authorizeAction($actor, $record, $action);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $action) {
|
||||
$record = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless(hash_equals($this->management->etag($record), $data['etag']), 409, 'Versão alterada.');
|
||||
$this->authorizeAction($actor, $record, $action);
|
||||
$context = $record->workflow_context ?? [];
|
||||
$state = $this->access->state($record);
|
||||
$before = ['status' => $state, 'publication_status' => $record->status, 'version' => $record->management_version];
|
||||
$from = match ($action) {
|
||||
'submit' => ['draft', 'needs_information'], 'start_review' => ['submitted'],
|
||||
'request_correction', 'pending_opinion', 'respond_opinion', 'reject', 'approve', 'review_gate', 'assign_review' => ['submitted', 'in_review', 'information_pending'],
|
||||
'publish' => ['approved'], 'suspend' => [$state],
|
||||
'assign_publication' => ['approved'],
|
||||
'request_revision' => ['approved', 'published', 'suspended'],
|
||||
'archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'rejected', 'published', 'suspended'],
|
||||
'request_archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'published', 'suspended'],
|
||||
'appeal', 'appeal_uphold', 'appeal_reopen' => ['rejected'],
|
||||
default => [],
|
||||
};
|
||||
abort_unless(in_array($state, $from, true), 409, 'Transição incompatível com o estado atual.');
|
||||
$decision = ['actor_id' => $actor->id, 'action' => $action, 'reason' => $data['reason'], 'at' => now()->toIso8601String(),
|
||||
'content_revision' => $context['content_revision'] ?? 1];
|
||||
$next = $state;
|
||||
$snapshot = [];
|
||||
if (in_array($action, ['submit', 'review_gate', 'pending_opinion', 'respond_opinion', 'approve', 'publish'], true)) {
|
||||
$snapshot = $this->contract->validateSubmission($record);
|
||||
if ($action !== 'submit') {
|
||||
abort_unless(hash_equals($context['submission']['hash'] ?? '', $snapshot['hash']), 409, 'Conteúdo ou recursos mudaram desde a submissão. Exige nova submissão/revisão.');
|
||||
}
|
||||
}
|
||||
if ($action === 'submit') {
|
||||
foreach ($context['opinions'] ?? [] as $opinionId => $opinion) {
|
||||
if (($opinion['status'] ?? '') === 'pending') {
|
||||
$context['opinions'][$opinionId]['status'] = 'superseded';
|
||||
$this->tasks->complete($opinion['task_id'] ?? null, 'Nova versão submetida; parecer anterior preservado.');
|
||||
}
|
||||
}
|
||||
$context['submission'] = [...$snapshot, ...$decision];
|
||||
$context['sla'] = ['policy_version' => null, 'due_at' => null, 'status' => 'unconfigured'];
|
||||
unset($context['approval'], $context['reviews'], $context['assignment'],$context['publication_assignment']);
|
||||
$record->first_submitted_at ??= now()->toIso8601String();
|
||||
$record->management_closed_once = true;
|
||||
$record->workflow_context = $context;
|
||||
$context['review_task_id'] = $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$this->tasks->complete($context['correction_task_id'] ?? null, $data['reason']);
|
||||
$next = 'submitted';
|
||||
} elseif ($action === 'start_review' || $action === 'assign_review') {
|
||||
$subject = $action === 'start_review' ? $actor : User::whereKey($data['assignee_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($subject, 'validate', $record->id) && ! $this->access->conflict($subject, $record)
|
||||
&& $subject->two_factor_confirmed_at !== null, 403, 'Responsável requer papel válido, MFA configurado e independência.');
|
||||
$context['review_task_id'] ??= $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$this->tasks->assign($record, $context['review_task_id'], $subject);
|
||||
$context['assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
|
||||
$next = 'in_review';
|
||||
} elseif ($action === 'review_gate') {
|
||||
$gate = $data['gate'] ?? '';
|
||||
abort_unless(in_array($gate, $this->contract->gates($record), true), 422, 'Gate não aplicável.');
|
||||
$legal = preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1;
|
||||
abort_unless($this->responsibility($actor, $record, $legal ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Responsabilidade de revisão necessária.');
|
||||
$documents = $data['evidence_document_ids'] ?? [];
|
||||
abort_unless($documents !== [] && array_diff($documents, array_keys($snapshot['resources']['documents'] ?? [])) === [], 422, 'Selecione evidência documental desta versão.');
|
||||
abort_unless(isset($data['gate_decision']), 422, 'Indique decisão fundamentada do gate.');
|
||||
$context['reviews'][$gate] = [...$decision, 'decision' => $data['gate_decision'], 'hash' => $snapshot['hash'], 'evidence_document_ids' => $documents];
|
||||
$next = 'in_review';
|
||||
} elseif ($action === 'approve') {
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0, 422, 'Parecer da versão atual ainda pendente.');
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['response']['decision'] ?? '') === 'rejected')) > 0, 422, 'Parecer desfavorável exige correção e nova versão.');
|
||||
foreach ($this->contract->gates($record) as $gate) {
|
||||
$review = $context['reviews'][$gate] ?? [];
|
||||
abort_unless(($review['decision'] ?? null) === 'approved' && ($review['hash'] ?? '') === $snapshot['hash'], 422, 'Gate '.$gate.' pendente, rejeitado ou de outra versão.');
|
||||
$reviewer = User::whereKey($review['actor_id'])->firstOrFail();
|
||||
abort_unless($this->access->scoped($reviewer, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($reviewer, $record) && $this->access->operational($reviewer, 'validate', $record->id)
|
||||
&& $this->responsibility($reviewer, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Revisor revogado, sem responsabilidade ou com conflito.');
|
||||
}
|
||||
$context['approval'] = [...$decision, 'hash' => $snapshot['hash'], 'gates' => $context['reviews'] ?? []];
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$record->workflow_context = $context;
|
||||
$context['publication_task_id'] = $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
$next = 'approved';
|
||||
} elseif ($action === 'assign_publication') {
|
||||
$subject = User::whereKey($data['assignee_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'publisher', $record->organization_id, $record->opportunity_category) && $this->access->operational($subject, 'publish', $record->id) && ! $this->access->conflict($subject, $record) && $subject->two_factor_confirmed_at !== null && (int) ($context['approval']['actor_id'] ?? 0) !== $subject->id, 403, 'Publicador exige MFA, âmbito e independência da aprovação.');
|
||||
$context['publication_task_id'] ??= $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
$this->tasks->assign($record, $context['publication_task_id'], $subject);
|
||||
$context['publication_assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
|
||||
} elseif ($action === 'publish') {
|
||||
Validator::make($data, ['confirm_publication' => 'required|accepted', 'preview_hash' => 'required|string|size:64'])->validate();
|
||||
$this->contract->validatePublication($snapshot);
|
||||
abort_unless(hash_equals($snapshot['hash'], $data['preview_hash']), 409, 'Pré-visualização diferente da versão aprovada.');
|
||||
abort_unless(($context['approval']['hash'] ?? '') === $snapshot['hash'], 409, 'Aprovação não corresponde ao conteúdo atual.');
|
||||
foreach ($this->contract->gates($record) as $gate) {
|
||||
$review = $context['approval']['gates'][$gate] ?? [];
|
||||
abort_unless(($review['decision'] ?? null) === 'approved' && ($review['hash'] ?? '') === $snapshot['hash'], 422, 'Revisão aprovada desta versão necessária.');
|
||||
$reviewer = User::whereKey($review['actor_id'])->firstOrFail();
|
||||
abort_unless($this->access->scoped($reviewer, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($reviewer, $record) && $this->access->operational($reviewer, 'validate', $record->id)
|
||||
&& $this->responsibility($reviewer, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Revisor revogado, sem responsabilidade ou com conflito na publicação.');
|
||||
}
|
||||
$approver = User::whereKey($context['approval']['actor_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($approver, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($approver, $record) && $this->access->operational($approver, 'validate', $record->id), 403, 'Aprovador revogado ou com conflito.');
|
||||
$p = $snapshot['payload'];
|
||||
if (! empty($p['review_due_date'])) {
|
||||
abort_unless($p['review_due_date'] > today()->toDateString(), 422, 'Data de revisão deve ser futura.');
|
||||
}
|
||||
if (isset($p['business_transaction'])) {
|
||||
abort_unless(in_array($p['business_transaction']['due_diligence_status'], ['data_room_ready', 'in_progress', 'completed', 'exceptions'], true), 422, 'Data room mínimo não preparado.');
|
||||
}
|
||||
if (isset($context['publication'])) {
|
||||
$context['publication_history'][] = $context['publication'];
|
||||
}
|
||||
$context['publication'] = [...$decision, 'hash' => $snapshot['hash'], 'visibility' => $p['visibility'],
|
||||
'public_fields' => ['title', 'summary', 'description', 'sector_id', 'province', 'district']];
|
||||
// Minimal public projection; contacts, valuations, evidence and originals remain private.
|
||||
$projection = $this->contract->publicProjection($p);
|
||||
$record->title = $projection['title'];
|
||||
$record->summary = $projection['summary'];
|
||||
$record->description = $projection['description'];
|
||||
$record->sector_id = $p['sector_id'];
|
||||
$locations = array_values(array_filter($snapshot['resources']['locations'], fn ($location) => $location['payload']['is_primary'] ?? false));
|
||||
$location = $locations[0]; // The contract requires exactly one primary location.
|
||||
$path = app(InvestmentGeography::class)->selection($location['payload'], true);
|
||||
$last = array_key_last($path);
|
||||
abort_unless($last !== null, 422, 'Localização principal sem hierarquia.');
|
||||
$record->primary_territory_id = $path[$last]->id;
|
||||
$record->province = $path[0]->name;
|
||||
$record->district = $path[1]->name;
|
||||
$record->geography_scope = $p['geographic_scope'] === 'national' ? 'national' : 'specific';
|
||||
$record->published_at = now();
|
||||
$record->status = 'published';
|
||||
$next = 'published';
|
||||
$this->tasks->complete($context['publication_task_id'] ?? null, $data['reason']);
|
||||
} elseif ($action === 'pending_opinion') {
|
||||
$gate = $data['gate'] ?? '';
|
||||
abort_unless(in_array($gate, $this->contract->gates($record), true), 422, 'Indique a revisão aplicável ao parecer.');
|
||||
$subject = User::whereKey($data['recipient_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($subject, 'validate', $record->id) && ! $this->access->conflict($subject, $record) && $subject->two_factor_confirmed_at !== null
|
||||
&& $this->responsibility($subject, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Destinatário exige responsabilidade, MFA e independência.');
|
||||
abort_if($subject->id === $actor->id, 422, 'O parecer deve ser solicitado a outro revisor.');
|
||||
$opinionId = (string) Str::uuid();
|
||||
$taskId = $this->tasks->ensure($record, 'opportunity_opinion:'.$opinionId, 'Parecer da oportunidade '.$record->reference);
|
||||
$this->tasks->assign($record, $taskId, $subject);
|
||||
$context['opinions'][$opinionId] = [...$decision, 'id' => $opinionId, 'recipient_id' => $subject->id, 'gate' => $gate, 'status' => 'pending', 'hash' => $snapshot['hash'], 'task_id' => $taskId];
|
||||
$next = 'information_pending';
|
||||
} elseif ($action === 'respond_opinion') {
|
||||
$opinionId = $data['opinion_id'] ?? '';
|
||||
$opinion = $context['opinions'][$opinionId] ?? [];
|
||||
abort_unless(($opinion['recipient_id'] ?? 0) === $actor->id, 403, 'Parecer atribuído a outro revisor.');
|
||||
abort_unless($this->responsibility($actor, $record, preg_match('/legal|registry|authority|confidentiality|license/', $opinion['gate'] ?? '') === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Responsabilidade do parecer revogada.');
|
||||
abort_unless(($opinion['status'] ?? '') === 'pending' && ($opinion['hash'] ?? '') === $snapshot['hash'], 409, 'Parecer encerrado ou de outra versão.');
|
||||
$documents = $data['evidence_document_ids'] ?? [];
|
||||
abort_unless(isset($data['gate_decision']) && $documents !== [] && array_diff($documents, array_keys($snapshot['resources']['documents'] ?? [])) === [], 422, 'Resposta exige decisão e documentos desta versão.');
|
||||
$context['opinions'][$opinionId]['status'] = 'answered';
|
||||
$context['opinions'][$opinionId]['response'] = [...$decision, 'decision' => $data['gate_decision'], 'evidence_document_ids' => $documents];
|
||||
$this->tasks->complete($opinion['task_id'], $data['reason']);
|
||||
$next = count(array_filter($context['opinions'], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0 ? 'information_pending' : 'in_review';
|
||||
} elseif ($action === 'request_correction') {
|
||||
abort_unless($data['correction_items'] ?? [], 422, 'Indique campos e documentos a corrigir.');
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$context['correction_items'] = $data['correction_items'];
|
||||
$context['correction_cycles'] = ($context['correction_cycles'] ?? 0) + 1;
|
||||
$record->workflow_context = $context;
|
||||
$context['correction_task_id'] = $this->tasks->ensure($record, 'opportunity_correction', 'Correções da oportunidade '.$record->reference);
|
||||
$next = 'needs_information';
|
||||
} elseif ($action === 'request_revision' || $action === 'appeal_reopen') {
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$this->tasks->complete($context['publication_task_id'] ?? null, $data['reason']);
|
||||
$context['decision_history'][] = ['approval' => $context['approval'] ?? null, 'reviews' => $context['reviews'] ?? null, 'submission' => $context['submission'] ?? null];
|
||||
unset($context['approval'], $context['reviews']);
|
||||
$next = 'needs_information';
|
||||
} elseif ($action === 'request_archive') {
|
||||
$context['request_archive'] = $decision;
|
||||
} elseif ($action === 'appeal') {
|
||||
abort_if($context['appeal']['pending'] ?? false, 409, 'Recurso já pendente.');
|
||||
$context['appeal'] = [...$decision, 'pending' => true];
|
||||
$context['appeal_task_id'] = $this->tasks->ensure($record, 'opportunity_appeal', 'Recurso da oportunidade '.$record->reference);
|
||||
} elseif ($action === 'appeal_uphold') {
|
||||
$next = 'rejected';
|
||||
} else {
|
||||
$next = match ($action) {
|
||||
'reject' => 'rejected', 'suspend' => 'suspended', 'archive' => 'archived'
|
||||
};
|
||||
if ($action === 'reject') {
|
||||
$context['rejection'] = $decision;
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
if (in_array($action, ['suspend', 'archive'], true)) {
|
||||
$record->status = $next;
|
||||
foreach (['review_task_id', 'correction_task_id', 'publication_task_id', 'appeal_task_id'] as $task) {
|
||||
$this->tasks->complete($context[$task] ?? null, $data['reason']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (in_array($action, ['appeal_uphold', 'appeal_reopen'], true)) {
|
||||
$context['appeal']['pending'] = false;
|
||||
$context['appeal']['decision'] = $decision;
|
||||
$this->tasks->complete($context['appeal_task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
if (in_array($action, ['request_correction', 'reject'], true)) {
|
||||
unset($context['approval'], $context['reviews']);
|
||||
}
|
||||
if (in_array($action, ['request_correction', 'reject', 'suspend', 'archive', 'request_revision', 'appeal_reopen'], true)) {
|
||||
foreach ($context['opinions'] ?? [] as $opinionId => $opinion) {
|
||||
if (($opinion['status'] ?? '') === 'pending') {
|
||||
$context['opinions'][$opinionId]['status'] = 'superseded';
|
||||
$this->tasks->complete($opinion['task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$context['working_state'] = $next;
|
||||
$context['last_decision'] = $decision;
|
||||
$context['events'][] = [...$decision, 'from' => $state, 'to' => $next];
|
||||
if ($record->status !== 'published' || in_array($action, ['suspend', 'archive'], true)) {
|
||||
$record->status = $next;
|
||||
}
|
||||
$record->management_version++;
|
||||
$record->workflow_context = $context;
|
||||
$record->save();
|
||||
$this->access->audit($actor, 'workflow_'.$action, ['record_id' => $record->id, 'before' => $before,
|
||||
'after' => ['status' => $next, 'publication_status' => $record->status, 'version' => $record->management_version], 'reason' => $data['reason']]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
private function responsibility(User $actor, Opportunity $record, string $name): bool
|
||||
{
|
||||
foreach ($this->access->grants($actor, $name === 'publication_coordinator' ? 'publisher' : 'validator') as $grant) {
|
||||
if (($grant->organization_id === null || $grant->organization_id === $record->organization_id)
|
||||
&& in_array($record->opportunity_category, json_decode($grant->opportunity_types, true), true)
|
||||
&& in_array($name, json_decode($grant->responsibilities, true), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function authorizeAction(User $actor, Opportunity $record, string $action): void
|
||||
{
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
$promoter = $this->access->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id);
|
||||
if (in_array($action, ['submit', 'request_archive', 'appeal', 'request_revision'], true)) {
|
||||
abort_unless($promoter && $this->access->operational($actor, 'edit', $record->id), 403);
|
||||
} else {
|
||||
$role = in_array($action, ['publish', 'assign_publication', 'suspend', 'archive'], true) ? 'publisher' : 'validator';
|
||||
$operation = $role === 'publisher' ? (in_array($action, ['publish', 'assign_publication'], true) ? 'publish' : 'archive') : 'validate';
|
||||
abort_unless($this->access->scoped($actor, $role, $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->mfa($actor) && $this->access->operational($actor, $operation, $record->id) && ! $this->access->conflict($actor, $record), 403, 'Papel, MFA e independência necessários.');
|
||||
if ($action === 'publish') {
|
||||
abort_if((int) ($record->workflow_context['approval']['actor_id'] ?? 0) === $actor->id, 403, 'O aprovador não publica a mesma versão.');
|
||||
abort_if(isset($record->workflow_context['publication_assignment']['assignee_user_id']) && (int) $record->workflow_context['publication_assignment']['assignee_user_id'] !== $actor->id, 403, 'Publicação atribuída a outro Publicador; requer reatribuição explícita.');
|
||||
}
|
||||
if ($action === 'assign_publication') {
|
||||
abort_unless($this->responsibility($actor, $record, 'publication_coordinator'), 403);
|
||||
}
|
||||
if ($action === 'assign_review') {
|
||||
abort_unless($this->responsibility($actor, $record, 'validation_coordinator'), 403);
|
||||
}
|
||||
if (in_array($action, ['start_review', 'review_gate', 'request_correction', 'pending_opinion', 'reject', 'approve'], true)
|
||||
&& isset($record->workflow_context['assignment']['assignee_user_id'])) {
|
||||
abort_unless((int) $record->workflow_context['assignment']['assignee_user_id'] === $actor->id, 403, 'Tarefa atribuída a outro Validador; o coordenador deve registar a reatribuição.');
|
||||
}
|
||||
if (in_array($action, ['appeal_uphold', 'appeal_reopen'], true)) {
|
||||
abort_unless($this->responsibility($actor, $record, 'appeal_reviewer') && ($record->workflow_context['appeal']['pending'] ?? false)
|
||||
&& (int) ($record->workflow_context['rejection']['actor_id'] ?? 0) !== $actor->id, 403, 'Recurso exige instância independente da rejeição.');
|
||||
}
|
||||
if ($action === 'suspend') {
|
||||
abort_unless($record->status === 'published', 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** First draft adapter, not a complete contract validator or a publication gate. */
|
||||
class OpportunityRealEstateDraft
|
||||
{
|
||||
/**
|
||||
* @param array<string,mixed> $values
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function validate(array $values): array
|
||||
{
|
||||
abort_unless(config('portal.opportunity_specialized_drafts_enabled'), 422, 'Campos especializados ainda não disponibilizados neste ambiente.');
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
if ($bytes === false) {
|
||||
throw new \RuntimeException('Normative opportunity schema unavailable.');
|
||||
}
|
||||
$schema = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
$properties = $schema['$defs']['realEstatePatch']['properties'];
|
||||
if ($values === [] || array_diff(array_keys($values), array_keys($properties))) {
|
||||
throw ValidationException::withMessages(['real_estate' => 'Indique campos do contrato imobiliário; campos desconhecidos ou de resposta não são graváveis.']);
|
||||
}
|
||||
$errors = [];
|
||||
foreach ($values as $key => $value) {
|
||||
$this->check($value, $properties[$key], 'real_estate.'.$key, $errors);
|
||||
}
|
||||
if ($errors) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $schema
|
||||
* @param array<string,string> $errors
|
||||
*/
|
||||
private function check(mixed $value, array $schema, string $path, array &$errors): void
|
||||
{
|
||||
$types = (array) ($schema['type'] ?? []);
|
||||
$valid = $types === [] || array_filter($types, fn ($type) => match ($type) {
|
||||
'null' => $value === null,
|
||||
'string' => is_string($value),
|
||||
'integer' => is_int($value),
|
||||
'number' => is_int($value) || is_float($value),
|
||||
'boolean' => is_bool($value),
|
||||
'array' => is_array($value) && array_is_list($value),
|
||||
// Laravel request arrays represent JSON objects, including empty ones.
|
||||
'object' => is_array($value) && ($value === [] || ! array_is_list($value)),
|
||||
default => false,
|
||||
}) !== [];
|
||||
if (! $valid || (isset($schema['enum']) && ! in_array($value, $schema['enum'], true))) {
|
||||
$errors[$path] = 'Tipo ou valor fora do contrato imobiliário §26.';
|
||||
|
||||
return;
|
||||
}
|
||||
if ($value === null) {
|
||||
return;
|
||||
}
|
||||
$rules = [];
|
||||
foreach (['minLength' => 'min', 'maxLength' => 'max', 'minItems' => 'min'] as $keyword => $rule) {
|
||||
if (isset($schema[$keyword])) {
|
||||
$rules[] = $rule.':'.$schema[$keyword];
|
||||
}
|
||||
}
|
||||
if (in_array('number', $types, true) || in_array('integer', $types, true)) {
|
||||
$rules[] = 'numeric';
|
||||
foreach (['minimum' => 'min', 'maximum' => 'max', 'exclusiveMinimum' => 'gt'] as $keyword => $rule) {
|
||||
if (isset($schema[$keyword])) {
|
||||
$rules[] = $rule.':'.$schema[$keyword];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (($schema['format'] ?? null) === 'uuid') {
|
||||
$rules[] = 'uuid';
|
||||
}
|
||||
if ($rules && Validator::make(['value' => $value], ['value' => $rules])->fails()) {
|
||||
$errors[$path] = 'Valor fora dos limites/formato do contrato imobiliário §26.';
|
||||
}
|
||||
if (isset($schema['items']) && is_array($value)) {
|
||||
foreach ($value as $index => $item) {
|
||||
$this->check($item, $schema['items'], $path.'.'.$index, $errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,10 +26,16 @@ class OpportunityResourceInstallation
|
||||
$files = [...$files, app_path('Services/ExistingBusinessIntake.php'), resource_path('js/pages/land-assistance/case.tsx')];
|
||||
$files = [...$files, resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx')];
|
||||
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Console/Commands/ImportDocumentBatch.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), config_path('geometry-correspondences.php'), app_path('Http/Controllers/PartnershipExchangeController.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
|
||||
|
||||
$files = [...$files, app_path('Services/OpportunityRealEstateDraft.php'), app_path('Http/Middleware/HandleInertiaRequests.php'), config_path('portal.php'),
|
||||
resource_path('data/investmoz-opportunity-modular.schema.json'), resource_path('js/pages/dashboard.tsx'), resource_path('js/components/app-sidebar.tsx'), resource_path('js/types/opportunity-management.ts'), base_path('vite.config.ts')];
|
||||
|
||||
$files = [...$files, resource_path('js/lib/portal-navigation.ts'), resource_path('js/components/portal-grouped-menu.tsx')];
|
||||
|
||||
$files = [...$files, ...PortalProfileAccess::fingerprintFiles()];
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ class OpportunityResources
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, int $opportunityId, string $kind, array $input, ?UploadedFile $file = null, ?string $id = null): \stdClass
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', Opportunity::withTrashed()->findOrFail($opportunityId));
|
||||
abort_unless($this->installed(), 503);
|
||||
$table = $this->table($kind);
|
||||
$data = Validator::make($input, [
|
||||
@@ -69,6 +69,7 @@ class OpportunityResources
|
||||
try {
|
||||
$result = DB::transaction(function () use ($actor, $opportunityId, $kind, $table, $data, $payload, $file, $id, $stored, $documentId) {
|
||||
$opportunity = $this->lock($opportunityId, $data['etag']);
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$record = $id ? DB::table($table)->where('id', $id)->where('opportunity_id', $opportunityId)->lockForUpdate()->first() : null;
|
||||
abort_if($id && ! $record, 404);
|
||||
abort_if($record && ($record->deleted_at || (int) $record->version !== (int) $data['version']), 409, 'Recurso alterado ou eliminado; preserve o preenchimento e reveja a versão.');
|
||||
@@ -147,11 +148,12 @@ class OpportunityResources
|
||||
/** @param array<string,mixed> $input */
|
||||
public function lifecycle(User $actor, int $opportunityId, string $kind, string $id, array $input): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', Opportunity::withTrashed()->findOrFail($opportunityId));
|
||||
abort_unless($this->installed(), 503);
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'version' => 'required|integer|min:1', 'action' => 'required|in:delete,restore', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $opportunityId, $kind, $id, $data) {
|
||||
$opportunity = $this->lock($opportunityId, $data['etag']);
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$table = $this->table($kind);
|
||||
$record = DB::table($table)->where('id', $id)->where('opportunity_id', $opportunityId)->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
@@ -210,6 +212,7 @@ class OpportunityResources
|
||||
{
|
||||
$rules = ['title' => 'nullable|string|max:120', 'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'visibility' => 'nullable|in:internal,authenticated,public'];
|
||||
if ($kind === 'locations') {
|
||||
$rules += ['country_code' => ['nullable', app(CountryCatalogue::class)->rule()]];
|
||||
$rules += ['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid', 'role' => 'nullable|in:headquarters,production,raw_material,storage,logistics,market,support,other', 'role_description' => 'nullable|string|max:1000', 'operational_unit' => 'nullable|string|max:120', 'is_primary' => 'nullable|boolean', 'address' => 'nullable|string|max:300', 'geometry' => 'nullable|array', 'area_value' => 'nullable|numeric|gt:0', 'area_unit' => 'nullable|in:sqm,ha,sqkm', 'allocation_percentage' => 'nullable|numeric|between:0,100', 'territorial_purpose' => 'nullable|in:implementation,context,impact,coverage', 'multi_district_rationale' => 'nullable|string|max:1000'];
|
||||
} elseif ($kind === 'images') {
|
||||
$rules += ['role' => 'nullable|in:cover,gallery,location,asset,product,plan,rendering,evidence,other', 'role_description' => 'nullable|string|max:1000', 'is_cover' => 'nullable|boolean', 'caption' => 'nullable|string|max:300', 'alt_text' => 'nullable|string|max:250', 'location_id' => ['nullable', 'uuid', Rule::exists('opportunity_location_drafts', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'captured_at' => 'nullable|date_format:Y-m-d|before_or_equal:today', 'author_source' => 'nullable|string|max:150', 'rights_status' => 'nullable|in:owned,licensed,authorized,public_domain', 'rights_document_id' => ['nullable', 'uuid', Rule::exists('opportunity_documents', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'rights_valid_until' => 'nullable|date_format:Y-m-d', 'sort_order' => 'nullable|integer|min:0'];
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Existing CRM tasks, explicit portal binding; no invented CRM opportunity or assignee. */
|
||||
class OpportunityWorkflowTasks
|
||||
{
|
||||
public function ensure(Opportunity $record, string $kind, string $title): string
|
||||
{
|
||||
$key = 'portal-opportunity:'.$record->id.':'.$kind.':'.($record->workflow_context['content_revision'] ?? 1);
|
||||
$existing = DB::table('tasks')->where('source_system', 'opportunity-workflow')->where('external_id', $key)->first();
|
||||
if ($existing) {
|
||||
return $existing->id;
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('tasks')->insert(['id' => $id, 'source_system' => 'opportunity-workflow', 'external_id' => $key,
|
||||
'correlation_id' => $record->management_creation_key, 'task_type' => $kind, 'title' => $title,
|
||||
'status' => 'open', 'due_at' => null, 'assignee_user_id' => null, 'data_classification' => 'restricted']);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function assign(Opportunity $record, string $taskId, User $subject): void
|
||||
{
|
||||
abort_unless(DB::table('tasks')->where('id', $taskId)->where('source_system', 'opportunity-workflow')
|
||||
->where('external_id', 'like', 'portal-opportunity:'.$record->id.':%')->whereIn('status', ['open', 'in_progress'])->exists(), 409, 'Tarefa não pertence à versão aberta.');
|
||||
DB::table('tasks')->where('id', $taskId)->update(['assignee_user_id' => $subject->id, 'status' => 'in_progress', 'version_no' => DB::raw('version_no+1')]);
|
||||
}
|
||||
|
||||
public function complete(?string $taskId, string $outcome): void
|
||||
{
|
||||
if ($taskId) {
|
||||
DB::table('tasks')->where('id', $taskId)->where('source_system', 'opportunity-workflow')->whereIn('status', ['open', 'in_progress'])
|
||||
->update(['status' => 'done', 'outcome' => $outcome, 'completed_at' => now(), 'version_no' => DB::raw('version_no+1')]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<\stdClass> */
|
||||
public function listing(Opportunity $record): array
|
||||
{
|
||||
return array_values(DB::table('tasks')->where('source_system', 'opportunity-workflow')->where('external_id', 'like', 'portal-opportunity:'.$record->id.':%')
|
||||
->get(['id', 'task_type', 'status', 'title', 'assignee_user_id', 'due_at', 'completed_at', 'outcome'])->all());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class PortalProfileAccess
|
||||
{
|
||||
public const VERSION = 'profiles-v1-20261010';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function fingerprintFiles(): array
|
||||
{
|
||||
return [__FILE__, app_path('Models/User.php'), app_path('Models/Opportunity.php'), config_path('portal.php'), base_path('routes/web.php'),
|
||||
app_path('Http/Middleware/HandleInertiaRequests.php'), app_path('Services/OpportunityManagement.php'),
|
||||
app_path('Services/OpportunityResources.php'), app_path('Services/OpportunityImageProcessor.php'),
|
||||
app_path('Services/PortalProfileAdministration.php'), app_path('Services/PortalSuperusers.php'),
|
||||
app_path('Services/OpportunityProfileWorkflow.php'), app_path('Http/Controllers/PortalProfileController.php'), app_path('Http/Controllers/DashboardController.php'),
|
||||
app_path('Http/Controllers/OpportunityManagementController.php'),
|
||||
app_path('Services/OpportunityCanonicalContract.php'), app_path('Services/OpportunityCategoryFields.php'), app_path('Services/OpportunityWorkflowTasks.php'), base_path('composer.json'), base_path('composer.lock'),
|
||||
resource_path('data/investmoz-opportunity-modular.schema.json'), resource_path('js/components/opportunity-canonical-fields.tsx'), resource_path('js/components/opportunity-parcel-geometry.tsx'),
|
||||
app_path('Http/Controllers/OpportunityResourceController.php'),
|
||||
app_path('Http/Controllers/InvestmentTerritoryController.php'),
|
||||
app_path('Http/Middleware/PortalProfileSession.php'), app_path('Http/Middleware/ProtectProfileOpportunity.php'),
|
||||
app_path('Http/Middleware/ProtectPrivilegedIdentity.php'), app_path('Http/Middleware/EnsurePortalProfiles.php'),
|
||||
app_path('Http/Middleware/AuditProfileDecision.php'), app_path('Providers/AppServiceProvider.php'),
|
||||
database_path('migrations/2026_10_10_040000_create_portal_profile_authorization.php'), base_path('bootstrap/app.php'),
|
||||
resource_path('js/pages/profiles/request.tsx'), resource_path('js/pages/profiles/administration.tsx'), resource_path('js/pages/profiles/audit.tsx'),
|
||||
resource_path('js/components/profile-navigation.tsx'), resource_path('js/components/opportunity-profile-actions.tsx'),
|
||||
resource_path('js/pages/management/opportunities.tsx'), resource_path('js/pages/management/opportunity-draft.tsx'),
|
||||
resource_path('js/types/profile-access.ts'), resource_path('js/lib/profile-json.ts'), resource_path('js/pages/management/shared.tsx'),
|
||||
app_path('Services/PortalProfileInstallation.php'), app_path('Http/Controllers/PortalProfileInstallationController.php'), config_path('portal_profiles.php'), resource_path('js/pages/profiles/installation.tsx')];
|
||||
}
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return config('portal.profile_access_enabled') && Schema::hasTable('portal_role_assignments')
|
||||
&& Schema::hasTable('portal_superuser_pair') && Schema::hasTable('portal_profile_requests')
|
||||
&& Schema::hasTable('portal_security_approvals') && Schema::hasColumn('users', 'portal_access_revision')
|
||||
&& Schema::hasColumn('opportunities', 'workflow_context') && Schema::hasColumn('opportunities', 'owner_user_id')
|
||||
&& Schema::hasColumn('opportunities', 'organization_id');
|
||||
}
|
||||
|
||||
/** @return list<\stdClass> */
|
||||
public function grants(User $actor, ?string $role = null): array
|
||||
{
|
||||
if (! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(DB::table('portal_role_assignments')->where('user_id', $actor->id)->whereNull('revoked_at')->where('starts_at', '<=', now())
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->when($role, fn ($q) => $q->where('role', $role))->get()->all());
|
||||
}
|
||||
|
||||
public function has(User $actor, string $role): bool
|
||||
{
|
||||
return $role === 'superuser' ? $this->superuser($actor) : $this->grants($actor, $role) !== [];
|
||||
}
|
||||
|
||||
public function superuser(User $actor): bool
|
||||
{
|
||||
return $this->available() && $actor->hasVerifiedEmail() && DB::table('portal_superuser_pair')->where('id', 1)
|
||||
->where(fn ($q) => $q->where('first_user_id', $actor->id)->orWhere('second_user_id', $actor->id))->exists();
|
||||
}
|
||||
|
||||
public function represents(User $actor, ?string $organization): bool
|
||||
{
|
||||
return $organization === null || DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')
|
||||
->where('m.user_id', $actor->id)->where('m.organization_id', $organization)
|
||||
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->exists();
|
||||
}
|
||||
|
||||
public function mfa(User $actor): bool
|
||||
{
|
||||
// Enrollment alone is insufficient: Fortify must have completed MFA in this session.
|
||||
return $actor->two_factor_confirmed_at !== null && $actor->two_factor_secret !== null
|
||||
&& session('login.id') === null && session('portal.mfa_actor') === $actor->id
|
||||
&& (int) session('portal.mfa_at', 0) >= time() - 900;
|
||||
}
|
||||
|
||||
public function scoped(User $actor, string $role, ?string $organization, string $type): bool
|
||||
{
|
||||
foreach ($this->grants($actor, $role) as $grant) {
|
||||
if (($grant->organization_id === $organization || ($role !== 'promoter' && $grant->organization_id === null))
|
||||
&& in_array($type, json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR), true)) {
|
||||
return $role !== 'promoter' || $this->represents($actor, $organization);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function operational(User $actor, string $action, ?int $recordId = null): bool
|
||||
{
|
||||
if ($this->has($actor, 'auditor')) {
|
||||
return false;
|
||||
}
|
||||
if (! $this->superuser($actor)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return DB::table('portal_security_approvals')->where('kind', 'elevation')->where('subject_user_id', $actor->id)
|
||||
->whereNotNull('approved_by')->whereNull('consumed_at')->where('expires_at', '>', now())
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('portal_superuser_pair')
|
||||
->where(fn ($holders) => $holders->whereColumn('first_user_id', 'portal_security_approvals.approved_by')->orWhereColumn('second_user_id', 'portal_security_approvals.approved_by')))
|
||||
->where('scope->action', $action)->where('scope->record_id', $recordId)->exists();
|
||||
}
|
||||
|
||||
public function canCreate(User $actor, ?string $organization, string $type): bool
|
||||
{
|
||||
return $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && $this->operational($actor, 'create');
|
||||
}
|
||||
|
||||
public function legacyWriteAllowed(User $actor): bool
|
||||
{
|
||||
// A deliberate v1 assignment cannot use the old allowlist to bypass its scope.
|
||||
if (! $actor->can('manage-portal')) {
|
||||
return false;
|
||||
}
|
||||
if (! Schema::hasTable('portal_role_assignments')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Revocation/expiry must not silently restore an older, wider privilege.
|
||||
return ! DB::table('portal_role_assignments')->where('user_id', $actor->id)->exists()
|
||||
&& ! DB::table('portal_superuser_pair')->where(fn ($q) => $q->where('first_user_id', $actor->id)->orWhere('second_user_id', $actor->id))->exists()
|
||||
&& ! DB::table('portal_security_approvals')->where('kind', 'replacement')->whereNotNull('consumed_at')->where('scope->old_user_id', $actor->id)->exists();
|
||||
}
|
||||
|
||||
public function canView(User $actor, Opportunity $record): bool
|
||||
{
|
||||
if ($record->owner_user_id === null) {
|
||||
return $actor->can('manage-portal');
|
||||
}
|
||||
if (! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
if ($this->has($actor, 'auditor') || $this->superuser($actor)) {
|
||||
return true;
|
||||
}
|
||||
$personal = $record->organization_id !== null || (int) $record->owner_user_id === $actor->id;
|
||||
|
||||
return ($personal && $this->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category))
|
||||
|| $this->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
|| $this->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category);
|
||||
}
|
||||
|
||||
public function canEdit(User $actor, Opportunity $record, ?string $newType = null): bool
|
||||
{
|
||||
if ($record->owner_user_id === null) {
|
||||
return $this->legacyWriteAllowed($actor);
|
||||
}
|
||||
|
||||
return $this->canView($actor, $record) && ! $record->trashed()
|
||||
&& in_array($this->state($record), ['draft', 'needs_information'], true)
|
||||
&& $this->scoped($actor, 'promoter', $record->organization_id, $newType ?? $record->opportunity_category)
|
||||
&& $this->operational($actor, 'edit', $record->id);
|
||||
}
|
||||
|
||||
public function conflict(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$context = $record->workflow_context ?? [];
|
||||
|
||||
return (int) $record->owner_user_id === $actor->id || in_array($actor->id, $context['contributors'] ?? [], true)
|
||||
|| ($record->organization_id !== null && DB::table('memberships')->where('user_id', $actor->id)
|
||||
->where('organization_id', $record->organization_id)->whereNull('deleted_at')->exists());
|
||||
}
|
||||
|
||||
public function state(Opportunity $record): string
|
||||
{
|
||||
return $record->workflow_context['working_state'] ?? $record->status;
|
||||
}
|
||||
|
||||
public function authorize(User $actor, string $action, Opportunity $record): void
|
||||
{
|
||||
$allowed = $action === 'view' ? $this->canView($actor, $record) : $this->canEdit($actor, $record);
|
||||
if (! $allowed) {
|
||||
$this->audit($actor, 'access_denied', ['record_id' => $record->id, 'action' => $action]);
|
||||
}
|
||||
abort_unless($allowed, 403, 'O perfil, representação, tipo ou estado não autoriza esta operação.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Opportunity> $query
|
||||
* @return Builder<Opportunity>
|
||||
*/
|
||||
public function scope(Builder $query, User $actor): Builder
|
||||
{
|
||||
if ($this->has($actor, 'auditor') || $this->superuser($actor)) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
return $query->where(function ($scope) use ($actor) {
|
||||
$scope->whereRaw('1=0');
|
||||
if ($actor->can('manage-portal')) {
|
||||
$scope->orWhereNull('owner_user_id');
|
||||
}
|
||||
foreach ($this->grants($actor) as $grant) {
|
||||
if ($grant->role === 'promoter' && ! $this->represents($actor, $grant->organization_id)) {
|
||||
continue;
|
||||
}
|
||||
$scope->orWhere(function ($allowed) use ($actor, $grant) {
|
||||
$allowed->whereNotNull('owner_user_id')->whereIn('opportunity_category', json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR));
|
||||
if ($grant->organization_id !== null) {
|
||||
$allowed->where('organization_id', $grant->organization_id);
|
||||
} elseif ($grant->role === 'promoter') {
|
||||
$allowed->whereNull('organization_id')->where('owner_user_id', $actor->id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function navigation(?User $actor): ?array
|
||||
{
|
||||
if (! $actor || ! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return null;
|
||||
}
|
||||
$contexts = [];
|
||||
foreach ($this->grants($actor, 'promoter') as $grant) {
|
||||
if (! $this->represents($actor, $grant->organization_id)) {
|
||||
continue;
|
||||
}
|
||||
foreach (json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR) as $type) {
|
||||
if ($this->canCreate($actor, $grant->organization_id, $type)) {
|
||||
$contexts[] = ['organization_id' => $grant->organization_id, 'type' => $type];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['contexts' => $contexts, 'mine' => $contexts ? '/minhas-oportunidades' : null, 'create' => $contexts ? '/minhas-oportunidades/create' : null,
|
||||
'request' => '/perfil/promotor', 'review' => $this->has($actor, 'validator') || $this->has($actor, 'publisher') || $this->has($actor, 'auditor') || $this->superuser($actor) ? '/minhas-oportunidades' : null,
|
||||
'audit' => $this->has($actor, 'auditor') || $this->superuser($actor) ? '/perfis/auditoria' : null, 'administration' => $this->superuser($actor) ? '/perfis/gestao' : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function audit(User $actor, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-profiles-v1', 'entity_type' => 'authorization', 'actor_user_id' => $actor->id,
|
||||
'action' => $action, 'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
|
||||
'after_data' => json_encode([...$data, 'policy_version' => self::VERSION, 'origin_ip' => request()->ip()], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
public function revokeSessions(User $subject): void
|
||||
{
|
||||
DB::table('users')->where('id', $subject->id)->increment('portal_access_revision');
|
||||
// Invalidate remember-me as well; no password or MFA changes.
|
||||
DB::table('users')->where('id', $subject->id)->update(['remember_token' => null]);
|
||||
if (Schema::hasTable('sessions')) {
|
||||
DB::table('sessions')->where('user_id', $subject->id)->delete();
|
||||
}
|
||||
if (Schema::hasTable('personal_access_tokens')) {
|
||||
DB::table('personal_access_tokens')->where('tokenable_type', User::class)->where('tokenable_id', $subject->id)->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class PortalProfileAdministration
|
||||
{
|
||||
public function __construct(private PortalProfileAccess $access) {}
|
||||
|
||||
public function administrative(User $actor): void
|
||||
{
|
||||
abort_unless($this->access->superuser($actor) && $this->access->mfa($actor), 403, 'Superutilizador com MFA recente necessário.');
|
||||
abort_if($this->access->has($actor, 'auditor'), 403, 'A restrição de leitura do Auditor prevalece.');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function grant(User $actor, array $input): string
|
||||
{
|
||||
$this->administrative($actor);
|
||||
$data = Validator::make($input, ['user_id' => 'required|integer|exists:users,id', 'role' => ['required', Rule::in(['promoter', 'validator', 'publisher', 'auditor'])],
|
||||
'organization_id' => 'nullable|uuid|exists:organizations,id', 'opportunity_types' => 'required|array|min:1', 'opportunity_types.*' => ['required', Rule::in(OpportunityManagement::CATEGORIES)],
|
||||
'responsibilities' => 'sometimes|array', 'responsibilities.*' => ['required', Rule::in(['validation_coordinator', 'technical_reviewer', 'legal_reviewer', 'appeal_reviewer', 'publication_coordinator'])],
|
||||
'expires_at' => 'nullable|date|after:now', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
abort_if((int) $data['user_id'] === $actor->id, 403, 'Não pode aprovar a sua atribuição.');
|
||||
abort_if($data['role'] === 'promoter', 422, 'Promotor exige pedido e revisão documental independente.');
|
||||
$responsibilities = match ($data['role']) {
|
||||
'validator' => ['validation_coordinator', 'technical_reviewer', 'legal_reviewer', 'appeal_reviewer'],
|
||||
'publisher' => ['publication_coordinator'],
|
||||
default => [],
|
||||
};
|
||||
abort_unless(array_diff($data['responsibilities'] ?? [], $responsibilities) === [], 422, 'Responsabilidade incompatível com o papel.');
|
||||
$subject = User::whereKey($data['user_id'])->firstOrFail();
|
||||
abort_unless($subject->hasVerifiedEmail(), 422);
|
||||
if (in_array($data['role'], ['validator', 'publisher'], true)) {
|
||||
abort_unless($subject->two_factor_secret !== null && $subject->two_factor_confirmed_at !== null, 422, 'Configure e confirme MFA antes de atribuir este papel.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
$id = (string) Str::uuid();
|
||||
$this->insertGrant($id, $actor, $data);
|
||||
$this->access->audit($actor, 'role_granted', ['assignment_id' => $id, 'subject_user_id' => $data['user_id'], 'role' => $data['role'], 'reason' => $data['reason']]);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function insertGrant(string $id, User $approver, array $data): void
|
||||
{
|
||||
DB::table('portal_role_assignments')->insert(['id' => $id, 'user_id' => $data['user_id'], 'role' => $data['role'], 'organization_id' => $data['organization_id'] ?? null,
|
||||
'opportunity_types' => json_encode(array_values(array_unique($data['opportunity_types'])), JSON_THROW_ON_ERROR), 'responsibilities' => json_encode($data['responsibilities'] ?? [], JSON_THROW_ON_ERROR),
|
||||
'source' => $data['source'] ?? 'independent-administration', 'request_id' => $data['request_id'] ?? null, 'approved_by' => $approver->id,
|
||||
'starts_at' => now(), 'expires_at' => $data['expires_at'] ?? null, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
|
||||
public function revoke(User $actor, string $id, string $reason): void
|
||||
{
|
||||
$this->administrative($actor);
|
||||
Validator::make(['reason' => $reason], ['reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $reason) {
|
||||
$row = DB::table('portal_role_assignments')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
if ($row->revoked_at !== null) {
|
||||
return;
|
||||
}
|
||||
DB::table('portal_role_assignments')->where('id', $id)->update(['revoked_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->revokeSessions(User::whereKey($row->user_id)->firstOrFail());
|
||||
$this->access->audit($actor, 'role_revoked', ['assignment_id' => $id, 'subject_user_id' => $row->user_id, 'reason' => $reason]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function request(User $actor, array $input): string
|
||||
{
|
||||
abort_unless($this->access->available() && $actor->hasVerifiedEmail(), 403);
|
||||
$data = Validator::make($input, ['creation_key' => 'required|uuid', 'representation_type' => 'required|in:individual,company,public_entity,association,partner',
|
||||
'organization_id' => 'nullable|uuid|exists:organizations,id', 'opportunity_types' => 'required|array|min:1', 'opportunity_types.*' => ['required', Rule::in(OpportunityManagement::CATEGORIES)],
|
||||
'document_ids' => 'required|array|min:1', 'document_ids.*' => 'required|uuid|exists:documents,id', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$organization = $data['organization_id'] ?? null;
|
||||
abort_unless(($data['representation_type'] === 'individual') === ($organization === null), 422, 'Pessoa singular usa âmbito próprio; as entidades exigem organização.');
|
||||
abort_unless($this->access->represents($actor, $organization), 403, 'Representação ativa de escrita necessária.');
|
||||
foreach ($data['document_ids'] as $id) {
|
||||
abort_unless(DB::table('documents')->where('id', $id)->where('uploaded_by', $actor->id)->whereNull('deleted_at')->where('status', 'active')
|
||||
->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->exists(), 422, 'Comprovativo próprio, íntegro e analisado necessário.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $organization) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40000)');
|
||||
$existing = DB::table('portal_profile_requests')->where('creation_key', $data['creation_key'])->first();
|
||||
if ($existing) {
|
||||
abort_unless((int) $existing->user_id === $actor->id, 403);
|
||||
abort_unless($existing->organization_id === $organization && $existing->representation_type === $data['representation_type']
|
||||
&& json_decode($existing->opportunity_types, true) === $data['opportunity_types'] && json_decode($existing->document_ids, true) === $data['document_ids'] && $existing->reason === $data['reason'], 409, 'Chave já usada com outro pedido.');
|
||||
|
||||
return $existing->id;
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('portal_profile_requests')->insert(['id' => $id, 'user_id' => $actor->id, 'organization_id' => $organization,
|
||||
'representation_type' => $data['representation_type'], 'opportunity_types' => json_encode($data['opportunity_types'], JSON_THROW_ON_ERROR),
|
||||
'document_ids' => json_encode($data['document_ids'], JSON_THROW_ON_ERROR), 'reason' => $data['reason'], 'creation_key' => $data['creation_key'], 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($actor, 'promoter_requested', ['request_id' => $id, 'types' => $data['opportunity_types']]);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function decide(User $actor, string $id, array $input): void
|
||||
{
|
||||
$this->administrative($actor);
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:20|max:1000',
|
||||
'verified_identity' => 'required|boolean|accepted_if:decision,approved', 'verified_representation' => 'required|boolean|accepted_if:decision,approved', 'verified_documents' => 'required|boolean|accepted_if:decision,approved',
|
||||
'approved_types' => 'present|array', 'approved_types.*' => ['required', Rule::in(OpportunityManagement::CATEGORIES)], 'expires_at' => 'nullable|date|after:now'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data) {
|
||||
$row = DB::table('portal_profile_requests')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
abort_if((int) $row->user_id === $actor->id, 403, 'Não pode aprovar o seu pedido.');
|
||||
abort_unless($row->status === 'pending' && (int) $row->version === (int) $data['version'], 409);
|
||||
$requested = json_decode($row->opportunity_types, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(array_diff($data['approved_types'], $requested) === [], 422, 'Só podem ser aprovados tipos pedidos.');
|
||||
$subject = User::whereKey($row->user_id)->firstOrFail();
|
||||
if ($data['decision'] === 'approved') {
|
||||
abort_unless($this->access->represents($subject, $row->organization_id), 403, 'Representação entretanto revogada.');
|
||||
foreach (json_decode($row->document_ids, true) as $document) {
|
||||
abort_unless(DB::table('documents')->where('id', $document)->where('uploaded_by', $subject->id)->whereNull('deleted_at')->where('status', 'active')
|
||||
->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->exists(), 422, 'Comprovativo entretanto indisponível.');
|
||||
}
|
||||
}
|
||||
if ($data['decision'] === 'approved') {
|
||||
abort_unless($data['approved_types'] !== [], 422, 'Escolha ao menos um tipo.');
|
||||
$this->insertGrant((string) Str::uuid(), $actor, ['user_id' => $subject->id, 'role' => 'promoter', 'organization_id' => $row->organization_id,
|
||||
'opportunity_types' => $data['approved_types'], 'request_id' => $id, 'source' => 'documented-promoter-request', 'expires_at' => $data['expires_at'] ?? null]);
|
||||
}
|
||||
DB::table('portal_profile_requests')->where('id', $id)->update(['status' => $data['decision'], 'version' => $row->version + 1, 'decided_by' => $actor->id,
|
||||
'decision_reason' => $data['reason'], 'decided_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($actor, 'promoter_request_decided', ['request_id' => $id, 'decision' => $data['decision'], 'approved_types' => $data['approved_types'], 'reason' => $data['reason'], 'checks' => array_intersect_key($data, array_flip(['verified_identity', 'verified_representation', 'verified_documents']))]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** Additive installation and separate, explicit bootstrap. No identities are inferred. */
|
||||
class PortalProfileInstallation
|
||||
{
|
||||
public const MIGRATION = '2026_10_10_040000_create_portal_profile_authorization';
|
||||
|
||||
public const TABLES = ['portal_profile_requests', 'portal_role_assignments', 'portal_superuser_pair', 'portal_security_approvals'];
|
||||
|
||||
public function __construct(private PortalProfileAccess $access) {}
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files = [...PortalProfileAccess::fingerprintFiles(), __FILE__, config_path('portal_profiles.php'),
|
||||
app_path('Http/Controllers/PortalProfileInstallationController.php'), resource_path('js/pages/profiles/installation.tsx')];
|
||||
|
||||
return hash('sha256', json_encode(array_map(fn ($path) => hash_file('sha256', $path), array_unique($files)), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function authorize(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail(), 403);
|
||||
if (Schema::hasTable('portal_role_assignments')) {
|
||||
abort_if(DB::table('portal_role_assignments')->where('user_id', $actor->id)->where('role', 'auditor')->whereNull('revoked_at')
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->exists(), 403, 'A restrição do Auditor prevalece.');
|
||||
}
|
||||
$pair = Schema::hasTable('portal_superuser_pair') ? DB::table('portal_superuser_pair')->where('id', 1)->first() : null;
|
||||
abort_unless($pair ? in_array($actor->id, [(int) $pair->first_user_id, (int) $pair->second_user_id], true) : $actor->can('manage-portal'), 403, 'Gestor de instalação ou titular da dupla necessário.');
|
||||
if ($write) {
|
||||
abort_unless($this->access->mfa($actor), 403, 'Conclua MFA nesta sessão; configuração de MFA isoladamente não autoriza a operação.');
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
||||
$schema = [];
|
||||
foreach (self::TABLES as $table) {
|
||||
$schema[$table] = Schema::hasTable($table);
|
||||
}
|
||||
foreach (['users' => ['portal_access_revision'], 'opportunities' => ['owner_user_id', 'organization_id', 'workflow_context']] as $table => $columns) {
|
||||
foreach ($columns as $column) {
|
||||
$schema[$table.'.'.$column] = Schema::hasColumn($table, $column);
|
||||
}
|
||||
}
|
||||
$all = ! in_array(false, $schema, true);
|
||||
$none = ! in_array(true, $schema, true);
|
||||
$consistent = ($ledger && $all) || (! $ledger && $none);
|
||||
$installed = $ledger && $all;
|
||||
$dependencies = [
|
||||
'management_020000' => DB::table('migrations')->where('migration', '2026_10_09_020000_extend_opportunity_management')->exists() && Schema::hasColumn('opportunities', 'management_draft'),
|
||||
'resources_030000' => DB::table('migrations')->where('migration', '2026_10_09_030000_extend_opportunity_resources')->exists()
|
||||
&& Schema::hasTable('opportunity_documents') && Schema::hasTable('opportunity_images') && Schema::hasTable('opportunity_location_drafts') && Schema::hasColumn('documents', 'storage_encryption'),
|
||||
'existing_identity_organization_audit' => Schema::hasTable('users') && Schema::hasTable('organizations') && Schema::hasTable('memberships') && Schema::hasTable('audit_events'),
|
||||
];
|
||||
$code = $this->fingerprint();
|
||||
$proofPath = config('portal_profiles.proof_directory').'/readiness.json';
|
||||
$proofBytes = is_file($proofPath) ? file_get_contents($proofPath) : false;
|
||||
$proof = is_string($proofBytes) ? json_decode($proofBytes, true) : [];
|
||||
$proof = is_array($proof) ? $proof : [];
|
||||
$fresh = isset($proof['verified_at']) && strtotime($proof['verified_at']) >= time() - 86400;
|
||||
$evidence = $fresh && ($proof['code_hash'] ?? '') === $code && ($proof['target']['database'] ?? '') === $identity->database
|
||||
&& (int) ($proof['target']['port'] ?? 0) === (int) $identity->port && ($proof['restore_verified'] ?? false) && ($proof['files_verified'] ?? false)
|
||||
&& ($proof['compatibility_verified'] ?? false) && ($proof['qa_passed'] ?? false)
|
||||
&& is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['dump_sha256'] ?? null)
|
||||
&& is_file($proof['files_path'] ?? '') && hash_file('sha256', $proof['files_path']) === ($proof['files_sha256'] ?? null);
|
||||
$ready = $consistent && ! in_array(false, $dependencies, true) && $evidence;
|
||||
$pair = $installed ? DB::table('portal_superuser_pair')->where('id', 1)->first() : null;
|
||||
$bootstrap = ['initialized' => $pair !== null, 'holders' => $pair ? [(int) $pair->first_user_id, (int) $pair->second_user_id] : [], 'version' => $pair?->version,
|
||||
'rule' => 'Escolher explicitamente duas contas confirmadas com MFA; um terceiro gestor com MFA aprova. Sem escolha automática, sem alteração de papéis legados.'];
|
||||
$plan = ['target' => $identity, 'code_hash' => $code, 'installed' => $installed, 'consistent' => $consistent, 'ledger' => $ledger, 'schema' => $schema,
|
||||
'dependencies' => $dependencies, 'ready' => $ready, 'backupDate' => $proof['verified_at'] ?? null, 'bootstrap' => $bootstrap,
|
||||
'path_190000_installed' => DB::table('migrations')->where('migration', '2026_10_09_190000_prepare_investor_path')->exists(),
|
||||
'migration' => self::MIGRATION, 'changes' => ['Quatro tabelas, uma coluna em users e três em opportunities; zero contas e zero atribuições automáticas.',
|
||||
'030000 precede esta ação; 190000 continua etapa posterior do percurso, sem dependência DDL desta migração.', 'Nenhuma flag ativada, dado publicado, titular escolhido ou privilégio legado removido.'],
|
||||
'rollback' => 'DDL e ledger são atómicos em PostgreSQL. Se vazio, down deve remover todas as colunas adicionadas; se houver uso/histórico, preservar e restaurar backup verificado, sem rollback destrutivo.'];
|
||||
$plan['hash'] = hash('sha256', json_encode($plan, JSON_THROW_ON_ERROR));
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true);
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
|
||||
return $this->receipt($actor, 'install', $data, function () use ($actor, $data) {
|
||||
$p = $this->preview($actor);
|
||||
abort_unless(hash_equals($p['hash'], $data['hash']), 409, 'Plano alterado; consulte a pré-visualização.');
|
||||
abort_unless($p['consistent'], 409, 'Ledger/schema incoerentes; recuperar antes de instalar.');
|
||||
if ($p['installed']) {
|
||||
return ['installed' => true, 'changed' => false, 'migration' => self::MIGRATION, 'bootstrap_required' => ! $p['bootstrap']['initialized'], 'flags_changed' => false];
|
||||
}
|
||||
abort_unless($p['ready'], 422, 'Dependências e provas atuais de backup/restauro/QA são necessárias.');
|
||||
config(['portal_profiles.authenticated_installation' => true]);
|
||||
try {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'A instalação falhou; a transação é revertida.');
|
||||
} finally {
|
||||
config(['portal_profiles.authenticated_installation' => false]);
|
||||
}
|
||||
$after = $this->preview($actor);
|
||||
abort_unless($after['installed'] && $after['consistent'], 500, 'Verificação pós-instalação falhou; reverter transação.');
|
||||
|
||||
return ['installed' => true, 'changed' => true, 'migration' => self::MIGRATION, 'bootstrap_required' => true, 'flags_changed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function bootstrap(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true);
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid',
|
||||
'first_user_id' => 'required|integer|exists:users,id', 'second_user_id' => 'required|integer|different:first_user_id|exists:users,id', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
|
||||
return $this->receipt($actor, 'bootstrap', $data, function () use ($actor, $data) {
|
||||
$p = $this->preview($actor);
|
||||
abort_unless(hash_equals($p['hash'], $data['hash']), 409, 'Plano alterado.');
|
||||
abort_unless($p['installed'] && ! $p['bootstrap']['initialized'], 409, 'Inicialização exige schema instalado e dupla ainda não designada. Use substituição para uma dupla existente.');
|
||||
config(['portal_profiles.bootstrap_authorized' => true]);
|
||||
try {
|
||||
app(PortalSuperusers::class)->initialize(User::query()->whereKey($data['first_user_id'])->firstOrFail(), User::query()->whereKey($data['second_user_id'])->firstOrFail(), $actor);
|
||||
} finally {
|
||||
config(['portal_profiles.bootstrap_authorized' => false]);
|
||||
}
|
||||
|
||||
return ['initialized' => true, 'holders' => [$data['first_user_id'], $data['second_user_id']], 'version' => 1, 'flags_changed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @param callable():array<string,mixed> $operation
|
||||
* @return array<string,mixed> */
|
||||
private function receipt(User $actor, string $scope, array $data, callable $operation): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $scope, $data, $operation) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40000)');
|
||||
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$previous = DB::table('audit_events')->where('source_system', 'portal-profile-installation')->where('action', $scope)->where('actor_user_id', $actor->id)->where('correlation_id', $data['idempotency_key'])->first();
|
||||
if ($previous) {
|
||||
$receipt = json_decode($previous->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave de repetição reutilizada com outro conteúdo.');
|
||||
|
||||
return $receipt['result'];
|
||||
}
|
||||
$result = $operation();
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-profile-installation', 'entity_type' => 'installation', 'actor_user_id' => $actor->id, 'action' => $scope,
|
||||
'correlation_id' => $data['idempotency_key'], 'data_classification' => 'restricted', 'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result, 'code_hash' => $this->fingerprint()], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class PortalSuperusers
|
||||
{
|
||||
public function __construct(private PortalProfileAccess $access, private PortalProfileAdministration $administration) {}
|
||||
|
||||
public function initialize(User $first, User $second, User $approver): void
|
||||
{
|
||||
// Bootstrap requires a separately authorized ceremony; never infer real holders.
|
||||
abort_unless(config('portal_profiles.bootstrap_authorized') === true, 403);
|
||||
abort_unless(count(array_unique([$first->id, $second->id, $approver->id])) === 3, 422);
|
||||
foreach ([$first, $second, $approver] as $user) {
|
||||
abort_unless($user->hasVerifiedEmail() && $user->two_factor_secret && $user->two_factor_confirmed_at, 422, 'Contas confirmadas com MFA necessário.');
|
||||
try {
|
||||
$secret = Crypt::decryptString($user->two_factor_secret);
|
||||
} catch (DecryptException) {
|
||||
abort(422, 'Configuração MFA incompatível com este ambiente. Recuperar a conta pelo procedimento existente antes da inicialização.');
|
||||
}
|
||||
abort_unless(strlen($secret) >= 16 && preg_match('/^[A-Z2-7]+=*$/', $secret), 422, 'Configuração MFA inválida.');
|
||||
abort_if(DB::table('portal_role_assignments')->where('user_id', $user->id)->where('role', 'auditor')->whereNull('revoked_at')
|
||||
->where('starts_at', '<=', now())->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->exists(), 422, 'A restrição do Auditor impede a designação de titular nesta cerimónia.');
|
||||
}
|
||||
abort_unless($this->access->mfa($approver), 403);
|
||||
DB::transaction(function () use ($first, $second, $approver) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40001)');
|
||||
$existing = DB::table('portal_superuser_pair')->where('id', 1)->first();
|
||||
if ($existing) {
|
||||
abort_unless((int) $existing->first_user_id === $first->id && (int) $existing->second_user_id === $second->id, 409, 'Inicialização já realizada. Use substituição atómica.');
|
||||
|
||||
return;
|
||||
}
|
||||
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $first->id, 'second_user_id' => $second->id, 'approved_by' => $approver->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($approver, 'superuser_pair_initialized', ['holders' => [$first->id, $second->id], 'version' => 1]);
|
||||
});
|
||||
}
|
||||
|
||||
public function requestReplacement(User $actor, int $oldId, int $newId, string $reason): string
|
||||
{
|
||||
$this->administration->administrative($actor);
|
||||
abort_unless(mb_strlen($reason) >= 20 && mb_strlen($reason) <= 1000 && $oldId !== $newId, 422);
|
||||
|
||||
return DB::transaction(function () use ($actor, $oldId, $newId, $reason) {
|
||||
$pair = DB::table('portal_superuser_pair')->where('id', 1)->lockForUpdate()->first();
|
||||
$holders = [(int) $pair->first_user_id, (int) $pair->second_user_id];
|
||||
abort_unless(in_array($oldId, $holders, true) && ! in_array($newId, $holders, true), 422);
|
||||
$candidate = User::findOrFail($newId);
|
||||
abort_unless($candidate->hasVerifiedEmail() && $candidate->two_factor_secret && $candidate->two_factor_confirmed_at, 422);
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('portal_security_approvals')->insert(['id' => $id, 'kind' => 'replacement', 'requested_by' => $actor->id, 'subject_user_id' => $newId,
|
||||
'scope' => json_encode(['old_user_id' => $oldId, 'pair_version' => (int) $pair->version], JSON_THROW_ON_ERROR), 'reason' => $reason,
|
||||
'expires_at' => now()->addMinutes(15), 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($actor, 'superuser_replacement_requested', ['approval_id' => $id, 'old_user_id' => $oldId, 'new_user_id' => $newId]);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
public function approve(User $actor, string $id): void
|
||||
{
|
||||
$this->administration->administrative($actor);
|
||||
DB::transaction(function () use ($actor, $id) {
|
||||
$row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row !== null, 404);
|
||||
abort_if((int) $row->requested_by === $actor->id || (int) $row->subject_user_id === $actor->id, 403, 'Aprovação independente necessária.');
|
||||
abort_unless($row->consumed_at === null && strtotime($row->expires_at) > time() && $row->approved_by === null, 409);
|
||||
DB::table('portal_security_approvals')->where('id', $id)->update(['approved_by' => $actor->id, 'updated_at' => now()]);
|
||||
$this->access->audit($actor, 'security_operation_approved', ['approval_id' => $id, 'kind' => $row->kind]);
|
||||
});
|
||||
}
|
||||
|
||||
public function applyReplacement(User $actor, string $id): void
|
||||
{
|
||||
$this->administration->administrative($actor);
|
||||
DB::transaction(function () use ($actor, $id) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(101026, 40001)');
|
||||
$pair = DB::table('portal_superuser_pair')->where('id', 1)->lockForUpdate()->first();
|
||||
$row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($row && $row->kind === 'replacement' && (int) $row->requested_by === $actor->id, 403);
|
||||
abort_unless($row->approved_by !== null && $row->consumed_at === null && strtotime($row->expires_at) > time(), 409);
|
||||
$scope = json_decode($row->scope, true, 512, JSON_THROW_ON_ERROR);
|
||||
$holders = [(int) $pair->first_user_id, (int) $pair->second_user_id];
|
||||
abort_unless((int) $pair->version === $scope['pair_version'] && in_array((int) $row->approved_by, $holders, true)
|
||||
&& in_array($scope['old_user_id'], $holders, true) && ! in_array((int) $row->subject_user_id, $holders, true), 409, 'Dupla ou aprovação mudou.');
|
||||
$candidate = User::whereKey($row->subject_user_id)->firstOrFail();
|
||||
abort_unless($candidate->hasVerifiedEmail() && $candidate->two_factor_secret && $candidate->two_factor_confirmed_at, 422);
|
||||
$column = (int) $pair->first_user_id === $scope['old_user_id'] ? 'first_user_id' : 'second_user_id';
|
||||
// A single UPDATE preserves two distinct holders at every observable state.
|
||||
DB::table('portal_superuser_pair')->where('id', 1)->update([$column => $candidate->id, 'version' => $pair->version + 1, 'approved_by' => $row->approved_by, 'updated_at' => now()]);
|
||||
DB::table('portal_security_approvals')->where('id', $id)->update(['consumed_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->revokeSessions(User::findOrFail($scope['old_user_id']));
|
||||
$this->access->audit($actor, 'superuser_replaced', ['approval_id' => $id, 'before' => $holders, 'after' => DB::table('portal_superuser_pair')->where('id', 1)->first(), 'alert' => 'Substituição de titular: verificar acessos e recuperação.']);
|
||||
});
|
||||
}
|
||||
|
||||
public function requestElevation(User $actor, string $action, ?int $recordId, string $reason): string
|
||||
{
|
||||
$this->administration->administrative($actor);
|
||||
abort_unless(in_array($action, ['create', 'edit', 'validate', 'publish', 'archive'], true) && mb_strlen($reason) >= 20 && mb_strlen($reason) <= 1000, 422);
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('portal_security_approvals')->insert(['id' => $id, 'kind' => 'elevation', 'requested_by' => $actor->id, 'subject_user_id' => $actor->id,
|
||||
'scope' => json_encode(['action' => $action, 'record_id' => $recordId], JSON_THROW_ON_ERROR), 'reason' => $reason,
|
||||
'expires_at' => now()->addMinutes(15), 'created_at' => now(), 'updated_at' => now()]);
|
||||
$this->access->audit($actor, 'elevation_requested', ['approval_id' => $id, 'action' => $action, 'record_id' => $recordId, 'reason' => $reason]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ class TerritoryGeometryImport
|
||||
{
|
||||
public function fingerprint(): string
|
||||
{
|
||||
return hash('sha256', implode('', array_map(fn ($f) => hash_file('sha256', $f), [__FILE__, config_path('geometry-import.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), base_path('routes/web.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
return hash('sha256', implode('', array_map(fn ($f) => hash_file('sha256', $f), [__FILE__, config_path('geometry-import.php'), config_path('geometry-correspondences.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), base_path('routes/web.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')])));
|
||||
}
|
||||
@@ -32,7 +32,7 @@ class TerritoryGeometryImport
|
||||
return;
|
||||
}
|
||||
$file = storage_path('app/private/investmoz-v2/geometry-import-activation-proof.json');
|
||||
$p = is_file($file) ? json_decode(file_get_contents($file), true) : [];
|
||||
$p = is_file($file) ? json_decode($this->readFile($file), true) : [];
|
||||
abort_unless(($p['restore_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['ui_passed'] ?? false)
|
||||
&& ($p['code_hash'] ?? '') === $this->fingerprint() && ($p['target']['database'] ?? '') === $target->database
|
||||
&& (int) ($p['target']['port'] ?? 0) === (int) $target->port && strtotime($p['verified_at'] ?? '') >= time() - 86400
|
||||
@@ -40,6 +40,7 @@ class TerritoryGeometryImport
|
||||
&& ($p['files_verified'] ?? false) && is_file($p['files_path'] ?? '') && hash_file('sha256', $p['files_path']) === ($p['files_sha256'] ?? null), 422, 'Backup/restauro e provas desta revisão e alvo necessários; preparação não autoriza ativação.');
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function preview(User $actor, int $level): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
@@ -48,12 +49,15 @@ class TerritoryGeometryImport
|
||||
$file = $directory.'/moz-adm'.$level.'-ine-20190607.geojson';
|
||||
$metadata = $directory.'/moz-adm'.$level.'-ine-metadata.html';
|
||||
abort_unless(is_file($file) && is_file($metadata), 422, 'Exemplar privado indisponível.');
|
||||
$text = file_get_contents($metadata);
|
||||
$text = $this->readFile($metadata);
|
||||
abort_unless(str_contains($text, 'Mozambique INE - Instituto Nacional de Estatistica') && str_contains($text, '2019-06-07'), 422, 'Metadados do exemplar divergentes.');
|
||||
$sourceHash = hash_file('sha256', $file);
|
||||
$source = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$source = json_decode($this->readFile($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(($source['type'] ?? '') === 'FeatureCollection' && count($source['features'] ?? []) === [1 => 11, 2 => 159, 3 => 411][$level] && ! ($source['exceededTransferLimit'] ?? false), 422, 'Exemplar incompleto.');
|
||||
$locations = DB::table('geo_locations')->where('location_type', [1 => 'province', 2 => 'district', 3 => 'admin_post'][$level])->whereNull('deleted_at')->get(['id', 'name', 'parent_id']);
|
||||
$locations = DB::table('geo_locations')->where('location_type', [1 => 'province', 2 => 'district', 3 => 'admin_post'][$level])->whereNull('deleted_at')->get(['id', 'name', 'parent_id', 'source_system', 'source_code', 'external_id']);
|
||||
$crosswalk = config('geometry-correspondences');
|
||||
$correspondences = $crosswalk['rows'][$level] ?? [];
|
||||
abort_if($correspondences && (($crosswalk['edition'] ?? null) !== '2019-06-07' || ($crosswalk['source_sha256'][$level] ?? null) !== $sourceHash), 422, 'Correspondências não pertencem a este exemplar; nenhuma aproximação aplicada.');
|
||||
$normalize = fn ($n) => strtolower(trim(Str::ascii($n)));
|
||||
$countryNames = array_map($normalize, [$source['features'][0]['properties']['ADM0_PT'], $source['features'][0]['properties']['ADM0_EN']]);
|
||||
$countries = DB::table('geo_locations')->where('location_type', 'country')->whereNull('deleted_at')->get(['id', 'name'])->filter(fn ($c) => in_array($normalize($c->name), $countryNames, true))->values();
|
||||
@@ -66,9 +70,19 @@ class TerritoryGeometryImport
|
||||
$external = '2019-06-07:adm'.$level.':'.$p['ADM'.$level.'_PCODE'];
|
||||
$parent = $level > 1 ? DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->where('external_id', '2019-06-07:adm'.($level - 1).':'.$p['ADM'.($level - 1).'_PCODE'])->where('properties->source_sha256', $parentSourceHash)->whereNull('deleted_at')->value('geo_location_id') : $countryId;
|
||||
$matches = $locations->filter(fn ($l) => $normalize($l->name) === $normalize($p['ADM'.$level.'_PT']) && $parent && $l->parent_id === $parent)->values();
|
||||
$correspondence = $correspondences[$p['ADM'.$level.'_PCODE']] ?? null;
|
||||
$matchBasis = 'unique_exact_name_and_matched_parent_after_case_and_diacritics';
|
||||
if ($correspondence) {
|
||||
abort_unless($correspondence['source_name'] === $p['ADM'.$level.'_PT'] && $correspondence['parent_source_code'] === $p['ADM'.($level - 1).'_PCODE'], 422, 'Nome/pai do exemplar divergente da correspondência explícita.');
|
||||
$matches = $locations->filter(fn ($l) => $parent && $l->parent_id === $parent
|
||||
&& $normalize($l->name) === $normalize($correspondence['target_name']) && $l->source_code === $correspondence['target_source_code']
|
||||
&& $l->source_system === $crosswalk['catalogue_source_system'] && str_starts_with($l->external_id ?? '', $crosswalk['catalogue_sha256'].':'))->values();
|
||||
$matchBasis = 'explicit_versioned_correspondence';
|
||||
}
|
||||
$row = ['external_id' => $external, 'name' => $p['ADM'.$level.'_PT'], 'parent_name' => $level > 1 ? $p['ADM'.($level - 1).'_PT'] : null,
|
||||
'parent_code' => $level > 1 ? $p['ADM'.($level - 1).'_PCODE'] : null, 'candidates' => $matches->all(), 'location_id' => count($matches) === 1 ? $matches[0]->id : null,
|
||||
'status' => count($matches) === 1 ? 'insert' : (! $parent ? 'parent_unresolved' : 'name_unresolved')];
|
||||
'status' => count($matches) === 1 ? 'insert' : (count($matches) > 1 ? ($correspondence ? 'correspondence_conflict' : 'ambiguous_name') : (! $parent ? 'parent_unresolved' : 'name_unresolved')),
|
||||
'match_basis' => $matchBasis, 'correspondence' => $correspondence, 'correspondence_version' => $correspondence ? $crosswalk['version'] : null];
|
||||
if ($row['location_id']) {
|
||||
$geometry = json_encode($feature['geometry'], JSON_THROW_ON_ERROR);
|
||||
$valid = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_NDims(g)=2 AND GeometryType(g) IN (\'POLYGON\',\'MULTIPOLYGON\') AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) q', [$geometry]);
|
||||
@@ -91,7 +105,7 @@ class TerritoryGeometryImport
|
||||
$rows[] = $row;
|
||||
}
|
||||
$scanFile = $directory.'/geometry-source-scans.json';
|
||||
$scans = is_file($scanFile) ? json_decode(file_get_contents($scanFile), true) : [];
|
||||
$scans = is_file($scanFile) ? json_decode($this->readFile($scanFile), true) : [];
|
||||
$scan = null;
|
||||
foreach ($scans['files'] ?? [] as $s) {
|
||||
if ($s['file'] === basename($file) && $s['sha256'] === $sourceHash) {
|
||||
@@ -101,6 +115,7 @@ class TerritoryGeometryImport
|
||||
$scanReady = ($scan['result'] ?? '') === 'clean' && ($scan['engine'] ?? '') === 'ClamAV' && strtotime($scans['captured_at'] ?? '') >= time() - config('geometry-import.scan_max_age_seconds');
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$plan = ['level' => $level, 'target' => $target, 'edition' => '2019-06-07', 'source_sha256' => $sourceHash, 'metadata_sha256' => hash_file('sha256', $metadata), 'code_hash' => $this->fingerprint(),
|
||||
'correspondence_version' => $crosswalk['version'], 'correspondence_sha256' => hash('sha256', json_encode($crosswalk, JSON_THROW_ON_ERROR)),
|
||||
'expected' => count($rows), 'resolved' => count(array_filter($rows, fn ($r) => in_array($r['status'], ['insert', 'reuse'], true))), 'rows' => $rows, 'scan_ready' => $scanReady, 'scan' => $scan, 'scan_at' => $scans['captured_at'] ?? null, 'published' => false];
|
||||
$plan['pending'] = $plan['expected'] - $plan['resolved'];
|
||||
$plan['hash'] = hash_hmac('sha256', json_encode([$actor->id, $plan], JSON_THROW_ON_ERROR), config('app.key'));
|
||||
@@ -108,6 +123,9 @@ class TerritoryGeometryImport
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->guard($actor, true);
|
||||
@@ -118,12 +136,14 @@ class TerritoryGeometryImport
|
||||
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Correspondências, fonte ou estado alterados; repita a pré-visualização.');
|
||||
abort_unless($plan['scan_ready'], 423, 'Scan limpo atual ligado ao original necessário.');
|
||||
abort_if(count(array_filter($plan['rows'], fn ($r) => str_contains($r['status'], 'conflict') || $r['status'] === 'invalid_geometry')) > 0, 409, 'Conflito de identidade/geometria: nenhuma escrita aplicada.');
|
||||
$bytes = file_get_contents(config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-20190607.geojson');
|
||||
$bytes = $this->readFile(config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-20190607.geojson');
|
||||
abort_unless(hash('sha256', $bytes) === $plan['source_sha256'], 409);
|
||||
$source = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
$metadata = config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-metadata.html';
|
||||
$metadataScan = app(MalwareScanner::class)->scan($metadata, filesize($metadata), storage_path('app/private'));
|
||||
abort_unless(($metadataScan['result'] ?? '') === 'clean', 423, 'Scan dos metadados do exemplar pendente ou inconclusivo.');
|
||||
$metadataSize = filesize($metadata);
|
||||
abort_unless(is_int($metadataSize), 422, 'Metadados indisponíveis durante a aplicação.');
|
||||
$metadataScan = app(MalwareScanner::class)->scan($metadata, $metadataSize, storage_path('app/private'));
|
||||
abort_unless($metadataScan['result'] === 'clean', 423, 'Scan dos metadados do exemplar pendente ou inconclusivo.');
|
||||
abort_unless(hash_file('sha256', $metadata) === $plan['metadata_sha256'], 409, 'Metadados alterados durante o scan.');
|
||||
$metadataScan['signatures_at'] = $metadataScan['signatures_at']?->format(DATE_ATOM);
|
||||
$batch = (string) Str::uuid();
|
||||
@@ -138,17 +158,20 @@ class TerritoryGeometryImport
|
||||
}
|
||||
$feature = $source['features'][$i];
|
||||
$id = (string) Str::uuid();
|
||||
$trace = ['authority' => 'Mozambique INE - Instituto Nacional de Estatistica', 'provider' => 'UNOCHA; exemplar hosted by World Bank', 'source_version' => $plan['edition'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'source_url' => 'https://services.arcgis.com/iQ1dY19aHwbSDYIF/arcgis/rest/services/Mozambique/FeatureServer/'.($data['level'] + 2), 'source_properties' => $feature['properties'], 'source_scan' => $plan['scan'], 'batch_id' => $batch, 'purpose' => 'administrative_boundary', 'investment_site' => false, 'legal_currentness' => 'not_determined', 'match_basis' => 'unique_exact_name_and_matched_parent_after_case_and_diacritics'];
|
||||
$trace = ['authority' => 'Mozambique INE - Instituto Nacional de Estatistica', 'provider' => 'UNOCHA; exemplar hosted by World Bank', 'source_version' => $plan['edition'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'source_url' => 'https://services.arcgis.com/iQ1dY19aHwbSDYIF/arcgis/rest/services/Mozambique/FeatureServer/'.($data['level'] + 2), 'source_properties' => $feature['properties'], 'source_scan' => $plan['scan'], 'batch_id' => $batch, 'purpose' => 'administrative_boundary', 'investment_site' => false, 'legal_currentness' => 'not_determined', 'match_basis' => $row['match_basis'], 'correspondence' => $row['correspondence'], 'correspondence_version' => $row['correspondence_version'], 'correspondence_sha256' => $plan['correspondence_sha256']];
|
||||
DB::insert('INSERT INTO geo_geometries(id,source_system,external_id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,?,?,?,ST_SetSRID(ST_GeomFromGeoJSON(?),4326),?::jsonb,?)', [$id, 'ine-cod-ab', $row['external_id'], $row['location_id'], strtolower($feature['geometry']['type']), json_encode($feature['geometry'], JSON_THROW_ON_ERROR), json_encode($trace, JSON_THROW_ON_ERROR), 'internal']);
|
||||
$created[] = ['id' => $id, 'checksum' => $this->snapshotHash($id)];
|
||||
}
|
||||
$result = ['batch_id' => $batch, 'level' => $data['level'], 'preview_hash' => $plan['hash'], 'expected' => $plan['expected'], 'resolved' => $plan['resolved'], 'created' => $created, 'inserted' => count($created), 'reused' => count($reused), 'reused_ids' => $reused, 'pending' => $plan['pending'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'metadata_scan' => $metadataScan, 'published' => false, 'reason' => $data['reason']];
|
||||
$result = ['batch_id' => $batch, 'level' => $data['level'], 'preview_hash' => $plan['hash'], 'expected' => $plan['expected'], 'resolved' => $plan['resolved'], 'created' => $created, 'inserted' => count($created), 'reused' => count($reused), 'reused_ids' => $reused, 'pending' => $plan['pending'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'correspondence_version' => $plan['correspondence_version'], 'correspondence_sha256' => $plan['correspondence_sha256'], 'metadata_scan' => $metadataScan, 'published' => false, 'reason' => $data['reason']];
|
||||
$this->audit($actor, $batch, 'geometry_import_applied', $result);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function reverse(User $actor, string $batch, array $input): array
|
||||
{
|
||||
$this->guard($actor, true);
|
||||
@@ -156,15 +179,31 @@ class TerritoryGeometryImport
|
||||
|
||||
return $this->receipt($actor, 'geometry-import-reverse', $data, function () use ($actor, $data, $batch) {
|
||||
$event = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_applied')->first();
|
||||
abort_unless($event, 404);
|
||||
abort_unless($event !== null, 404);
|
||||
$old = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_reversed')->first();
|
||||
if ($old) {
|
||||
return json_decode($old->after_data, true);
|
||||
}
|
||||
$manifest = json_decode($event->after_data, true);
|
||||
foreach ($manifest['created'] as $row) {
|
||||
DB::table('geo_geometries')->where('id', $row['id'])->lockForUpdate()->first();
|
||||
$geometry = DB::table('geo_geometries')->where('id', $row['id'])->lockForUpdate()->first();
|
||||
abort_unless($this->snapshotHash($row['id']) === $row['checksum'], 409, 'Geometria alterada ou publicada; reversão recusada.');
|
||||
// Source hierarchy is a real import dependency even though it is not a geometry FK.
|
||||
if (in_array((int) $manifest['level'], [1, 2], true)) {
|
||||
$properties = json_decode($geometry->properties, true, 512, JSON_THROW_ON_ERROR);
|
||||
$parentField = 'ADM'.$manifest['level'].'_PCODE';
|
||||
$code = $properties['source_properties'][$parentField] ?? null;
|
||||
abort_unless($code, 409, 'Correspondência original sem código territorial; reversão exige reconciliação.');
|
||||
$descendants = DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->whereNull('deleted_at')
|
||||
->where('properties->source_version', $properties['source_version'])
|
||||
->where('properties->source_properties->'.$parentField, $code)
|
||||
->where(function ($query) use ($manifest) {
|
||||
foreach (range((int) $manifest['level'] + 1, 3) as $level) {
|
||||
$query->orWhere('external_id', 'like', '2019-06-07:adm'.$level.':%');
|
||||
}
|
||||
});
|
||||
abort_if($descendants->exists(), 409, 'Limites descendentes dependem desta correspondência. Reverta primeiro postos, depois distritos e províncias; preserve os lotes anteriores.');
|
||||
}
|
||||
// Enumerate all real FKs, rather than assuming one consumer table.
|
||||
$references = DB::select("SELECT n.nspname AS schema,t.relname AS table_name,a.attname AS column_name FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace n ON n.oid=t.relnamespace JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=c.conkey[1] WHERE c.contype='f' AND c.confrelid='geo_geometries'::regclass");
|
||||
foreach ($references as $ref) {
|
||||
@@ -188,6 +227,10 @@ class TerritoryGeometryImport
|
||||
return hash('sha256', $r->value ?? 'missing');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @param callable():array<string,mixed> $operation
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function receipt(User $actor, string $scope, array $data, callable $operation): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $scope, $data, $operation) {
|
||||
@@ -207,8 +250,17 @@ class TerritoryGeometryImport
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function audit(User $actor, string $batch, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'geometry-import', 'entity_type' => 'geo_geometries', 'entity_id' => $batch, 'correlation_id' => $batch, 'actor_user_id' => $actor->id, 'action' => $action, 'after_data' => json_encode($data, JSON_THROW_ON_ERROR), 'data_classification' => 'internal']);
|
||||
}
|
||||
|
||||
private function readFile(string $path): string
|
||||
{
|
||||
$contents = file_get_contents($path);
|
||||
abort_unless(is_string($contents), 422, 'Exemplar/prova indisponível durante a leitura; operação recusada.');
|
||||
|
||||
return $contents;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,11 +28,15 @@ class VirtualDeskInstallation
|
||||
database_path('migrations/2026_10_01_000200_create_simulation_execution_core.php'),
|
||||
resource_path('js/components/investment-map-panel.tsx'), resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx'),
|
||||
...(glob(resource_path('js/pages/investor-path/*.tsx')) ?: [])];
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), config_path('geometry-correspondences.php'), app_path('Http/Controllers/LandAssistanceController.php'), app_path('Http/Controllers/PartnershipExchangeController.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
|
||||
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
|
||||
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
|
||||
$files = [...$files, app_path('Services/OpportunityManagement.php'), app_path('Services/OpportunityRealEstateDraft.php'), config_path('portal.php'),
|
||||
resource_path('data/investmoz-opportunity-modular.schema.json'), resource_path('js/components/app-sidebar.tsx'), resource_path('js/types/opportunity-management.ts'), base_path('vite.config.ts')];
|
||||
$files = [...$files, resource_path('js/lib/portal-navigation.ts'), resource_path('js/components/portal-grouped-menu.tsx')];
|
||||
sort($files);
|
||||
|
||||
$files = [...$files, ...PortalProfileAccess::fingerprintFiles()];
|
||||
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user