oportunidades 7
tests / ci (push) Waiting to run

This commit is contained in:
2026-10-13 11:40:29 +02:00
parent 20971d523f
commit 287e991486
2902 changed files with 1085456 additions and 25957 deletions
+12 -4
View File
@@ -78,6 +78,7 @@ final class LegacyContent
}
/** Resolve a library identity, preserving the already stored source URLs and versions. */
/** @return array<string, mixed> */
public function articleForResource(int $resourceId): array
{
abort_unless($this->available(), 404);
@@ -99,14 +100,14 @@ final class LegacyContent
$articles[] = $this->article($item['slug']);
}
abort_unless($articles !== [], 404);
return $articles;
}
/** @return list<array<string,mixed>> */
private function related(string $group, ?string $except = null): array
{
$identities = array_filter(config('legacy_content.articles', []), fn ($identity, $slug) =>
$identity['group'] === $group && $identity['publishable'] && $slug !== $except, ARRAY_FILTER_USE_BOTH);
$identities = array_filter(config('legacy_content.articles', []), fn ($identity, $slug) => $identity['group'] === $group && $identity['publishable'] && $slug !== $except, ARRAY_FILTER_USE_BOTH);
$resources = $this->publicResources()->whereIn('d.external_id', array_column($identities, 'external_id'))->get()->keyBy('external_id');
$result = [];
foreach ($identities as $slug => $identity) {
@@ -115,6 +116,7 @@ final class LegacyContent
$result[] = ['slug' => $slug, 'id' => (int) $row->resource_id, 'title' => $row->title, 'href' => '/'.$slug];
}
}
return $result;
}
@@ -134,11 +136,17 @@ final class LegacyContent
$doc->loadHTML('<?xml encoding="UTF-8"><html><body>'.$html.'</body></html>', LIBXML_NONET);
foreach ($doc->getElementsByTagName('a') as $anchor) {
$href = $anchor->getAttribute('href');
if (isset($links[rtrim($href, '/')])) { $anchor->setAttribute('href', $links[rtrim($href, '/')]); }
if (isset($links[rtrim($href, '/')])) {
$anchor->setAttribute('href', $links[rtrim($href, '/')]);
}
}
$body = $doc->getElementsByTagName('body')->item(0);
return $body ? implode('', array_map(fn ($child) => $doc->saveHTML($child), iterator_to_array($body->childNodes))) : '';
} finally { libxml_clear_errors(); libxml_use_internal_errors($old); }
} finally {
libxml_clear_errors();
libxml_use_internal_errors($old);
}
}
/** @param array<string, mixed> $input */
+52 -5
View File
@@ -15,6 +15,33 @@ use Opis\JsonSchema\Errors\ValidationError;
/** Explicit adapter of §25/26 to existing IDs and resource collections; never renumbers records. */
class OpportunityCanonicalContract
{
public const BASE_CATEGORIES = ['investment_project', 'real_estate', 'land_rights', 'business_sale', 'business_partnership', 'franchise'];
/** Availability of this bounded base-category delivery, without rewriting existing contracts/data. */
public function deliveryBlockers(array $payload): array
{
$errors = [];
if (! in_array($payload['opportunity_category'] ?? '', self::BASE_CATEGORIES, true) && ! app(OpportunityModularProfiles::class)->enabled()) {
$errors['canonical.opportunity_category'] = 'Categoria fora desta entrega: concessão, financiamento, fornecimento e outros permanecem indisponíveis. Os registos anteriores são preservados.';
}
if (($payload['opportunity_category'] ?? '') === 'real_estate') {
$property = $payload['real_estate'] ?? [];
foreach (['construction_status' => ['completed'], 'occupancy_status' => ['vacant'], 'transaction_type' => ['sale', 'lease']] as $field => $values) {
if (! empty($property[$field]) && ! in_array($property[$field], $values, true)) {
$errors['canonical.real_estate.'.$field] = 'Variante indisponível para submissão nesta entrega. Pode guardar e recuperar a preparação; estão incluídas venda e arrendamento de imóvel concluído e desocupado.';
}
}
if (array_filter($property['encumbrances'] ?? [], fn ($row) => ! empty($row['type']) && $row['type'] !== 'none')) {
$errors['canonical.real_estate.encumbrances'] = 'Imóvel com encargos: pode preparar e guardar; a submissão deste ramo não está incluída nesta entrega.';
}
if (! empty($property['max_built_area']) || ! empty($property['urban_limit_document_id'])) {
$errors['canonical.real_estate.max_built_area'] = 'Limitações urbanísticas adicionais: preparação disponível; este ramo de submissão aguarda demonstração própria.';
}
}
return $errors;
}
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
/** @return array<string,mixed> */
@@ -178,7 +205,7 @@ class OpportunityCanonicalContract
}
};
$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.');
$check(($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Identifique o promotor real da oportunidade; o operador do portal não o substitui.');
$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();
@@ -244,11 +271,18 @@ class OpportunityCanonicalContract
'payload' => $payload, 'resources' => $resources];
if (isset(OpportunityModularProfiles::PROFILES[$record->opportunity_category]) || ($payload['module_profile_version'] ?? '') === OpportunityModularProfiles::HISTORY_VERSION) {
$snapshot['qa_extension'] = ['version' => OpportunityModularProfiles::VERSION, 'profile_version' => $payload['module_profile_version'],
'functional_decision' => 'User recommendations accepted for QA, 10/10/2026; no active approval or security-holder nomination',
'functional_decision' => 'Experimental QA proposal; functional approval of modular contracts and SLA remains pending. Legacy integration authorization does not approve these modules.',
'gates' => $this->gates($record)];
if ($record->opportunity_category === 'other') {
$snapshot['qa_extension']['subtype'] = config('portal.opportunity_other_qa_subtypes.'.($payload['module_details']['subtype'] ?? ''), []);
}
// A documentary correction must not rewrite the checksum of an already
// signed, unchanged version. Its historical annotation is explicitly
// reconciled by the read adapter; new/changed content uses the current note.
$prior = $record->workflow_context['submission'] ?? [];
if (isset($prior['qa_extension']) && ($prior['payload'] ?? null) == $snapshot['payload'] && ($prior['resources'] ?? null) == $snapshot['resources']) {
$snapshot['qa_extension']['functional_decision'] = $prior['qa_extension']['functional_decision'];
}
}
$snapshot['hash'] = hash('sha256', json_encode($snapshot, JSON_THROW_ON_ERROR));
@@ -297,8 +331,16 @@ class OpportunityCanonicalContract
}
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 ($re['transaction_type'] === 'sale' && ($re['price'] ?? 0) <= 0) {
$errors['canonical.real_estate.price'] = 'Venda exige preço positivo.';
}
if ($re['transaction_type'] === 'lease') {
if (($re['rent'] ?? 0) <= 0) {
$errors['canonical.real_estate.rent'] = 'Arrendamento exige renda positiva.';
}
if (empty($re['rent_periodicity'])) {
$errors['canonical.real_estate.rent_periodicity'] = 'Indique a periodicidade da renda.';
}
}
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['property_condition'])) {
$errors['canonical.real_estate.property_condition'] = 'Imóvel existente exige condição identificada.';
@@ -438,6 +480,10 @@ class OpportunityCanonicalContract
public function options(User $actor, ?Opportunity $record): array
{
$orgs = array_values(array_unique(array_column(app(PortalProfileAccess::class)->navigation($actor)['contexts'] ?? [], 'organization_id')));
if (! $record && (app(PortalProfileAccess::class)->navigation($actor)['internalPromoter'] ?? false)) {
// A staff creation scope does not expose unrelated private contact lists.
$orgs = [];
}
if ($record?->organization_id) {
$orgs = [$record->organization_id];
}
@@ -451,7 +497,8 @@ class OpportunityCanonicalContract
'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(),
'contacts' => $contacts, 'contactInvestors' => $record?->organization_id ? DB::table('investors')->where('organization_id', $record->organization_id)->whereNull('deleted_at')->whereIn('status', ['prospect', 'active'])->get(['id', 'legal_name']) : [],
'countries' => app(CountryCatalogue::class)->all(),
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
'gates' => $record ? $this->gates($record) : [], 'resources' => $record ? array_combine(['locations', 'documents', 'images'], array_map(fn ($k) => array_values(array_filter(app(OpportunityResources::class)->listing($record->id, $k), fn ($row) => empty($row->deleted_at))), ['locations', 'documents', 'images'])) : []];
}
@@ -0,0 +1,112 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/** Identities and mutation history inside the existing workflow JSON, never parallel tables. */
class OpportunityCanonicalMetadata
{
/** @param array<string,mixed> $payload
* @return array<string,array<string,mixed>> */
private function items(array $payload, string $path = ''): array
{
$found = [];
foreach ($payload as $key => $value) {
$pointer = ltrim($path.'.'.$key, '.');
if (! is_array($value)) {
continue;
}
if (! array_is_list($value)) {
$found[$pointer] = $value;
}
$found += $this->items($value, $pointer);
}
return $found;
}
/** @param array<string,mixed> $before
* @param array<string,mixed> $after
* @param array<string,mixed> $metadata
* @return array<string,mixed> */
public function mutate(array $before, array $after, array $metadata, User $actor, string $reason): array
{
$old = $this->items($before);
$new = $this->items($after);
$active = $metadata['active'] ?? [];
$retired = $metadata['deleted'] ?? [];
$next = [];
$used = [];
foreach ($new as $path => $value) {
$fingerprint = OpportunityCanonicalValue::hash($value);
$match = null;
// A collection reorder preserves identity by bytes, not by its new index.
foreach ($active as $previousPath => $item) {
if (! isset($used[$previousPath]) && ($item['fingerprint'] ?? '') === $fingerprint
&& preg_replace('/\.\d+(?=\.|$)/', '.*', $previousPath) === preg_replace('/\.\d+(?=\.|$)/', '.*', $path)) {
$match = $previousPath;
break;
}
}
// Named singleton modules have a stable path; list rows need an unambiguous match.
if ($match === null && ! preg_match('/\.\d+(?:\.|$)/', $path) && isset($active[$path]) && ! isset($used[$path])) {
$match = $path;
}
$item = $match !== null ? $active[$match] : null;
if ($match !== null) {
$used[$match] = true;
}
$changed = $item === null || ($item['fingerprint'] ?? '') !== $fingerprint;
$legacy = $item === null && isset($old[$path]);
$item ??= ['id' => (string) Str::uuid(), 'version' => 0, 'created_by' => $legacy ? null : $actor->id,
'created_at' => $legacy ? null : now()->toIso8601String(), 'first_observed_at' => now()->toIso8601String(),
'identity_source' => $legacy ? 'legacy_first_observation_not_creation' : 'server_generated_new_item'];
if ($changed) {
$item['version']++;
$item['updated_by'] = $actor->id;
$item['updated_at'] = now()->toIso8601String();
}
$next[$path] = [...$item, 'fingerprint' => $fingerprint, 'is_deleted' => false,
'active' => true, 'deleted_at' => null, 'deleted_by' => null, 'delete_reason' => null];
}
foreach ($active as $path => $item) {
if (isset($used[$path])) {
continue;
}
$retired[$item['id']] = [...$item, 'path' => $path, 'version' => $item['version'] + 1,
'is_deleted' => true, 'active' => false, 'deleted_at' => now()->toIso8601String(),
'deleted_by' => $actor->id, 'delete_reason' => $reason, 'last_value' => $old[$path] ?? null];
}
return ['active' => $next, 'deleted' => $retired, 'rule' => 'existing-json-identities-v1'];
}
/** @param array<string,mixed> $payload
* @param array<string,mixed> $metadata
* @return array<string,mixed> */
public function project(array $payload, array $metadata): array
{
// Deepest paths first so a parent does not overwrite the children's identities.
$paths = array_keys($metadata['active'] ?? []);
foreach ($paths as $path) {
if (! is_string($path)) {
throw new \UnexpectedValueException('Canonical item paths must be named fields.');
}
}
usort($paths, fn ($a, $b) => substr_count($b, '.') <=> substr_count($a, '.'));
foreach ($paths as $path) {
$value = Arr::get($payload, $path);
if (! is_array($value)) {
continue;
}
$item = $metadata['active'][$path];
unset($item['fingerprint']);
Arr::set($payload, $path, [...$value, ...$item]);
}
return $payload;
}
}
+86 -8
View File
@@ -4,11 +4,15 @@ namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Read adapter only: preserve persisted identifiers and make unresolved metadata explicit. */
class OpportunityCanonicalResponse
{
public const VERSION = 'opportunity-response-existing-ids-20261010-1';
public const VERSION = 'opportunity-response-existing-ids-20261011-4';
/** @return array<string,mixed> */
public function read(User $actor, Opportunity $record): array
@@ -17,14 +21,32 @@ class OpportunityCanonicalResponse
$access->authorize($actor, 'view', $record);
$payload = app(OpportunityManagement::class)->values($record)['canonical'] ?? [];
$context = $record->workflow_context ?? [];
$data = [...$payload, 'id' => $record->id, 'opportunity_code' => $record->reference,
$data = [...app(OpportunityCanonicalMetadata::class)->project($payload, $context['canonical_items'] ?? []), 'id' => $record->id, 'opportunity_code' => $record->reference,
'opportunity_category' => $record->opportunity_category, 'status' => $access->state($record),
'version' => (int) $record->management_version, 'is_deleted' => $record->trashed(),
'deleted_at' => $record->deleted_at?->toIso8601String()];
foreach (['submitted' => 'submission', 'approved' => 'approval', 'published' => 'publication'] as $prefix => $key) {
'deleted_at' => $record->deleted_at?->toIso8601String(), ...$this->rootMetadata($record)];
foreach (['submitted' => 'submission', 'approved' => 'approval', 'published' => 'publication', 'archived' => 'archive'] as $prefix => $key) {
$data[$prefix.'_by'] = $context[$key]['actor_id'] ?? null;
$data[$prefix.'_at'] = $context[$key]['at'] ?? null;
}
$completion = app(OpportunityCompleteness::class)->calculate($payload);
$data['completion_percentage'] = $completion['percentage'];
$errors = [];
try {
app(OpportunityCanonicalContract::class)->validateSubmission($record);
} catch (ValidationException $failure) {
$errors = $failure->errors();
} catch (HttpExceptionInterface $failure) {
$errors = ['canonical.resources' => ['Recurso indisponível para validação; estado HTTP '.$failure->getStatusCode().'. Preserve o original e resolva a operação afetada.']];
}
$data['validation_result'] = ['errors' => $errors, 'warnings' => [], 'rule' => OpportunityCanonicalContract::VERSION,
'evaluated_at' => now()->toIso8601String(), 'persisted_submission_hash' => $context['submission']['hash'] ?? null,
'external_decision' => 'not_inferred'];
$mutations = [];
foreach (DB::table('audit_events')->where('source_system', 'opportunity-resources')->where('after_data->opportunity_id', $record->id)->orderBy('occurred_at')->orderBy('id')->get(['actor_user_id', 'action', 'occurred_at', 'after_data']) as $event) {
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
$mutations[$detail['resource_id']][] = ['actor' => $event->actor_user_id, 'action' => $event->action, 'at' => $event->occurred_at, 'reason' => $detail['reason'] ?? null];
}
$references = [];
foreach (OpportunityResources::KINDS as $kind) {
$references[$kind] = $payload[$kind] ?? [];
@@ -34,7 +56,7 @@ class OpportunityCanonicalResponse
$rows[$row->id] = $row;
}
}
$data[$kind] = array_map(function (string $id) use ($rows, $kind): array {
$data[$kind] = array_map(function (string $id) use ($rows, $kind, $mutations): array {
$row = $rows[$id] ?? null;
if ($row === null) {
return ['id' => $id, 'availability' => 'unavailable'];
@@ -42,6 +64,13 @@ class OpportunityCanonicalResponse
$value = [...$row->payload, 'id' => $row->id, 'version' => (int) $row->version,
'is_deleted' => $row->deleted_at !== null, 'deleted_at' => $row->deleted_at,
'created_by' => $row->created_by, 'created_at' => $row->created_at, 'updated_at' => $row->updated_at];
$events = $mutations[$id] ?? [];
$last = $events ? $events[array_key_last($events)] : null;
$deletion = $row->deleted_at && ($last['action'] ?? '') === 'delete' ? $last : null;
$value['updated_by'] = $last['actor'] ?? ((int) $row->version === 1 ? $row->created_by : null);
$value['deleted_by'] = $deletion['actor'] ?? null;
$value['delete_reason'] = $deletion && $deletion['reason'] ? Crypt::decryptString($deletion['reason']) : null;
$value['mutation_metadata_source'] = $last ? 'existing_audit_events' : 'creation_record_only';
if ($kind !== 'locations') {
$value['original_name'] = $row->file?->file_name;
$value['mime_type'] = $row->file?->media_type;
@@ -56,15 +85,64 @@ class OpportunityCanonicalResponse
return ['adapter_version' => self::VERSION,
'source_schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
'data' => $data, 'resource_references' => $references,
'validation_result' => ['scope' => 'recorded_submission_only', 'submission_hash' => $context['submission']['hash'] ?? null,
'completion' => $completion, 'materiality' => $context['materiality'] ?? null,
'review_conditions' => array_values($context['conditions'] ?? []),
'deleted_inline_items' => array_values($context['canonical_items']['deleted'] ?? []),
'validation_result' => ['scope' => 'current_payload_validation_and_recorded_submission_metadata', 'submission_hash' => $context['submission']['hash'] ?? null,
'submitted_content_revision' => $context['submission']['content_revision'] ?? null,
'current_content_revision' => $context['content_revision'] ?? 1,
'revalidated_on_read' => false, 'external_decision' => 'not_inferred'],
'revalidated_on_read' => true, 'external_decision' => 'not_inferred'],
'publication' => $record->publicationPresentation(),
'compatibility' => ['normative_response_complete' => false, 'opportunity_actor_sector_ids' => 'existing bigint, not converted to UUID',
'modular_decision' => 'Functional approval of four modular contracts and SLA remains pending; legacy integration did not approve them. Historical snapshot annotations are preserved, not current approvals.',
'opportunity_code' => 'existing reference preserved; no INV-MZ code invented',
'states' => 'existing workflow values preserved; no implicit stage equivalence',
'inline_modules' => 'management_draft canonical JSON with audited revisions; no parallel specialized tables',
'metadata_gaps' => ['completion_percentage algorithm', 'inline item IDs and mutation metadata', 'resource updated_by/deleted_by recovery']]];
'state_correspondence' => ['draft' => 'draft', 'needs_information' => 'returned', 'submitted' => 'submitted', 'approved' => 'approved', 'published' => 'published', 'suspended' => 'suspended', 'archived' => 'archived', 'rejected' => 'rejected'],
'unmapped_review_states' => 'in_review/information_pending preserve parallel gates; no single normative stage inferred',
'metadata_gaps' => ['Legacy inline creation metadata can be unknown; first observation is not creation. Ambiguous changed collection rows get new identities with previous identities retained as deleted.', 'Existing bigint IDs remain explicit compatibility differences; no renumbering.']]];
}
/**
* Recover actors from existing audited versions; an imported creator must never be inferred.
*
* @return array<string,mixed>
*/
private function rootMetadata(Opportunity $record): array
{
$events = [];
foreach (DB::table('audit_events')->whereIn('source_system', ['opportunity-management', 'portal-profiles-v1'])
->where('after_data->record_id', $record->id)->get(['source_system', 'actor_user_id', 'action', 'after_data']) as $event) {
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
$version = $detail['version'] ?? $detail['after']['version'] ?? null;
if (! is_int($version)) {
continue;
}
$events[$version] = ['actor' => $event->actor_user_id, 'action' => $event->action,
'reason' => $detail['reason'] ?? null, 'encrypted_reason' => $event->source_system === 'opportunity-management'];
}
ksort($events);
$creation = null;
$deletion = null;
foreach ($events as $event) {
if ($event['action'] === 'draft_created') {
$creation = $event;
}
if ($event['action'] === 'delete') {
$deletion = $event;
}
}
$latest = $events[(int) $record->management_version] ?? null;
$deletion = $record->trashed() ? $deletion : null;
return ['created_by' => $creation['actor'] ?? null, 'created_at' => $record->created_at?->toIso8601String(),
'updated_by' => $latest['actor'] ?? null, 'updated_at' => $record->updated_at?->toIso8601String(),
'deleted_by' => $deletion['actor'] ?? null,
'delete_reason' => $deletion && $deletion['reason'] ? ($deletion['encrypted_reason'] ? Crypt::decryptString($deletion['reason']) : $deletion['reason']) : null,
'mutation_metadata_source' => 'existing_audit_events_and_record_timestamps',
'mutation_metadata_gaps' => array_values(array_filter([
$creation === null ? 'No recorded creation actor; imported ownership does not establish creation.' : null,
$latest === null ? 'No audit actor matching the current management version; no updater inferred.' : null,
]))];
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Services;
/** Normalize object key order only. Ordered coordinates and lists retain their meaning. */
class OpportunityCanonicalValue
{
public static function hash(mixed $value): string
{
return hash('sha256', json_encode(self::normalize($value), JSON_THROW_ON_ERROR));
}
private static function normalize(mixed $value): mixed
{
if (! is_array($value)) {
return $value;
}
$result = array_map(self::normalize(...), $value);
if (! array_is_list($result)) {
ksort($result);
}
return $result;
}
}
@@ -61,6 +61,9 @@ class OpportunityCategoryFields
foreach (['markets' => 'marketCreate', 'risks' => 'riskCreate', 'licenses' => 'licenseCreate', 'milestones' => 'milestoneCreate'] as $field => $def) {
$common[$field]['items'] = ['$ref' => '#/$defs/'.$def];
}
// Reuse the existing canonical object definition in both editor and validation.
// The extracted Create property was opaque, preventing completion through the UI.
$common['environmental_social'] = ['$ref' => '#/$defs/environmentalSocialCreate'];
$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];
@@ -219,7 +222,11 @@ class OpportunityCategoryFields
}
$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.');
$communityKeys = [];
foreach ($lr['communities'] ?? [] as $i => $row) {
$key = json_encode([$row['name'] ?? null, $row['location_id'] ?? null]);
$fail(! isset($communityKeys[$key]), "land_rights.communities.$i.name", 'A mesma comunidade/localização já está incluída (§27).');
$communityKeys[$key] = true;
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.');
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Services;
use Opis\JsonSchema\Validator;
/** Transparent field completion, separate from validation, approval and external decisions. */
class OpportunityCompleteness
{
/** @param array<string,mixed> $payload
* @return array<string,mixed> */
public function calculate(array $payload): array
{
$schema = app(OpportunityCanonicalContract::class)->schema();
$validator = new Validator;
$paths = [];
$walk = function (mixed $value, array $node, string $path) use (&$walk, &$paths, $schema, $validator): void {
if (isset($node['$ref'])) {
$node = $schema['$defs'][basename($node['$ref'])] ?? $node;
}
$requirements = $node['required'] ?? [];
foreach ($node['allOf'] ?? [] as $condition) {
if (! isset($condition['if'])) {
$walk($value, $condition, $path);
continue;
}
$test = $condition['if'];
if (str_contains(json_encode($test, JSON_THROW_ON_ERROR), '#/$defs/')) {
$test['$defs'] = $schema['$defs'];
}
$actual = json_decode(json_encode(is_array($value) && ! array_is_list($value) ? (object) $value : $value, JSON_THROW_ON_ERROR), false, 512, JSON_THROW_ON_ERROR);
$yes = $validator->validate($actual, json_decode(json_encode($test, JSON_THROW_ON_ERROR), false, 512, JSON_THROW_ON_ERROR))->isValid();
$walk($value, $condition[$yes ? 'then' : 'else'] ?? [], $path);
}
foreach ($requirements as $key) {
$v = is_array($value) ? ($value[$key] ?? null) : null;
$paths[ltrim($path.'.'.$key, '.')] = $v !== null && $v !== '' && $v !== [];
}
foreach ($node['properties'] ?? [] as $key => $child) {
if (is_array($value) && array_key_exists($key, $value)) {
$walk($value[$key], $child, ltrim($path.'.'.$key, '.'));
}
}
if (isset($node['items']) && is_array($value) && array_is_list($value)) {
foreach ($value as $i => $child) {
$walk($child, $node['items'], $path.'.'.$i);
}
}
};
$walk($payload, ['$ref' => '#/$defs/opportunityCreate'], '');
$filled = count(array_filter($paths));
$total = count($paths);
return ['percentage' => $total ? round(100 * $filled / $total, 2) : 0, 'filled' => $filled, 'applicable' => $total,
'missing_paths' => array_keys(array_filter($paths, fn ($filled) => ! $filled)),
'rule' => 'required-applicable-fields-v1', 'scope' => 'Required fields and activated schema conditions; optional/hidden modules excluded. Presence is not validation or approval.'];
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace App\Services;
use App\Models\Contact;
use App\Models\Investor;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Reuse the CRM master without manufacturing an interest, lead or consent. */
class OpportunityContacts
{
public function save(User $actor, int $id, array $input): array
{
$access = app(PortalProfileAccess::class);
$record = Opportunity::withTrashed()->findOrFail($id);
$access->authorize($actor, 'edit', $record);
abort_unless($access->mfa($actor), 403, 'Confirme a autenticação multifator nesta sessão.');
$data = Validator::make($input, [
'etag' => 'required|string|size:64',
'full_name' => 'required|string|min:2|max:150',
'email' => 'required|email:rfc|max:150',
'phone' => ['required', 'regex:/^\+[1-9]\d{7,14}$/'],
'investor_id' => 'nullable|uuid',
'investor_type' => ['nullable', Rule::in(['domestic', 'foreign', 'institutional', 'individual'])],
])->validate();
$data['email'] = strtolower(trim($data['email']));
$data['full_name'] = trim(preg_replace('/\s+/u', ' ', $data['full_name']));
return DB::transaction(function () use ($actor, $id, $data, $access) {
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
$access->authorize($actor, 'edit', $record);
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409, 'A oportunidade mudou. Recupere a versão atual antes de cadastrar o contacto.');
DB::select('SELECT pg_advisory_xact_lock(170925, hashtext(?))', [$data['email']]);
$matches = Contact::withTrashed()->whereRaw('lower(trim(email)) = ?', [$data['email']])->lockForUpdate()->get();
$scoped = function (Contact $contact) use ($record): bool {
return $record->organization_id
? DB::table('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
->where('ic.contact_id', $contact->id)->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at')->exists()
: $contact->source_system === 'portal-user-contact' && $contact->external_id === 'user:'.$record->owner_user_id;
};
if ($matches->isNotEmpty()) {
$contact = $matches->first(fn ($row) => ! $row->trashed() && $scoped($row));
if ($matches->count() !== 1 || ! $contact || $contact->full_name !== $data['full_name'] || $contact->phone !== $data['phone']) {
throw ValidationException::withMessages(['email' => 'Não foi possível reutilizar este contacto neste âmbito. Escolha um contacto autorizado existente ou reconcilie os dados no cadastro mestre; nenhum registo foi alterado.']);
}
return ['contact' => $contact->only(['id', 'full_name']), 'reused' => true, 'message' => 'Contacto existente recuperado, sem duplicação. Guarde a seleção no rascunho.'];
}
$investor = null;
if ($record->organization_id) {
DB::select('SELECT pg_advisory_xact_lock(170926, hashtext(?))', [$record->organization_id]);
$investors = Investor::where('organization_id', $record->organization_id)->whereIn('status', ['prospect', 'active'])->lockForUpdate()->get();
if (! empty($data['investor_id'])) {
$investor = $investors->firstWhere('id', $data['investor_id']);
abort_unless($investor, 403, 'O cadastro selecionado não pertence ao promotor desta oportunidade.');
} elseif ($investors->count() === 1) {
$investor = $investors->first();
} elseif ($investors->count() > 1) {
throw ValidationException::withMessages(['investor_id' => 'Selecione o cadastro mestre do promotor; não será criada outra entidade.']);
} else {
if (empty($data['investor_type'])) {
throw ValidationException::withMessages(['investor_type' => 'Indique a classificação do promotor no cadastro existente.']);
}
$organization = DB::table('organizations')->where('id', $record->organization_id)->whereNull('deleted_at')->first();
abort_unless($organization, 422, 'Organização indisponível.');
$investor = new Investor;
PortalAudit::save($investor, ['organization_id' => $organization->id, 'legal_name' => $organization->name,
'investor_type' => $data['investor_type'], 'status' => 'prospect', 'source_system' => 'portal-promoter-master',
'external_id' => 'organization:'.$organization->id], $actor->id);
}
} else {
abort_unless(empty($data['investor_id']) && empty($data['investor_type']), 422);
}
$contact = new Contact;
PortalAudit::save($contact, ['full_name' => $data['full_name'], 'email' => $data['email'], 'phone' => $data['phone'],
'source_system' => $record->organization_id ? 'portal-promoter-contact' : 'portal-user-contact',
'external_id' => $record->organization_id ? null : 'user:'.$record->owner_user_id,
'data_classification' => 'internal'], $actor->id);
if ($investor) {
DB::table('investor_contacts')->insertOrIgnore(['investor_id' => $investor->id, 'contact_id' => $contact->id, 'is_primary' => false]);
}
$access->audit($actor, 'opportunity_contact_registered', ['record_id' => $id, 'contact_id' => $contact->id,
'organization_id' => $record->organization_id, 'investor_id' => $investor?->id, 'automatically_published' => false]);
return ['contact' => $contact->only(['id', 'full_name']), 'reused' => false, 'message' => 'Contacto guardado no cadastro existente. Guarde a seleção no rascunho; não foi publicado.'];
});
}
}
@@ -41,6 +41,33 @@ class OpportunityImageProcessor
abort_unless(hash_equals(trim($doc->sha256), hash('sha256', $bytes)), 409, 'Integridade divergente.');
$size = @getimagesizefromstring($bytes);
abort_unless($size && $size[0] >= 400 && $size[1] >= 400 && $size[0] * $size[1] <= 40000000, 422, 'Dimensões inválidas ou imagem excessiva para processamento seguro.');
$previousPayload = json_decode($image->payload, true, 512, JSON_THROW_ON_ERROR);
$previousDerivatives = $previousPayload['derivatives'] ?? [];
$expectedWidths = array_unique(array_map(fn ($width) => min($width, $size[0]), [320, 640, 1280]));
if (($previousPayload['derived_from_sha256'] ?? null) === trim($doc->sha256)
&& array_values(array_column($previousDerivatives, 'width')) === array_values($expectedWidths)) {
$reusable = true;
$retry = [];
foreach ($previousDerivatives as $derivative) {
$existing = DB::table('documents')->where('id', $derivative['document_id'])->whereNull('deleted_at')->first();
if (! $existing || $existing->source_system !== 'opportunity-image-derivatives' || ! $disk->exists($existing->storage_key)) {
$reusable = false;
break;
}
$existingBytes = Crypt::decryptString($disk->get($existing->storage_key));
if (! hash_equals(trim($existing->sha256), hash('sha256', $existingBytes))) {
$reusable = false;
break;
}
if ($existing->malware_scan_status !== 'clean') {
$retry[] = $existing->id;
}
}
if ($reusable) {
$documents = $retry;
return; // Retry scans of the same streams, without new files, versions or audit decisions.
}
}
$decoded = @imagecreatefromstring($bytes);
abort_unless($decoded !== false, 422, 'Não foi possível descodificar a imagem.');
$derivatives = [];
+21 -2
View File
@@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
@@ -64,6 +65,15 @@ class OpportunityManagement
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.');
// Canonical common fields are authoritative. The editor may echo legacy
// mirrors, but they must not impose a second, incompatible contract.
if (is_array($input['canonical'] ?? null)) {
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, $input['canonical'])) {
unset($input[$target]);
}
}
}
$data = Validator::make($input, [
'etag' => [$id ? 'required' : 'nullable', 'string', 'size:64'],
'creation_key' => [$id ? 'nullable' : 'required', 'uuid'],
@@ -115,6 +125,7 @@ class OpportunityManagement
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
}
$before = $record->getAttributes();
$previousCanonical = $record->exists ? ($this->values($record)['canonical'] ?? []) : [];
$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) : [];
@@ -125,7 +136,10 @@ class OpportunityManagement
// 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];
$value = $changes['canonical'][$source];
// Preserve the full text in canonical JSON; the legacy
// summary column is only a bounded presentation mirror.
$changes[$target] = $target === 'summary' && is_string($value) ? Str::limit($value, 499, '…') : $value;
}
}
}
@@ -156,6 +170,9 @@ class OpportunityManagement
$record->owner_user_id = $actor->id;
$record->organization_id = $data['organization_id'] ?? null;
$record->workflow_context = ['policy_version' => PortalProfileAccess::VERSION, 'contributors' => [$actor->id]];
if (($internal=$access->internalAssignment($actor,$data['opportunity_category'] ?? '')) !== null) {
$record->workflow_context=[...$record->workflow_context,'operator_organization_id'=>$internal->organization_id,'internal_assignment_id'=>$internal->id];
}
}
} else {
$record->management_version++;
@@ -179,9 +196,11 @@ class OpportunityManagement
}
if ($record->owner_user_id !== null) {
$context = $record->workflow_context ?? [];
unset($context['approval'], $context['reviews']);
unset($context['approval']);
$context['content_revision'] = ($context['content_revision'] ?? 0) + 1;
$context['contributors'] = array_values(array_unique([...($context['contributors'] ?? []), $actor->id]));
$context['canonical_items'] = app(OpportunityCanonicalMetadata::class)->mutate(
$previousCanonical, $this->values($record)['canonical'] ?? [], $context['canonical_items'] ?? [], $actor, $data['reason']);
$record->workflow_context = $context;
}
$record->save();
@@ -21,6 +21,7 @@ class OpportunityManagementInstallation
$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));
}
+99 -11
View File
@@ -22,7 +22,7 @@ class OpportunityProfileWorkflow
}
$actions = [];
$state = $this->access->state($record);
if ($this->access->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category)
if ($this->access->promoterRecordScope($actor, $record)
&& ($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)) {
@@ -40,6 +40,9 @@ class OpportunityProfileWorkflow
}
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 === 'approved' && count(array_filter($record->workflow_context['conditions'] ?? [], fn ($condition) => $condition['status'] === 'open' && $condition['blocking_action'] === 'publish')) > 0) {
$actions[] = 'review_gate';
}
if ($state === 'submitted') {
$actions[] = 'start_review';
}
@@ -93,10 +96,14 @@ class OpportunityProfileWorkflow
{
$this->access->authorize($actor, 'view', $record);
if (! $this->access->has($actor, 'validator') && ! $this->access->has($actor, 'publisher')) {
return ['validators' => [], 'publishers' => []];
return ['validators' => [], 'publishers' => [], 'condition_responsibles' => []];
}
$result = ['validators' => [], 'publishers' => []];
$result = ['validators' => [], 'publishers' => [], 'condition_responsibles' => []];
foreach (User::whereNotNull('email_verified_at')->whereNotNull('two_factor_confirmed_at')->get() as $candidate) {
if ($this->access->canView($candidate, $record) && (($this->access->promoterRecordScope($candidate, $record) && $this->access->operational($candidate, 'edit', $record->id))
|| ($this->access->scoped($candidate, 'validator', $record->organization_id, $record->opportunity_category) && $this->access->operational($candidate, 'validate', $record->id)))) {
$result['condition_responsibles'][] = ['id' => $candidate->id, 'name' => $candidate->name];
}
if ($this->access->conflict($candidate, $record)) {
continue;
}
@@ -138,8 +145,17 @@ class OpportunityProfileWorkflow
'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',
'condition' => 'sometimes|array:description,responsible_user_id,due_on,blocking_action',
'condition.description' => 'required_with:condition|string|min:10|max:1000',
'condition.responsible_user_id' => 'required_with:condition|integer|min:1',
'condition.due_on' => 'sometimes|nullable|date_format:Y-m-d',
'condition.blocking_action' => 'required_with:condition|in:approve,publish',
'resolve_condition_ids' => 'sometimes|array', 'resolve_condition_ids.*' => 'uuid|distinct',
])->validate();
$action = $data['action'];
if ($action !== 'review_gate' && (isset($data['condition']) || ! empty($data['resolve_condition_ids']))) {
throw ValidationException::withMessages(['condition' => 'Condições só podem ser verificadas numa revisão especializada autorizada.']);
}
$this->authorizeAction($actor, $record, $action);
return DB::transaction(function () use ($actor, $id, $data, $action) {
@@ -151,7 +167,8 @@ class OpportunityProfileWorkflow
$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'],
'request_correction', 'pending_opinion', 'respond_opinion', 'reject', 'approve', 'assign_review' => ['submitted', 'in_review', 'information_pending'],
'review_gate' => ['submitted', 'in_review', 'information_pending', 'approved'],
'publish' => ['approved'], 'suspend' => [$state],
'assign_publication' => ['approved'],
'request_revision' => ['approved', 'published', 'suspended'],
@@ -163,24 +180,52 @@ class OpportunityProfileWorkflow
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];
if (isset($context['review_cycle'])) {
$decision['review_cycle'] = $context['review_cycle'];
}
$next = $state;
$snapshot = [];
if ($action === 'submit' && $record->opportunity_category === 'land_rights') {
// Serialize the existing JSON-backed §27 uniqueness check across records.
DB::select('SELECT pg_advisory_xact_lock(111026,270000)');
}
if (in_array($action, ['submit', 'review_gate', 'pending_opinion', 'respond_opinion', 'approve', 'publish'], true)) {
$snapshot = $this->contract->validateSubmission($record);
$blockers = $this->contract->deliveryBlockers($this->management->values($record)['canonical'] ?? []);
try {
$snapshot = $this->contract->validateSubmission($record);
} catch (ValidationException $error) {
$errors = $error->errors();
foreach ($blockers as $field => $message) {
$errors[$field][] = $message;
}
throw ValidationException::withMessages($errors);
}
if ($blockers !== []) {
throw ValidationException::withMessages($blockers);
}
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') {
// New review attempt, even when the canonical content is unchanged.
// Historical decisions/tasks and the content revision keep their IDs.
$context['review_cycle'] = max((int) ($context['review_cycle'] ?? 0), $this->submissionCount($context)) + 1;
$decision['review_cycle'] = $context['review_cycle'];
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.');
}
}
$baseline = $context['review_baseline'] ?? $context['submission'] ?? [];
$materiality = app(OpportunityReviewMateriality::class)->reconcile($baseline, $snapshot, $context['reviews'] ?? [], $this->contract->gates($record), ! empty($context['force_review']));
$context['materiality'] = array_diff_key($materiality, ['reviews' => true]);
$context['reviews'] = $materiality['reviews'];
app(OpportunityReviewConditions::class)->reconcile($context, $snapshot, $materiality['reopened']);
$context['submission'] = [...$snapshot, ...$decision];
$context['sla'] = ['policy_version' => null, 'due_at' => null, 'status' => 'unconfigured'];
unset($context['approval'], $context['reviews'], $context['assignment'],$context['publication_assignment']);
unset($context['approval'], $context['assignment'], $context['publication_assignment'], $context['review_baseline'], $context['force_review']);
$record->first_submitted_at ??= now()->toIso8601String();
$record->management_closed_once = true;
$record->workflow_context = $context;
@@ -192,11 +237,25 @@ class OpportunityProfileWorkflow
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.');
if ($this->tasks->closedReviewBinding($record, $context['review_task_id'] ?? null)) {
// Recover only a completed task of this opportunity in an
// already submitted legacy attempt. Never reopen/delete it.
$oldTask = $context['review_task_id'];
$context['review_cycle'] = max(1, (int) ($context['review_cycle'] ?? 0), $this->submissionCount($context));
$record->workflow_context = $context;
$context['review_task_id'] = $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
$context['review_task_binding_history'][] = ['previous_task_id' => $oldTask, 'task_id' => $context['review_task_id'],
'review_cycle' => $context['review_cycle'], 'at' => now()->toIso8601String(), 'reason' => 'Completed legacy review binding replaced for the current submission; original preserved.'];
$decision['review_cycle'] = $context['review_cycle'];
}
$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') {
if ($state === 'approved') {
throw_unless(! empty($data['resolve_condition_ids']) && empty($data['condition']) && ($data['gate_decision'] ?? '') === 'approved', ValidationException::withMessages(['resolve_condition_ids' => 'Após aprovação, só verificar condições de publicação existentes; alterações exigem nova revisão.']));
}
$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;
@@ -204,14 +263,19 @@ class OpportunityProfileWorkflow
$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.');
app(OpportunityReviewConditions::class)->review($record, $actor, $data, $snapshot, $context);
$context['reviews'][$gate] = [...$decision, 'decision' => $data['gate_decision'], 'hash' => $snapshot['hash'], 'evidence_document_ids' => $documents];
$context['reviews'][$gate]['scope_hash'] = app(OpportunityReviewMateriality::class)->hash($snapshot, $gate, $context['reviews'][$gate]);
$context['reviews'][$gate]['scope_rule'] = OpportunityReviewMateriality::VERSION;
$next = 'in_review';
} elseif ($action === 'approve') {
app(OpportunityReviewConditions::class)->authorize($context, $snapshot, '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.');
abort_unless(($review['decision'] ?? null) === 'approved' && (($review['hash'] ?? '') === $snapshot['hash'] || ($review['accepted_submission_hash'] ?? '') === $snapshot['hash']), 422, 'Gate '.$gate.' pendente, rejeitado ou de outra versão.');
abort_unless(app(OpportunityReviewMateriality::class)->matches($snapshot, $gate, $review), 409, 'Âmbito da revisão alterado.');
$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)
@@ -229,13 +293,14 @@ class OpportunityProfileWorkflow
$this->tasks->assign($record, $context['publication_task_id'], $subject);
$context['publication_assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
} elseif ($action === 'publish') {
app(OpportunityReviewConditions::class)->authorize($context, $snapshot, '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.');
abort_unless(($review['decision'] ?? null) === 'approved' && (($review['hash'] ?? '') === $snapshot['hash'] || ($review['accepted_submission_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)
@@ -312,7 +377,9 @@ class OpportunityProfileWorkflow
$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']);
$context['review_baseline'] = $context['submission'] ?? [];
$context['force_review'] = $action === 'appeal_reopen' || $state === 'suspended';
unset($context['approval']);
$next = 'needs_information';
} elseif ($action === 'request_archive') {
$context['request_archive'] = $decision;
@@ -330,6 +397,9 @@ class OpportunityProfileWorkflow
$context['rejection'] = $decision;
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
}
if ($action === 'archive') {
$context['archive'] = $decision;
}
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) {
@@ -343,7 +413,10 @@ class OpportunityProfileWorkflow
$this->tasks->complete($context['appeal_task_id'] ?? null, $data['reason']);
}
if (in_array($action, ['request_correction', 'reject'], true)) {
unset($context['approval'], $context['reviews']);
if ($action === 'reject') {
$context['force_review'] = true;
}
unset($context['approval']);
}
if (in_array($action, ['request_correction', 'reject', 'suspend', 'archive', 'request_revision', 'appeal_reopen'], true)) {
foreach ($context['opinions'] ?? [] as $opinionId => $opinion) {
@@ -369,6 +442,21 @@ class OpportunityProfileWorkflow
});
}
/** @param array<array-key, mixed> $context */
private function submissionCount(array $context): int
{
$events = $context['events'] ?? [];
abort_unless(is_array($events), 409, 'Histórico de submissões inconsistente; preservar e recuperar antes de continuar.');
$count = 0;
foreach ($events as $event) {
if (is_array($event) && ($event['action'] ?? null) === 'submit') {
$count++;
}
}
return $count;
}
private function responsibility(User $actor, Opportunity $record, string $name): bool
{
foreach ($this->access->grants($actor, $name === 'publication_coordinator' ? 'publisher' : 'validator') as $grant) {
@@ -385,7 +473,7 @@ class OpportunityProfileWorkflow
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)
$promoter = $this->access->promoterRecordScope($actor, $record)
&& ($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);
@@ -35,7 +35,9 @@ class OpportunityResourceInstallation
$files = [...$files, resource_path('js/lib/portal-navigation.ts'), resource_path('js/components/portal-grouped-menu.tsx')];
$files = [...$files, ...PortalProfileAccess::fingerprintFiles()];
$files = [...$files, ...PortalProfileAccess::fingerprintFiles(), app_path('Services/OrganizationCountry.php'), app_path('Services/OrganizationCountryInstallation.php'),
database_path('migrations/2026_10_10_050000_extend_organization_country.php'), base_path('routes/investment.php')];
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}
@@ -0,0 +1,90 @@
<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/** Explicit internal review conditions in the existing workflow JSON and audit. */
class OpportunityReviewConditions
{
/** @param array<string,mixed> $data
* @param array<string,mixed> $snapshot
* @param array<string,mixed> $context */
public function review(Opportunity $record, User $actor, array $data, array $snapshot, array &$context): void
{
$gate = $data['gate'];
foreach ($data['resolve_condition_ids'] ?? [] as $id) {
$condition = $context['conditions'][$id] ?? null;
$this->require($condition !== null && $condition['gate'] === $gate && $condition['status'] === 'open', 'resolve_condition_ids', 'Selecione uma condição aberta desta revisão.');
$this->require(($data['gate_decision'] ?? '') === 'approved', 'gate_decision', 'A resolução exige verificação interna aprovada com evidência.');
$documents = [];
foreach ($data['evidence_document_ids'] ?? [] as $documentId) {
$documents[$documentId] = $snapshot['resources']['documents'][$documentId]['sha256'];
}
$this->require($documents !== [], 'evidence_document_ids', 'A resolução exige documento ativo e analisado desta oportunidade.');
$context['conditions'][$id]['status'] = 'resolved';
$context['conditions'][$id]['resolution'] = ['actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'], 'document_hashes' => $documents, 'content_revision' => $context['content_revision'] ?? 1, 'scope' => 'internal_verification_not_external_decision'];
}
if (! empty($data['condition'])) {
$input = $data['condition'];
$subject = User::query()->whereKey($input['responsible_user_id'])->first();
$access = app(PortalProfileAccess::class);
$this->require($subject !== null && $access->canView($subject, $record)
&& (($access->scoped($subject, 'promoter', $record->organization_id, $record->opportunity_category) && $access->operational($subject, 'edit', $record->id))
|| ($access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category) && $access->operational($subject, 'validate', $record->id))),
'condition.responsible_user_id', 'Selecione um responsável autorizado neste âmbito; não atribua responsabilidade externa.');
$id = (string) Str::uuid();
$context['conditions'][$id] = ['id' => $id, 'gate' => $gate, 'description' => $input['description'], 'responsible_user_id' => $subject->id,
'responsible_name' => $subject->name, 'due_on' => $input['due_on'] ?? null, 'blocking_action' => $input['blocking_action'],
'status' => 'open', 'created_by' => $actor->id, 'created_at' => now()->toIso8601String(), 'scope' => 'internal_review_condition', 'resolution_history' => []];
}
}
/** @param array<string,mixed> $context
* @param array<string,mixed> $snapshot
* @param list<string> $reopened */
public function reconcile(array &$context, array $snapshot, array $reopened): void
{
foreach ($context['conditions'] ?? [] as $id => $condition) {
if ($condition['status'] !== 'resolved') {
continue;
}
$matches = ! in_array($condition['gate'], $reopened, true);
foreach ($condition['resolution']['document_hashes'] ?? [] as $documentId => $sha) {
$matches = $matches && ($snapshot['resources']['documents'][$documentId]['sha256'] ?? null) === $sha;
}
if (! $matches) {
$context['conditions'][$id]['resolution_history'][] = $condition['resolution'];
unset($context['conditions'][$id]['resolution']);
$context['conditions'][$id]['status'] = 'open';
$context['conditions'][$id]['reopened_at'] = now()->toIso8601String();
}
}
}
/** @param array<string,mixed> $context
* @param array<string,mixed> $snapshot */
public function authorize(array $context, array $snapshot, string $action): void
{
foreach ($context['conditions'] ?? [] as $condition) {
if ($action === 'approve' && $condition['blocking_action'] !== 'approve') {
continue;
}
$resolved = $condition['status'] === 'resolved';
foreach ($condition['resolution']['document_hashes'] ?? [] as $id => $sha) {
$resolved = $resolved && ($snapshot['resources']['documents'][$id]['sha256'] ?? null) === $sha;
}
$this->require($resolved, 'conditions.'.$condition['id'], 'Condição pendente: '.$condition['description'].'. Responsável: '.$condition['responsible_name'].'. Prazo: '.($condition['due_on'] ?? 'não definido').'.');
}
}
private function require(bool $ok, string $field, string $message): void
{
if (! $ok) {
throw ValidationException::withMessages([$field => $message]);
}
}
}
@@ -0,0 +1,166 @@
<?php
namespace App\Services;
use Illuminate\Support\Arr;
/** §28.1: preserve signed decisions; only changed review scopes need new decisions. */
class OpportunityReviewMateriality
{
public const VERSION = 'review-scopes-20261011-v3';
public const PREVIOUS_VERSION = 'review-scopes-20261011-v2';
/** @param array<string,mixed> $snapshot
* @return array<string,mixed> */
private function scope(array $snapshot, string $gate, bool $extended = true): array
{
$p = $snapshot['payload'] ?? [];
$common = ['opportunity_category', 'promoter_id', 'promoter_type', 'sector_id', 'subsector_id', 'economic_activity_id', 'demand_statement', 'executive_summary'];
$fields = match ($gate) {
'property_review' => ['real_estate.property_type', 'real_estate.land_area', 'real_estate.built_area', 'real_estate.area_unit', 'real_estate.units', 'real_estate.occupancy_status', 'real_estate.price', 'real_estate.rent', 'real_estate.rent_periodicity', 'real_estate.valuation', 'real_estate.utilities'],
'registry_urban_review' => ['real_estate.transaction_type', 'real_estate.title_type', 'real_estate.registration_number', 'real_estate.encumbrances', 'real_estate.land_area', 'real_estate.area_unit'],
'building_compliance_review' => ['real_estate.construction_status', 'real_estate.property_condition', 'real_estate.built_area', 'real_estate.floors', 'real_estate.planning_permit_document_id', 'real_estate.use_license_document_id'],
'cadastral_screening' => ['land_rights.parcels', 'land_rights.overlaps_conflicts'],
'land_legal_review' => ['land_rights.operation_type', 'land_rights.duat_status', 'land_rights.duat_number', 'land_rights.holder_id', 'land_rights.holder_name', 'land_rights.issuing_authority_id', 'land_rights.issue_date', 'land_rights.expiry_date', 'land_rights.authorized_purpose', 'land_rights.improvements', 'land_rights.consideration'],
'community_environment_review' => ['land_rights.communities', 'land_rights.community_consultation', 'environmental_social'],
'competent_authority_clearance' => ['land_rights.required_authorizations', 'land_rights.exploitation_plan_document_id', 'land_rights.authorized_purpose'],
'corporate_screening' => ['business_transaction.legal_entity_id', 'business_transaction.legal_form', 'business_transaction.beneficial_owners', 'business_transaction.percentage_offered'],
'financial_review' => ['business_transaction.asking_price', 'business_transaction.valuation', 'business_transaction.financial_periods', 'business_transaction.assets_liabilities', 'business_transaction.employees', 'business_transaction.partner_contribution'],
'legal_tax_due_diligence' => ['business_transaction.transaction_type', 'business_transaction.percentage_offered', 'business_transaction.contracts_licenses', 'business_transaction.litigation_contingencies', 'business_transaction.governance_rights', 'business_transaction.franchise_terms', 'business_transaction.tax_labor_compliance'],
'partnership_governance_review' => ['business_transaction.percentage_offered', 'business_transaction.partner_contribution', 'business_transaction.governance_rights'],
'brand_license_review' => ['business_transaction.franchise_terms', 'business_transaction.contracts_licenses'],
'franchise_legal_review' => ['business_transaction.franchise_terms', 'business_transaction.contracts_licenses', 'business_transaction.litigation_contingencies'],
'confidentiality_clearance' => ['visibility', 'publish_contact', 'public_contact_id', 'business_transaction.confidentiality_level', 'business_transaction.teaser', 'business_transaction.nda_document_id', 'business_transaction.data_room_index_document_id'],
'technical_review' => ['demand_statement', 'opportunity_type', 'maturity_stage', 'investment_modalities', 'investor_profiles', 'products', 'assets', 'inputs', 'markets', 'competitive_advantage', 'employment', 'impact_indicators', 'total_investment', 'currency', 'investment_breakdown', 'secured_financing', 'funding_sought', 'financial_indicators', 'milestones', 'risks'],
'legal_territorial_review' => ['licenses', 'environmental_social', 'relations', 'truth_declaration'],
// Experimental modules have no approved scope contract: never carry their decisions.
default => array_keys($p),
};
if ($extended) {
$fields = [...$fields, ...match ($gate) {
'land_legal_review' => ['land_rights.holder_document_id', 'land_rights.area_unit'],
'community_environment_review' => ['land_rights.communities_affected'],
'competent_authority_clearance' => ['land_rights.exploitation_plan_required'],
'corporate_screening' => ['business_transaction.entity_registration'],
'financial_review' => ['business_transaction.available_financial_years', 'business_transaction.history_status', 'business_transaction.history_declaration', 'business_transaction.history_declaration_document_id', 'business_transaction.projections'],
'franchise_legal_review' => ['business_transaction.legal_entity_id', 'business_transaction.legal_form', 'business_transaction.beneficial_owners', 'business_transaction.entity_registration', 'business_transaction.governance_rights', 'business_transaction.tax_labor_compliance'],
'confidentiality_clearance' => ['internal_contact_id'],
default => [],
}];
}
$data = [];
foreach ([...$common, ...$fields] as $field) {
if (! is_string($field)) {
throw new \UnexpectedValueException('Canonical review fields must be named fields.');
}
$data[$field] = Arr::get($p, $field);
}
// Explicitly unclassified specialised fields conservatively reopen reviews.
// They cannot silently become immaterial when a schema gains a new field.
$classified = match ($p['opportunity_category'] ?? '') {
'real_estate' => ['transaction_type', 'property_type', 'construction_status', 'property_condition', 'land_area', 'built_area', 'area_unit', 'units', 'rooms', 'floors', 'amenities', 'utilities', 'occupancy_status', 'title_type', 'registration_number', 'encumbrances', 'price', 'rent', 'rent_periodicity', 'deposit', 'valuation', 'viewing', 'planning_permit_document_id', 'use_license_document_id', 'title_document_id', 'title_holder_name', 'issuing_authority_id', 'expected_completion_date', 'occupancy_details', 'occupancy_document_id', 'amenities_other', 'urban_limit_document_id', 'max_built_area'],
default => [],
};
if ($classified !== []) {
$data['unclassified_module_fields'] = array_diff_key($p['real_estate'] ?? [], array_flip($classified));
}
if ($gate === 'property_review') {
foreach (['rooms', 'amenities', 'deposit', 'occupancy_details', 'occupancy_document_id', 'amenities_other'] as $key) {
$data['real_estate.'.$key] = Arr::get($p, 'real_estate.'.$key);
}
}
if ($gate === 'registry_urban_review') {
foreach (['title_document_id', 'title_holder_name', 'issuing_authority_id', 'urban_limit_document_id', 'max_built_area'] as $key) {
$data['real_estate.'.$key] = Arr::get($p, 'real_estate.'.$key);
}
}
if ($gate === 'building_compliance_review') {
$data['real_estate.expected_completion_date'] = Arr::get($p, 'real_estate.expected_completion_date');
}
// A changed evidence file always invalidates a decision relying on it.
// Unrelated documents/images and editorial timestamps are not review evidence.
return $data;
}
/** @param array<string,mixed> $snapshot
* @param array<string,mixed> $review */
public function hash(array $snapshot, string $gate, array $review = [], bool $legacy = false, ?string $rule = null): string
{
$extended = ! $legacy && ($rule ?? self::VERSION) !== self::PREVIOUS_VERSION;
$data = $this->scope($snapshot, $gate, $extended);
$locationGates = ['registry_urban_review', 'cadastral_screening', 'legal_territorial_review', 'property_review'];
if (! $legacy) {
$locationGates = [...$locationGates, 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'];
}
if (in_array($gate, $locationGates, true)) {
$data['locations'] = array_map(fn ($r) => $r['payload'], $snapshot['resources']['locations'] ?? []);
}
foreach ($review['evidence_document_ids'] ?? [] as $id) {
$r = $snapshot['resources']['documents'][$id] ?? null;
$data['evidence'][$id] = $r ? ['sha256' => $r['sha256'] ?? null, 'payload' => $r['payload'] ?? [], 'deleted_at' => $r['deleted_at'] ?? null] : null;
}
if ($extended) {
// Nested references are part of the decision even when the reviewer
// selected a different supporting file. Preserve the original bytes.
$referenced = function (array $node) use (&$referenced, &$data, $snapshot): void {
foreach ($node as $key => $value) {
if (is_array($value)) {
$referenced($value);
} elseif (is_string($key) && is_string($value) && $value !== '' && (str_ends_with($key, 'document_id') || $key === 'image_id')) {
$kind = $key === 'image_id' ? 'images' : 'documents';
$resource = $snapshot['resources'][$kind][$value] ?? null;
$data['referenced_resources'][$kind][$value] = $resource ? ['sha256' => $resource['sha256'] ?? null, 'payload' => $resource['payload'] ?? [], 'deleted_at' => $resource['deleted_at'] ?? null] : null;
}
}
};
$referenced($data);
}
return $legacy ? hash('sha256', json_encode(Arr::sortRecursive($data), JSON_THROW_ON_ERROR)) : OpportunityCanonicalValue::hash($data);
}
/** @param array<string,mixed> $snapshot
* @param array<string,mixed> $review */
public function matches(array $snapshot, string $gate, array $review): bool
{
if (! isset($review['scope_hash'])) {
return true; // Caller must independently verify the original signed submission hash.
}
$rule = $review['scope_rule'] ?? '';
$legacy = ! in_array($rule, [self::VERSION, self::PREVIOUS_VERSION], true);
$expected = $this->hash($snapshot, $gate, $review, $legacy, $rule);
return hash_equals($review['scope_hash'], $expected);
}
/** @param array<string,mixed> $before
* @param array<string,mixed> $after
* @param array<string,mixed> $reviews
* @param list<string> $gates
* @return array<string,mixed> */
public function reconcile(array $before, array $after, array $reviews, array $gates, bool $force = false): array
{
$kept = [];
$reopened = [];
foreach ($gates as $gate) {
$review = $reviews[$gate] ?? [];
// Compare the signed baseline and new content with the new scope;
// separately validate old scope signatures under their original rule.
$priorHash = $this->hash($before, $gate, $review);
$currentHash = $this->hash($after, $gate, $review);
if (! $force && $before !== [] && ($review['decision'] ?? '') === 'approved' && $this->matches($before, $gate, $review) && hash_equals($priorHash, $currentHash)) {
$kept[$gate] = [...$review, 'scope_hash' => $priorHash, 'scope_rule' => self::VERSION, 'accepted_submission_hash' => $after['hash'],
'carried_forward' => ['rule' => self::VERSION, 'from_scope_hash' => $review['scope_hash'] ?? null, 'from_scope_rule' => $review['scope_rule'] ?? 'legacy_unspecified', 'from_submission_hash' => $before['hash'] ?? null, 'at' => now()->toIso8601String()]];
} else {
$reopened[] = $gate;
}
}
return ['rule' => self::VERSION, 'reviews' => $kept, 'reopened' => $reopened, 'retained' => array_keys($kept),
'reason' => $force ? 'Suspensão, rejeição ou recurso exige nova decisão; motivo anterior preservado.' : 'Comparação dos campos e evidências aplicáveis a cada revisão (§28.1).',
'final_approval' => 'Nova assinatura independente da versão; nenhum parecer ou decisão externa inventado.'];
}
}
+13 -1
View File
@@ -13,6 +13,9 @@ class OpportunityWorkflowTasks
public function ensure(Opportunity $record, string $kind, string $title): string
{
$key = 'portal-opportunity:'.$record->id.':'.$kind.':'.($record->workflow_context['content_revision'] ?? 1);
if (isset($record->workflow_context['review_cycle'])) {
$key .= ':cycle:'.$record->workflow_context['review_cycle'];
}
$existing = DB::table('tasks')->where('source_system', 'opportunity-workflow')->where('external_id', $key)->first();
if ($existing) {
return $existing->id;
@@ -32,11 +35,20 @@ class OpportunityWorkflowTasks
DB::table('tasks')->where('id', $taskId)->update(['assignee_user_id' => $subject->id, 'status' => 'in_progress', 'version_no' => DB::raw('version_no+1')]);
}
public function closedReviewBinding(Opportunity $record, ?string $id): bool
{
return $id !== null && DB::table('tasks')->where('id', $id)->where('source_system', 'opportunity-workflow')
->where('external_id', 'like', 'portal-opportunity:'.$record->id.':opportunity_review:%')->where('status', 'done')->exists();
}
public function complete(?string $taskId, string $outcome): void
{
if ($taskId) {
// Existing CRM outcome is a varchar(80) summary. The full reason is
// retained in the versioned workflow decision and its audit event.
$summary = mb_strlen($outcome) > 80 ? mb_substr($outcome, 0, 79).'…' : $outcome;
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')]);
->update(['status' => 'done', 'outcome' => $summary, 'completed_at' => now(), 'version_no' => DB::raw('version_no+1')]);
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
/** Country of constitution in the existing identity master, with explicit provenance. */
class OrganizationCountry
{
public function available(): bool
{
return config('portal.organization_country_enabled', false)
&& Schema::hasColumns('organizations', ['incorporation_country_code', 'incorporation_country_provenance']);
}
/** @return list<array<string, mixed>> */
public function represented(User $actor): array
{
if (! $this->available()) {
return [];
}
$readOnly = app(PortalProfileAccess::class)->has($actor, 'auditor');
return array_values(DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')
->where('m.user_id', $actor->id)->whereNull('m.deleted_at')->whereNull('o.deleted_at')
->get(['o.id', 'o.name', 'o.version_no', 'o.incorporation_country_code', 'o.incorporation_country_provenance', 'm.role'])
->unique('id')->map(fn ($o) => ['id' => $o->id, 'name' => $o->name, 'version' => $o->version_no,
'country' => $o->incorporation_country_code, 'provenance' => json_decode($o->incorporation_country_provenance ?? 'null', true),
'canEdit' => ! $readOnly && in_array($o->role, ['admin', 'manager', 'officer'], true)])->all());
}
public function authorize(User $actor, string $id, bool $write = false): void
{
abort_unless($this->available(), 409, 'Extensão do país de constituição ainda não instalada.');
abort_if($write && app(PortalProfileAccess::class)->has($actor, 'auditor'), 403, 'Auditor só consulta o cadastro mestre, mesmo com representação ou outros papéis.');
$roles = $write ? ['admin', 'manager', 'officer'] : ['admin', 'manager', 'officer', 'viewer'];
abort_unless(DB::table('memberships')->where('organization_id', $id)->where('user_id', $actor->id)
->whereNull('deleted_at')->whereIn('role', $roles)->exists()
&& DB::table('organizations')->where('id', $id)->whereNull('deleted_at')->exists(), 403, 'Representação da organização não autorizada.');
}
/** @param array<string, mixed> $data
* @return array{version:int, country:string} */
public function save(User $actor, string $id, array $data): array
{
$this->authorize($actor, $id, true);
$data = Validator::make($data, ['version' => 'required|integer|min:1',
'country' => ['required', 'string', app(CountryCatalogue::class)->rule()],
'source_reference' => 'required|string|min:5|max:2000'], [
'country.required' => 'Selecione o país de constituição da organização.',
'source_reference.required' => 'Indique a fonte ou referência deste país.',
'source_reference.min' => 'A referência deve ter pelo menos cinco caracteres.',
])->validate();
return DB::transaction(function () use ($actor, $id, $data) {
DB::table('memberships')->where('organization_id', $id)->where('user_id', $actor->id)->lockForUpdate()->get();
$this->authorize($actor, $id, true);
$row = DB::table('organizations')->where('id', $id)->lockForUpdate()->firstOrFail();
abort_unless((int) $row->version_no === (int) $data['version'], 409, 'Organização alterada. Recarregue.');
$provenance = ['kind' => 'representative_declaration', 'reference' => $data['source_reference'],
'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'source_system' => $row->source_system,
'external_id' => $row->external_id, 'verification' => 'country_declared_not_independently_verified'];
DB::table('organizations')->where('id', $id)->update(['incorporation_country_code' => $data['country'],
'incorporation_country_provenance' => json_encode($provenance, JSON_THROW_ON_ERROR), 'version_no' => $row->version_no + 1]);
DB::table('audit_events')->insert(['source_system' => 'organization-country', 'entity_type' => 'organizations',
'actor_user_id' => $actor->id, 'action' => 'incorporation_country_saved', 'data_classification' => 'restricted',
'before_data' => json_encode(['organization_id' => $id, 'snapshot' => Crypt::encryptString(json_encode($row, JSON_THROW_ON_ERROR))]),
'after_data' => json_encode(['organization_id' => $id, 'version' => $row->version_no + 1,
'snapshot' => Crypt::encryptString(json_encode(['country' => $data['country'], 'provenance' => $provenance], JSON_THROW_ON_ERROR))])]);
return ['version' => $row->version_no + 1, 'country' => $data['country']];
});
}
/** @return array<string, mixed> */
public function snapshot(User $actor, string $id): array
{
$this->authorize($actor, $id);
$org = DB::table('organizations')->where('id', $id)->lockForUpdate()->firstOrFail();
abort_unless($org->incorporation_country_code !== null, 422, 'País de constituição não informado no cadastro mestre.');
return ['organization_id' => $id, 'organization_version' => $org->version_no, 'country' => $org->incorporation_country_code,
'provenance' => json_decode($org->incorporation_country_provenance, true), 'reused_at' => now()->toIso8601String(), 'reused_by' => $actor->id];
}
}
@@ -0,0 +1,118 @@
<?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;
/** An explicit extension of the existing authenticated resource installer. */
class OrganizationCountryInstallation
{
public const MIGRATION = '2026_10_10_050000_extend_organization_country';
/** @return list<string> */
public function files(): array
{
return ['app/Services/OrganizationCountry.php', 'app/Services/OrganizationCountryInstallation.php', 'app/Providers/AppServiceProvider.php',
'app/Services/CountryCatalogue.php', 'app/Services/PortalProfileAccess.php', 'app/Services/PortalProfileInstallation.php',
'app/Http/Controllers/InvestmentWorkspaceController.php', 'app/Http/Controllers/InvestmentSubmissionController.php',
'app/Http/Controllers/OpportunityResourceController.php', 'app/Models/User.php', 'config/portal.php',
'routes/web.php', 'routes/investment.php', 'database/migrations/'.self::MIGRATION.'.php',
'resources/js/components/country-select.tsx', 'resources/js/pages/investment/profile.tsx',
'resources/js/pages/investment/submission.tsx', 'resources/js/pages/management/opportunity-install.tsx',
'resources/data/iso3166.tab', 'config/portal_profiles.php', 'composer.json', 'composer.lock'];
}
public function fingerprint(): string
{
return hash('sha256', json_encode(array_map(fn ($file) => [$file, hash_file('sha256', base_path($file))], $this->files()), JSON_THROW_ON_ERROR));
}
/** Separate bounded evidence: partial opportunity modules are not an installation dependency.
* @return array<string,mixed> */
public function evidence(object $identity): array
{
$path = storage_path('app/private/investmoz-v2/organization-country-installation/readiness.json');
$bytes = is_file($path) ? file_get_contents($path) : false;
$p = is_string($bytes) ? json_decode($bytes, true) : [];
$p = is_array($p) ? $p : [];
$target = get_object_vars($identity);
$ready = ($p['code_hash'] ?? '') === $this->fingerprint()
&& isset($target['database'], $target['port'])
&& ($p['target']['database'] ?? '') === $target['database'] && (int) ($p['target']['port'] ?? 0) === (int) $target['port']
&& strtotime($p['verified_at'] ?? '') >= time() - 86400
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false)
&& ($p['compatibility_verified'] ?? false) && ($p['reversal_verified'] ?? false)
&& is_file($p['dump_path'] ?? '') && hash_file('sha256', $p['dump_path']) === ($p['dump_sha256'] ?? '')
&& is_file($p['files_path'] ?? '') && hash_file('sha256', $p['files_path']) === ($p['files_sha256'] ?? '');
return ['ready' => $ready, 'backupDate' => $p['verified_at'] ?? null];
}
/** @return array<string, mixed> */
public function preview(User $actor): array
{
app(PortalProfileInstallation::class)->authorize($actor);
$identity = DB::selectOne('SELECT current_database() AS database, inet_server_port() AS port');
$evidence = $this->evidence($identity);
$columns = array_map(fn ($column) => Schema::hasColumn('organizations', $column), ['incorporation_country_code', 'incorporation_country_provenance']);
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
$installed = $ledger && ! in_array(false, $columns, true);
$consistent = ($ledger && ! in_array(false, $columns, true)) || (! $ledger && ! in_array(true, $columns, true));
$dependencies = array_reduce(['organizations', 'memberships', 'audit_events'], fn ($ok, $table) => $ok && Schema::hasTable($table), true);
$plan = ['migration' => self::MIGRATION, 'installed' => $installed, 'consistent' => $consistent, 'ready' => $consistent && $dependencies && $evidence['ready'],
'target' => $identity, 'code_hash' => $this->fingerprint(), 'backupDate' => $evidence['backupDate'],
'dependencies' => ['existing_organizations_memberships_audit' => $dependencies],
'changes' => ['Duas colunas opcionais no cadastro mestre organizations; zero tabelas, organizações, contas ou atribuições.',
'Preserva source_system, external_id, valores anteriores, versões e submissões; reutilização explícita, sem inferência por nome.',
'Ação independente de 030000, 040000 e 190000; não ativa flags, cálculos, publicação nem o percurso.'],
'rollback' => 'Desabilitar o consumidor mantém os dados. Não remover colunas com histórico; ensaiar a reversão de código e, se necessário, restauro no clone verificado.'];
$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
{
app(PortalProfileInstallation::class)->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 DB::transaction(function () use ($actor, $data) {
DB::select('SELECT pg_advisory_xact_lock(101026,50000)');
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$previous = DB::table('audit_events')->where('source_system', 'organization-country-installation')->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'];
}
$plan = $this->preview($actor);
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Plano alterado; consulte a pré-visualização.');
abort_unless($plan['consistent'], 409, 'Ledger/schema incoerentes. Recuperar antes de instalar.');
$changed = ! $plan['installed'];
if ($changed) {
abort_unless($plan['ready'], 422, 'Exige provas atuais da revisão, alvo, backup/restauro e compatibilidade.');
config(['organization_country.authenticated_installation' => true]);
try {
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500);
} finally {
config(['organization_country.authenticated_installation' => false]);
}
abort_unless($this->preview($actor)['installed'], 500, 'Verificação pós-instalação falhou.');
}
$result = ['installed' => true, 'changed' => $changed, 'migration' => self::MIGRATION, 'new_columns' => $changed ? 2 : 0, 'new_tables' => 0, 'new_organizations' => 0, 'flags_changed' => false];
DB::table('audit_events')->insert(['source_system' => 'organization-country-installation', 'entity_type' => 'installation', 'action' => 'install',
'actor_user_id' => $actor->id, 'correlation_id' => $data['idempotency_key'], 'data_classification' => 'restricted',
'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result, 'code_hash' => $plan['code_hash']], JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
+106
View File
@@ -0,0 +1,106 @@
<?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;
/** Owner-directed staff assignments use existing identities, organizations and grants. */
class PortalInternalDesignation
{
public function organizations(): array
{
return DB::table('organizations')->whereIn(DB::raw('id::text'), DB::table('audit_events')->where('source_system','portal-profiles-v1')->where('action','operator_organization_registered')->selectRaw("after_data->>'organization_id'"))->whereNull('deleted_at')
->get(['id','name','external_id','version_no'])->map(fn($r)=>$this->organization($r->id))->filter()->values()->all();
}
public function organization(?string $id): ?array
{
if ($id===null) return null;
$r=DB::table('organizations')->where('id',$id)->whereNull('deleted_at')->first();
if (!$r) return null;
$event=DB::table('audit_events')->where('source_system','portal-profiles-v1')->where('action','operator_organization_registered')
->where('after_data->organization_id',$id)->orderByDesc('occurred_at')->first();
if (!$event) return null;
$data=json_decode($event->after_data,true,512,JSON_THROW_ON_ERROR);
if (($data['organization']['name'] ?? null)!==$r->name || ($data['organization']['nuit'] ?? null)!==$r->external_id) return null;
return ['id'=>$r->id,'version'=>$r->version_no,...$data['organization'],'source_reference'=>$data['source_reference']];
}
public function registerOrganization(User $actor,array $input): array
{
app(PortalProfileAdministration::class)->administrative($actor);
$v=Validator::make($input,['operation_key'=>'required|uuid','name'=>'required|string|max:200','nuit'=>'required|string|regex:/^[0-9]{9}$/',
'contact'=>'required|string|regex:/^\+258[0-9]{9}$/','director'=>'required|string|max:200',
'function'=>'required|in:portal_owner_operator','source_reference'=>'required|string|min:20|max:1000'])->validate();
return DB::transaction(function()use($actor,$v){
DB::select('SELECT pg_advisory_xact_lock(101026,40001)');
$payload=array_intersect_key($v,array_flip(['name','nuit','contact','director','function']));
$existingEvent=DB::table('audit_events')->where('source_system','portal-profiles-v1')->whereIn('action',['operator_organization_registered','operator_organization_registration_recovered'])->where('after_data->operation_key',$v['operation_key'])->first();
if($existingEvent){
$e=json_decode($existingEvent->after_data,true);
abort_unless($e['organization']==$payload && $e['source_reference']===$v['source_reference'],409,'Esta chave corresponde a outro cadastro.');
return ['id'=>$e['organization_id'],'organization'=>$this->organization($e['organization_id']),'message'=>'Cadastro recuperado; não repetido.'];
}
$names=array_unique([$v['name'],preg_replace('/\s*,\s*/',' ',$v['name'])]);
$matches=DB::table('organizations')->where(fn($q)=>$q->where('external_id',$v['nuit'])->orWhereIn('name',$names)->orWhere('name',str_replace(' Lda',', Lda',$v['name'])))->lockForUpdate()->get();
abort_if($matches->count()>1,409,'Correspondência ambígua no cadastro mestre; não criar duplicado.');
$r=$matches->first();
if($r){
abort_if($r->deleted_at!==null || ($r->external_id!==null && $r->external_id!==$v['nuit']),409,'Identidade ou estado da organização exige reconciliação.');
$known=$this->organization($r->id);
if($known){
abort_unless(array_intersect_key($known,$payload)==$payload,409,'Dados do cadastro já existente diferem; preservar a versão anterior.');
app(PortalProfileAccess::class)->audit($actor,'operator_organization_registration_recovered',['operation_key'=>$v['operation_key'],'organization_id'=>$r->id,'organization'=>$payload,'source_reference'=>$v['source_reference']]);
return ['id'=>$r->id,'organization'=>$known,'message'=>'Organização existente recuperada.'];
}
$id=$r->id;
$before=['name'=>$r->name,'external_id'=>$r->external_id,'source_system'=>$r->source_system,'version_no'=>$r->version_no];
abort_unless(in_array($r->name,$names,true) || $r->name===str_replace(' Lda',', Lda',$v['name']),409,'Denominação divergente exige reconciliação expressa.');
DB::table('organizations')->where('id',$id)->update(['name'=>$v['name'],'external_id'=>$v['nuit'],'updated_at'=>now(),'version_no'=>$r->version_no+1]);
// Reconcile only the explicit comma alias; preserve previous values in audit.
}else{
$id=(string)Str::uuid();
DB::table('organizations')->insert(['id'=>$id,'name'=>$v['name'],'external_id'=>$v['nuit'],'source_system'=>'portal-operator-master','organization_type'=>'private']);
}
app(PortalProfileAccess::class)->audit($actor,'operator_organization_registered',['operation_key'=>$v['operation_key'],'organization_id'=>$id,
'organization'=>$payload,'previous_master_values'=>$before??null,'source_reference'=>$v['source_reference'],'metadata_storage'=>'existing_audit_snapshot','no_corporate_membership_created'=>true]);
return ['id'=>$id,'organization'=>$this->organization($id),'message'=>'Organização operadora registada no cadastro mestre. Nenhuma representação ou papel foi atribuído.'];
});
}
public function grant(User $actor,array $input): string
{
app(PortalProfileAdministration::class)->administrative($actor);
$v=Validator::make($input,['operation_key'=>'required|uuid','user_id'=>'required|integer|exists:users,id','role'=>['required',Rule::in(['promoter','validator','publisher'])],
'operator_organization_id'=>'required|uuid|exists:organizations,id','organization_id'=>'nullable|uuid|exists:organizations,id',
'opportunity_types'=>'required|array|min:1','opportunity_types.*'=>['required',Rule::in(OpportunityCanonicalContract::BASE_CATEGORIES)],
'confirmed_internal_designation'=>'required|accepted','reason'=>'required|string|min:20|max:1000',
'responsibilities'=>'sometimes|array|max:0','expires_at'=>'nullable|date|after:now'])->validate();
abort_if((int)$v['user_id']===$actor->id,403,'Não pode aprovar a sua atribuição.');
$subject=User::findOrFail($v['user_id']);
abort_unless($subject->hasVerifiedEmail() && $subject->two_factor_secret!==null && $subject->two_factor_confirmed_at!==null,422,'Confirmar contacto e o próprio MFA antes da atribuição interna.');
$organization=$this->organization($v['operator_organization_id']);
abort_unless($organization!==null,422,'Selecione a organização operadora cadastrada; não exige comprovativos de Promotor externo.');
if($v['role']==='promoter')abort_unless(($v['organization_id']??null)===$v['operator_organization_id'],422,'O vínculo interno é à organização operadora, não uma representação de gestão empresarial.');
return DB::transaction(function()use($actor,$v){
DB::select('SELECT pg_advisory_xact_lock(101026,40002)');
$subject=User::whereKey($v['user_id'])->lockForUpdate()->firstOrFail();
abort_unless($subject->hasVerifiedEmail() && $subject->two_factor_secret!==null && $subject->two_factor_confirmed_at!==null && $this->organization($v['operator_organization_id'])!==null,422,'Conta ou organização já não reúne as condições da atribuição.');
$e=DB::table('audit_events')->where('source_system','portal-profiles-v1')->where('action','role_granted')->where('after_data->operation_key',$v['operation_key'])->first();
$payload=array_intersect_key($v,array_flip(['user_id','role','operator_organization_id','organization_id','opportunity_types','reason','expires_at']));
if($e){$d=json_decode($e->after_data,true);abort_unless($d['designation']==$payload,409,'Chave usada numa atribuição diferente.');abort_unless(DB::table('portal_role_assignments')->where('id',$d['assignment_id'])->whereNull('revoked_at')->exists(),409,'A atribuição foi revogada.');return $d['assignment_id'];}
$duplicate=DB::table('portal_role_assignments')->where('user_id',$v['user_id'])->where('role',$v['role'])->where('source','internal-portal-designation')->whereNull('revoked_at')->where('starts_at','<=',now())->where(fn($q)=>$q->whereNull('expires_at')->orWhere('expires_at','>',now()))->exists();
abort_if($duplicate,409,'Já existe atribuição interna ativa: recupere-a antes de repetir ou alterar.');
$id=(string)Str::uuid();
app(PortalProfileAdministration::class)->insertGrant($id,$actor,[...$v,'source'=>'internal-portal-designation']);
app(PortalProfileAccess::class)->audit($actor,'role_granted',['assignment_id'=>$id,'subject_user_id'=>$v['user_id'],'role'=>$v['role'],
'operation_key'=>$v['operation_key'],'designation'=>$payload,'operator_organization_id'=>$v['operator_organization_id'],
'reason'=>$v['reason'],'authority'=>'portal-owner-internal-designation','external_promoter_documents_required'=>false,'no_corporate_membership_created'=>true]);
return $id;
});
}
}
+128 -24
View File
@@ -16,19 +16,20 @@ class PortalProfileAccess
/** @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'),
return [__FILE__, app_path('Services/OpportunityContacts.php'), resource_path('js/components/opportunity-contact-form.tsx'), app_path('Services/PortalInternalDesignation.php'), 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/OpportunityResources.php'), app_path('Services/OpportunityImageProcessor.php'), app_path('Services/VerifiedDocumentBinary.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/OpportunityCanonicalResponse.php'), app_path('Services/OpportunityCategoryFields.php'), app_path('Services/OpportunityModularProfiles.php'), app_path('Services/OpportunityWorkflowTasks.php'), base_path('composer.json'), base_path('composer.lock'),
app_path('Services/OpportunityReviewMateriality.php'), app_path('Services/OpportunityReviewConditions.php'), app_path('Services/OpportunityCanonicalMetadata.php'), app_path('Services/OpportunityCompleteness.php'), app_path('Services/OpportunityCanonicalValue.php'),
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'),
app_path('Http/Middleware/AuditProfileDecision.php'), app_path('Http/Middleware/EnsurePortalProfileAdministration.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'),
@@ -45,7 +46,17 @@ class PortalProfileAccess
public function available(): bool
{
return config('portal.profile_access_enabled') && Schema::hasTable('portal_role_assignments')
return config('portal.profile_access_enabled') && $this->installed();
}
public function governanceAvailable(): bool
{
return (config('portal.profile_administration_enabled') || config('portal.profile_access_enabled')) && $this->installed();
}
public function installed(): bool
{
return 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')
@@ -55,7 +66,7 @@ class PortalProfileAccess
/** @return list<\stdClass> */
public function grants(User $actor, ?string $role = null): array
{
if (! $this->available() || ! $actor->hasVerifiedEmail()) {
if (! $this->governanceAvailable() || ! $actor->hasVerifiedEmail()) {
return [];
}
@@ -70,7 +81,7 @@ class PortalProfileAccess
public function superuser(User $actor): bool
{
return $this->available() && $actor->hasVerifiedEmail() && DB::table('portal_superuser_pair')->where('id', 1)
return $this->governanceAvailable() && $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();
}
@@ -89,8 +100,46 @@ class PortalProfileAccess
&& (int) session('portal.mfa_at', 0) >= time() - 900;
}
public function internalAssignment(User $actor, string $type): ?\stdClass
{
foreach ($this->grants($actor, 'promoter') as $grant) {
if ($grant->source === 'internal-portal-designation'
&& in_array($type, json_decode($grant->opportunity_types, true), true)
&& app(PortalInternalDesignation::class)->organization($grant->organization_id) !== null) {
return $grant;
}
}
return null;
}
public function promoterRecordScope(User $actor, Opportunity $record): bool
{
foreach ($this->grants($actor, 'promoter') as $grant) {
if (! in_array($record->opportunity_category, json_decode($grant->opportunity_types, true), true)) {
continue;
}
if ($grant->source === 'internal-portal-designation') {
if (app(PortalInternalDesignation::class)->organization($grant->organization_id) !== null
&& ($record->workflow_context['operator_organization_id'] ?? null) === $grant->organization_id
&& ((int) $record->owner_user_id === $actor->id || in_array($actor->id, $record->workflow_context['contributors'] ?? [], true))) {
return true;
}
} elseif ($grant->organization_id === $record->organization_id && $this->represents($actor, $record->organization_id)
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id)) {
return true;
}
}
return false;
}
public function scoped(User $actor, string $role, ?string $organization, string $type): bool
{
if ($role === 'promoter' && $organization !== null && $this->internalAssignment($actor, $type) !== null
&& DB::table('organizations')->where('id', $organization)->whereNull('deleted_at')->exists()) {
return true;
}
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)) {
@@ -103,6 +152,9 @@ class PortalProfileAccess
public function operational(User $actor, string $action, ?int $recordId = null): bool
{
if (! $this->available()) {
return false;
}
if ($this->has($actor, 'auditor')) {
return false;
}
@@ -110,8 +162,13 @@ class PortalProfileAccess
return true;
}
if (! $this->mfa($actor)) {
return false;
}
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())
->whereNotNull('approved_by')->whereColumn('approved_by', '!=', 'subject_user_id')
->whereColumn('approved_by', '!=', 'requested_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();
@@ -119,7 +176,9 @@ class PortalProfileAccess
public function canCreate(User $actor, ?string $organization, string $type): bool
{
return $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && $this->operational($actor, 'create');
$included = in_array($type, OpportunityCanonicalContract::BASE_CATEGORIES, true) || app(OpportunityModularProfiles::class)->enabled();
return $included && $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && $this->operational($actor, 'create');
}
public function legacyWriteAllowed(User $actor): bool
@@ -138,22 +197,33 @@ class PortalProfileAccess
&& ! DB::table('portal_security_approvals')->where('kind', 'replacement')->whereNotNull('consumed_at')->where('scope->old_user_id', $actor->id)->exists();
}
/** Administration never grants operational access to a dossier or its attachments. */
public function hasOperationalReadScope(User $actor, Opportunity $record): bool
{
$personal = $record->organization_id !== null || (int) $record->owner_user_id === $actor->id;
return $this->promoterRecordScope($actor, $record)
|| $this->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category)
|| $this->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category);
}
public function canView(User $actor, Opportunity $record): bool
{
if ($record->owner_user_id !== null && ! $this->available()) {
return false;
}
if ($this->superuser($actor)) {
return ! $this->has($actor, 'auditor') && $this->hasOperationalReadScope($actor, $record)
&& $this->operational($actor, 'view', $record->id);
}
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);
return $this->has($actor, 'auditor') || $this->hasOperationalReadScope($actor, $record);
}
public function canEdit(User $actor, Opportunity $record, ?string $newType = null): bool
@@ -162,7 +232,7 @@ class PortalProfileAccess
return $this->legacyWriteAllowed($actor);
}
return $this->canView($actor, $record) && ! $record->trashed()
return $this->canView($actor, $record) && $this->promoterRecordScope($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);
@@ -197,22 +267,38 @@ class PortalProfileAccess
*/
public function scope(Builder $query, User $actor): Builder
{
if ($this->has($actor, 'auditor') || $this->superuser($actor)) {
if ($this->has($actor, 'auditor') && ! $this->superuser($actor)) {
return $query;
}
if ($this->superuser($actor)) {
$ids = DB::table('portal_security_approvals')->where('kind', 'elevation')->where('subject_user_id', $actor->id)
->where('scope->action', 'view')->whereNotNull('approved_by')->whereNull('consumed_at')->where('expires_at', '>', now())
->get()->filter(fn ($row) => $this->operational($actor, 'view', json_decode($row->scope, true)['record_id'] ?? null))
->map(fn ($row) => json_decode($row->scope, true)['record_id'])->all();
$query->whereIn('id', $ids);
}
return $query->where(function ($scope) use ($actor) {
$scope->whereRaw('1=0');
if ($actor->can('manage-portal')) {
if ($actor->can('manage-portal') && ! $this->superuser($actor)) {
$scope->orWhereNull('owner_user_id');
}
foreach ($this->grants($actor) as $grant) {
if ($grant->role === 'promoter' && ! $this->represents($actor, $grant->organization_id)) {
if (! in_array($grant->role, ['promoter', 'validator', 'publisher'], true)) {
continue;
}
if ($grant->role === 'promoter' && $grant->source !== 'internal-portal-designation' && ! $this->represents($actor, $grant->organization_id)) {
continue;
}
if ($grant->role === 'promoter' && $grant->source === 'internal-portal-designation' && app(PortalInternalDesignation::class)->organization($grant->organization_id) === null) {
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) {
if ($grant->role === 'promoter' && $grant->source === 'internal-portal-designation') {
$allowed->where(fn ($q) => $q->where('owner_user_id', $actor->id)->orWhereJsonContains('workflow_context->contributors', $actor->id))
->where('workflow_context->operator_organization_id', $grant->organization_id);
} elseif ($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);
@@ -225,23 +311,41 @@ class PortalProfileAccess
/** @return array<string,mixed>|null */
public function navigation(?User $actor): ?array
{
if (! $actor || ! $this->available() || ! $actor->hasVerifiedEmail()) {
if (! $actor || ! $this->governanceAvailable() || ! $actor->hasVerifiedEmail()) {
return null;
}
$contexts = [];
$seen = [];
$internalPromoter = false;
foreach ($this->grants($actor, 'promoter') as $grant) {
if ($grant->source === 'internal-portal-designation' && app(PortalInternalDesignation::class)->organization($grant->organization_id) !== null) {
$internalPromoter = true;
foreach (DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']) as $realPromoter) {
foreach (json_decode($grant->opportunity_types, true) as $type) {
$key = $realPromoter->id.'|'.$type;
if (! isset($seen[$key]) && $this->canCreate($actor, $realPromoter->id, $type)) {
$contexts[] = ['organization_id' => $realPromoter->id, 'organization_name' => $realPromoter->name, 'type' => $type];
$seen[$key] = true;
}
}
}
continue;
}
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)) {
$key = ($grant->organization_id ?? 'individual').'|'.$type;
if (! isset($seen[$key]) && $this->canCreate($actor, $grant->organization_id, $type)) {
$contexts[] = ['organization_id' => $grant->organization_id, 'type' => $type];
$seen[$key] = true;
}
}
}
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,
return ['contexts' => $contexts, 'internalPromoter' => $internalPromoter, 'mine' => $contexts ? '/minhas-oportunidades' : null, 'create' => $contexts ? '/minhas-oportunidades/create' : null,
'request' => '/perfil/promotor', 'review' => $this->available() && ($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];
}
+4 -1
View File
@@ -22,6 +22,9 @@ class PortalProfileAdministration
public function grant(User $actor, array $input): string
{
$this->administrative($actor);
if (($input['internal_designation'] ?? false) === true) {
return app(PortalInternalDesignation::class)->grant($actor, $input);
}
$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'])],
@@ -77,7 +80,7 @@ class PortalProfileAdministration
/** @param array<string,mixed> $input */
public function request(User $actor, array $input): string
{
abort_unless($this->access->available() && $actor->hasVerifiedEmail(), 403);
abort_unless($this->access->governanceAvailable() && $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();
+62 -8
View File
@@ -20,7 +20,7 @@ class PortalProfileInstallation
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')];
app_path('Http/Controllers/PortalProfileInstallationController.php'), resource_path('js/pages/profiles/installation.tsx'), resource_path('js/pages/profiles/bootstrap-confirmation.tsx'), base_path('routes/web.php')];
return hash('sha256', json_encode(array_map(fn ($path) => hash_file('sha256', $path), array_unique($files)), JSON_THROW_ON_ERROR));
}
@@ -78,7 +78,10 @@ class PortalProfileInstallation
$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.'];
'rule' => 'O primeiro titular apresenta o pedido com MFA e autorização de instalação; o segundo confirma numa operação separada com MFA. Sem autoaprovação, terceira pessoa obrigatória ou escolha automática.'];
$pending = $installed && ! $pair ? DB::table('portal_security_approvals')->where('kind', 'bootstrap')->whereNull('consumed_at')->where('expires_at', '>', now())
->where(fn ($q) => $q->where('requested_by', $actor->id)->orWhere('subject_user_id', $actor->id))->first() : null;
$bootstrap['pending'] = $pending ? ['approval_id' => $pending->id, 'confirmation_url' => '/management/profile-install/bootstrap/'.$pending->id, 'expires_at' => $pending->expires_at] : null;
$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(),
@@ -120,24 +123,75 @@ class PortalProfileInstallation
/** @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) {
abort_unless((int) $data['first_user_id'] === $actor->id, 403, 'O primeiro titular deve apresentar o seu próprio pedido; não é permitido inicializar terceiros.');
return $this->receipt($actor, 'bootstrap-request', $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.');
abort_unless($p['installed'] && $p['consistent'] && ! in_array(false, $p['dependencies'], true) && ! $p['bootstrap']['initialized'], 409, 'Schema consistente instalado e dupla não inicializada necessários.');
$second = User::findOrFail($data['second_user_id']);
foreach ([$actor, $second] as $user) app(PortalSuperusers::class)->validateBootstrapHolder($user);
abort_if(DB::table('portal_security_approvals')->where('kind', 'bootstrap')->whereNull('consumed_at')->where('expires_at', '>', now())->exists(), 409, 'Já existe pedido pendente. Recupere-o; não duplique a cerimónia.');
$id = (string) \Illuminate\Support\Str::uuid();
DB::table('portal_security_approvals')->insert(['id' => $id, 'kind' => 'bootstrap', 'requested_by' => $actor->id, 'subject_user_id' => $second->id,
'scope' => json_encode(['first_user_id' => $actor->id, 'second_user_id' => $second->id, 'code_hash' => $this->fingerprint(),
'target' => $p['target'], 'preview_hash' => $p['hash']], JSON_THROW_ON_ERROR), 'reason' => $data['reason'],
'expires_at' => now()->addMinutes(15), 'created_at' => now(), 'updated_at' => now()]);
return ['initialized' => false, 'pending' => true, 'approval_id' => $id, 'confirmation_url' => '/management/profile-install/bootstrap/'.$id,
'holders' => [$actor->id, $second->id], 'expires_in_seconds' => 900, 'flags_changed' => false, 'privileges_granted' => false];
});
}
/** Purpose-specific view; designation grants no general management access. */
public function bootstrapPreview(User $actor, string $id): array
{
abort_unless($actor->hasVerifiedEmail(), 403);
$row = DB::table('portal_security_approvals')->where('id', $id)->where('kind', 'bootstrap')->first();
abort_unless($row, 404);
abort_unless(in_array($actor->id, [(int) $row->requested_by, (int) $row->subject_user_id], true), 403, 'Apenas os dois titulares designados consultam este pedido.');
app(PortalSuperusers::class)->validateBootstrapHolder($actor);
$scope = json_decode($row->scope, true, 512, JSON_THROW_ON_ERROR);
$identity = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$current = $scope['code_hash'] === $this->fingerprint() && $scope['target']['database'] === $identity->database && (int) $scope['target']['port'] === (int) $identity->port;
$view = ['approval_id' => $id, 'requested_by' => (int) $row->requested_by, 'second_user_id' => (int) $row->subject_user_id,
'reason' => $row->reason, 'expires_at' => $row->expires_at, 'consumed' => $row->consumed_at !== null, 'code_current' => $current,
'expired' => strtotime($row->expires_at) <= time(), 'target' => $identity,
'can_confirm' => $actor->id === (int) $row->subject_user_id && $row->consumed_at === null && strtotime($row->expires_at) > time() && $current,
'mfa_confirmed_in_session' => $this->access->mfa($actor)];
$view['hash'] = hash('sha256', json_encode([$id, $row->requested_by, $row->subject_user_id, $row->scope, $row->reason, $row->expires_at], JSON_THROW_ON_ERROR));
return $view;
}
public function confirmBootstrap(User $actor, string $id, array $input): array
{
$view = $this->bootstrapPreview($actor, $id);
abort_unless($actor->id === $view['second_user_id'] && $actor->id !== $view['requested_by'], 403, 'O pedido não pode ser autoaprovado.');
abort_unless($this->access->mfa($actor), 403, 'Conclua MFA nesta sessão.');
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'confirm' => 'required|accepted', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000'])->validate();
$data['approval_id'] = $id;
return $this->receipt($actor, 'bootstrap-confirm', $data, function () use ($actor, $id, $data) {
$row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first();
$view = $this->bootstrapPreview($actor, $id);
abort_unless(hash_equals($view['hash'], $data['hash']), 409, 'Pedido alterado; consulte novamente.');
abort_unless($view['can_confirm'], 409, 'Pedido expirado, já consumido ou revisão/destino alterados.');
$first = User::findOrFail($row->requested_by);
$this->authorize($first);
$p = $this->preview($first);
abort_unless($p['installed'] && $p['consistent'] && ! in_array(false, $p['dependencies'], true) && ! $p['bootstrap']['initialized'], 409, 'Dependências ou dupla alteradas.');
app(PortalSuperusers::class)->validateBootstrapHolder($first);
DB::table('portal_security_approvals')->where('id', $id)->update(['approved_by' => $actor->id, 'updated_at' => now()]);
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);
app(PortalSuperusers::class)->initialize($first, $actor, $actor, $id);
} finally {
config(['portal_profiles.bootstrap_authorized' => false]);
}
return ['initialized' => true, 'holders' => [$data['first_user_id'], $data['second_user_id']], 'version' => 1, 'flags_changed' => false];
return ['initialized' => true, 'approval_id' => $id, 'holders' => [$first->id, $actor->id], 'version' => 1, 'flags_changed' => false];
});
}
+48 -26
View File
@@ -4,41 +4,58 @@ 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;
use Laravel\Fortify\Fortify;
class PortalSuperusers
{
public function __construct(private PortalProfileAccess $access, private PortalProfileAdministration $administration) {}
public function initialize(User $first, User $second, User $approver): void
private function mfaSecret(User $user): string
{
// 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.');
// Normal Fortify enrollment serializes the string; older QA fixtures used encryptString.
// Read either existing envelope without re-encryption, unserializing objects or changing keys.
$plain = Fortify::currentEncrypter()->decrypt($user->two_factor_secret, false);
abort_unless(is_string($plain), 422, 'Configuração MFA inválida.');
if (preg_match('/^s:[0-9]+:"([A-Z2-7]+=*)";$/D', $plain, $matches)
&& serialize($matches[1]) === $plain) {
return $matches[1];
}
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]);
return $plain;
}
public function validateBootstrapHolder(User $user): void
{
abort_unless($user->hasVerifiedEmail() && $user->two_factor_secret && $user->two_factor_confirmed_at, 422, 'Conta confirmada com MFA necessário.');
try {
$secret = $this->mfaSecret($user);
} catch (DecryptException) {
abort(422, 'Configuração MFA incompatível com este ambiente. Recuperar pelo procedimento existente.');
}
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 nesta cerimónia.');
}
public function initialize(User $first, User $second, User $confirmer, string $approvalId): void
{
abort_unless(config('portal_profiles.bootstrap_authorized') === true, 403);
abort_unless($first->id !== $second->id && $confirmer->id === $second->id, 403, 'Confirmação pelo segundo titular, distinta do pedido.');
foreach ([$first, $second] as $user) $this->validateBootstrapHolder($user);
abort_unless($this->access->mfa($confirmer), 403);
DB::transaction(function () use ($first, $second, $confirmer, $approvalId) {
DB::select('SELECT pg_advisory_xact_lock(101026, 40001)');
$approval = DB::table('portal_security_approvals')->where('id', $approvalId)->lockForUpdate()->first();
abort_unless($approval && $approval->kind === 'bootstrap' && (int) $approval->requested_by === $first->id
&& (int) $approval->subject_user_id === $second->id && (int) $approval->approved_by === $confirmer->id
&& $approval->consumed_at === null && strtotime($approval->expires_at) > time(), 409, 'Pedido cruzado inválido, expirado ou já consumido.');
abort_if(DB::table('portal_superuser_pair')->where('id', 1)->exists(), 409, 'Dupla existente; use substituição atómica.');
DB::table('portal_superuser_pair')->insert(['id' => 1, 'first_user_id' => $first->id, 'second_user_id' => $second->id, 'approved_by' => $confirmer->id, 'created_at' => now(), 'updated_at' => now()]);
DB::table('portal_security_approvals')->where('id', $approvalId)->update(['consumed_at' => now(), 'updated_at' => now()]);
$this->access->audit($confirmer, 'superuser_pair_initialized', ['approval_id' => $approvalId, 'requested_by' => $first->id, 'holders' => [$first->id, $second->id], 'version' => 1]);
});
}
@@ -69,6 +86,7 @@ class PortalSuperusers
DB::transaction(function () use ($actor, $id) {
$row = DB::table('portal_security_approvals')->where('id', $id)->lockForUpdate()->first();
abort_unless($row !== null, 404);
abort_unless(in_array($row->kind, ['replacement', 'elevation'], true), 403, 'Use a confirmação específica da inicialização cruzada.');
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()]);
@@ -103,7 +121,11 @@ class PortalSuperusers
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);
abort_unless(in_array($action, ['view', 'create', 'edit', 'validate', 'publish', 'archive'], true) && mb_strlen($reason) >= 20 && mb_strlen($reason) <= 1000, 422);
if ($action === 'view') {
$record = $recordId === null ? null : \App\Models\Opportunity::find($recordId);
abort_unless($record && $this->access->hasOperationalReadScope($actor, $record) && ! $this->access->has($actor, 'auditor'), 403, 'A consulta exige perfil operacional com âmbito válido; a elevação não o substitui.');
}
$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,
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace App\Services;
use Generator;
/** Read the accepted original one feature at a time, without changing its bytes. */
final class RetainedGeoJsonCollection
{
public function __construct(private readonly string $path) {}
/** @return array{type:mixed,feature_count:int,first_properties:array<string,mixed>,exceededTransferLimit:mixed} */
public function manifest(): array
{
$features = $this->features();
$count = 0;
$first = [];
foreach ($features as $feature) {
if ($count === 0) {
$first = $feature['properties'] ?? [];
}
$count++;
}
$metadata = $features->getReturn();
return ['type' => $metadata['type'] ?? null, 'feature_count' => $count, 'first_properties' => $first,
'exceededTransferLimit' => $metadata['exceededTransferLimit'] ?? false];
}
/** @return Generator<int,array<string,mixed>,mixed,array<string,mixed>> */
public function features(): Generator
{
$stream = fopen($this->path, 'rb');
abort_unless(is_resource($stream), 422, 'Exemplar privado indisponível.');
$buffer = '';
$position = 0;
$peek = static function () use ($stream, &$buffer, &$position): ?string {
if ($position === strlen($buffer)) {
$buffer = fread($stream, 65536);
$position = 0;
}
return $buffer !== '' ? $buffer[$position] : null;
};
$take = static function () use ($peek, &$position): ?string {
$char = $peek();
if ($char !== null) {
$position++;
}
return $char;
};
$white = static function () use ($peek, $take): void {
while (($c = $peek()) !== null && str_contains(" \t\r\n", $c)) {
$take();
}
};
$expect = static function (string $expected) use ($white, $take): void {
$white();
abort_unless($take() === $expected, 422, 'Estrutura JSON do exemplar inválida.');
};
$value = static function () use ($white, $peek, $take, &$buffer, &$position): string {
$white();
$first = $peek();
abort_unless($first !== null, 422, 'Exemplar JSON truncado.');
$structured = in_array($first, ['{', '[', '"'], true);
$result = $structured ? $take() : '';
$depth = $first === '"' ? 0 : 1;
$quoted = $first === '"';
$delimiters = $first === '{' ? '{}"' : ($first === '[' ? '[]"' : '"');
while (true) {
abort_unless($peek() !== null, 422, 'Exemplar JSON truncado.');
// Search whole numeric/coordinate spans in C; never loop through every byte in PHP.
$span = strcspn($buffer, $structured ? ($quoted ? '"\\' : $delimiters) : ",]} \t\r\n", $position);
$result .= substr($buffer, $position, $span);
$position += $span;
abort_if(strlen($result) > 4 * 1024 * 1024, 422, 'Elemento JSON excede o limite seguro de leitura.');
if ($position === strlen($buffer)) {
continue;
}
if (! $structured) {
break;
}
$c = $take();
$result .= $c;
if ($quoted) {
if ($c === '\\') {
$escaped = $take();
abort_unless($escaped !== null, 422, 'Exemplar JSON truncado.');
$result .= $escaped;
} elseif ($c === '"') {
$quoted = false;
}
} elseif ($c === '"') {
$quoted = true;
} elseif ($c === $first) {
$depth++;
} else {
$depth--;
}
if (! $quoted && $depth === 0) {
break;
}
}
abort_unless($result !== '', 422, 'Valor JSON ausente.');
return $result;
};
$decode = static function (string $bytes): mixed {
try {
return json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
abort(422, 'JSON do exemplar inválido.');
}
};
try {
$expect('{');
$metadata = [];
$keys = [];
$index = 0;
$hadFeatures = false;
$white();
abort_if($peek() === '}', 422, 'Exemplar sem coleção de elementos.');
while (true) {
$key = $decode($value());
abort_unless(is_string($key) && ! isset($keys[$key]), 422, 'Chave JSON inválida ou repetida.');
$keys[$key] = true;
$expect(':');
if ($key === 'features') {
$hadFeatures = true;
$expect('[');
$white();
if ($peek() !== ']') {
while (true) {
$feature = $decode($value());
abort_unless(is_array($feature) && ($feature['type'] ?? null) === 'Feature', 422, 'Elemento geográfico inválido.');
yield $index++ => $feature;
unset($feature);
$white();
if ($peek() === ']') {
break;
}$expect(',');
}
}
$expect(']');
} else {
$metadata[$key] = $decode($value());
}
$white();
if ($peek() === '}') {
break;
}$expect(',');
}
$expect('}');
$white();
abort_unless($peek() === null && $hadFeatures,422,'Exemplar incompleto ou com conteúdo adicional.');
return $metadata;
} finally {
fclose($stream);
}
}
}
+11 -10
View File
@@ -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'), 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'),
return hash('sha256', implode('', array_map(fn ($f) => hash_file('sha256', $f), [__FILE__, app_path('Services/RetainedGeoJsonCollection.php'), 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')])));
}
@@ -52,19 +52,20 @@ class TerritoryGeometryImport
$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($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.');
$collection = new RetainedGeoJsonCollection($file);
$source = $collection->manifest();
abort_unless(($source['type'] ?? '') === 'FeatureCollection' && $source['feature_count'] === [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', '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']]);
$countryNames = array_map($normalize, [$source['first_properties']['ADM0_PT'], $source['first_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();
$countryId = count($countries) === 1 ? $countries[0]->id : null;
$parentSourceHash = $level > 1 ? hash_file('sha256', $directory.'/moz-adm'.($level - 1).'-ine-20190607.geojson') : null;
$rows = [];
foreach ($source['features'] as $feature) {
foreach ($collection->features() as $feature) {
$p = $feature['properties'];
abort_unless(($p['ADM0_PCODE'] ?? '') === 'MZ', 422, 'Âmbito territorial do exemplar divergente.');
$external = '2019-06-07:adm'.$level.':'.$p['ADM'.$level.'_PCODE'];
@@ -136,9 +137,9 @@ 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 = $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);
$sourcePath = config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-20190607.geojson';
abort_unless(hash_file('sha256', $sourcePath) === $plan['source_sha256'], 409);
$collection = new RetainedGeoJsonCollection($sourcePath);
$metadata = config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-metadata.html';
$metadataSize = filesize($metadata);
abort_unless(is_int($metadataSize), 422, 'Metadados indisponíveis durante a aplicação.');
@@ -149,14 +150,14 @@ class TerritoryGeometryImport
$batch = (string) Str::uuid();
$created = [];
$reused = [];
foreach ($plan['rows'] as $i => $row) {
foreach ($collection->features() as $i => $feature) {
$row = $plan['rows'][$i];
if ($row['status'] === 'reuse') {
$reused[] = $row['geometry_id'];
}
if ($row['status'] !== 'insert') {
continue;
}
$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' => $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']);
+34 -1
View File
@@ -5,6 +5,8 @@ namespace App\Services;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\HeaderUtils;
@@ -12,8 +14,9 @@ use Symfony\Component\HttpFoundation\HeaderUtils;
/** Authorization/publication stays with the consumer; originals share integrity and cipher handling. */
class VerifiedDocumentBinary
{
public function respond(object $document, bool $inline = false): Response|BinaryFileResponse
public function respond(\stdClass $document, bool $inline = false): Response|BinaryFileResponse
{
$this->authorizeOpportunityAttachment($document);
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean'
&& ($document->deleted_at ?? null) === null && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
$disk = Storage::disk('local');
@@ -43,4 +46,34 @@ class VerifiedDocumentBinary
return $inline ? response()->file($path, $headers)->setContentDisposition('inline', basename($document->file_name)) : response()->download($path, basename($document->file_name), $headers);
}
/** The general document route must not bypass the opportunity's current authorization. */
private function authorizeOpportunityAttachment(\stdClass $document): void
{
$links = collect();
foreach (['opportunity_documents', 'opportunity_images'] as $table) {
if (! Schema::hasTable($table)) {
continue;
}
$query = DB::table($table)->where('document_id', $document->id);
if ($table === 'opportunity_images') {
$query->orWhereRaw("payload->'derivatives' @> ?::jsonb", [json_encode([['document_id' => $document->id]], JSON_THROW_ON_ERROR)]);
}
$links = $links->concat($query->get(['opportunity_id', 'deleted_at']));
}
$privateOrigin = in_array($document->source_system ?? null, ['opportunity-resources', 'opportunity-image-derivatives'], true);
if ($links->isEmpty() && ! $privateOrigin) {
return; // Other consumers retain their own publication/authorization rules.
}
$actor = request()->user();
abort_unless($actor instanceof \App\Models\User, 403, 'Anexo privado: é necessário acesso autorizado à oportunidade.');
foreach ($links as $link) {
$opportunity = \App\Models\Opportunity::find($link->opportunity_id);
if ($link->deleted_at === null && $opportunity && $opportunity->status !== 'archived'
&& app(PortalProfileAccess::class)->canView($actor, $opportunity)) {
return;
}
}
abort(403, 'O perfil atual não autoriza consultar este anexo da oportunidade.');
}
}
+7 -4
View File
@@ -204,10 +204,10 @@ class VirtualDesk
});
}
/** @return array<string,mixed> */
public function requestToolPrefill(User $actor, \stdClass $request): ?array
/** @return array<string,mixed>|null */
public function requestToolPrefill(User $actor, \stdClass $request, bool $lock = false): ?array
{
$case = $this->case($actor, $request->case_id);
$case = $this->case($actor, $request->case_id, false, $lock);
$payload = $this->decode($request->payload);
if (! config('investor-path.enabled') || (int) $case->user_id !== $actor->id || ! $case->simulation_id || $case->closed_at
|| ! in_array($request->status, ['draft', 'returned'], true) || trim((string) ($payload['description'] ?? '')) !== ''
@@ -218,6 +218,9 @@ class VirtualDesk
$draftRequest = Request::create('/');
$draftRequest->setUserResolver(fn () => $actor);
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
if ($lock) {
$draft = SimulationFormDraft::query()->whereKey($draft->id)->lockForUpdate()->firstOrFail();
}
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$description = (string) ($economic['project_summary'] ?? '');
if (trim($description) === '') {
@@ -313,7 +316,7 @@ class VirtualDesk
abort_unless(in_array($request->status, ['draft', 'returned'], true) && $request->version === (int) $data['version'], 409, 'Pedido alterado ou já submetido.');
$prefill = null;
if (! empty($data['tool_prefill'])) {
$prefill = $this->requestToolPrefill($actor, $request);
$prefill = $this->requestToolPrefill($actor, $request, true);
$source = $data['tool_prefill'];
if ($submit || ! $prefill || $source['draft_id'] !== $prefill['draft_id'] || (int) $source['draft_version'] !== $prefill['draft_version']
|| ! hash_equals($prefill['snapshot_sha256'], $source['snapshot_sha256'])
+1
View File
@@ -37,6 +37,7 @@ class VirtualDeskInstallation
sort($files);
$files = [...$files, ...PortalProfileAccess::fingerprintFiles()];
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}