@@ -14,12 +14,52 @@ use Throwable;
|
||||
|
||||
class ImportDocumentBatch extends Command
|
||||
{
|
||||
protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import}';
|
||||
protected $signature = 'documents:import-batch {manifest : JSON manifest inside storage/app/private/document-import-staging} {--apply : Register private drafts and queue malware scans} {--actor= : Existing user ID responsible for an applied import} {--pilot-agronegocio : Restrict to the approved two-original pilot} {--sectors-lot20 : Restrict to the named 20-resource sector batch} {--sectors-trio : Restrict to the three named sector articles and reuse the existing image} {--backup-proof= : Fresh verified destination backup receipt for active pilot apply}';
|
||||
|
||||
protected $description = 'Preview or idempotently import a document batch into the existing private library';
|
||||
|
||||
private const MAX_BYTES = 10485760;
|
||||
|
||||
private const PILOT_MANIFEST_SHA256 = '0b720b0a6f7539de1d3eca9e32f89a6b9038848dc0b97ad21ace605154d9ddd8';
|
||||
|
||||
private const PILOT_HASHES = [
|
||||
'legacy-tempo-post-171985-20260420' => '0929184a6d4645b9046512675394ad4f60575273f6dab0955f71cc7474a6a4e2',
|
||||
'legacy-tempo-agronegocio-image-5e3840705cf98226' => '5e3840705cf98226d1f189cf665aaa98cb05da96c645159a1332a1d429d642eb',
|
||||
];
|
||||
|
||||
private const SECTORS_MANIFEST_SHA256 = 'ade9a00c031534f4341e8f6bd5e425b502ee03efc9fcfaec4f463a10fb28201b';
|
||||
|
||||
private const SECTORS_HASHES = [
|
||||
'legacy-tempo-post-171981-20260430' => '26a70f16cd511c579f08633655ff312db05122f81e44852dd4b163fa6eef85f1',
|
||||
'legacy-tempo-post-172679-20260430' => '2003755b7dac53b43f4608e707321db6d2f29878926a0e74f4cf27627b70a9cb',
|
||||
'legacy-tempo-post-172674-20260430' => '3ae780f082a8fa7c767635cce98563f5bc027c9656c9f41f8788843a17fa1f54',
|
||||
'legacy-tempo-post-171990-20260616' => '8cab862be245382dd4c1fd5fcb423c47aed7be3a22e0a7f8d5521510cc36bc72',
|
||||
'legacy-tempo-post-172263-20260414' => '538495cd5b31047ac1c5993fdaf298ec1303330368248b251c87d201d31ff211',
|
||||
'legacy-tempo-post-172256-20260414' => 'dcc29cbd36cf57e0a5c88dd312c84ee03c32a3d18ae9216d3715dc7b5a6960bf',
|
||||
'legacy-tempo-post-172261-20260414' => '88177fccd78d8516dba670c6f71272af062cc981d52d97adefe5bf77c613b16a',
|
||||
'legacy-tempo-post-172258-20260417' => '48314a576dea2f2dadf47d8f1eadd7ab58030606b02eebe17aa9bd6badffb7e9',
|
||||
'legacy-tempo-post-172253-20260414' => 'e90e39e49ba65bbbcbbc303c6eca456e445238daf9acc935ab03690819281678',
|
||||
'legacy-tempo-post-172240-20260414' => '8c5e91c937032680883793a12844f1128f7ac99e97c63b68c23d1396e009ba9d',
|
||||
'legacy-tempo-post-172237-20260417' => 'a62a43e31da32795a7286f4c152a93d5dc829233e72023b00ea61fd8e2fcb58c',
|
||||
'legacy-tempo-post-172233-20260417' => '345dfd72d8ebf459eae8eb025d699afddbae751df55ffa8d053568cd08096c97',
|
||||
'legacy-tempo-post-172230-20260414' => '4f4570f7bbd5599cb925ed996c1734a23582362fe485736931a53b9266565d4e',
|
||||
'legacy-tempo-post-172223-20260414' => '514a9d88c097d234038fa6341f5a5b01e8938cb6a9535a807145c84c37010a4d',
|
||||
'legacy-tempo-post-172219-20260414' => '0d468ae0de9a76d2b140bc8cb5c555f29626fb6422287c917762bec3e615a70c',
|
||||
'legacy-tempo-post-171992-20260430' => '05eb492dd6cfca6a7f305b633658a16723c315168f4b2c75103f22d1fac84032',
|
||||
'legacy-tempo-image-0a2c50d91dad3a60' => '0a2c50d91dad3a6007544634540e0f61b11d3506682a5a19066bae03cdcba490',
|
||||
'legacy-tempo-image-28f41f12e10ab345' => '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa',
|
||||
'legacy-tempo-image-fe9a2e382e385b35' => 'fe9a2e382e385b35f6e61ae320e199a979678677fd327fb7d4b07d8ce0111c11',
|
||||
'legacy-tempo-image-8e58544e49e719f9' => '8e58544e49e719f9c865c91e07ef1030155a9e3d59260e6dc93e9c9e25674e39',
|
||||
];
|
||||
|
||||
private const TRIO_MANIFEST_SHA256 = '9210ad7e1bea557349c440fd8295b321a10c2ddd34cc170f3dad18b5517751f8';
|
||||
private const TRIO_REUSED_IMAGE_SHA256 = '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa';
|
||||
private const TRIO_HASHES = [
|
||||
'legacy-tempo-post-173209-20260623' => '926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941',
|
||||
'legacy-tempo-post-173218-20260616' => '43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5',
|
||||
'legacy-tempo-post-173213-20260616' => '0ba605ae43dec7f685610f828df884bc82cb4da67131fc9783b5cdbe4cc6d9f0',
|
||||
];
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$staging = storage_path('app/private/document-import-staging');
|
||||
@@ -43,7 +83,8 @@ class ImportDocumentBatch extends Command
|
||||
}
|
||||
|
||||
try {
|
||||
$manifest = json_decode((string) file_get_contents($manifestPath), true, 512, JSON_THROW_ON_ERROR);
|
||||
$manifestBytes = (string) file_get_contents($manifestPath);
|
||||
$manifest = json_decode($manifestBytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable) {
|
||||
$this->error('Manifest is not valid JSON.');
|
||||
|
||||
@@ -57,7 +98,24 @@ class ImportDocumentBatch extends Command
|
||||
|
||||
$apply = (bool) $this->option('apply');
|
||||
$actorId = $this->option('actor');
|
||||
if ($apply) {
|
||||
$pilot = (bool) $this->option('pilot-agronegocio');
|
||||
$sectors = (bool) $this->option('sectors-lot20');
|
||||
$trio = (bool) $this->option('sectors-trio');
|
||||
if ((int) $pilot + (int) $sectors + (int) $trio > 1) {
|
||||
$this->error('Select exactly one named batch; agribusiness scope is unchanged.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($pilot || $sectors || $trio) {
|
||||
try {
|
||||
$this->validatePilot($manifestPath, $manifestBytes, $manifest, $stagingReal, $apply, $actorId, $sectors, $trio);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('Pilot refused before import: '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
if ($apply && ! $pilot && ! $sectors && ! $trio) {
|
||||
// CLI attribution is not an authenticated active installation. Rehearsals stay isolated.
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
if (! app()->environment('testing') || ! str_ends_with($target->database, '_test') || (int) $target->port !== 55441
|
||||
@@ -87,6 +145,9 @@ class ImportDocumentBatch extends Command
|
||||
$label = is_array($record) ? (string) ($record['external_id'] ?? '#'.($index + 1)) : '#'.($index + 1);
|
||||
try {
|
||||
$validated = $this->validateRecord($record, $stagingReal);
|
||||
if (($pilot || $sectors || $trio) && ! hash_equals(($trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES))[$validated['external_id']] ?? '', $validated['sha256'])) {
|
||||
throw new RuntimeException('Approved pilot bytes changed after preview validation.');
|
||||
}
|
||||
$hash = $validated['sha256'];
|
||||
if (isset($seenHashes[$hash])) {
|
||||
$this->line($label.' | duplicate bytes within batch; references item '.$seenHashes[$hash]);
|
||||
@@ -215,6 +276,80 @@ class ImportDocumentBatch extends Command
|
||||
return $failures > 0 ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
|
||||
/** The extra CLI path is a named, byte-bound pilot; it is not a general active import gate. */
|
||||
private function validatePilot(string $manifestPath, string $manifestBytes, array $manifest, string $staging, bool $apply, mixed $actorId, bool $sectors = false, bool $trio = false): void
|
||||
{
|
||||
$allowed = $trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES);
|
||||
$manifestName = $trio ? 'legacy-trio-20261015/manifest.json' : ($sectors ? 'legacy-setores-lote20-20261015/manifest.json' : 'legacy-agronegocio/manifest.json');
|
||||
$manifestHash = $trio ? self::TRIO_MANIFEST_SHA256 : ($sectors ? self::SECTORS_MANIFEST_SHA256 : self::PILOT_MANIFEST_SHA256);
|
||||
if ($manifestPath !== realpath($staging.'/'.$manifestName)
|
||||
|| ! hash_equals($manifestHash, hash('sha256', $manifestBytes))
|
||||
|| count($manifest['documents']) !== count($allowed)) {
|
||||
throw new RuntimeException('Only the exact selected manifest and its fixed resource list are allowed.');
|
||||
}
|
||||
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||
$host = config('database.connections.pgsql.host');
|
||||
$qa = app()->environment('testing') && str_ends_with($target->database, '_test') && (int) $target->port === 55441;
|
||||
$active = ! app()->environment('testing') && $target->database === 'investemoz' && (int) $target->port === 5432;
|
||||
if ((! $qa && ! $active) || ! in_array($host, ['127.0.0.1', 'localhost'], true) || config('database.connections.pgsql.url')) {
|
||||
throw new RuntimeException('Pilot target identity is not permitted.');
|
||||
}
|
||||
if ($apply || $actorId !== null) {
|
||||
$actor = is_string($actorId) && preg_match('/^[1-9][0-9]*$/D', $actorId) ? User::find((int) $actorId) : null;
|
||||
if (! $actor || ! $actor->can('manage-portal')) {
|
||||
throw new RuntimeException('A real existing account with effective manage-portal authorization is required.');
|
||||
}
|
||||
}
|
||||
if ($active && $apply) {
|
||||
$this->validatePilotBackup($this->option('backup-proof'));
|
||||
}
|
||||
if ($trio) {
|
||||
$images = DB::table('documents as d')->join('portal_resources as r', 'r.document_id', '=', 'd.id')
|
||||
->where('d.external_id', 'legacy-tempo-image-28f41f12e10ab345')->where('d.sha256', self::TRIO_REUSED_IMAGE_SHA256)
|
||||
->whereNull('d.deleted_at')->where('d.status', 'active')->where('d.data_classification', 'public')
|
||||
->where('d.rights_status', 'authorized')->where('r.rights_status', 'authorized')->where('r.published', true)
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->get(['d.storage_key']);
|
||||
if ($images->count() !== 1 || ! Storage::disk('local')->exists($images[0]->storage_key)
|
||||
|| ! hash_equals(self::TRIO_REUSED_IMAGE_SHA256, hash_file('sha256', Storage::disk('local')->path($images[0]->storage_key)))) {
|
||||
throw new RuntimeException('The shared image must already exist once, published, authorized and clean with the exact original bytes; no image is imported.');
|
||||
}
|
||||
}
|
||||
foreach ($manifest['documents'] as $record) {
|
||||
$entry = $this->validateRecord($record, $staging);
|
||||
if (! hash_equals($allowed[$entry['external_id']] ?? '', $entry['sha256'])) {
|
||||
throw new RuntimeException('Article or image differs from the approved SHA-256.');
|
||||
}
|
||||
$existing = DB::table('documents')->where('sha256', $entry['sha256'])->whereNull('deleted_at')->first();
|
||||
if ($existing && ($existing->external_id !== $entry['external_id']
|
||||
|| ! DB::table('portal_resources')->where('document_id', $existing->id)->exists())) {
|
||||
throw new RuntimeException('Matching bytes have another identity or no library resource; reconcile explicitly.');
|
||||
}
|
||||
if (DB::table('documents')->where('external_id', $entry['external_id'])->whereNull('deleted_at')
|
||||
->where('sha256', '!=', $entry['sha256'])->exists()
|
||||
|| (! $existing && DB::table('portal_resources')->where('document_identity_key', $this->identity($entry))->exists())) {
|
||||
throw new RuntimeException('Existing identity/version conflicts with this pilot; no overwrite or partial preflight import.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function validatePilotBackup(mixed $path): void
|
||||
{
|
||||
if (! is_string($path) || ! is_file($path)) {
|
||||
throw new RuntimeException('Active pilot apply requires a fresh verified backup/restoration receipt.');
|
||||
}
|
||||
$proof = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
|
||||
$verified = strtotime($proof['verified_at'] ?? '');
|
||||
if (! ($proof['restore_verified'] ?? false) || ! ($proof['files_verified'] ?? false)
|
||||
|| ($proof['target']['database'] ?? '') !== 'investemoz' || (int) ($proof['target']['port'] ?? 0) !== 5432
|
||||
|| ! str_ends_with($proof['restore_target']['database'] ?? '', '_test') || (int) ($proof['restore_target']['port'] ?? 0) !== 55441
|
||||
|| $verified === false || $verified > time() || $verified < time() - 86400
|
||||
|| ! is_file($proof['dump_path'] ?? '') || ! is_file($proof['files_path'] ?? '')
|
||||
|| ! hash_equals($proof['sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
|
||||
|| ! hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))) {
|
||||
throw new RuntimeException('Backup/restoration identity, freshness or integrity does not match the active pilot.');
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function validateRecord(mixed $record, string $stagingRoot): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\ExistingBusinessClassification;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class ExistingBusinessClassificationController extends Controller
|
||||
{
|
||||
public function show(Request $request, string $id, ExistingBusinessClassification $service): Response|JsonResponse
|
||||
{
|
||||
$props = ['supplement' => $service->privateView($request->user(), app(BusinessRepository::class)->find($id))];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/business-classification', $props);
|
||||
}
|
||||
|
||||
public function act(Request $request, string $id, ExistingBusinessClassification $service): JsonResponse
|
||||
{
|
||||
$business = $service->act($request->user(), $id, $request->all());
|
||||
|
||||
return response()->json(['supplement' => $service->privateView($request->user(), $business)]);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
if (! empty($filters['geo_location_id'])) {
|
||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, app(InvestmentGeography::class)->descendants($filters['geo_location_id']));
|
||||
}
|
||||
foreach (['zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) {
|
||||
foreach (['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'zee_id', 'zfi_id', 'park_id', 'education', 'facets', 'sector', 'province', 'district', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level'] as $field) {
|
||||
if (isset($filters[$field]) && $filters[$field] !== '' && $filters[$field] !== false && $filters[$field] !== []) {
|
||||
return $query->whereRaw('false')->get();
|
||||
}
|
||||
@@ -131,7 +131,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
{
|
||||
$filters = $catalogue->filters($request);
|
||||
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
|
||||
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
|
||||
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
|
||||
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
|
||||
$zoneFilters = $filters;
|
||||
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\FintechInvestment;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\SectorInvestment;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -21,21 +23,45 @@ class InvestorPathController extends Controller
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
|
||||
}
|
||||
|
||||
public function sectorStart(Request $request, string $sectorSlug, InvestorPath $path): JsonResponse|Response
|
||||
{
|
||||
abort_unless($path->available(), 404);
|
||||
$data = ['contexts' => $path->contexts($request->user()), 'sectorSource' => app(SectorInvestment::class)->context($sectorSlug)];
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
|
||||
}
|
||||
|
||||
public function sectorAttach(Request $request, string $id): JsonResponse|RedirectResponse
|
||||
{
|
||||
app(SectorInvestment::class)->attach($request->user(), $id, $request->all());
|
||||
|
||||
return $request->expectsJson() ? response()->json(['ok' => true]) : redirect('/investimentos/'.$id)->with('success', 'Setor associado ao mesmo dossier.');
|
||||
}
|
||||
|
||||
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
|
||||
{
|
||||
$sector = $request->validate(['sector_slug' => 'nullable|string|max:150'])['sector_slug'] ?? null;
|
||||
if ($sector !== null) {
|
||||
app(SectorInvestment::class)->context($sector);
|
||||
}
|
||||
$source = $request->input('content_resource_id');
|
||||
if ($source !== null) {
|
||||
$resourceId = filter_var($source, FILTER_VALIDATE_INT);
|
||||
abort_unless(is_int($resourceId) && $resourceId !== 0, 422);
|
||||
app(LegacyContent::class)->articleForResource($resourceId);
|
||||
}
|
||||
$id = DB::transaction(function () use ($path, $request, $source): string {
|
||||
$id = DB::transaction(function () use ($path, $request, $source, $sector): string {
|
||||
$id = $path->create($request->user(), $request->all());
|
||||
if ($source !== null) {
|
||||
$case = $path->view($request->user(), $id)['case'];
|
||||
app(LegacyContent::class)->attach($request->user(), $id, ['version' => $case['version'], 'resource_id' => (int) $source]);
|
||||
}
|
||||
|
||||
if ($sector !== null) {
|
||||
$case = $path->view($request->user(), $id)['case'];
|
||||
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector]);
|
||||
}
|
||||
|
||||
return $id;
|
||||
});
|
||||
|
||||
@@ -80,6 +106,14 @@ class InvestorPathController extends Controller
|
||||
return $request->expectsJson() ? response()->json(['id' => $task], 201) : back()->with('success', 'Tarefa assumida no acompanhamento interno.');
|
||||
}
|
||||
|
||||
public function fintech(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
|
||||
{
|
||||
abort_unless($path->available(), 404);
|
||||
app(FintechInvestment::class)->save($request->user(), $id, $request->all());
|
||||
|
||||
return $this->saved($request, 'Caracterização Fintech guardada no mesmo dossier; pendências e histórico preservados.');
|
||||
}
|
||||
|
||||
private function saved(Request $request, string $message): JsonResponse|RedirectResponse
|
||||
{
|
||||
return $request->expectsJson() ? response()->json(['message' => $message]) : back()->with('success', $message);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OpportunityClassification;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OpportunityClassificationController extends Controller
|
||||
{
|
||||
public function index(Request $request, int $id, OpportunityClassification $service): JsonResponse
|
||||
{
|
||||
$record = Opportunity::findOrFail($id);
|
||||
app(PortalProfileAccess::class)->authorize($request->user(), 'view', $record);
|
||||
|
||||
return response()->json(['version' => $service::VERSION, 'etag' => app(OpportunityManagement::class)->etag($record), 'rows' => $service->listing($request->user(), $record), 'duplicates' => $service->duplicates($request->user(), $record)])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function review(Request $request, int $id, OpportunityClassification $service): JsonResponse
|
||||
{
|
||||
$record = $service->review($request->user(), Opportunity::findOrFail($id), $request->all());
|
||||
|
||||
return response()->json(['etag' => app(OpportunityManagement::class)->etag($record), 'rows' => $service->listing($request->user(), $record)])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,11 @@ class OpportunityManagementController extends Controller
|
||||
'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'),
|
||||
'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]);
|
||||
$values = $record ? $service->values($record) : [];
|
||||
if (! $record && $request->filled('sector_id')) {
|
||||
$selection = $request->validate(['sector_id' => ['required', 'integer', Rule::exists('sectors', 'id')->where('is_active', true)->whereNull('deleted_at')]]);
|
||||
$values['sector_id'] = (int) $selection['sector_id'];
|
||||
$values['canonical']['sector_id'] = (int) $selection['sector_id'];
|
||||
}
|
||||
Inertia::share('publicationPreview', app(OpportunityCanonicalContract::class)->publicProjection($values['canonical'] ?? []));
|
||||
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
|
||||
|
||||
|
||||
@@ -123,12 +123,21 @@ class PortalProfileController extends Controller
|
||||
return app(OpportunityManagementController::class)->index($request, app(OpportunityManagement::class));
|
||||
}
|
||||
|
||||
public function edit(Request $request, PortalProfileAccess $access, ?int $id = null): Response
|
||||
public function edit(Request $request, PortalProfileAccess $access, ?int $id = null): Response|\Symfony\Component\HttpFoundation\Response
|
||||
{
|
||||
if ($id) {
|
||||
$access->authorize($request->user(), str_ends_with($request->path(), '/view') ? 'view' : 'edit', Opportunity::withTrashed()->findOrFail($id));
|
||||
} else {
|
||||
abort_unless($access->navigation($request->user())['contexts'] ?? [], 403);
|
||||
if (! ($access->navigation($request->user())['contexts'] ?? [])) {
|
||||
$reason = $access->has($request->user(), 'auditor')
|
||||
? 'O papel de Auditor permite consulta e impede a criação de oportunidades.'
|
||||
: 'Esta conta não dispõe de um contexto ativo de Promotor para uma organização e modalidade autorizadas. Confirme a vigência, o âmbito e os tipos atribuídos na gestão de perfis. A elevação excecional de Superutilizador não substitui a autorização de Promotor.';
|
||||
if ($request->expectsJson()) {
|
||||
abort(403, $reason);
|
||||
}
|
||||
|
||||
return response()->view('profiles.creation-unavailable', ['reason' => $reason], 403);
|
||||
}
|
||||
}
|
||||
|
||||
return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id);
|
||||
|
||||
@@ -6,6 +6,8 @@ use App\Http\Resources\PublicBusinessOpportunityResource;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use App\Services\ExistingBusinessClassification;
|
||||
use App\Services\OpportunityClassification;
|
||||
use App\Services\InvestmentGeography;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -19,16 +21,10 @@ class PublicBusinessOpportunityController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:120'],
|
||||
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
|
||||
'sector' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
|
||||
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
]);
|
||||
$filters = $this->filters($request);
|
||||
|
||||
$query = $this->publishedQuery();
|
||||
app(ExistingBusinessClassification::class)->constrain($query, $filters);
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
@@ -53,12 +49,27 @@ class PublicBusinessOpportunityController extends Controller
|
||||
$query->where('existing_businesses.modality', $filters['modality']);
|
||||
}
|
||||
|
||||
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->withQueryString());
|
||||
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->appends($filters));
|
||||
if ($request->expectsJson()) {
|
||||
return $results->response();
|
||||
}
|
||||
|
||||
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path]);
|
||||
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path,
|
||||
'classificationOptions' => app(OpportunityClassification::class)->options(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz'])]);
|
||||
}
|
||||
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:120'],
|
||||
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
|
||||
'sector' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
|
||||
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
...app(ExistingBusinessClassification::class)->filterRules(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $slug): Response|JsonResponse
|
||||
@@ -69,7 +80,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
return $resource->response();
|
||||
}
|
||||
|
||||
$returnFilters = $request->query();
|
||||
$returnFilters = $this->filters($request);
|
||||
|
||||
return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request),
|
||||
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
|
||||
@@ -80,7 +91,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
{
|
||||
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
|
||||
|
||||
$returnFilters = $request->query();
|
||||
$returnFilters = $this->filters($request);
|
||||
|
||||
return Inertia::render('investment/business-interest', [
|
||||
'record' => (new PublicBusinessOpportunityResource($record))->resolve($request),
|
||||
@@ -109,6 +120,7 @@ class PublicBusinessOpportunityController extends Controller
|
||||
'existing_businesses.activity_code', 'existing_businesses.stage', 'existing_businesses.objective',
|
||||
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
|
||||
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
|
||||
'existing_businesses.owner_user_id', 'existing_businesses.organization_id', 'existing_businesses.version_no', 'existing_businesses.expires_at', 'existing_businesses.status', 'existing_businesses.modality',
|
||||
'public_location.province', 'public_location.district', 'public_location.locality']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\SectorInvestment;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
@@ -23,6 +24,7 @@ class PublicPortalController extends Controller
|
||||
$sector = Sector::where('slug', $slug)->where('is_active', true)->firstOrFail();
|
||||
|
||||
return Inertia::render('portal/services', ['section' => 'sector', 'sector' => $sector->only(['name', 'slug', 'description', 'short_description']),
|
||||
'sectorEntry' => array_key_exists($sector->slug, SectorInvestment::CONTENT) ? app(SectorInvestment::class)->publicView($sector) : null,
|
||||
'opportunities' => $sector->opportunities()->published()->latest('published_at')->limit(12)->get(['title', 'slug', 'province', 'summary'])]);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ class ProtectProfileOpportunity
|
||||
if ($record && ($record->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades'))) {
|
||||
abort_if($record->owner_user_id === null && str_starts_with($request->path(), 'minhas-oportunidades'), 403, 'Registo legado não convertido para a política v1.');
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') ? 'view' : 'edit', $record);
|
||||
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') || $request->is('minhas-oportunidades/*/classification/review') ? 'view' : 'edit', $record);
|
||||
abort_if($request->is('management/opportunity-origin/apply'), 403, 'O cadastro privado v1 não usa a classificação editorial dos exemplos legados.');
|
||||
abort_if($request->isMethod('POST') && str_ends_with($request->path(), '/lifecycle') && ! str_contains($request->path(), '/resources/'), 403, 'Use o workflow com decisões segregadas; o perfil não concede exclusão.');
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ class PublicBusinessOpportunityResource extends JsonResource
|
||||
'province' => $this->resource->getAttribute('province'),
|
||||
'district' => $this->resource->getAttribute('district'),
|
||||
'locality' => $this->resource->getAttribute('locality'),
|
||||
'multidimensional' => app(\App\Services\ExistingBusinessClassification::class)->publicRows($this->resource),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ExistingBusinessPolicy
|
||||
{
|
||||
@@ -96,6 +97,50 @@ class ExistingBusinessPolicy
|
||||
}
|
||||
}
|
||||
|
||||
/** Supplement-only authority never changes the normal content/workflow abilities. */
|
||||
public function prepareClassification(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->owns($user, $business) && ! app(PortalProfileAccess::class)->has($user, 'auditor')
|
||||
&& in_array($business->status, ['draft', 'needs_information', 'published'], true);
|
||||
}
|
||||
|
||||
public function reviewClassification(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& ! app(PortalProfileAccess::class)->has($user, 'auditor')
|
||||
&& in_array($business->status, ['triage', 'in_review', 'needs_information', 'published'], true)
|
||||
&& $this->designated($user, 'reviewers', $business);
|
||||
}
|
||||
|
||||
/** Current responsibility check without requiring a reviewer's live browser session on public reads. */
|
||||
public function classificationReviewerScope(User $user, ExistingBusiness $business, string $dimension): bool
|
||||
{
|
||||
if ($business->trashed() || ! $user->hasVerifiedEmail() || (int) $business->owner_user_id === (int) $user->id) {
|
||||
return false;
|
||||
}
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->has($user, 'auditor')) { return false; }
|
||||
if (! $access->available()) {
|
||||
return $access->legacyWriteAllowed($user) && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
|
||||
}
|
||||
if ($business->modality !== 'company_sale') { return false; }
|
||||
$responsibility = $dimension === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
|
||||
return collect($access->grants($user, 'validator'))->contains(fn ($g) => $g->organization_id === null
|
||||
&& in_array('business_sale', json_decode($g->opportunity_types, true), true)
|
||||
&& in_array($responsibility, json_decode($g->responsibilities, true), true));
|
||||
}
|
||||
|
||||
public function discloseClassification(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
if ($business->trashed() || $business->status !== 'published' || (int) $business->owner_user_id === (int) $user->id
|
||||
|| app(PortalProfileAccess::class)->has($user, 'auditor') || ! $this->designated($user, 'publishers', $business)) {
|
||||
return false;
|
||||
}
|
||||
return ! DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
->whereIn('to_status', ['approval_l2', 'approved'])->where('actor_id', $user->id)->exists();
|
||||
}
|
||||
|
||||
private function designatedAny(User $user, ?ExistingBusiness $business = null): bool
|
||||
{
|
||||
foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) {
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use App\Policies\ExistingBusinessPolicy;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Supplement of the same UUID. All state remains in the existing immutable encrypted journal. */
|
||||
class ExistingBusinessClassification
|
||||
{
|
||||
public const VERSION = 'business-classification-20261016-v1';
|
||||
private const ACTIONS = ['classification_prepared', 'classification_reviewed', 'classification_disclosed', 'classification_withdrawn'];
|
||||
|
||||
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']);
|
||||
if (! $revision) {
|
||||
return ['schema_version' => self::VERSION, 'relations' => [], 'authors' => [], 'decisions' => [], 'publication' => []];
|
||||
}
|
||||
$state = json_decode(Crypt::decryptString($revision->snapshot), true, 512, JSON_THROW_ON_ERROR)['context']['multidimensional'] ?? null;
|
||||
abort_unless(is_array($state) && ($state['schema_version'] ?? '') === self::VERSION, 409, 'Versão do suplemento não reconhecida; preserve o histórico.');
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
private function hash(array $row): string
|
||||
{
|
||||
return OpportunityCanonicalValue::hash($row);
|
||||
}
|
||||
|
||||
private function evidence(array $row, ExistingBusiness $business): ?array
|
||||
{
|
||||
$id = $row['classification']['document_id'] ?? null;
|
||||
if (! $id) {
|
||||
return null;
|
||||
}
|
||||
$document = DB::table('existing_business_document_links as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.existing_business_id', $business->id)->where('d.id', $id)
|
||||
->first(['l.id as link_id', 'd.id', 'd.sha256', 'd.version_no', 'd.status', 'd.deleted_at', 'd.valid_until', 'd.malware_scan_status', 'd.malware_scanned_sha256']);
|
||||
|
||||
return $document ? (array) $document : ['unavailable' => $id];
|
||||
}
|
||||
|
||||
private function evidenceHash(array $row, ExistingBusiness $business): ?string
|
||||
{
|
||||
$evidence = $this->evidence($row, $business);
|
||||
|
||||
return $evidence === null ? null : OpportunityCanonicalValue::hash($evidence);
|
||||
}
|
||||
|
||||
private function validateRows(array $rows, ExistingBusiness $business, bool $confirming = false): void
|
||||
{
|
||||
$seen = [];
|
||||
foreach ($rows as $i => $row) {
|
||||
$fail = fn ($key, $message) => throw ValidationException::withMessages(['canonical.relations.'.$i.'.'.$key => $message]);
|
||||
Validator::make($row, [
|
||||
'related_id' => ['required', 'string', 'max:80'], 'relation_type' => ['required', 'string', 'max:80'],
|
||||
'classification' => ['required', 'array:target_type,purpose,criteria,justification,source_reference,citation,document_id,authority_id,requested_state,disclosure,valid_from,valid_until,external_status,external_act_reference,production_stage'],
|
||||
'classification.target_type' => ['required', Rule::in(array_keys(OpportunityClassification::TARGETS))],
|
||||
'classification.purpose' => ['required', Rule::in(array_keys(OpportunityClassification::PURPOSES))],
|
||||
'classification.requested_state' => ['required', Rule::in(['draft', 'preliminary', 'in_validation'])],
|
||||
'classification.disclosure' => ['required', Rule::in(['restricted', 'public'])],
|
||||
'classification.criteria' => ['nullable', 'string', 'max:2000'], 'classification.justification' => ['nullable', 'string', 'max:4000'],
|
||||
'classification.source_reference' => ['nullable', 'string', 'max:2000'], 'classification.citation' => ['nullable', 'string', 'max:1000'],
|
||||
'classification.document_id' => ['nullable', 'uuid'], 'classification.authority_id' => ['nullable', 'uuid'],
|
||||
'classification.valid_from' => ['nullable', 'date_format:Y-m-d'], 'classification.valid_until' => ['nullable', 'date_format:Y-m-d'],
|
||||
'classification.external_status' => ['required', Rule::in(OpportunityClassification::EXTERNAL)],
|
||||
'classification.external_act_reference' => ['nullable', 'string', 'max:2000'], 'classification.production_stage' => ['nullable', 'string', 'max:250'],
|
||||
])->validate();
|
||||
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'];
|
||||
if (($kind === 'sector' && ! ctype_digit($row['related_id'])) || ($kind !== 'sector' && ! Str::isUuid($row['related_id']))) {
|
||||
$fail('related_id', 'Identificador de referência inválido.');
|
||||
}
|
||||
if (! app(OpportunityClassification::class)->targets($kind)->where('id', $row['related_id'])->exists()) {
|
||||
$fail('related_id', 'Selecione uma referência existente e consultável.');
|
||||
}
|
||||
if (in_array($c['purpose'], ['regime_recognition', 'enterprise_admission', 'specific_benefit'], true) && $kind !== 'zone') {
|
||||
$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.'); }
|
||||
$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.');
|
||||
}
|
||||
if (! empty($c['authority_id']) && ! DB::table('authorities')->where('id', $c['authority_id'])->where('status', 'published')->exists()) {
|
||||
$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 (($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 ($evidence && ($evidence['status'] !== 'active' || $evidence['deleted_at'] !== null || $evidence['malware_scan_status'] !== 'clean'
|
||||
|| ! hash_equals(trim($evidence['sha256']), trim((string) $evidence['malware_scanned_sha256']))
|
||||
|| (! empty($evidence['valid_until']) && $evidence['valid_until'] < today()->toDateString()))) {
|
||||
$fail('classification.document_id', 'O suporte associado não está disponível, íntegro e analisado para esta confirmação.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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']; }
|
||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||
$reviewer = User::find($decision['actor_id']);
|
||||
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)) {
|
||||
return 'in_validation';
|
||||
}
|
||||
|
||||
return 'confirmed';
|
||||
}
|
||||
|
||||
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];
|
||||
$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,
|
||||
'history' => $state['decisions'][$hash]['history'] ?? []];
|
||||
}
|
||||
$documents = DB::table('existing_business_document_links as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.existing_business_id', $business->id)->whereNull('d.deleted_at')->get(['d.id', 'd.file_name', 'd.sha256']);
|
||||
|
||||
return ['id' => $business->id, 'title' => $business->public_title, 'status' => $business->status, 'version_no' => $business->version_no,
|
||||
'rows' => $rows, 'publication' => $this->publicRows($business), 'publication_version' => $state['publication_version'] ?? null,
|
||||
'preview' => $this->publicRows($business, [...$state, 'publication' => array_values(array_filter($state['relations'], fn ($r) => $r['classification']['disclosure'] === 'public'))]),
|
||||
'can_prepare' => Gate::forUser($actor)->allows('prepareClassification', $business),
|
||||
'can_disclose' => Gate::forUser($actor)->allows('discloseClassification', $business),
|
||||
'options' => app(OpportunityClassification::class)->options(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz']),
|
||||
'documents' => $documents->map(fn ($d) => ['id' => $d->id, 'payload' => ['title' => $d->file_name], 'file' => ['file_name' => $d->file_name]])];
|
||||
}
|
||||
|
||||
public function act(User $actor, string $id, array $input): ExistingBusiness
|
||||
{
|
||||
$data = Validator::make($input, [
|
||||
'action' => ['required', Rule::in(['prepare', 'review', 'disclose', 'withdraw'])], 'version_no' => ['required', 'integer', 'min:1'],
|
||||
'reason' => ['required', 'string', 'min:20', 'max:1000'],
|
||||
'rows' => ['required_if:action,prepare', 'array', 'max:100'],
|
||||
'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.');
|
||||
|
||||
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);
|
||||
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; }
|
||||
} 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']));
|
||||
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); }
|
||||
$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];
|
||||
$state['decisions'][$data['hash']] = [...$decision, 'history' => [...($prior['history'] ?? []), $decision]];
|
||||
if (in_array($data['state'], ['revoked', 'archived'], true)) {
|
||||
// Explicit withdrawal is retained: a later confirmation must not silently republish it.
|
||||
$state['publication'] = array_values(array_filter($state['publication'], fn ($r) => $this->hash($r) !== $data['hash']));
|
||||
}
|
||||
} else {
|
||||
$publication = $action === 'withdraw' ? [] : array_values(array_filter($state['relations'], fn ($r) => $r['classification']['disclosure'] === 'public'));
|
||||
$this->validateRows($publication, $business);
|
||||
// Existing publication independence also applies to the actors deciding this supplement.
|
||||
foreach ($publication as $row) {
|
||||
abort_if((int) ($state['decisions'][$this->hash($row)]['actor_id'] ?? 0) === (int) $actor->id, 403, 'A divulgação deve ser feita por pessoa diferente de quem decidiu a associação.');
|
||||
}
|
||||
$state['publication'] = $publication;
|
||||
$state['publication_version'] = $business->version_no + 1;
|
||||
$state['publication_actor'] = $actor->id;
|
||||
$state['publication_at'] = now()->toIso8601String();
|
||||
}
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
$event = ['prepare' => 'classification_prepared', 'review' => 'classification_reviewed', 'disclose' => 'classification_disclosed', 'withdraw' => 'classification_withdrawn'][$action];
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $event, $data['reason'], ['multidimensional' => $state]);
|
||||
|
||||
return $business;
|
||||
});
|
||||
}
|
||||
|
||||
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 = [];
|
||||
foreach ($state['publication'] as $row) {
|
||||
$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; }
|
||||
$effective = $this->effective($business, $row, $state);
|
||||
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]}, '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];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public function filterRules(): array
|
||||
{
|
||||
return ['association_type' => ['nullable', Rule::in(array_keys(OpportunityClassification::TARGETS))],
|
||||
'association_target' => ['nullable', 'string', 'max:80'], 'association_purpose' => ['nullable', Rule::in(array_keys(OpportunityClassification::PURPOSES))],
|
||||
'association_state' => ['nullable', Rule::in(OpportunityClassification::STATES)],
|
||||
'chain_id' => ['nullable', 'uuid'], 'authority_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid']];
|
||||
}
|
||||
|
||||
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; }
|
||||
$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']));
|
||||
$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; }
|
||||
}
|
||||
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['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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Ai\InvestorGuidanceRules;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Private characterization in the existing dossier; no legal classification or new workflow. */
|
||||
final class FintechInvestment
|
||||
{
|
||||
public const VERSION = 'fintech-preparation-v1';
|
||||
|
||||
public const FIELDS = [
|
||||
'problem' => 'Problema a resolver', 'clients' => 'Público-alvo e clientes nacionais/estrangeiros',
|
||||
'value' => 'Proposta de valor', 'revenues' => 'Modelo de receitas', 'services' => 'Serviços pretendidos',
|
||||
'channels' => 'Canais de prestação', 'currencies' => 'Moedas de operação declaradas',
|
||||
'location' => 'Localização efetiva e instalações', 'coverage' => 'Abrangência de operação',
|
||||
'technology' => 'Tecnologia e arquitetura', 'infrastructure' => 'Infraestrutura',
|
||||
'suppliers' => 'Fornecedores críticos', 'security' => 'Segurança e resposta a incidentes',
|
||||
'continuity' => 'Continuidade e recuperação', 'partners' => 'Instituições financeiras e parceiros',
|
||||
'team' => 'Equipa e capacidade operacional', 'maturity' => 'Maturidade declarada',
|
||||
'dependencies' => 'Dependências concretas', 'schedule' => 'Calendário de implementação',
|
||||
];
|
||||
|
||||
public const ACTIVITIES = ['moves_funds' => 'Movimentar fundos', 'deposits' => 'Receber depósitos',
|
||||
'custody' => 'Custodiar fundos', 'credit' => 'Conceder crédito', 'payments' => 'Serviços de pagamento',
|
||||
'investment_intermediation' => 'Intermediar investimentos', 'other' => 'Outra atividade potencialmente regulada'];
|
||||
|
||||
public const DOCUMENTS = ['business_plan' => ['S04', 'Modelo de negócio, mercado e plano de investimento'],
|
||||
'entity' => ['S05', 'Entidade, representação e participação'], 'architecture' => ['S06', 'Arquitetura tecnológica e fluxos de dados'],
|
||||
'security' => ['S16', 'Segurança, continuidade e fornecedores'], 'fund_flows' => ['S08', 'Fluxos de fundos e enquadramento da atividade'],
|
||||
'customers' => ['S17', 'Atendimento, reclamações e proteção do utilizador'],
|
||||
'external' => ['S08', 'Pedido ou decisão externa e respetivo âmbito'], 'tests' => ['S17', 'Testes e preparação operacional']];
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
public function save(User $actor, string $id, array $input): void
|
||||
{
|
||||
$keys = implode(',', array_keys(self::FIELDS));
|
||||
$activities = implode(',', array_keys(self::ACTIVITIES));
|
||||
$rules = ['version' => 'required|integer|min:1', 'profile' => ['required', 'array:model,fields,operation_countries,activities,activity_basis,documents'],
|
||||
'profile.model' => ['nullable', Rule::in(['technology_provider', 'financial_operator', 'undetermined'])],
|
||||
'profile.fields' => ['nullable', 'array:'.$keys], 'profile.operation_countries' => 'nullable|array|max:249',
|
||||
'profile.operation_countries.*' => ['required', 'distinct', app(CountryCatalogue::class)->rule()],
|
||||
'profile.activities' => ['nullable', 'array:'.$activities], 'profile.activity_basis' => 'nullable|string|max:3000',
|
||||
'profile.documents' => 'nullable|array|max:8', 'profile.documents.*' => 'nullable|uuid'];
|
||||
foreach (self::FIELDS as $key => $label) {
|
||||
$rules['profile.fields.'.$key] = 'nullable|string|max:4000';
|
||||
}
|
||||
foreach (self::ACTIVITIES as $key => $label) {
|
||||
$rules['profile.activities.'.$key] = ['nullable', Rule::in(['yes', 'no', 'unknown'])];
|
||||
}
|
||||
$rules['profile.documents'] = ['nullable', 'array:'.implode(',', array_keys(self::DOCUMENTS))];
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at, 409, 'O dossier está encerrado.');
|
||||
abort_unless($this->desk->owns($actor, $case), 403, 'Sem autorização para preparar este dossier.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$profile = $data['profile'];
|
||||
$profile['model'] = $profile['model'] ?? 'undetermined';
|
||||
$profile['fields'] = array_map(fn ($v) => trim((string) $v), $profile['fields'] ?? []);
|
||||
$profile['activities'] = array_replace(array_fill_keys(array_keys(self::ACTIVITIES), 'unknown'), $profile['activities'] ?? []);
|
||||
$profile['operation_countries'] = $profile['operation_countries'] ?? [];
|
||||
sort($profile['operation_countries']);
|
||||
$profile['documents'] = array_filter($profile['documents'] ?? []);
|
||||
$profile['activity_basis'] = trim($profile['activity_basis'] ?? '');
|
||||
foreach ($profile['documents'] as $key => $document) {
|
||||
if (! DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('l.document_id', $document)->whereNull('d.deleted_at')->exists()) {
|
||||
throw ValidationException::withMessages(['profile.documents.'.$key => 'O documento deixou de estar disponível neste dossier. Selecione um anexo associado e disponível; os campos preenchidos foram preservados.']);
|
||||
}
|
||||
}
|
||||
$hash = $this->fingerprint($profile);
|
||||
$old = $payload['investor_path']['fintech'] ?? null;
|
||||
if (($old['sha256'] ?? null) === $hash) {
|
||||
return;
|
||||
}
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi alterado; recupere a versão atual antes de guardar.');
|
||||
if ($old) {
|
||||
$payload['investor_path']['fintech_history'][] = $old;
|
||||
}
|
||||
$payload['investor_path']['fintech'] = ['schema' => self::VERSION, 'sha256' => $hash, 'profile' => $profile, 'actor_id' => $actor->id, 'saved_at' => now()->toIso8601String()];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'fintech_characterization_saved', ['schema' => self::VERSION, 'sha256' => $hash, 'previous_sha256' => $old['sha256'] ?? null]);
|
||||
});
|
||||
}
|
||||
|
||||
private function fingerprint(array $value): string
|
||||
{
|
||||
$canonical = function ($v) use (&$canonical) {
|
||||
if (! is_array($v)) {
|
||||
return $v;
|
||||
}
|
||||
if (! array_is_list($v)) {
|
||||
ksort($v);
|
||||
}
|
||||
|
||||
return array_map($canonical, $v);
|
||||
};
|
||||
|
||||
return hash('sha256', json_encode($canonical($value), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function reviewFingerprints(array $record): array
|
||||
{
|
||||
$profile = $record['profile'] ?? [];
|
||||
$fields = $profile['fields'] ?? [];
|
||||
$project = static fn (array $keys) => array_replace(array_fill_keys($keys, ''), array_intersect_key($fields, array_flip($keys)));
|
||||
$countries = $profile['operation_countries'] ?? [];
|
||||
sort($countries);
|
||||
|
||||
// Country order and an omitted versus empty optional field are not material changes.
|
||||
return [
|
||||
'S02' => $this->fingerprint($project(['problem', 'clients', 'value', 'revenues'])),
|
||||
'S08' => $this->fingerprint([$profile['model'] ?? 'undetermined', $profile['activities'] ?? [], $countries, $fields['services'] ?? '', $profile['activity_basis'] ?? '']),
|
||||
'S17' => $this->fingerprint($project(['technology', 'infrastructure', 'suppliers', 'security', 'continuity', 'channels', 'location'])),
|
||||
];
|
||||
}
|
||||
|
||||
public function adjustSteps(array $payload, array $steps): array
|
||||
{
|
||||
$record = $payload['investor_path']['fintech'] ?? null;
|
||||
if (! $record) {
|
||||
return $steps;
|
||||
}
|
||||
$fingerprints = $this->reviewFingerprints($record);
|
||||
foreach ($steps as &$step) {
|
||||
$hash = $fingerprints[$step['code']] ?? null;
|
||||
if (! $hash) {
|
||||
continue;
|
||||
}
|
||||
$reviewed = in_array($step['saved_state'], ['approved', 'reviewing', 'completed', 'ready_to_submit', 'submitted'], true);
|
||||
if ($reviewed && ($step['detail']['fintech_fingerprint'] ?? null) !== $hash) {
|
||||
$step['fintech_review_required'] = true;
|
||||
$step['state'] = 'correction_required';
|
||||
$step['reason'] = 'Pressupostos Fintech alterados ou ainda não abrangidos por esta revisão. O parecer anterior está preservado; é necessária conferência deste âmbito.';
|
||||
}
|
||||
}
|
||||
unset($step);
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
public function view(array $payload, array $steps): array
|
||||
{
|
||||
$record = $payload['investor_path']['fintech'] ?? null;
|
||||
$p = $record['profile'] ?? [];
|
||||
$declared = $p['activities'] ?? [];
|
||||
$basis = $p['activity_basis'] ?? '';
|
||||
$requirements = [];
|
||||
foreach (self::ACTIVITIES as $key => $label) {
|
||||
$value = $declared[$key] ?? 'unknown';
|
||||
$requirements[] = ['code' => $key, 'activity' => $label,
|
||||
'declared' => $value, 'state' => $value === 'yes' ? 'applicable' : ($value === 'no' && mb_strlen($basis) >= 3 ? 'dispensed' : 'undetermined'),
|
||||
'action' => 'Preparar o enquadramento documental desta atividade', 'preparation_allowed' => true,
|
||||
'basis' => $value === 'no' && mb_strlen($basis) >= 3 ? $basis : 'Declaração do promotor; a atividade e o enquadramento jurídico concreto ainda precisam de correspondência documental.',
|
||||
'source' => ['nature' => 'investor_declaration', 'reference' => $record['sha256'] ?? null, 'provision' => null, 'version' => null, 'valid_period' => null],
|
||||
'legal_license_state' => 'undetermined', 'limit' => 'Dispensa apenas desta preparação declarada; não é dispensa de licença ou confirmação externa.'];
|
||||
}
|
||||
$docs = [];
|
||||
foreach (self::DOCUMENTS as $key => [$stage,$label]) {
|
||||
$conditional = in_array($key, ['fund_flows', 'external'], true);
|
||||
$needed = $conditional ? (in_array('yes', $declared, true) ? 'applicable' : 'undetermined') : 'support';
|
||||
$docs[] = ['code' => $key, 'stage' => $stage, 'label' => $label, 'applicability' => $needed, 'document_id' => $p['documents'][$key] ?? null, 'required_at_creation' => false, 'action' => $key === 'external' ? 'Documentar o ato quando existir; usar a etapa e a conferência independente existentes.' : 'Preparar e associar ao dossier sem duplicar originais.'];
|
||||
}
|
||||
$facts = ['project_summary' => $p['fields']['problem'] ?? '', 'activity' => $p['fields']['services'] ?? '', 'target_customers' => $p['fields']['clients'] ?? '', 'location' => $p['fields']['location'] ?? '', 'resource_plan' => $p['fields']['technology'] ?? '', 'schedule' => $p['fields']['schedule'] ?? ''];
|
||||
$guidance = app(InvestorGuidanceRules::class)->evaluate($facts);
|
||||
$map = ['idea' => 'S01', 'market' => 'S02', 'location' => 'S09', 'resources' => 'S06', 'finance' => 'S12', 'execution' => 'S16', 'support' => 'S19'];
|
||||
$guidance = array_map(fn ($item) => ['stage' => $map[$item['id']], 'recommendations' => $item['recommendations']], $guidance);
|
||||
|
||||
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')),
|
||||
'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.']];
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,13 @@ class InvestmentCatalogue
|
||||
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
|
||||
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
|
||||
'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'],
|
||||
'association_type' => ['nullable', 'in:'.implode(',', array_keys(OpportunityClassification::TARGETS))],
|
||||
'association_target' => ['nullable', 'string', 'max:80'],
|
||||
'association_state' => ['nullable', 'in:'.implode(',', OpportunityClassification::STATES)],
|
||||
'association_purpose' => ['nullable', 'in:'.implode(',', array_keys(OpportunityClassification::PURPOSES))],
|
||||
'authority_id' => ['nullable', 'uuid'], 'chain_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid'],
|
||||
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
||||
'publication_state' => ['nullable', 'in:published'],
|
||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
app(InvestmentGeography::class)->selection($filters);
|
||||
|
||||
@@ -164,6 +171,8 @@ class InvestmentCatalogue
|
||||
if (! empty($filters['before'])) {
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
|
||||
}
|
||||
if (! empty($filters['category'])) $query->where('opportunity_category', $filters['category']);
|
||||
app(OpportunityClassification::class)->constrain($query, $filters);
|
||||
$sort = $filters['sort'] ?? 'recent';
|
||||
|
||||
// Monetary sorting stays grouped by currency; no undocumented FX conversion.
|
||||
@@ -178,7 +187,10 @@ class InvestmentCatalogue
|
||||
* @return array<string,mixed> */
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
{
|
||||
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||
$result = ['classification' => app(OpportunityClassification::class)->options(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||
'categories' => OpportunityManagement::CATEGORIES,
|
||||
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
||||
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
|
||||
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
|
||||
@@ -245,6 +257,8 @@ class InvestmentCatalogue
|
||||
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
|
||||
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id)
|
||||
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
|
||||
$opportunity = Opportunity::findOrFail($id);
|
||||
$result['classification'] = $management ? [] : app(OpportunityClassification::class)->publicRows($opportunity);
|
||||
$result['primary_territory_path'] = app(InvestmentGeography::class)->path(DB::table('opportunities')->where('id', $id)->value('primary_territory_id'));
|
||||
$result['opportunity_locations'] = app(InvestmentRelations::class)->opportunityLocations($id, $management);
|
||||
$result['source_evidence'] = app(InvestmentTerritorialTraceability::class)->sources('opportunities', $id);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\LandAssistanceCase;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -92,6 +93,7 @@ final class InvestorPath
|
||||
'detail' => $detail, 'preparation_allowed' => $value !== 'no',
|
||||
'action_gaps' => []];
|
||||
}
|
||||
$steps = app(FintechInvestment::class)->adjustSteps($payload, $steps);
|
||||
$byCode = collect($steps)->keyBy('code');
|
||||
foreach ($steps as &$step) {
|
||||
foreach ($step['dependencies'] as $action => $dependencies) {
|
||||
@@ -126,15 +128,17 @@ final class InvestorPath
|
||||
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
|
||||
|
||||
$landCase = (int) $case->user_id === $actor->id
|
||||
? \App\Models\LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
|
||||
? LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
|
||||
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id) : null;
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
'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' => $path['fact_reasons'] ?? [],
|
||||
'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,
|
||||
'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['code']] : null,
|
||||
'results' => $results, 'requests' => $requests, 'documents' => $documents,
|
||||
'sector_contexts' => ($owner || $manager) ? ($path['sector_contexts'] ?? []) : [],
|
||||
'content_sources' => ($owner || $manager) ? ($path['content_sources'] ?? []) : [],
|
||||
'tasks' => DB::table('tasks')->where('desk_case_id', $id)
|
||||
->whereNull('deleted_at')
|
||||
@@ -182,6 +186,7 @@ final class InvestorPath
|
||||
$step = $this->findStep($view, $code);
|
||||
abort_unless($step !== null && $step['preparation_allowed'], 422, 'Etapa dispensada de preparação; altere os pressupostos com fundamento.');
|
||||
$state = $data['state'];
|
||||
abort_if($state === 'completed' && ($step['fintech_review_required'] ?? false), 422, 'Os pressupostos Fintech desta revisão mudaram; preserve a preparação e atualize a conferência antes da conclusão.');
|
||||
$internal = in_array($state, ['reviewing', 'correction_required'], true);
|
||||
$external = in_array($state, ['approved', 'rejected', 'expired'], true);
|
||||
$scope = 'investor_preparation';
|
||||
@@ -210,7 +215,7 @@ final class InvestorPath
|
||||
if ($state === 'completed' && in_array($code, ['S07', 'S08', 'S10', 'S11', 'S14', 'S15', 'S17', 'S18'], true)) {
|
||||
abort_unless(($step['saved_state'] ?? '') === 'approved' && in_array($data['action'], ['execute', 'operate'], true), 422, 'Conclusão operacional exige acto externo documentado; use preparação enquanto aguarda.');
|
||||
}
|
||||
$detail = [...$data, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
|
||||
$detail = [...$data, 'fintech_fingerprint' => $view['fintech']['review_fingerprints'][$code] ?? null, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
|
||||
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($detail),
|
||||
'status' => in_array($state, ['completed', 'approved'], true) ? 'completed' : ($state === 'not_started' ? 'pending' : 'active'),
|
||||
'version_no' => $step['version'] + 1, 'updated_at' => now()]);
|
||||
|
||||
@@ -18,6 +18,11 @@ final class LegacyContent
|
||||
{
|
||||
public function available(): bool
|
||||
{
|
||||
// Explicit delivery gate; document publication and access checks remain independent.
|
||||
if (config('portal.legacy_content_enabled', false)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! config('portal.legacy_content_qa_enabled') || ! app()->environment('testing')
|
||||
|| config('database.connections.pgsql.host') !== '127.0.0.1'
|
||||
|| config('database.connections.pgsql.url') || (int) config('database.connections.pgsql.port') !== 55441) {
|
||||
@@ -164,6 +169,10 @@ final class LegacyContent
|
||||
$payload = $desk->decode($case->payload);
|
||||
foreach ($payload['investor_path']['content_sources'] ?? [] as $existing) {
|
||||
if ($existing['resource_id'] === $article['id'] && $existing['sha256'] === $article['sha256']) {
|
||||
if ($article['sector']) {
|
||||
app(SectorInvestment::class)->attach($actor, $caseId, ['version' => $data['version'], 'sector_slug' => $article['sector']['slug']]);
|
||||
}
|
||||
|
||||
return; // Same source/version replay: neither another reference nor another event.
|
||||
}
|
||||
}
|
||||
@@ -174,6 +183,9 @@ final class LegacyContent
|
||||
'saved_at' => now()->toIso8601String()];
|
||||
DB::table('desk_cases')->where('id', $caseId)->update(['payload' => $desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$desk->event($desk->case($actor, $caseId), $actor, 'legacy_content_referenced', ['resource_id' => $article['id'], 'sha256' => $article['sha256']]);
|
||||
if ($article['sector']) {
|
||||
app(SectorInvestment::class)->attach($actor, $caseId, ['version' => $case->version + 1, 'sector_slug' => $article['sector']['slug']]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ class OpportunityCanonicalContract
|
||||
}
|
||||
$schema = app(OpportunityCategoryFields::class)->enrich($schema);
|
||||
$schema = app(OpportunityModularProfiles::class)->extend($schema);
|
||||
$schema = app(OpportunityClassification::class)->extend($schema);
|
||||
$schema = $this->writeSchema($schema, $draft);
|
||||
$properties = &$schema['$defs']['opportunityCreate']['properties'];
|
||||
unset($properties['mutation_context']); // Actor, audit reason and revision are server-owned.
|
||||
@@ -213,6 +214,9 @@ class OpportunityCanonicalContract
|
||||
*/
|
||||
private function schemaData(mixed $value, array $node, array $defs): mixed
|
||||
{
|
||||
if (($node['x-investmoz-classification'] ?? false) && is_array($value)) {
|
||||
$node = isset($value['classification']) ? $defs['relationCreate'] : ['type' => 'object'];
|
||||
}
|
||||
if (isset($node['$ref'])) {
|
||||
$name = basename($node['$ref']);
|
||||
$node = $defs[$name] ?? $node;
|
||||
@@ -543,6 +547,7 @@ class OpportunityCanonicalContract
|
||||
|
||||
return ['version' => self::VERSION, 'modularProfiles' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::PROFILES : [],
|
||||
'historyVersion' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::HISTORY_VERSION : null,
|
||||
'classification' => app(OpportunityClassification::class)->options(),
|
||||
'schema' => $this->schema(true)['$defs']['opportunityCreate'],
|
||||
'definitions' => $this->schema(true)['$defs'],
|
||||
'submissionTextLimits' => ['demand_statement' => array_intersect_key($submissionProperties['demand_statement'], array_flip(['minLength', 'maxLength']))],
|
||||
|
||||
@@ -39,6 +39,7 @@ class OpportunityCanonicalResponse
|
||||
} catch (HttpExceptionInterface $failure) {
|
||||
$errors = ['canonical.resources' => ['Recurso indisponível para validação; estado HTTP '.$failure->getStatusCode().'. Preserve o original e resolva a operação afetada.']];
|
||||
}
|
||||
$data['classification'] = app(OpportunityClassification::class)->listing($actor, $record);
|
||||
$data['validation_result'] = ['errors' => $errors, 'warnings' => [], 'rule' => OpportunityCanonicalContract::VERSION,
|
||||
'evaluated_at' => now()->toIso8601String(), 'persisted_submission_hash' => $context['submission']['hash'] ?? null,
|
||||
'external_decision' => 'not_inferred'];
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Additive adapter over canonical relations. Never creates master data or inferred pivots. */
|
||||
class OpportunityClassification
|
||||
{
|
||||
public const VERSION = 'classification-relations-20261015-v1';
|
||||
|
||||
public const DIMENSIONS = ['territory' => 'Enquadramento territorial', 'production' => 'Organização produtiva', 'regulation' => 'Regime regulatório', 'activity' => 'Atividade económica'];
|
||||
|
||||
public const TARGETS = [
|
||||
'corridor' => ['development_corridors', 'name', 'territory'],
|
||||
'location' => ['geo_locations', 'name', 'territory'],
|
||||
'cluster' => ['economic_clusters', 'name', 'production'],
|
||||
'project' => ['projects', 'name', 'production'],
|
||||
'chain' => ['value_chains', 'name', 'production'],
|
||||
'park' => ['investment_zones', 'name', 'production'],
|
||||
'zone' => ['investment_zones', 'name', 'regulation'],
|
||||
'sector' => ['sectors', 'name', 'activity'],
|
||||
'activity' => ['economic_activities', 'label_pt_mz', 'activity'],
|
||||
];
|
||||
|
||||
public const PURPOSES = ['location' => 'Localização', 'coverage' => 'Abrangência documentada', 'proximity' => 'Proximidade, sem pertença', 'administrative_boundary' => 'Limite administrativo', 'parcel' => 'Parcela referenciada',
|
||||
'connectivity' => 'Conectividade e fluxos', 'productive_complementarity' => 'Complementaridade produtiva', 'specialization' => 'Especialização do cluster', 'anchor' => 'Projeto âncora documentado',
|
||||
'zone_location' => 'Localização na zona', 'regime_recognition' => 'Reconhecimento do regime', 'enterprise_admission' => 'Admissão do empreendimento', 'specific_benefit' => 'Benefício específico', 'park_operation' => 'Operação do parque',
|
||||
'financing_need' => 'Necessidade de financiamento', 'payments' => 'Pagamentos', 'risk_management' => 'Gestão de riscos', 'financial_instrument' => 'Instrumento financeiro',
|
||||
'logistics_service' => 'Serviço logístico', 'physical_asset' => 'Ativo físico/capacidade', 'economic_activity' => 'Atividade económica', 'production_stage' => 'Etapa da cadeia produtiva'];
|
||||
|
||||
public const STATES = ['draft', 'preliminary', 'in_validation', 'confirmed', 'rejected', 'archived', 'revoked'];
|
||||
|
||||
public const EXTERNAL = ['not_assessed', 'pending', 'documented_granted', 'documented_denied', 'expired'];
|
||||
|
||||
public function extend(array $schema): array
|
||||
{
|
||||
$fields = ['target_type' => ['type' => 'string', 'enum' => array_keys(self::TARGETS)],
|
||||
'purpose' => ['type' => 'string', 'enum' => array_keys(self::PURPOSES)],
|
||||
'criteria' => ['type' => 'string', 'maxLength' => 2000], 'justification' => ['type' => 'string', 'maxLength' => 4000],
|
||||
'source_reference' => ['type' => 'string', 'maxLength' => 2000], 'citation' => ['type' => 'string', 'maxLength' => 1000],
|
||||
'document_id' => ['type' => ['string', 'null'], 'format' => 'uuid'],
|
||||
'authority_id' => ['type' => ['string', 'null'], 'format' => 'uuid'],
|
||||
'requested_state' => ['type' => 'string', 'enum' => ['draft', 'preliminary', 'in_validation']],
|
||||
'disclosure' => ['type' => 'string', 'enum' => ['restricted', 'public']],
|
||||
'valid_from' => ['type' => ['string', 'null'], 'format' => 'date'], 'valid_until' => ['type' => ['string', 'null'], 'format' => 'date'],
|
||||
'external_status' => ['type' => 'string', 'enum' => self::EXTERNAL],
|
||||
'external_act_reference' => ['type' => 'string', 'maxLength' => 2000],
|
||||
'production_stage' => ['type' => 'string', 'maxLength' => 250],
|
||||
];
|
||||
// Same collection for every approved modality; old untyped relations remain valid.
|
||||
$schema['$defs']['relationCreate']['properties']['classification'] = ['type' => 'object', 'additionalProperties' => false, 'properties' => $fields];
|
||||
$schema['$defs']['relation']['properties']['classification'] = ['type' => 'object', 'additionalProperties' => false, 'properties' => $fields];
|
||||
foreach (['opportunity', 'opportunityCreate'] as $name) {
|
||||
$schema['$defs'][$name]['properties']['relations'] ??= ['type' => 'array', 'items' => ['$ref' => '#/$defs/relation']];
|
||||
$schema['$defs'][$name]['properties']['enterprise_size'] = ['type' => ['string', 'null'], 'maxLength' => 120];
|
||||
}
|
||||
// The extracted Create had generic objects here. Type only the new adapter;
|
||||
// pre-existing relation shapes remain accepted without recertification.
|
||||
$schema['$defs']['opportunityCreate']['properties']['relations']['items'] = ['x-investmoz-classification' => true, 'anyOf' => [
|
||||
['type' => 'object', 'not' => ['required' => ['classification']]],
|
||||
['$ref' => '#/$defs/relationCreate'],
|
||||
]];
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/** Only consultable targets: a promoter's draft permission is not access to private master data. */
|
||||
public function targets(string $kind): \Illuminate\Database\Query\Builder
|
||||
{
|
||||
abort_unless(isset(self::TARGETS[$kind]), 422);
|
||||
[$table] = self::TARGETS[$kind];
|
||||
$query = DB::table($table);
|
||||
if (in_array($kind, ['sector', 'activity'], true)) {
|
||||
return $kind === 'sector' ? $query->whereNull('deleted_at')->where('is_active', true) : $query->where('status', 'published');
|
||||
}
|
||||
$query->whereNull('deleted_at');
|
||||
if ($kind === 'chain') {
|
||||
$query->whereIn('cluster_id', $this->targets('cluster')->select('id'));
|
||||
}
|
||||
if ($kind === 'location') {
|
||||
$query->whereIn('id', app(InvestmentGeography::class)->publicReferences()->select('id'));
|
||||
}
|
||||
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'));
|
||||
}
|
||||
if (in_array($kind, ['project', 'cluster', 'corridor'], true)) {
|
||||
$foreign = ['project' => 'project_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id'][$kind];
|
||||
|
||||
return $query->where(fn ($q) => $q->where('data_classification', 'public')->orWhereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign)));
|
||||
}
|
||||
|
||||
return $query->where('data_classification', 'public');
|
||||
}
|
||||
|
||||
public function options(): array
|
||||
{
|
||||
$targets = [];
|
||||
foreach (self::TARGETS as $kind => [$table, $label, $dimension]) {
|
||||
$targets[$kind] = $this->targets($kind)->orderBy($label)->get(['id', $label.' as label']);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
public function validate(array $payload, Opportunity $record): void
|
||||
{
|
||||
$seen = [];
|
||||
foreach ($payload['relations'] ?? [] as $i => $row) {
|
||||
if (! isset($row['classification'])) {
|
||||
continue;
|
||||
}
|
||||
$c = $row['classification'];
|
||||
$prefix = 'canonical.relations.'.$i;
|
||||
$fail = fn ($key, $message) => throw ValidationException::withMessages([$prefix.'.'.$key => $message]);
|
||||
$allowed = ['target_type', 'purpose', 'criteria', 'justification', 'source_reference', 'citation', 'document_id', 'authority_id', 'requested_state', 'disclosure', 'valid_from', 'valid_until', 'external_status', 'external_act_reference', 'production_stage'];
|
||||
if (array_diff(array_keys($c), $allowed)) {
|
||||
$fail('classification', 'Campo de certificação ou metadado não permitido. A decisão é registada pelo revisor autorizado.');
|
||||
}
|
||||
$validator = Validator::make($c, [
|
||||
'target_type' => 'required|in:'.implode(',', array_keys(self::TARGETS)), 'purpose' => 'required|in:'.implode(',', array_keys(self::PURPOSES)),
|
||||
'requested_state' => 'sometimes|in:draft,preliminary,in_validation', 'disclosure' => 'sometimes|in:restricted,public',
|
||||
'external_status' => 'sometimes|in:'.implode(',', self::EXTERNAL),
|
||||
'criteria' => 'sometimes|nullable|string|max:2000', 'justification' => 'sometimes|nullable|string|max:4000',
|
||||
'source_reference' => 'sometimes|nullable|string|max:2000', 'citation' => 'sometimes|nullable|string|max:1000',
|
||||
'document_id' => 'sometimes|nullable|uuid', 'authority_id' => 'sometimes|nullable|uuid',
|
||||
'valid_from' => 'sometimes|nullable|date_format:Y-m-d', 'valid_until' => 'sometimes|nullable|date_format:Y-m-d',
|
||||
'external_act_reference' => 'sometimes|nullable|string|max:2000', 'production_stage' => 'sometimes|nullable|string|max:250',
|
||||
]);
|
||||
if ($validator->fails()) {
|
||||
throw ValidationException::withMessages(collect($validator->errors()->messages())->mapWithKeys(fn ($v, $k) => [$prefix.'.classification.'.$k => $v])->all());
|
||||
}
|
||||
$kind = $c['target_type'] ?? '';
|
||||
$id = (string) ($row['related_id'] ?? '');
|
||||
if (($kind === 'sector' && ! ctype_digit($id)) || ($kind !== 'sector' && ! Str::isUuid($id))) {
|
||||
$fail('related_id', 'Identificador de referência inválido.');
|
||||
}
|
||||
if (! isset(self::TARGETS[$kind]) || ! $this->targets($kind)->where('id', (string) ($row['related_id'] ?? ''))->exists()) {
|
||||
$fail('related_id', 'Selecione uma referência existente e consultável; nenhum cadastro é criado por esta relação.');
|
||||
}
|
||||
$purpose = $c['purpose'] ?? '';
|
||||
if (! isset(self::PURPOSES[$purpose])) {
|
||||
$fail('classification.purpose', 'Indique a finalidade da relação.');
|
||||
}
|
||||
if (in_array($purpose, ['regime_recognition', 'enterprise_admission', 'specific_benefit'], true) && $kind !== 'zone') {
|
||||
$fail('classification.purpose', 'Regime, admissão e benefício usam a relação regulatória com a zona, separada da ficha física do parque.');
|
||||
}
|
||||
$identity = self::TARGETS[$kind][0].':'.$row['related_id'].':'.$purpose;
|
||||
if (isset($seen[$identity])) {
|
||||
$fail('related_id', 'Esta referência e finalidade já estão 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.');
|
||||
}
|
||||
if (! empty($c['document_id']) && ! DB::table('opportunity_documents')->where('id', $c['document_id'])->where('opportunity_id', $record->id)->whereNull('deleted_at')->exists()) {
|
||||
$fail('classification.document_id', 'Documento deve pertencer aos anexos desta oportunidade.');
|
||||
}
|
||||
if (! empty($c['authority_id']) && ! DB::table('authorities')->where('id', $c['authority_id'])->where('status', 'published')->exists()) {
|
||||
$fail('classification.authority_id', 'Entidade competente não consta do catálogo publicado.');
|
||||
}
|
||||
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; a associação não concede o direito.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function hash(array $row): string
|
||||
{
|
||||
// Client identity/status cannot certify a relation. Object-order normalization is reused.
|
||||
return OpportunityCanonicalValue::hash($row);
|
||||
}
|
||||
|
||||
public function canReview(User $actor, Opportunity $record, string $dimension): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$responsibility = $dimension === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
|
||||
|
||||
return $access->canView($actor, $record) && $access->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $access->conflict($actor, $record) && $access->operational($actor, 'validate', $record->id) && $access->mfa($actor)
|
||||
&& collect($access->grants($actor, 'validator'))->contains(fn ($g) => in_array($record->opportunity_category, json_decode($g->opportunity_types, true), true)
|
||||
&& ($g->organization_id === null || $g->organization_id === $record->organization_id) && in_array($responsibility, json_decode($g->responsibilities, true), true));
|
||||
}
|
||||
|
||||
public function state(Opportunity $record, array $row): string
|
||||
{
|
||||
$decision = $record->workflow_context['classification_decisions'][$this->hash($row)] ?? null;
|
||||
if ($decision && $decision['state'] !== 'confirmed') {
|
||||
return $decision['state'];
|
||||
}
|
||||
if ($decision) {
|
||||
$reviewer = User::find($decision['actor_id']);
|
||||
$c = $row['classification'];
|
||||
if (! empty($c['document_id']) && ($decision['evidence_hash'] ?? '') !== $this->evidenceHash($row)) {
|
||||
return 'in_validation';
|
||||
}
|
||||
// Current grants/conflicts still apply; reading a public page never requires the reviewer's browser session.
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$responsibility = self::TARGETS[$c['target_type']][2] === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
|
||||
$responsible = $reviewer && collect($access->grants($reviewer, 'validator'))->contains(fn ($g) => ($g->organization_id === null || $g->organization_id === $record->organization_id)
|
||||
&& in_array($record->opportunity_category, json_decode($g->opportunity_types, true), true) && in_array($responsibility, json_decode($g->responsibilities, true), true));
|
||||
if ($responsible && ! $access->conflict($reviewer, $record)) {
|
||||
return 'confirmed';
|
||||
}
|
||||
|
||||
return 'in_validation';
|
||||
}
|
||||
|
||||
return $row['classification']['requested_state'] ?? 'preliminary';
|
||||
}
|
||||
|
||||
private function evidenceHash(array $row): ?string
|
||||
{
|
||||
$id = $row['classification']['document_id'] ?? null;
|
||||
if (! $id) {
|
||||
return null;
|
||||
}
|
||||
$resource = DB::table('opportunity_documents as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $id)
|
||||
->first(['r.id', 'r.version', 'r.deleted_at', 'd.sha256']);
|
||||
|
||||
return OpportunityCanonicalValue::hash($resource ? (array) $resource : ['unavailable' => $id]);
|
||||
}
|
||||
|
||||
public function listing(User $actor, Opportunity $record): array
|
||||
{
|
||||
app(PortalProfileAccess::class)->authorize($actor, 'view', $record);
|
||||
$rows = app(OpportunityManagement::class)->values($record)['canonical']['relations'] ?? [];
|
||||
$rows = array_values(array_filter($rows, fn ($row) => isset($row['classification'])));
|
||||
|
||||
return array_map(function ($row) use ($record, $actor) {
|
||||
$kind = $row['classification']['target_type'];
|
||||
$dimension = self::TARGETS[$kind][2];
|
||||
$metadata = $record->workflow_context['canonical_items'] ?? [];
|
||||
$prior = [];
|
||||
foreach ($metadata['deleted'] ?? [] as $item) {
|
||||
$old = $item['last_value'] ?? [];
|
||||
if (isset($old['classification']) && ($old['related_id'] ?? null) === $row['related_id'] && ($old['classification']['target_type'] ?? null) === $kind
|
||||
&& ($old['classification']['purpose'] ?? null) === $row['classification']['purpose'] && $this->hash($old) !== $this->hash($row)) {
|
||||
$prior[] = ['metadata' => array_diff_key($item, ['last_value' => true]), 'history' => $record->workflow_context['classification_decisions'][$this->hash($old)]['history'] ?? [], 'relation' => $old];
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
'can_review' => $this->canReview($actor, $record, $dimension), 'history' => $record->workflow_context['classification_decisions'][$this->hash($row)]['history'] ?? []];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
return DB::transaction(function () use ($actor, $record, $data) {
|
||||
$record = Opportunity::whereKey($record->id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->status === 'archived', 409, 'Oportunidade arquivada; preserve o histórico e use o workflow aprovado.');
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$access->authorize($actor, 'view', $record);
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409, 'A oportunidade mudou. Atualize antes de decidir; o rascunho permanece guardado.');
|
||||
$rows = app(OpportunityManagement::class)->values($record)['canonical']['relations'] ?? [];
|
||||
// A revocation also reaches a previously published version after a draft correction.
|
||||
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']);
|
||||
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.');
|
||||
if ($data['state'] === 'confirmed') {
|
||||
foreach (['criteria', 'justification', 'source_reference', 'citation'] as $key) {
|
||||
abort_if(empty(trim($c[$key] ?? '')), 422, 'Confirmação exige critérios, justificação, fonte e citação por associação. A preparação pode continuar como preliminar.');
|
||||
}
|
||||
$this->validate(['relations' => [$row]], $record);
|
||||
}
|
||||
$context = $record->workflow_context ?? [];
|
||||
$before = $context['classification_decisions'][$data['hash']] ?? null;
|
||||
$decision = ['state' => $data['state'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'], 'evidence_hash' => $this->evidenceHash($row), 'version' => ($before['version'] ?? 0) + 1];
|
||||
$context['classification_decisions'][$data['hash']] = [...$decision, 'history' => [...($before['history'] ?? []), $decision]];
|
||||
$record->workflow_context = $context;
|
||||
$record->management_version++;
|
||||
$record->save();
|
||||
$access->audit($actor, 'classification_'.$data['state'], ['record_id' => $record->id, 'relation_hash' => $data['hash'], 'before' => $before, 'after' => $decision]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** Frozen at the existing editorial publication, not on draft save or association confirmation. */
|
||||
public function publication(array $payload): array
|
||||
{
|
||||
return array_values(array_filter($payload['relations'] ?? [], fn ($r) => isset($r['classification']) && ($r['classification']['disclosure'] ?? 'restricted') === 'public'));
|
||||
}
|
||||
|
||||
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') {
|
||||
return [];
|
||||
}
|
||||
$rows = [];
|
||||
foreach ($record->workflow_context['publication']['classification'] ?? [] as $row) {
|
||||
$c = $row['classification'];
|
||||
$kind = $c['target_type'];
|
||||
if (! isset(self::TARGETS[$kind]) || ($c['disclosure'] ?? '') !== 'public') {
|
||||
continue;
|
||||
}
|
||||
$target = $this->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;
|
||||
}
|
||||
$state = $this->state($record, $row);
|
||||
if (in_array($state, ['archived', 'revoked'], true)) {
|
||||
continue;
|
||||
}
|
||||
// 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,
|
||||
'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,
|
||||
'production_stage' => $c['production_stage'] ?? null, 'valid_from' => $c['valid_from'] ?? null, 'valid_until' => $c['valid_until'] ?? null];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** Same public projection for count/list/map; AND across filters, OR across selected associations. */
|
||||
public function constrain(Builder $query, array $filters): void
|
||||
{
|
||||
$keys = ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id'];
|
||||
if (! array_filter(array_intersect_key($filters, array_flip($keys)), fn ($v) => $v !== null && $v !== '')) {
|
||||
return;
|
||||
}
|
||||
// Query candidates in bounded chunks to apply the exact visibility/decision rules used by detail.
|
||||
// IDs only, no private payload leaves this service. A future indexed projection is an optimization, not another catalogue.
|
||||
$ids = [];
|
||||
(clone $query)->reorder()->select('opportunities.*')->chunkById(200, function ($records) use (&$ids, $filters) {
|
||||
foreach ($records as $record) {
|
||||
$rows = $this->publicRows($record);
|
||||
$main = array_filter(array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_state', 'association_purpose'])), fn ($v) => $v !== null && $v !== '');
|
||||
$matches = $main === [] || collect($rows)->contains(function ($r) use ($main) {
|
||||
foreach (['association_type' => 'target_type', 'association_target' => 'target_id', 'association_state' => 'state', 'association_purpose' => 'purpose'] as $filter => $field) {
|
||||
if (isset($main[$filter]) && ($r[$field] ?? null) !== $main[$filter]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
if (! empty($filters['chain_id'])) {
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === 'chain' && $r['target_id'] === $filters['chain_id']);
|
||||
}
|
||||
if (! empty($filters['authority_id'])) {
|
||||
$matches = $matches && collect($rows)->contains(fn ($r) => $r['authority_id'] === $filters['authority_id']);
|
||||
}
|
||||
if (! empty($filters['subsector_id'])) {
|
||||
$matches = $matches && (($record->workflow_context['publication']['taxonomy']['subsector_id'] ?? '') === $filters['subsector_id'] || collect($rows)->contains(fn ($r) => $r['target_type'] === 'activity' && $r['target_id'] === $filters['subsector_id']));
|
||||
}
|
||||
if ($matches) {
|
||||
$ids[] = $record->id;
|
||||
}
|
||||
}
|
||||
}, 'opportunities.id', 'id');
|
||||
$query->whereIn('opportunities.id', $ids);
|
||||
}
|
||||
|
||||
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'])
|
||||
->map(fn ($r) => ['id' => $r->id, 'reference' => $r->reference, 'reason' => 'Título exato normalizado; identidade do negócio por determinar. Nenhuma fusão executada.'])->all();
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,7 @@ class OpportunityManagement
|
||||
if (array_key_exists('canonical', $changes)) {
|
||||
$previous = $record->exists ? $this->values($record) : [];
|
||||
$changes['canonical'] = [...($previous['canonical'] ?? []), ...$changes['canonical']];
|
||||
app(OpportunityClassification::class)->validate($changes['canonical'], $record);
|
||||
if (($changes['canonical']['opportunity_category'] ?? ($changes['opportunity_category'] ?? $record->opportunity_category)) !== ($changes['opportunity_category'] ?? $record->opportunity_category)) {
|
||||
throw ValidationException::withMessages(['canonical.opportunity_category' => 'Contrato e registo devem usar a mesma categoria.']);
|
||||
}
|
||||
|
||||
@@ -332,7 +332,9 @@ class OpportunityProfileWorkflow
|
||||
'catalogue_version' => $context['publication']['maturity']['catalogue_version'] ?? null]];
|
||||
}
|
||||
$context['publication'] = [...$decision, 'hash' => $snapshot['hash'], 'visibility' => $p['visibility'],
|
||||
'public_fields' => ['title', 'summary', 'description', 'sector_id', 'province', 'district']];
|
||||
'public_fields' => ['title', 'summary', 'description', 'sector_id', 'province', 'district'],
|
||||
'classification' => app(OpportunityClassification::class)->publication($p),
|
||||
'taxonomy' => array_intersect_key($p, array_flip(['subsector_id', 'economic_activity_id']))];
|
||||
// Minimal public projection; contacts, valuations, evidence and originals remain private.
|
||||
$projection = $this->contract->publicProjection($p);
|
||||
$record->title = $projection['title'];
|
||||
|
||||
@@ -16,7 +16,7 @@ class PortalProfileAccess
|
||||
/** @return list<string> */
|
||||
public static function fingerprintFiles(): array
|
||||
{
|
||||
return [__FILE__, app_path('Services/OpportunityContacts.php'), resource_path('js/components/opportunity-contact-form.tsx'), app_path('Services/PortalInternalDesignation.php'), app_path('Models/User.php'), app_path('Models/Opportunity.php'), config_path('portal.php'), base_path('routes/web.php'),
|
||||
return [__FILE__, app_path('Services/OpportunityClassification.php'), app_path('Http/Controllers/OpportunityClassificationController.php'), resource_path('js/components/opportunity-classification.tsx'), app_path('Services/OpportunityContacts.php'), resource_path('js/components/opportunity-contact-form.tsx'), app_path('Services/PortalInternalDesignation.php'), app_path('Models/User.php'), app_path('Models/Opportunity.php'), config_path('portal.php'), base_path('routes/web.php'),
|
||||
app_path('Http/Middleware/HandleInertiaRequests.php'), app_path('Services/OpportunityManagement.php'),
|
||||
app_path('Services/OpportunityResources.php'), app_path('Services/OpportunityImageProcessor.php'), app_path('Services/VerifiedDocumentBinary.php'),
|
||||
app_path('Services/PortalProfileAdministration.php'), app_path('Services/PortalSuperusers.php'),
|
||||
@@ -39,7 +39,7 @@ class PortalProfileAccess
|
||||
resource_path('js/pages/dashboard.tsx'), resource_path('js/pages/PortalInvestidor.tsx'),
|
||||
resource_path('js/layouts/portal-navigation.tsx'), resource_path('js/components/interactive-investment-map.tsx'),
|
||||
resource_path('js/components/simulation-form.tsx'), resource_path('js/lib/simulation-form.ts'), app_path('Services/LegacyContent.php'),
|
||||
resource_path('js/components/ui/sidebar.tsx'), resource_path('js/components/simulation-financial-tools.tsx'), resource_path('js/components/simulation-cashflow-planner.tsx'), resource_path('js/pages/investor-path/show.tsx'), resource_path('views/app.blade.php'),
|
||||
resource_path('js/components/ui/sidebar.tsx'), resource_path('js/components/simulation-financial-tools.tsx'), resource_path('js/components/simulation-cashflow-planner.tsx'), resource_path('js/pages/investor-path/show.tsx'), resource_path('views/app.blade.php'), resource_path('views/profiles/creation-unavailable.blade.php'),
|
||||
resource_path('js/pages/management/opportunity-resources.tsx'),
|
||||
app_path('Services/PortalProfileInstallation.php'), app_path('Http/Controllers/PortalProfileInstallationController.php'), config_path('portal_profiles.php'), resource_path('js/pages/profiles/installation.tsx')];
|
||||
}
|
||||
@@ -162,6 +162,14 @@ class PortalProfileAccess
|
||||
return true;
|
||||
}
|
||||
|
||||
// Normal Promotor authority comes from its existing scope, not from the
|
||||
// Superutilizador membership. Other/extraneous actions retain elevation.
|
||||
if (in_array($action, ['view', 'edit'], true) && $recordId !== null) {
|
||||
$record = Opportunity::withTrashed()->find($recordId);
|
||||
if ($record && $record->owner_user_id !== null && $this->promoterRecordScope($actor, $record)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (! $this->mfa($actor)) {
|
||||
return false;
|
||||
}
|
||||
@@ -178,7 +186,8 @@ class PortalProfileAccess
|
||||
{
|
||||
$included = in_array($type, OpportunityCanonicalContract::BASE_CATEGORIES, true) || app(OpportunityModularProfiles::class)->enabled();
|
||||
|
||||
return $included && $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && $this->operational($actor, 'create');
|
||||
// This is creation as an authorized Promotor, never an exceptional SU act.
|
||||
return $included && $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && ! $this->has($actor, 'auditor');
|
||||
}
|
||||
|
||||
public function legacyWriteAllowed(User $actor): bool
|
||||
@@ -275,7 +284,30 @@ class PortalProfileAccess
|
||||
->where('scope->action', 'view')->whereNotNull('approved_by')->whereNull('consumed_at')->where('expires_at', '>', now())
|
||||
->get()->filter(fn ($row) => $this->operational($actor, 'view', json_decode($row->scope, true)['record_id'] ?? null))
|
||||
->map(fn ($row) => json_decode($row->scope, true)['record_id'])->all();
|
||||
$query->whereIn('id', $ids);
|
||||
$query->where(function ($eligible) use ($ids, $actor) {
|
||||
$eligible->whereIn('id', $ids);
|
||||
if ($this->has($actor, 'auditor')) {
|
||||
return;
|
||||
}
|
||||
foreach ($this->grants($actor, 'promoter') as $grant) {
|
||||
$internal = $grant->source === 'internal-portal-designation';
|
||||
if (($internal && app(PortalInternalDesignation::class)->organization($grant->organization_id) === null)
|
||||
|| (! $internal && ! $this->represents($actor, $grant->organization_id))) {
|
||||
continue;
|
||||
}
|
||||
$eligible->orWhere(function ($normal) use ($actor, $grant, $internal) {
|
||||
$normal->whereNotNull('owner_user_id')->whereIn('opportunity_category', json_decode($grant->opportunity_types, true));
|
||||
if ($internal) {
|
||||
$normal->where(fn ($q) => $q->where('owner_user_id', $actor->id)->orWhereJsonContains('workflow_context->contributors', $actor->id))
|
||||
->where('workflow_context->operator_organization_id', $grant->organization_id);
|
||||
} elseif ($grant->organization_id !== null) {
|
||||
$normal->where('organization_id', $grant->organization_id);
|
||||
} else {
|
||||
$normal->whereNull('organization_id')->where('owner_user_id', $actor->id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $query->where(function ($scope) use ($actor) {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Entry adapter over existing sector, opportunity, portfolio and private dossier records. */
|
||||
final class SectorInvestment
|
||||
{
|
||||
// Editorial bridges, not renamed masters or automatic opportunity classifications.
|
||||
public const CONTENT = [
|
||||
'mineracao' => ['mineracao', 'energia-mineracao'], 'energia-especifica' => ['energia', 'energia-mineracao'],
|
||||
'agronegocio' => ['agronegocio'], 'turismo' => ['turismo'], 'infraestruturas' => ['infraestruturas'],
|
||||
'tecnologias-de-informacao' => ['tech-fintech'], 'mercado-financeiro' => ['tech-fintech'],
|
||||
'fintech' => ['tech-fintech'], 'imobiliario' => ['imobiliario'],
|
||||
'bens-de-consumo-e-franquias' => ['bens-de-consumo-franquias'],
|
||||
];
|
||||
|
||||
public function sector(string $slug): Sector
|
||||
{
|
||||
return Sector::where('slug', $slug)->where('is_active', true)->firstOrFail();
|
||||
}
|
||||
|
||||
public function context(string $slug): array
|
||||
{
|
||||
$sector = $this->sector($slug);
|
||||
|
||||
return [...$sector->only(['id', 'name', 'slug']), 'href' => '/sectores/'.$sector->slug];
|
||||
}
|
||||
|
||||
public function publicView(Sector $sector): array
|
||||
{
|
||||
$query = Opportunity::published()->where('sector_id', $sector->id);
|
||||
$articles = [];
|
||||
if (app(LegacyContent::class)->available()) {
|
||||
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
|
||||
try {
|
||||
$a = app(LegacyContent::class)->article($slug);
|
||||
$articles[] = ['title' => $a['title'], 'href' => $a['href'], 'image' => $a['image'], 'sha256' => $a['sha256'], 'scope' => $slug === 'tech-fintech' && $sector->slug !== 'fintech' ? 'Especialização Fintech; não representa todo o setor.' : 'Conteúdo educativo relacionado; não é uma oportunidade concreta.'];
|
||||
} catch (HttpException $e) {
|
||||
if ($e->getStatusCode() !== 404) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$relations = [];
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $table => $foreign) {
|
||||
$ids = DB::table('opportunity_'.$table)->whereIn('opportunity_id', (clone $query)->select('id'))->pluck($foreign);
|
||||
foreach (InvestmentPortfolioController::visible()->whereIn($foreign, $ids)->orderBy('title')->get() as $dossier) {
|
||||
$relations[] = ['id' => $dossier->id, 'title' => $dossier->title, 'href' => '/carteira/'.$dossier->id, 'kind' => $table,
|
||||
'basis' => 'Associação cadastrada entre uma oportunidade pública deste setor e esta ficha publicada.', 'source' => $dossier->source];
|
||||
}
|
||||
}
|
||||
$locations = [];
|
||||
foreach ((clone $query)->orderBy('id')->get(['id', 'title', 'slug']) as $opportunity) {
|
||||
foreach (app(InvestmentRelations::class)->opportunityLocations($opportunity->id) as $location) {
|
||||
$locations[] = ['opportunity_title' => $opportunity->title, 'href' => '/oportunidades/'.$opportunity->slug, 'location' => $location];
|
||||
}
|
||||
}
|
||||
|
||||
return ['articles' => $articles, 'relations' => collect($relations)->unique('id')->values()->all(), 'locations' => $locations,
|
||||
'start_href' => app(InvestorPath::class)->available() ? '/investimentos/a-partir-do-setor/'.$sector->slug : null,
|
||||
'start_notice' => app(InvestorPath::class)->available() ? null : 'O percurso para guardar a ideia está temporariamente indisponível. A consulta e o apoio continuam disponíveis.',
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/create?sector_id='.$sector->id : null,
|
||||
'register_notice' => app(PortalProfileAccess::class)->available() ? null : 'O cadastro por perfis está temporariamente indisponível; pode preparar a ideia e contactar o apoio.',
|
||||
'specialization_href' => in_array($sector->slug, ['tecnologias-de-informacao', 'mercado-financeiro'], true) ? '/sectores/fintech' : null,
|
||||
'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];
|
||||
}
|
||||
|
||||
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();
|
||||
$context = $this->context($data['sector_slug']);
|
||||
abort_unless(app(InvestorPath::class)->available(), 404);
|
||||
DB::transaction(function () use ($actor, $id, $data, $context) {
|
||||
$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']['sector_contexts'] ?? [] as $existing) {
|
||||
if ($existing['id'] === $context['id']) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier foi alterado; recupere a versão atual.');
|
||||
$payload['investor_path']['sector_contexts'][] = [...$context, 'actor_id' => $actor->id, 'saved_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, 'sector_context_referenced', ['sector_id' => $context['id'], 'sector_slug' => $context['slug']]);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user