fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -24,8 +24,8 @@ class InvestorGuidance
|
||||
return Schema::hasColumn('tasks', 'desk_case_id');
|
||||
}
|
||||
|
||||
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator. */
|
||||
/** @return array<string,mixed> */
|
||||
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator.
|
||||
* @return array<string,mixed> */
|
||||
public function context(User $actor, \stdClass $case): array
|
||||
{
|
||||
$base = $this->desk->decode($case->payload);
|
||||
|
||||
@@ -103,7 +103,9 @@ final class BusinessFormSchema
|
||||
// The field limit is a text length, not an 8% ceiling.
|
||||
$rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
|
||||
function ($attribute, $value, $fail) {
|
||||
if (strlen((string) $value) > 8) $fail('Indique a percentagem com até 8 caracteres.');
|
||||
if (strlen((string) $value) > 8) {
|
||||
$fail('Indique a percentagem com até 8 caracteres.');
|
||||
}
|
||||
}];
|
||||
foreach (['valid_until', 'mandate_valid_until'] as $date) {
|
||||
$rules['payload.'.$date][] = 'date_format:Y-m-d';
|
||||
|
||||
@@ -23,17 +23,26 @@ final class ClusterCompetitiveness
|
||||
->where('entity_type', 'economic_clusters')->where('entity_id', $cluster);
|
||||
}
|
||||
|
||||
private function decode(?object $event): array
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function decode(?\stdClass $event): array
|
||||
{
|
||||
return $event ? json_decode(Crypt::decryptString(json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['snapshot']), true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['version' => 0, 'draft' => null, 'approved' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function current(string $cluster): array
|
||||
{
|
||||
return $this->decode($this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->first());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function management(string $cluster): array
|
||||
{
|
||||
$state = $this->current($cluster);
|
||||
@@ -44,6 +53,10 @@ final class ClusterCompetitiveness
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $draft
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function validateDraft(array $draft, string $cluster): array
|
||||
{
|
||||
$rules = ['version' => 'required|integer|in:1', 'clusterId' => 'required|string|in:'.$cluster,
|
||||
@@ -69,6 +82,9 @@ final class ClusterCompetitiveness
|
||||
return $clean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|null $draft
|
||||
*/
|
||||
private function assertComplete(?array $draft): void
|
||||
{
|
||||
$missing = ! $draft || ! $draft['sector'] || ! $draft['region'];
|
||||
@@ -84,7 +100,10 @@ final class ClusterCompetitiveness
|
||||
}
|
||||
}
|
||||
|
||||
/** Reuse the portal's encrypted, append-only audit snapshots; no new schema or mutable publication fields. */
|
||||
/** Reuse the portal's encrypted, append-only audit snapshots; no new schema or mutable publication fields.
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function change(EconomicCluster $cluster, int $actor, int $expected, string $action, array $input = []): array
|
||||
{
|
||||
return DB::transaction(function () use ($cluster, $actor, $expected, $action, $input) {
|
||||
@@ -96,7 +115,7 @@ final class ClusterCompetitiveness
|
||||
$state['draft'] = $this->validateDraft($input['draft'], $cluster->id);
|
||||
} elseif ($action === 'restored') {
|
||||
$event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first();
|
||||
abort_unless($event, 404);
|
||||
abort_unless($event !== null, 404);
|
||||
$state['draft'] = $this->decode($event)['draft'];
|
||||
} elseif ($action === 'approved') {
|
||||
$this->assertComplete($state['draft']);
|
||||
@@ -120,6 +139,9 @@ final class ClusterCompetitiveness
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function publicData(string $cluster): ?array
|
||||
{
|
||||
$approved = $this->current($cluster)['approved'];
|
||||
|
||||
@@ -9,9 +9,14 @@ use Illuminate\Support\Facades\DB;
|
||||
/** Navigation over existing authorisations; never grants a role or publishes content. */
|
||||
final class ContentManagement
|
||||
{
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function access(?User $actor): array
|
||||
{
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) return [];
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) {
|
||||
return [];
|
||||
}
|
||||
$profiles = app(PortalProfileAccess::class);
|
||||
$navigation = $profiles->navigation($actor);
|
||||
$legacy = $profiles->legacyWriteAllowed($actor);
|
||||
@@ -19,15 +24,23 @@ final class ContentManagement
|
||||
$editor = $documents->full($actor) || $documents->editorial($actor);
|
||||
$upload = $editor || $documents->limited($actor);
|
||||
$result = [];
|
||||
if (app(Procurement::class)->available() && app(Procurement::class)->access($actor)) $result['procurement'] = ['index' => '/management/concursos', 'create' => '/management/concursos/novo'];
|
||||
if (app(Procurement::class)->available() && app(Procurement::class)->access($actor)) {
|
||||
$result['procurement'] = ['index' => '/management/concursos', 'create' => '/management/concursos/novo'];
|
||||
}
|
||||
if ($legacy || ($navigation['mine'] ?? null) || ($navigation['review'] ?? null)) {
|
||||
$result['opportunities'] = ['index' => $legacy ? '/management/opportunities' : '/minhas-oportunidades',
|
||||
'create' => $legacy ? '/management/opportunities/create' : ($navigation['create'] ?? null), 'profileWorkflow' => ! $legacy];
|
||||
}
|
||||
if ($upload) $result['documents'] = ['index' => '/management/portal-services', 'edit' => $editor];
|
||||
if ($upload) {
|
||||
$result['documents'] = ['index' => '/management/portal-services', 'edit' => $editor];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function view(User $actor): array
|
||||
{
|
||||
$access = $this->access($actor);
|
||||
@@ -45,6 +58,7 @@ final class ContentManagement
|
||||
$counts['documents'] = $query ? $query->select('r.published', DB::raw('count(*) as total'))->groupBy('r.published')->get()
|
||||
->mapWithKeys(fn ($row) => [$row->published ? 'published' : 'unpublished' => (int) $row->total]) : [];
|
||||
}
|
||||
|
||||
return ['access' => $access, 'counts' => $counts];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,19 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\CheckedFile;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
|
||||
/** Supplement the six named agribusiness sections without changing corridor masters or source documents. */
|
||||
final class CorridorAgribusiness
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $links
|
||||
*/
|
||||
public function enrich(string $html, array $links = []): string
|
||||
{
|
||||
$data = json_decode(file_get_contents(__DIR__.'/../../database/data/corridor-investment-opportunities.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$data = json_decode(CheckedFile::read(__DIR__.'/../../database/data/corridor-investment-opportunities.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$doc = new DOMDocument;
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
try {
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
@@ -14,22 +16,33 @@ final class CorridorAgribusinessOpportunities
|
||||
{
|
||||
public const SOURCE_HASH = '1473b06c48aa234e771660e3f2a51b9d2e4e1943bd52d878e0ae854ee6657055';
|
||||
|
||||
/** Documentary cross-reference only; keep the two source designations and master records intact. */
|
||||
public function portfolioOpportunityIds(\App\Models\InvestmentDossier $dossier): array
|
||||
/** Documentary cross-reference only; keep the two source designations and master records intact.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function portfolioOpportunityIds(InvestmentDossier $dossier): array
|
||||
{
|
||||
if (!$dossier->corridor_id || data_get($dossier->content, 'code') !== 'COR-02') return [];
|
||||
if (! $dossier->corridor_id || data_get($dossier->content, 'code') !== 'COR-02') {
|
||||
return [];
|
||||
}
|
||||
// COR-02 is Beira e Centro in investment-portfolio.json. The seven entries are explicitly
|
||||
// grouped under Corredor da Beira in the accepted source, not selected by province/name search.
|
||||
$keys = collect($this->entries())->where('corridor', 'Corredor da Beira')->pluck('key');
|
||||
|
||||
return Opportunity::published()->whereIn('management_creation_key', $keys)
|
||||
->where('workflow_context->corridor_agribusiness->source_sha256', self::SOURCE_HASH)->pluck('id')->all();
|
||||
}
|
||||
|
||||
public const LIMITATIONS = 'Promotor, implantação exacta, área, montante, financiamento, viabilidade e licenças não indicados nesta fonte. O corredor é um enquadramento documental; não identifica uma parcela nem confirma disponibilidade.';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function entries(): array
|
||||
{
|
||||
$data = json_decode(file_get_contents(database_path('data/corridor-investment-opportunities.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($data['source_sha256'] !== self::SOURCE_HASH) throw new \RuntimeException('Fonte divergente; reconciliar antes de cadastrar.');
|
||||
$data = json_decode(CheckedFile::read(database_path('data/corridor-investment-opportunities.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($data['source_sha256'] !== self::SOURCE_HASH) {
|
||||
throw new \RuntimeException('Fonte divergente; reconciliar antes de cadastrar.');
|
||||
}
|
||||
$sector = Sector::where('slug', 'agronegocio')->where('is_active', true)->whereNull('deleted_at')->firstOrFail();
|
||||
$entries = [];
|
||||
foreach ($data['groups'] as $g => $group) {
|
||||
@@ -42,14 +55,21 @@ final class CorridorAgribusinessOpportunities
|
||||
'summary' => $item['description'], 'description' => $description, 'sector_id' => $sector->id];
|
||||
}
|
||||
}
|
||||
if (count($entries) !== 34) throw new \RuntimeException('O lote deve conter as 34 entradas da fonte.');
|
||||
if (count($entries) !== 34) {
|
||||
throw new \RuntimeException('O lote deve conter as 34 entradas da fonte.');
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function register(User $actor, string $organization): array
|
||||
{
|
||||
// The caller uses the ordinary profile creation route and its approved scope.
|
||||
abort_unless(str_starts_with(request()->path(), 'minhas-oportunidades'), 422);
|
||||
|
||||
return DB::transaction(function () use ($actor, $organization) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(231026, 34)');
|
||||
$result = [];
|
||||
@@ -60,6 +80,7 @@ final class CorridorAgribusinessOpportunities
|
||||
abort_unless(data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') === self::SOURCE_HASH, 409);
|
||||
// Recovery never overwrites editorial changes, withdrawal or archive.
|
||||
$result[] = ['id' => $record->id, 'created' => false, 'key' => $entry['key']];
|
||||
|
||||
continue;
|
||||
}
|
||||
$record = app(OpportunityManagement::class)->save($actor, ['creation_key' => $entry['key'], 'organization_id' => $organization,
|
||||
@@ -81,17 +102,29 @@ final class CorridorAgribusinessOpportunities
|
||||
'after_data' => json_encode(['record_id' => $record->id, 'source' => $entry, 'no_publication' => true, 'no_master_relation_inferred' => true], JSON_THROW_ON_ERROR)]);
|
||||
$result[] = ['id' => $record->id, 'created' => true, 'key' => $entry['key']];
|
||||
}
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function articleLinks(): array
|
||||
{
|
||||
// Reading an original article must work before the optional sector/opportunity catalogue is loaded.
|
||||
if (! Sector::where('slug', 'agronegocio')->where('is_active', true)->exists()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$records = Opportunity::published()->whereIn('management_creation_key', array_column($this->entries(), 'key'))->get()->keyBy('management_creation_key');
|
||||
$links = [];
|
||||
foreach ($this->entries() as $entry) {
|
||||
if ($record = $records->get($entry['key'])) $links[$entry['group']][$entry['index']] = '/oportunidades/'.$record->slug;
|
||||
if ($record = $records->get($entry['key'])) {
|
||||
$links[$entry['group']][$entry['index']] = '/oportunidades/'.$record->slug;
|
||||
}
|
||||
}
|
||||
|
||||
return $links;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ final class DeclaredOriginStatistics
|
||||
abort_unless(app(ScopedPortalAdministration::class)->interestOperator($actor), 403);
|
||||
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
|
||||
$groups = [];
|
||||
$interests=DB::table('interest_requests')->whereNull('deleted_at');
|
||||
app(ScopedPortalAdministration::class)->interestQuery($interests,$actor);
|
||||
$interests = DB::table('interest_requests')->whereNull('deleted_at');
|
||||
app(ScopedPortalAdministration::class)->interestQuery($interests, $actor);
|
||||
foreach ($interests->select('metadata')->cursor() as $row) {
|
||||
$metadata = json_decode($row->metadata ?? '{}', true);
|
||||
$code = $metadata['declared_origin_country_code'] ?? null;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
@@ -37,6 +38,7 @@ class DocumentManagementAccess
|
||||
public function editorialResources(User $actor): Builder
|
||||
{
|
||||
abort_unless($this->editorial($actor), 403);
|
||||
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
||||
->where(function ($query) use ($actor) {
|
||||
@@ -50,7 +52,7 @@ class DocumentManagementAccess
|
||||
->where('d.external_id', $item['external_id']);
|
||||
});
|
||||
}
|
||||
foreach (json_decode(file_get_contents(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $item) {
|
||||
foreach (json_decode(CheckedFile::read(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $item) {
|
||||
// These exact original bytes contain the legacy identity/source.
|
||||
// Destination upload IDs differ; the approved file scope does not.
|
||||
$query->orWhere('d.sha256', $item['sha256']);
|
||||
@@ -80,6 +82,9 @@ class DocumentManagementAccess
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $data
|
||||
*/
|
||||
public function audit(User $actor, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert([
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -11,14 +12,19 @@ use Illuminate\Support\Facades\Schema;
|
||||
class EconomicReferenceCatalog
|
||||
{
|
||||
public const LOT = 'lot-01';
|
||||
|
||||
public const SOURCE = 'economic-reference-lot-01';
|
||||
|
||||
public const MANIFEST_SHA256 = 'ba1bb3406fd55e39c19fd2a2755f3dfc2a1160b67eee8b3b6e12cd43f4223b04';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function manifest(): array
|
||||
{
|
||||
$file = database_path('data/economic-references-lot-01.json');
|
||||
abort_unless(is_file($file) && hash_equals(self::MANIFEST_SHA256, hash_file('sha256', $file)), 422, 'Manifesto económico ausente ou diferente da revisão delimitada.');
|
||||
$manifest = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(is_file($file) && hash_equals(self::MANIFEST_SHA256, CheckedFile::sha256($file)), 422, 'Manifesto económico ausente ou diferente da revisão delimitada.');
|
||||
$manifest = json_decode(CheckedFile::read($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless(($manifest['lot'] ?? '') === self::LOT && count($manifest['activities'] ?? []) === 5
|
||||
&& count($manifest['chains'] ?? []) === 5 && count($manifest['links'] ?? []) === 4, 422, 'Lote económico fora do âmbito.');
|
||||
|
||||
@@ -40,7 +46,9 @@ class EconomicReferenceCatalog
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
if (! $this->schemaAvailable() || $this->publicationState() !== 'published') { return false; }
|
||||
if (! $this->schemaAvailable() || $this->publicationState() !== 'published') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return DB::table('reference_catalog_versions')->where('id', $this->manifest()['catalog']['id'])->where('status', 'published')->exists();
|
||||
}
|
||||
@@ -48,7 +56,9 @@ class EconomicReferenceCatalog
|
||||
public function constrain(Builder $query, string $kind): Builder
|
||||
{
|
||||
$manifest = $this->manifest();
|
||||
if ($kind === 'activity') $query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
|
||||
if ($kind === 'activity') {
|
||||
$query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
|
||||
}
|
||||
if (in_array($kind, ['activity', 'chain'], true) && ! $this->available()) {
|
||||
$query->whereNotIn('id', array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'));
|
||||
}
|
||||
@@ -59,17 +69,29 @@ class EconomicReferenceCatalog
|
||||
/** A withdrawn published reference can be retained verbatim, never introduced as a new choice. */
|
||||
public function historicalTarget(string $kind, string $id): bool
|
||||
{
|
||||
if ($kind === 'activity' && $id === SectorOrganization::LEGACY_ACTIVITY_ID) return DB::table('economic_activities')->where('id', $id)->where('sector_id', 2)->where('status', 'published')->exists();
|
||||
if (! in_array($kind, ['activity', 'chain'], true) || ! $this->schemaAvailable()) { return false; }
|
||||
if ($kind === 'activity' && $id === SectorOrganization::LEGACY_ACTIVITY_ID) {
|
||||
return DB::table('economic_activities')->where('id', $id)->where('sector_id', 2)->where('status', 'published')->exists();
|
||||
}
|
||||
if (! in_array($kind, ['activity', 'chain'], true) || ! $this->schemaAvailable()) {
|
||||
return false;
|
||||
}
|
||||
$manifest = $this->manifest();
|
||||
if (! in_array($id, array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'), true)) { return false; }
|
||||
if (! DB::table('audit_events')->where('source_system', self::SOURCE)->where('action', 'publish')->exists()) { return false; }
|
||||
if (! in_array($id, array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'), true)) {
|
||||
return false;
|
||||
}
|
||||
if (! DB::table('audit_events')->where('source_system', self::SOURCE)->where('action', 'publish')->exists()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $kind === 'activity'
|
||||
? DB::table('economic_activities')->where('id', $id)->where('status', 'published')->exists()
|
||||
: DB::table('value_chains')->where('id', $id)->whereNull('deleted_at')->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $historicalIds
|
||||
* @return Collection<int, \stdClass>
|
||||
*/
|
||||
public function activities(array $historicalIds = []): Collection
|
||||
{
|
||||
$rows = DB::table('economic_activities')->where('status', 'published')->get();
|
||||
@@ -79,14 +101,19 @@ class EconomicReferenceCatalog
|
||||
foreach ($historicalIds as $id) {
|
||||
$seen = [];
|
||||
while (isset($byId[$id]) && ! isset($seen[$id])) {
|
||||
$allowed[] = $id; $seen[$id] = true; $id = $byId[$id]->parent_id;
|
||||
$allowed[] = $id;
|
||||
$seen[$id] = true;
|
||||
$id = $byId[$id]->parent_id;
|
||||
}
|
||||
}
|
||||
|
||||
$available = $this->available();
|
||||
return $rows->filter(fn ($r) => in_array($r->id, $allowed, true))->map(function ($row) use ($byId, $available) {
|
||||
|
||||
return $rows->filter(fn ($r) => in_array($r->id, $allowed, true))->map(function ($row) use ($byId, $available): \stdClass {
|
||||
$meta = property_exists($row, 'metadata') ? json_decode($row->metadata, true) : [];
|
||||
$path = []; $current = $row; $seen = [];
|
||||
$path = [];
|
||||
$current = $row;
|
||||
$seen = [];
|
||||
while ($current && ! isset($seen[$current->id])) {
|
||||
$seen[$current->id] = true;
|
||||
array_unshift($path, ['id' => $current->id, 'code' => $current->code, 'label' => $current->label_pt_mz]);
|
||||
@@ -94,21 +121,31 @@ class EconomicReferenceCatalog
|
||||
}
|
||||
$isLot = ($meta['lot'] ?? '') === self::LOT;
|
||||
|
||||
return (object) ['id' => $row->id, 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
|
||||
$option = ['id' => $row->id, 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
|
||||
'label_pt_mz' => $row->label_pt_mz, 'catalog_version_id' => $row->catalog_version_id, 'code' => $row->code,
|
||||
'level' => $meta['level'] ?? null, 'path' => $path, 'display_label' => implode(' → ', array_column($path, 'code')).' — '.$row->label_pt_mz,
|
||||
'source_version' => $meta['source_version'] ?? null, 'edition' => $meta['edition'] ?? null,
|
||||
'historical_only' => $isLot && ! $available];
|
||||
$result = new \stdClass;
|
||||
foreach ($option as $key => $value) {
|
||||
$result->{$key} = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
})->values();
|
||||
}
|
||||
|
||||
public function validHierarchy(int $sectorId, ?string $subsectorId, ?string $activityId, bool $historical = false): bool
|
||||
{
|
||||
if (! $subsectorId || ! $activityId) { return false; }
|
||||
if (! $subsectorId || ! $activityId) {
|
||||
return false;
|
||||
}
|
||||
$sector = DB::table('sectors')->where('id', $sectorId)->whereNull('deleted_at')->where('is_active', true)->exists();
|
||||
$subsector = DB::table('economic_activities')->where('id', $subsectorId)->where('status', 'published')->first();
|
||||
$activity = DB::table('economic_activities')->where('id', $activityId)->where('status', 'published')->first();
|
||||
if (! $sector || ! $subsector || ! $activity || $activity->catalog_version_id !== $subsector->catalog_version_id) { return false; }
|
||||
if (! $sector || ! $subsector || ! $activity || $activity->catalog_version_id !== $subsector->catalog_version_id) {
|
||||
return false;
|
||||
}
|
||||
$manifest = $this->manifest();
|
||||
if ($activity->catalog_version_id !== $manifest['catalog']['id']) {
|
||||
$root = $subsector->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
|
||||
@@ -116,10 +153,15 @@ class EconomicReferenceCatalog
|
||||
return $root && (int) $root->sector_id === $sectorId && $activity->parent_id === $subsector->id;
|
||||
}
|
||||
if ((! $this->available() && ! $historical) || $sectorId !== (int) $manifest['existing']['sector']['id']
|
||||
|| $subsector->code !== '01' || $activity->code !== '01120') { return false; }
|
||||
$current = $activity; $codes = []; $seen = [];
|
||||
|| $subsector->code !== '01' || $activity->code !== '01120') {
|
||||
return false;
|
||||
}
|
||||
$current = $activity;
|
||||
$codes = [];
|
||||
$seen = [];
|
||||
while ($current && ! isset($seen[$current->id])) {
|
||||
$seen[$current->id] = true; array_unshift($codes, $current->code);
|
||||
$seen[$current->id] = true;
|
||||
array_unshift($codes, $current->code);
|
||||
$current = $current->parent_id ? DB::table('economic_activities')->where('id', $current->parent_id)->where('catalog_version_id', $activity->catalog_version_id)->where('status', 'published')->first() : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,19 +4,22 @@ namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Bounded authenticated extension. No generic seeding, arbitrary path or caller-supplied actor. */
|
||||
class EconomicReferenceInstallation
|
||||
{
|
||||
public const MIGRATION = '2026_10_16_120000_extend_economic_reference_hierarchy';
|
||||
|
||||
public const OPERATIONS = ['schema', 'import', 'publish', 'withdraw'];
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function files(): array
|
||||
{
|
||||
return ['app/Services/EconomicReferenceCatalog.php', 'app/Services/EconomicReferenceInstallation.php',
|
||||
@@ -32,13 +35,22 @@ class EconomicReferenceInstallation
|
||||
return hash('sha256', json_encode(array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files()), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
private function directory(): string { return storage_path('app/private/investmoz-v2/economic-references/lot-01'); }
|
||||
private function directory(): string
|
||||
{
|
||||
return storage_path('app/private/investmoz-v2/economic-references/lot-01');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function target(): array
|
||||
{
|
||||
return (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
*/
|
||||
private function qa(array $target): bool
|
||||
{
|
||||
return app()->environment('testing') && str_ends_with($target['database'], '_test') && (int) $target['port'] === 55441
|
||||
@@ -48,20 +60,32 @@ class EconomicReferenceInstallation
|
||||
private function authorize(User $actor, bool $write = false, string $operation = ''): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Acesso reservado à gestão autorizada.');
|
||||
if (! $write) { return; }
|
||||
if (! $write) {
|
||||
return;
|
||||
}
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_if($access->has($actor, 'auditor'), 403, 'A restrição de Auditor permite apenas consulta.');
|
||||
abort_unless($access->mfa($actor), 403, 'Conclua MFA nesta sessão para executar esta ação.');
|
||||
if ($operation === 'schema') { app(PortalProfileInstallation::class)->authorize($actor, true); }
|
||||
if ($operation === 'schema') {
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
}
|
||||
abort_unless(! app()->environment('testing') || $this->qa($this->target()), 403, 'Alvo QA isolado inválido.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function evidence(array $target, string $code, string $operation): array
|
||||
{
|
||||
if ($this->qa($target)) { return ['ready' => true, 'mode' => 'isolated_QA', 'date' => null]; }
|
||||
if (app()->environment('testing')) { return ['ready' => false, 'mode' => 'invalid_QA', 'date' => null]; }
|
||||
if ($this->qa($target)) {
|
||||
return ['ready' => true, 'mode' => 'isolated_QA', 'date' => null];
|
||||
}
|
||||
if (app()->environment('testing')) {
|
||||
return ['ready' => false, 'mode' => 'invalid_QA', 'date' => null];
|
||||
}
|
||||
$path = $this->directory().'/readiness.json';
|
||||
$proof = is_file($path) ? json_decode(file_get_contents($path), true) : [];
|
||||
$proof = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||
$date = strtotime($proof['verified_at'] ?? '');
|
||||
$permission = $proof['active_authorization'] ?? [];
|
||||
$ready = ! config('database.connections.pgsql.url') && in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||
@@ -73,8 +97,8 @@ class EconomicReferenceInstallation
|
||||
&& ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
|
||||
&& str_ends_with($proof['restore_target']['database'] ?? '', '_test') && (int) ($proof['restore_target']['port'] ?? 0) === 55441
|
||||
&& is_file($proof['dump_path'] ?? '') && is_file($proof['files_path'] ?? '')
|
||||
&& hash_equals($proof['dump_sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
|
||||
&& hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))
|
||||
&& hash_equals($proof['dump_sha256'] ?? '', CheckedFile::sha256($proof['dump_path']))
|
||||
&& hash_equals($proof['files_sha256'] ?? '', CheckedFile::sha256($proof['files_path']))
|
||||
&& ($permission['decision_record'] ?? '') !== '' && ($permission['code_hash'] ?? '') === $code
|
||||
&& ($permission['manifest_sha256'] ?? '') === EconomicReferenceCatalog::MANIFEST_SHA256
|
||||
&& in_array($operation, $permission['operations'] ?? [], true);
|
||||
@@ -83,25 +107,35 @@ class EconomicReferenceInstallation
|
||||
'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||
}
|
||||
|
||||
/** No source scan/write in preview. Paths are fixed, private and confined to this lot. */
|
||||
/** No source scan/write in preview. Paths are fixed, private and confined to this lot.
|
||||
* @param array<array-key, mixed> $manifest
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function sources(array $manifest): array
|
||||
{
|
||||
$root = realpath($this->directory()); $sources = [];
|
||||
$root = realpath($this->directory());
|
||||
$sources = [];
|
||||
foreach ($manifest['sources'] as $entry) {
|
||||
$path = $root ? realpath($root.DIRECTORY_SEPARATOR.$entry['relative_path']) : false;
|
||||
$inside = $path && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $root)).'/');
|
||||
$matches = $inside && is_file($path) && filesize($path) === $entry['bytes'] && hash_equals($entry['sha256'], hash_file('sha256', $path));
|
||||
$matches = $inside && is_file($path) && filesize($path) === $entry['bytes'] && hash_equals($entry['sha256'], CheckedFile::sha256($path));
|
||||
$sources[] = ['name' => $entry['name'], 'sha256' => $entry['sha256'], 'bytes' => $entry['bytes'], 'ready' => (bool) $matches];
|
||||
}
|
||||
|
||||
return $sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $manifest
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function referenceRows(array $manifest): array
|
||||
{
|
||||
$rows = [['table' => 'reference_catalog_versions', 'data' => $manifest['catalog']]];
|
||||
foreach (['activities' => 'economic_activities', 'chains' => 'value_chains', 'links' => 'value_chain_links'] as $group => $table) {
|
||||
foreach ($manifest[$group] as $row) { $rows[] = ['table' => $table, 'data' => $row]; }
|
||||
foreach ($manifest[$group] as $row) {
|
||||
$rows[] = ['table' => $table, 'data' => $row];
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
@@ -113,41 +147,67 @@ class EconomicReferenceInstallation
|
||||
->whereRaw("after_data->'result'->'changed' @> ?::jsonb", [json_encode([$id])])->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $manifest
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function references(array $manifest, bool $schemaReady): array
|
||||
{
|
||||
$results = [];
|
||||
foreach ($this->referenceRows($manifest) as $row) {
|
||||
$expected = $row['data']; $table = $row['table'];
|
||||
$expected = $row['data'];
|
||||
$table = $row['table'];
|
||||
$current = DB::table($table)->where('id', $expected['id'])->first();
|
||||
$conflict = false;
|
||||
foreach ($expected as $key => $value) {
|
||||
if (! $current || ($key === 'metadata' && ! $schemaReady)) { continue; }
|
||||
if ($key === 'status') { $conflict = $conflict || ! in_array($current->$key, ['draft', 'published'], true); continue; }
|
||||
if ($key === 'data_classification') { $conflict = $conflict || ! in_array($current->$key, ['internal', 'public'], true); continue; }
|
||||
if (! $current || ($key === 'metadata' && ! $schemaReady)) {
|
||||
continue;
|
||||
}
|
||||
if ($key === 'status') {
|
||||
$conflict = $conflict || ! in_array($current->$key, ['draft', 'published'], true);
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($key === 'data_classification') {
|
||||
$conflict = $conflict || ! in_array($current->$key, ['internal', 'public'], true);
|
||||
|
||||
continue;
|
||||
}
|
||||
$actual = $key === 'metadata' ? json_decode($current->$key, true) : $current->$key;
|
||||
if (OpportunityCanonicalValue::hash($actual) !== OpportunityCanonicalValue::hash($value)) { $conflict = true; }
|
||||
if (OpportunityCanonicalValue::hash($actual) !== OpportunityCanonicalValue::hash($value)) {
|
||||
$conflict = true;
|
||||
}
|
||||
}
|
||||
$identity = DB::table($table)->where('id', '!=', $expected['id']);
|
||||
if ($table === 'reference_catalog_versions') { $identity->where('catalog_code', $expected['catalog_code'])->where('version_no', $expected['version_no'])->where('locale', $expected['locale']); }
|
||||
elseif ($table === 'economic_activities') { $identity->where('catalog_version_id', $expected['catalog_version_id'])->where('code', $expected['code']); }
|
||||
else { $identity->where('source_system', $expected['source_system'])->where('external_id', $expected['external_id']); }
|
||||
if ($table === 'reference_catalog_versions') {
|
||||
$identity->where('catalog_code', $expected['catalog_code'])->where('version_no', $expected['version_no'])->where('locale', $expected['locale']);
|
||||
} elseif ($table === 'economic_activities') {
|
||||
$identity->where('catalog_version_id', $expected['catalog_version_id'])->where('code', $expected['code']);
|
||||
} else {
|
||||
$identity->where('source_system', $expected['source_system'])->where('external_id', $expected['external_id']);
|
||||
}
|
||||
$conflict = $conflict || $identity->exists();
|
||||
if ($table === 'value_chains') {
|
||||
$conflict = $conflict || DB::table($table)->where('id', '!=', $expected['id'])->where('cluster_id', $expected['cluster_id'])->where('code', $expected['code'])->whereNull('deleted_at')->exists();
|
||||
}
|
||||
$results[] = ['table' => $table, 'id' => $expected['id'], 'code' => $expected['code'] ?? $expected['external_id'] ?? $expected['catalog_code'],
|
||||
'status' => $conflict ? 'conflict' : ($current ? 'reuse' : 'insert'), 'current_hash' => $current ? OpportunityCanonicalValue::hash((array) $current) : null,
|
||||
'current_visibility' => $current?->status ?? $current?->data_classification ?? null];
|
||||
'current_visibility' => $current->status ?? $current->data_classification ?? null];
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
$catalog = app(EconomicReferenceCatalog::class); $manifest = $catalog->manifest();
|
||||
$target = $this->target(); $code = $this->fingerprint();
|
||||
$catalog = app(EconomicReferenceCatalog::class);
|
||||
$manifest = $catalog->manifest();
|
||||
$target = $this->target();
|
||||
$code = $this->fingerprint();
|
||||
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
||||
$column = $catalog->schemaAvailable();
|
||||
$unique = DB::selectOne("SELECT 1 FROM pg_constraint WHERE conrelid='public.economic_activities'::regclass AND conname='economic_activities_sector_uq'") !== null;
|
||||
@@ -155,19 +215,31 @@ class EconomicReferenceInstallation
|
||||
$index = DB::selectOne("SELECT 1 FROM pg_indexes WHERE schemaname='public' AND indexname='economic_activities_sector_idx'") !== null;
|
||||
$installed = $ledger && $column && ! $unique && $sectorNullable && $index;
|
||||
$consistent = $installed || (! $ledger && ! $column && $unique && ! $sectorNullable && ! $index);
|
||||
$rows = $this->references($manifest, $column); $sources = $this->sources($manifest); $reasons = [];
|
||||
$rows = $this->references($manifest, $column);
|
||||
$sources = $this->sources($manifest);
|
||||
$reasons = [];
|
||||
foreach (['sector' => 'sectors', 'cluster' => 'economic_clusters'] as $name => $table) {
|
||||
$expected = $manifest['existing'][$name]; $record = DB::table($table)->where('id', $expected['id'])->whereNull('deleted_at')->first();
|
||||
$expected = $manifest['existing'][$name];
|
||||
$record = DB::table($table)->where('id', $expected['id'])->whereNull('deleted_at')->first();
|
||||
foreach (array_filter($expected, fn ($v) => $v !== null) as $field => $value) {
|
||||
if (! $record || (string) ($record->$field ?? '') !== (string) $value) { $reasons[] = 'Identidade/atributos do '.$name.' divergentes do manifesto; não foi usada semelhança de nomes.'; break; }
|
||||
if (! $record || (string) ($record->$field ?? '') !== (string) $value) {
|
||||
$reasons[] = 'Identidade/atributos do '.$name.' divergentes do manifesto; não foi usada semelhança de nomes.';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! $consistent) { $reasons[] = 'Ledger e esquema divergentes; reconciliar antes de instalar.'; }
|
||||
if (collect($rows)->contains('status', 'conflict')) { $reasons[] = 'Conflito de identidade/versão: não será aplicado parcialmente.'; }
|
||||
if (collect($sources)->contains('ready', false)) { $reasons[] = 'Exemplar privado ausente ou com bytes diferentes.'; }
|
||||
if (! $consistent) {
|
||||
$reasons[] = 'Ledger e esquema divergentes; reconciliar antes de instalar.';
|
||||
}
|
||||
if (collect($rows)->contains('status', 'conflict')) {
|
||||
$reasons[] = 'Conflito de identidade/versão: não será aplicado parcialmente.';
|
||||
}
|
||||
if (collect($sources)->contains('ready', false)) {
|
||||
$reasons[] = 'Exemplar privado ausente ou com bytes diferentes.';
|
||||
}
|
||||
$imported = ! collect($rows)->contains(fn ($r) => $r['status'] !== 'reuse');
|
||||
$scanPath = $this->directory().'/scans.json';
|
||||
$scan = is_file($scanPath) ? json_decode(file_get_contents($scanPath), true) : null;
|
||||
$scan = is_file($scanPath) ? json_decode(CheckedFile::read($scanPath), true) : null;
|
||||
$state = ['target' => $target, 'code_hash' => $code, 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256,
|
||||
'migration' => self::MIGRATION, 'installed' => $installed, 'consistent' => $consistent, 'imported' => $imported,
|
||||
'publication' => $catalog->publicationState(), 'rows' => $rows, 'sources' => $sources, 'scan' => $scan,
|
||||
@@ -175,15 +247,27 @@ class EconomicReferenceInstallation
|
||||
$operations = [];
|
||||
foreach (self::OPERATIONS as $operation) {
|
||||
$why = $reasons;
|
||||
try { $this->authorize($actor, true, $operation); } catch (HttpException $e) { $why[] = $e->getMessage(); }
|
||||
try {
|
||||
$this->authorize($actor, true, $operation);
|
||||
} catch (HttpException $e) {
|
||||
$why[] = $e->getMessage();
|
||||
}
|
||||
$evidence = $this->evidence($target, $code, $operation);
|
||||
if (! $evidence['ready']) { $why[] = 'Decisão própria do ativo e prova fresca desta revisão/alvo/backup/restauro necessárias.'; }
|
||||
if ($operation !== 'schema' && ! $installed) { $why[] = 'Instale primeiro o esquema nominal.'; }
|
||||
if (in_array($operation, ['publish', 'withdraw'], true) && ! $imported) { $why[] = 'Importação privada completa necessária antes de publicar/retirar.'; }
|
||||
if (! $evidence['ready']) {
|
||||
$why[] = 'Decisão própria do ativo e prova fresca desta revisão/alvo/backup/restauro necessárias.';
|
||||
}
|
||||
if ($operation !== 'schema' && ! $installed) {
|
||||
$why[] = 'Instale primeiro o esquema nominal.';
|
||||
}
|
||||
if (in_array($operation, ['publish', 'withdraw'], true) && ! $imported) {
|
||||
$why[] = 'Importação privada completa necessária antes de publicar/retirar.';
|
||||
}
|
||||
if (in_array($operation, ['publish', 'withdraw'], true) && ! DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('action', 'import')->where('after_data->result->manifest_sha256', EconomicReferenceCatalog::MANIFEST_SHA256)->exists()) {
|
||||
$why[] = 'Execute a importação privada autenticada, inclusive para registos reutilizados.';
|
||||
}
|
||||
if ($operation === 'withdraw' && $state['publication'] === 'private') { $why[] = 'O lote ainda não teve publicação para retirar.'; }
|
||||
if ($operation === 'withdraw' && $state['publication'] === 'private') {
|
||||
$why[] = 'O lote ainda não teve publicação para retirar.';
|
||||
}
|
||||
if ($operation === 'withdraw' && collect($rows)->contains(fn ($r) => $r['status'] === 'reuse'
|
||||
&& in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id']))) {
|
||||
$why[] = 'Há referências anteriores já públicas reutilizadas: reconciliar o mapa de retirada antes de agir.';
|
||||
@@ -195,22 +279,34 @@ class EconomicReferenceInstallation
|
||||
return [...$state, 'operations' => $operations];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $manifest
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function scan(array $manifest): array
|
||||
{
|
||||
$directory = realpath($this->directory()); $records = [];
|
||||
abort_unless($directory, 422, 'Área privada do lote indisponível.');
|
||||
$directory = realpath($this->directory());
|
||||
$records = [];
|
||||
abort_unless(is_string($directory), 422, 'Área privada do lote indisponível.');
|
||||
$paths = [['name' => 'manifesto', 'path' => database_path('data/economic-references-lot-01.json'), 'sha256' => EconomicReferenceCatalog::MANIFEST_SHA256]];
|
||||
foreach ($manifest['sources'] as $source) { $paths[] = ['name' => $source['name'], 'path' => $directory.'/'.$source['relative_path'], 'sha256' => $source['sha256']]; }
|
||||
foreach ($manifest['sources'] as $source) {
|
||||
$paths[] = ['name' => $source['name'], 'path' => $directory.'/'.$source['relative_path'], 'sha256' => $source['sha256']];
|
||||
}
|
||||
foreach ($paths as $file) {
|
||||
abort_unless(is_file($file['path']) && hash_equals($file['sha256'], hash_file('sha256', $file['path'])), 409, 'Originais alterados após prévia.');
|
||||
abort_unless(is_file($file['path']) && hash_equals($file['sha256'], CheckedFile::sha256($file['path'])), 409, 'Originais alterados após prévia.');
|
||||
// Scanner's path confinement uses the private source directory; manifest is scanned via a private exact copy.
|
||||
$path = $file['path'];
|
||||
if ($file['name'] === 'manifesto') { $path = $directory.'/manifest-scanned.json'; file_put_contents($path, file_get_contents($file['path'])); }
|
||||
$result = app(MalwareScanner::class)->scan($path, filesize($path), $directory);
|
||||
if ($result['signatures_at'] instanceof \DateTimeInterface) { $result['signatures_at'] = $result['signatures_at']->format(DATE_ATOM); }
|
||||
if ($file['name'] === 'manifesto') {
|
||||
$path = $directory.'/manifest-scanned.json';
|
||||
file_put_contents($path, file_get_contents($file['path']));
|
||||
}
|
||||
$result = app(MalwareScanner::class)->scan($path, CheckedFile::size($path), $directory);
|
||||
if ($result['signatures_at'] instanceof \DateTimeInterface) {
|
||||
$result['signatures_at'] = $result['signatures_at']->format(DATE_ATOM);
|
||||
}
|
||||
$records[] = ['name' => $file['name'], 'sha256' => $file['sha256'], 'scan' => $result];
|
||||
abort_unless($result['result'] === 'clean', 423, 'Scan não concluído ou não limpo para '.$file['name'].'. Nenhuma referência foi importada/publicada.');
|
||||
abort_unless(hash_equals($file['sha256'], hash_file('sha256', $file['path'])) && hash_equals($file['sha256'], hash_file('sha256', $path)), 409, 'Bytes alterados durante o scan.');
|
||||
abort_unless(CheckedFile::matches($file['path'], $file['sha256']) && CheckedFile::matches($path, $file['sha256']), 409, 'Bytes alterados durante o scan.');
|
||||
}
|
||||
$proof = ['at' => now()->toIso8601String(), 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'files' => $records];
|
||||
file_put_contents($directory.'/scans.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
@@ -218,11 +314,15 @@ class EconomicReferenceInstallation
|
||||
return $proof;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(User $actor, string $operation, array $input): array
|
||||
{
|
||||
abort_unless(in_array($operation, self::OPERATIONS, true), 404);
|
||||
$this->authorize($actor, true, $operation);
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', 'reason', '_token']), 422, 'Campo de ator, manifesto ou conteúdo arbitrário não permitido.');
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', 'reason', '_token']) !== [], 422, 'Campo de ator, manifesto ou conteúdo arbitrário não permitido.');
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $operation, $data) {
|
||||
@@ -235,44 +335,73 @@ class EconomicReferenceInstallation
|
||||
|
||||
return [...$receipt['result'], 'replayed' => true, 'current_publication' => app(EconomicReferenceCatalog::class)->publicationState()];
|
||||
}
|
||||
$plan = $this->preview($actor); $phase = $plan['operations'][$operation];
|
||||
$plan = $this->preview($actor);
|
||||
$phase = $plan['operations'][$operation];
|
||||
abort_unless(hash_equals($phase['hash'], $data['hash']), 409, 'Alvo, ator, revisão ou estado alterados; consulte nova prévia.');
|
||||
abort_unless($phase['ready'], 422, implode(' ', $phase['reasons']));
|
||||
$manifest = app(EconomicReferenceCatalog::class)->manifest(); $changed = []; $reused = [];
|
||||
foreach ($this->referenceRows($manifest) as $row) { DB::table($row['table'])->where('id', $row['data']['id'])->lockForUpdate()->first(); }
|
||||
$manifest = app(EconomicReferenceCatalog::class)->manifest();
|
||||
$changed = [];
|
||||
$reused = [];
|
||||
foreach ($this->referenceRows($manifest) as $row) {
|
||||
DB::table($row['table'])->where('id', $row['data']['id'])->lockForUpdate()->first();
|
||||
}
|
||||
DB::table('sectors')->where('id', $manifest['existing']['sector']['id'])->lockForUpdate()->first();
|
||||
DB::table('economic_clusters')->where('id', $manifest['existing']['cluster']['id'])->lockForUpdate()->first();
|
||||
// Recheck after locks in case another approved writer changed a reused master.
|
||||
abort_unless($this->preview($actor)['operations'][$operation]['hash'] === $phase['hash'], 409, 'Referências alteradas durante a preparação da operação.');
|
||||
if ($operation === 'schema' && ! $plan['installed']) {
|
||||
config(['economic_references.authenticated_installation' => true]);
|
||||
try { abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na migration nominal.'); }
|
||||
finally { config(['economic_references.authenticated_installation' => false]); }
|
||||
try {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na migration nominal.');
|
||||
} finally {
|
||||
config(['economic_references.authenticated_installation' => false]);
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'], 500, 'Esquema instalado não corresponde ao plano.');
|
||||
$changed[] = self::MIGRATION;
|
||||
} elseif ($operation === 'import') {
|
||||
$scan = $this->scan($manifest);
|
||||
foreach ($this->referenceRows($manifest) as $i => $row) {
|
||||
if ($plan['rows'][$i]['status'] === 'reuse') { $reused[] = $row['data']['id']; continue; }
|
||||
$values = $row['data']; if (isset($values['metadata'])) { $values['metadata'] = json_encode($values['metadata'], JSON_THROW_ON_ERROR); }
|
||||
if ($plan['rows'][$i]['status'] === 'reuse') {
|
||||
$reused[] = $row['data']['id'];
|
||||
|
||||
continue;
|
||||
}
|
||||
$values = $row['data'];
|
||||
if (isset($values['metadata'])) {
|
||||
$values['metadata'] = json_encode($values['metadata'], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
DB::table($row['table'])->insert([...$values, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$changed[] = $values['id'];
|
||||
}
|
||||
} elseif ($operation === 'publish' || $operation === 'withdraw') {
|
||||
if ($operation === 'publish') { $scan = $this->scan($manifest); }
|
||||
if ($operation === 'publish') {
|
||||
$scan = $this->scan($manifest);
|
||||
}
|
||||
foreach ($this->referenceRows($manifest) as $row) {
|
||||
$table = $row['table']; $record = DB::table($table)->where('id', $row['data']['id'])->lockForUpdate()->first();
|
||||
$table = $row['table'];
|
||||
$record = DB::table($table)->where('id', $row['data']['id'])->lockForUpdate()->first();
|
||||
if (in_array($table, ['reference_catalog_versions', 'economic_activities'], true)) {
|
||||
if ($operation === 'publish' && $record->status === 'draft') {
|
||||
DB::table($table)->where('id', $record->id)->update(['status' => 'published', 'updated_at' => now()]); $changed[] = $record->id;
|
||||
} else { $reused[] = $record->id; }
|
||||
DB::table($table)->where('id', $record->id)->update(['status' => 'published', 'updated_at' => now()]);
|
||||
$changed[] = $record->id;
|
||||
} else {
|
||||
$reused[] = $record->id;
|
||||
}
|
||||
} else {
|
||||
$visibility = $operation === 'publish' ? 'public' : 'internal';
|
||||
// Withdrawal touches only objects this importer created, never pre-existing public references.
|
||||
$createdHere = $this->createdHere($record->id);
|
||||
if ($operation === 'withdraw' && ! $createdHere) { $reused[] = $record->id; continue; }
|
||||
if ($record->data_classification !== $visibility) { DB::table($table)->where('id', $record->id)->update(['data_classification' => $visibility, 'updated_at' => now()]); $changed[] = $record->id; }
|
||||
else { $reused[] = $record->id; }
|
||||
if ($operation === 'withdraw' && ! $createdHere) {
|
||||
$reused[] = $record->id;
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($record->data_classification !== $visibility) {
|
||||
DB::table($table)->where('id', $record->id)->update(['data_classification' => $visibility, 'updated_at' => now()]);
|
||||
$changed[] = $record->id;
|
||||
} else {
|
||||
$reused[] = $record->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -280,7 +409,9 @@ class EconomicReferenceInstallation
|
||||
'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'code_hash' => $plan['code_hash'], 'replayed' => false,
|
||||
'publications' => $operation === 'publish' ? 'references only; no investment or original source publication' : 'none', 'business_records_changed' => 0,
|
||||
'receipt' => $data['idempotency_key'], 'scan' => $scan ?? null];
|
||||
if ($operation === 'import') { $result['previously_public'] = array_values(array_column(array_filter($plan['rows'], fn ($r) => $r['status'] === 'reuse' && in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id'])), 'id')); }
|
||||
if ($operation === 'import') {
|
||||
$result['previously_public'] = array_column(array_filter($plan['rows'], fn ($r) => $r['status'] === 'reuse' && in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id'])), 'id');
|
||||
}
|
||||
DB::table('audit_events')->insert(['source_system' => EconomicReferenceCatalog::SOURCE, 'entity_type' => 'economic-reference-batch', 'entity_id' => $manifest['catalog']['id'],
|
||||
'actor_user_id' => $actor->id, 'correlation_id' => $data['idempotency_key'], 'action' => $operation, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
@@ -12,75 +14,139 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
|
||||
class EditorialInstallation
|
||||
{
|
||||
public const SOURCE='editorial-schema-installation';
|
||||
public const MIGRATION='2026_10_18_160000_add_portal_editorial_content';
|
||||
public const SOURCE = 'editorial-schema-installation';
|
||||
|
||||
public const MIGRATION = '2026_10_18_160000_add_portal_editorial_content';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function files(): array
|
||||
{
|
||||
return ['app/Http/Controllers/EditorialArticleController.php', 'app/Http/Controllers/PortalManagementController.php', 'app/Http/Controllers/PortalServicesController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Services/InvestmentCatalogue.php', 'app/Services/LegacyContent.php', 'app/Services/OpportunityClassification.php', 'routes/web.php', 'database/migrations/2026_10_18_160000_add_portal_editorial_content.php', 'resources/js/pages/management/editor.tsx', 'resources/js/pages/portal/article-editor.tsx', 'resources/js/pages/portal/article.tsx', 'resources/js/pages/portal/document.tsx', 'resources/js/pages/portal/manage.tsx', 'app/Services/EditorialInstallation.php', 'resources/views/management/editorial-installation.blade.php', 'resources/views/management/editorial-mfa.blade.php'];
|
||||
}
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
|
||||
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
|
||||
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
|
||||
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
|
||||
$files = array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files());
|
||||
foreach (File::allFiles(public_path('build')) as $file) {
|
||||
$files[] = ['public/build/'.$file->getRelativePathname(), hash_file('sha256', $file->getPathname())];
|
||||
}
|
||||
usort($files, fn ($a, $b) => strcmp($a[0], $b[0]));
|
||||
|
||||
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
private function authorize(User $actor,bool $write=false): void
|
||||
|
||||
private function authorize(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
|
||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'), 403, 'Gestão autorizada necessária.');
|
||||
if ($write) {
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
}
|
||||
}
|
||||
private function evidence(array $target,string $code): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function evidence(array $target, string $code): array
|
||||
{
|
||||
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
|
||||
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
|
||||
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
|
||||
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
|
||||
$path=storage_path('app/private/investmoz-v2/editorial/readiness.json');
|
||||
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
|
||||
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
|
||||
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
|
||||
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
|
||||
$qa = app()->environment('testing') && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test')
|
||||
&& config('database.connections.pgsql.host') === '127.0.0.1' && ! config('database.connections.pgsql.url');
|
||||
if ($qa) {
|
||||
return ['ready' => true, 'mode' => 'isolated_QA'];
|
||||
}
|
||||
if (app()->environment('testing')) {
|
||||
return ['ready' => false, 'mode' => 'invalid_QA'];
|
||||
}
|
||||
$path = storage_path('app/private/investmoz-v2/editorial/readiness.json');
|
||||
$p = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||
$date = strtotime($p['verified_at'] ?? '');
|
||||
$auth = $p['active_authorization'] ?? [];
|
||||
$ready = $target['database'] === 'investemoz' && (int) $target['port'] === 5432 && ! config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||
&& ($p['target']['database'] ?? '') === $target['database'] && (int) ($p['target']['port'] ?? 0) === (int) $target['port']
|
||||
&& ($p['code_hash'] ?? '') === $code && $date !== false && $date <= time() && $date >= time() - 86400
|
||||
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
|
||||
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===self::MIGRATION;
|
||||
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
|
||||
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int) ($p['restore_target']['port'] ?? 0) === 55441 && str_ends_with($p['restore_target']['database'] ?? '', '_test')
|
||||
&& ($auth['decision_record'] ?? '') !== '' && ($auth['code_hash'] ?? '') === $code && ($auth['migration'] ?? '') === self::MIGRATION;
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
$file = $p[$kind.'_path'] ?? '';
|
||||
$ready = $ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '', CheckedFile::sha256($file));
|
||||
}
|
||||
|
||||
return ['ready' => $ready, 'mode' => 'active_requires_own_authorization_and_fresh_proof', 'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
|
||||
$ledgerCount=DB::table('migrations')->where('migration',self::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('portal_resources','editorial_content');
|
||||
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='portal_resources' AND column_name='editorial_content'");
|
||||
$correct=$shape && $shape->data_type==='jsonb' && $shape->is_nullable==='YES';
|
||||
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
|
||||
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
|
||||
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
|
||||
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
|
||||
$state=['target'=>$target,'migration'=>self::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
|
||||
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
|
||||
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
|
||||
$this->authorize($actor);
|
||||
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$code = $this->fingerprint();
|
||||
$ledgerCount = DB::table('migrations')->where('migration', self::MIGRATION)->count();
|
||||
$ledger = $ledgerCount === 1;
|
||||
$column = Schema::hasColumn('portal_resources', 'editorial_content');
|
||||
$shape = DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='portal_resources' AND column_name='editorial_content'");
|
||||
$correct = $shape && $shape->data_type === 'jsonb' && $shape->is_nullable === 'YES';
|
||||
$consistent = ($ledger && $column && $correct) || ($ledgerCount === 0 && ! $column);
|
||||
$reasons = [];
|
||||
if (! $consistent) {
|
||||
$reasons[] = 'Ledger e coluna divergentes; reconciliar sem instalação parcial.';
|
||||
}
|
||||
try {
|
||||
$this->authorize($actor, true);
|
||||
} catch (HttpException $e) {
|
||||
$reasons[] = $e->getMessage();
|
||||
}
|
||||
$evidence = $this->evidence($target, $code);
|
||||
if (! $evidence['ready']) {
|
||||
$reasons[] = 'Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';
|
||||
}
|
||||
$state = ['target' => $target, 'migration' => self::MIGRATION, 'code_hash' => $code, 'installed' => $ledger && $column,
|
||||
'consistent' => $consistent, 'ready' => $reasons === [], 'reasons' => $reasons, 'evidence' => $evidence];
|
||||
|
||||
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||
}
|
||||
public function apply(User $actor,array $input): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor,true);
|
||||
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
|
||||
return DB::transaction(function()use($actor,$data){
|
||||
DB::select('SELECT pg_advisory_xact_lock(181026,160000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
|
||||
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
|
||||
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
|
||||
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
|
||||
if(!$plan['installed']){
|
||||
config(['editorial.authenticated_installation'=>true]);
|
||||
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.self::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
|
||||
finally{config(['editorial.authenticated_installation'=>false]);}
|
||||
$this->authorize($actor, true);
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', '_token']) !== [], 422, 'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(181026,160000)');
|
||||
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$old = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $data['idempotency_key'])->first();
|
||||
if ($old) {
|
||||
$receipt = json_decode($old->after_data, true);
|
||||
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave já utilizada com outro ator ou conteúdo.');
|
||||
|
||||
return [...$receipt['result'], 'replayed' => true];
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
|
||||
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'portal-editorial-schema','entity_id'=>null,'actor_user_id'=>$actor->id,
|
||||
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
|
||||
$plan = $this->preview($actor);
|
||||
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Prévia alterada; consulte novamente.');
|
||||
abort_unless($plan['ready'], 422, implode(' ', $plan['reasons']));
|
||||
if (! $plan['installed']) {
|
||||
config(['editorial.authenticated_installation' => true]);
|
||||
try {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na instalação nominal.');
|
||||
} finally {
|
||||
config(['editorial.authenticated_installation' => false]);
|
||||
}
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'], 500, 'Esquema nominal inconsistente.');
|
||||
$result = ['migration' => $plan['migration'], 'code_hash' => $plan['code_hash'], 'target' => $plan['target'], 'changed' => ! $plan['installed'], 'business_records_changed' => 0, 'replayed' => false, 'receipt' => $data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'portal-editorial-schema', 'entity_id' => null, 'actor_user_id' => $actor->id,
|
||||
'correlation_id' => $data['idempotency_key'], 'action' => 'schema', 'data_classification' => 'restricted', 'after_data' => json_encode(['request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\CheckedFile;
|
||||
use GuzzleHttp\Psr7\Uri;
|
||||
use GuzzleHttp\Psr7\UriResolver;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
@@ -11,7 +13,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
/** Reads verified originals without writing a derived edition or changing publication. */
|
||||
final class EditorialReading
|
||||
{
|
||||
public function publicResources()
|
||||
public function publicResources(): Builder
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->where('r.published', true)->where('r.rights_status', 'authorized')->where('d.rights_status', 'authorized')
|
||||
@@ -19,9 +21,12 @@ final class EditorialReading
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256');
|
||||
}
|
||||
|
||||
public function original(object $resource): ?array
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function original(\stdClass $resource): ?array
|
||||
{
|
||||
$document = DB::table('documents')->find($resource->document_id);
|
||||
$document = DB::table('documents')->where('id', $resource->document_id)->first();
|
||||
if (! $document || $document->status !== 'active' || $document->malware_scan_status !== 'clean' || ! in_array($document->media_type, ['text/plain', 'application/json'], true)) {
|
||||
return null;
|
||||
}
|
||||
@@ -40,7 +45,11 @@ final class EditorialReading
|
||||
return trim(html_entity_decode(strip_tags(preg_replace('~</(?:p|div|li|h[1-6]|tr)>|<br\s*/?>~i', "\n\n", $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
|
||||
}
|
||||
|
||||
public function content(object $resource, ?array $original): array
|
||||
/**
|
||||
* @param array<array-key, mixed>|null $original
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function content(\stdClass $resource, ?array $original): array
|
||||
{
|
||||
return $resource->editorial_content ? json_decode($resource->editorial_content, true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['body' => $this->plain($original['content_html'] ?? ''), 'image_resource_id' => null, 'image_mode' => 'original', 'preserve_original_html' => true];
|
||||
@@ -60,19 +69,23 @@ final class EditorialReading
|
||||
}
|
||||
}
|
||||
|
||||
public function reading(object $resource, ?array $override = null, bool $private = false): array
|
||||
/**
|
||||
* @param array<array-key, mixed>|null $override
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function reading(\stdClass $resource, ?array $override = null, bool $private = false): array
|
||||
{
|
||||
$original = $this->original($resource);
|
||||
$content = $override ?? $this->content($resource, $original);
|
||||
abort_unless(trim($content['body'] ?? '') !== '', 404, 'Este documento não contém um artigo legível.');
|
||||
$document = DB::table('documents')->find($resource->document_id);
|
||||
$document = DB::table('documents')->where('id', $resource->document_id)->first();
|
||||
// The original is verified above; ordinary text adaptations retain the binary gate too.
|
||||
app(VerifiedDocumentBinary::class)->respond($document);
|
||||
$mode = $content['image_mode'] ?? (! empty($content['image_resource_id']) ? 'selected' : 'none');
|
||||
$originalImageUrl = $this->sourceUrl($original['image_source_url'] ?? null, $original['source_url'] ?? null);
|
||||
$expectedImageSha = $original['image_sha256'] ?? null;
|
||||
if (! $expectedImageSha && $originalImageUrl === 'https://investemoz.tempo.co.mz/images/tempo-background.png') {
|
||||
foreach (json_decode(file_get_contents(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $accepted) {
|
||||
foreach (json_decode(CheckedFile::read(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $accepted) {
|
||||
if ($accepted['sha256'] === $document->sha256) {
|
||||
$expectedImageSha = $accepted['original_image_sha256'] ?? null;
|
||||
break;
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use App\Policies\ExistingBusinessPolicy;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -19,8 +20,12 @@ use Illuminate\Validation\ValidationException;
|
||||
class ExistingBusinessClassification
|
||||
{
|
||||
public const VERSION = 'business-classification-20261016-v1';
|
||||
|
||||
private const ACTIONS = ['classification_prepared', 'classification_reviewed', 'classification_disclosed', 'classification_withdrawn'];
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function context(ExistingBusiness $business): array
|
||||
{
|
||||
$revision = DB::table('existing_business_revisions')->where('business_id', $business->id)->whereIn('action', self::ACTIONS)->orderByDesc('version_no')->first(['snapshot']);
|
||||
@@ -33,11 +38,18 @@ class ExistingBusinessClassification
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
private function hash(array $row): string
|
||||
{
|
||||
return OpportunityCanonicalValue::hash($row);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
private function evidence(array $row, ExistingBusiness $business): ?array
|
||||
{
|
||||
$id = $row['classification']['document_id'] ?? null;
|
||||
@@ -51,6 +63,9 @@ class ExistingBusinessClassification
|
||||
return $document ? (array) $document : ['unavailable' => $id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
private function evidenceHash(array $row, ExistingBusiness $business): ?string
|
||||
{
|
||||
$evidence = $this->evidence($row, $business);
|
||||
@@ -58,6 +73,9 @@ class ExistingBusinessClassification
|
||||
return $evidence === null ? null : OpportunityCanonicalValue::hash($evidence);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $rows
|
||||
*/
|
||||
private function validateRows(array $rows, ExistingBusiness $business, bool $confirming = false): void
|
||||
{
|
||||
$seen = [];
|
||||
@@ -80,7 +98,8 @@ class ExistingBusinessClassification
|
||||
if (array_diff(array_keys($row), ['related_id', 'relation_type', 'classification'])) {
|
||||
$fail('classification', 'Metadados de decisão ou campos desconhecidos não podem ser enviados pelo autor.');
|
||||
}
|
||||
$c = $row['classification']; $kind = $c['target_type'];
|
||||
$c = $row['classification'];
|
||||
$kind = $c['target_type'];
|
||||
if (($kind === 'sector' && ! ctype_digit($row['related_id'])) || ($kind !== 'sector' && ! Str::isUuid($row['related_id']))) {
|
||||
$fail('related_id', 'Identificador de referência inválido.');
|
||||
}
|
||||
@@ -91,7 +110,9 @@ class ExistingBusinessClassification
|
||||
$fail('classification.purpose', 'Regime, admissão e benefício usam a relação regulatória com a zona.');
|
||||
}
|
||||
$identity = OpportunityClassification::TARGETS[$kind][0].':'.$row['related_id'].':'.$c['purpose'];
|
||||
if (isset($seen[$identity])) { $fail('related_id', 'Referência e finalidade já associadas; recupere a relação existente.'); }
|
||||
if (isset($seen[$identity])) {
|
||||
$fail('related_id', 'Referência e finalidade já associadas; recupere a relação existente.');
|
||||
}
|
||||
$seen[$identity] = true;
|
||||
if (! empty($c['valid_from']) && ! empty($c['valid_until']) && $c['valid_until'] < $c['valid_from']) {
|
||||
$fail('classification.valid_until', 'O fim da vigência precede o início.');
|
||||
@@ -100,13 +121,17 @@ class ExistingBusinessClassification
|
||||
$fail('classification.authority_id', 'Entidade competente não consta do catálogo publicado.');
|
||||
}
|
||||
$evidence = $this->evidence($row, $business);
|
||||
if ($evidence && isset($evidence['unavailable'])) { $fail('classification.document_id', 'Documento não está associado a este anúncio.'); }
|
||||
if ($evidence && isset($evidence['unavailable'])) {
|
||||
$fail('classification.document_id', 'Documento não está associado a este anúncio.');
|
||||
}
|
||||
if (($c['external_status'] ?? '') === 'documented_granted' && (empty($c['document_id']) || empty(trim($c['external_act_reference'] ?? '')))) {
|
||||
$fail('classification.external_act_reference', 'Um ato declarado como concedido exige documento e referência próprios.');
|
||||
}
|
||||
if ($confirming) {
|
||||
foreach (['criteria', 'justification', 'source_reference', 'citation'] as $key) {
|
||||
if (empty(trim($c[$key] ?? ''))) { $fail('classification.'.$key, 'Confirmação exige fundamento e fonte/citação por relação; a preparação pode continuar preliminar.'); }
|
||||
if (empty(trim($c[$key] ?? ''))) {
|
||||
$fail('classification.'.$key, 'Confirmação exige fundamento e fonte/citação por relação; a preparação pode continuar preliminar.');
|
||||
}
|
||||
}
|
||||
if ($evidence && ($evidence['status'] !== 'active' || $evidence['deleted_at'] !== null || $evidence['malware_scan_status'] !== 'clean'
|
||||
|| ! hash_equals(trim($evidence['sha256']), trim((string) $evidence['malware_scanned_sha256']))
|
||||
@@ -117,13 +142,21 @@ class ExistingBusinessClassification
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
* @param array<array-key, mixed> $state
|
||||
*/
|
||||
private function effective(ExistingBusiness $business, array $row, array $state): string
|
||||
{
|
||||
$decision = $state['decisions'][$this->hash($row)] ?? null;
|
||||
if (! $decision) { return $row['classification']['requested_state'] ?? 'preliminary'; }
|
||||
if ($decision['state'] !== 'confirmed') { return $decision['state']; }
|
||||
if (! $decision) {
|
||||
return $row['classification']['requested_state'] ?? 'preliminary';
|
||||
}
|
||||
if ($decision['state'] !== 'confirmed') {
|
||||
return $decision['state'];
|
||||
}
|
||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||
$reviewer = User::find($decision['actor_id']);
|
||||
$reviewer = User::whereKey($decision['actor_id'])->first();
|
||||
if (! $reviewer || ! app(ExistingBusinessPolicy::class)->classificationReviewerScope($reviewer, $business, $dimension)
|
||||
|| (int) ($state['authors'][$this->hash($row)] ?? 0) === (int) $reviewer->id
|
||||
|| ($decision['evidence_hash'] ?? null) !== $this->evidenceHash($row, $business)) {
|
||||
@@ -133,13 +166,17 @@ class ExistingBusinessClassification
|
||||
return 'confirmed';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function privateView(User $actor, ExistingBusiness $business): array
|
||||
{
|
||||
Gate::forUser($actor)->authorize('view', $business);
|
||||
$state = $this->context($business);
|
||||
$rows = [];
|
||||
foreach ($state['relations'] as $row) {
|
||||
$hash = $this->hash($row); $dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||
$hash = $this->hash($row);
|
||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||
$rows[] = ['hash' => $hash, 'relation' => $row, 'dimension' => $dimension, 'state' => $this->effective($business, $row, $state),
|
||||
'can_review' => Gate::forUser($actor)->allows('reviewClassification', $business) && app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
||||
&& (int) ($state['authors'][$hash] ?? 0) !== (int) $actor->id,
|
||||
@@ -158,6 +195,9 @@ class ExistingBusinessClassification
|
||||
'documents' => $documents->map(fn ($d) => ['id' => $d->id, 'payload' => ['title' => $d->file_name], 'file' => ['file_name' => $d->file_name]])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function act(User $actor, string $id, array $input): ExistingBusiness
|
||||
{
|
||||
$data = Validator::make($input, [
|
||||
@@ -167,26 +207,32 @@ class ExistingBusinessClassification
|
||||
'hash' => ['required_if:action,review', 'string', 'size:64'],
|
||||
'state' => ['required_if:action,review', Rule::in(['in_validation', 'confirmed', 'rejected', 'archived', 'revoked'])],
|
||||
], ['reason.required' => 'Indique o fundamento da ação.', 'reason.min' => 'O fundamento deve ter pelo menos 20 caracteres.'])->validate();
|
||||
abort_if(array_diff(array_keys($input), ['action', 'version_no', 'reason', 'rows', 'hash', 'state']), 422, 'Esta ação aceita apenas campos da classificação.');
|
||||
abort_if(array_diff(array_keys($input), ['action', 'version_no', 'reason', 'rows', 'hash', 'state']) !== [], 422, 'Esta ação aceita apenas campos da classificação.');
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
$action = $data['action'];
|
||||
Gate::forUser($actor)->authorize(match ($action) { 'prepare' => 'prepareClassification', 'review' => 'reviewClassification', default => 'discloseClassification' }, $business);
|
||||
Gate::forUser($actor)->authorize(match ($action) {
|
||||
'prepare' => 'prepareClassification', 'review' => 'reviewClassification', default => 'discloseClassification'
|
||||
}, $business);
|
||||
abort_unless($business->version_no === (int) $data['version_no'], 409, 'A versão mudou. Atualize antes de decidir; preserve os valores preparados.');
|
||||
$state = $this->context($business);
|
||||
if ($action === 'prepare') {
|
||||
$this->validateRows($data['rows'], $business);
|
||||
$state['relations'] = $data['rows'];
|
||||
foreach ($data['rows'] as $row) { $state['authors'][$this->hash($row)] ??= $actor->id; }
|
||||
foreach ($data['rows'] as $row) {
|
||||
$state['authors'][$this->hash($row)] ??= $actor->id;
|
||||
}
|
||||
} elseif ($action === 'review') {
|
||||
$search = in_array($data['state'], ['revoked', 'archived'], true) ? [...$state['relations'], ...$state['publication']] : $state['relations'];
|
||||
$row = collect($search)->first(fn ($r) => hash_equals($this->hash($r), $data['hash']));
|
||||
$row = collect(StructuredData::collectionItems($search))->first(fn ($r) => hash_equals($this->hash($r), $data['hash']));
|
||||
abort_unless($row, 409, 'Associação inexistente nesta versão.');
|
||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||
abort_unless(app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
||||
&& (int) ($state['authors'][$data['hash']] ?? 0) !== (int) $actor->id, 403, 'Revisão exige responsabilidade e independência aplicáveis.');
|
||||
if ($data['state'] === 'confirmed') { $this->validateRows([$row], $business, true); }
|
||||
if ($data['state'] === 'confirmed') {
|
||||
$this->validateRows([$row], $business, true);
|
||||
}
|
||||
$prior = $state['decisions'][$data['hash']] ?? [];
|
||||
$decision = ['state' => $data['state'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'],
|
||||
'evidence_hash' => $this->evidenceHash($row, $business), 'version' => ($prior['version'] ?? 0) + 1];
|
||||
@@ -216,21 +262,35 @@ class ExistingBusinessClassification
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed>|null $preparedState
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicRows(ExistingBusiness $business, ?array $preparedState = null): array
|
||||
{
|
||||
if ($business->trashed() || $business->status !== 'published' || ! $business->published_at || $business->published_at->isFuture()
|
||||
|| ($business->expires_at && $business->expires_at->isBefore(today()))) { return []; }
|
||||
$state = $preparedState ?? $this->context($business); $rows = [];
|
||||
|| ($business->expires_at && $business->expires_at->isBefore(today()))) {
|
||||
return [];
|
||||
}
|
||||
$state = $preparedState ?? $this->context($business);
|
||||
$rows = [];
|
||||
foreach ($state['publication'] as $row) {
|
||||
$c = $row['classification']; $kind = $c['target_type'];
|
||||
if (($c['disclosure'] ?? '') !== 'public' || ! isset(OpportunityClassification::TARGETS[$kind])) { continue; }
|
||||
$c = $row['classification'];
|
||||
$kind = $c['target_type'];
|
||||
if (($c['disclosure'] ?? '') !== 'public' || ! isset(OpportunityClassification::TARGETS[$kind])) {
|
||||
continue;
|
||||
}
|
||||
$target = app(OpportunityClassification::class)->targets($kind)->where('id', $row['related_id'])->first();
|
||||
if (! $target || (! empty($c['valid_from']) && $c['valid_from'] > today()->toDateString()) || (! empty($c['valid_until']) && $c['valid_until'] < today()->toDateString())) { continue; }
|
||||
if (! $target || (! empty($c['valid_from']) && $c['valid_from'] > today()->toDateString()) || (! empty($c['valid_until']) && $c['valid_until'] < today()->toDateString())) {
|
||||
continue;
|
||||
}
|
||||
$effective = $this->effective($business, $row, $state);
|
||||
if (in_array($effective, ['archived', 'revoked'], true)) { continue; }
|
||||
if (in_array($effective, ['archived', 'revoked'], true)) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['dimension' => OpportunityClassification::TARGETS[$kind][2], 'target_type' => $kind, 'target_id' => (string) $row['related_id'],
|
||||
'label' => $target->{OpportunityClassification::TARGETS[$kind][1]}, 'target_code' => $target->code ?? null,
|
||||
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)?->path ?? []) : [], 'purpose' => $c['purpose'], 'purpose_label' => OpportunityClassification::PURPOSES[$c['purpose']],
|
||||
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)->path ?? []) : [], 'purpose' => $c['purpose'], 'purpose_label' => OpportunityClassification::PURPOSES[$c['purpose']],
|
||||
'state' => $effective, 'source_reference' => $c['source_reference'] ?? null, 'citation' => $c['citation'] ?? null,
|
||||
'authority_id' => $c['authority_id'] ?? null, 'production_stage' => $c['production_stage'] ?? null,
|
||||
'external_status' => $c['external_status'], 'valid_from' => $c['valid_from'] ?? null, 'valid_until' => $c['valid_until'] ?? null];
|
||||
@@ -239,6 +299,9 @@ class ExistingBusinessClassification
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function filterRules(): array
|
||||
{
|
||||
return ['association_type' => ['nullable', Rule::in(array_keys(OpportunityClassification::TARGETS))],
|
||||
@@ -247,25 +310,41 @@ class ExistingBusinessClassification
|
||||
'chain_id' => ['nullable', 'uuid'], 'authority_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid']];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @param Builder<ExistingBusiness> $query
|
||||
*/
|
||||
public function constrain(Builder $query, array $filters): void
|
||||
{
|
||||
$filters = array_filter(array_intersect_key($filters, $this->filterRules()), fn ($v) => $v !== null && $v !== '');
|
||||
if ($filters === []) { return; }
|
||||
if ($filters === []) {
|
||||
return;
|
||||
}
|
||||
$ids = [];
|
||||
(clone $query)->reorder()->select('existing_businesses.*')->chunkById(200, function ($records) use ($filters, &$ids) {
|
||||
foreach ($records as $business) {
|
||||
$rows = $this->publicRows($business); $same = array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_purpose', 'association_state']));
|
||||
$rows = $this->publicRows($business);
|
||||
$same = array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_purpose', 'association_state']));
|
||||
$matches = ! $same || collect($rows)->contains(function ($row) use ($same) {
|
||||
foreach (['association_type' => 'target_type', 'association_target' => 'target_id', 'association_purpose' => 'purpose', 'association_state' => 'state'] as $key => $field) {
|
||||
if (isset($same[$key]) && $same[$key] !== $row[$field]) { return false; }
|
||||
if (isset($same[$key]) && $same[$key] !== $row[$field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
foreach (['chain_id' => 'chain', 'subsector_id' => 'activity'] as $key => $type) {
|
||||
if (! empty($filters[$key])) { $matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === $type && $r['target_id'] === $filters[$key]); }
|
||||
if (! empty($filters[$key])) {
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === $type && $r['target_id'] === $filters[$key]);
|
||||
}
|
||||
}
|
||||
if (! empty($filters['authority_id'])) {
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => ($r['authority_id'] ?? null) === $filters['authority_id']);
|
||||
}
|
||||
if ($matches) {
|
||||
$ids[] = $business->id;
|
||||
}
|
||||
if (! empty($filters['authority_id'])) { $matches = $matches && collect($rows)->contains(fn ($r) => ($r['authority_id'] ?? null) === $filters['authority_id']); }
|
||||
if ($matches) { $ids[] = $business->id; }
|
||||
}
|
||||
}, 'existing_businesses.id', 'id');
|
||||
$query->whereIn('existing_businesses.id', $ids);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
@@ -9,28 +10,28 @@ final class ExistingBusinessProfileCategory
|
||||
// Exact catalogue correspondences plus the explicit mappings already present
|
||||
// in BusinessWizard and the transaction variants in OpportunityCategoryFields.
|
||||
public const MAP = [
|
||||
'company_sale'=>'business_sale', 'participation_sale'=>'business_sale',
|
||||
'buyer_search'=>'business_sale', 'succession'=>'business_sale',
|
||||
'franchise'=>'franchise', 'real_estate'=>'real_estate', 'land_right'=>'land_rights',
|
||||
'investment_project'=>'investment_project', 'expansion'=>'investment_project',
|
||||
'internationalization'=>'investment_project', 'agricultural_investment'=>'investment_project',
|
||||
'business_partnership'=>'business_partnership', 'strategic_partner'=>'business_partnership',
|
||||
'joint_venture'=>'business_partnership', 'capital_increase'=>'financing',
|
||||
'financial_investor'=>'financing', 'financing_request'=>'financing',
|
||||
'concession_opportunity'=>'concession', 'supply_opportunity'=>'supply',
|
||||
'company_sale' => 'business_sale', 'participation_sale' => 'business_sale',
|
||||
'buyer_search' => 'business_sale', 'succession' => 'business_sale',
|
||||
'franchise' => 'franchise', 'real_estate' => 'real_estate', 'land_right' => 'land_rights',
|
||||
'investment_project' => 'investment_project', 'expansion' => 'investment_project',
|
||||
'internationalization' => 'investment_project', 'agricultural_investment' => 'investment_project',
|
||||
'business_partnership' => 'business_partnership', 'strategic_partner' => 'business_partnership',
|
||||
'joint_venture' => 'business_partnership', 'capital_increase' => 'financing',
|
||||
'financial_investor' => 'financing', 'financing_request' => 'financing',
|
||||
'concession_opportunity' => 'concession', 'supply_opportunity' => 'supply',
|
||||
];
|
||||
|
||||
// Native form types are separate from the persisted modality. No default to a project.
|
||||
public const FORM_TYPES = [
|
||||
'investment_project'=>'investment_project', 'company_sale'=>'company_sale',
|
||||
'asset_sale'=>'asset_sale', 'business_partnership'=>'business_partnership',
|
||||
'financing_request'=>'financing_request', 'concession_opportunity'=>'concession_opportunity',
|
||||
'supply_opportunity'=>'supply_opportunity', 'participation_sale'=>'company_sale',
|
||||
'asset_lease'=>'asset_sale', 'capital_increase'=>'financing_request',
|
||||
'financial_investor'=>'financing_request', 'strategic_partner'=>'business_partnership',
|
||||
'joint_venture'=>'business_partnership', 'expansion'=>'investment_project',
|
||||
'agricultural_investment'=>'investment_project', 'internationalization'=>'investment_project',
|
||||
'buyer_search'=>'company_sale', 'succession'=>'company_sale',
|
||||
'investment_project' => 'investment_project', 'company_sale' => 'company_sale',
|
||||
'asset_sale' => 'asset_sale', 'business_partnership' => 'business_partnership',
|
||||
'financing_request' => 'financing_request', 'concession_opportunity' => 'concession_opportunity',
|
||||
'supply_opportunity' => 'supply_opportunity', 'participation_sale' => 'company_sale',
|
||||
'asset_lease' => 'asset_sale', 'capital_increase' => 'financing_request',
|
||||
'financial_investor' => 'financing_request', 'strategic_partner' => 'business_partnership',
|
||||
'joint_venture' => 'business_partnership', 'expansion' => 'investment_project',
|
||||
'agricultural_investment' => 'investment_project', 'internationalization' => 'investment_project',
|
||||
'buyer_search' => 'company_sale', 'succession' => 'company_sale',
|
||||
];
|
||||
|
||||
public static function category(ExistingBusiness $business): ?string
|
||||
|
||||
@@ -38,6 +38,9 @@ final class FintechInvestment
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function save(User $actor, string $id, array $input): void
|
||||
{
|
||||
$keys = implode(',', array_keys(self::FIELDS));
|
||||
@@ -89,6 +92,9 @@ final class FintechInvestment
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $value
|
||||
*/
|
||||
private function fingerprint(array $value): string
|
||||
{
|
||||
$canonical = function ($v) use (&$canonical) {
|
||||
@@ -105,6 +111,10 @@ final class FintechInvestment
|
||||
return hash('sha256', json_encode($canonical($value), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $record
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function reviewFingerprints(array $record): array
|
||||
{
|
||||
$profile = $record['profile'] ?? [];
|
||||
@@ -121,6 +131,11 @@ final class FintechInvestment
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @param array<array-key, mixed> $steps
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function adjustSteps(array $payload, array $steps): array
|
||||
{
|
||||
$record = $payload['investor_path']['fintech'] ?? null;
|
||||
@@ -145,6 +160,11 @@ final class FintechInvestment
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @param array<array-key, mixed> $steps
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function view(array $payload, array $steps): array
|
||||
{
|
||||
$record = $payload['investor_path']['fintech'] ?? null;
|
||||
@@ -174,7 +194,7 @@ final class FintechInvestment
|
||||
|
||||
return ['guidance' => $guidance, 'guidance_version' => InvestorGuidanceRules::VERSION, 'schema' => self::VERSION, 'record' => $record, 'fields' => self::FIELDS, 'activities' => self::ACTIVITIES, 'countries' => app(CountryCatalogue::class)->all(),
|
||||
'requirements' => $requirements, 'documents' => $docs, 'review_fingerprints' => $record ? $this->reviewFingerprints($record) : [],
|
||||
'affected_reviews' => array_values(array_column(array_filter($steps,fn ($s) => $s['fintech_review_required'] ?? false), 'code')),
|
||||
'affected_reviews' => array_column(array_filter($steps, fn ($s) => $s['fintech_review_required'] ?? false), 'code'),
|
||||
'limits' => ['Fintech é caracterização do investimento, não nova categoria jurídica ou autorização.', 'Preparação de orçamento, tecnologia, documentos e parceiros pode avançar em paralelo.', 'Países de operação não alteram país mestre, origem, nacionalidade ou residências.', 'Capitais mínimos, taxas, prazos e licenças específicos permanecem por determinar sem disposição e período aplicáveis.']];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ final class InterestWorkflow
|
||||
|
||||
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
|
||||
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->interest($actor,$locked),403);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->interest($actor, $locked), 403);
|
||||
$from = $locked->status;
|
||||
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
|
||||
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
@@ -239,7 +240,8 @@ class InvestmentCatalogue
|
||||
};
|
||||
}
|
||||
|
||||
private function declaredProvince($query, string $name): void
|
||||
/** @param Builder<Opportunity> $query */
|
||||
private function declaredProvince(Builder $query, string $name): void
|
||||
{
|
||||
// Read the published province declaration only when no more precise territory contradicts it.
|
||||
// This does not assign any canonical ID, district, post, locality or coordinates to the record.
|
||||
@@ -249,7 +251,8 @@ class InvestmentCatalogue
|
||||
->whereRaw('lower(btrim(opportunities.province)) = ?', [mb_strtolower(trim($name))]));
|
||||
}
|
||||
|
||||
private function approvedCorridorProvince($query, string $provinceId): void
|
||||
/** @param Builder<Opportunity> $query */
|
||||
private function approvedCorridorProvince(Builder $query, string $provinceId): void
|
||||
{
|
||||
$code = app(InvestmentGeography::class)->publicReferences()->where('id', $provinceId)->value('source_code');
|
||||
$names = [];
|
||||
@@ -344,8 +347,8 @@ class InvestmentCatalogue
|
||||
// A chain's documented scope comes from its public cluster, never
|
||||
// from the opportunities surviving the current search.
|
||||
$ids = app(OpportunityClassification::class)->targets('chain')
|
||||
->whereIn('cluster_id', $result['clusters']->pluck('id'))->pluck('id');
|
||||
$result['classification']['targets']['chain'] = collect($result['classification']['targets']['chain'])->whereIn('id', $ids)->values();
|
||||
->whereIn('cluster_id', ($result['clusters'] ?? collect())->pluck('id'))->pluck('id');
|
||||
$result['classification']['targets']['chain'] = collect(StructuredData::collectionItems($result['classification']['targets']['chain']))->whereIn('id', $ids)->values();
|
||||
}
|
||||
// Activities are a public classification catalogue, not evidence of
|
||||
// investment availability in a territory or sector.
|
||||
@@ -353,6 +356,10 @@ class InvestmentCatalogue
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function publicAssociatedIds(array $filters): array
|
||||
{
|
||||
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
|
||||
|
||||
@@ -4,9 +4,11 @@ namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Resolve documented complements without creating opportunities or master relations. */
|
||||
final class InvestmentComplements
|
||||
@@ -23,6 +25,9 @@ final class InvestmentComplements
|
||||
'finance' => ['Financiamento', 'financiamento|serviços financeiros'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function options(string $origin, ?string $territory = null): array
|
||||
{
|
||||
[$originKind, $originId] = array_pad(explode(':', $origin, 2), 2, '');
|
||||
@@ -30,18 +35,24 @@ final class InvestmentComplements
|
||||
$principal = null;
|
||||
$relationEvidence = [];
|
||||
if (str_starts_with($origin, 'portfolio:')) {
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->findOrFail(substr($origin, 10));
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->whereKey(substr($origin, 10))->firstOrFail();
|
||||
$text = trim(($record->content['focus'] ?? '')."\n".($record->content['gaps'] ?? '')."\n".($record->content['description'] ?? ''));
|
||||
$reference = ['key' => $origin, 'title' => $record->title, 'href' => '/carteira/'.$record->id, 'version' => $record->version_no];
|
||||
$ids = app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record);
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign) $ids = [...$ids, ...DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->pluck('opportunity_id')->all()];
|
||||
if ($record->$foreign) {
|
||||
$ids = [...$ids, ...DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->pluck('opportunity_id')->all()];
|
||||
}
|
||||
}
|
||||
$basis = $record->source;
|
||||
foreach (array_unique($ids) as $id) $relationEvidence[$id] = ['type' => 'portfolio', 'origin' => $origin, 'source' => $basis];
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$relationEvidence[$id] = ['type' => 'portfolio', 'origin' => $origin, 'source' => $basis];
|
||||
}
|
||||
$serviceOrigins = [['dossier', $record->id]];
|
||||
foreach (['project_id' => 'project', 'cluster_id' => 'cluster'] as $foreign => $type) {
|
||||
if ($record->$foreign) $serviceOrigins[] = [$type, $record->$foreign];
|
||||
if ($record->$foreign) {
|
||||
$serviceOrigins[] = [$type, $record->$foreign];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$reference = app(InvestorContext::class)->reference($origin);
|
||||
@@ -49,8 +60,10 @@ final class InvestmentComplements
|
||||
// The context resolver has already checked the actor's private scope.
|
||||
// A private preparation is valid dossier input, not a public offer
|
||||
// from which this public-complement catalogue can infer services.
|
||||
if (($reference['visibility'] ?? 'public') === 'private') return [];
|
||||
$principal = Opportunity::published()->findOrFail($reference['id']);
|
||||
if (($reference['visibility'] ?? 'public') === 'private') {
|
||||
return [];
|
||||
}
|
||||
$principal = Opportunity::published()->whereKey($reference['id'])->firstOrFail();
|
||||
$text = $principal->summary;
|
||||
$basis = 'Resumo cadastrado da oportunidade '.$principal->reference;
|
||||
$projects = DB::table('opportunity_projects')->where('opportunity_id', $principal->id)->pluck('project_id');
|
||||
@@ -59,18 +72,24 @@ final class InvestmentComplements
|
||||
$targetProjects = DB::table('opportunity_projects')->whereIn('project_id', $links->pluck('complementary_project_id'))->get();
|
||||
$ids = [$principal->id, ...$targetProjects->pluck('opportunity_id')->all()];
|
||||
$relationEvidence[$principal->id] = ['type' => 'same_fiche', 'source' => $basis];
|
||||
foreach ($targetProjects as $targetProject) $relationEvidence[$targetProject->opportunity_id] = ['type' => 'complementary_project',
|
||||
'links' => $links->where('complementary_project_id', $targetProject->project_id)->values()->map(fn($link) => (array)$link)->all()];
|
||||
foreach (Opportunity::published()->whereIn('id', $ids)->where('id', '!=', $principal->id)->get() as $linked) $text .= "\n".$linked->summary;
|
||||
if (count($ids) > 1) $basis .= '; relações complementares públicas entre projectos';
|
||||
foreach ($targetProjects as $targetProject) {
|
||||
$relationEvidence[$targetProject->opportunity_id] = ['type' => 'complementary_project',
|
||||
'links' => $links->where('complementary_project_id', $targetProject->project_id)->values()->map(fn ($link) => (array) $link)->all()];
|
||||
}
|
||||
foreach (Opportunity::published()->whereIn('id', $ids)->where('id', '!=', $principal->id)->get() as $linked) {
|
||||
$text .= "\n".$linked->summary;
|
||||
}
|
||||
if (count($ids) > 1) {
|
||||
$basis .= '; relações complementares públicas entre projectos';
|
||||
}
|
||||
$serviceOrigins = [['investment', (string) $principal->id]];
|
||||
$classification = app(OpportunityClassification::class);
|
||||
$principalChains = collect($classification->publicRows($principal))->where('target_type', 'chain')->filter(fn($r) => !empty($r['source_reference']));
|
||||
$principalChains = collect($classification->publicRows($principal))->where('target_type', 'chain')->filter(fn ($r) => ! empty($r['source_reference']));
|
||||
$chains = $principalChains->pluck('target_id')->all();
|
||||
if ($chains) {
|
||||
Opportunity::published()->whereNot('id', $principal->id)->chunkById(100, function ($records) use (&$ids, &$relationEvidence, $chains, $principalChains, $classification) {
|
||||
foreach ($records as $candidate) {
|
||||
$related = collect($classification->publicRows($candidate))->where('target_type', 'chain')->filter(fn($r) => !empty($r['source_reference']));
|
||||
$related = collect($classification->publicRows($candidate))->where('target_type', 'chain')->filter(fn ($r) => ! empty($r['source_reference']));
|
||||
$shared = array_intersect($chains, $related->pluck('target_id')->all());
|
||||
if ($shared) {
|
||||
$ids[] = $candidate->id;
|
||||
@@ -84,15 +103,25 @@ final class InvestmentComplements
|
||||
$candidates = Opportunity::published()->whereIn('id', array_unique($ids))->get();
|
||||
$items = [];
|
||||
foreach (self::TERMS as $code => [$label, $pattern]) {
|
||||
if (!preg_match('/\b(?:'.$pattern.')\b/iu', $text, $match)) continue;
|
||||
if (! preg_match('/\b(?:'.$pattern.')\b/iu', $text, $match)) {
|
||||
continue;
|
||||
}
|
||||
$offers = [];
|
||||
foreach ($candidates as $candidate) {
|
||||
// A common corridor alone does not prove the component. Keep the supporting excerpt.
|
||||
if (!preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title."\n".$candidate->summary, $evidence)) continue;
|
||||
if (! preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title."\n".$candidate->summary, $evidence)) {
|
||||
continue;
|
||||
}
|
||||
// Mentioning a need for funding/training in a project's summary is not an offer.
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && !preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title)) continue;
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && preg_match('/\b(?:necessidade|pedido|procura)\b/iu', $candidate->title)) continue;
|
||||
if ($territory && $candidate->primary_territory_id && !$this->compatible($territory, $candidate->primary_territory_id)) continue;
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && ! preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title)) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && preg_match('/\b(?:necessidade|pedido|procura)\b/iu', $candidate->title)) {
|
||||
continue;
|
||||
}
|
||||
if ($territory && $candidate->primary_territory_id && ! $this->compatible($territory, $candidate->primary_territory_id)) {
|
||||
continue;
|
||||
}
|
||||
$offers[] = ['key' => 'opportunity:'.$candidate->id, 'title' => $candidate->title, 'href' => '/oportunidades/'.$candidate->slug,
|
||||
'relationship' => $relationEvidence[$candidate->id] ?? null,
|
||||
'version' => $candidate->management_version, 'evidence' => $evidence[0], 'location' => ($principal && $principal->id === $candidate->id ? 'Componente referido na própria ficha. ' : '').($candidate->primary_territory_id ? app(InvestorContext::class)->reference('territory:'.$candidate->primary_territory_id)['title'] : 'Implantação por definir')];
|
||||
@@ -100,62 +129,80 @@ final class InvestmentComplements
|
||||
// Services are concrete published offerings explicitly associated with this source.
|
||||
$services = [];
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && Schema::hasTable('partnership_origins') && Schema::hasTable('partnership_interests')) {
|
||||
if ($serviceOrigins) {
|
||||
$services = DB::table('portal_partnerships as p')->join('partnership_origins as o', 'o.partnership_id', '=', 'p.id')
|
||||
->where(function ($q) use ($serviceOrigins) {
|
||||
foreach ($serviceOrigins as [$type, $id]) $q->orWhere(fn($q) => $q->where('o.type', $type)->where('o.target_id', $id));
|
||||
})->where('p.status', 'published')->where('p.kind', 'offering')
|
||||
->where('p.partnership_type', $code === 'finance' ? 'finance' : 'training')
|
||||
->when($code !== 'finance', fn($q) => $q->where(fn($q) => $q->where('p.title', 'ilike', '%'.$match[0].'%')->orWhereRaw("p.payload->>'summary' ILIKE ?", ['%'.$match[0].'%'])))->distinct()->get(['p.id', 'p.title'])
|
||||
->filter(function ($p) use ($territory) {
|
||||
if (!$territory) return true;
|
||||
$locations = DB::table('partnership_locations')->where('partnership_id', $p->id)->pluck('geo_location_id');
|
||||
return $locations->isEmpty() || $locations->contains(fn($id) => $this->compatible($territory, $id));
|
||||
})->map(fn ($p) => ['key' => 'partnership:'.$p->id, 'title' => $p->title, 'href' => '/parcerias/'.$p->id, 'location' => 'Consultar âmbito na oferta'])->values()->all();
|
||||
}
|
||||
$services = DB::table('portal_partnerships as p')->join('partnership_origins as o', 'o.partnership_id', '=', 'p.id')
|
||||
->where(function ($q) use ($serviceOrigins) {
|
||||
foreach ($serviceOrigins as [$type, $id]) {
|
||||
$q->orWhere(fn ($q) => $q->where('o.type', $type)->where('o.target_id', $id));
|
||||
}
|
||||
})->where('p.status', 'published')->where('p.kind', 'offering')
|
||||
->where('p.partnership_type', $code === 'finance' ? 'finance' : 'training')
|
||||
->when($code !== 'finance', fn ($q) => $q->where(fn ($q) => $q->where('p.title', 'ilike', '%'.$match[0].'%')->orWhereRaw("p.payload->>'summary' ILIKE ?", ['%'.$match[0].'%'])))->distinct()->get(['p.id', 'p.title'])
|
||||
->filter(function ($p) use ($territory) {
|
||||
if (! $territory) {
|
||||
return true;
|
||||
}
|
||||
$locations = DB::table('partnership_locations')->where('partnership_id', $p->id)->pluck('geo_location_id');
|
||||
|
||||
return $locations->isEmpty() || $locations->contains(fn ($id) => $this->compatible($territory, $id));
|
||||
})->map(fn ($p) => ['key' => 'partnership:'.$p->id, 'title' => $p->title, 'href' => '/parcerias/'.$p->id, 'location' => 'Consultar âmbito na oferta'])->values()->all();
|
||||
}
|
||||
$excerpt = collect(explode("\n", $text))->first(fn($line) => preg_match('/\b(?:'.$pattern.')\b/iu', $line));
|
||||
$excerpt = collect(explode("\n", $text))->first(fn ($line) => preg_match('/\b(?:'.$pattern.')\b/iu', $line) === 1);
|
||||
$items[] = ['code' => $code, 'title' => $label, 'origin' => $reference, 'territory_id' => $territory, 'territory' => $territoryReference,
|
||||
'source' => $basis, 'excerpt' => $excerpt, 'source_sha256' => hash('sha256', $text), 'opportunities' => $offers, 'services' => $services];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function compatible(string $a, string $b): bool
|
||||
{
|
||||
if ($a === $b) return true;
|
||||
if ($a === $b) {
|
||||
return true;
|
||||
}
|
||||
$geo = app(InvestmentGeography::class);
|
||||
|
||||
return in_array($b, $geo->descendants($a), true) || in_array($a, $geo->descendants($b), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @param array<array-key, mixed> $previous
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function resolve(array $input, array $previous = []): array
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($input as $choice) {
|
||||
$target = $choice['target'] ?? null;
|
||||
$old = collect($previous)->first(fn($r) => $r['origin']['key'] === $choice['origin'] && $r['code'] === $choice['code'] && ($r['target']['key'] ?? null) === $target && ($r['territory_id'] ?? null) === ($choice['territory_id'] ?? null));
|
||||
$old = collect($previous)->first(fn ($r) => $r['origin']['key'] === $choice['origin'] && $r['code'] === $choice['code'] && ($r['target']['key'] ?? null) === $target && ($r['territory_id'] ?? null) === ($choice['territory_id'] ?? null));
|
||||
try {
|
||||
$item = collect($this->options($choice['origin'], $choice['territory_id'] ?? null))->firstWhere('code', $choice['code']);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
|
||||
if (!$old) throw $e;
|
||||
} catch (ModelNotFoundException $e) {
|
||||
if (! $old) {
|
||||
throw $e;
|
||||
}
|
||||
$item = null;
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
|
||||
if (!$old || $e->getStatusCode() !== 404) throw $e;
|
||||
} catch (HttpException $e) {
|
||||
if (! $old || $e->getStatusCode() !== 404) {
|
||||
throw $e;
|
||||
}
|
||||
$item = null;
|
||||
}
|
||||
$offer = $target && $item ? collect([...$item['opportunities'], ...$item['services']])->firstWhere('key', $target) : null;
|
||||
if ($old && (!$item || ($target && !$offer) || (!$target && ($item['opportunities'] || $item['services'])))) {
|
||||
if ($old && (! $item || ($target && ! $offer) || (! $target && ($item['opportunities'] || $item['services'])))) {
|
||||
$resolved[$old['key']] = [...$old, 'availability' => 'review_required'];
|
||||
|
||||
continue;
|
||||
}
|
||||
abort_unless($item, 422, 'Complemento sem referência documentada neste investimento.');
|
||||
abort_if($target && !$offer, 422, 'A oferta complementar deixou de estar disponível neste contexto.');
|
||||
abort_if(!$target && ($item['opportunities'] || $item['services']), 422, 'Já existe uma oferta relacionada; seleccione a ficha correspondente.');
|
||||
abort_if($target && ! $offer, 422, 'A oferta complementar deixou de estar disponível neste contexto.');
|
||||
abort_if(! $target && ($item['opportunities'] || $item['services']), 422, 'Já existe uma oferta relacionada; seleccione a ficha correspondente.');
|
||||
$key = hash('sha256', $choice['origin'].'|'.$choice['code'].'|'.($target ?? 'idea').'|'.($choice['territory_id'] ?? ''));
|
||||
$resolved[$key] = ['key' => $key, 'origin' => $item['origin'], 'code' => $item['code'], 'title' => $item['title'],
|
||||
'kind' => $target ? (str_starts_with($target, 'opportunity:') ? 'opportunity' : 'service') : 'need',
|
||||
'target' => $offer, 'territory_id' => $item['territory_id'], 'territory' => $item['territory'], 'source' => $item['source'], 'excerpt' => $item['excerpt'], 'source_sha256' => $item['source_sha256']];
|
||||
}
|
||||
|
||||
return array_values($resolved);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,83 +3,123 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/** An identified opportunity within the authorised dossier, never the account's last choice. */
|
||||
final class InvestmentConsumerScope
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
*/
|
||||
public function key(array $context, ?string $key, bool $required = false): ?string
|
||||
{
|
||||
$choices = $context['opportunity_choices'] ?? [];
|
||||
$key = $key ?: (count($choices) === 1 ? $choices[0]['opportunity']['key'] : null);
|
||||
abort_if($key && !collect($choices)->contains('opportunity.key', $key), 422, 'Escolha uma oportunidade deste dossier.');
|
||||
abort_if($required && count($choices) > 1 && !$key, 422, 'Escolha a oportunidade em tratamento.');
|
||||
abort_if($key && ! collect(StructuredData::collectionItems($choices))->contains('opportunity.key', $key), 422, 'Escolha uma oportunidade deste dossier.');
|
||||
abort_if($required && count($choices) > 1 && ! $key, 422, 'Escolha a oportunidade em tratamento.');
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function facts(array $payload, array $context, ?string $key): array
|
||||
{
|
||||
$key = $this->key($context, $key);
|
||||
$path = $payload['investor_path'] ?? [];
|
||||
$defaults = ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
|
||||
// A dossier-wide dispensation cannot decide a distinct opportunity's needs.
|
||||
if ($key && count($context['opportunity_choices'] ?? []) > 1) return [...$defaults, ...($path['opportunity_facts'][$key] ?? [])];
|
||||
if ($key && isset($path['opportunity_facts'][$key])) return [...$defaults, ...$path['opportunity_facts'][$key]];
|
||||
if (count($context['opportunity_choices'] ?? []) > 1) return $defaults;
|
||||
if ($key && count($context['opportunity_choices'] ?? []) > 1) {
|
||||
return [...$defaults, ...($path['opportunity_facts'][$key] ?? [])];
|
||||
}
|
||||
if ($key && isset($path['opportunity_facts'][$key])) {
|
||||
return [...$defaults, ...$path['opportunity_facts'][$key]];
|
||||
}
|
||||
if (count($context['opportunity_choices'] ?? []) > 1) {
|
||||
return $defaults;
|
||||
}
|
||||
|
||||
return [...$defaults, ...($path['facts'] ?? [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function context(array $context, ?string $key): array
|
||||
{
|
||||
$choices = $context['opportunity_choices'] ?? [];
|
||||
if (!$choices) return $context;
|
||||
if (! $choices) {
|
||||
return $context;
|
||||
}
|
||||
$key = $key ?: (count($choices) === 1 ? $choices[0]['opportunity']['key'] : null);
|
||||
$choice = $key ? collect($choices)->firstWhere('opportunity.key', $key) : null;
|
||||
abort_if($key && !$choice, 422, 'Escolha uma oportunidade deste dossier.');
|
||||
$choice = $key ? collect(StructuredData::collectionItems($choices))->firstWhere('opportunity.key', $key) : null;
|
||||
abort_if($key && ! $choice, 422, 'Escolha uma oportunidade deste dossier.');
|
||||
$specific = ['project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'special_zone_id', 'investment_regime'];
|
||||
$context['fields'] = Arr::except($context['fields'], $specific);
|
||||
$context['provenance'] = Arr::except($context['provenance'] ?? [], $specific);
|
||||
$context['selection'] = Arr::except($context['selection'], ['opportunity', 'territory', 'park']);
|
||||
if (!$choice) {
|
||||
if (! $choice) {
|
||||
$context['opportunity_choices'] = [];
|
||||
$context['requirements_assessment']['requirements'] = [];
|
||||
|
||||
return $context;
|
||||
}
|
||||
$context['selection']['opportunity'] = $choice['opportunity'];
|
||||
$context['fields'] = [...$context['fields'], ...Arr::only($choice['opportunity']['fields'], $specific)];
|
||||
foreach (Arr::only($choice['opportunity']['fields'], $specific) as $field => $value) $context['provenance'][$field] = Arr::only($choice['opportunity'], ['key','kind','id','title','version','sha256']);
|
||||
foreach (Arr::only($choice['opportunity']['fields'], $specific) as $field => $value) {
|
||||
$context['provenance'][$field] = Arr::only($choice['opportunity'], ['key', 'kind', 'id', 'title', 'version', 'sha256']);
|
||||
}
|
||||
unset($context['selection']['sector']);
|
||||
if (!empty($context['fields']['sector_id'])) $context['selection']['sector'] = app(InvestorContext::class)->reference('sector:'.$context['fields']['sector_id']);
|
||||
if (! empty($context['fields']['sector_id'])) {
|
||||
$context['selection']['sector'] = app(InvestorContext::class)->reference('sector:'.$context['fields']['sector_id']);
|
||||
}
|
||||
if ($choice['territory']) {
|
||||
$context['selection']['territory'] = $choice['territory'];
|
||||
$context['fields'] = [...Arr::except($context['fields'], array_keys(InvestmentGeography::FIELDS)), ...$choice['territory']['fields']];
|
||||
foreach ($choice['territory']['fields'] as $field => $value) $context['provenance'][$field] = Arr::only($choice['territory'], ['key','kind','id','title','version','sha256']);
|
||||
foreach ($choice['territory']['fields'] as $field => $value) {
|
||||
$context['provenance'][$field] = Arr::only($choice['territory'], ['key', 'kind', 'id', 'title', 'version', 'sha256']);
|
||||
}
|
||||
} else {
|
||||
$context['fields'] = Arr::except($context['fields'], ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location']);
|
||||
}
|
||||
$park = $choice['park'] ?? null;
|
||||
if ($park) $context['selection']['park'] = $park;
|
||||
if ($park) {
|
||||
$context['selection']['park'] = $park;
|
||||
}
|
||||
$context['fields']['special_zone_id'] = $park['id'] ?? '';
|
||||
$context['fields']['investment_regime'] = $park['fields']['investment_regime'] ?? 'general';
|
||||
$context['opportunity_choices'] = [$choice];
|
||||
$context['requirements_assessment']['requirements'] = array_values(array_filter($context['requirements_assessment']['requirements'] ?? [], fn($r) => $r['opportunity_key'] === $key));
|
||||
$context['requirements_assessment']['requirements'] = array_values(array_filter($context['requirements_assessment']['requirements'] ?? [], fn ($r) => $r['opportunity_key'] === $key));
|
||||
$context['consumer_opportunity'] = $choice;
|
||||
$context['complements'] = array_values(array_filter($context['complements'] ?? [], fn($c) => ($c['origin']['key'] ?? null) === $key || ($c['target']['key'] ?? null) === $key || in_array(substr($c['origin']['key'] ?? '',10),array_column($choice['portfolio_origins'] ?? [],'id'),true)));
|
||||
$context['dependency_hash'] = app(InvestorContext::class)->dependencyHash(['opportunity_choices'=>[$choice], 'fields'=>Arr::except($context['fields'],['project_title','project_summary']), 'complements'=>$context['complements']]);
|
||||
$context['complements'] = array_values(array_filter($context['complements'] ?? [], fn ($c) => ($c['origin']['key'] ?? null) === $key || ($c['target']['key'] ?? null) === $key || in_array(substr($c['origin']['key'] ?? '', 10), array_column($choice['portfolio_origins'] ?? [], 'id'), true)));
|
||||
$context['dependency_hash'] = app(InvestorContext::class)->dependencyHash(['opportunity_choices' => [$choice], 'fields' => Arr::except($context['fields'], ['project_title', 'project_summary']), 'complements' => $context['complements']]);
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function bind(User $actor, string $id, array $payload, bool $required = false): array
|
||||
{
|
||||
$case = app(VirtualDesk::class)->case($actor, $id, true);
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$scoped = $this->context($context, $payload['context_opportunity'] ?? null);
|
||||
$choice = $scoped['consumer_opportunity'] ?? null;
|
||||
abort_if($required && count($context['opportunity_choices'] ?? []) > 1 && !$choice, 422, 'Escolha a oportunidade em tratamento antes de submeter.');
|
||||
if (!$choice) return Arr::except($payload, ['context_opportunity', 'context_opportunity_snapshot']);
|
||||
abort_if($required && count($context['opportunity_choices'] ?? []) > 1 && ! $choice, 422, 'Escolha a oportunidade em tratamento antes de submeter.');
|
||||
if (! $choice) {
|
||||
return Arr::except($payload, ['context_opportunity', 'context_opportunity_snapshot']);
|
||||
}
|
||||
// Canonical server snapshot; client text cannot establish a different origin or territory.
|
||||
$payload['context_opportunity'] = $choice['opportunity']['key'];
|
||||
$payload['context_opportunity_snapshot'] = json_encode(['context_id' => $id, 'revision' => $context['revision'], 'choice' => $choice, 'requirements' => $scoped['requirements_assessment'] ?? null], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ final class InvestmentContextRequirements
|
||||
{
|
||||
public const VERSION = 'context-requirements-20261023';
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function assess(array $context): array
|
||||
{
|
||||
$rows = [];
|
||||
@@ -32,16 +36,21 @@ final class InvestmentContextRequirements
|
||||
['Actividades efectivas e modalidade', 'Requerimento e anexos da modalidade aplicável; acto quando emitido'],
|
||||
'Identificar as actividades efectivas antes de seleccionar o procedimento. O nome Agronegócio não escolhe uma licença única.', 'https://www.bau.gov.mz/nossos-servicos/');
|
||||
foreach (['processing' => ['Licenciamento industrial', 'Decreto 22/2014'], 'trade' => ['Licenciamento comercial', 'Decreto 34/2013']] as $activity => [$title, $basis]) {
|
||||
if (in_array($activity, $activities, true)) $add($activity, $title, 'conditional', 'S08', 'BAU, IP / entidade licenciadora da modalidade',
|
||||
['Caracterização do estabelecimento e actividade', 'Documentos e regime aplicáveis, incluindo simplificado ou mera comunicação quando preenchidas as suas condições'],
|
||||
$basis.'; regimes 39/2017 e 27/2023 no catálogo oficial BAU. Dimensão e modalidade ainda devem ser especificadas; não se selecciona automaticamente o regime.', 'https://www.bau.gov.mz/legislacao/');
|
||||
if (in_array($activity, $activities, true)) {
|
||||
$add($activity, $title, 'conditional', 'S08', 'BAU, IP / entidade licenciadora da modalidade',
|
||||
['Caracterização do estabelecimento e actividade', 'Documentos e regime aplicáveis, incluindo simplificado ou mera comunicação quando preenchidas as suas condições'],
|
||||
$basis.'; regimes 39/2017 e 27/2023 no catálogo oficial BAU. Dimensão e modalidade ainda devem ser especificadas; não se selecciona automaticamente o regime.', 'https://www.bau.gov.mz/legislacao/');
|
||||
}
|
||||
}
|
||||
foreach (['water' => 'Uso de água', 'forestry' => 'Actividade florestal', 'animal' => 'Actividade pecuária', 'transport' => 'Transporte e logística'] as $activity => $title) {
|
||||
if (in_array($activity, $activities, true)) $add($activity, $title, 'undetermined', 'S08', 'Autoridade sectorial competente a identificar para a modalidade declarada',
|
||||
['Modalidade e dimensão da actividade', 'Fonte e documentação sectorial específica a associar ao dossier'],
|
||||
'Actividade declarada; a referência do lote não contém o procedimento específico. Não se considera dispensada ou autorizada.', 'https://www.apiex.gov.mz/wp-content/uploads/2024/01/Mozambique-Business-Licensing-Guide.pdf');
|
||||
if (in_array($activity, $activities, true)) {
|
||||
$add($activity, $title, 'undetermined', 'S08', 'Autoridade sectorial competente a identificar para a modalidade declarada',
|
||||
['Modalidade e dimensão da actividade', 'Fonte e documentação sectorial específica a associar ao dossier'],
|
||||
'Actividade declarada; a referência do lote não contém o procedimento específico. Não se considera dispensada ou autorizada.', 'https://www.apiex.gov.mz/wp-content/uploads/2024/01/Mozambique-Business-Licensing-Guide.pdf');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['version' => self::VERSION, 'requirements' => $rows,
|
||||
'fiscal_notice' => 'Localização, corredor, cluster ou projecto âncora não activam benefícios fiscais. O simulador mantém as condições, fonte, período e âmbito próprios; condições ausentes permanecem indeterminadas.'];
|
||||
}
|
||||
|
||||
@@ -10,40 +10,65 @@ final class InvestmentCorridorContext
|
||||
public function key(Opportunity $record): ?string
|
||||
{
|
||||
$name = data_get($record->workflow_context, 'corridor_agribusiness.corridor');
|
||||
foreach (config('investment_corridors') as $key => $entry) if ($entry['name'] === $name) return $key;
|
||||
foreach (config('investment_corridors') as $key => $entry) {
|
||||
if ($entry['name'] === $name) {
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Reuse Tempo's approved provincial context; never infer a district or master link. */
|
||||
/** Reuse Tempo's approved provincial context; never infer a district or master link.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function catalogueProvinces(Opportunity $record): array
|
||||
{
|
||||
if (data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') !== CorridorAgribusinessOpportunities::SOURCE_HASH) return [];
|
||||
if ($record->primary_territory_id || $record->additionalTerritories()->exists()) return [];
|
||||
if (data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') !== CorridorAgribusinessOpportunities::SOURCE_HASH) {
|
||||
return [];
|
||||
}
|
||||
if ($record->primary_territory_id || $record->additionalTerritories()->exists()) {
|
||||
return [];
|
||||
}
|
||||
$key = $this->key($record);
|
||||
|
||||
return $key ? $this->provinces($key) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function provinces(string $key): array
|
||||
{
|
||||
$entry = config('investment_corridors.'.$key);
|
||||
abort_unless(is_array($entry), 422, 'Seleccione um corredor disponível.');
|
||||
$records = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')
|
||||
->whereIn('source_code', $entry['provinces'])->get(['id', 'name', 'parent_id', 'location_type', 'source_code'])->all();
|
||||
abort_unless(count($records) === count($entry['provinces']), 503, 'Não foi possível recuperar todas as províncias deste corredor. Tente novamente.');
|
||||
if (! (count($records) === count($entry['provinces']))) {
|
||||
abort(503, 'Não foi possível recuperar todas as províncias deste corredor. Tente novamente.');
|
||||
}
|
||||
|
||||
return $records;
|
||||
}
|
||||
|
||||
public function compatible(string $key, ?string $territory): bool
|
||||
{
|
||||
if (!$territory) return true;
|
||||
if (! $territory) {
|
||||
return true;
|
||||
}
|
||||
$path = app(InvestmentGeography::class)->path($territory);
|
||||
|
||||
return $path !== [] && in_array($path[0]->id, array_column($this->provinces($key), 'id'), true);
|
||||
}
|
||||
|
||||
/** Both membership in the selected area and documented public zone coverage are required. */
|
||||
/** Both membership in the selected area and documented public zone coverage are required.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function parks(?string $key, ?string $territory): array
|
||||
{
|
||||
if (!$key || !$territory) return [];
|
||||
if (! $key || ! $territory) {
|
||||
return [];
|
||||
}
|
||||
abort_unless($this->compatible($key, $territory), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
$selectedPath = array_column(app(InvestmentGeography::class)->path($territory), 'id');
|
||||
$candidates = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get();
|
||||
@@ -51,18 +76,24 @@ final class InvestmentCorridorContext
|
||||
foreach ($candidates as $zone) {
|
||||
$ids = DB::table('investment_zone_locations')->where('zone_id', $zone->id)->where('validation_status', 'validated')
|
||||
->whereIn('scope_type', ['legal_scope', 'administrative', 'site'])
|
||||
->where(fn($q)=>$q->whereNull('valid_from')->orWhereDate('valid_from','<=',today()))
|
||||
->where(fn($q)=>$q->whereNull('valid_until')->orWhereDate('valid_until','>=',today()))->get(['geo_location_id','scope_type'])->all();
|
||||
if ($zone->primary_territory_id) $ids[] = (object)['geo_location_id'=>$zone->primary_territory_id,'scope_type'=>'site'];
|
||||
->where(fn ($q) => $q->whereNull('valid_from')->orWhereDate('valid_from', '<=', today()))
|
||||
->where(fn ($q) => $q->whereNull('valid_until')->orWhereDate('valid_until', '>=', today()))->get(['geo_location_id', 'scope_type'])->all();
|
||||
if ($zone->primary_territory_id) {
|
||||
$ids[] = (object) ['geo_location_id' => $zone->primary_territory_id, 'scope_type' => 'site'];
|
||||
}
|
||||
foreach ($ids as $link) {
|
||||
$id=$link->geo_location_id;
|
||||
if (!$this->compatible($key, $id)) continue;
|
||||
$id = $link->geo_location_id;
|
||||
if (! $this->compatible($key, $id)) {
|
||||
continue;
|
||||
}
|
||||
$path = array_column(app(InvestmentGeography::class)->path($id), 'id');
|
||||
if (in_array($territory, $path, true) || ($link->scope_type==='legal_scope' && in_array($id, $selectedPath, true))) {
|
||||
$result[] = $zone->only(['id', 'name', 'category', 'version_no']); break;
|
||||
if (in_array($territory, $path, true) || ($link->scope_type === 'legal_scope' && in_array($id, $selectedPath, true))) {
|
||||
$result[] = $zone->only(['id', 'name', 'category', 'version_no']);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,10 @@ final class InvestmentGeography
|
||||
{
|
||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||
|
||||
/** Resolve an old province-name search only when the public register has exactly one match. */
|
||||
/** Resolve an old province-name search only when the public register has exactly one match.
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function provinceSearch(array $filters): array
|
||||
{
|
||||
if (empty($filters['province_id']) && is_string($filters['province'] ?? null) && trim($filters['province']) !== '') {
|
||||
|
||||
@@ -4,47 +4,73 @@ namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Multiple identified references in the existing encrypted investment context. */
|
||||
final class InvestmentOpportunityChoices
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $ids
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function portfolioOrigins(array $ids, int $opportunity): array
|
||||
{
|
||||
$origins = [];
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->findOrFail($id);
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->whereKey($id)->firstOrFail();
|
||||
$kind = null;
|
||||
if (in_array($opportunity, app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record), true)) $kind = 'corridor';
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $opportunity)->where($foreign, $record->$foreign)->exists()) $kind = rtrim($relation, 's');
|
||||
if (in_array($opportunity, app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record), true)) {
|
||||
$kind = 'corridor';
|
||||
}
|
||||
abort_unless($kind, 422, 'A associação escolhida não pertence a esta oportunidade.');
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $opportunity)->where($foreign, $record->$foreign)->exists()) {
|
||||
$kind = rtrim($relation, 's');
|
||||
}
|
||||
}
|
||||
abort_unless($kind !== null, 422, 'A associação escolhida não pertence a esta oportunidade.');
|
||||
$origins[] = ['id' => $record->id, 'title' => $record->title, 'kind' => $kind, 'href' => '/carteira/'.$record->id,
|
||||
'version' => $record->version_no, 'sha256' => hash('sha256', json_encode([$record->title, $record->source, $record->content], JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
return $origins;
|
||||
}
|
||||
|
||||
/** Add explicitly consulted associations without resetting saved geography or deliberate answers. */
|
||||
/** Add explicitly consulted associations without resetting saved geography or deliberate answers.
|
||||
* @param array<array-key, mixed> $entries
|
||||
* @param array<array-key, mixed> $saved
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function mergeEntries(array $saved, array $entries): array
|
||||
{
|
||||
foreach ($entries as $entry) {
|
||||
$index = array_search($entry['opportunity']['key'], array_column(array_column($saved, 'opportunity'), 'key'), true);
|
||||
if ($index === false) { $saved[] = $entry; continue; }
|
||||
if ($index === false) {
|
||||
$saved[] = $entry;
|
||||
|
||||
continue;
|
||||
}
|
||||
$origins = collect([...($saved[$index]['portfolio_origins'] ?? []), ...($entry['portfolio_origins'] ?? [])])->unique('id')->values()->all();
|
||||
if ($origins) $saved[$index]['portfolio_origins'] = $origins;
|
||||
if ($origins) {
|
||||
$saved[$index]['portfolio_origins'] = $origins;
|
||||
}
|
||||
}
|
||||
|
||||
return $saved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $choices
|
||||
* @param array<array-key, mixed> $previous
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function resolve(array $choices, array $previous = [], bool $pending = false): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($choices as $choice) {
|
||||
$ref = app(InvestorContext::class)->reference($choice['source']);
|
||||
abort_unless($ref['kind'] === 'opportunity', 422, 'Seleccione uma ficha de oportunidade.');
|
||||
$record = Opportunity::findOrFail($ref['id']);
|
||||
$record = Opportunity::whereKey($ref['id'])->firstOrFail();
|
||||
$old = collect($previous)->first(fn ($row) => $row['opportunity']['key'] === $ref['key']);
|
||||
$origins = $this->portfolioOrigins($choice['portfolio_origins'] ?? array_column($old['portfolio_origins'] ?? [], 'id'), (int) $record->id);
|
||||
$corridors = app(InvestmentCorridorContext::class);
|
||||
@@ -52,14 +78,18 @@ final class InvestmentOpportunityChoices
|
||||
$provinces = $corridor ? $corridors->provinces($corridor) : [];
|
||||
$documented = $record->primary_territory_id;
|
||||
$territory = array_key_exists('territory', $choice) ? $choice['territory'] : ($documented ? 'territory:'.$documented : null);
|
||||
if (!$territory && count($provinces) === 1) $territory = 'territory:'.$provinces[0]->id;
|
||||
if ($corridor && $territory) abort_unless($corridors->compatible($corridor, substr($territory, 10)), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
if (! $territory && count($provinces) === 1) {
|
||||
$territory = 'territory:'.$provinces[0]->id;
|
||||
}
|
||||
if ($corridor && $territory) {
|
||||
abort_unless($corridors->compatible($corridor, substr($territory, 10)), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
$previousTerritory = $old['territory']['key'] ?? null;
|
||||
$newAlternative = $documented && $territory !== 'territory:'.$documented
|
||||
&& (! $old || ($old['documented_territory_id'] ?? null) !== $documented || $territory !== $previousTerritory);
|
||||
$corridorChanged = $old && ($old['corridor_key'] ?? $corridors->key($record)) !== $corridor;
|
||||
$incompatibleOld = $corridorChanged && $previousTerritory && !$corridors->compatible($corridor, substr($previousTerritory, 10));
|
||||
if (!$pending && ($newAlternative || ($previousTerritory && $territory !== $previousTerritory && !$incompatibleOld))) {
|
||||
$incompatibleOld = $corridorChanged && $previousTerritory && ! $corridors->compatible($corridor, substr($previousTerritory, 10));
|
||||
if (! $pending && ($newAlternative || ($previousTerritory && $territory !== $previousTerritory && ! $incompatibleOld))) {
|
||||
abort_unless(! empty($choice['confirm_location_change']) && mb_strlen(trim($choice['location_reason'] ?? '')) >= 20,
|
||||
422, 'Uma localização documentada ou já confirmada só muda por escolha explícita, com confirmação e motivo.');
|
||||
}
|
||||
@@ -69,17 +99,17 @@ final class InvestmentOpportunityChoices
|
||||
$park = $parkKey ? app(InvestorContext::class)->reference($parkKey) : null;
|
||||
if ($park) {
|
||||
$eligible = $corridor ? array_column($corridors->parks($corridor, $location['id'] ?? null), 'id') : [];
|
||||
if (!in_array($park['id'], $eligible, true)) {
|
||||
abort_if(!empty($choice['park']), 422, 'A zona ou parque não é compatível com a localização desta oportunidade.');
|
||||
if (! in_array($park['id'], $eligible, true)) {
|
||||
abort_if(! empty($choice['park']), 422, 'A zona ou parque não é compatível com a localização desta oportunidade.');
|
||||
$park = null;
|
||||
}
|
||||
abort_unless(!$park || $park['kind'] === 'park', 422);
|
||||
abort_unless(! $park || $park['kind'] === 'park', 422);
|
||||
}
|
||||
$result[] = ['opportunity' => $ref, 'territory' => $location, ...($origins ? ['portfolio_origins' => $origins] : []),
|
||||
'park' => $park,
|
||||
'corridor_key' => $corridor, 'corridor_name' => $corridor ? config('investment_corridors.'.$corridor.'.name') : null,
|
||||
'allowed_provinces' => array_map(fn($p)=>(array)$p, $provinces),
|
||||
'territory_path' => $location ? array_map(fn ($node) => \Illuminate\Support\Arr::only((array) $node, ['id', 'name', 'parent_id', 'location_type']), app(InvestmentGeography::class)->path($location['id'], true)) : [],
|
||||
'allowed_provinces' => array_map(fn ($p) => (array) $p, $provinces),
|
||||
'territory_path' => $location ? array_map(fn ($node) => Arr::only((array) $node, ['id', 'name', 'parent_id', 'location_type']), app(InvestmentGeography::class)->path($location['id'], true)) : [],
|
||||
'activities' => $choice['activities'] ?? ($old['activities'] ?? []),
|
||||
'documented_territory_id' => $documented, 'location_reason' => $choice['location_reason'] ?? '',
|
||||
'location_state' => $location ? ($documented && $territory === 'territory:'.$documented ? 'documented' : 'investor_selected') : 'undetermined',
|
||||
@@ -88,6 +118,7 @@ final class InvestmentOpportunityChoices
|
||||
'source' => data_get($record->workflow_context, 'corridor_agribusiness.source'),
|
||||
'source_sha256' => data_get($record->workflow_context, 'corridor_agribusiness.source_sha256')];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentZone;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -11,6 +12,7 @@ use Illuminate\Support\Str;
|
||||
class InvestmentZoneIntegralDetails
|
||||
{
|
||||
public const GROUPS = ['titles', 'phases', 'plots', 'occupants', 'observations', 'chains'];
|
||||
|
||||
public const EXTRA = [
|
||||
'titles' => ['kind', 'identifier', 'valid_from', 'valid_until'],
|
||||
'phases' => ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
|
||||
@@ -19,79 +21,179 @@ class InvestmentZoneIntegralDetails
|
||||
'observations' => ['indicator', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
|
||||
'chains' => ['kind', 'organization_id', 'documentary_name', 'zone_link_id', 'phase_id', 'plot_id'],
|
||||
];
|
||||
|
||||
public const COMMON = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', 'disclosure', 'private_note', 'support_document_ids'];
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $before
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function merge(InvestmentZone $zone, array $before, array $input): array
|
||||
{
|
||||
abort_if(array_diff(array_keys($input), ['schema_version', 'remove_ids', ...self::GROUPS]), 422, 'Campo da ficha integral desconhecido.');
|
||||
abort_if(array_diff(array_keys($input), ['schema_version', 'remove_ids', ...self::GROUPS]) !== [], 422, 'Campo da ficha integral desconhecido.');
|
||||
$rules = ['schema_version' => 'sometimes|in:1', 'remove_ids' => 'sometimes|array:'.implode(',', self::GROUPS)];
|
||||
foreach (self::GROUPS as $group) {
|
||||
$rules[$group] = 'sometimes|array|max:200';
|
||||
$rules[$group.'.*'] = 'array:'.implode(',', [...self::COMMON, ...self::EXTRA[$group]]);
|
||||
foreach (['id'=>'nullable|uuid','label'=>'required|string|max:300','label_en'=>'nullable|string|max:300','description'=>'nullable|string|max:3000','description_en'=>'nullable|string|max:3000','knowledge'=>'required|in:unknown,documented,disputed','source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500','disclosure'=>'required|boolean','private_note'=>'nullable|string|max:4000','support_document_ids'=>'sometimes|array|max:20','support_document_ids.*'=>'uuid'] as $key=>$rule) $rules[$group.'.*.'.$key]=$rule;
|
||||
foreach (self::EXTRA[$group] as $key) $rules[$group.'.*.'.$key]=match ($key) {
|
||||
'organization_id','phase_id','plot_id','zone_link_id','geometry_id'=>'nullable|uuid',
|
||||
'area'=>'nullable|numeric|min:0|max:999999999999999',
|
||||
'value'=>'nullable|numeric|between:-999999999999999,999999999999999',
|
||||
'starts_at','ends_at','valid_from','valid_until','period_start','period_end'=>'nullable|date_format:Y-m-d',
|
||||
'expansion'=>'nullable|boolean',
|
||||
default=>'nullable|string|max:2000',
|
||||
};
|
||||
$rules['remove_ids.'.$group]='sometimes|array|max:200';$rules['remove_ids.'.$group.'.*']='uuid';
|
||||
}
|
||||
$rules['plots.*.area_unit']='nullable|in:ha,m2';
|
||||
$rules['plots.*.status']='nullable|in:unknown,planned,available_declared,reserved,occupied,construction,inactive';
|
||||
$rules['phases.*.status']='nullable|in:unknown,planned,construction,operational,suspended,closed';
|
||||
$rules['occupants.*.status']='nullable|in:unknown,approved,construction,installed,inactive';
|
||||
$rules['titles.*.kind']='nullable|in:creation,land_use,licence,special_regime,other';
|
||||
$rules['chains.*.kind']='nullable|in:anchor,supplier,unmet_need,other';
|
||||
$rules['observations.*.indicator']='required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
|
||||
$data=Validator::make($input,$rules)->validate();$result=$before;
|
||||
foreach(self::GROUPS as$group){
|
||||
$rows=collect($before[$group]??[])->keyBy('id')->all();$remove=$data['remove_ids'][$group]??[];$seen=[];
|
||||
foreach($data[$group]??[]as$item){
|
||||
$id=$item['id']??(string)Str::uuid();abort_if(in_array($id,$seen,true)||in_array($id,$remove,true),422,'Identificador repetido ou removido na mesma operação.');$seen[]=$id;
|
||||
$item=[...($rows[$id]??[]),...$item,'id'=>$id];
|
||||
if($item['knowledge']!=='unknown')abort_unless(trim($item['source_reference']??'')!=='',422,'Indique a fonte documental ou preserve como desconhecido.');
|
||||
if($item['knowledge']==='unknown')abort_if(isset($item['value'])||isset($item['area']),422,'Quantidade desconhecida deve permanecer vazia, não zero.');
|
||||
if($item['knowledge']==='unknown'&&!empty($item['status']))abort_unless($item['status']==='unknown',422,'Situação operacional declarada exige fonte ou indicação de divergência.');
|
||||
foreach([['starts_at','ends_at'],['valid_from','valid_until'],['period_start','period_end']]as[$a,$b])if(isset($item[$a],$item[$b]))abort_if($item[$b]<$item[$a],422,'Período final anterior ao início.');
|
||||
if($group==='plots'&&isset($item['area']))abort_unless(!empty($item['area_unit'])&&!empty($item['scope']),422,'Área declarada exige unidade e âmbito.');
|
||||
if($group==='plots'&&($item['status']??'')==='available_declared')abort_unless($item['knowledge']==='documented'&&!empty($item['source_date']),422,'Disponibilidade declarada exige fonte e data; não é disponibilidade em tempo real.');
|
||||
if($group==='observations'&&isset($item['value']))abort_unless(!empty($item['unit'])&&!empty($item['period_start'])&&!empty($item['period_end'])&&!empty($item['scope'])&&!empty($item['population']),422,'Indicador numérico exige unidade, período, âmbito e base/população.');
|
||||
if(!empty($item['organization_id']))abort_unless(DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->exists(),422,'Reutilize uma entidade existente.');
|
||||
if(!empty($item['geometry_id']))abort_unless(DB::table('investment_zone_geometries')->where('zone_id',$zone->id)->where('geometry_id',$item['geometry_id'])->exists(),422,'Geometria deve estar associada a este parque; limite administrativo não é perímetro.');
|
||||
if(!empty($item['zone_link_id']))abort_unless(DB::table('investment_zone_links')->where('zone_id',$zone->id)->where('id',$item['zone_link_id'])->exists(),422,'Relação económica deve pertencer a este parque.');
|
||||
foreach($item['support_document_ids']??[]as$doc)abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d','d.id','=','a.document_id')->where('a.zone_id',$zone->id)->where('d.id',$doc)->whereNull('d.deleted_at')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256')->exists(),422,'Suporte deve estar consultável e associado a este parque.');
|
||||
$rows[$id]=$item;
|
||||
foreach (['id' => 'nullable|uuid', 'label' => 'required|string|max:300', 'label_en' => 'nullable|string|max:300', 'description' => 'nullable|string|max:3000', 'description_en' => 'nullable|string|max:3000', 'knowledge' => 'required|in:unknown,documented,disputed', 'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'scope' => 'nullable|string|max:500', 'disclosure' => 'required|boolean', 'private_note' => 'nullable|string|max:4000', 'support_document_ids' => 'sometimes|array|max:20', 'support_document_ids.*' => 'uuid'] as $key => $rule) {
|
||||
$rules[$group.'.*.'.$key] = $rule;
|
||||
}
|
||||
foreach($remove as$id){abort_unless(isset($rows[$id]),422,'O detalhe a remover não pertence ao parque.');unset($rows[$id]);}
|
||||
abort_if(count($rows)>200,422,'Limite de detalhes excedido.');$result[$group]=array_values($rows);
|
||||
foreach (self::EXTRA[$group] as $key) {
|
||||
$rules[$group.'.*.'.$key] = match ($key) {
|
||||
'organization_id','phase_id','plot_id','zone_link_id','geometry_id' => 'nullable|uuid',
|
||||
'area' => 'nullable|numeric|min:0|max:999999999999999',
|
||||
'value' => 'nullable|numeric|between:-999999999999999,999999999999999',
|
||||
'starts_at','ends_at','valid_from','valid_until','period_start','period_end' => 'nullable|date_format:Y-m-d',
|
||||
'expansion' => 'nullable|boolean',
|
||||
default => 'nullable|string|max:2000',
|
||||
};
|
||||
}
|
||||
$rules['remove_ids.'.$group] = 'sometimes|array|max:200';
|
||||
$rules['remove_ids.'.$group.'.*'] = 'uuid';
|
||||
}
|
||||
$rules['plots.*.area_unit'] = 'nullable|in:ha,m2';
|
||||
$rules['plots.*.status'] = 'nullable|in:unknown,planned,available_declared,reserved,occupied,construction,inactive';
|
||||
$rules['phases.*.status'] = 'nullable|in:unknown,planned,construction,operational,suspended,closed';
|
||||
$rules['occupants.*.status'] = 'nullable|in:unknown,approved,construction,installed,inactive';
|
||||
$rules['titles.*.kind'] = 'nullable|in:creation,land_use,licence,special_regime,other';
|
||||
$rules['chains.*.kind'] = 'nullable|in:anchor,supplier,unmet_need,other';
|
||||
$rules['observations.*.indicator'] = 'required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
$result = $before;
|
||||
foreach (self::GROUPS as $group) {
|
||||
$rows = collect(StructuredData::collectionItems($before[$group] ?? []))->keyBy('id')->all();
|
||||
$remove = $data['remove_ids'][$group] ?? [];
|
||||
$seen = [];
|
||||
foreach ($data[$group] ?? [] as $item) {
|
||||
$id = $item['id'] ?? (string) Str::uuid();
|
||||
abort_if(in_array($id, $seen, true) || in_array($id, $remove, true), 422, 'Identificador repetido ou removido na mesma operação.');
|
||||
$seen[] = $id;
|
||||
$item = [...($rows[$id] ?? []), ...$item, 'id' => $id];
|
||||
if ($item['knowledge'] !== 'unknown') {
|
||||
abort_unless(trim($item['source_reference'] ?? '') !== '', 422, 'Indique a fonte documental ou preserve como desconhecido.');
|
||||
}
|
||||
if ($item['knowledge'] === 'unknown') {
|
||||
abort_if(isset($item['value']) || isset($item['area']), 422, 'Quantidade desconhecida deve permanecer vazia, não zero.');
|
||||
}
|
||||
if ($item['knowledge'] === 'unknown' && ! empty($item['status'])) {
|
||||
abort_unless($item['status'] === 'unknown', 422, 'Situação operacional declarada exige fonte ou indicação de divergência.');
|
||||
}
|
||||
foreach ([['starts_at', 'ends_at'], ['valid_from', 'valid_until'], ['period_start', 'period_end']] as [$a,$b]) {
|
||||
if (isset($item[$a],$item[$b])) {
|
||||
abort_if($item[$b] < $item[$a], 422, 'Período final anterior ao início.');
|
||||
}
|
||||
}
|
||||
if ($group === 'plots' && isset($item['area'])) {
|
||||
abort_unless(! empty($item['area_unit']) && ! empty($item['scope']), 422, 'Área declarada exige unidade e âmbito.');
|
||||
}
|
||||
if ($group === 'plots' && ($item['status'] ?? '') === 'available_declared') {
|
||||
abort_unless($item['knowledge'] === 'documented' && ! empty($item['source_date']), 422, 'Disponibilidade declarada exige fonte e data; não é disponibilidade em tempo real.');
|
||||
}
|
||||
if ($group === 'observations' && isset($item['value'])) {
|
||||
abort_unless(! empty($item['unit']) && ! empty($item['period_start']) && ! empty($item['period_end']) && ! empty($item['scope']) && ! empty($item['population']), 422, 'Indicador numérico exige unidade, período, âmbito e base/população.');
|
||||
}
|
||||
if (! empty($item['organization_id'])) {
|
||||
abort_unless(DB::table('organizations')->where('id', $item['organization_id'])->whereNull('deleted_at')->exists(), 422, 'Reutilize uma entidade existente.');
|
||||
}
|
||||
if (! empty($item['geometry_id'])) {
|
||||
abort_unless(DB::table('investment_zone_geometries')->where('zone_id', $zone->id)->where('geometry_id', $item['geometry_id'])->exists(), 422, 'Geometria deve estar associada a este parque; limite administrativo não é perímetro.');
|
||||
}
|
||||
if (! empty($item['zone_link_id'])) {
|
||||
abort_unless(DB::table('investment_zone_links')->where('zone_id', $zone->id)->where('id', $item['zone_link_id'])->exists(), 422, 'Relação económica deve pertencer a este parque.');
|
||||
}
|
||||
foreach ($item['support_document_ids'] ?? [] as $doc) {
|
||||
abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')->where('a.zone_id', $zone->id)->where('d.id', $doc)->whereNull('d.deleted_at')->where('d.status', 'active')->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->exists(), 422, 'Suporte deve estar consultável e associado a este parque.');
|
||||
}
|
||||
$rows[$id] = $item;
|
||||
}
|
||||
foreach ($remove as $id) {
|
||||
abort_unless(isset($rows[$id]), 422, 'O detalhe a remover não pertence ao parque.');
|
||||
unset($rows[$id]);
|
||||
}
|
||||
abort_if(count($rows) > 200, 422, 'Limite de detalhes excedido.');
|
||||
$result[$group] = array_values($rows);
|
||||
}
|
||||
// References resolve only inside this park, including new items in the same transaction.
|
||||
foreach(self::GROUPS as$group)foreach($result[$group]as$item){
|
||||
foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key]))abort_unless(in_array($item[$key],array_column($result[$target],'id'),true),422,'Referência interna inexistente ou de outro parque.');
|
||||
if(!empty($item['phase_id'])&&!empty($item['plot_id'])){$plot=collect($result['plots'])->firstWhere('id',$item['plot_id']);abort_if(!empty($plot['phase_id'])&&$plot['phase_id']!==$item['phase_id'],422,'Lote e fase não correspondem.');}
|
||||
foreach (self::GROUPS as $group) {
|
||||
foreach ($result[$group] as $item) {
|
||||
foreach (['phase_id' => 'phases', 'plot_id' => 'plots'] as $key => $target) {
|
||||
if (! empty($item[$key])) {
|
||||
abort_unless(in_array($item[$key], array_column($result[$target], 'id'), true), 422, 'Referência interna inexistente ou de outro parque.');
|
||||
}
|
||||
}
|
||||
if (! empty($item['phase_id']) && ! empty($item['plot_id'])) {
|
||||
$plot = collect($result['plots'])->firstWhere('id', $item['plot_id']);
|
||||
abort_if(! empty($plot['phase_id']) && $plot['phase_id'] !== $item['phase_id'], 422, 'Lote e fase não correspondem.');
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach(['phases','plots']as$group){$codes=[];foreach($result[$group]as$item)if(trim($item['code']??'')!==''){$code=mb_strtolower(trim($item['code']));abort_if(in_array($code,$codes,true),422,'Código interno repetido no parque.');$codes[]=$code;}}
|
||||
$keys=[];foreach($result['occupants']as$item){$key=implode('|',[$item['organization_id']??$item['documentary_name']??$item['id'],$item['plot_id']??'',$item['valid_from']??'',$item['valid_until']??'']);abort_if(in_array($key,$keys,true),422,'Ocupante/período já registado; reutilize o detalhe.');$keys[]=$key;}
|
||||
$keys=[];foreach($result['observations']as$item){if(!isset($item['period_start'],$item['period_end']))continue;$key=implode('|',[$item['indicator'],$item['period_start'],$item['period_end'],$item['scope']??'',$item['population']??'',$item['unit']??'',$item['methodology']??'',$item['source_reference']??'',$item['source_date']??'',$item['phase_id']??'',$item['plot_id']??'']);abort_if(in_array($key,$keys,true),422,'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');$keys[]=$key;}
|
||||
return [...$result,'schema_version'=>1];
|
||||
foreach (['phases', 'plots'] as $group) {
|
||||
$codes = [];
|
||||
foreach ($result[$group] as $item) {
|
||||
if (trim($item['code'] ?? '') !== '') {
|
||||
$code = mb_strtolower(trim($item['code']));
|
||||
abort_if(in_array($code, $codes, true), 422, 'Código interno repetido no parque.');
|
||||
$codes[] = $code;
|
||||
}
|
||||
}
|
||||
}
|
||||
$keys = [];
|
||||
foreach ($result['occupants'] as $item) {
|
||||
$key = implode('|', [$item['organization_id'] ?? $item['documentary_name'] ?? $item['id'], $item['plot_id'] ?? '', $item['valid_from'] ?? '', $item['valid_until'] ?? '']);
|
||||
abort_if(in_array($key, $keys, true), 422, 'Ocupante/período já registado; reutilize o detalhe.');
|
||||
$keys[] = $key;
|
||||
}
|
||||
$keys = [];
|
||||
foreach ($result['observations'] as $item) {
|
||||
if (! isset($item['period_start'],$item['period_end'])) {
|
||||
continue;
|
||||
}$key = implode('|', [$item['indicator'], $item['period_start'], $item['period_end'], $item['scope'] ?? '', $item['population'] ?? '', $item['unit'] ?? '', $item['methodology'] ?? '', $item['source_reference'] ?? '', $item['source_date'] ?? '', $item['phase_id'] ?? '', $item['plot_id'] ?? '']);
|
||||
abort_if(in_array($key, $keys, true), 422, 'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');
|
||||
$keys[] = $key;
|
||||
}
|
||||
|
||||
return [...$result, 'schema_version' => 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $fields
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicData(array $fields): array
|
||||
{
|
||||
$public=['schema_version'=>1];
|
||||
foreach(self::GROUPS as$group){$public[$group]=[];foreach($fields[$group]??[]as$item){
|
||||
if(!($item['disclosure']??false))continue;
|
||||
$keys=['id','label','label_en','description','description_en','knowledge','source_reference','source_date','scope',...self::EXTRA[$group]];
|
||||
$visible=array_intersect_key($item,array_flip($keys));unset($visible['organization_id'],$visible['documentary_name'],$visible['geometry_id'],$visible['zone_link_id']);
|
||||
if(in_array($group,['occupants','chains'],true)&&!empty($item['organization_id'])){$org=DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->where('data_classification','public')->first();abort_unless($org&&$item['knowledge']==='documented',422,'Divulgar entidade exige cadastro público e fonte; a menção preliminar permanece privada.');$visible['organization_name']=$org->name;}
|
||||
if($group==='occupants')abort_unless(!empty($visible['organization_name']),422,'Ocupante por identificar permanece privado.');
|
||||
$public[$group][]=$visible;
|
||||
}}
|
||||
$public = ['schema_version' => 1];
|
||||
foreach (self::GROUPS as $group) {
|
||||
$public[$group] = [];
|
||||
foreach ($fields[$group] ?? [] as $item) {
|
||||
if (! ($item['disclosure'] ?? false)) {
|
||||
continue;
|
||||
}
|
||||
$keys = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', ...self::EXTRA[$group]];
|
||||
$visible = array_intersect_key($item, array_flip($keys));
|
||||
unset($visible['organization_id'],$visible['documentary_name'],$visible['geometry_id'],$visible['zone_link_id']);
|
||||
if (in_array($group, ['occupants', 'chains'], true) && ! empty($item['organization_id'])) {
|
||||
$org = DB::table('organizations')->where('id', $item['organization_id'])->whereNull('deleted_at')->where('data_classification', 'public')->first();
|
||||
abort_unless($org && $item['knowledge'] === 'documented', 422, 'Divulgar entidade exige cadastro público e fonte; a menção preliminar permanece privada.');
|
||||
$visible['organization_name'] = $org->name;
|
||||
}
|
||||
if ($group === 'occupants') {
|
||||
abort_unless(! empty($visible['organization_name']), 422, 'Ocupante por identificar permanece privado.');
|
||||
}
|
||||
$public[$group][] = $visible;
|
||||
}
|
||||
}
|
||||
// A disclosed item must not leak the identifier of an undisclosed phase or plot.
|
||||
foreach(self::GROUPS as$group)foreach($public[$group]as&$item)foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key])&&!in_array($item[$key],array_column($public[$target],'id'),true))unset($item[$key]);unset($item);
|
||||
foreach (self::GROUPS as $group) {
|
||||
foreach ($public[$group] as &$item) {
|
||||
foreach (['phase_id' => 'phases', 'plot_id' => 'plots'] as $key => $target) {
|
||||
if (! empty($item[$key]) && ! in_array($item[$key], array_column($public[$target], 'id'), true)) {
|
||||
unset($item[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}unset($item);
|
||||
|
||||
return $public;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentZone;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -14,119 +15,188 @@ use Illuminate\Validation\ValidationException;
|
||||
class InvestmentZoneOperationalDetails
|
||||
{
|
||||
public const MIGRATION = '2026_10_16_140000_add_investment_zone_operational_details';
|
||||
|
||||
public const GROUPS = ['responsibilities', 'conditions', 'risks'];
|
||||
|
||||
public function installed(): bool { return Schema::hasColumn('investment_zones', 'operational_details'); }
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasColumn('investment_zones', 'operational_details');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function stored(InvestmentZone $zone): ?array
|
||||
{
|
||||
$raw = $zone->getRawOriginal('operational_details');
|
||||
|
||||
return $raw ? json_decode($raw, true, 512, JSON_THROW_ON_ERROR) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function recover(InvestmentZone $zone): array
|
||||
{
|
||||
$stored = $this->stored($zone);
|
||||
if (!$stored) { return ['schema_version'=>1, 'responsibilities'=>[], 'conditions'=>[], 'risks'=>[], 'review'=>[]]; }
|
||||
if (! $stored) {
|
||||
return ['schema_version' => 1, 'responsibilities' => [], 'conditions' => [], 'risks' => [], 'review' => []];
|
||||
}
|
||||
try {
|
||||
if (($stored['schema_version'] ?? null) !== 1) { throw new \RuntimeException('Unsupported supplement'); }
|
||||
if (($stored['schema_version'] ?? null) !== 1) {
|
||||
throw new \RuntimeException('Unsupported supplement');
|
||||
}
|
||||
|
||||
return json_decode(Crypt::decryptString($stored['private_ciphertext']), true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\Throwable $e) {
|
||||
throw ValidationException::withMessages(['operational_details'=>'Não foi possível recuperar os detalhes privados. Os dados foram preservados; contacte o suporte.']);
|
||||
throw ValidationException::withMessages(['operational_details' => 'Não foi possível recuperar os detalhes privados. Os dados foram preservados; contacte o suporte.']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicData(InvestmentZone $zone): array
|
||||
{
|
||||
return $this->stored($zone)['public'] ?? [];
|
||||
}
|
||||
|
||||
/** Merge only supplied keys. An absent group/item is preserved; removal requires explicit IDs. */
|
||||
/** Merge only supplied keys. An absent group/item is preserved; removal requires explicit IDs.
|
||||
* @param array<array-key, mixed> $before
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function merge(InvestmentZone $zone, array $before, array $input, ?string $operatorId): array
|
||||
{
|
||||
abort_unless($zone->category==='industrial_park',422,'O complemento L1 aplica-se à ficha de parques.');
|
||||
abort_unless($this->installed(),503,'Detalhes L1 ainda não instalados. A ficha pública foi preservada.');
|
||||
$rules=['integral'=>'sometimes|array','schema_version'=>'sometimes|in:1','responsibilities'=>'sometimes|array|max:40','conditions'=>'sometimes|array|max:60','risks'=>'sometimes|array|max:40',
|
||||
'remove_ids'=>'sometimes|array:responsibilities,conditions,risks','review'=>'sometimes|array:source_reference,source_date,scope,confidence,last_reviewed_at,next_review_at,private_note',
|
||||
'review.confidence'=>'nullable|in:unknown,reported,documented,disputed','review.last_reviewed_at'=>'nullable|date_format:Y-m-d','review.next_review_at'=>'nullable|date_format:Y-m-d','review.private_note'=>'nullable|string|max:4000'];
|
||||
$common='id,label,knowledge,disclosure,source_reference,source_date,scope,private_note,support_document_ids';
|
||||
foreach(self::GROUPS as $g){
|
||||
$extra=$g==='responsibilities'?',role,organization_id,documentary_name,private_contact,public_contact,declared_nature,management_model':($g==='conditions'?',value,currency,unit,period,valid_from,valid_until,modality':',risk_type,mitigation,responsible_role,channel,channel_owner');
|
||||
$rules[$g.'.*']=['array:'.$common.$extra];
|
||||
foreach(['id'=>'nullable|uuid','label'=>'required|string|max:300','knowledge'=>'required|in:unknown,documented,disputed','disclosure'=>'required|boolean',
|
||||
'source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500','private_note'=>'nullable|string|max:4000',
|
||||
'support_document_ids'=>'sometimes|array|max:10','support_document_ids.*'=>'uuid'] as $k=>$r){$rules[$g.'.*.'.$k]=$r;}
|
||||
$rules['remove_ids.'.$g]='sometimes|array|max:60';$rules['remove_ids.'.$g.'.*']='uuid';
|
||||
abort_unless($zone->category === 'industrial_park', 422, 'O complemento L1 aplica-se à ficha de parques.');
|
||||
abort_unless($this->installed(), 503, 'Detalhes L1 ainda não instalados. A ficha pública foi preservada.');
|
||||
$rules = ['integral' => 'sometimes|array', 'schema_version' => 'sometimes|in:1', 'responsibilities' => 'sometimes|array|max:40', 'conditions' => 'sometimes|array|max:60', 'risks' => 'sometimes|array|max:40',
|
||||
'remove_ids' => 'sometimes|array:responsibilities,conditions,risks', 'review' => 'sometimes|array:source_reference,source_date,scope,confidence,last_reviewed_at,next_review_at,private_note',
|
||||
'review.confidence' => 'nullable|in:unknown,reported,documented,disputed', 'review.last_reviewed_at' => 'nullable|date_format:Y-m-d', 'review.next_review_at' => 'nullable|date_format:Y-m-d', 'review.private_note' => 'nullable|string|max:4000'];
|
||||
$common = 'id,label,knowledge,disclosure,source_reference,source_date,scope,private_note,support_document_ids';
|
||||
foreach (self::GROUPS as $g) {
|
||||
$extra = $g === 'responsibilities' ? ',role,organization_id,documentary_name,private_contact,public_contact,declared_nature,management_model' : ($g === 'conditions' ? ',value,currency,unit,period,valid_from,valid_until,modality' : ',risk_type,mitigation,responsible_role,channel,channel_owner');
|
||||
$rules[$g.'.*'] = ['array:'.$common.$extra];
|
||||
foreach (['id' => 'nullable|uuid', 'label' => 'required|string|max:300', 'knowledge' => 'required|in:unknown,documented,disputed', 'disclosure' => 'required|boolean',
|
||||
'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'scope' => 'nullable|string|max:500', 'private_note' => 'nullable|string|max:4000',
|
||||
'support_document_ids' => 'sometimes|array|max:10', 'support_document_ids.*' => 'uuid'] as $k => $r) {
|
||||
$rules[$g.'.*.'.$k] = $r;
|
||||
}
|
||||
$rules['remove_ids.'.$g] = 'sometimes|array|max:60';
|
||||
$rules['remove_ids.'.$g.'.*'] = 'uuid';
|
||||
}
|
||||
foreach(['source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500']as$k=>$r){$rules['review.'.$k]=$r;}
|
||||
foreach(['role'=>'required|in:owner,promoter,operator,manager','organization_id'=>'nullable|uuid','documentary_name'=>'nullable|string|max:300','private_contact'=>'nullable|string|max:1000','public_contact'=>'nullable|string|max:1000','declared_nature'=>'nullable|string|max:300','management_model'=>'nullable|string|max:500']as$k=>$r){$rules['responsibilities.*.'.$k]=$r;}
|
||||
foreach(['value'=>'nullable|numeric|min:0','currency'=>'nullable|in:MZN,USD,EUR,ZAR','unit'=>'nullable|string|max:80','period'=>'nullable|string|max:80','valid_from'=>'nullable|date_format:Y-m-d','valid_until'=>'nullable|date_format:Y-m-d','modality'=>'nullable|string|max:300']as$k=>$r){$rules['conditions.*.'.$k]=$r;}
|
||||
foreach(['risk_type'=>'nullable|string|max:300','mitigation'=>'nullable|string|max:2000','responsible_role'=>'nullable|in:owner,promoter,operator,manager,unknown','channel'=>'nullable|string|max:1000','channel_owner'=>'nullable|in:park,tempo,unknown']as$k=>$r){$rules['risks.*.'.$k]=$r;}
|
||||
abort_if(array_diff(array_keys($input),['schema_version',...self::GROUPS,'review','remove_ids','integral']),422,'Campo L1 não reconhecido.');
|
||||
$data=Validator::make($input,$rules)->validate();$result=$before;
|
||||
foreach(self::GROUPS as $g){
|
||||
$rows=collect($before[$g] ?? [])->keyBy('id')->all();$removals=$data['remove_ids'][$g] ?? []; $seen=[];
|
||||
foreach($data[$g] ?? [] as $item){
|
||||
$id=$item['id'] ?? (string)Str::uuid();
|
||||
abort_if(in_array($id,$seen,true)||in_array($id,$removals,true),422,'Identificador L1 repetido ou removido na mesma operação.');$seen[]=$id;
|
||||
$item=[...($rows[$id] ?? []),...$item,'id'=>$id];
|
||||
if($item['knowledge']==='unknown') { abort_if(isset($item['value']),422,'Valor desconhecido deve permanecer vazio, nunca zero por defeito.'); }
|
||||
else { abort_unless(trim($item['source_reference'] ?? '')!=='',422,'Identifique a fonte da informação documentada ou divergente.'); }
|
||||
if($g==='conditions' && isset($item['value'])){
|
||||
abort_unless(trim($item['currency'] ?? '')!=='' && trim($item['unit'] ?? '')!=='' && trim($item['scope'] ?? '')!=='',422,'Uma tarifa numérica exige moeda, unidade/base e âmbito; pode manter o valor desconhecido.');
|
||||
foreach (['source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'scope' => 'nullable|string|max:500'] as $k => $r) {
|
||||
$rules['review.'.$k] = $r;
|
||||
}
|
||||
foreach (['role' => 'required|in:owner,promoter,operator,manager', 'organization_id' => 'nullable|uuid', 'documentary_name' => 'nullable|string|max:300', 'private_contact' => 'nullable|string|max:1000', 'public_contact' => 'nullable|string|max:1000', 'declared_nature' => 'nullable|string|max:300', 'management_model' => 'nullable|string|max:500'] as $k => $r) {
|
||||
$rules['responsibilities.*.'.$k] = $r;
|
||||
}
|
||||
foreach (['value' => 'nullable|numeric|min:0', 'currency' => 'nullable|in:MZN,USD,EUR,ZAR', 'unit' => 'nullable|string|max:80', 'period' => 'nullable|string|max:80', 'valid_from' => 'nullable|date_format:Y-m-d', 'valid_until' => 'nullable|date_format:Y-m-d', 'modality' => 'nullable|string|max:300'] as $k => $r) {
|
||||
$rules['conditions.*.'.$k] = $r;
|
||||
}
|
||||
foreach (['risk_type' => 'nullable|string|max:300', 'mitigation' => 'nullable|string|max:2000', 'responsible_role' => 'nullable|in:owner,promoter,operator,manager,unknown', 'channel' => 'nullable|string|max:1000', 'channel_owner' => 'nullable|in:park,tempo,unknown'] as $k => $r) {
|
||||
$rules['risks.*.'.$k] = $r;
|
||||
}
|
||||
abort_if(array_diff(array_keys($input), ['schema_version', ...self::GROUPS, 'review', 'remove_ids', 'integral']) !== [], 422, 'Campo L1 não reconhecido.');
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
$result = $before;
|
||||
foreach (self::GROUPS as $g) {
|
||||
$rows = collect(StructuredData::collectionItems($before[$g] ?? []))->keyBy('id')->all();
|
||||
$removals = $data['remove_ids'][$g] ?? [];
|
||||
$seen = [];
|
||||
foreach ($data[$g] ?? [] as $item) {
|
||||
$id = $item['id'] ?? (string) Str::uuid();
|
||||
abort_if(in_array($id, $seen, true) || in_array($id, $removals, true), 422, 'Identificador L1 repetido ou removido na mesma operação.');
|
||||
$seen[] = $id;
|
||||
$item = [...($rows[$id] ?? []), ...$item, 'id' => $id];
|
||||
if ($item['knowledge'] === 'unknown') {
|
||||
abort_if(isset($item['value']), 422, 'Valor desconhecido deve permanecer vazio, nunca zero por defeito.');
|
||||
} else {
|
||||
abort_unless(trim($item['source_reference'] ?? '') !== '', 422, 'Identifique a fonte da informação documentada ou divergente.');
|
||||
}
|
||||
if($g==='conditions' && isset($item['valid_from'],$item['valid_until'])){
|
||||
abort_if($item['valid_until']<$item['valid_from'],422,'O fim da vigência é anterior ao início; preserve datas desconhecidas como desconhecidas.');
|
||||
if ($g === 'conditions' && isset($item['value'])) {
|
||||
abort_unless(trim($item['currency'] ?? '') !== '' && trim($item['unit'] ?? '') !== '' && trim($item['scope'] ?? '') !== '', 422, 'Uma tarifa numérica exige moeda, unidade/base e âmbito; pode manter o valor desconhecido.');
|
||||
}
|
||||
if($g==='risks' && !empty($item['channel']) && ($item['channel_owner'] ?? 'unknown')==='park'){
|
||||
abort_unless($item['knowledge']==='documented' && trim($item['source_reference'] ?? '')!=='',422,'O canal próprio do parque exige fonte; pode manter o canal desconhecido ou usar o apoio da Tempo identificado como tal.');
|
||||
if ($g === 'conditions' && isset($item['valid_from'],$item['valid_until'])) {
|
||||
abort_if($item['valid_until'] < $item['valid_from'], 422, 'O fim da vigência é anterior ao início; preserve datas desconhecidas como desconhecidas.');
|
||||
}
|
||||
if($g==='responsibilities'){
|
||||
$org=$item['organization_id'] ?? null;
|
||||
if($org){abort_unless(DB::table('organizations')->where('id',$org)->whereNull('deleted_at')->exists(),422,'Reutilize uma entidade existente ou mantenha a menção documental preliminar.');}
|
||||
if($item['role']==='operator' && $org){
|
||||
$operator=$operatorId;
|
||||
abort_unless($operator===$org,422,'O operador é a associação canónica da ficha; não crie outro no suplemento.');
|
||||
if ($g === 'risks' && ! empty($item['channel']) && ($item['channel_owner'] ?? 'unknown') === 'park') {
|
||||
abort_unless($item['knowledge'] === 'documented', 422, 'O canal próprio do parque exige fonte; pode manter o canal desconhecido ou usar o apoio da Tempo identificado como tal.');
|
||||
}
|
||||
if ($g === 'responsibilities') {
|
||||
$org = $item['organization_id'] ?? null;
|
||||
if ($org) {
|
||||
abort_unless(DB::table('organizations')->where('id', $org)->whereNull('deleted_at')->exists(), 422, 'Reutilize uma entidade existente ou mantenha a menção documental preliminar.');
|
||||
}
|
||||
if ($item['role'] === 'operator' && $org) {
|
||||
$operator = $operatorId;
|
||||
abort_unless($operator === $org, 422, 'O operador é a associação canónica da ficha; não crie outro no suplemento.');
|
||||
}
|
||||
}
|
||||
foreach($item['support_document_ids'] ?? []as$document){
|
||||
abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d','d.id','=','a.document_id')->where('a.zone_id',$zone->id)->where('d.id',$document)
|
||||
->whereNull('d.deleted_at')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256')->exists(),422,'Selecione suporte consultável já associado à ficha; a publicação do anexo é independente.');
|
||||
foreach ($item['support_document_ids'] ?? [] as $document) {
|
||||
abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')->where('a.zone_id', $zone->id)->where('d.id', $document)
|
||||
->whereNull('d.deleted_at')->where('d.status', 'active')->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->exists(), 422, 'Selecione suporte consultável já associado à ficha; a publicação do anexo é independente.');
|
||||
}
|
||||
$rows[$id]=$item;
|
||||
$rows[$id] = $item;
|
||||
}
|
||||
foreach($removals as$id){abort_unless(isset($rows[$id]),422,'Detalhe a remover não pertence à ficha.');unset($rows[$id]);}
|
||||
abort_if(count($rows)>($g==='conditions'?60:40),422,'Limite de detalhes por grupo excedido.');
|
||||
$result[$g]=array_values($rows);
|
||||
foreach ($removals as $id) {
|
||||
abort_unless(isset($rows[$id]), 422, 'Detalhe a remover não pertence à ficha.');
|
||||
unset($rows[$id]);
|
||||
}
|
||||
abort_if(count($rows) > ($g === 'conditions' ? 60 : 40), 422, 'Limite de detalhes por grupo excedido.');
|
||||
$result[$g] = array_values($rows);
|
||||
}
|
||||
$pairs=[];foreach($result['responsibilities'] as$item){$key=$item['role'].'|'.($item['organization_id'] ?? $item['documentary_name'] ?? $item['id']);abort_if(in_array($key,$pairs,true),422,'A mesma entidade/função já está registada; reutilize o detalhe existente.');$pairs[]=$key;}
|
||||
if(array_key_exists('review',$data)){$result['review']=[...($before['review'] ?? []),...$data['review']];}
|
||||
if(array_key_exists('integral',$data)){$result['integral']=app(InvestmentZoneIntegralDetails::class)->merge($zone,$before['integral'] ?? [],$data['integral']);}
|
||||
$result['schema_version']=1;
|
||||
$pairs = [];
|
||||
foreach ($result['responsibilities'] as $item) {
|
||||
$key = $item['role'].'|'.($item['organization_id'] ?? $item['documentary_name'] ?? $item['id']);
|
||||
abort_if(in_array($key, $pairs, true), 422, 'A mesma entidade/função já está registada; reutilize o detalhe existente.');
|
||||
$pairs[] = $key;
|
||||
}
|
||||
if (array_key_exists('review', $data)) {
|
||||
$result['review'] = [...($before['review'] ?? []), ...$data['review']];
|
||||
}
|
||||
if (array_key_exists('integral', $data)) {
|
||||
$result['integral'] = app(InvestmentZoneIntegralDetails::class)->merge($zone, $before['integral'] ?? [], $data['integral']);
|
||||
}
|
||||
$result['schema_version'] = 1;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $fields
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function pack(array $fields): array
|
||||
{
|
||||
$public=[];
|
||||
foreach(self::GROUPS as$g){
|
||||
$public[$g]=[];
|
||||
foreach($fields[$g] ?? []as$item){
|
||||
if(!($item['disclosure'] ?? false)){continue;}
|
||||
$keys=['label','knowledge','source_reference','source_date','scope'];
|
||||
if($g==='conditions'){$keys=[...$keys,'value','currency','unit','period','valid_from','valid_until','modality'];}
|
||||
if($g==='risks'){$keys=[...$keys,'risk_type','mitigation','responsible_role','channel','channel_owner'];}
|
||||
$visible=array_intersect_key($item,array_flip($keys));
|
||||
if($g==='responsibilities'){
|
||||
$org=empty($item['organization_id'])?null:DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->where('data_classification','public')->first();
|
||||
abort_unless($org && $item['knowledge']==='documented',422,'Divulgação de função exige entidade pública existente e fundamento; menção preliminar continua privada.');
|
||||
$visible=[...$visible,'role'=>$item['role'],'organization_name'=>$org->name,'public_contact'=>$item['public_contact'] ?? null,'declared_nature'=>$item['declared_nature'] ?? null,'management_model'=>$item['management_model'] ?? null];
|
||||
$public = [];
|
||||
foreach (self::GROUPS as $g) {
|
||||
$public[$g] = [];
|
||||
foreach ($fields[$g] ?? [] as $item) {
|
||||
if (! ($item['disclosure'] ?? false)) {
|
||||
continue;
|
||||
}
|
||||
$public[$g][]=$visible;
|
||||
$keys = ['label', 'knowledge', 'source_reference', 'source_date', 'scope'];
|
||||
if ($g === 'conditions') {
|
||||
$keys = [...$keys, 'value', 'currency', 'unit', 'period', 'valid_from', 'valid_until', 'modality'];
|
||||
}
|
||||
if ($g === 'risks') {
|
||||
$keys = [...$keys, 'risk_type', 'mitigation', 'responsible_role', 'channel', 'channel_owner'];
|
||||
}
|
||||
$visible = array_intersect_key($item, array_flip($keys));
|
||||
if ($g === 'responsibilities') {
|
||||
$org = empty($item['organization_id']) ? null : DB::table('organizations')->where('id', $item['organization_id'])->whereNull('deleted_at')->where('data_classification', 'public')->first();
|
||||
abort_unless($org && $item['knowledge'] === 'documented', 422, 'Divulgação de função exige entidade pública existente e fundamento; menção preliminar continua privada.');
|
||||
$visible = [...$visible, 'role' => $item['role'], 'organization_name' => $org->name, 'public_contact' => $item['public_contact'] ?? null, 'declared_nature' => $item['declared_nature'] ?? null, 'management_model' => $item['management_model'] ?? null];
|
||||
}
|
||||
$public[$g][] = $visible;
|
||||
}
|
||||
}
|
||||
if(isset($fields['integral'])){$public['integral']=app(InvestmentZoneIntegralDetails::class)->publicData($fields['integral']);}
|
||||
$public['review']=array_intersect_key($fields['review'] ?? [],array_flip(['source_reference','source_date','scope','confidence','last_reviewed_at','next_review_at']));
|
||||
return ['schema_version'=>1,'public'=>$public,'private_ciphertext'=>Crypt::encryptString(json_encode($fields,JSON_THROW_ON_ERROR))];
|
||||
if (isset($fields['integral'])) {
|
||||
$public['integral'] = app(InvestmentZoneIntegralDetails::class)->publicData($fields['integral']);
|
||||
}
|
||||
$public['review'] = array_intersect_key($fields['review'] ?? [], array_flip(['source_reference', 'source_date', 'scope', 'confidence', 'last_reviewed_at', 'next_review_at']));
|
||||
|
||||
return ['schema_version' => 1, 'public' => $public, 'private_ciphertext' => Crypt::encryptString(json_encode($fields, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
@@ -12,75 +14,140 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
|
||||
class InvestmentZoneOperationalDetailsInstallation
|
||||
{
|
||||
public const SOURCE='investment-zone-details-installation';
|
||||
public const SOURCE = 'investment-zone-details-installation';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function files(): array
|
||||
{
|
||||
return ['app/Models/InvestmentZone.php', 'app/Http/Controllers/InvestmentZoneController.php', 'app/Services/InvestmentZones.php', 'app/Services/InvestmentZoneOperationalProfile.php', 'resources/js/pages/investment/zone.tsx', 'resources/js/pages/investment/zones.tsx', 'routes/investment-zones.php', 'resources/js/components/investment-zone-installation.tsx', 'app/Services/InvestmentZoneOperationalDetails.php', 'app/Services/InvestmentZoneOperationalDetailsInstallation.php', 'resources/js/components/investment-zone-operational-details.tsx', 'database/migrations/2026_10_16_140000_add_investment_zone_operational_details.php'];
|
||||
}
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
|
||||
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
|
||||
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
|
||||
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
|
||||
$files = array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files());
|
||||
foreach (File::allFiles(public_path('build')) as $file) {
|
||||
$files[] = ['public/build/'.$file->getRelativePathname(), hash_file('sha256', $file->getPathname())];
|
||||
}
|
||||
usort($files, fn ($a, $b) => strcmp($a[0], $b[0]));
|
||||
|
||||
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
private function authorize(User $actor,bool $write=false): void
|
||||
|
||||
private function authorize(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
|
||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Gestão autorizada necessária.');
|
||||
if ($write) {
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
}
|
||||
}
|
||||
private function evidence(array $target,string $code): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function evidence(array $target, string $code): array
|
||||
{
|
||||
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
|
||||
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
|
||||
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
|
||||
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
|
||||
$path=storage_path('app/private/investmoz-v2/park-details/readiness.json');
|
||||
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
|
||||
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
|
||||
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
|
||||
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
|
||||
$qa = app()->environment('testing') && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test')
|
||||
&& config('database.connections.pgsql.host') === '127.0.0.1' && ! config('database.connections.pgsql.url');
|
||||
if ($qa) {
|
||||
return ['ready' => true, 'mode' => 'isolated_QA'];
|
||||
}
|
||||
if (app()->environment('testing')) {
|
||||
return ['ready' => false, 'mode' => 'invalid_QA'];
|
||||
}
|
||||
$path = storage_path('app/private/investmoz-v2/park-details/readiness.json');
|
||||
$p = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||
$date = strtotime($p['verified_at'] ?? '');
|
||||
$auth = $p['active_authorization'] ?? [];
|
||||
$ready = $target['database'] === 'investemoz' && (int) $target['port'] === 5432 && ! config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||
&& ($p['target']['database'] ?? '') === $target['database'] && (int) ($p['target']['port'] ?? 0) === (int) $target['port']
|
||||
&& ($p['code_hash'] ?? '') === $code && $date !== false && $date <= time() && $date >= time() - 86400
|
||||
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
|
||||
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===InvestmentZoneOperationalDetails::MIGRATION;
|
||||
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
|
||||
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int) ($p['restore_target']['port'] ?? 0) === 55441 && str_ends_with($p['restore_target']['database'] ?? '', '_test')
|
||||
&& ($auth['decision_record'] ?? '') !== '' && ($auth['code_hash'] ?? '') === $code && ($auth['migration'] ?? '') === InvestmentZoneOperationalDetails::MIGRATION;
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
$file = $p[$kind.'_path'] ?? '';
|
||||
$ready = $ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '', CheckedFile::sha256($file));
|
||||
}
|
||||
|
||||
return ['ready' => $ready, 'mode' => 'active_requires_own_authorization_and_fresh_proof', 'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
|
||||
$ledgerCount=DB::table('migrations')->where('migration',InvestmentZoneOperationalDetails::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('investment_zones','operational_details');
|
||||
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='operational_details'");
|
||||
$correct=$shape && $shape->data_type==='jsonb' && $shape->is_nullable==='YES';
|
||||
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
|
||||
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
|
||||
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
|
||||
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
|
||||
if(!app(InvestmentZoneOperationalProfile::class)->installed() || DB::table('migrations')->where('migration',InvestmentZoneOperationalProfile::MIGRATION)->count()!==1){$reasons[]='Base 130000 ausente ou divergente; instalar/verificar antes de L1.';}
|
||||
$state=['target'=>$target,'migration'=>InvestmentZoneOperationalDetails::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
|
||||
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
|
||||
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
|
||||
$this->authorize($actor);
|
||||
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$code = $this->fingerprint();
|
||||
$ledgerCount = DB::table('migrations')->where('migration', InvestmentZoneOperationalDetails::MIGRATION)->count();
|
||||
$ledger = $ledgerCount === 1;
|
||||
$column = Schema::hasColumn('investment_zones', 'operational_details');
|
||||
$shape = DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='operational_details'");
|
||||
$correct = $shape && $shape->data_type === 'jsonb' && $shape->is_nullable === 'YES';
|
||||
$consistent = ($ledger && $column && $correct) || ($ledgerCount === 0 && ! $column);
|
||||
$reasons = [];
|
||||
if (! $consistent) {
|
||||
$reasons[] = 'Ledger e coluna divergentes; reconciliar sem instalação parcial.';
|
||||
}
|
||||
try {
|
||||
$this->authorize($actor, true);
|
||||
} catch (HttpException $e) {
|
||||
$reasons[] = $e->getMessage();
|
||||
}
|
||||
$evidence = $this->evidence($target, $code);
|
||||
if (! $evidence['ready']) {
|
||||
$reasons[] = 'Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';
|
||||
}
|
||||
if (! app(InvestmentZoneOperationalProfile::class)->installed() || DB::table('migrations')->where('migration', InvestmentZoneOperationalProfile::MIGRATION)->count() !== 1) {
|
||||
$reasons[] = 'Base 130000 ausente ou divergente; instalar/verificar antes de L1.';
|
||||
}
|
||||
$state = ['target' => $target, 'migration' => InvestmentZoneOperationalDetails::MIGRATION, 'code_hash' => $code, 'installed' => $ledger && $column,
|
||||
'consistent' => $consistent, 'ready' => $reasons === [], 'reasons' => $reasons, 'evidence' => $evidence];
|
||||
|
||||
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||
}
|
||||
public function apply(User $actor,array $input): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor,true);
|
||||
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
|
||||
return DB::transaction(function()use($actor,$data){
|
||||
DB::select('SELECT pg_advisory_xact_lock(161026,140000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
|
||||
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
|
||||
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
|
||||
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
|
||||
if(!$plan['installed']){
|
||||
config(['investment-zone-details.authenticated_installation'=>true]);
|
||||
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.InvestmentZoneOperationalDetails::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
|
||||
finally{config(['investment-zone-details.authenticated_installation'=>false]);}
|
||||
$this->authorize($actor, true);
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', '_token']) !== [], 422, 'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(161026,140000)');
|
||||
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$old = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $data['idempotency_key'])->first();
|
||||
if ($old) {
|
||||
$receipt = json_decode($old->after_data, true);
|
||||
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave já utilizada com outro ator ou conteúdo.');
|
||||
|
||||
return [...$receipt['result'], 'replayed' => true];
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
|
||||
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'investment-zone-profile','entity_id'=>null,'actor_user_id'=>$actor->id,
|
||||
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
|
||||
$plan = $this->preview($actor);
|
||||
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Prévia alterada; consulte novamente.');
|
||||
abort_unless($plan['ready'], 422, implode(' ', $plan['reasons']));
|
||||
if (! $plan['installed']) {
|
||||
config(['investment-zone-details.authenticated_installation' => true]);
|
||||
try {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.InvestmentZoneOperationalDetails::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na instalação nominal.');
|
||||
} finally {
|
||||
config(['investment-zone-details.authenticated_installation' => false]);
|
||||
}
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'], 500, 'Esquema nominal inconsistente.');
|
||||
$result = ['migration' => $plan['migration'], 'code_hash' => $plan['code_hash'], 'target' => $plan['target'], 'changed' => ! $plan['installed'], 'business_records_changed' => 0, 'replayed' => false, 'receipt' => $data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'investment-zone-profile', 'entity_id' => null, 'actor_user_id' => $actor->id,
|
||||
'correlation_id' => $data['idempotency_key'], 'action' => 'schema', 'data_classification' => 'restricted', 'after_data' => json_encode(['request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -13,131 +13,186 @@ use Illuminate\Validation\ValidationException;
|
||||
class InvestmentZoneOperationalProfile
|
||||
{
|
||||
public const MIGRATION = '2026_10_16_130000_add_investment_zone_editorial_draft';
|
||||
public const FIELDS = ['code','category','name','name_en','description','description_en','province','district','operator_id','legal_source_id',
|
||||
'physical_category','legal_regime','operational_status','development_status','availability_status','area_components','source_evidence',
|
||||
'area_value','area_unit','aliases','activities','resources','data_as_of','sources_consulted_at','parent_zone_id','historical_territory'];
|
||||
public const DETAIL_PUBLIC = ['id','name','status','source_reference','source_date','kind','scope','capacity_type','capacity_value','capacity_unit','focus','economic_activity_id'];
|
||||
|
||||
public function installed(): bool { return Schema::hasColumn('investment_zones', 'editorial_draft'); }
|
||||
public const FIELDS = ['code', 'category', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'operator_id', 'legal_source_id',
|
||||
'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_components', 'source_evidence',
|
||||
'area_value', 'area_unit', 'aliases', 'activities', 'resources', 'data_as_of', 'sources_consulted_at', 'parent_zone_id', 'historical_territory'];
|
||||
|
||||
public const DETAIL_PUBLIC = ['id', 'name', 'status', 'source_reference', 'source_date', 'kind', 'scope', 'capacity_type', 'capacity_value', 'capacity_unit', 'focus', 'economic_activity_id'];
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasColumn('investment_zones', 'editorial_draft');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function draft(InvestmentZone $zone): ?array
|
||||
{
|
||||
$raw = $zone->getRawOriginal('editorial_draft');
|
||||
if (! $raw) { return null; }
|
||||
try { $data = json_decode(Crypt::decryptString($raw), true, 512, JSON_THROW_ON_ERROR); }
|
||||
catch (\Throwable $e) { throw ValidationException::withMessages(['editorial_draft'=>'Não foi possível recuperar a preparação privada. Os dados foram preservados; contacte o suporte.']); }
|
||||
if (! $raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$data = json_decode(Crypt::decryptString($raw), true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\Throwable $e) {
|
||||
throw ValidationException::withMessages(['editorial_draft' => 'Não foi possível recuperar a preparação privada. Os dados foram preservados; contacte o suporte.']);
|
||||
}
|
||||
abort_unless(($data['schema_version'] ?? null) === 1 && is_array($data['fields'] ?? null), 409, 'Formato de preparação incompatível; os dados foram preservados.');
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function workingVersion(InvestmentZone $zone): int { return (int) ($this->draft($zone)['working_version'] ?? $zone->version_no); }
|
||||
public function workingVersion(InvestmentZone $zone): int
|
||||
{
|
||||
return (int) ($this->draft($zone)['working_version'] ?? $zone->version_no);
|
||||
}
|
||||
|
||||
public function nextVersion(InvestmentZone $zone): int
|
||||
{
|
||||
return max((int) $zone->version_no, (int) DB::table('investment_zone_revisions')->where('zone_id',$zone->id)->max('version_no')) + 1;
|
||||
return max((int) $zone->version_no, (int) DB::table('investment_zone_revisions')->where('zone_id', $zone->id)->max('version_no')) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function management(InvestmentZone $zone): array
|
||||
{
|
||||
$draft = $this->draft($zone);
|
||||
return [...$zone->toArray(), ...($draft['fields'] ?? []), 'version_no'=>$draft['working_version'] ?? $zone->version_no,
|
||||
'public_version_no'=>$zone->version_no, 'base_public_version'=>$draft['base_public_version'] ?? $zone->version_no,
|
||||
'has_private_draft'=>$draft !== null, 'profile_available'=>$this->installed(),
|
||||
'operational_details'=>($draft['fields']['operational_details'] ?? app(InvestmentZoneOperationalDetails::class)->recover($zone)),
|
||||
'details_available'=>app(InvestmentZoneOperationalDetails::class)->installed()];
|
||||
|
||||
return [...$zone->toArray(), ...($draft['fields'] ?? []), 'version_no' => $draft['working_version'] ?? $zone->version_no,
|
||||
'public_version_no' => $zone->version_no, 'base_public_version' => $draft['base_public_version'] ?? $zone->version_no,
|
||||
'has_private_draft' => $draft !== null, 'profile_available' => $this->installed(),
|
||||
'operational_details' => ($draft['fields']['operational_details'] ?? app(InvestmentZoneOperationalDetails::class)->recover($zone)),
|
||||
'details_available' => app(InvestmentZoneOperationalDetails::class)->installed()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $record
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicDetails(array $record): array
|
||||
{
|
||||
unset($record['editorial_draft'], $record['operational_details']);
|
||||
foreach (['activities','resources'] as $key) {
|
||||
if (isset($record[$key])) { $record[$key] = array_map(fn ($item)=>array_intersect_key($item,array_flip(self::DETAIL_PUBLIC)), $record[$key]); }
|
||||
foreach (['activities', 'resources'] as $key) {
|
||||
if (isset($record[$key])) {
|
||||
$record[$key] = array_map(fn ($item) => array_intersect_key($item, array_flip(self::DETAIL_PUBLIC)), $record[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
private function mergeDetails(string $zoneId,array $before, array $after): array
|
||||
/**
|
||||
* @param array<array-key, mixed> $after
|
||||
* @param array<array-key, mixed> $before
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function mergeDetails(string $zoneId, array $before, array $after): array
|
||||
{
|
||||
$result=[];
|
||||
$result = [];
|
||||
foreach ($after as $item) {
|
||||
$old = collect($before)->first(fn($b)=>isset($item['id']) ? ($b['id'] ?? null)===$item['id'] : ($b['name'] ?? null)===($item['name'] ?? null));
|
||||
$item=[...($old ?? []), ...$item];
|
||||
$old = collect($before)->first(fn ($b) => isset($item['id']) ? ($b['id'] ?? null) === $item['id'] : ($b['name'] ?? null) === ($item['name'] ?? null));
|
||||
$item = [...($old ?? []), ...$item];
|
||||
$item['id'] ??= (string) Str::uuid();
|
||||
if (isset($item['capacity_value']) && empty($item['capacity_unit'])) { throw ValidationException::withMessages(['resources'=>'Indique a unidade da capacidade declarada; pode deixar o valor desconhecido.']); }
|
||||
if (!empty($item['economic_activity_id'])) {
|
||||
abort_unless(trim((string)($item['source_reference'] ?? '')) !== '' && DB::table('economic_activities')->where('id',$item['economic_activity_id'])->where('data_classification','public')->whereNull('deleted_at')->exists(),422,'A correspondência CAE exige referência publicada e fundamento explícito.');
|
||||
if (isset($item['capacity_value']) && empty($item['capacity_unit'])) {
|
||||
throw ValidationException::withMessages(['resources' => 'Indique a unidade da capacidade declarada; pode deixar o valor desconhecido.']);
|
||||
}
|
||||
if (! empty($item['economic_activity_id'])) {
|
||||
abort_unless(trim((string) ($item['source_reference'] ?? '')) !== '' && DB::table('economic_activities')->where('id', $item['economic_activity_id'])->where('data_classification', 'public')->whereNull('deleted_at')->exists(), 422, 'A correspondência CAE exige referência publicada e fundamento explícito.');
|
||||
}
|
||||
foreach ($item['support_document_ids'] ?? [] as $document) {
|
||||
abort_unless(DB::table('investment_zone_attachments')->where('zone_id',$zoneId)->where('document_id',$document)->exists(),422,'Selecione suporte privado já associado a esta ficha.');
|
||||
$d=DB::table('documents')->where('id',$document)->whereNull('deleted_at')->first();
|
||||
abort_unless($d && $d->status==='active' && $d->malware_scan_status==='clean' && trim($d->sha256)===$d->malware_scanned_sha256,422,'Documento de suporte ainda não consultável.');
|
||||
abort_unless(DB::table('investment_zone_attachments')->where('zone_id', $zoneId)->where('document_id', $document)->exists(), 422, 'Selecione suporte privado já associado a esta ficha.');
|
||||
$d = DB::table('documents')->where('id', $document)->whereNull('deleted_at')->first();
|
||||
abort_unless($d && $d->status === 'active' && $d->malware_scan_status === 'clean' && trim($d->sha256) === $d->malware_scanned_sha256, 422, 'Documento de suporte ainda não consultável.');
|
||||
}
|
||||
$result[]=$item;
|
||||
$result[] = $item;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** Called with zone row locked by InvestmentZones. Only this encrypted column is written. */
|
||||
public function prepare(InvestmentZone $zone,array $data,int $actor): InvestmentZone
|
||||
/** Called with zone row locked by InvestmentZones. Only this encrypted column is written.
|
||||
* @param array<array-key, mixed> $data
|
||||
*/
|
||||
public function prepare(InvestmentZone $zone, array $data, int $actor): InvestmentZone
|
||||
{
|
||||
abort_unless($this->installed(),503,'A preparação privada requer a instalação nominal da ficha de parques. A publicação anterior foi preservada.');
|
||||
abort_unless((int)$data['version_no']===$this->workingVersion($zone),409,'A preparação mudou; recupere a versão atual antes de guardar.');
|
||||
$previous=$this->draft($zone);
|
||||
$base=$previous['fields'] ?? array_intersect_key($zone->toArray(),array_flip(self::FIELDS));
|
||||
$fields=[...$base,...array_intersect_key($data,array_flip(self::FIELDS))];
|
||||
$details=app(InvestmentZoneOperationalDetails::class);
|
||||
if (array_key_exists('operational_details',$data)) {
|
||||
$fields['operational_details']=$details->merge($zone,$base['operational_details'] ?? $details->recover($zone),$data['operational_details'],$fields['operator_id'] ?? null);
|
||||
} elseif ($details->stored($zone) && !array_key_exists('operational_details',$fields)) {
|
||||
$fields['operational_details']=$details->recover($zone);
|
||||
abort_unless($this->installed(), 503, 'A preparação privada requer a instalação nominal da ficha de parques. A publicação anterior foi preservada.');
|
||||
abort_unless((int) $data['version_no'] === $this->workingVersion($zone), 409, 'A preparação mudou; recupere a versão atual antes de guardar.');
|
||||
$previous = $this->draft($zone);
|
||||
$base = $previous['fields'] ?? array_intersect_key($zone->toArray(), array_flip(self::FIELDS));
|
||||
$fields = [...$base, ...array_intersect_key($data, array_flip(self::FIELDS))];
|
||||
$details = app(InvestmentZoneOperationalDetails::class);
|
||||
if (array_key_exists('operational_details', $data)) {
|
||||
$fields['operational_details'] = $details->merge($zone, $base['operational_details'] ?? $details->recover($zone), $data['operational_details'], $fields['operator_id'] ?? null);
|
||||
} elseif ($details->stored($zone) && ! array_key_exists('operational_details', $fields)) {
|
||||
$fields['operational_details'] = $details->recover($zone);
|
||||
}
|
||||
$details=app(InvestmentZoneOperationalDetails::class);
|
||||
if (array_key_exists('operational_details',$data)) {
|
||||
$fields['operational_details']=$details->merge($zone,$base['operational_details'] ?? $details->recover($zone),$data['operational_details'],$fields['operator_id'] ?? null);
|
||||
} elseif ($details->stored($zone) && !array_key_exists('operational_details',$fields)) {
|
||||
$fields['operational_details']=$details->recover($zone);
|
||||
$details = app(InvestmentZoneOperationalDetails::class);
|
||||
if (array_key_exists('operational_details', $data)) {
|
||||
$fields['operational_details'] = $details->merge($zone, $base['operational_details'] ?? $details->recover($zone), $data['operational_details'], $fields['operator_id'] ?? null);
|
||||
} elseif ($details->stored($zone) && ! array_key_exists('operational_details', $fields)) {
|
||||
$fields['operational_details'] = $details->recover($zone);
|
||||
}
|
||||
foreach (['activities','resources'] as $key) { if (array_key_exists($key,$data)) { $fields[$key]=$this->mergeDetails($zone->id,$base[$key] ?? [],$data[$key]); } }
|
||||
$draft=['schema_version'=>1,'base_public_version'=>$previous['base_public_version'] ?? (int)$zone->version_no,
|
||||
'working_version'=>$this->nextVersion($zone),'fields'=>$fields,'actor_id'=>$actor,'prepared_at'=>now()->toIso8601String()];
|
||||
DB::table('investment_zones')->where('id',$zone->id)->update(['editorial_draft'=>Crypt::encryptString(json_encode($draft,JSON_THROW_ON_ERROR))]);
|
||||
$this->snapshot($zone,$draft['working_version'],$actor,'profile_prepared',['public'=>[...$zone->toArray(),'operational_details'=>$details->stored($zone)],'draft'=>$draft]);
|
||||
foreach (['activities', 'resources'] as $key) {
|
||||
if (array_key_exists($key, $data)) {
|
||||
$fields[$key] = $this->mergeDetails($zone->id, $base[$key] ?? [], $data[$key]);
|
||||
}
|
||||
}
|
||||
$draft = ['schema_version' => 1, 'base_public_version' => $previous['base_public_version'] ?? (int) $zone->version_no,
|
||||
'working_version' => $this->nextVersion($zone), 'fields' => $fields, 'actor_id' => $actor, 'prepared_at' => now()->toIso8601String()];
|
||||
DB::table('investment_zones')->where('id', $zone->id)->update(['editorial_draft' => Crypt::encryptString(json_encode($draft, JSON_THROW_ON_ERROR))]);
|
||||
$this->snapshot($zone, $draft['working_version'], $actor, 'profile_prepared', ['public' => [...$zone->toArray(), 'operational_details' => $details->stored($zone)], 'draft' => $draft]);
|
||||
|
||||
return $zone->fresh();
|
||||
}
|
||||
|
||||
/** Apply only inside the publication transaction; a failed validation rolls everything back. */
|
||||
public function promote(InvestmentZone $zone,int $version): void
|
||||
public function promote(InvestmentZone $zone, int $version): void
|
||||
{
|
||||
$draft=$this->draft($zone);
|
||||
abort_unless($version===$this->workingVersion($zone),409,'A preparação mudou; recupere a versão atual antes de publicar.');
|
||||
if (!$draft) { return; }
|
||||
abort_unless((int)$draft['base_public_version']===(int)$zone->version_no,409,'A publicação base mudou. Reconcilie a preparação antes de publicar; ambos os estados foram preservados.');
|
||||
$zone->fill(array_intersect_key($draft['fields'],array_flip(self::FIELDS)));
|
||||
if (array_key_exists('operational_details',$draft['fields'])) {
|
||||
$zone->setAttribute('operational_details',app(InvestmentZoneOperationalDetails::class)->pack($draft['fields']['operational_details']));
|
||||
$draft = $this->draft($zone);
|
||||
abort_unless($version === $this->workingVersion($zone), 409, 'A preparação mudou; recupere a versão atual antes de publicar.');
|
||||
if (! $draft) {
|
||||
return;
|
||||
}
|
||||
abort_unless((int) $draft['base_public_version'] === (int) $zone->version_no, 409, 'A publicação base mudou. Reconcilie a preparação antes de publicar; ambos os estados foram preservados.');
|
||||
$zone->fill(array_intersect_key($draft['fields'], array_flip(self::FIELDS)));
|
||||
if (array_key_exists('operational_details', $draft['fields'])) {
|
||||
$zone->setAttribute('operational_details', app(InvestmentZoneOperationalDetails::class)->pack($draft['fields']['operational_details']));
|
||||
}
|
||||
// Existing resource support remains in the encrypted snapshot; L1 private fields are durable.
|
||||
foreach(['activities','resources'] as $key) { $zone->setAttribute($key,$this->publicDetails([$key=>$zone->$key ?? []])[$key]); }
|
||||
$zone->setAttribute('editorial_draft',null);
|
||||
foreach (['activities', 'resources'] as $key) {
|
||||
$zone->setAttribute($key, $this->publicDetails([$key => $zone->$key ?? []])[$key]);
|
||||
}
|
||||
$zone->setAttribute('editorial_draft', null);
|
||||
}
|
||||
|
||||
public function reconcile(InvestmentZone $zone,int $working,int $public,int $actor): InvestmentZone
|
||||
public function reconcile(InvestmentZone $zone, int $working, int $public, int $actor): InvestmentZone
|
||||
{
|
||||
$draft=$this->draft($zone);
|
||||
abort_unless($draft && $working===(int)$draft['working_version'] && $public===(int)$zone->version_no,409,'Versões alteradas; recupere a ficha pública e a preparação antes de reconciliar.');
|
||||
abort_if((int)$draft['base_public_version']===$public,422,'A preparação já corresponde à versão pública atual.');
|
||||
$draft['base_public_version']=$public;$draft['working_version']=$this->nextVersion($zone);$draft['actor_id']=$actor;$draft['prepared_at']=now()->toIso8601String();
|
||||
DB::table('investment_zones')->where('id',$zone->id)->update(['editorial_draft'=>Crypt::encryptString(json_encode($draft,JSON_THROW_ON_ERROR))]);
|
||||
$this->snapshot($zone,$draft['working_version'],$actor,'profile_reconciled',['public'=>[...$zone->toArray(),'operational_details'=>app(InvestmentZoneOperationalDetails::class)->stored($zone)],'draft'=>$draft]);
|
||||
$draft = $this->draft($zone);
|
||||
abort_unless($draft && $working === (int) $draft['working_version'] && $public === (int) $zone->version_no, 409, 'Versões alteradas; recupere a ficha pública e a preparação antes de reconciliar.');
|
||||
abort_if((int) $draft['base_public_version'] === $public, 422, 'A preparação já corresponde à versão pública atual.');
|
||||
$draft['base_public_version'] = $public;
|
||||
$draft['working_version'] = $this->nextVersion($zone);
|
||||
$draft['actor_id'] = $actor;
|
||||
$draft['prepared_at'] = now()->toIso8601String();
|
||||
DB::table('investment_zones')->where('id', $zone->id)->update(['editorial_draft' => Crypt::encryptString(json_encode($draft, JSON_THROW_ON_ERROR))]);
|
||||
$this->snapshot($zone, $draft['working_version'], $actor, 'profile_reconciled', ['public' => [...$zone->toArray(), 'operational_details' => app(InvestmentZoneOperationalDetails::class)->stored($zone)], 'draft' => $draft]);
|
||||
|
||||
return $zone->fresh();
|
||||
}
|
||||
|
||||
public function snapshot(InvestmentZone $zone,int $version,int $actor,string $action,array $data): void
|
||||
/**
|
||||
* @param array<array-key, mixed> $data
|
||||
*/
|
||||
public function snapshot(InvestmentZone $zone, int $version, int $actor, string $action, array $data): void
|
||||
{
|
||||
$json=json_encode($data,JSON_THROW_ON_ERROR);$hash=hash('sha256',$json);
|
||||
DB::table('investment_zone_revisions')->insert(['id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'version_no'=>$version,
|
||||
'actor_id'=>$actor,'action'=>$action,'snapshot'=>Crypt::encryptString($json),'sha256'=>$hash]);
|
||||
DB::table('audit_events')->insert(['source_system'=>'investment-zones','entity_type'=>'investment_zones','entity_id'=>$zone->id,
|
||||
'actor_user_id'=>$actor,'action'=>$action,'after_data'=>json_encode(['version_no'=>$version,'sha256'=>$hash],JSON_THROW_ON_ERROR)]);
|
||||
$json = json_encode($data, JSON_THROW_ON_ERROR);
|
||||
$hash = hash('sha256', $json);
|
||||
DB::table('investment_zone_revisions')->insert(['id' => (string) Str::uuid(), 'zone_id' => $zone->id, 'version_no' => $version,
|
||||
'actor_id' => $actor, 'action' => $action, 'snapshot' => Crypt::encryptString($json), 'sha256' => $hash]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'investment-zones', 'entity_type' => 'investment_zones', 'entity_id' => $zone->id,
|
||||
'actor_user_id' => $actor, 'action' => $action, 'after_data' => json_encode(['version_no' => $version, 'sha256' => $hash], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,41 +8,55 @@ use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class InvestmentZonePathContext
|
||||
{
|
||||
public const NOTICE='Referência para preparação; não constitui reserva de lote, confirmação de disponibilidade ou autorização de instalação.';
|
||||
public const NOTICE = 'Referência para preparação; não constitui reserva de lote, confirmação de disponibilidade ou autorização de instalação.';
|
||||
|
||||
public function context(string $id,int $version): array
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function context(string $id, int $version): array
|
||||
{
|
||||
$zone=app(InvestmentZones::class)->visible()->where('category','industrial_park')->findOrFail($id);
|
||||
abort_unless((int)$zone->version_no===$version,409,'A ficha pública mudou. Consulte a versão atual e confirme novamente; a seleção anterior não foi substituída.');
|
||||
return ['zone_id'=>$zone->id,'consulted_public_version'=>(int)$zone->version_no,'title'=>$zone->name,'href'=>'/zonas/'.$zone->id,
|
||||
'province'=>$zone->province,'district'=>$zone->district,'notice'=>self::NOTICE];
|
||||
$zone = app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->findOrFail($id);
|
||||
abort_unless((int) $zone->version_no === $version, 409, 'A ficha pública mudou. Consulte a versão atual e confirme novamente; a seleção anterior não foi substituída.');
|
||||
|
||||
return ['zone_id' => $zone->id, 'consulted_public_version' => (int) $zone->version_no, 'title' => $zone->name, 'href' => '/zonas/'.$zone->id,
|
||||
'province' => $zone->province, 'district' => $zone->district, 'notice' => self::NOTICE];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function input(array $input): array
|
||||
{
|
||||
return Validator::make($input,['zone_id'=>'required|uuid','consulted_public_version'=>'required|integer|min:1'])->validate();
|
||||
return Validator::make($input, ['zone_id' => 'required|uuid', 'consulted_public_version' => 'required|integer|min:1'])->validate();
|
||||
}
|
||||
|
||||
public function attach(User $actor,string $id,array $input): void
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function attach(User $actor, string $id, array $input): void
|
||||
{
|
||||
abort_unless(app(InvestorPath::class)->available(),404);
|
||||
$data=Validator::make($input,['zone_id'=>'required|uuid','consulted_public_version'=>'required|integer|min:1','version'=>'required|integer|min:1','confirm'=>'required|accepted'])->validate();
|
||||
DB::transaction(function()use($actor,$id,$data){
|
||||
$desk=app(VirtualDesk::class);$case=$desk->case($actor,$id,true,true);
|
||||
abort_if($case->closed_at,409,'O dossier está encerrado.');
|
||||
abort_unless(DB::table('investor_journeys')->where('id',$case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(),409,'Este dossier conserva outro roteiro.');
|
||||
$payload=$desk->decode($case->payload);
|
||||
foreach($payload['investor_path']['zone_contexts'] ?? [] as $existing){
|
||||
if($existing['zone_id']===$data['zone_id'] && (int)$existing['consulted_public_version']===(int)$data['consulted_public_version']){return;}
|
||||
abort_unless(app(InvestorPath::class)->available(), 404);
|
||||
$data = Validator::make($input, ['zone_id' => 'required|uuid', 'consulted_public_version' => 'required|integer|min:1', 'version' => 'required|integer|min:1', 'confirm' => 'required|accepted'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data) {
|
||||
$desk = app(VirtualDesk::class);
|
||||
$case = $desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409, 'O dossier está encerrado.');
|
||||
abort_unless(DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(), 409, 'Este dossier conserva outro roteiro.');
|
||||
$payload = $desk->decode($case->payload);
|
||||
foreach ($payload['investor_path']['zone_contexts'] ?? [] as $existing) {
|
||||
if ($existing['zone_id'] === $data['zone_id'] && (int) $existing['consulted_public_version'] === (int) $data['consulted_public_version']) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
abort_unless((int)$case->version===(int)$data['version'],409,'O dossier mudou; recupere a versão atual.');
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409, 'O dossier mudou; recupere a versão atual.');
|
||||
// Lock the public record while checking the consulted version and recording its reference.
|
||||
DB::table('investment_zones')->where('id',$data['zone_id'])->lockForUpdate()->firstOrFail();
|
||||
$context=$this->context($data['zone_id'],(int)$data['consulted_public_version']);
|
||||
abort_unless(count($payload['investor_path']['zone_contexts'] ?? [])<100,422,'Limite de referências deste dossier atingido.');
|
||||
$payload['investor_path']['zone_contexts'][]=[...$context,'selected_at'=>now()->toIso8601String()];
|
||||
DB::table('desk_cases')->where('id',$id)->update(['payload'=>$desk->encode($payload),'version'=>$case->version+1,'updated_at'=>now()]);
|
||||
$desk->event($desk->case($actor,$id),$actor,'park_reference_selected',['zone_id'=>$context['zone_id'],'consulted_public_version'=>$context['consulted_public_version'],'scope'=>'preparation_reference_only']);
|
||||
DB::table('investment_zones')->where('id', $data['zone_id'])->lockForUpdate()->firstOrFail();
|
||||
$context = $this->context($data['zone_id'], (int) $data['consulted_public_version']);
|
||||
abort_unless(count($payload['investor_path']['zone_contexts'] ?? []) < 100, 422, 'Limite de referências deste dossier atingido.');
|
||||
$payload['investor_path']['zone_contexts'][] = [...$context, 'selected_at' => now()->toIso8601String()];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($desk->case($actor, $id), $actor, 'park_reference_selected', ['zone_id' => $context['zone_id'], 'consulted_public_version' => $context['consulted_public_version'], 'scope' => 'preparation_reference_only']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
@@ -12,79 +14,142 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
|
||||
class InvestmentZoneProfileInstallation
|
||||
{
|
||||
public const SOURCE='investment-zone-profile-installation';
|
||||
public const SOURCE = 'investment-zone-profile-installation';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function files(): array
|
||||
{
|
||||
return ['app/Models/InvestmentZone.php','app/Services/InvestmentZones.php','app/Services/InvestmentZoneOperationalProfile.php',
|
||||
'app/Services/InvestmentZonePathContext.php','app/Services/InvestmentZoneProfileInstallation.php','app/Http/Controllers/InvestmentZoneController.php',
|
||||
'app/Http/Controllers/InvestorPathController.php','app/Services/InvestorPath.php','routes/investment-zones.php','routes/investor-path.php',
|
||||
'resources/js/pages/investment/zone.tsx','resources/js/pages/investment/zones.tsx','resources/js/pages/investor-path/index.tsx',
|
||||
'resources/js/pages/investor-path/show.tsx','resources/js/components/investment-zone-installation.tsx',
|
||||
return ['app/Models/InvestmentZone.php', 'app/Services/InvestmentZones.php', 'app/Services/InvestmentZoneOperationalProfile.php',
|
||||
'app/Services/InvestmentZonePathContext.php', 'app/Services/InvestmentZoneProfileInstallation.php', 'app/Http/Controllers/InvestmentZoneController.php',
|
||||
'app/Http/Controllers/InvestorPathController.php', 'app/Services/InvestorPath.php', 'routes/investment-zones.php', 'routes/investor-path.php',
|
||||
'resources/js/pages/investment/zone.tsx', 'resources/js/pages/investment/zones.tsx', 'resources/js/pages/investor-path/index.tsx',
|
||||
'resources/js/pages/investor-path/show.tsx', 'resources/js/components/investment-zone-installation.tsx',
|
||||
'database/migrations/'.InvestmentZoneOperationalProfile::MIGRATION.'.php'];
|
||||
}
|
||||
|
||||
public function fingerprint(): string
|
||||
{
|
||||
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
|
||||
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
|
||||
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
|
||||
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
|
||||
$files = array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files());
|
||||
foreach (File::allFiles(public_path('build')) as $file) {
|
||||
$files[] = ['public/build/'.$file->getRelativePathname(), hash_file('sha256', $file->getPathname())];
|
||||
}
|
||||
usort($files, fn ($a, $b) => strcmp($a[0], $b[0]));
|
||||
|
||||
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
private function authorize(User $actor,bool $write=false): void
|
||||
|
||||
private function authorize(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor),403,'Gestão autorizada necessária.');
|
||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Gestão autorizada necessária.');
|
||||
if ($write) {
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
}
|
||||
}
|
||||
private function evidence(array $target,string $code): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function evidence(array $target, string $code): array
|
||||
{
|
||||
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
|
||||
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
|
||||
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
|
||||
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
|
||||
$path=storage_path('app/private/investmoz-v2/park-profile/readiness.json');
|
||||
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
|
||||
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
|
||||
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
|
||||
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
|
||||
$qa = app()->environment('testing') && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test')
|
||||
&& config('database.connections.pgsql.host') === '127.0.0.1' && ! config('database.connections.pgsql.url');
|
||||
if ($qa) {
|
||||
return ['ready' => true, 'mode' => 'isolated_QA'];
|
||||
}
|
||||
if (app()->environment('testing')) {
|
||||
return ['ready' => false, 'mode' => 'invalid_QA'];
|
||||
}
|
||||
$path = storage_path('app/private/investmoz-v2/park-profile/readiness.json');
|
||||
$p = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||
$date = strtotime($p['verified_at'] ?? '');
|
||||
$auth = $p['active_authorization'] ?? [];
|
||||
$ready = $target['database'] === 'investemoz' && (int) $target['port'] === 5432 && ! config('database.connections.pgsql.url')
|
||||
&& in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||
&& ($p['target']['database'] ?? '') === $target['database'] && (int) ($p['target']['port'] ?? 0) === (int) $target['port']
|
||||
&& ($p['code_hash'] ?? '') === $code && $date !== false && $date <= time() && $date >= time() - 86400
|
||||
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
|
||||
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===InvestmentZoneOperationalProfile::MIGRATION;
|
||||
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
|
||||
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
|
||||
&& ($p['restored_boot_verified'] ?? false) && (int) ($p['restore_target']['port'] ?? 0) === 55441 && str_ends_with($p['restore_target']['database'] ?? '', '_test')
|
||||
&& ($auth['decision_record'] ?? '') !== '' && ($auth['code_hash'] ?? '') === $code && ($auth['migration'] ?? '') === InvestmentZoneOperationalProfile::MIGRATION;
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
$file = $p[$kind.'_path'] ?? '';
|
||||
$ready = $ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '', CheckedFile::sha256($file));
|
||||
}
|
||||
|
||||
return ['ready' => $ready, 'mode' => 'active_requires_own_authorization_and_fresh_proof', 'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
|
||||
$ledgerCount=DB::table('migrations')->where('migration',InvestmentZoneOperationalProfile::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('investment_zones','editorial_draft');
|
||||
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='editorial_draft'");
|
||||
$correct=$shape && $shape->data_type==='text' && $shape->is_nullable==='YES';
|
||||
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
|
||||
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
|
||||
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
|
||||
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
|
||||
$state=['target'=>$target,'migration'=>InvestmentZoneOperationalProfile::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
|
||||
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
|
||||
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
|
||||
$this->authorize($actor);
|
||||
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$code = $this->fingerprint();
|
||||
$ledgerCount = DB::table('migrations')->where('migration', InvestmentZoneOperationalProfile::MIGRATION)->count();
|
||||
$ledger = $ledgerCount === 1;
|
||||
$column = Schema::hasColumn('investment_zones', 'editorial_draft');
|
||||
$shape = DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='investment_zones' AND column_name='editorial_draft'");
|
||||
$correct = $shape && $shape->data_type === 'text' && $shape->is_nullable === 'YES';
|
||||
$consistent = ($ledger && $column && $correct) || ($ledgerCount === 0 && ! $column);
|
||||
$reasons = [];
|
||||
if (! $consistent) {
|
||||
$reasons[] = 'Ledger e coluna divergentes; reconciliar sem instalação parcial.';
|
||||
}
|
||||
try {
|
||||
$this->authorize($actor, true);
|
||||
} catch (HttpException $e) {
|
||||
$reasons[] = $e->getMessage();
|
||||
}
|
||||
$evidence = $this->evidence($target, $code);
|
||||
if (! $evidence['ready']) {
|
||||
$reasons[] = 'Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';
|
||||
}
|
||||
$state = ['target' => $target, 'migration' => InvestmentZoneOperationalProfile::MIGRATION, 'code_hash' => $code, 'installed' => $ledger && $column,
|
||||
'consistent' => $consistent, 'ready' => $reasons === [], 'reasons' => $reasons, 'evidence' => $evidence];
|
||||
|
||||
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||
}
|
||||
public function apply(User $actor,array $input): array
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor,true);
|
||||
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
|
||||
return DB::transaction(function()use($actor,$data){
|
||||
DB::select('SELECT pg_advisory_xact_lock(161026,130000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
|
||||
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
|
||||
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
|
||||
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
|
||||
if(!$plan['installed']){
|
||||
config(['investment-zone-profile.authenticated_installation'=>true]);
|
||||
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.InvestmentZoneOperationalProfile::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
|
||||
finally{config(['investment-zone-profile.authenticated_installation'=>false]);}
|
||||
$this->authorize($actor, true);
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', '_token']) !== [], 422, 'Ator, migration ou caminho arbitrário não permitido.');
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(161026,130000)');
|
||||
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$old = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $data['idempotency_key'])->first();
|
||||
if ($old) {
|
||||
$receipt = json_decode($old->after_data, true);
|
||||
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave já utilizada com outro ator ou conteúdo.');
|
||||
|
||||
return [...$receipt['result'], 'replayed' => true];
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
|
||||
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'investment-zone-profile','entity_id'=>null,'actor_user_id'=>$actor->id,
|
||||
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
|
||||
$plan = $this->preview($actor);
|
||||
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Prévia alterada; consulte novamente.');
|
||||
abort_unless($plan['ready'], 422, implode(' ', $plan['reasons']));
|
||||
if (! $plan['installed']) {
|
||||
config(['investment-zone-profile.authenticated_installation' => true]);
|
||||
try {
|
||||
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.InvestmentZoneOperationalProfile::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na instalação nominal.');
|
||||
} finally {
|
||||
config(['investment-zone-profile.authenticated_installation' => false]);
|
||||
}
|
||||
}
|
||||
abort_unless($this->preview($actor)['installed'], 500, 'Esquema nominal inconsistente.');
|
||||
$result = ['migration' => $plan['migration'], 'code_hash' => $plan['code_hash'], 'target' => $plan['target'], 'changed' => ! $plan['installed'], 'business_records_changed' => 0, 'replayed' => false, 'receipt' => $data['idempotency_key']];
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'investment-zone-profile', 'entity_id' => null, 'actor_user_id' => $actor->id,
|
||||
'correlation_id' => $data['idempotency_key'], 'action' => 'schema', 'data_classification' => 'restricted', 'after_data' => json_encode(['request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -97,15 +97,16 @@ class InvestmentZones
|
||||
return DB::transaction(function () use ($id, $data, $actor) {
|
||||
$zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone;
|
||||
if ($id && $zone->category === 'industrial_park') {
|
||||
$prepared=app(InvestmentZoneOperationalProfile::class)->prepare($zone,$data,$actor);
|
||||
$this->storePendingLocations($zone,$data['locations'] ?? [],$actor);
|
||||
$prepared = app(InvestmentZoneOperationalProfile::class)->prepare($zone, $data, $actor);
|
||||
$this->storePendingLocations($zone, $data['locations'] ?? [], $actor);
|
||||
|
||||
return $prepared;
|
||||
}
|
||||
abort_if($id && (int) $zone->version_no !== (int) $data['version_no'], 409, 'Versão alterada. Recarregue antes de guardar.');
|
||||
$version = $id ? (int) $zone->version_no + 1 : 1;
|
||||
$locations = $data['locations'] ?? [];
|
||||
unset($data['locations'], $data['version_no']);
|
||||
abort_if(array_key_exists('operational_details',$data),422,'Prepare L1 numa ficha de parque existente; não cria outro cadastro.');
|
||||
abort_if(array_key_exists('operational_details', $data), 422, 'Prepare L1 numa ficha de parque existente; não cria outro cadastro.');
|
||||
$zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null,
|
||||
'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save();
|
||||
foreach ($locations as $location) {
|
||||
@@ -127,8 +128,11 @@ class InvestmentZones
|
||||
return DB::transaction(function () use ($id, $version, $actor) {
|
||||
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
$profile = app(InvestmentZoneOperationalProfile::class);
|
||||
if ($zone->category === 'industrial_park') { $profile->promote($zone,$version); }
|
||||
else { abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.'); }
|
||||
if ($zone->category === 'industrial_park') {
|
||||
$profile->promote($zone, $version);
|
||||
} else {
|
||||
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.');
|
||||
}
|
||||
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
|
||||
$evidence = $zone->source_evidence ?? [];
|
||||
$officialEvidence = collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional'], true)
|
||||
@@ -166,8 +170,8 @@ class InvestmentZones
|
||||
{
|
||||
return DB::transaction(function () use ($id, $version, $actor) {
|
||||
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
$profile=app(InvestmentZoneOperationalProfile::class);
|
||||
abort_if(($zone->category === 'industrial_park' ? $profile->workingVersion($zone) : (int)$zone->version_no) !== $version, 409, 'Versão alterada.');
|
||||
$profile = app(InvestmentZoneOperationalProfile::class);
|
||||
abort_if(($zone->category === 'industrial_park' ? $profile->workingVersion($zone) : (int) $zone->version_no) !== $version, 409, 'Versão alterada.');
|
||||
$zone->fill(['version_no' => $zone->category === 'industrial_park' ? $profile->nextVersion($zone) : $version + 1, 'publication_status' => 'suspended'])->save();
|
||||
$this->snapshot($zone, $actor, 'suspended');
|
||||
|
||||
@@ -201,7 +205,7 @@ class InvestmentZones
|
||||
|
||||
private function snapshot(InvestmentZone $zone, int $actor, string $action): void
|
||||
{
|
||||
$json = json_encode([...$zone->toArray(),'operational_details'=>app(InvestmentZoneOperationalDetails::class)->stored($zone)],JSON_THROW_ON_ERROR);
|
||||
$json = json_encode([...$zone->toArray(), 'operational_details' => app(InvestmentZoneOperationalDetails::class)->stored($zone)], JSON_THROW_ON_ERROR);
|
||||
DB::table('investment_zone_revisions')->insert(['id' => (string) Str::uuid(), 'zone_id' => $zone->id,
|
||||
'version_no' => $zone->version_no, 'actor_id' => $actor, 'action' => $action,
|
||||
'snapshot' => Crypt::encryptString($json), 'sha256' => hash('sha256', $json)]);
|
||||
@@ -210,14 +214,16 @@ class InvestmentZones
|
||||
'after_data' => json_encode(['version_no' => $zone->version_no, 'sha256' => hash('sha256', $json)], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
/** Existing explicit territorial control: new associations remain pending, never promoted with the profile. */
|
||||
private function storePendingLocations(InvestmentZone $zone,array $locations,int $actor): void
|
||||
/** Existing explicit territorial control: new associations remain pending, never promoted with the profile.
|
||||
* @param array<array-key, mixed> $locations
|
||||
*/
|
||||
private function storePendingLocations(InvestmentZone $zone, array $locations, int $actor): void
|
||||
{
|
||||
foreach($locations as $location){
|
||||
foreach ($locations as $location) {
|
||||
DB::table('investment_zone_locations')->insertOrIgnore([
|
||||
'id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'geo_location_id'=>$location['geo_location_id'],
|
||||
'scope_type'=>$location['scope_type'] ?? 'administrative','source_reference'=>$location['source_reference'],
|
||||
'legal_source_id'=>$location['legal_source_id'] ?? null,'validation_status'=>'pending','editor_id'=>$actor,'version_no'=>1,'created_at'=>now(),'updated_at'=>now(),
|
||||
'id' => (string) Str::uuid(), 'zone_id' => $zone->id, 'geo_location_id' => $location['geo_location_id'],
|
||||
'scope_type' => $location['scope_type'] ?? 'administrative', 'source_reference' => $location['source_reference'],
|
||||
'legal_source_id' => $location['legal_source_id'] ?? null, 'validation_status' => 'pending', 'editor_id' => $actor, 'version_no' => 1, 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
@@ -27,63 +28,83 @@ final class InvestorContext
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function draft(User $actor, string $id): ?array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id, true);
|
||||
$draft = $this->desk->decode($case->payload)['investor_path']['context_drafts'][(string)$actor->id] ?? null;
|
||||
return $draft ? [...$draft, 'needs_review' => (int)$draft['version'] !== (int)$case->version] : null;
|
||||
$draft = $this->desk->decode($case->payload)['investor_path']['context_drafts'][(string) $actor->id] ?? null;
|
||||
|
||||
return $draft ? [...$draft, 'needs_review' => (int) $draft['version'] !== (int) $case->version] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function saveDraft(User $actor, string $id, array $input): array
|
||||
{
|
||||
$case=$this->desk->case($actor,$id,true);
|
||||
abort_if($case->closed_at,409);
|
||||
$sequence = (int)($input['draft_sequence'] ?? 0);
|
||||
$entrySources=Validator::make($input,['entry_sources'=>'sometimes|array|max:200','entry_sources.*'=>'string|max:100'])->validate()['entry_sources']??[];
|
||||
$case = $this->desk->case($actor, $id, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
$sequence = (int) ($input['draft_sequence'] ?? 0);
|
||||
$entrySources = Validator::make($input, ['entry_sources' => 'sometimes|array|max:200', 'entry_sources.*' => 'string|max:100'])->validate()['entry_sources'] ?? [];
|
||||
unset($input['draft_sequence'],$input['entry_sources']);
|
||||
abort_unless($sequence > 0, 422);
|
||||
$data = $this->input($input);
|
||||
if (isset($data['complements'])) app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
|
||||
foreach ($data['selection'] as $slot=>$key) {
|
||||
if (!$key) continue;
|
||||
$ref=$this->reference($key);
|
||||
abort_unless(in_array($ref['kind'],$slot==='opportunity'?['opportunity','business']:[$slot],true),422,'Referência incompatível com a escolha.');
|
||||
if (isset($data['complements'])) {
|
||||
app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
|
||||
}
|
||||
foreach ($data['selection'] as $slot => $key) {
|
||||
if (! $key) {
|
||||
continue;
|
||||
}
|
||||
$ref = $this->reference($key);
|
||||
if (! (in_array($ref['kind'], $slot === 'opportunity' ? ['opportunity', 'business'] : [$slot], true))) {
|
||||
abort(422, 'Referência incompatível com a escolha.');
|
||||
}
|
||||
}
|
||||
foreach ($data['opportunity_choices'] ?? [] as $choice) {
|
||||
$ref = $this->reference($choice['source']);
|
||||
abort_unless($ref['kind'] === 'opportunity', 422);
|
||||
$record = Opportunity::findOrFail($ref['id']);
|
||||
$record = Opportunity::whereKey($ref['id'])->firstOrFail();
|
||||
app(InvestmentOpportunityChoices::class)->portfolioOrigins($choice['portfolio_origins'] ?? [], (int) $record->id);
|
||||
$key = $choice['corridor_key'] ?? app(InvestmentCorridorContext::class)->key($record);
|
||||
if (!empty($choice['territory'])) {
|
||||
if (! empty($choice['territory'])) {
|
||||
$location = $this->reference($choice['territory']);
|
||||
abort_unless($location['kind'] === 'territory', 422);
|
||||
if ($key) abort_unless(app(InvestmentCorridorContext::class)->compatible($key, $location['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
}
|
||||
if (isset($data['opportunity_choices'])) app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $this->state($case)['opportunity_choices'] ?? [], true);
|
||||
if (!empty($data['selection']['park'])) {
|
||||
$first=$data['opportunity_choices'][0] ?? null;
|
||||
$source=$first['source'] ?? $data['selection']['opportunity'] ?? null;
|
||||
if ($source && str_starts_with($source,'opportunity:')) {
|
||||
$key=$first['corridor_key'] ?? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail(substr($source,12)));
|
||||
if ($key) {
|
||||
$territory=$first['territory'] ?? $data['selection']['territory'] ?? null;
|
||||
$ids=app(InvestmentCorridorContext::class)->provinces($key);
|
||||
$territory=$territory ? substr($territory,10) : (count($ids)===1?$ids[0]->id:null);
|
||||
$park=$this->reference($data['selection']['park']);
|
||||
abort_unless($park['kind']==='park' && in_array($park['id'],array_column(app(InvestmentCorridorContext::class)->parks($key,$territory),'id'),true),422,'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
abort_unless(app(InvestmentCorridorContext::class)->compatible($key, $location['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($data['opportunity_choices'])) {
|
||||
app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $this->state($case)['opportunity_choices'] ?? [], true);
|
||||
}
|
||||
if (! empty($data['selection']['park'])) {
|
||||
$first = $data['opportunity_choices'][0] ?? null;
|
||||
$source = $first['source'] ?? $data['selection']['opportunity'] ?? null;
|
||||
if ($source && str_starts_with($source, 'opportunity:')) {
|
||||
$key = $first['corridor_key'] ?? app(InvestmentCorridorContext::class)->key(Opportunity::whereKey(substr($source, 12))->firstOrFail());
|
||||
if ($key) {
|
||||
$territory = $first['territory'] ?? $data['selection']['territory'] ?? null;
|
||||
$ids = app(InvestmentCorridorContext::class)->provinces($key);
|
||||
$territory = $territory ? substr($territory, 10) : (count($ids) === 1 ? $ids[0]->id : null);
|
||||
$park = $this->reference($data['selection']['park']);
|
||||
abort_unless($park['kind'] === 'park' && in_array($park['id'], array_column(app(InvestmentCorridorContext::class)->parks($key, $territory), 'id'), true), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $sequence, $entrySources) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at || (int)$case->version !== (int)$data['version'], 409, 'O dossier mudou. Recupere os dados antes de continuar.');
|
||||
abort_if($case->closed_at || (int) $case->version !== (int) $data['version'], 409, 'O dossier mudou. Recupere os dados antes de continuar.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$previous = $payload['investor_path']['context_drafts'][(string)$actor->id] ?? [];
|
||||
$previous = $payload['investor_path']['context_drafts'][(string) $actor->id] ?? [];
|
||||
abort_if(($previous['draft_sequence'] ?? 0) > $sequence, 409, 'Existe um rascunho mais recente. Recupere o dossier antes de continuar.');
|
||||
$payload['investor_path']['context_drafts'][(string)$actor->id] = [...$data, 'draft_sequence' => $sequence, 'entry_sources'=>array_values(array_unique([...($previous['entry_sources']??[]),...$entrySources]))];
|
||||
$payload['investor_path']['context_drafts'][(string) $actor->id] = [...$data, 'draft_sequence' => $sequence, 'entry_sources' => array_values(array_unique([...($previous['entry_sources'] ?? []), ...$entrySources]))];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload)]);
|
||||
|
||||
return ['saved' => true];
|
||||
});
|
||||
}
|
||||
@@ -93,6 +114,9 @@ final class InvestorContext
|
||||
return Schema::hasTable('investor_navigation_preferences');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function state(\stdClass $case): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
@@ -112,7 +136,9 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($context['opportunity_choices']) && !array_key_exists('park', $context['opportunity_choices'][0])) $context['opportunity_choices'][0]['park'] = $context['selection']['park'] ?? null;
|
||||
if (! empty($context['opportunity_choices']) && ! array_key_exists('park', $context['opportunity_choices'][0])) {
|
||||
$context['opportunity_choices'][0]['park'] = $context['selection']['park'] ?? null;
|
||||
}
|
||||
$zone = $context['selection']['park'] ?? null;
|
||||
$context['fields']['investment_regime'] = $zone['fields']['investment_regime'] ?? 'general';
|
||||
$context['fields']['special_zone_id'] = $zone['id'] ?? '';
|
||||
@@ -120,13 +146,22 @@ final class InvestorContext
|
||||
return $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $selection
|
||||
*/
|
||||
public function dependencyHash(array $selection): string
|
||||
{
|
||||
unset($selection['portfolio'], $selection['selection']['portfolio']);
|
||||
if (isset($selection['opportunity_choices'])) $selection['opportunity_choices'] = array_map(fn($choice)=>Arr::except($choice,['portfolio_origins']),$selection['opportunity_choices']);
|
||||
if (isset($selection['opportunity_choices'])) {
|
||||
$selection['opportunity_choices'] = array_map(fn ($choice) => Arr::except($choice, ['portfolio_origins']), $selection['opportunity_choices']);
|
||||
}
|
||||
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($selection), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function reference(string $key): array
|
||||
{
|
||||
[$kind,$id] = array_pad(explode(':', $key, 2), 2, '');
|
||||
@@ -140,7 +175,7 @@ final class InvestorContext
|
||||
$zoneAnalysis = null;
|
||||
if ($kind === 'opportunity') {
|
||||
abort_unless(ctype_digit($id), 422, 'Identificador de oportunidade inválido.');
|
||||
$o = Opportunity::with('sector')->findOrFail((int) $id);
|
||||
$o = Opportunity::with('sector')->whereKey((int) $id)->firstOrFail();
|
||||
$published = Opportunity::published()->whereKey($o->id)->exists();
|
||||
if (! $published) {
|
||||
abort_unless(request()->user() && $o->status !== 'archived' && app(PortalProfileAccess::class)->canView(request()->user(), $o), 404, 'Ficha privada indisponível neste âmbito.');
|
||||
@@ -160,7 +195,9 @@ final class InvestorContext
|
||||
$fields['sector'] = $o->sector->name;
|
||||
}
|
||||
$proactive = $published ? app(ProactiveInvestment::class)->publicData($o) : ($draft['proactive'] ?? null);
|
||||
if ($proactive) $zoneAnalysis = ['proactive' => $proactive, 'source_key' => $key, 'source_version' => $version, 'private_source' => !$published];
|
||||
if ($proactive) {
|
||||
$zoneAnalysis = ['proactive' => $proactive, 'source_key' => $key, 'source_version' => $version, 'private_source' => ! $published];
|
||||
}
|
||||
// Text labels do not establish a canonical territorial correspondence.
|
||||
if ($o->province) {
|
||||
$fields['province'] = $o->province;
|
||||
@@ -173,7 +210,7 @@ final class InvestorContext
|
||||
}
|
||||
} elseif ($kind === 'portfolio') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$dossier = \App\Http\Controllers\InvestmentPortfolioController::visible()->findOrFail($id);
|
||||
$dossier = InvestmentPortfolioController::visible()->whereKey($id)->firstOrFail();
|
||||
$title = $dossier->title;
|
||||
$href = '/carteira/'.$id;
|
||||
// Documentary coverage is not the investor's chosen implantation.
|
||||
@@ -185,7 +222,7 @@ final class InvestorContext
|
||||
'geography' => app(InvestmentRelations::class)->dossier($dossier), 'available_opportunity' => false];
|
||||
} elseif ($kind === 'business') {
|
||||
abort_unless(config('existing-business.enabled') && Str::isUuid($id), 404);
|
||||
$o = ExistingBusiness::published()->with('sector')->findOrFail($id);
|
||||
$o = ExistingBusiness::published()->with('sector')->whereKey($id)->firstOrFail();
|
||||
$title = $o->public_title;
|
||||
$href = '/negocios/'.$o->public_slug;
|
||||
$version = $o->version_no;
|
||||
@@ -198,7 +235,9 @@ final class InvestorContext
|
||||
if ($location) {
|
||||
$leaf = $location->province_id;
|
||||
foreach (['district', 'admin_post', 'locality'] as $level) {
|
||||
if (in_array($location->precision_level, array_slice(['province', 'district', 'admin_post', 'locality', 'exact'], array_search($level, ['province', 'district', 'admin_post', 'locality', 'exact'])), true) && $location->{$level.'_id'}) {
|
||||
if (in_array($location->precision_level, match ($level) {
|
||||
'district' => ['district', 'admin_post', 'locality', 'exact'], 'admin_post' => ['admin_post', 'locality', 'exact'], 'locality' => ['locality', 'exact']
|
||||
}, true) && $location->{$level.'_id'}) {
|
||||
$leaf = $location->{$level.'_id'};
|
||||
}
|
||||
}
|
||||
@@ -208,7 +247,7 @@ final class InvestorContext
|
||||
}
|
||||
} elseif ($kind === 'sector') {
|
||||
abort_unless(ctype_digit($id), 422);
|
||||
$s = Sector::where('is_active', true)->findOrFail((int) $id);
|
||||
$s = Sector::where('is_active', true)->whereKey((int) $id)->firstOrFail();
|
||||
$title = $s->name;
|
||||
$href = SectorOrganization::href($s->slug);
|
||||
$version = $s->updated_at?->toIso8601String();
|
||||
@@ -216,14 +255,14 @@ final class InvestorContext
|
||||
} elseif ($kind === 'territory') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$t = app(InvestmentGeography::class)->publicReferences()->whereIn('location_type', array_values(InvestmentGeography::FIELDS))->where('id', $id)->first();
|
||||
abort_unless($t, 404, 'Território público indisponível.');
|
||||
abort_unless($t !== null, 404, 'Território público indisponível.');
|
||||
$title = $t->name;
|
||||
$version = $t->version_no;
|
||||
$href = '/oportunidades?'.$t->location_type.'_id='.$id;
|
||||
$fields = $this->territoryFields($id);
|
||||
} elseif ($kind === 'park') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$p = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->findOrFail($id);
|
||||
$p = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->whereKey($id)->firstOrFail();
|
||||
$title = $p->name;
|
||||
$fields = ['special_zone_id' => (string) $p->id, 'investment_regime' => (string) $p->category];
|
||||
$version = $p->version_no;
|
||||
@@ -249,6 +288,9 @@ final class InvestorContext
|
||||
return [...$record, 'sha256' => hash('sha256', json_encode($record, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function territoryFields(string $id): array
|
||||
{
|
||||
$path = app(InvestmentGeography::class)->path($id);
|
||||
@@ -271,6 +313,9 @@ final class InvestorContext
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function options(string $query = ''): array
|
||||
{
|
||||
$query = mb_substr(trim($query), 0, 120);
|
||||
@@ -296,6 +341,9 @@ final class InvestorContext
|
||||
'parks' => app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get(['id', 'name', 'category', 'version_no'])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function current(User $actor): array
|
||||
{
|
||||
if (! $this->installed()) {
|
||||
@@ -322,6 +370,10 @@ final class InvestorContext
|
||||
return ['installed' => true, 'focus' => ['case_id' => $case->id, 'step_code' => $p->step_code, 'version' => (int) $p->version]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function focus(User $actor, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
|
||||
@@ -344,9 +396,13 @@ final class InvestorContext
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function input(array $input): array
|
||||
{
|
||||
abort_if(array_diff(array_keys($input), ['complements', 'opportunity_choices', 'version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', 'document_links', '_token']), 422, 'Campo de controlo desconhecido.');
|
||||
abort_if(array_diff(array_keys($input), ['complements', 'opportunity_choices', 'version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', 'document_links', '_token']) !== [], 422, 'Campo de controlo desconhecido.');
|
||||
|
||||
abort_if(! app(PrivateInvestmentPreparation::class)->available() && (! empty($input['document_links']) || array_intersect(array_keys(is_array($input['declarations'] ?? null) ? $input['declarations'] : []), PrivateInvestmentPreparation::FIELDS)), 409, 'Esta preparação ainda não está disponível neste ambiente. As respostas foram preservadas.');
|
||||
|
||||
@@ -375,6 +431,10 @@ final class InvestorContext
|
||||
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor, string $id, array $input): array
|
||||
{
|
||||
$data = $this->input($input);
|
||||
@@ -397,7 +457,7 @@ final class InvestorContext
|
||||
if (! array_key_exists('opportunity_choices', $data) && array_key_exists('territory', $data['selection'])) {
|
||||
$source = $data['selection']['opportunity'] ?? ($old['selection']['opportunity']['key'] ?? null);
|
||||
if ($source && str_starts_with($source, 'opportunity:')) {
|
||||
$documented = Opportunity::findOrFail(substr($source, 12))->primary_territory_id;
|
||||
$documented = Opportunity::whereKey(substr($source, 12))->firstOrFail()->primary_territory_id;
|
||||
abort_if($documented && $data['selection']['territory'] !== 'territory:'.$documented, 422,
|
||||
'Confirme a alternativa territorial por ficha e indique o motivo; a localização documentada foi preservada.');
|
||||
}
|
||||
@@ -407,15 +467,21 @@ final class InvestorContext
|
||||
$data['selection']['opportunity'] = $choices[0]['opportunity']['key'] ?? null;
|
||||
// Shared fields concern the first identified opportunity; other sites remain separate.
|
||||
$data['selection']['territory'] = $choices[0]['territory']['key'] ?? null;
|
||||
if (array_key_exists('park', $data['opportunity_choices'][0] ?? [])) $data['selection']['park'] = $choices[0]['park']['key'] ?? null;
|
||||
if (array_key_exists('park', $data['opportunity_choices'][0] ?? [])) {
|
||||
$data['selection']['park'] = $choices[0]['park']['key'] ?? null;
|
||||
}
|
||||
} elseif (array_key_exists('opportunity', $data['selection']) && $choices !== []) {
|
||||
abort(422, 'Actualize a selecção identificada de oportunidades; não substitua silenciosamente o conjunto por uma ficha.');
|
||||
}
|
||||
$selection = $old['selection'];
|
||||
foreach ($complements as $complement) {
|
||||
if (($complement['availability'] ?? '') === 'review_required') continue;
|
||||
if (($complement['availability'] ?? '') === 'review_required') {
|
||||
continue;
|
||||
}
|
||||
foreach ([$complement['origin']['key'], $complement['target']['key'] ?? ''] as $key) {
|
||||
if (str_starts_with($key, 'opportunity:')) abort_unless(in_array($key, array_column(array_column($choices, 'opportunity'), 'key'), true), 422, 'Conserve a oportunidade escolhida ou retire explicitamente a sua relação complementar.');
|
||||
if (str_starts_with($key, 'opportunity:')) {
|
||||
abort_unless(in_array($key, array_column(array_column($choices, 'opportunity'), 'key'), true), 422, 'Conserve a oportunidade escolhida ou retire explicitamente a sua relação complementar.');
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($data['selection'] as $slot => $key) {
|
||||
@@ -426,16 +492,20 @@ final class InvestorContext
|
||||
}
|
||||
$ref = $this->reference($key);
|
||||
$expected = $slot === 'opportunity' ? ['opportunity', 'business'] : [$slot];
|
||||
abort_unless(in_array($ref['kind'], $expected, true), 422, 'Referência incompatível com a dimensão.');
|
||||
if (! (in_array($ref['kind'], $expected, true))) {
|
||||
abort(422, 'Referência incompatível com a dimensão.');
|
||||
}
|
||||
$selection[$slot] = $ref;
|
||||
}
|
||||
$corridor = $choices[0]['corridor_key'] ?? (isset($selection['opportunity']) && $selection['opportunity']['kind'] === 'opportunity'
|
||||
? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail($selection['opportunity']['id'])) : null);
|
||||
if ($corridor && isset($selection['territory'])) abort_unless(app(InvestmentCorridorContext::class)->compatible($corridor, $selection['territory']['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
? app(InvestmentCorridorContext::class)->key(Opportunity::whereKey($selection['opportunity']['id'])->firstOrFail()) : null);
|
||||
if ($corridor && isset($selection['territory'])) {
|
||||
abort_unless(app(InvestmentCorridorContext::class)->compatible($corridor, $selection['territory']['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
if ($corridor && isset($selection['park'])) {
|
||||
$eligible = array_column(app(InvestmentCorridorContext::class)->parks($corridor, $selection['territory']['id'] ?? null), 'id');
|
||||
if (!in_array($selection['park']['id'], $eligible, true)) {
|
||||
abort_if(!empty($data['selection']['park']), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
if (! in_array($selection['park']['id'], $eligible, true)) {
|
||||
abort_if(! empty($data['selection']['park']), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
unset($selection['park']);
|
||||
}
|
||||
}
|
||||
@@ -484,14 +554,16 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
if ($corridor) {
|
||||
foreach (['province_id','district_id','admin_post_id','locality_id','province','district','location'] as $key) {
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'] as $key) {
|
||||
if (isset($selection['territory']['fields'][$key])) {
|
||||
$fields[$key]=(string)$selection['territory']['fields'][$key];
|
||||
$provenance[$key]=Arr::except($selection['territory'],['fields']);
|
||||
} else unset($fields[$key],$provenance[$key]);
|
||||
$fields[$key] = (string) $selection['territory']['fields'][$key];
|
||||
$provenance[$key] = Arr::except($selection['territory'], ['fields']);
|
||||
} else {
|
||||
unset($fields[$key],$provenance[$key]);
|
||||
}
|
||||
}
|
||||
$fields['special_zone_id']=$selection['park']['id']??'';
|
||||
$fields['investment_regime']=$selection['park']['fields']['investment_regime']??'general';
|
||||
$fields['special_zone_id'] = $selection['park']['id'] ?? '';
|
||||
$fields['investment_regime'] = $selection['park']['fields']['investment_regime'] ?? 'general';
|
||||
}
|
||||
$replaced = [];
|
||||
foreach (array_unique([...array_keys($old['fields']), ...array_keys($fields)]) as $key) {
|
||||
@@ -505,11 +577,16 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
$changedFields = array_column($replaced, 'field');
|
||||
if ($complements !== ($old['complements'] ?? [])) $changed[] = 'complements';
|
||||
if ($complements !== ($old['complements'] ?? [])) {
|
||||
$changed[] = 'complements';
|
||||
}
|
||||
$choicesChanged = $choices !== ($old['opportunity_choices'] ?? []);
|
||||
$choiceInputsChanged = array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$choices) !== array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$old['opportunity_choices']??[]);
|
||||
if ($choiceInputsChanged) $changed = array_values(array_unique([...$changed, 'opportunity', 'territory']));
|
||||
elseif ($choicesChanged) $changed[] = 'portfolio_origins';
|
||||
$choiceInputsChanged = array_map(fn ($c) => Arr::except($c, ['portfolio_origins']), $choices) !== array_map(fn ($c) => Arr::except($c, ['portfolio_origins']), $old['opportunity_choices'] ?? []);
|
||||
if ($choiceInputsChanged) {
|
||||
$changed = array_values(array_unique([...$changed, 'opportunity', 'territory']));
|
||||
} elseif ($choicesChanged) {
|
||||
$changed[] = 'portfolio_origins';
|
||||
}
|
||||
$conditionsChanged = (bool) array_intersect($changedFields, array_diff(self::FIELDS, ['project_title', 'project_summary']));
|
||||
$dependencyChanged = $choiceInputsChanged || in_array('complements', $changed, true) || $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection) || $conditionsChanged;
|
||||
$privateConditionsChanged = (bool) array_intersect($changedFields, PrivateInvestmentPreparation::FIELDS);
|
||||
@@ -524,7 +601,9 @@ final class InvestorContext
|
||||
if ($privateConditionsChanged) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S05', 'S06', 'S07']));
|
||||
}
|
||||
if (in_array('complements', $changed, true)) $steps = array_values(array_unique([...$steps, 'S02', 'S08']));
|
||||
if (in_array('complements', $changed, true)) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S08']));
|
||||
}
|
||||
$privatePreparation = null;
|
||||
if (app(PrivateInvestmentPreparation::class)->available()) {
|
||||
$docs = $this->preparationDocuments($id);
|
||||
@@ -543,6 +622,10 @@ final class InvestorContext
|
||||
return [...$plan, 'preview_hash' => $hash];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function commit(User $actor, string $id, array $input): array
|
||||
{
|
||||
abort_unless($this->installed(), 409, 'Instalação do contexto ainda pendente.');
|
||||
@@ -586,7 +669,7 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
$payload['investor_path']['context'] = $context;
|
||||
unset($payload['investor_path']['context_drafts'][(string)$actor->id]);
|
||||
unset($payload['investor_path']['context_drafts'][(string) $actor->id]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'title' => $context['fields']['project_title'] ?? $case->title, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'investment_context_changed', ['before' => $before, 'after' => $context, 'affected_result_ids' => array_column($plan['dependent_results'], 'id'), 'preserved_request_ids' => array_column($plan['requests'], 'id')]);
|
||||
$result = ['case_id' => $id, 'version' => (int) $case->version + 1, 'revision' => $revision, 'replayed' => false];
|
||||
@@ -596,6 +679,9 @@ final class InvestorContext
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function view(User $actor, string $id, ?string $opportunity = null): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
@@ -622,21 +708,28 @@ final class InvestorContext
|
||||
|
||||
$prefill = $this->prefill($ctx, $opportunity);
|
||||
$saved = $this->desk->decode($case->payload);
|
||||
if (!empty($saved['reuse_consent'])) {
|
||||
$contacts = array_filter(['email' => $saved['email'] ?? null, 'phone' => $saved['profile']['phone'] ?? null], fn($v) => is_string($v) && $v !== '');
|
||||
if (! empty($saved['reuse_consent'])) {
|
||||
$contacts = array_filter(['email' => $saved['email'] ?? null, 'phone' => $saved['profile']['phone'] ?? null], fn ($v) => is_string($v) && $v !== '');
|
||||
$prefill['simulator'] = [...$contacts, ...$prefill['simulator']];
|
||||
$prefill['land'] = [...$contacts, ...(!empty($saved['name']) ? ['full_name' => $saved['name']] : []), ...$prefill['land']];
|
||||
$prefill['land'] = [...$contacts, ...(! empty($saved['name']) ? ['full_name' => $saved['name']] : []), ...$prefill['land']];
|
||||
}
|
||||
|
||||
return ['private_investment' => $preparation, 'preparation_documents' => $this->preparationDocuments($id), 'simulator_context_revision' => $simulatorRevision, 'case' => $path['case'], 'context' => $ctx, 'steps' => array_map(fn ($s) => Arr::only($s, ['code', 'title', 'state', 'context_review_required']), $path['steps']),
|
||||
'can_write' => $path['canWrite'], 'next' => $path['next'], 'results' => $path['results'], 'requests' => $path['requests'],
|
||||
'prefill' => $prefill, 'notice' => 'A seleção apoia a preparação e não confirma benefícios, licenças, direitos ou disponibilidade.'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preparationDocuments(string $id): array
|
||||
{
|
||||
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->whereNull('d.deleted_at')->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.version_no', 'd.sha256'])->map(fn ($row) => (array) $row)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function landPreparation(\stdClass $case, ?string $opportunity = null): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
@@ -648,6 +741,10 @@ final class InvestorContext
|
||||
return ['need' => in_array($need, ['yes', 'no'], true) ? $need : 'unknown', 'reason' => $key ? ($path['opportunity_fact_reasons'][$key]['land_needed'] ?? '') : ($path['fact_reasons']['land_needed'] ?? '')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $ctx
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function prefill(array $ctx, ?string $opportunity = null): array
|
||||
{
|
||||
$original = $ctx;
|
||||
@@ -659,15 +756,21 @@ final class InvestorContext
|
||||
$sim += ['journey_type' => 'investor', 'journey_type_label' => 'Avaliar o meu investimento', 'purpose' => 'simulate_only', 'purpose_label' => 'Apenas simular'];
|
||||
if (($ctx['land_preparation']['need'] ?? null) === 'yes') {
|
||||
$tenure = ['duat' => ['duat', 'DUAT'], 'lease' => ['leased', 'Arrendado']][$f['site_tenure'] ?? ''] ?? null;
|
||||
if ($tenure) [$sim['land_status'], $sim['land_status_label']] = $tenure;
|
||||
if ($tenure) {
|
||||
[$sim['land_status'], $sim['land_status_label']] = $tenure;
|
||||
}
|
||||
}
|
||||
// Human labels travel with the exact existing identifiers, not inferred locations.
|
||||
foreach (app(InvestmentGeography::class)->publicReferences()->whereIn('id', array_values(Arr::only($f, array_keys(InvestmentGeography::FIELDS))))->get(['id', 'name']) as $place) {
|
||||
foreach (array_keys(InvestmentGeography::FIELDS) as $key) {
|
||||
if (($f[$key] ?? null) === $place->id) $sim[$key.'_label'] = $place->name;
|
||||
if (($f[$key] ?? null) === $place->id) {
|
||||
$sim[$key.'_label'] = $place->name;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! empty($f['sector_id']) && ($sector = Sector::where('is_active', true)->find($f['sector_id']))) $sim['sector_id_label'] = $sector->name;
|
||||
if (! empty($f['sector_id']) && ($sector = Sector::where('is_active', true)->whereKey($f['sector_id'])->first())) {
|
||||
$sim['sector_id_label'] = $sector->name;
|
||||
}
|
||||
$zone = $ctx['selection']['park'] ?? null;
|
||||
$sim['context_applicability_snapshot'] = json_encode([
|
||||
'version' => 1, 'context_revision' => $ctx['revision'],
|
||||
@@ -675,12 +778,13 @@ final class InvestorContext
|
||||
'portfolio_origin' => $ctx['selection']['portfolio'] ?? null,
|
||||
'zone' => $zone ? Arr::only($zone, ['id', 'title', 'href', 'version', 'sha256', 'fields', 'analysis']) : null,
|
||||
'provenance' => $ctx['provenance'],
|
||||
'opportunity_choices' => $ctx['opportunity_choices'] ?? [],
|
||||
// Retain dossier options as provenance when no consumer is selected; scoped fields remain empty.
|
||||
'opportunity_choices' => ($ctx['opportunity_choices'] ?? []) ?: ($original['opportunity_choices'] ?? []),
|
||||
'complements' => $ctx['complements'] ?? [],
|
||||
'requirements_assessment' => $ctx['requirements_assessment'] ?? null,
|
||||
'path' => $ctx['path_applicability'] ?? null,
|
||||
'land_preparation' => $ctx['land_preparation'] ?? null,
|
||||
'field_provenance' => array_map(fn($origin) => Arr::only($origin, ['kind', 'title', 'version', 'context_revision']), $ctx['provenance'] ?? []),
|
||||
'field_provenance' => array_map(fn ($origin) => Arr::only($origin, ['kind', 'title', 'version', 'context_revision']), $ctx['provenance'] ?? []),
|
||||
'preparation' => isset($ctx['preparation_assessment']) ? Arr::except($ctx['preparation_assessment'], ['questions']) : null,
|
||||
'fields' => Arr::only($f, ['investor_origin', 'tax_residency_country', 'entity_stage', 'currency', 'expected_start_date', 'investment_regime']),
|
||||
'notice' => 'Referências e declarações para preparação; sem reconhecimento automático de elegibilidade ou benefício.',
|
||||
@@ -688,6 +792,7 @@ final class InvestorContext
|
||||
|
||||
$scoped = app(InvestmentConsumerScope::class)->context($original, $opportunity);
|
||||
$f = $scoped['fields'];
|
||||
|
||||
return ['simulator' => $sim, 'land' => array_filter(['project_reference' => $f['project_title'] ?? null, 'activity' => $f['sector'] ?? null, 'purpose' => $f['project_summary'] ?? null, 'parcels' => [Arr::only($f, array_keys(InvestmentGeography::FIELDS))]], fn ($v) => $v !== null),
|
||||
'desk' => array_filter(['title' => $f['project_title'] ?? null, 'territory_id' => $f['locality_id'] ?? $f['admin_post_id'] ?? $f['district_id'] ?? $f['province_id'] ?? null, 'location_source' => isset($f['province_id']) ? 'Referência consultada no contexto v'.($ctx['revision'] ?? 0).': '.($f['location'] ?? 'território identificado').'. Não confirma disponibilidade.' : null, 'description' => $f['project_summary'] ?? null, 'sector' => $f['sector'] ?? null, ...Arr::only($f, array_keys(InvestmentGeography::FIELDS))], fn ($v) => $v !== null),
|
||||
'submission' => array_filter(['currency' => $f['currency'] ?? null, 'sector' => $f['sector'] ?? null, 'objective' => $f['project_summary'] ?? null, 'location' => $f['location'] ?? null], fn ($v) => $v !== null)];
|
||||
|
||||
@@ -20,7 +20,7 @@ final class InvestorContextConsumers
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public function landRevision(string $id): int
|
||||
@@ -32,7 +32,7 @@ return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public function submissionRevision(string $id): int
|
||||
@@ -44,9 +44,12 @@ return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function assertReviewed(User $actor, string $id, array $input, int $bound): int
|
||||
{
|
||||
$case = app(VirtualDesk::class)->case($actor, $id, true, true);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
@@ -15,6 +16,9 @@ final class InvestorContextInstallation
|
||||
{
|
||||
public const SOURCE = 'investor-context-installation';
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function files(): array
|
||||
{
|
||||
return ['app/Http/Controllers/InvestmentSubmissionController.php', 'app/Http/Controllers/InvestorContextController.php', 'app/Http/Controllers/LandAssistanceController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Http/Controllers/VirtualDeskController.php', 'app/Http/Requests/StoreLandAssistanceCaseRequest.php', 'app/Services/InvestorContext.php', 'app/Services/InvestorContextConsumers.php', 'app/Services/InvestorContextInstallation.php', 'app/Services/InvestorPath.php', 'app/Services/VirtualDesk.php', 'database/migrations/2026_10_16_150000_create_investor_navigation_preferences.php', 'resources/js/app.tsx', 'resources/js/components/catalogue-navigation.tsx', 'resources/js/components/dossier-navigation-context.tsx', 'resources/js/components/dossier-prefill.tsx', 'resources/js/components/navigation-context.tsx', 'resources/js/components/portal-grouped-menu.tsx', 'resources/js/components/simulation-form.tsx', 'resources/js/layouts/app/app-sidebar-layout.tsx', 'resources/js/layouts/portal-navigation.tsx', 'resources/js/lib/investor-context.ts', 'resources/js/lib/investor-path.ts', 'resources/js/lib/portal-navigation.ts', 'resources/js/pages/desk/request.tsx', 'resources/js/pages/investment/business-opportunity.tsx', 'resources/js/pages/investment/catalogue.tsx', 'resources/js/pages/investment/detail.tsx', 'resources/js/pages/investment/submission.tsx', 'resources/js/pages/investment/zone.tsx', 'resources/js/pages/investor-path/context-installation.tsx', 'resources/js/pages/investor-path/context-start.tsx', 'resources/js/pages/investor-path/context.tsx', 'resources/js/pages/investor-path/show.tsx', 'resources/js/pages/land-assistance/form.tsx', 'resources/js/pages/portal/services.tsx', 'resources/js/pages/portal/why-invest.tsx', 'routes/investment.php', 'routes/investor-path.php', 'routes/web.php'];
|
||||
@@ -41,6 +45,9 @@ final class InvestorContextInstallation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor): array
|
||||
{
|
||||
$this->authorize($actor);
|
||||
@@ -60,12 +67,12 @@ final class InvestorContextInstallation
|
||||
}
|
||||
$isolated = app()->environment('testing') && config('database.connections.pgsql.host') === '127.0.0.1' && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test') && ! config('database.connections.pgsql.url');
|
||||
$proofPath = storage_path('app/private/investmoz-v2/investor-context/readiness.json');
|
||||
$proof = is_file($proofPath) ? json_decode(file_get_contents($proofPath), true) : [];
|
||||
$proof = is_file($proofPath) ? json_decode(CheckedFile::read($proofPath), true) : [];
|
||||
$fresh = ! app()->environment('testing') && ($proof['code_hash'] ?? '') === $code && ($proof['target'] ?? []) === $target && ($proof['authorization_record'] ?? '') !== '' && ($proof['migration'] ?? '') === InvestorContext::MIGRATION
|
||||
&& ($proof['restore_verified'] ?? false) && ($proof['restored_boot_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && strtotime($proof['verified_at'] ?? '') <= time();
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
$p = $proof[$kind.'_path'] ?? '';
|
||||
$fresh = $fresh && is_file($p) && hash_equals($proof[$kind.'_sha256'] ?? '', hash_file('sha256', $p));
|
||||
$fresh = $fresh && is_file($p) && hash_equals($proof[$kind.'_sha256'] ?? '', CheckedFile::sha256($p));
|
||||
}
|
||||
if (! $isolated && ! $fresh) {
|
||||
$reasons[] = 'Autorização específica, hashes e backup/restauro/arranque frescos desta candidata necessários.';
|
||||
@@ -75,10 +82,14 @@ final class InvestorContextInstallation
|
||||
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true);
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'operation_key', 'confirm', '_token']), 422, 'Migration, ator ou caminho arbitrário recusado.');
|
||||
abort_if(array_diff(array_keys($input), ['hash', 'operation_key', 'confirm', '_token']) !== [], 422, 'Migration, ator ou caminho arbitrário recusado.');
|
||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'operation_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\CrmTask;
|
||||
use App\Models\LandAssistanceCase;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -152,7 +153,7 @@ final class InvestorPath
|
||||
$landCase = (int) $case->user_id === $actor->id
|
||||
? LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
|
||||
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id
|
||||
&& (!$allChoices || ($opportunity && ($land->payload['context_opportunity'] ?? null) === $opportunity))) : null;
|
||||
&& (! $allChoices || ($opportunity && ($land->payload['context_opportunity'] ?? null) === $opportunity))) : null;
|
||||
|
||||
$preparation = ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(PrivateInvestmentPreparation::class)->assess($context, $documents->map(fn ($d) => (array) $d)->all()) : null;
|
||||
if ($preparation && $preparation['enabled']) {
|
||||
@@ -163,7 +164,7 @@ final class InvestorPath
|
||||
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
|
||||
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $factReasons,
|
||||
'context_opportunity' => $opportunity, 'opportunity_options' => $allChoices,
|
||||
'fintech' => ($owner || $manager) && (isset($path['fintech']) || collect($path['sector_contexts'] ?? [])->contains(fn ($s) => in_array($s['slug'], ['fintech', 'tecnologias-de-informacao', 'mercado-financeiro'], true)) || collect($path['content_sources'] ?? [])->contains('return_href', '/tech-fintech')) ? app(FintechInvestment::class)->view($payload, $steps) : null,
|
||||
'fintech' => ($owner || $manager) && (isset($path['fintech']) || collect(StructuredData::collectionItems($path['sector_contexts'] ?? []))->contains(fn ($s) => in_array($s['slug'], ['fintech', 'tecnologias-de-informacao', 'mercado-financeiro'], true)) || collect(StructuredData::collectionItems($path['content_sources'] ?? []))->contains('return_href', '/tech-fintech')) ? app(FintechInvestment::class)->view($payload, $steps) : null,
|
||||
'canWrite' => $owner && ! $case->closed_at, 'canReview' => $manager && (int) $case->user_id !== $actor->id && ! $case->closed_at,
|
||||
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => $next['href'] ?? '#'.$next['code']] : null,
|
||||
'investment_context' => ($owner || $manager) ? [...$context, 'opportunity_choices' => $opportunity ? $context['opportunity_choices'] : $allChoices] : null,
|
||||
@@ -256,8 +257,11 @@ final class InvestorPath
|
||||
abort_if($state === 'completed' && ($step['context_review_required'] ?? false) && (! (bool) ($data['context_reviewed'] ?? false) || ($data['context_revision'] ?? -1) !== ($view['investment_context']['revision'] ?? 0)), 422, 'O contexto desta etapa exige nova conferência fundamentada; o registo anterior permanece no histórico.');
|
||||
$detail = [...$data, 'context_dependency_hash' => $view['investment_context']['dependency_hash'] ?? null, 'fintech_fingerprint' => $view['fintech']['review_fingerprints'][$code] ?? null, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
|
||||
$stored = $this->desk->decode(DB::table('journey_steps')->where('id', $step['id'])->value('path_detail'));
|
||||
if ($key) $stored['opportunities'][$key] = $detail;
|
||||
else $stored = [...$stored, ...$detail];
|
||||
if ($key) {
|
||||
$stored['opportunities'][$key] = $detail;
|
||||
} else {
|
||||
$stored = [...$stored, ...$detail];
|
||||
}
|
||||
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($stored),
|
||||
'status' => in_array($state, ['completed', 'approved'], true) ? 'completed' : ($state === 'not_started' ? 'pending' : 'active'),
|
||||
'version_no' => $step['version'] + 1, 'updated_at' => now()]);
|
||||
|
||||
@@ -5,13 +5,18 @@ namespace App\Services;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedPattern;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMNode;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** A reading adapter over the existing library, never a second content/opportunity register. */
|
||||
final class LegacyContent
|
||||
@@ -68,13 +73,13 @@ final class LegacyContent
|
||||
$opportunities = Opportunity::published()->whereIn('sector_id', $relatedSectors->pluck('id'))->latest('published_at')->limit(12)->get(['id', 'title', 'slug', 'province', 'summary']);
|
||||
}
|
||||
$localHtml = $this->localLinks($this->sanitize($source['content_html']));
|
||||
$editorial = \Illuminate\Support\Facades\Schema::hasColumn('portal_resources', 'editorial_content')
|
||||
$editorial = Schema::hasColumn('portal_resources', 'editorial_content')
|
||||
? DB::table('portal_resources')->where('id', $row->resource_id)->value('editorial_content') : null;
|
||||
if ($editorial) {
|
||||
$adaptation = json_decode($editorial, true, 64, JSON_THROW_ON_ERROR);
|
||||
$localHtml = implode('', array_map(fn ($p) => '<p>'.nl2br(e($p)).'</p>', preg_split('/\n\s*\n/', $adaptation['body'])));
|
||||
$localHtml = implode('', array_map(fn ($p) => '<p>'.nl2br(e($p)).'</p>', CheckedPattern::split('/\n\s*\n/', $adaptation['body'])));
|
||||
$source['title'] = $row->title;
|
||||
if (!empty($adaptation['image_resource_id'])) {
|
||||
if (! empty($adaptation['image_resource_id'])) {
|
||||
$image = $this->publicResources()->where('r.id', $adaptation['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->first();
|
||||
}
|
||||
}
|
||||
@@ -86,11 +91,15 @@ final class LegacyContent
|
||||
$relatedArticles = [];
|
||||
if ($includeRelated) {
|
||||
foreach ($this->related($identity['group'], $slug) as $item) {
|
||||
if (in_array($item['href'], $alreadyLinked, true)) continue;
|
||||
if (in_array($item['href'], $alreadyLinked, true)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$relatedArticles[] = $this->article($item['slug'], false);
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $error) {
|
||||
if ($error->getStatusCode() !== 404) throw $error;
|
||||
} catch (HttpException $error) {
|
||||
if ($error->getStatusCode() !== 404) {
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,16 +134,21 @@ final class LegacyContent
|
||||
&& str_contains($plain, 'Infraestruturas turísticas') && str_contains($plain, 'Oportunidades Regionais')) {
|
||||
return 'Conheça os temas de turismo e hospitalidade abordados no guia: hotelaria, ecoturismo, infraestruturas de apoio e referências regionais. Use este enquadramento para preparar a sua ideia de investimento.';
|
||||
}
|
||||
preg_match_all('~<p\b[^>]*>(.*?)</p>~isu', $html, $paragraphs);
|
||||
foreach ([...($paragraphs[1] ?? []), $html] as $paragraph) {
|
||||
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($paragraph), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
|
||||
if (mb_strlen($text) >= 60) return \Illuminate\Support\Str::limit($text, 320);
|
||||
if (preg_match_all('~<p\b[^>]*>(.*?)</p>~isu', $html, $paragraphs) === false) {
|
||||
throw new \RuntimeException('Invalid paragraph encoding; original preserved.');
|
||||
}
|
||||
foreach ([...$paragraphs[1], $html] as $paragraph) {
|
||||
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($paragraph), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
|
||||
if (mb_strlen($text) >= 60) {
|
||||
return Str::limit($text, 320);
|
||||
}
|
||||
}
|
||||
|
||||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
|
||||
}
|
||||
|
||||
/** Resolve a library identity, preserving the already stored source URLs and versions. */
|
||||
/** @return array<string, mixed> */
|
||||
/** 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);
|
||||
@@ -239,8 +253,10 @@ final class LegacyContent
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve explicit transport aliases without changing original IDs, versions or relations. */
|
||||
private function identityResources(): \Illuminate\Support\Collection
|
||||
/** Resolve explicit transport aliases without changing original IDs, versions or relations.
|
||||
* @return Collection<int, \stdClass>
|
||||
*/
|
||||
private function identityResources(): Collection
|
||||
{
|
||||
$identities = array_column(config('legacy_content.articles', []), 'external_id');
|
||||
$aliases = config('legacy_content_aliases', []);
|
||||
@@ -269,6 +285,7 @@ final class LegacyContent
|
||||
$row->legacy_identity = $identity;
|
||||
$resolved->put($identity, $row);
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,10 @@ 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. */
|
||||
/** Availability of this bounded base-category delivery, without rewriting existing contracts/data.
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function deliveryBlockers(array $payload): array
|
||||
{
|
||||
$errors = [];
|
||||
@@ -44,7 +47,10 @@ class OpportunityCanonicalContract
|
||||
|
||||
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function schema(bool $draft = false, array $payload = []): array
|
||||
{
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
@@ -173,6 +179,7 @@ class OpportunityCanonicalContract
|
||||
$args = $node->args();
|
||||
if ($node->keyword() === 'type' && in_array($prefix, ['canonical.initiative.responsible_name', 'canonical.initiative.coverage_statement'], true)) {
|
||||
$errors[$prefix][] = 'Informação em falta: preencha este campo antes de submeter.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -298,7 +305,7 @@ class OpportunityCanonicalContract
|
||||
&& hash_equals(trim($file->sha256), trim((string) $file->malware_scanned_sha256)), "$kind.$index", 'Original ativo com análise antimalware correspondente obrigatória.');
|
||||
if ($file) {
|
||||
// Verify actual bytes/cipher integrity as well as the recorded scan hash.
|
||||
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($row, $file);
|
||||
app(OpportunityLibrarySupport::class)->assertAvailable($row, $file);
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
$row->sha256 = trim($file->sha256);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -40,6 +41,10 @@ class OpportunityClassification
|
||||
|
||||
public const EXTERNAL = ['not_assessed', 'pending', 'documented_granted', 'documented_denied', 'expired'];
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $schema
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function extend(array $schema): array
|
||||
{
|
||||
$fields = ['target_type' => ['type' => 'string', 'enum' => array_keys(self::TARGETS)],
|
||||
@@ -86,7 +91,8 @@ class OpportunityClassification
|
||||
$query->whereIn('cluster_id', $this->targets('cluster')->select('id'));
|
||||
}
|
||||
if ($kind === 'location') {
|
||||
$query->whereIn('id', app(InvestmentGeography::class)->publicReferences()->select('id'));
|
||||
// Use the authoritative public scope directly; wrapping it in a second scan multiplies recursive ancestry checks.
|
||||
$query = app(InvestmentGeography::class)->publicReferences();
|
||||
}
|
||||
if (in_array($kind, ['zone', 'park'], true)) {
|
||||
return $query->whereIn('id', app(InvestmentZones::class)->visible()->select('id'))->when($kind === 'park', fn ($q) => $q->where('category', 'industrial_park'));
|
||||
@@ -100,6 +106,9 @@ class OpportunityClassification
|
||||
return app(EconomicReferenceCatalog::class)->constrain($query->where('data_classification', 'public'), $kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
$targets = [];
|
||||
@@ -112,6 +121,9 @@ class OpportunityClassification
|
||||
return ['version' => self::VERSION, 'dimensions' => self::DIMENSIONS, 'types' => array_map(fn ($v) => $v[2], self::TARGETS), 'purposes' => self::PURPOSES, 'states' => self::STATES, 'externalStates' => self::EXTERNAL, 'targets' => $targets];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
*/
|
||||
public function validate(array $payload, Opportunity $record): void
|
||||
{
|
||||
$previousPayload = $record->exists ? (app(OpportunityManagement::class)->values($record)['canonical'] ?? []) : [];
|
||||
@@ -185,16 +197,26 @@ class OpportunityClassification
|
||||
}
|
||||
}
|
||||
|
||||
/** Exact persisted relation retention is not permission to choose a withdrawn target anew. */
|
||||
/** Exact persisted relation retention is not permission to choose a withdrawn target anew.
|
||||
* @param array<array-key, mixed> $previousRows
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
public function canRetainReference(string $kind, string $id, array $row, array $previousRows): bool
|
||||
{
|
||||
if ($this->targets($kind)->where('id', $id)->exists()) { return true; }
|
||||
if (! app(EconomicReferenceCatalog::class)->historicalTarget($kind, $id)) { return false; }
|
||||
if ($this->targets($kind)->where('id', $id)->exists()) {
|
||||
return true;
|
||||
}
|
||||
if (! app(EconomicReferenceCatalog::class)->historicalTarget($kind, $id)) {
|
||||
return false;
|
||||
}
|
||||
$content = fn ($r) => array_intersect_key($r, array_flip(['related_id', 'relation_type', 'classification']));
|
||||
|
||||
return collect($previousRows)->contains(fn ($old) => OpportunityCanonicalValue::hash($content($old)) === OpportunityCanonicalValue::hash($content($row)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
public function hash(array $row): string
|
||||
{
|
||||
// Client identity/status cannot certify a relation. Object-order normalization is reused.
|
||||
@@ -212,6 +234,9 @@ class OpportunityClassification
|
||||
&& ($g->organization_id === null || $g->organization_id === $record->organization_id) && in_array($responsibility, json_decode($g->responsibilities, true), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
public function state(Opportunity $record, array $row): string
|
||||
{
|
||||
$decision = $record->workflow_context['classification_decisions'][$this->hash($row)] ?? null;
|
||||
@@ -219,7 +244,7 @@ class OpportunityClassification
|
||||
return $decision['state'];
|
||||
}
|
||||
if ($decision) {
|
||||
$reviewer = User::find($decision['actor_id']);
|
||||
$reviewer = User::whereKey($decision['actor_id'])->first();
|
||||
$c = $row['classification'];
|
||||
if (! empty($c['document_id']) && ($decision['evidence_hash'] ?? '') !== $this->evidenceHash($row)) {
|
||||
return 'in_validation';
|
||||
@@ -239,6 +264,9 @@ class OpportunityClassification
|
||||
return $row['classification']['requested_state'] ?? 'preliminary';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $row
|
||||
*/
|
||||
private function evidenceHash(array $row): ?string
|
||||
{
|
||||
$id = $row['classification']['document_id'] ?? null;
|
||||
@@ -251,6 +279,9 @@ class OpportunityClassification
|
||||
return OpportunityCanonicalValue::hash($resource ? (array) $resource : ['unavailable' => $id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function listing(User $actor, Opportunity $record): array
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'view', $record);
|
||||
@@ -271,11 +302,14 @@ class OpportunityClassification
|
||||
}
|
||||
|
||||
return ['hash' => $this->hash($row), 'dimension' => $dimension, 'relation' => $row, 'state' => $this->state($record, $row),
|
||||
'metadata' => collect($metadata['active'] ?? [])->first(fn ($m) => ($m['fingerprint'] ?? '') === $this->hash($row)), 'previous_versions' => $prior,
|
||||
'metadata' => collect(StructuredData::collectionItems($metadata['active'] ?? []))->first(fn ($m) => ($m['fingerprint'] ?? '') === $this->hash($row)), 'previous_versions' => $prior,
|
||||
'can_review' => $this->canReview($actor, $record, $dimension), 'history' => $record->workflow_context['classification_decisions'][$this->hash($row)]['history'] ?? []];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function review(User $actor, Opportunity $record, array $input): Opportunity
|
||||
{
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'hash' => 'required|string|size:64', 'state' => 'required|in:in_validation,confirmed,rejected,archived,revoked', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
@@ -291,7 +325,7 @@ class OpportunityClassification
|
||||
if (in_array($data['state'], ['revoked', 'archived'], true)) {
|
||||
$rows = [...$rows, ...($record->workflow_context['publication']['classification'] ?? [])];
|
||||
}
|
||||
$row = collect($rows)->first(fn ($r) => isset($r['classification']) && $this->hash($r) === $data['hash']);
|
||||
$row = collect(StructuredData::collectionItems($rows))->first(fn ($r) => isset($r['classification']) && $this->hash($r) === $data['hash']);
|
||||
abort_unless($row, 409, 'Associação inexistente nesta versão.');
|
||||
$c = $row['classification'];
|
||||
abort_unless($this->canReview($actor, $record, self::TARGETS[$c['target_type']][2]), 403, 'Revisão exige âmbito, responsabilidade, MFA e independência aprovados.');
|
||||
@@ -314,12 +348,18 @@ class OpportunityClassification
|
||||
});
|
||||
}
|
||||
|
||||
/** Frozen at the existing editorial publication, not on draft save or association confirmation. */
|
||||
/** Frozen at the existing editorial publication, not on draft save or association confirmation.
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publication(array $payload): array
|
||||
{
|
||||
return array_values(array_filter($payload['relations'] ?? [], fn ($r) => isset($r['classification']) && ($r['classification']['disclosure'] ?? 'restricted') === 'public'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicRows(Opportunity $record): array
|
||||
{
|
||||
if ($record->trashed() || $record->status !== 'published' || ! $record->published_at || $record->published_at->isFuture() || ($record->workflow_context['publication']['visibility'] ?? '') !== 'public') {
|
||||
@@ -343,7 +383,7 @@ class OpportunityClassification
|
||||
// Original documents, internal rationale, actor IDs and decision history stay private.
|
||||
$rows[] = ['dimension' => self::TARGETS[$kind][2], 'target_type' => $kind, 'target_id' => (string) $row['related_id'], 'label' => $target->{self::TARGETS[$kind][1]},
|
||||
'purpose' => $c['purpose'], 'purpose_label' => self::PURPOSES[$c['purpose']], 'target_code' => $target->code ?? null, 'catalog_version' => $target->catalog_version_id ?? null,
|
||||
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)?->path ?? []) : [],
|
||||
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)->path ?? []) : [],
|
||||
'physical_category' => $target->physical_category ?? null, 'legal_regime' => $target->legal_regime ?? null,
|
||||
'state' => $state, 'source_reference' => $c['source_reference'] ?? null, 'citation' => $c['citation'] ?? null,
|
||||
'authority_id' => $c['authority_id'] ?? null, 'external_status' => $c['external_status'] ?? 'not_assessed', 'availability_confirmed' => false,
|
||||
@@ -353,7 +393,10 @@ class OpportunityClassification
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** Same public projection for count/list/map; AND across filters, OR across selected associations. */
|
||||
/** Same public projection for count/list/map; AND across filters, OR across selected associations.
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @param Builder<Opportunity> $query
|
||||
*/
|
||||
public function constrain(Builder $query, array $filters): void
|
||||
{
|
||||
$keys = ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id'];
|
||||
@@ -383,7 +426,7 @@ class OpportunityClassification
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => $r['authority_id'] === $filters['authority_id']);
|
||||
}
|
||||
if (! empty($filters['subsector_id'])) {
|
||||
$matches = $matches && (in_array($filters['subsector_id'], array_intersect_key($record->workflow_context['publication']['taxonomy'] ?? [], array_flip(['subsector_id','economic_activity_id'])), true) || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
|
||||
$matches = $matches && (in_array($filters['subsector_id'], array_intersect_key($record->workflow_context['publication']['taxonomy'] ?? [], array_flip(['subsector_id', 'economic_activity_id'])), true) || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
|
||||
}
|
||||
if ($matches) {
|
||||
$ids[] = $record->id;
|
||||
@@ -393,9 +436,13 @@ class OpportunityClassification
|
||||
$query->whereIn('opportunities.id', $ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function duplicates(User $actor, Opportunity $record): array
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'view', $record);
|
||||
|
||||
// Exact-title candidates only within the actor's existing visibility; never merge or reveal another dossier.
|
||||
return app(PortalProfileAccess::class)->scope(Opportunity::query(), $actor)->whereKeyNot($record->id)
|
||||
->whereRaw('lower(trim(title))=lower(trim(?))', [$record->title])->limit(10)->get(['id', 'reference', 'title'])
|
||||
|
||||
@@ -14,6 +14,10 @@ use Illuminate\Validation\ValidationException;
|
||||
/** Reuse the CRM master without manufacturing an interest, lead or consent. */
|
||||
class OpportunityContacts
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function save(User $actor, int $id, array $input): array
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
@@ -63,7 +67,7 @@ class OpportunityContacts
|
||||
$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.');
|
||||
abort_unless($investor !== null, 403, 'O cadastro selecionado não pertence ao promotor desta oportunidade.');
|
||||
} elseif ($investors->count() === 1) {
|
||||
$investor = $investors->first();
|
||||
} elseif ($investors->count() > 1) {
|
||||
@@ -73,7 +77,7 @@ class OpportunityContacts
|
||||
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.');
|
||||
abort_unless($organization !== null, 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',
|
||||
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Support\StructuredData;
|
||||
|
||||
/** Read-only grouping of the existing public catalogue. */
|
||||
final class OpportunityCorridorExplorer
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $filters
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function groups(array $filters): array
|
||||
{
|
||||
$catalogue = app(InvestmentCatalogue::class);
|
||||
@@ -14,7 +18,7 @@ final class OpportunityCorridorExplorer
|
||||
foreach ($catalogue->query($filters)->get() as $record) {
|
||||
$context = $catalogue->context($record->id);
|
||||
$classification = $context['classification'] ?? [];
|
||||
$corridors = collect($context['corridors'])->mapWithKeys(fn ($c) => ['corridor:'.$c->id => $c->name])->all();
|
||||
$corridors = collect(StructuredData::collectionItems($context['corridors']))->mapWithKeys(fn ($c) => ['corridor:'.$c->id => $c->name])->all();
|
||||
foreach ($classification as $relation) {
|
||||
if ($relation['target_type'] === 'corridor' && ! in_array($relation['purpose'], ['proximity', 'administrative_boundary'], true)) {
|
||||
$corridors['corridor:'.$relation['target_id']] = $relation['label'];
|
||||
@@ -27,12 +31,16 @@ final class OpportunityCorridorExplorer
|
||||
$corridors['source:'.hash('sha256', $source['corridor'])] = $source['corridor'];
|
||||
$chain = $source['chain'];
|
||||
}
|
||||
$chains = collect($classification)->where('target_type', 'chain')->pluck('label')->all();
|
||||
if ($chain) $chains[] = $chain;
|
||||
$stages = collect($classification)->pluck('production_stage')->filter()->unique()->values()->all();
|
||||
$chains = collect(StructuredData::collectionItems($classification))->where('target_type', 'chain')->pluck('label')->all();
|
||||
if ($chain) {
|
||||
$chains[] = $chain;
|
||||
}
|
||||
$stages = collect(StructuredData::collectionItems($classification))->pluck('production_stage')->filter()->unique()->values()->all();
|
||||
// Keep the source's actual activity description rather than inventing stage labels.
|
||||
if ($stages === [] && $chain && ! empty($source['summary'])) $stages = [$source['summary']];
|
||||
$path = collect($context['primary_territory_path'] ?? []);
|
||||
if ($stages === [] && $chain && ! empty($source['summary'])) {
|
||||
$stages = [$source['summary']];
|
||||
}
|
||||
$path = collect(StructuredData::collectionItems($context['primary_territory_path'] ?? []));
|
||||
$province = $path->firstWhere('location_type', 'province')->name ?? $record->province;
|
||||
$district = $path->firstWhere('location_type', 'district')->name ?? $record->district;
|
||||
$contextProvinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record);
|
||||
@@ -53,6 +61,7 @@ final class OpportunityCorridorExplorer
|
||||
}
|
||||
unset($group);
|
||||
uasort($groups, fn ($a, $b) => ($a['id'] === 'other' ? 1 : 0) <=> ($b['id'] === 'other' ? 1 : 0) ?: strnatcasecmp($a['name'], $b['name']));
|
||||
|
||||
return array_values($groups);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class OpportunityImageProcessor
|
||||
$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)) {
|
||||
&& array_column($previousDerivatives, 'width') === array_values($expectedWidths)) {
|
||||
$reusable = true;
|
||||
$retry = [];
|
||||
foreach ($previousDerivatives as $derivative) {
|
||||
@@ -65,6 +65,7 @@ class OpportunityImageProcessor
|
||||
}
|
||||
if ($reusable) {
|
||||
$documents = $retry;
|
||||
|
||||
return; // Retry scans of the same streams, without new files, versions or audit decisions.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,17 +11,28 @@ class OpportunityInitiativeApplicability
|
||||
'unit_investment' => ['total_investment', 'currency', 'investment_breakdown', 'secured_financing', 'funding_sought', 'financial_indicators'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $p
|
||||
*/
|
||||
public function enabled(array $p): bool
|
||||
{
|
||||
return ($p['opportunity_category'] ?? null) === 'investment_project'
|
||||
&& in_array($p['initiative']['kind'] ?? null, ['program', 'portfolio'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $p
|
||||
*/
|
||||
public function applicable(array $p, string $group): bool
|
||||
{
|
||||
return ! $this->enabled($p) || ($p['initiative']['applicability'][$group] ?? 'missing') !== 'not_applicable';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @param array<array-key, mixed> $schema
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function schema(array $schema, array $payload): array
|
||||
{
|
||||
$base = &$schema['$defs']['opportunityCreate'];
|
||||
@@ -42,6 +53,7 @@ class OpportunityInitiativeApplicability
|
||||
if (isset($payload['initiative'])) {
|
||||
$base['allOf'][] = ['properties' => ['opportunity_category' => ['const' => 'investment_project']]];
|
||||
}
|
||||
|
||||
return $schema;
|
||||
}
|
||||
$ignored = [];
|
||||
@@ -73,9 +85,14 @@ class OpportunityInitiativeApplicability
|
||||
if (! $this->applicable($payload, 'physical_site')) {
|
||||
unset($base['properties']['locations']['minItems']);
|
||||
}
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $errors
|
||||
* @param array<array-key, mixed> $p
|
||||
*/
|
||||
public function validate(array $p, array &$errors): void
|
||||
{
|
||||
if (! $this->enabled($p)) {
|
||||
@@ -91,4 +108,3 @@ class OpportunityInitiativeApplicability
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -11,12 +12,15 @@ use Illuminate\Support\Facades\Validator;
|
||||
/** An existing opportunity resource references the original document. No binary or permission is copied. */
|
||||
class OpportunityLibrarySupport
|
||||
{
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function choices(User $actor): array
|
||||
{
|
||||
return $this->sources($actor)->orderBy('r.id')->limit(100)->get(['r.id', 'r.title', 'r.version_label', 'r.metadata_version', 'r.published', 'd.sha256'])->all();
|
||||
}
|
||||
|
||||
private function sources(User $actor)
|
||||
private function sources(User $actor): Builder
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
||||
@@ -24,18 +28,21 @@ class OpportunityLibrarySupport
|
||||
->whereIn('d.data_classification', ['internal', 'public'])
|
||||
->when(! $actor->can('manage-portal'), function ($query) use ($actor) {
|
||||
$query->where(function ($scope) use ($actor) {
|
||||
$scope->where(fn ($public) => $public->where('r.published',true)->where('d.data_classification','public')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256'));
|
||||
$scope->where(fn ($public) => $public->where('r.published', true)->where('d.data_classification', 'public')->where('d.status', 'active')->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256'));
|
||||
if ($actor->hasVerifiedEmail()) {
|
||||
$scope->orWhere(fn ($own) => $own->where('r.created_by',$actor->id)->where('d.uploaded_by',$actor->id));
|
||||
$scope->orWhere(fn ($own) => $own->where('r.created_by', $actor->id)->where('d.uploaded_by', $actor->id));
|
||||
}
|
||||
$editorial=app(DocumentManagementAccess::class);
|
||||
$editorial = app(DocumentManagementAccess::class);
|
||||
if ($editorial->editorial($actor)) {
|
||||
$scope->orWhereIn('r.id',$editorial->editorialResources($actor)->select('r.id'));
|
||||
$scope->orWhereIn('r.id', $editorial->editorialResources($actor)->select('r.id'));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function attach(User $actor, Opportunity $opportunity, array $input): \stdClass
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
@@ -45,12 +52,13 @@ class OpportunityLibrarySupport
|
||||
$opportunity = Opportunity::whereKey($opportunity->id)->lockForUpdate()->firstOrFail();
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'edit', $opportunity);
|
||||
$source = $this->sources($actor)->where('r.id', $data['resource_id'])->lockForUpdate()->first(['r.*', 'd.id as original_id', 'd.sha256', 'd.version_no']);
|
||||
abort_unless($source, 403, 'O acesso actual à biblioteca não permite reutilizar este original.');
|
||||
abort_unless($source !== null, 403, 'O acesso actual à biblioteca não permite reutilizar este original.');
|
||||
$existing = DB::table('opportunity_documents')->where('opportunity_id', $opportunity->id)->whereNull('deleted_at')->where('document_id', $source->original_id)->first();
|
||||
if ($existing) {
|
||||
$payload = json_decode($existing->payload, true);
|
||||
abort_unless(($payload['library_source']['resource_id'] ?? null) === $source->id, 409, 'Original já associado por outro percurso; recuperar o suporte existente.');
|
||||
abort_unless(($payload['section'] ?? null) === ($data['section'] ?? null) && ($payload['supported_statement'] ?? null) === ($data['supported_statement'] ?? null), 409, 'Original já associado com outra referência; editar explicitamente o suporte existente.');
|
||||
|
||||
return $existing;
|
||||
}
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($opportunity), $data['etag']), 409, 'A ficha mudou; preserve a selecção e recupere a versão actual.');
|
||||
@@ -71,6 +79,7 @@ class OpportunityLibrarySupport
|
||||
'reason' => Crypt::encryptString($data['reason']), 'snapshot' => Crypt::encryptString(json_encode($after, JSON_THROW_ON_ERROR))])]);
|
||||
$opportunity->management_version++;
|
||||
$opportunity->save();
|
||||
|
||||
return $after;
|
||||
});
|
||||
}
|
||||
@@ -79,19 +88,28 @@ class OpportunityLibrarySupport
|
||||
{
|
||||
$payload = is_string($resource->payload) ? json_decode($resource->payload, true) : $resource->payload;
|
||||
$pin = $payload['library_source'] ?? null;
|
||||
if (! $pin) return;
|
||||
if (! $pin) {
|
||||
return;
|
||||
}
|
||||
$source = DB::table('portal_resources')->where('id', $pin['resource_id'])->first();
|
||||
abort_unless($source && $source->rights_status !== 'restricted' && $document->rights_status !== 'restricted'
|
||||
&& in_array($document->data_classification, ['internal', 'public'], true)
|
||||
&& $document->id === $pin['document_id'] && hash_equals($pin['sha256'], trim($document->sha256)), 403, 'O original está retirado, restrito ou já não corresponde à versão guardada.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function snapshot(User $actor, Opportunity $opportunity): array
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if (! $access->canView($actor, $opportunity)) return [];
|
||||
if (! $access->canView($actor, $opportunity)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect(app(OpportunityResources::class)->listing($opportunity->id, 'documents'))->filter(fn ($r) => ! $r->deleted_at && isset($r->payload['library_source']))->map(function ($r) use ($opportunity) {
|
||||
$pin = $r->payload['library_source'];
|
||||
|
||||
return [...$pin, 'title' => $r->payload['title'], 'support_id' => $r->id, 'support_version' => $r->version,
|
||||
'section' => $r->payload['section'] ?? null, 'opportunity_id' => $opportunity->id,
|
||||
'download_url' => '/minhas-oportunidades/'.$opportunity->id.'/resources/documents/'.$r->id.'/download?source_sha256='.$pin['sha256']];
|
||||
|
||||
@@ -63,7 +63,7 @@ class OpportunityManagement
|
||||
abort_if(array_key_exists('organization_id', $input) && $input['organization_id'] !== $existingRecord->organization_id, 403, 'A organização não pode ser alterada por edição.');
|
||||
}
|
||||
} elseif ($profileCreation) {
|
||||
abort_unless(($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? '') || (isset($input['proactive']) && empty($input['organization_id']) && !$access->has($actor, 'auditor') && $access->internalAssignment($actor, $input['opportunity_category'] ?? '') !== null)), 403);
|
||||
abort_unless(($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? '') || (isset($input['proactive']) && empty($input['organization_id']) && ! $access->has($actor, 'auditor') && $access->internalAssignment($actor, $input['opportunity_category'] ?? '') !== null)), 403);
|
||||
} else {
|
||||
abort_unless($access->legacyWriteAllowed($actor), 403, 'O papel v1 não usa a criação legada para contornar o seu âmbito.');
|
||||
}
|
||||
@@ -128,7 +128,9 @@ class OpportunityManagement
|
||||
$this->check($record, $data['etag']);
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
if (array_key_exists('proactive', $data)) {
|
||||
$data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
}
|
||||
$before = $record->getAttributes();
|
||||
$previousCanonical = $record->exists ? ($this->values($record)['canonical'] ?? []) : [];
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS]));
|
||||
@@ -172,12 +174,12 @@ class OpportunityManagement
|
||||
$record->management_version = 1;
|
||||
$record->estimated_investment_currency = null;
|
||||
if ($profileCreation) {
|
||||
abort_unless(($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? '') || (isset($data['proactive']) && empty($data['organization_id']) && !$access->has($actor, 'auditor') && $access->internalAssignment($actor, $data['opportunity_category'] ?? '') !== null)), 403);
|
||||
abort_unless(($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? '') || (isset($data['proactive']) && empty($data['organization_id']) && ! $access->has($actor, 'auditor') && $access->internalAssignment($actor, $data['opportunity_category'] ?? '') !== null)), 403);
|
||||
$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];
|
||||
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 {
|
||||
@@ -227,7 +229,9 @@ class OpportunityManagement
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->owner_user_id !== null, 403, 'A v1 exige pedido e decisão de arquivo; não concede exclusão ou restauro ao Promotor.');
|
||||
$this->check($record, $data['etag']);
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
if (array_key_exists('proactive', $data)) {
|
||||
$data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
}
|
||||
$before = $record->getAttributes();
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_unless($record->trashed() || $record->status === 'archived', 409, 'Registo não está eliminado/arquivado.');
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Catalogue versions are not interchangeable: historical positions keep their meaning. */
|
||||
@@ -24,7 +26,9 @@ final class OpportunityMaturity
|
||||
|
||||
public const LEGACY_LABELS = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
|
||||
|
||||
/** Public selection is explicit; historical numbers never stand for current stages. */
|
||||
/** Public selection is explicit; historical numbers never stand for current stages.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public static function searchOptions(): array
|
||||
{
|
||||
$options = [];
|
||||
@@ -34,10 +38,14 @@ final class OpportunityMaturity
|
||||
foreach (self::LEGACY_LABELS as $level => $label) {
|
||||
$options[] = ['value' => 'historical:'.$level, 'label' => $label.' — registo histórico', 'group' => 'Classificações históricas'];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public static function constrainSearch(\Illuminate\Database\Eloquent\Builder $query, string $selection): void
|
||||
/**
|
||||
* @param Builder<Opportunity> $query
|
||||
*/
|
||||
public static function constrainSearch(Builder $query, string $selection): void
|
||||
{
|
||||
[$kind, $value] = explode(':', $selection, 2);
|
||||
if ($kind === 'stage') {
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Exceptions\HttpResponseException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -14,16 +16,22 @@ use Illuminate\Validation\Rule;
|
||||
final class OpportunityPromotion
|
||||
{
|
||||
public const PURPOSE = 'promotional_preparation';
|
||||
|
||||
public const NOTICE = 'Em preparação. A divulgação não confirma financiamento, disponibilidade de terreno, licenças ou autorização de execução do investimento.';
|
||||
|
||||
public function allowed(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($record->trashed() || $record->owner_user_id === null || ! $access->canView($actor, $record)
|
||||
|| $access->has($actor, 'auditor') || in_array($record->status, ['archived', 'rejected'], true)) return false;
|
||||
|| $access->has($actor, 'auditor') || in_array($record->status, ['archived', 'rejected'], true)) {
|
||||
return false;
|
||||
}
|
||||
// Never overwrite a normal approved publication or its workflow decisions.
|
||||
if ($record->published_at && data_get($record->workflow_context, 'publication.purpose') !== self::PURPOSE) return false;
|
||||
if ($record->published_at && data_get($record->workflow_context, 'publication.purpose') !== self::PURPOSE) {
|
||||
return false;
|
||||
}
|
||||
$internal = $access->internalAssignment($actor, $record->opportunity_category);
|
||||
|
||||
return ($internal && $access->promoterRecordScope($actor, $record) && $access->operational($actor, 'edit', $record->id))
|
||||
|| ($access->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category)
|
||||
&& $access->operational($actor, 'publish', $record->id));
|
||||
@@ -33,10 +41,13 @@ final class OpportunityPromotion
|
||||
{
|
||||
abort_unless($this->allowed($actor, $record), 403, 'A designação e o âmbito existentes não autorizam esta divulgação.');
|
||||
if (! app(PortalProfileAccess::class)->mfa($actor)) {
|
||||
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(['message' => 'Confirme a entrada normal com MFA recente para divulgar.'], 403)->header('X-Portal-Reauthentication', 'required'));
|
||||
throw new HttpResponseException(response()->json(['message' => 'Confirme a entrada normal com MFA recente para divulgar.'], 403)->header('X-Portal-Reauthentication', 'required'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function editor(User $actor, Opportunity $record): array
|
||||
{
|
||||
abort_unless($this->allowed($actor, $record), 403);
|
||||
@@ -47,15 +58,20 @@ final class OpportunityPromotion
|
||||
'description' => $existing ? $record->description : '', 'source_reference' => '', 'edition' => '', 'source_date' => '',
|
||||
'limitations' => '', 'territory_ids' => $existing ? DB::table('opportunity_locations')->where('opportunity_id', $record->id)->pluck('geo_location_id')->all() : [],
|
||||
'sector_id' => $record->sector_id];
|
||||
|
||||
return ['record' => ['id' => $record->id, 'reference' => $record->reference], 'etag' => app(OpportunityManagement::class)->etag($record),
|
||||
'proactiveRelations' => app(ProactiveInvestment::class)->publicationRelations($record), 'proactiveKind' => app(OpportunityManagement::class)->values($record)['proactive']['kind'] ?? null, 'proactiveEnabled' => isset(app(OpportunityManagement::class)->values($record)['proactive']), 'proactiveEvidence' => array_values(array_filter(app(OpportunityManagement::class)->values($record)['proactive']['evidence'] ?? [], fn ($e) => $e['access'] === 'public')), 'proactiveOptions' => app(ProactiveInvestment::class)->options(), 'initial' => [...$form, ...($saved['input']['proactive_public'] ?? null ? ['proactive_public' => $saved['input']['proactive_public']] : [])], 'publicNow' => $existing && $record->status === 'published',
|
||||
'reauthenticationRequired' => ! app(PortalProfileAccess::class)->mfa($actor),
|
||||
'sectors' => \App\Models\Sector::catalog()->orderBy('name')->get(['id', 'name']),
|
||||
'sectors' => Sector::catalog()->orderBy('name')->get(['id', 'name']),
|
||||
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type']),
|
||||
'history' => DB::table('audit_events')->where('source_system', 'tempo-preparation-publication')
|
||||
->where('after_data->record_id', $record->id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at'])];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor, Opportunity $record, array $input): array
|
||||
{
|
||||
$this->authorize($actor, $record);
|
||||
@@ -64,11 +80,13 @@ final class OpportunityPromotion
|
||||
'description' => 'nullable|string|max:6000', 'limitations' => 'nullable|string|max:2500',
|
||||
'source_reference' => 'nullable|string|max:2000', 'edition' => 'nullable|string|max:150', 'source_date' => 'nullable|date_format:Y-m-d',
|
||||
'proactive_public' => 'sometimes|array', 'proactive_reviewed' => 'sometimes|boolean',
|
||||
'sector_id' => ['nullable', 'integer', Rule::in(\App\Models\Sector::catalog()->pluck('id')->all())],
|
||||
'sector_id' => ['nullable', 'integer', Rule::in(Sector::catalog()->pluck('id')->all())],
|
||||
'territory_ids' => 'sometimes|array|max:30', 'territory_ids.*' => 'required|uuid|distinct',
|
||||
])->validate();
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409, 'A ficha mudou. Reabra antes de preparar outra prévia.');
|
||||
if ($data['action'] === 'withdraw') abort_unless(data_get($record->workflow_context, 'publication.purpose') === self::PURPOSE, 409);
|
||||
if ($data['action'] === 'withdraw') {
|
||||
abort_unless(data_get($record->workflow_context, 'publication.purpose') === self::PURPOSE, 409);
|
||||
}
|
||||
$paths = [];
|
||||
foreach ($data['territory_ids'] ?? [] as $id) {
|
||||
$path = app(InvestmentGeography::class)->path($id, true);
|
||||
@@ -84,22 +102,38 @@ final class OpportunityPromotion
|
||||
$projection = ['title' => $text('title'), 'summary' => $text('summary'), 'description' => $body,
|
||||
'sector_id' => $data['sector_id'] ?? null, 'maturity_label' => 'Em preparação', 'notice' => self::NOTICE,
|
||||
'territories' => array_map(fn ($p) => ['id' => end($p)->id, 'label' => implode(' / ', array_column($p, 'name'))], $paths)];
|
||||
if ($data['action'] === 'disclose' && ($proactive = app(ProactiveInvestment::class)->publication($record, $data))) { $projection['proactive'] = $proactive; $projection['description'] .= "\n\n".implode("\n", [$proactive['group'] === 'ideas' ? 'Ideia em preparação' : ($proactive['group'] === 'needs' ? 'Necessidade — '.$proactive['state'] : 'O que existe'), 'Necessidade: '.$proactive['need'], 'Proposta: '.$proactive['proposal'], 'Fundamento: '.$proactive['basis'], 'Limitações: '.$proactive['limitations'], 'Próximo passo: '.$proactive['next_action'], ProactiveInvestment::NOTICE]); }
|
||||
if ($data['action'] === 'disclose') abort_unless($projection['title'] !== '' && $projection['summary'] !== '', 422, 'Indique título e resumo em texto simples.');
|
||||
if ($data['action'] === 'withdraw') $projection = [...$projection, ...$record->only(['title', 'summary', 'description', 'sector_id', 'maturity_label'])];
|
||||
if ($data['action'] === 'disclose' && ($proactive = app(ProactiveInvestment::class)->publication($record, $data))) {
|
||||
$projection['proactive'] = $proactive;
|
||||
$projection['description'] .= "\n\n".implode("\n", [$proactive['group'] === 'ideas' ? 'Ideia em preparação' : ($proactive['group'] === 'needs' ? 'Necessidade — '.$proactive['state'] : 'O que existe'), 'Necessidade: '.$proactive['need'], 'Proposta: '.$proactive['proposal'], 'Fundamento: '.$proactive['basis'], 'Limitações: '.$proactive['limitations'], 'Próximo passo: '.$proactive['next_action'], ProactiveInvestment::NOTICE]);
|
||||
}
|
||||
if ($data['action'] === 'disclose') {
|
||||
abort_unless($projection['title'] !== '' && $projection['summary'] !== '', 422, 'Indique título e resumo em texto simples.');
|
||||
}
|
||||
if ($data['action'] === 'withdraw') {
|
||||
$projection = [...$projection, ...$record->only(['title', 'summary', 'description', 'sector_id', 'maturity_label'])];
|
||||
}
|
||||
$payload = ['actor_id' => $actor->id, 'record_id' => $record->id, 'etag' => $data['etag'], 'action' => $data['action'],
|
||||
'input' => $data, 'projection' => $projection, 'expires' => now()->addMinutes(15)->timestamp];
|
||||
|
||||
return ['action' => $data['action'], 'projection' => $projection, 'token' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
|
||||
'current' => $record->only(['title', 'summary', 'description', 'status']), 'writes' => false];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function confirm(User $actor, int $id, array $input): array
|
||||
{
|
||||
$data = Validator::make($input, ['token' => 'required|string|max:300000', 'operation_key' => 'required|uuid',
|
||||
'confirm' => 'required|accepted', 'reason' => 'required|string|min:10|max:1000'])->validate();
|
||||
try { $preview = json_decode(Crypt::decryptString($data['token']), true, flags: JSON_THROW_ON_ERROR); }
|
||||
catch (\Throwable) { abort(422, 'Prévia inválida. Prepare outra prévia.'); }
|
||||
try {
|
||||
$preview = json_decode(Crypt::decryptString($data['token']), true, flags: JSON_THROW_ON_ERROR);
|
||||
} catch (\Throwable) {
|
||||
abort(422, 'Prévia inválida. Prepare outra prévia.');
|
||||
}
|
||||
abort_unless(($preview['actor_id'] ?? null) === $actor->id && ($preview['record_id'] ?? null) === $id, 403);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $preview) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['promotional-operation:'.$data['operation_key']]);
|
||||
$record = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
@@ -110,6 +144,7 @@ final class OpportunityPromotion
|
||||
if ($replay) {
|
||||
$prior = json_decode($replay->after_data, true);
|
||||
abort_unless($prior['record_id'] === $id && (int) $replay->actor_user_id === $actor->id && hash_equals($prior['request_hash'], $digest), 409, 'Chave usada noutra operação.');
|
||||
|
||||
return ['id' => $id, 'replayed' => true, 'message' => 'Operação já registada; nenhuma alteração repetida.'];
|
||||
}
|
||||
abort_unless(($preview['expires'] ?? 0) >= now()->timestamp, 409, 'A prévia expirou. Prepare outra prévia.');
|
||||
@@ -124,7 +159,9 @@ final class OpportunityPromotion
|
||||
$action = 'promotional_summary_withdrawn';
|
||||
} else {
|
||||
$p = $preview['projection'];
|
||||
if ($p['sector_id'] !== null) abort_unless(\App\Models\Sector::catalog()->whereKey($p['sector_id'])->exists(), 409, 'O sector deixou de estar disponível no catálogo. Prepare outra prévia.');
|
||||
if ($p['sector_id'] !== null) {
|
||||
abort_unless(Sector::catalog()->whereKey($p['sector_id'])->exists(), 409, 'O sector deixou de estar disponível no catálogo. Prepare outra prévia.');
|
||||
}
|
||||
$paths = [];
|
||||
foreach ($preview['input']['territory_ids'] ?? [] as $territory) {
|
||||
$path = app(InvestmentGeography::class)->path($territory, true);
|
||||
@@ -141,15 +178,21 @@ final class OpportunityPromotion
|
||||
$context['publication'] = ['visibility' => 'public', 'purpose' => self::PURPOSE, 'actor_id' => $actor->id,
|
||||
'at' => now()->toIso8601String(), 'execution_approved' => false, 'private_draft_preserved' => true];
|
||||
$action = data_get($before, 'status') === 'published' ? 'promotional_summary_updated' : 'promotional_summary_published';
|
||||
foreach (['title', 'summary', 'description', 'sector_id', 'maturity_label'] as $field) $record->{$field} = $p[$field];
|
||||
foreach (['promoter_name', 'promoter_type', 'financing_modality', 'expected_impact', 'maturity_level', 'estimated_investment_amount', 'estimated_investment_currency'] as $field) $record->{$field} = null;
|
||||
foreach (['title', 'summary', 'description', 'sector_id', 'maturity_label'] as $field) {
|
||||
$record->{$field} = $p[$field];
|
||||
}
|
||||
foreach (['promoter_name', 'promoter_type', 'financing_modality', 'expected_impact', 'maturity_level', 'estimated_investment_amount', 'estimated_investment_currency'] as $field) {
|
||||
$record->{$field} = null;
|
||||
}
|
||||
$main = $paths[0] ?? [];
|
||||
$record->primary_territory_id = $main ? end($main)->id : null;
|
||||
$record->province = collect($main)->firstWhere('location_type', 'province')?->name;
|
||||
$record->district = collect($main)->firstWhere('location_type', 'district')?->name;
|
||||
$record->geography_scope = count($paths) > 1 ? 'multiple' : ($main ? 'specific' : 'unspecified');
|
||||
DB::table('opportunity_locations')->where('opportunity_id', $id)->delete();
|
||||
foreach ($preview['input']['territory_ids'] ?? [] as $territory) DB::table('opportunity_locations')->insert(['opportunity_id' => $id, 'geo_location_id' => $territory]);
|
||||
foreach ($preview['input']['territory_ids'] ?? [] as $territory) {
|
||||
DB::table('opportunity_locations')->insert(['opportunity_id' => $id, 'geo_location_id' => $territory]);
|
||||
}
|
||||
$record->status = 'published';
|
||||
$record->is_featured = false;
|
||||
$record->last_validated_at = null;
|
||||
@@ -164,6 +207,7 @@ final class OpportunityPromotion
|
||||
'after_data' => json_encode(['record_id' => $id, 'operation_key' => $data['operation_key'], 'request_hash' => $digest,
|
||||
'reason' => $data['reason'], 'projection' => $preview['projection'], 'execution_approved' => false,
|
||||
'record' => $record->getRawOriginal()], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return ['id' => $id, 'replayed' => false, 'message' => $preview['action'] === 'withdraw' ? 'Resumo retirado; cadastro e histórico preservados.' : 'Resumo divulgado como Em preparação. Não autoriza execução do investimento.'];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@ final class OpportunityPublicText
|
||||
public static function description(Opportunity $record, string $text): string
|
||||
{
|
||||
$source = data_get($record->workflow_context, 'corridor_agribusiness');
|
||||
if (! is_array($source) || ($source['source_sha256'] ?? null) !== CorridorAgribusinessOpportunities::SOURCE_HASH) return $text;
|
||||
if (! is_array($source) || ($source['source_sha256'] ?? null) !== CorridorAgribusinessOpportunities::SOURCE_HASH) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
$hash = CorridorAgribusinessOpportunities::SOURCE_HASH;
|
||||
$sourceLine = 'Fonte: '.$source['source'].'; SHA-256 '.$hash;
|
||||
@@ -20,13 +22,20 @@ final class OpportunityPublicText
|
||||
$paragraph = trim($paragraph);
|
||||
if (in_array($paragraph, [$sourceLine, $sourceLine.'.', 'Edição: Não indicada.', 'Data-base: Não indicada.',
|
||||
'Limitações e lacunas: '.CorridorAgribusinessOpportunities::LIMITATIONS,
|
||||
OpportunityPromotion::NOTICE], true)) continue;
|
||||
if ($paragraph === 'Enquadramento documental: '.$source['corridor'].'.') $paragraph = $source['corridor'].'.';
|
||||
OpportunityPromotion::NOTICE], true)) {
|
||||
continue;
|
||||
}
|
||||
if ($paragraph === 'Enquadramento documental: '.$source['corridor'].'.') {
|
||||
$paragraph = $source['corridor'].'.';
|
||||
}
|
||||
if ($paragraph === CorridorAgribusinessOpportunities::LIMITATIONS) {
|
||||
$paragraph = 'A localização exacta, a disponibilidade de terreno e as condições do investimento serão definidas durante a preparação do projecto.';
|
||||
}
|
||||
if ($paragraph !== '') $result[] = $paragraph;
|
||||
if ($paragraph !== '') {
|
||||
$result[] = $paragraph;
|
||||
}
|
||||
}
|
||||
|
||||
return implode("\n\n", $result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,22 +7,33 @@ use App\Models\Opportunity;
|
||||
/** Read-only presentation of existing references. Does not reconcile, confirm or save data. */
|
||||
class OpportunityTerritorialPresentation
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $locations
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function describe(Opportunity $record, array $locations): array
|
||||
{
|
||||
$path = array_values(array_filter(app(InvestmentGeography::class)->path($record->primary_territory_id, true), fn ($node) => in_array($node->location_type, ['province', 'district', 'admin_post', 'locality'], true)));
|
||||
$mainIds = array_column($path, 'id', 'location_type');
|
||||
$differences = [];
|
||||
foreach ($locations as $location) {
|
||||
if ($location->deleted_at || empty($location->payload['is_primary']) || !$path) continue;
|
||||
if ($location->deleted_at || empty($location->payload['is_primary']) || ! $path) {
|
||||
continue;
|
||||
}
|
||||
$p = $location->payload;
|
||||
$different = false;
|
||||
foreach ($mainIds as $level => $id) if (!empty($p[$level.'_id']) && $p[$level.'_id'] !== $id) $different = true;
|
||||
$foreign = !empty($p['country_code']) && $p['country_code'] !== 'MZ';
|
||||
foreach ($mainIds as $level => $id) {
|
||||
if (! empty($p[$level.'_id']) && $p[$level.'_id'] !== $id) {
|
||||
$different = true;
|
||||
}
|
||||
}
|
||||
$foreign = ! empty($p['country_code']) && $p['country_code'] !== 'MZ';
|
||||
if ($foreign || $different) {
|
||||
$differences[] = ['resource_id' => $location->id, 'title' => $p['title'] ?? 'Localização sem título',
|
||||
$differences[] = ['resource_id' => data_get($location, 'id'), 'title' => $p['title'] ?? 'Localização sem título',
|
||||
'message' => 'A referência principal da ficha e esta localização documentada apontam para territórios diferentes. Confirme se a distinção é intencional; nenhum valor foi substituído.'];
|
||||
}
|
||||
}
|
||||
|
||||
return ['path' => $path, 'differences' => $differences];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,95 +11,131 @@ use Illuminate\Validation\Rule;
|
||||
/** Owner-directed staff assignments use existing identities, organizations and grants. */
|
||||
class PortalInternalDesignation
|
||||
{
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
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();
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
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']];
|
||||
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
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
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){
|
||||
$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.'];
|
||||
$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.'];
|
||||
$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]);
|
||||
$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']);
|
||||
} 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.'];
|
||||
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
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
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){
|
||||
$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::whereKey($v['user_id'])->firstOrFail();
|
||||
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]);
|
||||
$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;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Additive installation and separate, explicit bootstrap. No identities are inferred. */
|
||||
class PortalProfileInstallation
|
||||
@@ -33,6 +34,7 @@ class PortalProfileInstallation
|
||||
return false;
|
||||
}
|
||||
$target = config('portal_profiles.bootstrap_designated_database', '');
|
||||
|
||||
return $target !== '' && DB::selectOne('SELECT current_database() AS database')->database === $target;
|
||||
}
|
||||
|
||||
@@ -134,40 +136,47 @@ class PortalProfileInstallation
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
|
||||
public function bootstrap(User $actor, array $input): array
|
||||
{
|
||||
$this->authorize($actor, true, 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();
|
||||
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['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']);
|
||||
$second = User::whereKey($data['second_user_id'])->firstOrFail();
|
||||
if ($this->designatedBootstrap($actor)) {
|
||||
abort_unless($this->designatedBootstrap($second), 403, 'Use os dois titulares expressamente designados para este destino.');
|
||||
}
|
||||
foreach ([$actor, $second] as $user) app(PortalSuperusers::class)->validateBootstrapHolder($user);
|
||||
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();
|
||||
$id = (string) 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. */
|
||||
/** Purpose-specific view; designation grants no general management access.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
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.');
|
||||
abort_unless($row !== null, 404);
|
||||
if (! (in_array($actor->id, [(int) $row->requested_by, (int) $row->subject_user_id], true))) {
|
||||
abort(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');
|
||||
@@ -178,9 +187,14 @@ class PortalProfileInstallation
|
||||
'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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function confirmBootstrap(User $actor, string $id, array $input): array
|
||||
{
|
||||
$view = $this->bootstrapPreview($actor, $id);
|
||||
@@ -188,12 +202,13 @@ class PortalProfileInstallation
|
||||
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);
|
||||
$first = User::whereKey($row->requested_by)->firstOrFail();
|
||||
$this->authorize($first, false, true);
|
||||
$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.');
|
||||
@@ -205,6 +220,7 @@ class PortalProfileInstallation
|
||||
} finally {
|
||||
config(['portal_profiles.bootstrap_authorized' => false]);
|
||||
}
|
||||
|
||||
return ['initialized' => true, 'approval_id' => $id, 'holders' => [$first->id, $actor->id], 'version' => 1, 'flags_changed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -26,7 +27,6 @@ class PortalSuperusers
|
||||
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.');
|
||||
@@ -44,7 +44,9 @@ class PortalSuperusers
|
||||
{
|
||||
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);
|
||||
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)');
|
||||
@@ -123,7 +125,7 @@ class PortalSuperusers
|
||||
$this->administration->administrative($actor);
|
||||
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);
|
||||
$record = $recordId === null ? null : 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();
|
||||
|
||||
@@ -22,6 +22,9 @@ final class PrivateInvestmentPreparation
|
||||
return (bool) config('investor-path.private_preparation', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function questions(): array
|
||||
{
|
||||
$tri = ['unknown' => 'Por determinar', 'yes' => 'Sim', 'no' => 'Não'];
|
||||
@@ -44,6 +47,9 @@ final class PrivateInvestmentPreparation
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $f
|
||||
*/
|
||||
private function number(array $f, string $key): ?BigDecimal
|
||||
{
|
||||
$value = $f[$key] ?? '';
|
||||
@@ -51,19 +57,47 @@ final class PrivateInvestmentPreparation
|
||||
return is_scalar($value) && preg_match('/^\d+(?:\.\d+)?$/D', (string) $value) ? BigDecimal::of((string) $value) : null;
|
||||
}
|
||||
|
||||
/** @param array<array-key, mixed> $fields
|
||||
* @param list<string> $missing
|
||||
*/
|
||||
private function answer(array $fields, string $key, array &$missing): ?bool
|
||||
{
|
||||
$value = $fields[$key] ?? null;
|
||||
if ($value === 'yes') {
|
||||
return true;
|
||||
}
|
||||
if ($value === 'no') {
|
||||
return false;
|
||||
}
|
||||
$missing[] = $key;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @param array<string, bool|null> $triggers
|
||||
* @return list<string>
|
||||
*/
|
||||
private function triggerReasons(array $triggers): array
|
||||
{
|
||||
$reasons = [];
|
||||
foreach (['amount' => 'Valor superior a 32 mil milhões MZN — R13(2), R21(2)(a)', 'project_concession' => 'PPP/concessão empresarial — Lei 8/2023, art. 22(1)(b)(ii), R21(2)(b)', 'significant_implications' => 'Implicações significativas declaradas — Lei 8/2023, art. 22(1)(b)(i), R21(1)', 'land_extension' => 'Extensão de terra igual/superior a 10 mil hectares — Lei 8/2023, art. 22(1)(b)(iii), R21(2)(c)', 'forest_concession' => 'Concessão florestal superior a 100 mil hectares — Lei 8/2023, art. 22(1)(b)(iv), R21(2)(d)'] as $condition => $description) {
|
||||
if (($triggers[$condition] ?? null) === true) {
|
||||
$reasons[] = $description.'.';
|
||||
}
|
||||
}
|
||||
|
||||
return $reasons;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @param array<array-key, mixed> $documents
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function assess(array $context, array $documents = []): array
|
||||
{
|
||||
$f = $context['fields'] ?? [];
|
||||
$missing = [];
|
||||
$answer = function (string $key) use ($f, &$missing): ?bool {
|
||||
if (! in_array($f[$key] ?? '', ['yes', 'no'], true)) {
|
||||
$missing[] = $key;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $f[$key] === 'yes';
|
||||
};
|
||||
$enabled = ($f['investment_preparation'] ?? '') === 'yes';
|
||||
$date = $f['expected_start_date'] ?? '';
|
||||
$period = preg_match('/^2026-\d{2}-\d{2}$/D', $date) === 1;
|
||||
@@ -102,9 +136,9 @@ final class PrivateInvestmentPreparation
|
||||
$reasons[] = 'A condição monetária não é determinada noutra moeda: não se fez conversão.';
|
||||
}
|
||||
foreach (['project_concession', 'significant_implications'] as $key) {
|
||||
$triggers[$key] = $answer($key);
|
||||
$triggers[$key] = $this->answer($f, $key, $missing);
|
||||
}
|
||||
$land = $answer('land_extension');
|
||||
$land = $this->answer($f, 'land_extension', $missing);
|
||||
if ($land === true) {
|
||||
$area = $this->number($f, 'area_required');
|
||||
$unit = $f['area_unit'] ?? '';
|
||||
@@ -117,7 +151,7 @@ final class PrivateInvestmentPreparation
|
||||
} else {
|
||||
$triggers['land_extension'] = $land;
|
||||
}
|
||||
$forest = $answer('forest_concession');
|
||||
$forest = $this->answer($f, 'forest_concession', $missing);
|
||||
if ($forest === true) {
|
||||
$area = $this->number($f, 'forest_concession_hectares');
|
||||
if (! $area) {
|
||||
@@ -126,11 +160,7 @@ final class PrivateInvestmentPreparation
|
||||
} else {
|
||||
$triggers['forest_concession'] = $forest;
|
||||
}
|
||||
foreach (['amount' => 'Valor superior a 32 mil milhões MZN — R13(2), R21(2)(a)', 'project_concession' => 'PPP/concessão empresarial — Lei 8/2023, art. 22(1)(b)(ii), R21(2)(b)', 'significant_implications' => 'Implicações significativas declaradas — Lei 8/2023, art. 22(1)(b)(i), R21(1)', 'land_extension' => 'Extensão de terra igual/superior a 10 mil hectares — Lei 8/2023, art. 22(1)(b)(iii), R21(2)(c)', 'forest_concession' => 'Concessão florestal superior a 100 mil hectares — Lei 8/2023, art. 22(1)(b)(iv), R21(2)(d)'] as $condition => $description) {
|
||||
if (($triggers[$condition] ?? null) === true) {
|
||||
$reasons[] = $description.'.';
|
||||
}
|
||||
}
|
||||
$reasons = [...$reasons, ...$this->triggerReasons($triggers)];
|
||||
$mode = in_array(true, $triggers, true) ? 'authorization' : (in_array(null, $triggers, true) ? 'indeterminate' : 'registration');
|
||||
$reasons[] = $mode === 'authorization' ? 'Foi identificada uma condição de autorização; as restantes condições desconhecidas não foram presumidas negativas.' : ($mode === 'registration' ? 'As condições de autorização deste lote foram declaradas negativas e o montante não ultrapassa o limite.' : 'Falta resolver pelo menos uma condição de autorização.');
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\User;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
@@ -13,33 +15,39 @@ use Illuminate\Validation\ValidationException;
|
||||
final class ProactiveInvestment
|
||||
{
|
||||
public const VERSION = 1;
|
||||
|
||||
public const NOTICE = 'A ausência de registo não comprova ausência de oferta. Proximidade não comprova contrato, participação, energia acessível, terra disponível ou benefício fiscal. Necessidade confirmada não comprova viabilidade comercial; hipótese de fornecimento não é encomenda.';
|
||||
|
||||
public const GROUPS = ['exists' => 'O que existe', 'needs' => 'Necessidades identificadas', 'ideas' => 'Ideias de investimento'];
|
||||
|
||||
public function draft(array $input, ?Opportunity $record = null, ?\App\Models\User $actor = null): array
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function draft(array $input, ?Opportunity $record = null, ?User $actor = null): array
|
||||
{
|
||||
$d = Validator::make(['proactive' => $input], [
|
||||
'proactive' => 'required|array:version,kind,evidence,need,idea,relations,supply_comparisons', 'proactive.version' => 'required|integer|in:1',
|
||||
'proactive.kind' => 'required|in:exists,needs,ideas', 'proactive.evidence' => 'present|array|max:60',
|
||||
'proactive.evidence.*' => 'array:id,category,purpose,statement,interpretation,source,locator,period,scope,coverage,verified_on,access,document_id,observation_id',
|
||||
'proactive.evidence.*.observation_id'=>'sometimes|nullable|string|size:64',
|
||||
'proactive.supply_comparisons'=>'sometimes|array|max:40',
|
||||
'proactive.evidence.*.observation_id' => 'sometimes|nullable|string|size:64',
|
||||
'proactive.supply_comparisons' => 'sometimes|array|max:40',
|
||||
'proactive.evidence.*.id' => 'required|uuid|distinct',
|
||||
'proactive.evidence.*.category' => 'required|in:activity,resource,infrastructure,supply,demand',
|
||||
'proactive.evidence.*.purpose' => 'required|in:local,methodology',
|
||||
'proactive.evidence.*.access' => 'required|in:internal,public',
|
||||
'proactive.evidence.*.document_id' => 'nullable|uuid',
|
||||
'proactive.evidence.*.verified_on' => 'nullable|date_format:Y-m-d|before_or_equal:today',
|
||||
...collect(['statement','interpretation','source','locator','period','scope','coverage'])->mapWithKeys(fn ($k) => ['proactive.evidence.*.'.$k => 'present|nullable|string|max:4000'])->all(),
|
||||
...collect(['statement', 'interpretation', 'source', 'locator', 'period', 'scope', 'coverage'])->mapWithKeys(fn ($k) => ['proactive.evidence.*.'.$k => 'present|nullable|string|max:4000'])->all(),
|
||||
'proactive.need' => 'required|array:state,problem,observed_supply,observed_demand,type,clients,evidence_ids,limitations,missing,confirmation',
|
||||
'proactive.need.state' => 'required|in:hypothesis,confirmed',
|
||||
'proactive.need.type' => 'nullable|in:quantity,quality,logistics,processing,coordination,support',
|
||||
...collect(['problem','observed_supply','observed_demand','clients','limitations','missing','confirmation'])->mapWithKeys(fn ($k) => ['proactive.need.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
...collect(['problem', 'observed_supply', 'observed_demand', 'clients', 'limitations', 'missing', 'confirmation'])->mapWithKeys(fn ($k) => ['proactive.need.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
'proactive.need.evidence_ids' => 'present|array|max:60', 'proactive.need.evidence_ids.*' => 'uuid|distinct',
|
||||
'proactive.idea' => 'required|array:solution,activity,chain_id,stage,coverage,mode,resources,assumptions,conditions,pending,next_action',
|
||||
'proactive.idea.chain_id' => ['nullable','uuid',Rule::exists('value_chains','id')->whereNull('deleted_at')],
|
||||
'proactive.idea.chain_id' => ['nullable', 'uuid', Rule::exists('value_chains', 'id')->whereNull('deleted_at')],
|
||||
'proactive.idea.mode' => 'nullable|in:create,expand,associate',
|
||||
...collect(['solution','activity','stage','coverage','resources','assumptions','conditions','pending','next_action'])->mapWithKeys(fn ($k) => ['proactive.idea.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
...collect(['solution', 'activity', 'stage', 'coverage', 'resources', 'assumptions', 'conditions', 'pending', 'next_action'])->mapWithKeys(fn ($k) => ['proactive.idea.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
'proactive.relations' => 'present|array|max:40',
|
||||
'proactive.relations.*' => 'array:id,kind,target_id,relation,reference,evidence_ids',
|
||||
'proactive.relations.*.id' => 'required|uuid|distinct',
|
||||
@@ -49,144 +57,220 @@ final class ProactiveInvestment
|
||||
'proactive.relations.*.reference' => 'required|string|max:4000',
|
||||
'proactive.relations.*.evidence_ids' => 'present|array|max:60', 'proactive.relations.*.evidence_ids.*' => 'uuid|distinct',
|
||||
])->validate()['proactive'];
|
||||
$actor??=auth()->user();
|
||||
if (!empty($d['supply_comparisons'])) $d['supply_comparisons']=app(ProactiveSupply::class)->comparisons($actor,$d['supply_comparisons'],$record);
|
||||
foreach($d['evidence'] as &$proof){
|
||||
if(!empty($proof['observation_id'])){
|
||||
$canonical=app(ProactiveSupply::class)->evidence($actor,$proof['observation_id'],$record);
|
||||
if($proof['access']!=='internal') $this->fail('evidence','A observação da base interna não pode ser reclassificada como pública.');
|
||||
$proof=array_replace($proof,$canonical);
|
||||
$actor ??= auth()->user();
|
||||
if (! empty($d['supply_comparisons'])) {
|
||||
$d['supply_comparisons'] = app(ProactiveSupply::class)->comparisons($actor, $d['supply_comparisons'], $record);
|
||||
}
|
||||
foreach ($d['evidence'] as &$proof) {
|
||||
if (! empty($proof['observation_id'])) {
|
||||
$canonical = app(ProactiveSupply::class)->evidence($actor, $proof['observation_id'], $record);
|
||||
if ($proof['access'] !== 'internal') {
|
||||
$this->fail('evidence', 'A observação da base interna não pode ser reclassificada como pública.');
|
||||
}
|
||||
$proof = array_replace($proof, $canonical);
|
||||
}
|
||||
}
|
||||
unset($proof);
|
||||
foreach($d['supply_comparisons']??[] as $comparison){
|
||||
if(!in_array($comparison['observation_id'],array_column($d['evidence'],'observation_id'),true))$this->fail('supply_comparisons','A comparação deve conservar a evidência interna da observação seleccionada.');
|
||||
foreach ($d['supply_comparisons'] ?? [] as $comparison) {
|
||||
if (! in_array($comparison['observation_id'], array_column($d['evidence'], 'observation_id'), true)) {
|
||||
$this->fail('supply_comparisons', 'A comparação deve conservar a evidência interna da observação seleccionada.');
|
||||
}
|
||||
}
|
||||
$ids = array_column($d['evidence'], 'id');
|
||||
foreach ([$d['need'], ...$d['relations']] as $row) {
|
||||
if (array_diff($row['evidence_ids'], $ids)) $this->fail('evidence', 'Seleccione apenas evidências desta análise.');
|
||||
if (array_diff($row['evidence_ids'], $ids)) {
|
||||
$this->fail('evidence', 'Seleccione apenas evidências desta análise.');
|
||||
}
|
||||
}
|
||||
$seen = [];
|
||||
foreach ($d['evidence'] as $e) {
|
||||
$key = mb_strtolower(trim(($e['source'] ?? '').'|'.($e['locator'] ?? '').'|'.($e['statement'] ?? '')));
|
||||
if (trim($key, '| ') !== '' && isset($seen[$key])) $this->fail('evidence', 'A mesma evidência já foi registada; edite a entrada existente.');
|
||||
if (trim($key, '| ') !== '' && isset($seen[$key])) {
|
||||
$this->fail('evidence', 'A mesma evidência já foi registada; edite a entrada existente.');
|
||||
}
|
||||
$seen[$key] = true;
|
||||
if (! empty($e['document_id'])) $this->document($record, $e['document_id'], $e['access'] === 'public');
|
||||
if (! empty($e['document_id'])) {
|
||||
$this->document($record, $e['document_id'], $e['access'] === 'public');
|
||||
}
|
||||
}
|
||||
$seen = [];
|
||||
foreach ($d['relations'] as $row) {
|
||||
$target = app(OpportunityClassification::class)->targets($row['kind'])->where('id', $row['target_id'])->exists();
|
||||
if (! $target) $this->fail('relations', 'Referência existente indisponível; não foi criada outra empresa, zona ou estrutura.');
|
||||
if (! $target) {
|
||||
$this->fail('relations', 'Referência existente indisponível; não foi criada outra empresa, zona ou estrutura.');
|
||||
}
|
||||
$key = $row['kind'].'|'.$row['target_id'];
|
||||
if (isset($seen[$key])) $this->fail('relations', 'A referência já está nesta análise; reúna o fundamento na entrada existente.');
|
||||
if (isset($seen[$key])) {
|
||||
$this->fail('relations', 'A referência já está nesta análise; reúna o fundamento na entrada existente.');
|
||||
}
|
||||
$seen[$key] = true;
|
||||
if ($row['relation'] === 'documented' && ! $row['evidence_ids']) $this->fail('relations', 'Relação documentada exige evidência seleccionada; mantenha hipótese ou proximidade quando não demonstrada.');
|
||||
if ($row['relation'] === 'documented' && ! $row['evidence_ids']) {
|
||||
$this->fail('relations', 'Relação documentada exige evidência seleccionada; mantenha hipótese ou proximidade quando não demonstrada.');
|
||||
}
|
||||
}
|
||||
if ($d['kind'] !== 'exists' && $d['need']['state'] === 'confirmed') {
|
||||
foreach (['problem','observed_supply','observed_demand','type','clients','confirmation'] as $field) {
|
||||
if (trim($d['need'][$field] ?? '') === '') $this->fail('need.'.$field, 'Confirmação exige observação e fundamento concretos; pode guardar como hipótese.');
|
||||
foreach (['problem', 'observed_supply', 'observed_demand', 'type', 'clients', 'confirmation'] as $field) {
|
||||
if (trim($d['need'][$field] ?? '') === '') {
|
||||
$this->fail('need.'.$field, 'Confirmação exige observação e fundamento concretos; pode guardar como hipótese.');
|
||||
}
|
||||
}
|
||||
if (! $d['need']['evidence_ids']) {
|
||||
$this->fail('need.evidence_ids', 'Uma hipótese não é confirmada sem evidência seleccionada.');
|
||||
}
|
||||
if (! $d['need']['evidence_ids']) $this->fail('need.evidence_ids', 'Uma hipótese não é confirmada sem evidência seleccionada.');
|
||||
foreach ($d['evidence'] as $e) {
|
||||
if (! in_array($e['id'], $d['need']['evidence_ids'], true)) continue;
|
||||
if ($e['purpose'] !== 'local') $this->fail('need.evidence_ids', 'Uma referência metodológica internacional não confirma oferta ou procura local. Preserve a hipótese e recolha evidência local.');
|
||||
foreach (['statement','source','locator','period','scope','coverage','verified_on'] as $field) {
|
||||
if (trim($e[$field] ?? '') === '') $this->fail('evidence', 'Evidência da necessidade confirmada: faltam facto, fonte, localizador, período, abrangência, cobertura ou data de verificação.');
|
||||
if (! in_array($e['id'], $d['need']['evidence_ids'], true)) {
|
||||
continue;
|
||||
}
|
||||
if ($e['purpose'] !== 'local') {
|
||||
$this->fail('need.evidence_ids', 'Uma referência metodológica internacional não confirma oferta ou procura local. Preserve a hipótese e recolha evidência local.');
|
||||
}
|
||||
foreach (['statement', 'source', 'locator', 'period', 'scope', 'coverage', 'verified_on'] as $field) {
|
||||
if (trim($e[$field] ?? '') === '') {
|
||||
$this->fail('evidence', 'Evidência da necessidade confirmada: faltam facto, fonte, localizador, período, abrangência, cobertura ou data de verificação.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $d;
|
||||
}
|
||||
|
||||
private function document(?Opportunity $record, string $id, bool $public): void
|
||||
{
|
||||
$row = $record?->exists ? DB::table('opportunity_documents as link')->join('documents as d','d.id','=','link.document_id')
|
||||
->where('link.opportunity_id', $record->id)->where('d.id', $id)->whereNull('link.deleted_at')->first(['d.data_classification','d.status','d.malware_scan_status','d.sha256','d.malware_scanned_sha256','d.rights_status','link.payload','link.deleted_at']) : null;
|
||||
if (! $row) $this->fail('evidence', 'Documento não associado à ficha neste âmbito; reutilize o gestor documental existente.');
|
||||
$row = $record?->exists ? DB::table('opportunity_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')
|
||||
->where('link.opportunity_id', $record->id)->where('d.id', $id)->whereNull('link.deleted_at')->first(['d.data_classification', 'd.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256', 'd.rights_status', 'link.payload', 'link.deleted_at']) : null;
|
||||
if (! $row) {
|
||||
$this->fail('evidence', 'Documento não associado à ficha neste âmbito; reutilize o gestor documental existente.');
|
||||
}
|
||||
if ($public && ($row->data_classification !== 'public' || $row->status !== 'active' || $row->malware_scan_status !== 'clean' || $row->sha256 !== $row->malware_scanned_sha256 || $row->rights_status === 'restricted' || data_get(json_decode($row->payload, true), 'visibility') !== 'public')) {
|
||||
$this->fail('evidence', 'Documento interno, restrito ou sem disponibilização pública: preserve a evidência interna, sem a divulgar.');
|
||||
}
|
||||
}
|
||||
|
||||
/** No private field is copied into the public summary automatically. */
|
||||
/** No private field is copied into the public summary automatically.
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function publication(Opportunity $record, array $input): ?array
|
||||
{
|
||||
$private = app(OpportunityManagement::class)->values($record)['proactive'] ?? null;
|
||||
if (! $private) {
|
||||
if (isset($input['proactive_public'])) $this->fail('publication', 'Prepare a análise antes de divulgar esta síntese.');
|
||||
if (isset($input['proactive_public'])) {
|
||||
$this->fail('publication', 'Prepare a análise antes de divulgar esta síntese.');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
$d = Validator::make($input, [
|
||||
'proactive_reviewed' => 'required|accepted',
|
||||
'proactive_public' => 'required|array:group,state,need,proposal,basis,limitations,next_action,evidence_ids,chain_id,stage,resources,assumptions,conditions,relation_ids',
|
||||
'proactive_public.group' => 'required|in:exists,needs,ideas',
|
||||
'proactive_public.resources'=>'nullable|string|max:2500', 'proactive_public.assumptions'=>'nullable|string|max:2500', 'proactive_public.conditions'=>'nullable|string|max:2500',
|
||||
'proactive_public.relation_ids'=>'sometimes|array|max:40', 'proactive_public.relation_ids.*'=>'uuid|distinct',
|
||||
'proactive_public.resources' => 'nullable|string|max:2500', 'proactive_public.assumptions' => 'nullable|string|max:2500', 'proactive_public.conditions' => 'nullable|string|max:2500',
|
||||
'proactive_public.relation_ids' => 'sometimes|array|max:40', 'proactive_public.relation_ids.*' => 'uuid|distinct',
|
||||
'proactive_public.state' => 'required|in:hypothesis,confirmed', 'proactive_public.chain_id' => 'nullable|uuid', 'proactive_public.stage' => 'nullable|string|max:1000',
|
||||
'proactive_public.need'=>'required_unless:proactive_public.group,exists|nullable|string|max:2500', 'proactive_public.proposal'=>'required_if:proactive_public.group,ideas|nullable|string|max:2500',
|
||||
...collect(['basis','limitations','next_action'])->mapWithKeys(fn ($k) => ['proactive_public.'.$k => 'required|string|max:2500'])->all(),
|
||||
'proactive_public.need' => 'required_unless:proactive_public.group,exists|nullable|string|max:2500', 'proactive_public.proposal' => 'required_if:proactive_public.group,ideas|nullable|string|max:2500',
|
||||
...collect(['basis', 'limitations', 'next_action'])->mapWithKeys(fn ($k) => ['proactive_public.'.$k => 'required|string|max:2500'])->all(),
|
||||
'proactive_public.evidence_ids' => 'present|array|max:60', 'proactive_public.evidence_ids.*' => 'uuid|distinct',
|
||||
])->validate()['proactive_public'];
|
||||
$d += ['need'=>'','proposal'=>''];
|
||||
if ($d['group'] !== $private['kind']) $this->fail('publication', 'O grupo público deve corresponder à análise guardada.');
|
||||
$d += ['need' => '', 'proposal' => ''];
|
||||
if ($d['group'] !== $private['kind']) {
|
||||
$this->fail('publication', 'O grupo público deve corresponder à análise guardada.');
|
||||
}
|
||||
$proofs = [];
|
||||
foreach ($d['evidence_ids'] as $id) {
|
||||
$e = collect($private['evidence'])->firstWhere('id', $id);
|
||||
if (! $e || $e['access'] !== 'public') $this->fail('publication', 'Não pode divulgar evidência interna nem a sua fonte indirectamente. Redija uma síntese independente ou seleccione evidência pública autorizada.');
|
||||
if (! empty($e['document_id'])) $this->document($record, $e['document_id'], true);
|
||||
$proofs[] = array_intersect_key($e, array_flip(['id','category','purpose','statement','source','locator','period','scope','coverage','verified_on']));
|
||||
$e = collect(StructuredData::collectionItems($private['evidence']))->firstWhere('id', $id);
|
||||
if (! $e || $e['access'] !== 'public') {
|
||||
$this->fail('publication', 'Não pode divulgar evidência interna nem a sua fonte indirectamente. Redija uma síntese independente ou seleccione evidência pública autorizada.');
|
||||
}
|
||||
if (! empty($e['document_id'])) {
|
||||
$this->document($record, $e['document_id'], true);
|
||||
}
|
||||
$proofs[] = array_intersect_key($e, array_flip(['id', 'category', 'purpose', 'statement', 'source', 'locator', 'period', 'scope', 'coverage', 'verified_on']));
|
||||
}
|
||||
if ($d['group'] !== 'exists' && $d['state'] === 'confirmed' && ($private['need']['state'] !== 'confirmed' || array_diff($private['need']['evidence_ids'], $d['evidence_ids']))) $this->fail('publication', 'Confirmação pública exige a necessidade confirmada e o fundamento público seleccionado; pode divulgar uma hipótese com limitações explícitas.');
|
||||
if (!empty($d['chain_id']) && !app(OpportunityClassification::class)->targets('chain')->where('id', $d['chain_id'])->exists()) $this->fail('publication', 'Cadeia de valor pública indisponível.');
|
||||
$relations=[];
|
||||
if ($d['group'] !== 'exists' && $d['state'] === 'confirmed' && ($private['need']['state'] !== 'confirmed' || array_diff($private['need']['evidence_ids'], $d['evidence_ids']))) {
|
||||
$this->fail('publication', 'Confirmação pública exige a necessidade confirmada e o fundamento público seleccionado; pode divulgar uma hipótese com limitações explícitas.');
|
||||
}
|
||||
if (! empty($d['chain_id']) && ! app(OpportunityClassification::class)->targets('chain')->where('id', $d['chain_id'])->exists()) {
|
||||
$this->fail('publication', 'Cadeia de valor pública indisponível.');
|
||||
}
|
||||
$relations = [];
|
||||
foreach ($d['relation_ids'] ?? [] as $id) {
|
||||
$r=collect($private['relations'])->firstWhere('id',$id);
|
||||
if (!$r || array_diff($r['evidence_ids'],$d['evidence_ids'])) $this->fail('publication','A relação exige o fundamento público seleccionado; nenhuma referência interna é copiada.');
|
||||
$target=app(OpportunityClassification::class)->targets($r['kind'])->where('id',$r['target_id'])->first(['id',OpportunityClassification::TARGETS[$r['kind']][1].' as name']);
|
||||
if (!$target) $this->fail('publication','Referência pública da relação indisponível.');
|
||||
$relations[]=['kind'=>$r['kind'],'target_id'=>$r['target_id'],'label'=>$target->name,'relationship'=>$r['relation'],'evidence_ids'=>$r['evidence_ids'],'basis'=>$d['basis']];
|
||||
$r = collect(StructuredData::collectionItems($private['relations']))->firstWhere('id', $id);
|
||||
if (! $r || array_diff($r['evidence_ids'], $d['evidence_ids'])) {
|
||||
$this->fail('publication', 'A relação exige o fundamento público seleccionado; nenhuma referência interna é copiada.');
|
||||
}
|
||||
$target = app(OpportunityClassification::class)->targets($r['kind'])->where('id', $r['target_id'])->first(['id', OpportunityClassification::TARGETS[$r['kind']][1].' as name']);
|
||||
if (! $target) {
|
||||
$this->fail('publication', 'Referência pública da relação indisponível.');
|
||||
}
|
||||
$relations[] = ['kind' => $r['kind'], 'target_id' => $r['target_id'], 'label' => $target->name, 'relationship' => $r['relation'], 'evidence_ids' => $r['evidence_ids'], 'basis' => $d['basis']];
|
||||
}
|
||||
// Catch literal reuse of private statements, interpretations, references and document identities.
|
||||
$publicText = mb_strtolower(implode(' ', [...array_filter($input, 'is_scalar'), ...array_filter($d, 'is_scalar')]));
|
||||
foreach ($private['evidence'] as $e) {
|
||||
if ($e['access'] === 'public') continue;
|
||||
foreach (['statement','interpretation','source','locator','document_id'] as $key) {
|
||||
if ($e['access'] === 'public') {
|
||||
continue;
|
||||
}
|
||||
foreach (['statement', 'interpretation', 'source', 'locator', 'document_id'] as $key) {
|
||||
$value = trim($e[$key] ?? '');
|
||||
if (mb_strlen($value) >= 10 && str_contains($publicText, mb_strtolower($value))) $this->fail('publication', 'O resumo contém informação de evidência interna. Reveja a síntese e a divulgação indirecta antes de publicar.');
|
||||
if (mb_strlen($value) >= 10 && str_contains($publicText, mb_strtolower($value))) {
|
||||
$this->fail('publication', 'O resumo contém informação de evidência interna. Reveja a síntese e a divulgação indirecta antes de publicar.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...array_map(fn ($v) => is_string($v) ? trim(strip_tags($v)) : $v, $d),
|
||||
'version' => self::VERSION, 'relations'=>$relations, 'evidence' => $proofs, 'notice' => self::NOTICE,
|
||||
'version' => self::VERSION, 'relations' => $relations, 'evidence' => $proofs, 'notice' => self::NOTICE,
|
||||
'availability_confirmed' => false, 'economic_validation' => false];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>|null
|
||||
*/
|
||||
public function publicData(Opportunity $record): ?array
|
||||
{
|
||||
$p = data_get($record->workflow_context, 'promotional_summary.projection.proactive');
|
||||
|
||||
return is_array($p) && Opportunity::published()->whereKey($record->id)->exists() ? $p : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicationRelations(Opportunity $record): array
|
||||
{
|
||||
return collect(app(OpportunityManagement::class)->values($record)['proactive']['relations'] ?? [])->map(function($r){
|
||||
$label=app(OpportunityClassification::class)->targets($r['kind'])->where('id',$r['target_id'])->value(OpportunityClassification::TARGETS[$r['kind']][1]);
|
||||
return $label?['id'=>$r['id'],'label'=>$label,'relationship'=>$r['relation']]:null;
|
||||
return collect(StructuredData::collectionItems(app(OpportunityManagement::class)->values($record)['proactive']['relations'] ?? []))->map(function ($r) {
|
||||
$label = app(OpportunityClassification::class)->targets($r['kind'])->where('id', $r['target_id'])->value(OpportunityClassification::TARGETS[$r['kind']][1]);
|
||||
|
||||
return $label ? ['id' => $r['id'], 'label' => $label, 'relationship' => $r['relation']] : null;
|
||||
})->filter()->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function history(?Opportunity $record): array
|
||||
{
|
||||
if (!$record) return [];
|
||||
if (! $record) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $record->id)->orderByDesc('occurred_at')->orderByRaw("(after_data->>'version')::integer DESC")->limit(30)->get()->map(function ($event) {
|
||||
$entry=json_decode($event->after_data,true);$snapshot=json_decode(Crypt::decryptString($entry['snapshot']),true);
|
||||
$draft=json_decode($snapshot['management_draft'] ?? '{}',true);$need=$draft['proactive']['need'] ?? null;
|
||||
return $need ? ['at'=>$event->occurred_at,'version'=>$entry['version'],'state'=>$need['state'],'problem'=>$need['problem'],'confirmation'=>$need['confirmation'],'evidence_ids'=>$need['evidence_ids']] : null;
|
||||
$entry = json_decode($event->after_data, true);
|
||||
$snapshot = json_decode(Crypt::decryptString($entry['snapshot']), true);
|
||||
$draft = json_decode($snapshot['management_draft'] ?? '{}', true);
|
||||
$need = $draft['proactive']['need'] ?? null;
|
||||
|
||||
return $need ? ['at' => $event->occurred_at, 'version' => $entry['version'], 'state' => $need['state'], 'problem' => $need['problem'], 'confirmation' => $need['confirmation'], 'evidence_ids' => $need['evidence_ids']] : null;
|
||||
})->filter()->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function options(?Opportunity $record = null): array
|
||||
{
|
||||
return ['documents' => $record ? DB::table('opportunity_documents as l')->join('documents as d','d.id','=','l.document_id')->where('l.opportunity_id',$record->id)->whereNull('l.deleted_at')->whereNull('d.deleted_at')->get(['d.id','d.file_name as title'])->all() : [], 'groups' => self::GROUPS, 'references' => collect(['project','cluster','corridor','park','chain'])->mapWithKeys(fn ($kind) => [$kind => app(OpportunityClassification::class)->targets($kind)->orderBy(OpportunityClassification::TARGETS[$kind][1])->limit(300)->get(['id', OpportunityClassification::TARGETS[$kind][1].' as name'])])->all()];
|
||||
return ['documents' => $record ? DB::table('opportunity_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.opportunity_id', $record->id)->whereNull('l.deleted_at')->whereNull('d.deleted_at')->get(['d.id', 'd.file_name as title'])->all() : [], 'groups' => self::GROUPS, 'references' => collect(['project', 'cluster', 'corridor', 'park', 'chain'])->mapWithKeys(fn ($kind) => [$kind => app(OpportunityClassification::class)->targets($kind)->orderBy(OpportunityClassification::TARGETS[$kind][1])->limit(300)->get(['id', OpportunityClassification::TARGETS[$kind][1].' as name'])])->all()];
|
||||
}
|
||||
|
||||
private function fail(string $key, string $message): never
|
||||
|
||||
@@ -7,7 +7,9 @@ use App\Models\User;
|
||||
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;
|
||||
|
||||
/** Internal observations, never a public business directory or proof of demand. */
|
||||
final class ProactiveSupply
|
||||
@@ -16,85 +18,118 @@ final class ProactiveSupply
|
||||
|
||||
public function authorize(User $actor, ?Opportunity $record = null): void
|
||||
{
|
||||
$access=app(PortalProfileAccess::class);
|
||||
$internal=collect(OpportunityManagement::CATEGORIES)->contains(fn($type)=>$access->internalAssignment($actor,$type)!==null);
|
||||
abort_unless($access->legacyWriteAllowed($actor)||$internal,403);
|
||||
if ($record?->exists) $access->authorize($actor,'view',$record);
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$internal = collect(OpportunityManagement::CATEGORIES)->contains(fn ($type) => $access->internalAssignment($actor, $type) !== null);
|
||||
abort_unless($access->legacyWriteAllowed($actor) || $internal, 403);
|
||||
if ($record?->exists) {
|
||||
$access->authorize($actor, 'view', $record);
|
||||
}
|
||||
}
|
||||
|
||||
private function read(User $actor, callable $callback): mixed
|
||||
{
|
||||
return DB::transaction(function()use($actor,$callback){
|
||||
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)",[(string)$actor->id]);
|
||||
return DB::transaction(function () use ($actor, $callback) {
|
||||
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)", [(string) $actor->id]);
|
||||
|
||||
return $callback();
|
||||
});
|
||||
}
|
||||
|
||||
public function search(User $actor,array $input,?Opportunity $record=null): array
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function search(User $actor, array $input, ?Opportunity $record = null): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make($input,[
|
||||
'territory_id'=>['required','uuid',Rule::exists('geo_locations','id')->whereNull('deleted_at')],
|
||||
'activity'=>'nullable|string|max:150','sector'=>'nullable|string|max:250','page'=>'nullable|integer|min:1|max:100000',
|
||||
$this->authorize($actor, $record);
|
||||
$v = Validator::make($input, [
|
||||
'territory_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
|
||||
'activity' => 'nullable|string|max:150', 'sector' => 'nullable|string|max:250', 'page' => 'nullable|integer|min:1|max:100000',
|
||||
])->validate();
|
||||
if(!Schema::hasTable('proactive_supply_observations'))return ['installed'=>false,'rows'=>[],'total'=>null,'limitations'=>self::LIMITATIONS,'status'=>'Base interna ainda não carregada neste ambiente.'];
|
||||
return $this->read($actor,function()use($v){
|
||||
$ids=[$v['territory_id']];
|
||||
if (! Schema::hasTable('proactive_supply_observations')) {
|
||||
return ['installed' => false, 'rows' => [], 'total' => null, 'limitations' => self::LIMITATIONS, 'status' => 'Base interna ainda não carregada neste ambiente.'];
|
||||
}
|
||||
|
||||
return $this->read($actor, function () use ($v) {
|
||||
$ids = [$v['territory_id']];
|
||||
// Canonical descendants, not a name-only cross-province match.
|
||||
$front=$ids;
|
||||
for($depth=0;$depth<5&&$front;$depth++){
|
||||
$front=DB::table('geo_locations')->whereIn('parent_id',$front)->whereNull('deleted_at')->pluck('id')->all();
|
||||
$ids=[...$ids,...$front];
|
||||
$front = $ids;
|
||||
for ($depth = 0; $depth < 5 && $front; $depth++) {
|
||||
$front = DB::table('geo_locations')->whereIn('parent_id', $front)->whereNull('deleted_at')->pluck('id')->all();
|
||||
$ids = [...$ids, ...$front];
|
||||
}
|
||||
$base=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->whereIn('o.territory_id',$ids);
|
||||
$sectors=(clone $base)->where('o.sector','<>','')->distinct()->orderBy('o.sector')->pluck('o.sector')->all();
|
||||
if(!empty($v['sector']))$base->where('o.sector',$v['sector']);
|
||||
if(!empty($v['activity']))$base->where(fn($q)=>$q->where('o.cae','ilike','%'.$v['activity'].'%')->orWhereRaw("translate(lower(o.activity),'áàâãéêíóôõúç','aaaaeeiooouc') LIKE ?",['%'.strtolower(\Illuminate\Support\Str::ascii($v['activity'])).'%']));
|
||||
$page=$v['page']??1;
|
||||
$base = DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s', 's.sha256', '=', 'o.source_hash')->whereIn('o.territory_id', $ids);
|
||||
$sectors = (clone $base)->where('o.sector', '<>', '')->distinct()->orderBy('o.sector')->pluck('o.sector')->all();
|
||||
if (! empty($v['sector'])) {
|
||||
$base->where('o.sector', $v['sector']);
|
||||
}
|
||||
if (! empty($v['activity'])) {
|
||||
$base->where(fn ($q) => $q->where('o.cae', 'ilike', '%'.$v['activity'].'%')->orWhereRaw("translate(lower(o.activity),'áàâãéêíóôõúç','aaaaeeiooouc') LIKE ?", ['%'.strtolower(Str::ascii($v['activity'])).'%']));
|
||||
}
|
||||
$page = $v['page'] ?? 1;
|
||||
// Exact repeated observations are retained in storage, counted separately.
|
||||
$total=(clone $base)->whereNull('o.duplicate_of')->count();
|
||||
$duplicates=(clone $base)->whereNotNull('o.duplicate_of')->count();
|
||||
$rows=(clone $base)->whereNull('o.duplicate_of')->orderBy('o.name')->orderBy('o.id')->offset(($page-1)*25)->limit(25)->get(['o.id','o.entity_key','o.name','o.province','o.district','o.territory_id','o.territory_resolution','o.cae','o.activity','o.sector','o.source_date','o.sheet','o.row_number','o.source_hash','o.identity_conflict','s.name as source_name','s.period as source_period','s.imported_at']);
|
||||
$coverage=DB::table('proactive_supply_observations')->selectRaw("count(*) FILTER (WHERE territory_id IS NULL) AS unmapped, count(*) FILTER (WHERE territory_resolution='province_only_district_unknown') AS province_only")->first();
|
||||
return ['installed'=>true,'rows'=>$rows,'total'=>$total,'duplicate_sightings'=>$duplicates,'page'=>$page,'per_page'=>25,'sectors'=>$sectors,'territory_coverage'=>$coverage,'limitations'=>self::LIMITATIONS,'status'=>$total?'Registos documentais encontrados; não equivalem a empresas únicas ou oferta actual confirmada.':'Informação insuficiente nesta base e nestes filtros.'];
|
||||
$total = (clone $base)->whereNull('o.duplicate_of')->count();
|
||||
$duplicates = (clone $base)->whereNotNull('o.duplicate_of')->count();
|
||||
$rows = (clone $base)->whereNull('o.duplicate_of')->orderBy('o.name')->orderBy('o.id')->offset(($page - 1) * 25)->limit(25)->get(['o.id', 'o.entity_key', 'o.name', 'o.province', 'o.district', 'o.territory_id', 'o.territory_resolution', 'o.cae', 'o.activity', 'o.sector', 'o.source_date', 'o.sheet', 'o.row_number', 'o.source_hash', 'o.identity_conflict', 's.name as source_name', 's.period as source_period', 's.imported_at']);
|
||||
$coverage = DB::table('proactive_supply_observations')->selectRaw("count(*) FILTER (WHERE territory_id IS NULL) AS unmapped, count(*) FILTER (WHERE territory_resolution='province_only_district_unknown') AS province_only")->first();
|
||||
|
||||
return ['installed' => true, 'rows' => $rows, 'total' => $total, 'duplicate_sightings' => $duplicates, 'page' => $page, 'per_page' => 25, 'sectors' => $sectors, 'territory_coverage' => $coverage, 'limitations' => self::LIMITATIONS, 'status' => $total ? 'Registos documentais encontrados; não equivalem a empresas únicas ou oferta actual confirmada.' : 'Informação insuficiente nesta base e nestes filtros.'];
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve server-side source lineage; a caller cannot fabricate an internal observation. */
|
||||
public function comparisons(User $actor,array $input,?Opportunity $record): array
|
||||
/** Resolve server-side source lineage; a caller cannot fabricate an internal observation.
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function comparisons(User $actor, array $input, ?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make(['rows'=>$input],[
|
||||
'rows'=>'array|max:40','rows.*'=>'array:observation_id,relationship,rationale,limitations',
|
||||
'rows.*.observation_id'=>'required|string|size:64|distinct',
|
||||
'rows.*.relationship'=>'required|in:competition,complementarity,partner,uncertain',
|
||||
'rows.*.rationale'=>'required|string|max:4000','rows.*.limitations'=>'required|string|max:4000',
|
||||
$this->authorize($actor, $record);
|
||||
$v = Validator::make(['rows' => $input], [
|
||||
'rows' => 'array|max:40', 'rows.*' => 'array:observation_id,relationship,rationale,limitations',
|
||||
'rows.*.observation_id' => 'required|string|size:64|distinct',
|
||||
'rows.*.relationship' => 'required|in:competition,complementarity,partner,uncertain',
|
||||
'rows.*.rationale' => 'required|string|max:4000', 'rows.*.limitations' => 'required|string|max:4000',
|
||||
])->validate()['rows'];
|
||||
if(!$v)return [];
|
||||
abort_unless(Schema::hasTable('proactive_supply_observations'),422,'Base interna indisponível.');
|
||||
return $this->read($actor,function()use($v){
|
||||
$fingerprints=[];
|
||||
foreach($v as $row){
|
||||
$o=DB::table('proactive_supply_observations')->where('id',$row['observation_id'])->first();
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.supply_comparisons'=>'Registo da oferta indisponível; preserve a referência anterior e confira o ambiente.']);
|
||||
if($o->duplicate_of!==null||isset($fingerprints[$o->fingerprint]))throw \Illuminate\Validation\ValidationException::withMessages(['proactive.supply_comparisons'=>'Esta observação administrativa é repetida. Compare a referência original uma única vez; a repetição e a sua fonte permanecem conservadas na base interna.']);
|
||||
$fingerprints[$o->fingerprint]=true;
|
||||
if (! $v) {
|
||||
return [];
|
||||
}
|
||||
abort_unless(Schema::hasTable('proactive_supply_observations'), 422, 'Base interna indisponível.');
|
||||
|
||||
return $this->read($actor, function () use ($v) {
|
||||
$fingerprints = [];
|
||||
foreach ($v as $row) {
|
||||
$o = DB::table('proactive_supply_observations')->where('id', $row['observation_id'])->first();
|
||||
if (! $o) {
|
||||
throw ValidationException::withMessages(['proactive.supply_comparisons' => 'Registo da oferta indisponível; preserve a referência anterior e confira o ambiente.']);
|
||||
}
|
||||
if ($o->duplicate_of !== null || isset($fingerprints[$o->fingerprint])) {
|
||||
throw ValidationException::withMessages(['proactive.supply_comparisons' => 'Esta observação administrativa é repetida. Compare a referência original uma única vez; a repetição e a sua fonte permanecem conservadas na base interna.']);
|
||||
}
|
||||
$fingerprints[$o->fingerprint] = true;
|
||||
}
|
||||
|
||||
return $v;
|
||||
});
|
||||
}
|
||||
|
||||
public function evidence(User $actor,string $id,?Opportunity $record): array
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function evidence(User $actor, string $id, ?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
return $this->read($actor,function()use($id){
|
||||
$o=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->where('o.id',$id)->first(['o.*','s.name as source_name','s.period as source_period']);
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.evidence'=>'Observação interna indisponível neste ambiente.']);
|
||||
return ['observation_id'=>$o->id,'category'=>'supply','purpose'=>'local','access'=>'internal','document_id'=>null,
|
||||
'statement'=>'Registo administrativo: '.$o->name.'; CAE '.$o->cae.'; '.($o->activity?:'actividade por classificar').'; '.$o->district.', '.$o->province.'. Não confirma actividade actual.',
|
||||
'source'=>$o->source_name.'; SHA256 '.$o->source_hash,'locator'=>$o->sheet.'!linha '.$o->row_number,
|
||||
'period'=>$o->source_date.'; '.$o->source_period,'scope'=>$o->district.', '.$o->province,
|
||||
'coverage'=>self::LIMITATIONS.($o->identity_conflict?' Identificador partilhado por denominações divergentes: identidade por conferir.':''),
|
||||
$this->authorize($actor, $record);
|
||||
|
||||
return $this->read($actor, function () use ($id) {
|
||||
$o = DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s', 's.sha256', '=', 'o.source_hash')->where('o.id', $id)->first(['o.*', 's.name as source_name', 's.period as source_period']);
|
||||
if (! $o) {
|
||||
throw ValidationException::withMessages(['proactive.evidence' => 'Observação interna indisponível neste ambiente.']);
|
||||
}
|
||||
|
||||
return ['observation_id' => $o->id, 'category' => 'supply', 'purpose' => 'local', 'access' => 'internal', 'document_id' => null,
|
||||
'statement' => 'Registo administrativo: '.$o->name.'; CAE '.$o->cae.'; '.($o->activity ?: 'actividade por classificar').'; '.$o->district.', '.$o->province.'. Não confirma actividade actual.',
|
||||
'source' => $o->source_name.'; SHA256 '.$o->source_hash, 'locator' => $o->sheet.'!linha '.$o->row_number,
|
||||
'period' => $o->source_date.'; '.$o->source_period, 'scope' => $o->district.', '.$o->province,
|
||||
'coverage' => self::LIMITATIONS.($o->identity_conflict ? ' Identificador partilhado por denominações divergentes: identidade por conferir.' : ''),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedPattern;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -38,6 +39,9 @@ final class Procurement
|
||||
abort_unless($this->access($actor), 403, 'Use a autorização editorial já atribuída.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function references(User $actor): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
@@ -54,13 +58,16 @@ final class Procurement
|
||||
->orderBy('r.title')->get(['r.id', 'r.title', 'r.published', 'd.malware_scan_status'])];
|
||||
}
|
||||
|
||||
public function record(string $id): object
|
||||
public function record(string $id): \stdClass
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
|
||||
return DB::table('portal_tenders')->where('id', $id)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function save(User $actor, ?string $id, array $input): string
|
||||
{
|
||||
$this->guard($actor);
|
||||
@@ -84,6 +91,10 @@ final class Procurement
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function normalize(User $actor, array $input): array
|
||||
{
|
||||
$rules = array_fill_keys(self::TEXT, 'nullable|string|max:12000');
|
||||
@@ -110,6 +121,9 @@ final class Procurement
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(User $actor, string $id, string $act): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
@@ -119,7 +133,7 @@ final class Procurement
|
||||
Validator::make($p, array_fill_keys(['title', 'reference', 'organization_id', 'modality', 'object', 'regime', 'instrument', 'edition', 'rule_source', 'origin_published_at', 'deadline', 'delivery_channel', 'timezone'], 'required'))->validate();
|
||||
Validator::make($p, ['timezone' => 'timezone', 'object_kind' => 'nullable|in:works,goods,services,mixed,other', 'guarantee_status' => 'nullable|in:required,not_required,unknown'])->validate();
|
||||
Validator::make($p, ['public_reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$dates = [];
|
||||
$dates = ['origin_published_at' => null, 'clarifications_at' => null, 'deadline' => null, 'opening_at' => null];
|
||||
foreach (['origin_published_at', 'clarifications_at', 'deadline', 'opening_at'] as $field) {
|
||||
if (empty($p[$field])) {
|
||||
continue;
|
||||
@@ -148,7 +162,7 @@ final class Procurement
|
||||
$this->require(! empty($p['minimum_calendar_source']), 'minimum_calendar_source', 'Identifique a fonte do calendário de dias úteis e feriados.');
|
||||
$weekdays = array_filter(array_map('trim', explode(',', (string) ($p['minimum_working_days'] ?? ''))));
|
||||
$this->require(count($weekdays) > 0 && ! array_diff($weekdays, ['1', '2', '3', '4', '5', '6', '7']), 'minimum_working_days', 'Indique os dias de trabalho documentados (1=segunda, 7=domingo).');
|
||||
$holidays = array_values(array_filter(preg_split('/[\s,;]+/', (string) ($p['minimum_holidays'] ?? ''))));
|
||||
$holidays = array_values(array_filter(CheckedPattern::split('/[\s,;]+/', (string) ($p['minimum_holidays'] ?? ''))));
|
||||
Validator::make(['dates' => $holidays], ['dates' => 'array|max:1000', 'dates.*' => 'date_format:Y-m-d'])->validate();
|
||||
for ($left = (int) $p['minimum_days'],$iterations = 0; $left > 0; $iterations++) {
|
||||
$this->require($iterations < 36500, 'minimum_days', 'Calendário insuficiente para calcular o prazo indicado.');
|
||||
@@ -222,6 +236,9 @@ final class Procurement
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function publish(User $actor, string $id, array $input): void
|
||||
{
|
||||
$this->guard($actor);
|
||||
@@ -237,6 +254,9 @@ final class Procurement
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
*/
|
||||
private function version(User $actor, string $id, int $version, string $act, array $payload, string $reason, bool $published): string
|
||||
{
|
||||
$vid = (string) Str::uuid();
|
||||
@@ -254,6 +274,9 @@ final class Procurement
|
||||
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('opportunity_images as oi')->whereColumn('oi.document_id', 'd.id')->whereRaw("NOT jsonb_exists(COALESCE(oi.payload,'{}'::jsonb),'library_source')"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publishedVersion(string $id): array
|
||||
{
|
||||
$v = DB::table('portal_tender_versions')->where('id', $id)->whereNotNull('published_at')->firstOrFail();
|
||||
@@ -265,6 +288,9 @@ final class Procurement
|
||||
return ['id' => $v->id, 'version' => $v->version, 'act' => $v->act, 'payload' => $p, 'published_at' => $v->published_at, 'reason' => $v->reason];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $version
|
||||
*/
|
||||
public function state(array $version): string
|
||||
{
|
||||
$p = $version['payload'];
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\CheckedPattern;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Public projection only. Management retains the complete stored records and links. */
|
||||
@@ -19,28 +20,38 @@ final class PublicDocumentPresentation
|
||||
|
||||
private function text(?string $value): ?string
|
||||
{
|
||||
if ($value === null) return null;
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
// Imported descriptions can contain implementation notes. Never mutate the original.
|
||||
$sentences = preg_split('/(?<=[.!?])\s+|[\r\n]+/u', strip_tags($value));
|
||||
$safe = array_filter($sentences, fn ($text) => !preg_match('~(?:\b(?:supports|cites|evidence)\b|\btheme\s*:|\bfiscal\.[\w.]+|\b(?:SHA-?256|hash|preflight|repositório|autenticidade|comparação binária|estado de vigência|revisão de direitos)\b|Cópia mantida em privado|\b[0-9a-f]{40,64}\b|(?:^|\s)(?:[A-Z]:[\\/]|(?:docs|outputs|resources|storage|app)/))~iu', $text));
|
||||
$sentences = CheckedPattern::split('/(?<=[.!?])\s+|[\r\n]+/u', strip_tags($value));
|
||||
$safe = array_filter($sentences, fn ($text) => ! preg_match('~(?:\b(?:supports|cites|evidence)\b|\btheme\s*:|\bfiscal\.[\w.]+|\b(?:SHA-?256|hash|preflight|repositório|autenticidade|comparação binária|estado de vigência|revisão de direitos)\b|Cópia mantida em privado|\b[0-9a-f]{40,64}\b|(?:^|\s)(?:[A-Z]:[\\/]|(?:docs|outputs|resources|storage|app)/))~iu', $text));
|
||||
$result = trim(implode(' ', $safe));
|
||||
|
||||
return $result !== '' ? $result : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function resource(object $row): array
|
||||
{
|
||||
$r=(array)$row;
|
||||
$public = array_intersect_key($r, array_flip(['id','document_type','document_date','applicable_from','applicable_until','language','territorial_scope','territory_name','source_confirmation','legal_status','size_bytes']));
|
||||
foreach (['title','description','issuer','document_number','category','topic','version_label'] as $key) $public[$key]=$this->text($r[$key]??null);
|
||||
$r = (array) $row;
|
||||
$public = array_intersect_key($r, array_flip(['id', 'document_type', 'document_date', 'applicable_from', 'applicable_until', 'language', 'territorial_scope', 'territory_name', 'source_confirmation', 'legal_status', 'size_bytes']));
|
||||
foreach (['title', 'description', 'issuer', 'document_number', 'category', 'topic', 'version_label'] as $key) {
|
||||
$public[$key] = $this->text($r[$key] ?? null);
|
||||
}
|
||||
$public['title'] ??= 'Documento';
|
||||
$url=$r['source_url']??null;
|
||||
$public['source_url']=is_string($url)&&filter_var($url,FILTER_VALIDATE_URL)&&in_array(strtolower(parse_url($url,PHP_URL_SCHEME)??''),['https','http'],true)?$url:null;
|
||||
$public['download_url']=route('services.download',['id'=>$r['id']]);
|
||||
$public['view_url']=in_array($r['media_type']??null,['application/pdf','image/jpeg','image/png','image/webp'],true)?route('services.document.view',['id'=>$r['id']]):null;
|
||||
$public['usage_notice']=in_array($r['document_type']??'', ['legislation','procedure','official_form','digital_adaptation','guidance_template'],true)
|
||||
$url = $r['source_url'] ?? null;
|
||||
$scheme = is_string($url) ? parse_url($url, PHP_URL_SCHEME) : null;
|
||||
$public['source_url'] = is_string($url) && filter_var($url, FILTER_VALIDATE_URL) && is_string($scheme) && in_array(strtolower($scheme), ['https', 'http'], true) ? $url : null;
|
||||
$public['download_url'] = route('services.download', ['id' => $r['id']]);
|
||||
$public['view_url'] = in_array($r['media_type'] ?? null, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true) ? route('services.document.view', ['id' => $r['id']]) : null;
|
||||
$public['usage_notice'] = in_array($r['document_type'] ?? '', ['legislation', 'procedure', 'official_form', 'digital_adaptation', 'guidance_template'], true)
|
||||
? 'Confirme no documento ou junto da entidade competente as condições aplicáveis ao seu caso. A consulta não garante benefícios nem aplicação fiscal.' : null;
|
||||
$keys=DB::table('portal_resource_links')->where('resource_id',$r['id'])->where('target_type','module')->pluck('target_key');
|
||||
$public['context_actions']=$keys->filter(fn($key)=>isset(self::ACTIONS[$key]))->map(fn($key)=>self::ACTIONS[$key])->unique('href')->values()->all();
|
||||
$keys = DB::table('portal_resource_links')->where('resource_id', $r['id'])->where('target_type', 'module')->pluck('target_key');
|
||||
$public['context_actions'] = $keys->filter(fn ($key) => isset(self::ACTIONS[$key]))->map(fn ($key) => self::ACTIONS[$key])->unique('href')->values()->all();
|
||||
|
||||
return $public;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,11 @@ final class RetainedGeoJsonCollection
|
||||
$position = 0;
|
||||
$peek = static function () use ($stream, &$buffer, &$position): ?string {
|
||||
if ($position === strlen($buffer)) {
|
||||
$buffer = fread($stream, 65536);
|
||||
$chunk = fread($stream, 65536);
|
||||
if ($chunk === false) {
|
||||
throw new \RuntimeException('Não foi possível ler o exemplar GeoJSON; original preservado.');
|
||||
}
|
||||
$buffer = $chunk;
|
||||
$position = 0;
|
||||
}
|
||||
|
||||
@@ -153,7 +157,7 @@ final class RetainedGeoJsonCollection
|
||||
}
|
||||
$expect('}');
|
||||
$white();
|
||||
abort_unless($peek() === null && $hadFeatures,422,'Exemplar incompleto ou com conteúdo adicional.');
|
||||
abort_unless($peek() === null && $hadFeatures, 422, 'Exemplar incompleto ou com conteúdo adicional.');
|
||||
|
||||
return $metadata;
|
||||
} finally {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Reuses approved administration; never changes the global gate or private-record ACL. */
|
||||
@@ -10,41 +12,52 @@ final class ScopedPortalAdministration
|
||||
{
|
||||
public function administrative(?User $actor): bool
|
||||
{
|
||||
if (!$actor || !$actor->hasVerifiedEmail()) return false;
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->has($actor, 'auditor')) return false;
|
||||
if ($access->has($actor, 'auditor')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ($access->superuser($actor) && $access->mfa($actor))
|
||||
|| ($access->legacyWriteAllowed($actor) && $access->mfa($actor));
|
||||
}
|
||||
|
||||
public function interestOperator(?User $actor): bool
|
||||
{
|
||||
if (!$actor || !$actor->hasVerifiedEmail()) return false;
|
||||
$access=app(PortalProfileAccess::class);
|
||||
return !$access->has($actor,'auditor') && $access->mfa($actor)
|
||||
&& ($this->administrative($actor) || DB::table('interest_requests')->where('assigned_to',$actor->id)->whereNull('deleted_at')->exists());
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
$access = app(PortalProfileAccess::class);
|
||||
|
||||
return ! $access->has($actor, 'auditor') && $access->mfa($actor)
|
||||
&& ($this->administrative($actor) || DB::table('interest_requests')->where('assigned_to', $actor->id)->whereNull('deleted_at')->exists());
|
||||
}
|
||||
|
||||
public function interest(User $actor, InterestRequest $record): bool
|
||||
{
|
||||
return $this->interestOperator($actor)
|
||||
&& ($actor->can('manage-portal') || (int)$record->assigned_to===$actor->id);
|
||||
&& ($actor->can('manage-portal') || (int) $record->assigned_to === $actor->id);
|
||||
}
|
||||
|
||||
public function interestQuery($query, User $actor): void
|
||||
/** @param Builder<InterestRequest>|\Illuminate\Database\Query\Builder $query */
|
||||
public function interestQuery(Builder|\Illuminate\Database\Query\Builder $query, User $actor): void
|
||||
{
|
||||
if (!$actor->can('manage-portal')) $query->where('assigned_to',$actor->id);
|
||||
if (! $actor->can('manage-portal')) {
|
||||
$query->where('assigned_to', $actor->id);
|
||||
}
|
||||
}
|
||||
|
||||
public function deskDecision(User $actor, object $request): bool
|
||||
public function deskDecision(User $actor, \stdClass $request): bool
|
||||
{
|
||||
return $actor->can('manage-portal')
|
||||
|| ($this->administrative($actor) && (int)$request->analyst_id===$actor->id);
|
||||
|| ($this->administrative($actor) && (int) $request->analyst_id === $actor->id);
|
||||
}
|
||||
|
||||
public function deskCaseDecision(User $actor, string $id): bool
|
||||
{
|
||||
return $actor->can('manage-portal') || ($this->administrative($actor)
|
||||
&& DB::table('desk_requests')->where('case_id',$id)->where('analyst_id',$actor->id)->exists());
|
||||
&& DB::table('desk_requests')->where('case_id', $id)->where('analyst_id', $actor->id)->exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
@@ -27,6 +28,9 @@ final class SectorInvestment
|
||||
return Sector::where('slug', $slug)->where('is_active', true)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function context(string $slug): array
|
||||
{
|
||||
$sector = $this->sector($slug);
|
||||
@@ -34,7 +38,9 @@ final class SectorInvestment
|
||||
return [...$sector->only(['id', 'name', 'slug']), 'href' => SectorOrganization::href($sector->slug)];
|
||||
}
|
||||
|
||||
/** Public detail shared by the catalogue and the individual sector page. */
|
||||
/** Public detail shared by the catalogue and the individual sector page.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function page(Sector $sector): array
|
||||
{
|
||||
return [
|
||||
@@ -45,6 +51,9 @@ final class SectorInvestment
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function publicView(Sector $sector): array
|
||||
{
|
||||
$creation = app(ContentManagement::class)->access(request()->user())['opportunities']['create'] ?? null;
|
||||
@@ -75,16 +84,20 @@ final class SectorInvestment
|
||||
'content_notice' => $sector->slug === 'mercado-financeiro' ? 'O artigo geral de Mercado Financeiro permanece vazio e não foi publicado. A preparação de negócios neste setor está disponível.' : null];
|
||||
}
|
||||
|
||||
/** Published guides for an explicit sector; never inferred from proximity. */
|
||||
/** Published guides for an explicit sector; never inferred from proximity.
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function guides(?Sector $sector): array
|
||||
{
|
||||
if (! $sector) return [];
|
||||
if (! $sector) {
|
||||
return [];
|
||||
}
|
||||
$articles = [];
|
||||
if (app(LegacyContent::class)->available()) {
|
||||
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
|
||||
try {
|
||||
$a = app(LegacyContent::class)->article($slug, false);
|
||||
$articles[] = \Illuminate\Support\Arr::only($a, ['title', 'href', 'image', 'sha256', 'summary', 'author', 'opportunities_href', 'opportunities_label', 'has_opportunities']);
|
||||
$articles[] = Arr::only($a, ['title', 'href', 'image', 'sha256', 'summary', 'author', 'opportunities_href', 'opportunities_label', 'has_opportunities']);
|
||||
} catch (HttpException $e) {
|
||||
if ($e->getStatusCode() !== 404) {
|
||||
throw $e;
|
||||
@@ -92,9 +105,13 @@ final class SectorInvestment
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $articles;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
*/
|
||||
public function attach(User $actor, string $id, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'sector_slug' => 'required|string|max:150'])->validate();
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
/** Tempo, 18/10/2026: existing masters, one specialization, historical combined bridge. */
|
||||
final class SectorOrganization
|
||||
{
|
||||
public const LEGACY_COMBINED = 'energia';
|
||||
|
||||
public const FINTECH = 'fintech';
|
||||
|
||||
public const LEGACY_ACTIVITY_ID = 'a2000000-0000-4000-8000-000000000002';
|
||||
|
||||
public static function href(string $slug): string
|
||||
@@ -21,7 +25,9 @@ final class SectorOrganization
|
||||
};
|
||||
}
|
||||
|
||||
/** A historical combined filter remains a union, never an arbitrary reassignment. */
|
||||
/** A historical combined filter remains a union, never an arbitrary reassignment.
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function slugs(string $slug): array
|
||||
{
|
||||
return match ($slug) {
|
||||
@@ -32,17 +38,27 @@ final class SectorOrganization
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Opportunity> $query
|
||||
* @return Builder<Opportunity>
|
||||
*/
|
||||
public static function constrain(Builder $query, string $slug): Builder
|
||||
{
|
||||
return $query->whereHas('sector', fn ($s) => $s->whereIn('slug', self::slugs($slug)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<Opportunity>
|
||||
*/
|
||||
public static function opportunities(Sector $sector): Builder
|
||||
{
|
||||
return self::constrain(Opportunity::published(), $sector->slug);
|
||||
}
|
||||
|
||||
public static function catalog()
|
||||
/**
|
||||
* @return Collection<int, Sector>
|
||||
*/
|
||||
public static function catalog(): Collection
|
||||
{
|
||||
return Sector::catalog()->orderBy('sort_order')->get()->each(function ($sector) {
|
||||
$sector->setAttribute('opportunities_count', self::opportunities($sector)->count());
|
||||
|
||||
@@ -2,18 +2,22 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Support\CheckedFile;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** Existing session, permission and MFA control; no actor argument or console entry point. */
|
||||
final class SectorReconciliationExecution
|
||||
{
|
||||
public const SOURCE = 'sector-reconciliation-authenticated';
|
||||
|
||||
public const OPERATION = 'sector-reconciliation-20261018';
|
||||
|
||||
private function actor(Request $request): \App\Models\User
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
abort_if(app()->runningInConsole(), 403, 'A execução exige a sessão HTTP autenticada existente.');
|
||||
$actor = Auth::guard('web')->user();
|
||||
@@ -21,7 +25,7 @@ final class SectorReconciliationExecution
|
||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'), 403);
|
||||
// Same installation permission and Fortify session MFA used by 140000/150000.
|
||||
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||
abort_unless((int)$request->session()->get('portal.mfa_at', 0) <= time(), 403, 'MFA da sessão inválido.');
|
||||
abort_unless((int) $request->session()->get('portal.mfa_at', 0) <= time(), 403, 'MFA da sessão inválido.');
|
||||
|
||||
return $actor;
|
||||
}
|
||||
@@ -29,45 +33,62 @@ final class SectorReconciliationExecution
|
||||
public function revision(): string
|
||||
{
|
||||
$file = database_path('data/sector-reconciliation-execution.json');
|
||||
$manifest = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$manifest = json_decode(CheckedFile::read($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$files = ['database/data/sector-reconciliation-execution.json' => hash_file('sha256', $file)];
|
||||
foreach ($manifest['files'] as $path) $files[$path] = hash_file('sha256', base_path($path));
|
||||
foreach ($manifest['files'] as $path) {
|
||||
$files[$path] = hash_file('sha256', base_path($path));
|
||||
}
|
||||
$sql = database_path('data/sector-reconciliation-20261018.sql');
|
||||
abort_unless(hash_equals($manifest['sql_sha256'], hash_file('sha256', $sql)), 409, 'SQL diferente da revisão delimitada.');
|
||||
abort_unless(hash_equals($manifest['sql_sha256'], CheckedFile::sha256($sql)), 409, 'SQL diferente da revisão delimitada.');
|
||||
$files['database/data/sector-reconciliation-20261018.sql'] = hash_file('sha256', $sql);
|
||||
foreach (\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $build) $files['public/build/'.$build->getRelativePathname()] = hash_file('sha256', $build->getPathname());
|
||||
foreach (File::allFiles(public_path('build')) as $build) {
|
||||
$files['public/build/'.$build->getRelativePathname()] = hash_file('sha256', $build->getPathname());
|
||||
}
|
||||
ksort($files);
|
||||
|
||||
return hash('sha256', json_encode($files, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function target(): array
|
||||
{
|
||||
return (array) DB::connection()->selectOne('SELECT current_database() AS database, inet_server_port() AS port', [], false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $target
|
||||
*/
|
||||
private function readiness(string $revision, array $target): void
|
||||
{
|
||||
$p = storage_path('app/private/investmoz-v2/sector-reconciliation/readiness.json');
|
||||
$proof = is_file($p) ? json_decode(file_get_contents($p), true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$proof = is_file($p) ? json_decode(CheckedFile::read($p), true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
abort_unless(($proof['operation'] ?? '') === self::OPERATION && ($proof['revision'] ?? '') === $revision
|
||||
&& ($proof['target'] ?? []) === $target && !empty($proof['authorization_record']), 409, 'Préflight/autorização da revisão e destino necessários.');
|
||||
$isolated = app()->environment('testing') && (int)$target['port'] === 55441
|
||||
&& ($proof['target'] ?? []) === $target && ! empty($proof['authorization_record']), 409, 'Préflight/autorização da revisão e destino necessários.');
|
||||
$isolated = app()->environment('testing') && (int) $target['port'] === 55441
|
||||
&& str_ends_with($target['database'], '_test') && config('database.connections.pgsql.host') === '127.0.0.1'
|
||||
&& !config('database.connections.pgsql.url');
|
||||
if (!$isolated) {
|
||||
&& ! config('database.connections.pgsql.url');
|
||||
if (! $isolated) {
|
||||
abort_unless(($proof['restore_verified'] ?? false) && ($proof['restored_boot_verified'] ?? false)
|
||||
&& strtotime($proof['verified_at'] ?? '') >= time() - 86400 && strtotime($proof['verified_at'] ?? '') <= time(), 409, 'Backup/restauro fresco do procedimento existente necessário.');
|
||||
foreach (['dump', 'files'] as $kind) abort_unless(is_file($proof[$kind.'_path'] ?? '')
|
||||
&& hash_equals($proof[$kind.'_sha256'] ?? '', hash_file('sha256', $proof[$kind.'_path'])), 409);
|
||||
foreach (['dump', 'files'] as $kind) {
|
||||
abort_unless(is_file($proof[$kind.'_path'] ?? '')
|
||||
&& hash_equals($proof[$kind.'_sha256'] ?? '', CheckedFile::sha256($proof[$kind.'_path'])), 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function preview(Request $request): array
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
abort_if($request->query->count(), 422, 'Ator, revisão ou opções por URL recusados.');
|
||||
$revision = $this->revision(); $target = $this->target(); $this->readiness($revision, $target);
|
||||
abort_if($request->query->count() > 0, 422, 'Ator, revisão ou opções por URL recusados.');
|
||||
$revision = $this->revision();
|
||||
$target = $this->target();
|
||||
$this->readiness($revision, $target);
|
||||
$state = ['operation' => self::OPERATION, 'revision' => $revision, 'target' => $target,
|
||||
'actor' => ['id' => $actor->id, 'name' => $actor->name], 'migrations' => [], 'ready' => true];
|
||||
$state['hash'] = hash_hmac('sha256', json_encode([$actor->id, $request->session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'));
|
||||
@@ -75,6 +96,9 @@ final class SectorReconciliationExecution
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function apply(Request $request): array
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
@@ -82,7 +106,9 @@ final class SectorReconciliationExecution
|
||||
$data = Validator::make($request->all(), ['hash' => 'required|string|size:64', 'operation_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||
$db = DB::connection();
|
||||
abort_unless($db->transactionLevel() === 0, 409, 'A operação deve possuir a sua transação.');
|
||||
$revision = $this->revision(); $target = $this->target(); $this->readiness($revision, $target);
|
||||
$revision = $this->revision();
|
||||
$target = $this->target();
|
||||
$this->readiness($revision, $target);
|
||||
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
|
||||
$result = $db->transaction(function () use ($db, $actor, $data, $request, $revision, $target, $requestHash) {
|
||||
@@ -90,8 +116,9 @@ final class SectorReconciliationExecution
|
||||
$old = $db->table('audit_events')->useWritePdo()->where('source_system', self::SOURCE)->where('correlation_id', $data['operation_key'])->first();
|
||||
if ($old) {
|
||||
$saved = json_decode($old->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
abort_unless((int)$old->actor_user_id === $actor->id && ($saved['revision'] ?? '') === $revision
|
||||
abort_unless((int) $old->actor_user_id === $actor->id && ($saved['revision'] ?? '') === $revision
|
||||
&& hash_equals($saved['request_hash'], $requestHash), 409);
|
||||
|
||||
return [...$saved['receipt'], 'replayed' => true];
|
||||
}
|
||||
$plan = $this->preview($request);
|
||||
@@ -99,13 +126,13 @@ final class SectorReconciliationExecution
|
||||
$before = $db->selectOne("SELECT pg_backend_pid() AS pid, txid_current()::text AS txid, NULLIF(current_setting('investmoz.actor_user_id',true),'') AS actor", [], false);
|
||||
abort_unless($before->actor === null, 409, 'Ligação contém um ator anterior; operação recusada.');
|
||||
// true means SET LOCAL. Same write connection and transaction execute every statement.
|
||||
$db->selectOne("SELECT set_config('investmoz.actor_user_id',?,true), set_config('investmoz.operation_key',?,true), set_config('investmoz.authorized_revision',?,true)", [(string)$actor->id, $data['operation_key'], $revision], false);
|
||||
$db->selectOne("SELECT set_config('investmoz.actor_user_id',?,true), set_config('investmoz.operation_key',?,true), set_config('investmoz.authorized_revision',?,true)", [(string) $actor->id, $data['operation_key'], $revision], false);
|
||||
$oldDataEvent = $db->table('audit_events')->useWritePdo()->where('source_system', self::OPERATION)->exists();
|
||||
$db->getPdo()->exec(file_get_contents(database_path('data/sector-reconciliation-20261018.sql')));
|
||||
$db->getPdo()->exec(CheckedFile::read(database_path('data/sector-reconciliation-20261018.sql')));
|
||||
$scope = $db->selectOne("SELECT pg_backend_pid() AS pid, txid_current()::text AS txid, current_setting('investmoz.actor_user_id') AS actor", [], false);
|
||||
abort_unless($scope->pid === $before->pid && $scope->txid === $before->txid && (int)$scope->actor === $actor->id, 500);
|
||||
abort_unless($scope->pid === $before->pid && $scope->txid === $before->txid && (int) $scope->actor === $actor->id, 500);
|
||||
$receipt = ['operation' => self::OPERATION, 'operation_key' => $data['operation_key'], 'revision' => $revision,
|
||||
'actor_user_id' => $actor->id, 'target' => $target, 'changed' => !$oldDataEvent, 'opportunity_id' => 2,
|
||||
'actor_user_id' => $actor->id, 'target' => $target, 'changed' => ! $oldDataEvent, 'opportunity_id' => 2,
|
||||
'sector_id' => 8, 'replayed' => false, 'connection_pid' => $scope->pid, 'transaction_id' => $scope->txid];
|
||||
$db->table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'sector-reconciliation', 'action' => 'execute',
|
||||
'actor_user_id' => $actor->id, 'correlation_id' => $data['operation_key'], 'data_classification' => 'internal',
|
||||
|
||||
@@ -23,6 +23,10 @@ final class SimulationExecution
|
||||
return $this->createPayload($payload, $actorId, $organizationId, $token, $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $snapshot
|
||||
* @return array{simulation: Simulation, token: string|null, replayed: bool}
|
||||
*/
|
||||
public function createFiscalQaPreview(array $snapshot, int $actorId, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
@@ -34,6 +38,10 @@ final class SimulationExecution
|
||||
$actorId, null, null, $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array{simulation: Simulation, token: string|null, replayed: bool}
|
||||
*/
|
||||
public function createPublishedFiscal(array $input, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
|
||||
{
|
||||
$payload = ['scenario_kind' => 'fiscal_rule_published', 'fiscal_input' => $input, 'organization_id' => $organizationId];
|
||||
@@ -42,6 +50,10 @@ final class SimulationExecution
|
||||
fn (): array => app(SimulationPublishedFiscal::class)->admit($input));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $payload
|
||||
* @return array{simulation: Simulation, token: string|null, replayed: bool}
|
||||
*/
|
||||
private function createPayload(array $payload, ?int $actorId, ?string $organizationId, ?string $token, string $key, ?callable $admit = null): array
|
||||
{
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
|
||||
|
||||
@@ -7,11 +7,16 @@ namespace App\Services;
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\User;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use App\Support\StructuredData;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Exact operation-level IVA calculation against an explicit QA draft; never a payment/return total. */
|
||||
final class SimulationFiscalQaPreview
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function create(User $actor, string $ruleId, array $input, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
@@ -20,7 +25,7 @@ final class SimulationFiscalQaPreview
|
||||
$rule = app(SimulationTaxRuleGovernance::class)->show($actor, $ruleId);
|
||||
abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422,
|
||||
'Seleccione o rascunho do primeiro lote fiscal.');
|
||||
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
abort_if(collect(StructuredData::collectionItems($rule->rule_definition['nodes'] ?? []))->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
'Este percurso preserva o valor exacto e não aplica arredondamento automático.');
|
||||
$source = InvestmentLegalSource::findOrFail($rule->legal_source_id);
|
||||
$version = $rule->attributesToArray();
|
||||
|
||||
@@ -9,6 +9,14 @@ use Brick\Math\BigRational;
|
||||
/** Shared snapshot representation; eligibility is resolved by each admission adapter. */
|
||||
final class SimulationFiscalSnapshot
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed>|null $evaluation
|
||||
* @param array<array-key, mixed> $input
|
||||
* @param array<array-key, mixed> $missing
|
||||
* @param array<array-key, mixed> $resolution
|
||||
* @param array<array-key, mixed> $version
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function build(array $version, array $input, array $resolution, ?array $evaluation, array $missing, bool $published = false): array
|
||||
{
|
||||
$date = $input['reference_date'];
|
||||
|
||||
@@ -4,6 +4,9 @@ namespace App\Services;
|
||||
|
||||
final class SimulationFiscalSourceAcceptance
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $source
|
||||
*/
|
||||
public static function eligible(array $source, ?string $hash = null): bool
|
||||
{
|
||||
if (($source['validation_status'] ?? null) === 'validated') {
|
||||
|
||||
@@ -60,7 +60,9 @@ final class SimulationFormDrafts
|
||||
throw new HttpException(409, 'Já existe um rascunho activo. Carregue-o antes de guardar novas alterações.');
|
||||
}
|
||||
|
||||
if ($case) $data['economic_snapshot'] = $this->landContext($data['economic_snapshot'], $case);
|
||||
if ($case) {
|
||||
$data['economic_snapshot'] = $this->landContext($data['economic_snapshot'], $case);
|
||||
}
|
||||
$snapshotHash = hash('sha256', json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
$draft = SimulationFormDraft::query()->create([
|
||||
'id' => (string) Str::uuid(), 'owner_user_id' => $actorId, 'anonymous_token_hash' => $tokenHash,
|
||||
@@ -459,15 +461,30 @@ final class SimulationFormDrafts
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $economic
|
||||
* @param array<array-key, mixed> $previous
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function preserveInactiveLandStatus(SimulationFormDraft $draft, array $economic, array $previous, ?int $actorId): array
|
||||
{
|
||||
if (! $actorId || ! config('investor-path.enabled') || ! app(VirtualDesk::class)->installed()) return $economic;
|
||||
if (! $actorId || ! config('investor-path.enabled') || ! app(VirtualDesk::class)->installed()) {
|
||||
return $economic;
|
||||
}
|
||||
// Use the real owner-bound dossier even if a request omits its context parameter.
|
||||
$case = DB::table('desk_cases')->where('simulation_id', $draft->id)->where('user_id', $actorId)->first();
|
||||
if (! $case) return $economic;
|
||||
if (! $case) {
|
||||
return $economic;
|
||||
}
|
||||
|
||||
return $this->landContext($economic, $case, $previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $economic
|
||||
* @param array<array-key, mixed>|null $previous
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function landContext(array $economic, \stdClass $case, ?array $previous = null): array
|
||||
{
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? $previous['context_applicability_snapshot'] ?? '', true);
|
||||
@@ -475,10 +492,16 @@ final class SimulationFormDrafts
|
||||
$key = app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), is_string($key) ? $key : null);
|
||||
$decision = app(InvestorContext::class)->landPreparation($case, $key);
|
||||
if ($decision['need'] !== 'yes' && $previous !== null) {
|
||||
if (array_key_exists('land_status', $previous)) $economic['land_status'] = $previous['land_status'];
|
||||
else unset($economic['land_status']);
|
||||
if (isset($previous['selection_labels']['land_status'])) $economic['selection_labels']['land_status'] = $previous['selection_labels']['land_status'];
|
||||
else unset($economic['selection_labels']['land_status']);
|
||||
if (array_key_exists('land_status', $previous)) {
|
||||
$economic['land_status'] = $previous['land_status'];
|
||||
} else {
|
||||
unset($economic['land_status']);
|
||||
}
|
||||
if (isset($previous['selection_labels']['land_status'])) {
|
||||
$economic['selection_labels']['land_status'] = $previous['selection_labels']['land_status'];
|
||||
} else {
|
||||
unset($economic['selection_labels']['land_status']);
|
||||
}
|
||||
}
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? $previous['context_applicability_snapshot'] ?? '', true);
|
||||
if (! is_array($snapshot) || ($snapshot['version'] ?? null) !== 1) {
|
||||
@@ -486,7 +509,9 @@ final class SimulationFormDrafts
|
||||
}
|
||||
$snapshot['land_preparation'] = $decision;
|
||||
$snapshot['consumer_opportunity'] = $key;
|
||||
if ($key) $economic['context_opportunity'] = $key;
|
||||
if ($key) {
|
||||
$economic['context_opportunity'] = $key;
|
||||
}
|
||||
$economic['context_applicability_snapshot'] = json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
return $economic;
|
||||
|
||||
@@ -5,6 +5,11 @@ namespace App\Services;
|
||||
/** Explains a failed selection; never changes answers, eligibility or calculation. */
|
||||
final class SimulationIvaDiagnostics
|
||||
{
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @param array<array-key, mixed> $versions
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function explain(array $versions, string $start, string $end, array $context): array
|
||||
{
|
||||
$diagnostics = [];
|
||||
|
||||
@@ -6,7 +6,9 @@ namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\SimulationTaxRuleVersion;
|
||||
use App\Support\StructuredData;
|
||||
use Brick\Math\BigRational;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -14,6 +16,9 @@ use Illuminate\Support\Str;
|
||||
/** Admission freezes eligibility without granting the public consumer governance write access. */
|
||||
final class SimulationPublishedFiscal
|
||||
{
|
||||
/**
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function availability(): array
|
||||
{
|
||||
$enabled = (bool) config('simulation-fiscal-consumer.enabled');
|
||||
@@ -24,6 +29,9 @@ final class SimulationPublishedFiscal
|
||||
: 'O cálculo de IVA geral sobre base líquida está indisponível para novas execuções. Os históricos mantêm-se acessíveis.'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<SimulationTaxRuleVersion>
|
||||
*/
|
||||
private function boundRule(): Builder
|
||||
{
|
||||
if (! Str::isUuid((string) config('simulation-fiscal-consumer.rule_id')) || config('simulation-fiscal-consumer.rule_version') < 1) {
|
||||
@@ -36,6 +44,10 @@ final class SimulationPublishedFiscal
|
||||
->where('scope_key', 'mz.internal-general-net.mzn');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
public function admit(array $input, bool $missingBase = false): array
|
||||
{
|
||||
if (isset($input['monthly_sales'])) {
|
||||
@@ -51,7 +63,7 @@ final class SimulationPublishedFiscal
|
||||
'A versão autorizada de IVA não está disponível para novas execuções. Os históricos foram preservados.');
|
||||
abort_if($input['reference_date'] < '2026-01-01' || $input['reference_date'] > '2026-12-31', 422,
|
||||
'Este cálculo abrange apenas exigibilidade em 2026. As entradas foram preservadas.');
|
||||
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
abort_if(collect(StructuredData::collectionItems($rule->rule_definition['nodes'] ?? []))->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
'A versão seleccionada não é compatível com o cálculo exacto deste consumidor.');
|
||||
DB::select('select pg_advisory_xact_lock_shared(261022, hashtext(?))', [(string) $rule->legal_source_id]);
|
||||
$source = InvestmentLegalSource::whereKey($rule->legal_source_id)->firstOrFail();
|
||||
@@ -87,6 +99,10 @@ final class SimulationPublishedFiscal
|
||||
return app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $input
|
||||
* @return array<array-key, mixed>
|
||||
*/
|
||||
private function admitMonthly(array $input): array
|
||||
{
|
||||
$rows = [];
|
||||
@@ -95,7 +111,7 @@ final class SimulationPublishedFiscal
|
||||
$complete = true;
|
||||
$previous = null;
|
||||
foreach ($input['monthly_sales'] as $sale) {
|
||||
abort_unless($previous === null || $sale['date'] === date('Y-m-d', strtotime($previous.' +1 month')), 422, 'A projecção deve conter meses consecutivos, sem duplicações.');
|
||||
abort_unless($previous === null || $sale['date'] === CarbonImmutable::parse($previous)->addMonth()->format('Y-m-d'), 422, 'A projecção deve conter meses consecutivos, sem duplicações.');
|
||||
$previous = $sale['date'];
|
||||
$known = $sale['amount'] !== null && $sale['amount'] !== '';
|
||||
$net = $input['sales_vat_basis'] === 'net';
|
||||
@@ -103,7 +119,7 @@ final class SimulationPublishedFiscal
|
||||
'currency' => $input['currency'], 'reference_date' => $sale['date'],
|
||||
'operation' => 'internal_general_net', 'scope_declared' => $input['scope_declared']], ! $known || ! $net);
|
||||
$snapshot ??= $month;
|
||||
$rate = collect($month['fiscal_provenance']['resolution'])->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
$rate = collect(StructuredData::collectionItems($month['fiscal_provenance']['resolution']))->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
$vat = $month['result']['value'];
|
||||
$status = ! $known ? 'missing_sales' : (! $net ? 'unsupported_basis' : ($vat === null ? 'indeterminate' : 'calculated'));
|
||||
$rows[] = ['date' => $sale['date'], 'sales_declared' => $sale['amount'],
|
||||
|
||||
@@ -138,7 +138,11 @@ final class SimulationTaxParameterResolver
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'published');
|
||||
}
|
||||
|
||||
/** Explicit draft preview. Never used by the published-parameter API. */
|
||||
/** Explicit draft preview. Never used by the published-parameter API.
|
||||
* @param array<array-key, mixed> $context
|
||||
* @param array<array-key, mixed> $versions
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function resolveDraftForQa(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
@@ -146,6 +150,11 @@ final class SimulationTaxParameterResolver
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'draft');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $context
|
||||
* @param array<array-key, mixed> $versions
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function resolveWithStatus(array $versions, string $component, string $periodStart, string $periodEnd, array $context, string $requiredStatus): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
@@ -62,14 +64,16 @@ class VerifiedDocumentBinary
|
||||
$links = $links->concat($query->get(['opportunity_id', 'deleted_at', 'payload']));
|
||||
}
|
||||
$privateOrigin = in_array($document->source_system ?? null, ['opportunity-resources', 'opportunity-image-derivatives'], true);
|
||||
if (! $privateOrigin) $links = $links->reject(fn ($link) => isset(json_decode($link->payload, true)['library_source']));
|
||||
if (! $privateOrigin) {
|
||||
$links = $links->reject(fn ($link) => isset(json_decode($link->payload, true)['library_source']));
|
||||
}
|
||||
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.');
|
||||
abort_unless($actor instanceof User, 403, 'Anexo privado: é necessário acesso autorizado à oportunidade.');
|
||||
foreach ($links as $link) {
|
||||
$opportunity = \App\Models\Opportunity::find($link->opportunity_id);
|
||||
$opportunity = Opportunity::whereKey($link->opportunity_id)->first();
|
||||
if ($link->deleted_at === null && $opportunity && $opportunity->status !== 'archived'
|
||||
&& app(PortalProfileAccess::class)->canView($actor, $opportunity)) {
|
||||
return;
|
||||
|
||||
@@ -197,9 +197,13 @@ class VirtualDesk
|
||||
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
|
||||
}
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
if (count($context['opportunity_choices'] ?? []) > 1 && !$opportunity) $payload['description'] = '';
|
||||
if (count($context['opportunity_choices'] ?? []) > 1 && ! $opportunity) {
|
||||
$payload['description'] = '';
|
||||
}
|
||||
$mapped = app(InvestorContext::class)->prefill($context, $opportunity)['desk'];
|
||||
if ($opportunity) $payload['context_opportunity'] = $opportunity;
|
||||
if ($opportunity) {
|
||||
$payload['context_opportunity'] = $opportunity;
|
||||
}
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $caseId, $payload);
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
foreach (['territory_id' => 'territory_id', 'location_source' => 'location_source', 'title' => 'title', 'description' => 'description', 'sector' => 'sector', 'province_id' => 'province_id', 'district_id' => 'district_id', 'admin_post_id' => 'admin_post_id', 'locality_id' => 'locality_id'] as $field => $source) {
|
||||
@@ -237,7 +241,9 @@ class VirtualDesk
|
||||
if (count($contextChoices) > 1) {
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? '{}', true);
|
||||
$draftChoices = $snapshot['opportunity_choices'] ?? [];
|
||||
if (count($draftChoices) !== 1 || ($draftChoices[0]['opportunity']['key'] ?? null) !== ($payload['context_opportunity'] ?? null)) return null;
|
||||
if (count($draftChoices) !== 1 || ($draftChoices[0]['opportunity']['key'] ?? null) !== ($payload['context_opportunity'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
$description = (string) ($economic['project_summary'] ?? '');
|
||||
if (trim($description) === '') {
|
||||
|
||||
Reference in New Issue
Block a user