oportunidades 4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-10 07:03:59 +02:00
parent e662230df7
commit 6ddafc95ba
179 changed files with 22750 additions and 933 deletions
@@ -53,6 +53,7 @@ class InterestRequestController extends Controller
'phone' => $validated['phone'] ?? null,
'investor_type' => $validated['investorType'],
'country' => $validated['country'],
'metadata' => ['declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null],
'sector_interest' => $validated['sectorInterest'],
'opportunity_reference' => $validated['opportunityReference'] ?? null,
'investment_range' => $validated['investmentRange'] ?? null,
@@ -3,19 +3,25 @@
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Services\CountryCatalogue;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class ReferenceCatalogController extends Controller
{
private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities'];
private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities', 'countries'];
public function index(Request $request, string $catalog): JsonResponse
{
$catalog = $this->validatedCatalog($catalog);
if ($catalog === 'countries') {
return $this->countries($request);
}
$rules = [
'q' => ['nullable', 'string', 'max:100'],
@@ -89,6 +95,21 @@ class ReferenceCatalogController extends Controller
->header('ETag', 'W/"catalog-'.substr(hash('sha256', $catalog.'|'.$version->version_no.'|'.json_encode($data, JSON_THROW_ON_ERROR)), 0, 32).'"');
}
private function countries(Request $request): JsonResponse
{
$data = $request->validate(['q' => 'nullable|string|max:100', 'page' => 'nullable|integer|min:1', 'per_page' => 'nullable|integer|min:1|max:100', 'parent_id' => 'prohibited', 'version' => 'prohibited']);
$term = strtolower(Str::ascii(trim($data['q'] ?? '')));
$items = collect(app(CountryCatalogue::class)->all())
->filter(fn (array $country) => $term === '' || str_contains(strtolower(Str::ascii(implode(' ', $country))), $term))
->values()->map(fn (array $country) => ['id' => $country['code'], 'value' => $country['code'], 'code' => $country['code'], 'name' => $country['name'], 'label' => $country['name']]);
$page = (int) ($data['page'] ?? 1);
$perPage = (int) ($data['per_page'] ?? 50);
$result = new LengthAwarePaginator($items->forPage($page, $perPage)->values(), $items->count(), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
return response()->json([...$result->toArray(), 'meta' => ['catalog' => 'countries', 'source' => 'Local ISO 3166 catalogue', 'sha256' => hash_file('sha256', resource_path('data/iso3166.tab'))]])
->header('Cache-Control', 'public, max-age=300');
}
/** @param array<string,mixed> $data */
private function authorities(string $versionId, array $data): Builder
{
@@ -171,7 +192,7 @@ class ReferenceCatalogController extends Controller
});
}
/** @return 'authorities'|'jurisdictions'|'economic-activities' */
/** @return 'authorities'|'jurisdictions'|'economic-activities'|'countries' */
private function validatedCatalog(string $catalog): string
{
abort_unless(in_array($catalog, self::CATALOGS, true), 404);
+11 -1
View File
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Models\InterestRequest;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\InvestorPath;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
@@ -14,7 +15,16 @@ class DashboardController extends Controller
public function __invoke(Request $request): Response
{
if (! $request->user()->can('manage-portal')) {
return Inertia::render('dashboard', ['summary' => null]);
$path = app(InvestorPath::class);
$contexts = $path->contexts($request->user());
$current = $contexts ? $path->view($request->user(), $contexts[0]['id']) : null;
return Inertia::render('dashboard', ['summary' => null, 'investorPath' => $path->available() ? [
'contexts' => $contexts,
'current' => $current ? ['id' => $current['case']['id'], 'next' => $current['next'],
'pending' => count(array_filter($current['steps'], fn ($step) => ! in_array($step['state'], ['completed', 'approved', 'dispensed'], true))),
'documents' => count($current['documents']), 'results' => count($current['results']), 'tasks' => count($current['tasks'])] : null,
] : null]);
}
$counts = InterestRequest::query()->selectRaw('status, count(*) as total')
@@ -6,6 +6,7 @@ use App\Models\ExistingBusiness;
use App\Models\ExistingBusinessObject;
use App\Models\Sector;
use App\Services\BusinessFormSchema;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake;
use App\Services\ExistingBusinessObjects;
@@ -15,9 +16,11 @@ use App\Services\Mne\BusinessRepository;
use App\Services\Mne\CompatibilityShadow;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
@@ -35,7 +38,23 @@ class ExistingBusinessController extends Controller
} else {
$query->where('owner_user_id', $request->user()->id);
}
$props = ['records' => $query->orderByDesc('updated_at')->paginate(20)->through(fn ($row) => $this->record($row)),
$filters = $request->validate(['country' => ['nullable', app(CountryCatalogue::class)->rule()], 'origin' => ['nullable', Rule::in([...array_column(app(CountryCatalogue::class)->all(), 'code'), 'unknown'])], 'page' => ['nullable', 'integer', 'min:1']]);
$query->orderByDesc('updated_at');
if (! empty($filters['country']) || ! empty($filters['origin'])) {
// The private payload is encrypted: filter only the already-authorized collection.
$matches = $query->get()->filter(function ($business) use ($filters) {
$payload = $business->payload;
$origin = $payload['declared_origin_country_code'] ?? null;
$validOrigin = in_array($origin, array_column(app(CountryCatalogue::class)->all(), 'code'), true) ? $origin : 'unknown';
return (empty($filters['country']) || ($payload['country'] ?? null) === $filters['country']) && (empty($filters['origin']) || $validOrigin === $filters['origin']);
})->values();
$page = (int) ($filters['page'] ?? 1);
$records = new LengthAwarePaginator($matches->forPage($page, 20)->values(), $matches->count(), 20, $page, ['path' => $request->url(), 'query' => $request->query()]);
} else {
$records = $query->paginate(20)->withQueryString();
}
$props = ['records' => $records->through(fn ($row) => $this->record($row)), 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all(),
'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES];
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props);
@@ -46,7 +65,7 @@ class ExistingBusinessController extends Controller
$business = app(BusinessRepository::class)->find($id);
Gate::authorize('view', $business);
app(CompatibilityShadow::class)->schedule($id);
$props = ['sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
'canTriage' => $request->user()->can('triage', $business),
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
@@ -10,6 +10,7 @@ use App\Services\InvestmentZones;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;
@@ -130,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(\Illuminate\Support\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, ['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)) {
@@ -7,6 +7,7 @@ use App\Models\InterestRequest;
use App\Models\InvestmentSpecificNeed;
use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentWorkspace;
@@ -111,7 +112,7 @@ class InvestmentSubmissionController extends Controller
$target = $row->opportunity_id ? Opportunity::published()->find($row->opportunity_id) : null;
$dossier = $row->dossier_id ? InvestmentPortfolioController::visible()->find($row->dossier_id) : null;
$zoneOrigin = DB::table('investment_submission_zones')->where('submission_id', $id)->first(['zone_id', 'zone_version', 'intent']);
$data = ['countries' => app(\App\Services\CountryCatalogue::class)->all(), 'submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
$data = ['countries' => app(CountryCatalogue::class)->all(), 'submission' => $row->only(['id', 'payload', 'version', 'status', 'opportunity_id', 'dossier_id']), 'zone_origin' => $zoneOrigin,
'target' => ($target ? $target->title : null) ?? ($dossier ? $dossier->title : null), 'references' => [
...$catalogue->references(), 'options' => DB::table('investment_reference_options')->orderBy('label')->get()],
'needs' => InvestmentSpecificNeed::where('submission_id', $id)->get(),
@@ -145,9 +146,9 @@ class InvestmentSubmissionController extends Controller
$required = $submitting ? 'required' : 'nullable';
$data = $request->validate(['version' => ['required', 'integer', 'min:1'],
'payload' => ['required', 'array:full_name,email,phone,country,residence_country_code,incorporation_country_code,declared_origin_country_code,organisation,representative_role,experience,investment_capacity,profile_id,sector,objective,participation_id,partnership_id,estimated_amount,currency,horizon,location,cluster_ids,corridor_ids,project_ids,contact_consent,other_details'],
'payload.residence_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.incorporation_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.other_details' => ['nullable', 'string', 'max:5000'],
'payload.full_name' => [$required, 'string', ...($submitting ? ['min:3'] : []), 'max:150'], 'payload.email' => [$required, $submitting ? 'email:rfc' : 'string', 'max:150'],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => [$submitting ? 'required_without:payload.declared_origin_country_code' : 'nullable', 'nullable', 'string', 'max:100'],
@@ -3,6 +3,7 @@
namespace App\Http\Controllers;
use App\Services\InvestmentZones;
use App\Services\TerritoryGeometry;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -10,6 +11,17 @@ use Illuminate\Validation\ValidationException;
class InvestmentTerritoryController extends Controller
{
public function geometries(Request $request): JsonResponse
{
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
$management = $request->is('management/*');
if ($management) {
abort_unless($request->user()?->can('manage-portal'), 403);
}
return response()->json(app(TerritoryGeometry::class)->context($data['territory_id'], $management));
}
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
public function subjects(Request $request): JsonResponse
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Models\InvestmentSubmission;
use App\Models\User;
use App\Services\CountryCatalogue;
use App\Services\InvestmentWorkspace;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
@@ -18,7 +19,7 @@ class InvestmentWorkspaceController extends Controller
{
public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse
{
$data = ['countries' => app(\App\Services\CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
$data = ['countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) {
$company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
@@ -32,7 +33,7 @@ class InvestmentWorkspaceController extends Controller
{
$data = $request->validate(['version' => ['required', 'integer', 'min:0'],
'payload' => ['required', 'array:phone,country,residence_country_code,sector,experience,investment_capacity'],
'payload.residence_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'],
'payload.sector' => ['nullable', 'string', 'max:150'], 'payload.experience' => ['nullable', 'string', 'max:2000'],
'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]);
@@ -55,7 +56,7 @@ class InvestmentWorkspaceController extends Controller
{
$data = $request->validate(['version' => ['required', 'integer', 'min:0'],
'payload' => ['required', 'array:name,country,incorporation_country_code,registration,sector,role,description'],
'payload.incorporation_country_code' => ['nullable', 'string', app(\App\Services\CountryCatalogue::class)->rule()],
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required_without:payload.incorporation_country_code', 'nullable', 'string', 'max:100'],
'payload.registration' => ['nullable', 'string', 'max:100'], 'payload.sector' => ['nullable', 'string', 'max:150'],
'payload.role' => ['required', 'string', 'max:150'], 'payload.description' => ['nullable', 'string', 'max:2000']]);
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Services\Ai\EvidenceRepository;
use App\Services\Ai\InvestorGuidance;
use App\Services\InvestorPath;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
@@ -18,7 +19,10 @@ class InvestorGuidanceController extends Controller
$actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$cases = DB::table('desk_cases')->whereNull('closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))
->orderByDesc('updated_at')->get(['id', 'title']);
->orderByDesc('updated_at')->get(['id', 'title', 'journey_id'])->map(function ($case) {
return ['id' => $case->id, 'title' => $case->title, 'path_supported' => app(InvestorPath::class)->available()
&& $case->journey_id && DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->exists()];
});
return response()->json(['cases' => $cases]);
}
@@ -0,0 +1,71 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestorPath;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class InvestorPathController extends Controller
{
public function index(Request $request, InvestorPath $path): JsonResponse|Response
{
abort_unless($path->available(), 404);
$data = ['contexts' => $path->contexts($request->user())];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
}
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
{
$id = $path->create($request->user(), $request->all());
return $request->expectsJson() ? response()->json(['id' => $id], 201) : redirect('/investimentos/'.$id)->with('success', 'Investimento guardado no seu dossier.');
}
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
{
$data = $path->view($request->user(), $id);
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/show', $data);
}
public function facts(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$path->facts($request->user(), $id, $request->all());
return $this->saved($request, 'Aplicabilidade registada; o histórico foi preservado.');
}
public function stage(Request $request, string $id, string $code, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$path->stage($request->user(), $id, $code, $request->all());
return $this->saved($request, 'Etapa e fundamento registados.');
}
public function tool(Request $request, string $id, InvestorPath $path): JsonResponse
{
abort_unless($path->available(), 404);
return response()->json(['result' => $path->returnTool($request, $id, $request->all())]);
}
public function task(Request $request, string $id, InvestorPath $path): JsonResponse|RedirectResponse
{
abort_unless($path->available(), 404);
$task = $path->task($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['id' => $task], 201) : back()->with('success', 'Tarefa assumida no acompanhamento interno.');
}
private function saved(Request $request, string $message): JsonResponse|RedirectResponse
{
return $request->expectsJson() ? response()->json(['message' => $message]) : back()->with('success', $message);
}
}
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Models\InterestRequest;
use App\Models\Investor;
use App\Models\InvestorJourney;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission;
use App\Services\PortalAudit;
use Illuminate\Http\RedirectResponse;
@@ -23,10 +24,12 @@ class InvestorWorkspaceController extends Controller
$interest = $journey->interest_request_id ? InterestRequest::find($journey->interest_request_id) : null;
return ['id' => $journey->id, 'dossier_id' => $dossier?->id, 'title' => $dossier->title ?? 'Ficha temporariamente indisponível',
'status' => $journey->status, 'reference' => $interest?->reference, 'request_status' => $interest?->status];
'status' => $journey->status, 'reference' => $interest?->reference, 'request_status' => $interest?->status,
'country' => $interest?->country,
'declared_origin' => app(CountryCatalogue::class)->describe($interest?->metadata['declared_origin_country_code'] ?? null)];
});
return Inertia::render('portfolio/workspace', ['journeys' => $journeys]);
return Inertia::render('portfolio/workspace', ['journeys' => $journeys, 'countries' => app(CountryCatalogue::class)->all()]);
}
public function start(Request $request, string $id): RedirectResponse
@@ -57,7 +60,8 @@ class InvestorWorkspaceController extends Controller
public function submit(Request $request, string $id, InterestSubmission $submission): RedirectResponse
{
$data = $request->validate(['message' => ['required', 'string', 'min:20', 'max:5000'], 'country' => ['required', 'string', 'max:100'],
$data = $request->validate(['message' => ['required', 'string', 'min:20', 'max:5000'], 'country' => ['required', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'privacy_consent' => ['accepted'], 'role' => ['required', 'in:investir,financiar,fornecer,operar,parceria'],
'horizon' => ['required', 'string', 'max:100']]);
DB::transaction(function () use ($request, $id, $data, $submission) {
@@ -74,6 +78,7 @@ class InvestorWorkspaceController extends Controller
'sector_interest' => Str::limit($dossier->content['sector'] ?? $dossier->title, 150, ''), 'message' => $data['message'],
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/carteira/'.$dossier->id,
'metadata' => ['journey_id' => $journey->id, 'dossier_id' => $dossier->id, 'origin_dossier_id' => $journey->origin_dossier_id,
'declared_origin_country_code' => $data['declared_origin_country_code'] ?? null,
'project_id' => $dossier->project_id ?? $origin?->project_id,
'cluster_id' => $dossier->cluster_id ?? $origin?->cluster_id, 'corridor_id' => $dossier->corridor_id ?? $origin?->corridor_id,
'role' => $data['role'], 'horizon' => $data['horizon'], 'purpose' => 'Acompanhamento da manifestação de interesse'],
@@ -8,7 +8,9 @@ use App\Http\Requests\StoreLandAssistanceCaseRequest;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\LandAssistanceCase;
use App\Services\CountryCatalogue;
use App\Services\InterestSubmission;
use App\Services\InvestmentGeography;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -57,6 +59,7 @@ class LandAssistanceController extends Controller
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1',
'countries' => app(CountryCatalogue::class)->all(),
]);
}
@@ -70,6 +73,7 @@ class LandAssistanceController extends Controller
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
'disclaimer' => self::DISCLAIMER,
'modelVersion' => 'land-assistance-v1',
'countries' => app(CountryCatalogue::class)->all(),
]);
}
@@ -102,6 +106,7 @@ class LandAssistanceController extends Controller
{
$case = $this->owned($request, $id);
$data = [
...$this->presentation($case),
'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']),
'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')
@@ -162,6 +167,7 @@ class LandAssistanceController extends Controller
'sectorInterest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacyConsent' => true, 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
'declared_origin_country_code' => $payload['declared_origin_country_code'] ?? null,
], $case->crm_submission_key, fn () => InterestRequest::create([
'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $payload['full_name'],
'email' => $payload['email'], 'phone' => $payload['phone'] ?? null,
@@ -169,7 +175,8 @@ class LandAssistanceController extends Controller
'sector_interest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/terra-duat',
'metadata' => ['kind' => 'support', 'portal_user_id' => $request->user()->id,
'land_case_id' => $case->id, 'land_case_reference' => $case->reference],
'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
'declared_origin_country_code' => $payload['declared_origin_country_code'] ?? null],
]));
$case->forceFill([
'payload' => $payload,
@@ -304,6 +311,22 @@ class LandAssistanceController extends Controller
]);
}
/** @return array<string,mixed> */
private function presentation(LandAssistanceCase $case, bool $management = false): array
{
$payload = $case->payload;
$countries = app(CountryCatalogue::class);
$country = $countries->describe($payload['country'] ?? null);
$paths = [];
foreach ($payload['parcels'] ?? [] as $parcel) {
$id = $parcel['locality_id'] ?? $parcel['admin_post_id'] ?? $parcel['district_id'] ?? $parcel['province_id'] ?? null;
$paths[] = app(InvestmentGeography::class)->path($id ?: null, $management);
}
return ['countryName' => $country['code'] !== null ? $country['name'] : ($payload['country'] ?? 'Não informado'),
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths];
}
public function manage(Request $request): Response
{
$cases = LandAssistanceCase::query()->latest('updated_at')->paginate(30)->through(fn (LandAssistanceCase $case): array => [
@@ -321,6 +344,7 @@ class LandAssistanceController extends Controller
$events = DB::table('land_assistance_events')->where('case_id', $id)->orderBy('created_at')->get(['action', 'version', 'metadata', 'created_at']);
return Inertia::render('land-assistance/case', [
...$this->presentation($case, true),
'case' => $case->only(['id', 'reference', 'status', 'version', 'payload', 'updated_at']),
'documents' => DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
->where('link.case_id', $id)->whereIn('document.status', ['active', 'quarantined'])->whereNull('document.deleted_at')->get(['link.id', 'link.category', 'document.file_name', 'document.status']),
@@ -8,6 +8,7 @@ use App\Models\Sector;
use App\Services\InvestmentGeography;
use App\Services\OpportunityManagement;
use App\Services\OpportunityManagementInstallation;
use App\Services\OpportunityMaturity;
use App\Services\OpportunityResources;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
@@ -67,10 +68,11 @@ class OpportunityManagementController extends Controller
return app(PortalManagementController::class)->edit('opportunities', $id);
}
$record = $id ? Opportunity::withTrashed()->findOrFail($id) : null;
$values = $record ? ($record->management_draft ? json_decode($record->management_draft, true) : $record->only(OpportunityManagement::FIELDS)) : [];
$values = $record ? $service->values($record) : [];
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
return Inertia::render('management/opportunity-draft', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view'), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'categories' => OpportunityManagement::CATEGORIES,
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES, 'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS],
'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true),
'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]);
}
@@ -54,7 +54,7 @@ class OpportunityResourceController extends Controller
$image->derivativePreviews = [];
foreach ($image->payload['derivatives'] ?? [] as $derived) {
if (DB::table('documents')->where('id', $derived['document_id'])->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->exists()) {
$image->derivativePreviews[] = [...$derived, 'url' => URL::temporarySignedRoute('opportunity-image-preview', now()->addMinutes(10), ['id' => $id, 'resourceId' => $image->id, 'documentId' => $derived['document_id']])];
$image->derivativePreviews[] = [...$derived, 'url' => URL::temporarySignedRoute('management.opportunity-image-preview', now()->addMinutes(10), ['id' => $id, 'resourceId' => $image->id, 'documentId' => $derived['document_id']])];
}
}
}
@@ -7,6 +7,8 @@ use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\CountryCatalogue;
use App\Services\DeclaredOriginStatistics;
use App\Services\InterestWorkflow;
use App\Services\InvestmentGeography;
use App\Services\InvestmentWorkspace;
@@ -56,10 +58,22 @@ class PortalManagementController extends Controller
'q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in(self::STATES)],
'follow_up' => ['nullable', Rule::in(['overdue', 'upcoming', 'unassigned'])],
'country' => ['nullable', app(CountryCatalogue::class)->rule()],
'origin' => ['nullable', Rule::in([...array_column(app(CountryCatalogue::class)->all(), 'code'), 'unknown'])],
]);
$query = InterestRequest::query()->with('assignee:id,name')->select([
'id', 'reference', 'full_name', 'email', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
]);
if ($country = $filters['country'] ?? null) {
$query->where('country', $country);
}
if ($origin = $filters['origin'] ?? null) {
if ($origin === 'unknown') {
$query->where(fn ($q) => $q->whereNull('metadata->declared_origin_country_code')->orWhereNotIn('metadata->declared_origin_country_code', array_column(app(CountryCatalogue::class)->all(), 'code')));
} else {
$query->where('metadata->declared_origin_country_code', $origin);
}
}
if ($term = $filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('reference', "%{$term}%")
->orWhereLike('full_name', "%{$term}%")->orWhereLike('email', "%{$term}%"));
@@ -78,8 +92,18 @@ class PortalManagementController extends Controller
}
return Inertia::render('management/interests', [
'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString(),
'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString()->through(function ($row) {
$result = $row->toArray();
$result['declaredOrigin'] = app(CountryCatalogue::class)->describe($row->metadata['declared_origin_country_code'] ?? null);
$country = app(CountryCatalogue::class)->describe($row->country);
$result['countryName'] = $country['code'] !== null ? $country['name'] : $row->country;
unset($result['metadata']);
return $result;
}),
'filters' => $filters,
'countries' => app(CountryCatalogue::class)->all(),
'originStatistics' => app(DeclaredOriginStatistics::class)->forManager($request->user(), $filters['origin'] ?? null),
]);
}
@@ -97,6 +121,7 @@ class PortalManagementController extends Controller
->orderBy('created_at')->get(['purpose', 'policy_version', 'status', 'granted_at', 'withdrawn_at']);
return Inertia::render('management/interest', [
'declaredOrigin' => app(CountryCatalogue::class)->describe($interest->metadata['declared_origin_country_code'] ?? null),
'interest' => $interest->only([
'id', 'reference', 'full_name', 'email', 'phone', 'investor_type', 'country',
'sector_interest', 'opportunity_reference', 'investment_range', 'message',
@@ -5,9 +5,11 @@ namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InterestRequest;
use App\Models\Sector;
use App\Services\CountryCatalogue;
use App\Services\IdempotencyConflict;
use App\Services\InterestSubmission;
use App\Services\Malware\MalwareScanner;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\QueryException;
@@ -37,7 +39,7 @@ class PortalServicesController extends Controller
$essentialResources = collect();
}
return Inertia::render('PortalInvestidor', ['essentialResources' => $essentialResources]);
return Inertia::render('PortalInvestidor', ['essentialResources' => $essentialResources, 'countries' => app(CountryCatalogue::class)->all()]);
}
private function resources(): Builder
@@ -64,7 +66,7 @@ class PortalServicesController extends Controller
'stage' => ['nullable', 'array', 'max:10'], 'stage.*' => ['string', 'max:80'],
'module' => ['nullable', 'array', 'max:10'], 'module.*' => ['string', 'max:80'],
]);
$props = ['section' => $page, 'filters' => $filters];
$props = ['section' => $page, 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all()];
if ($page === 'sectors') {
$props['sectors'] = Sector::where('is_active', true)->withCount(['opportunities' => fn ($q) => $q->published()])->orderBy('sort_order')->get(['id', 'name', 'slug', 'short_description']);
}
@@ -222,7 +224,8 @@ class PortalServicesController extends Controller
$data = $request->validate([
'kind' => ['required', 'in:support,investor,company,partnership'],
'fullName' => ['required', 'string', 'min:3', 'max:150'], 'email' => ['required', 'email:rfc', 'max:150'],
'phone' => ['nullable', 'string', 'max:30'], 'country' => ['required', 'string', 'max:100'],
'phone' => ['nullable', 'string', 'max:30'], 'country' => ['required', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'company' => ['nullable', 'required_if:kind,company', 'string', 'max:150'],
'sectorInterest' => ['required', 'string', 'max:150'], 'message' => ['required', 'string', 'min:20', 'max:2000'],
'privacyConsent' => ['required', 'accepted'], 'submission_key' => ['required', 'uuid'],
@@ -240,7 +243,8 @@ class PortalServicesController extends Controller
'sector_interest' => $data['sectorInterest'], 'message' => $data['message'],
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/apoio',
'metadata' => ['kind' => $data['kind'], 'company' => $data['company'] ?? null,
'portal_user_id' => $data['portal_user_id'], 'partnership_id' => $data['partnership_id'] ?? null],
'portal_user_id' => $data['portal_user_id'], 'partnership_id' => $data['partnership_id'] ?? null,
'declared_origin_country_code' => $data['declared_origin_country_code'] ?? null],
]));
} catch (IdempotencyConflict) {
abort(409, 'Este envio já foi usado com dados diferentes. Recarregue o formulário.');
@@ -260,17 +264,12 @@ class PortalServicesController extends Controller
return back()->with('success', 'Proposta recebida para publicação. Acompanhe no Balcão Virtual.');
}
public function download(int $id): BinaryFileResponse
public function download(int $id): BinaryFileResponse|\Illuminate\Http\Response
{
$resource = $this->resources()->where('r.id', $id)->first(['d.storage_key', 'd.file_name', 'd.sha256']);
$resource = $this->resources()->where('r.id', $id)->first(['d.*']);
abort_unless($resource !== null, 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($resource->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($resource->sha256, $checksum), 404);
return response()->download($path, basename($resource->file_name), ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store']);
return app(VerifiedDocumentBinary::class)->respond($resource);
}
public function showDocument(Request $request, int $id): Response
@@ -306,42 +305,21 @@ class PortalServicesController extends Controller
]);
}
public function viewDocument(int $id): BinaryFileResponse
public function viewDocument(int $id): BinaryFileResponse|\Illuminate\Http\Response
{
$document = $this->resources()->where('r.id', $id)->first([
'd.storage_key', 'd.file_name', 'd.sha256', 'd.media_type',
]);
$document = $this->resources()->where('r.id', $id)->first(['d.*']);
abort_unless($document && in_array($document->media_type, ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'], true), 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($document->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($document->sha256, $checksum), 404);
return response()->file($path, [
'Content-Type' => $document->media_type,
'X-Content-Type-Options' => 'nosniff',
'Content-Security-Policy' => "sandbox; default-src 'none'; style-src 'unsafe-inline'",
'Cache-Control' => 'private, no-store',
])->setContentDisposition('inline', basename($document->file_name));
return app(VerifiedDocumentBinary::class)->respond($document, true);
}
public function downloadForManager(string $id): BinaryFileResponse
public function downloadForManager(string $id): BinaryFileResponse|\Illuminate\Http\Response
{
$document = DB::table('documents')->where('id', $id)->whereNull('deleted_at')->first([
'storage_key', 'file_name', 'sha256', 'status', 'malware_scan_status', 'malware_scanned_sha256',
]);
$document = DB::table('documents')->where('id', $id)->whereNull('deleted_at')->first();
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
$root = realpath(Storage::disk('local')->path(''));
$path = realpath(Storage::disk('local')->path($document->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$checksum = hash_file('sha256', $path);
abort_unless($checksum !== false && hash_equals($document->sha256, $checksum), 404);
return response()->download($path, basename($document->file_name), [
'X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store',
]);
return app(VerifiedDocumentBinary::class)->respond($document);
}
public function manage(MalwareScanner $scanner): Response
@@ -437,8 +415,8 @@ class PortalServicesController extends Controller
$id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]);
$this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'created', $request->user()->id, 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'],
DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer,
'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, $duplicate ? 'resource_registered_possible_duplicate' : 'resource_registered', 'portal_resources', $id);
@@ -475,8 +453,8 @@ class PortalServicesController extends Controller
DB::table('portal_resource_links')->where('resource_id', $id)->delete();
$this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'metadata_updated', $request->user()->id, $expectedVersion + 1);
DB::table('documents')->where('id', $document->id)->update(['issuer' => $data['issuer'] ?: $document->issuer,
'issued_on' => $data['document_date'] ?: $document->issued_on, 'rights_status' => $data['rights_status'],
DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer,
'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
$this->audit($request, 'resource_metadata_updated', 'portal_resources', $id);
});
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Http\Resources\PublicBusinessOpportunityResource;
use App\Models\ExistingBusiness;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts;
use App\Services\InvestmentGeography;
use Illuminate\Database\Eloquent\Builder;
@@ -84,6 +85,7 @@ class PublicBusinessOpportunityController extends Controller
return Inertia::render('investment/business-interest', [
'record' => (new PublicBusinessOpportunityResource($record))->resolve($request),
'modalities' => ExistingBusinessDrafts::MODALITIES,
'countries' => app(CountryCatalogue::class)->all(),
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
]);
}
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\CountryCatalogue;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
@@ -32,13 +33,13 @@ class PublicPortalController extends Controller
public function interest(?string $slug = null): Response
{
return $slug ? $this->detail($slug, 'interest') : Inertia::render('PortalInvestidor', ['initialView' => 'interest']);
return $slug ? $this->detail($slug, 'interest') : Inertia::render('PortalInvestidor', ['initialView' => 'interest', 'countries' => app(CountryCatalogue::class)->all()]);
}
private function detail(string $slug, string $view): Response
{
$opportunity = Opportunity::with('sector:id,name,slug')->published()->where('slug', $slug)->firstOrFail();
return Inertia::render('PortalInvestidor', ['initialView' => $view, 'initialOpportunity' => $opportunity]);
return Inertia::render('PortalInvestidor', ['initialView' => $view, 'initialOpportunity' => $opportunity, 'countries' => app(CountryCatalogue::class)->all()]);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers;
use App\Services\TerritoryGeometryImport;
use Illuminate\Http\Request;
use Inertia\Inertia;
class TerritoryGeometryImportController extends Controller
{
public function preview(Request $request, TerritoryGeometryImport $service)
{
$data = $request->validate(['level' => 'nullable|integer|in:1,2,3']);
$plan = $service->preview($request->user(), (int) ($data['level'] ?? 1));
return $request->expectsJson() ? response()->json($plan) : Inertia::render('management/territory-geometry-import', ['plan' => $plan]);
}
public function apply(Request $request, TerritoryGeometryImport $service)
{
return response()->json($service->apply($request->user(), $request->all()));
}
public function reverse(Request $request, string $batch, TerritoryGeometryImport $service)
{
return response()->json($service->reverse($request->user(), $batch, $request->all()));
}
}
+21 -9
View File
@@ -3,10 +3,13 @@
namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\InvestmentSubmission;
use App\Models\User;
use App\Services\Ai\InvestorGuidance;
use App\Services\CountryCatalogue;
use App\Services\InstitutionalLinkMonitor;
use App\Services\InvestmentGeography;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
@@ -48,7 +51,7 @@ class VirtualDeskController extends Controller
$data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(),
'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']),
'companies' => DB::table('investment_company_declarations')->where('user_id', $actor->id)->get(['id', 'payload'])->map(fn ($c) => ['id' => $c->id, 'name' => $desk->decode($c->payload)['name'] ?? 'Declaração empresarial']),
'submissions' => \App\Models\InvestmentSubmission::where('user_id', $actor->id)->get()->map(fn ($s) => ['id' => $s->id, 'status' => $s->status, 'name' => ($s->opportunity_id ? DB::table('opportunities')->where('id', $s->opportunity_id)->value('title') : null) ?? ($s->dossier_id ? DB::table('investment_dossiers')->where('id', $s->dossier_id)->value('title') : null) ?? ($s->payload['organisation'] ?? null)]),
'submissions' => InvestmentSubmission::where('user_id', $actor->id)->get()->map(fn ($s) => ['id' => $s->id, 'status' => $s->status, 'name' => ($s->opportunity_id ? DB::table('opportunities')->where('id', $s->opportunity_id)->value('title') : null) ?? ($s->dossier_id ? DB::table('investment_dossiers')->where('id', $s->dossier_id)->value('title') : null) ?? ($s->payload['organisation'] ?? null)]),
'journeys' => DB::table('investor_journeys as j')->leftJoin('investment_dossiers as d', 'd.id', '=', 'j.dossier_id')->where('j.user_id', $actor->id)->whereNull('j.deleted_at')->get(['j.id', 'j.dossier_id', 'j.status', 'd.title as name']),
'simulationDrafts' => DB::table('simulation_form_drafts')->where('owner_user_id', $actor->id)->whereNull('deleted_at')->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->get(['id', 'version_no']),
'guidanceTasks' => app(InvestorGuidance::class)->installed() ? DB::table('tasks as t')->join('desk_cases as c', 'c.id', '=', 't.desk_case_id')
@@ -72,7 +75,11 @@ class VirtualDeskController extends Controller
$case = $desk->case($request->user(), $id);
$owner = $desk->owns($request->user(), $case, false);
$this->auditRead($request, 'desk_cases', $id);
$data = ['case' => [...(array) $case, 'payload' => Arr::except($desk->decode($case->payload), $owner ? ['_creation_hash'] : ['_creation_hash', 'profile', 'company', 'investment', 'name', 'email']), 'workflow' => json_decode($case->workflow, true)],
$hidden = $owner ? ['_creation_hash'] : ['_creation_hash', 'profile', 'company', 'investment', 'name', 'email'];
if ((int) $case->user_id !== $request->user()->id) {
$hidden[] = 'investor_path';
}
$data = ['case' => [...(array) $case, 'payload' => Arr::except($desk->decode($case->payload), $hidden), 'workflow' => json_decode($case->workflow, true)],
'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at')
->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id))
->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null,
@@ -122,6 +129,13 @@ class VirtualDeskController extends Controller
$row = $desk->request($request->user(), $id);
$case = $desk->case($request->user(), $row->case_id);
$payload = $desk->decode($row->payload);
$definition = $desk->definition($row);
$territoryPaths = [];
foreach ($definition['fields'] as $key => $field) {
if ($field['type'] === 'territory') {
$territoryPaths[$key] = app(InvestmentGeography::class)->path($payload[$key] ?? null);
}
}
$messageKinds = [];
foreach (DB::table('desk_events')->where('request_id', $id)->where('action', 'message_added')->get() as $event) {
$original = $desk->decode($event->payload);
@@ -130,8 +144,8 @@ class VirtualDeskController extends Controller
}
}
$this->auditRead($request, 'desk_requests', $id);
$data = ['countries' => app(\App\Services\CountryCatalogue::class)->all(), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $desk->definition($row),
$data = ['countries' => app(CountryCatalogue::class)->all(), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
'owner' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'), 'analyst' => (int) $row->analyst_id === $request->user()->id,
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
@@ -274,7 +288,7 @@ class VirtualDeskController extends Controller
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Documento privado associado; consulte o estado da análise.');
}
public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse
public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse|\Illuminate\Http\Response
{
$desk->case($request->user(), $id);
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('l.id', $document)->whereNull('d.deleted_at')->first(['d.*', 'l.request_id']);
@@ -282,12 +296,10 @@ class VirtualDeskController extends Controller
$desk->request($request->user(), $doc->request_id);
}
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 404);
$path = realpath(Storage::disk('local')->path($doc->storage_key));
$root = realpath(Storage::disk('local')->path(''));
abort_unless($path && $root && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path) && is_string($actualHash = hash_file('sha256', $path)) && hash_equals(trim($doc->sha256), $actualHash), 404);
$response = app(VerifiedDocumentBinary::class)->respond($doc);
$this->auditRead($request, 'documents', $doc->id, 'document_downloaded');
return response()->download($path, $doc->file_name, ['Cache-Control' => 'private, no-store']);
return $response;
}
public function notification(Request $request, int $id): RedirectResponse
@@ -2,6 +2,7 @@
namespace App\Http\Middleware;
use App\Services\InvestorPath;
use Illuminate\Http\Request;
use Inertia\Middleware;
@@ -42,6 +43,7 @@ class HandleInertiaRequests extends Middleware
'educationEnabled' => (bool) config('education.enabled', false),
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
'investorPathEnabled' => app(InvestorPath::class)->available(),
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
'auth' => [
'user' => $request->user(),
@@ -2,6 +2,7 @@
namespace App\Http\Requests;
use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
@@ -30,7 +31,8 @@ class StoreInterestRequestRequest extends FormRequest
'investorType' => ['required', 'string', Rule::in([
'individual', 'empresa', 'fundo', 'entidade_publica', 'outro',
])],
'country' => ['required', 'string', 'max:100'],
'country' => ['required', 'string', 'max:100', ...($knownKey ? [] : [app(CountryCatalogue::class)->legacyCountryRule()])],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'sectorInterest' => ['required', 'string', 'max:150'],
// A known receipt can replay after withdrawal; the service verifies the payload hash.
'opportunityReference' => ['nullable', 'string', 'max:80', ...($knownKey ? [] : [
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Http\Requests;
use App\Services\CountryCatalogue;
use App\Services\InvestmentGeography;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;
@@ -28,7 +29,7 @@ class StoreLandAssistanceCaseRequest extends FormRequest
{
return [
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
'payload' => ['required', 'array:support_kind,request_description,project_reference,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
'payload' => ['required', 'array:support_kind,request_description,project_reference,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
'payload.support_kind' => ['nullable', 'in:investment,home,family_exploitation,recognition,regularization,delimitation,change_of_use,transfer,existing_process,conflict_guidance,other'],
'payload.request_description' => ['nullable', 'string', 'max:4000'],
'payload.project_reference' => ['nullable', 'string', 'max:160'],
@@ -38,7 +39,8 @@ class StoreLandAssistanceCaseRequest extends FormRequest
'payload.email' => ['nullable', 'email:rfc', 'max:150'],
'payload.phone' => ['nullable', 'string', 'max:30'],
'payload.preferred_contact' => ['nullable', 'in:email,phone,any'],
'payload.country' => ['nullable', 'string', 'max:100'],
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.nationality' => ['nullable', 'string', 'max:120'],
'payload.representative_name' => ['nullable', 'string', 'max:200'],
'payload.representative_role' => ['nullable', 'string', 'max:120'],
@@ -132,7 +134,9 @@ class StoreLandAssistanceCaseRequest extends FormRequest
continue;
}
$record = $geography->publicReferences()->where('id', $id)->first(['id', 'parent_id', 'location_type']);
if ($gap || ! $record || $record->location_type !== $expectedType || ($expectedType === 'province' ? $record->parent_id !== null : (string) $record->parent_id !== $parent)) {
// The populated workbook hierarchy has country -> province. The public
// selector deliberately starts at province; it is not a root in storage.
if ($gap || ! $record || $record->location_type !== $expectedType || ($expectedType !== 'province' && (string) $record->parent_id !== $parent)) {
$validator->errors()->add("payload.parcels.$index.$field", 'A hierarquia territorial declarada é incoerente ou não está publicada.');
$gap = true;
}
@@ -2,6 +2,7 @@
namespace App\Http\Requests;
use App\Services\CountryCatalogue;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;
@@ -62,6 +63,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$rules = [
// Anonymous clients must send an empty snapshot; `required` rejects
// an empty array before the privacy policy can enforce that shape.
'context' => ['nullable', 'uuid'],
'personal_snapshot' => ['present', 'array:'.implode(',', $personal)],
'economic_snapshot' => ['required', 'array:'.implode(',', $economic)],
'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'],
@@ -169,6 +171,10 @@ class StoreSimulationFormDraftRequest extends FormRequest
'contact_province', 'contact_district', 'preferred_channel'] as $field) {
$rules['personal_snapshot.'.$field] = ['nullable', 'string', 'max:3000'];
}
foreach (['tax_residency_country', 'fiscal_residency_country', 'contact_country'] as $field) {
$rules['personal_snapshot.'.$field][] = app(CountryCatalogue::class)->legacyCountryRule();
}
$rules['economic_snapshot.funds_origin_countries.*'][] = app(CountryCatalogue::class)->legacyCountryRule();
return $rules;
}
+4 -2
View File
@@ -132,9 +132,11 @@ class InvestorGuidance
$actions = ['opportunities' => '/oportunidades', 'locations' => '/oportunidades?view=map', 'partners' => '/parcerias',
'documents' => '/documentos', 'plan' => $case->submission_id && (int) $case->user_id === $actor->id ? '/investidor/manifestacoes/'.$case->submission_id : '/balcao-virtual/dossiers/'.$id,
'simulator' => '/simulador-fiscal', 'support' => '/balcao-virtual/dossiers/'.$id];
// The simulator recovers its current owner-scoped draft; do not pass private payload in URLs.
// Pin the linked owner-scoped draft instead of opening another project's current draft.
// The receiving API still enforces ownership; no private payload is carried in the URL.
if ($case->simulation_id && $context['financial_draft'] !== null) {
$actions['plan'] = '/simulador-fiscal';
$actions['simulator'] = '/simulador-fiscal?draft='.rawurlencode($case->simulation_id);
$actions['plan'] = $actions['simulator'];
}
$phases = $this->rules->evaluate($context['facts'], $context['evidence']);
foreach ($phases as &$phase) {
+8 -3
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\In;
use Illuminate\Validation\ValidationException;
final class BusinessFormSchema
@@ -13,7 +14,8 @@ final class BusinessFormSchema
return [
'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']],
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição (código ISO de duas letras)', 'en' => 'Country of origin or incorporation (two-letter ISO code)', 'type' => 'text', 'max' => 2],
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição', 'en' => 'Country of origin or incorporation', 'type' => 'country', 'max' => 100],
'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem declarado desta solicitação (opcional)', 'en' => 'Declared country of origin of this request (optional)', 'type' => 'country', 'max' => 2],
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50],
'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200],
'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
@@ -77,7 +79,7 @@ final class BusinessFormSchema
];
}
/** @return array<string, array<int,string>> */
/** @return array<string, list<string|\Closure|In>> */
public static function rules(): array
{
$rules = [];
@@ -89,7 +91,8 @@ final class BusinessFormSchema
}
$rules['payload.contact_email'][] = 'nullable';
$rules['payload.contact_email'][] = 'email';
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/';
$rules['payload.country'][] = app(CountryCatalogue::class)->legacyCountryRule();
$rules['payload.declared_origin_country_code'][] = app(CountryCatalogue::class)->rule();
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
@@ -122,6 +125,8 @@ final class BusinessFormSchema
$rules[$field] = ['required'];
}
$rules['sector_id'] = ['required'];
$rules['country'] = ['required', 'string', app(CountryCatalogue::class)->rule()];
$rules['declared_origin_country_code'] = ['nullable', 'string', app(CountryCatalogue::class)->rule()];
$rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email'];
$rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/'];
$rules['legitimacy_declaration'] = ['required', 'in:yes'];
+22 -1
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\In;
/** Shared ISO identifiers; independent of administrative territories and IP data. */
final class CountryCatalogue
@@ -28,8 +29,28 @@ final class CountryCatalogue
return $countries;
}
public function rule(): \Illuminate\Validation\Rules\In
public function rule(): In
{
return Rule::in(array_column($this->all(), 'code'));
}
/** Accept existing free-text integrations; validate ISO-shaped values without rewriting them. */
public function legacyCountryRule(): \Closure
{
$codes = array_column($this->all(), 'code');
return static function (string $attribute, mixed $value, \Closure $fail) use ($codes): void {
if (is_string($value) && preg_match('/^[a-zA-Z]{2}$/D', $value) && ! in_array($value, $codes, true)) {
$fail('Seleccione um código ISO de país válido.');
}
};
}
/** @return array{code:string|null,name:string} */
public function describe(?string $code): array
{
$names = array_column($this->all(), 'name', 'code');
return isset($names[$code ?? '']) ? ['code' => $code, 'name' => $names[$code]] : ['code' => null, 'name' => 'Não informado'];
}
}
+11 -1
View File
@@ -3,6 +3,7 @@
namespace App\Services;
use App\Models\User;
use App\Services\Mne\BusinessRepository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@@ -28,14 +29,23 @@ final class DeclaredOriginStatistics
$desk[$key] = ($desk[$key] ?? 0) + 1;
}
}
$businesses = [];
if (Schema::hasTable('existing_businesses')) {
foreach (app(BusinessRepository::class)->query()->whereNotIn('status', ['draft', 'cancelled'])->cursor() as $business) {
$code = $business->payload['declared_origin_country_code'] ?? null;
$key = is_string($code) && isset($names[$code]) ? $code : '';
$businesses[$key] = ($businesses[$key] ?? 0) + 1;
}
}
// Distinct request collections; summing them could count the same investor twice.
if ($origin !== null && $origin !== '') {
$key = $origin === 'unknown' ? '' : $origin;
$groups = array_intersect_key($groups, [$key => true]);
$desk = array_intersect_key($desk, [$key => true]);
$businesses = array_intersect_key($businesses, [$key => true]);
}
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names)];
return ['interests' => $this->format($groups, $names), 'desk' => $this->format($desk, $names), 'businesses' => $this->format($businesses, $names)];
}
/** @param array<string, int> $counts
+2 -1
View File
@@ -81,7 +81,8 @@ final class ExistingBusinessIntake
} elseif (($business->payload['wizard_version'] ?? null) === '1') {
Validator::make($business->payload, [
'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'],
'contact_email' => ['required', 'email'], 'country' => ['required', 'regex:/^[A-Z]{2}$/'],
'contact_email' => ['required', 'email'], 'country' => ['required', app(CountryCatalogue::class)->rule()],
'declared_origin_country_code' => ['nullable', app(CountryCatalogue::class)->rule()],
'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'],
'legitimacy_declaration' => ['required', 'in:yes'],
'mandate_reference' => ['required_if:acting_capacity,representative'],
+334
View File
@@ -0,0 +1,334 @@
<?php
namespace App\Services;
use App\Models\CrmTask;
use App\Models\SimulationFormDraft;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
final class InvestorPath
{
public function __construct(private readonly VirtualDesk $desk) {}
public function available(): bool
{
return (bool) config('investor-path.enabled') && $this->desk->installed()
&& Schema::hasColumn('investor_journeys', 'path_definition_id') && Schema::hasColumn('journey_steps', 'path_detail');
}
/** @param array<string,mixed> $input */
public function create(User $actor, array $input): string
{
abort_unless($this->available(), 404);
return DB::transaction(function () use ($actor, $input): string {
$case = $this->desk->createCase($actor, $input);
$this->initialize($actor, $case->id);
return $case->id;
});
}
public function initialize(User $actor, string $id): void
{
abort_unless($this->available(), 404);
DB::transaction(function () use ($actor, $id): void {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
if ($case->journey_id) {
$existing = DB::table('investor_journeys')->where('id', $case->journey_id)->firstOrFail();
// Never convert or renumber a saved portfolio/legacy journey implicitly.
abort_unless($existing->path_definition_id !== null, 409, 'O percurso existente foi preservado; a conversão exige uma correspondência explícita.');
return;
}
$version = DB::table('questionnaire_versions')->where('id', config('investor-path.definition_id'))
->where('code', 'investor-path-19')->where('status', 'published')->firstOrFail();
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
InvestorPathDefinition::validate($definition);
$journey = (string) Str::uuid();
DB::table('investor_journeys')->insert(['id' => $journey, 'investor_id' => $case->investor_id, 'user_id' => $actor->id,
'status' => 'started', 'path_definition_id' => $version->id, 'source_system' => 'investor-path', 'data_classification' => 'confidential']);
foreach ($definition['steps'] as $step) {
DB::table('journey_steps')->insert(['id' => (string) Str::uuid(), 'journey_id' => $journey, 'step_code' => $step['code'],
'sequence_no' => $step['sequence'], 'status' => 'pending', 'source_system' => 'investor-path', 'data_classification' => 'confidential',
'path_detail' => $this->desk->encode(['state' => 'not_started'])]);
}
DB::table('desk_cases')->where('id', $id)->update(['journey_id' => $journey, 'version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'investor_path_started', ['journey_id' => $journey, 'definition_id' => $version->id, 'source_sha256' => $definition['source_sha256']]);
});
}
/** @return array<string,mixed> */
public function view(User $actor, string $id): array
{
abort_unless($this->available(), 404);
$case = $this->desk->case($actor, $id);
$journey = DB::table('investor_journeys')->where('id', $case->journey_id)->whereNull('deleted_at')->firstOrFail();
abort_unless($journey->path_definition_id !== null, 409, 'Este dossier conserva o seu roteiro original.');
$version = DB::table('questionnaire_versions')->where('id', $journey->path_definition_id)->firstOrFail();
$definition = json_decode($version->schema_snapshot, true, 512, JSON_THROW_ON_ERROR);
$payload = $this->desk->decode($case->payload);
$path = $payload['investor_path'] ?? [];
$facts = $path['facts'] ?? ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
$records = DB::table('journey_steps')->where('journey_id', $journey->id)->whereNull('deleted_at')->get()->keyBy('step_code');
$steps = [];
foreach ($definition['steps'] as $step) {
$row = $records->get($step['code']);
abort_unless($row !== null, 409, 'Etapa em falta; reparar a instalação sem reconstruir o histórico.');
$detail = $this->desk->decode($row->path_detail);
$value = $step['branch'] ? ($facts[$step['branch']] ?? 'unknown') : 'yes';
$applicable = $value === 'unknown' ? 'undetermined' : ($value === 'no' ? 'not_needed_for_preparation' : 'applicable');
$state = $value === 'no' ? 'dispensed' : $detail['state'];
$steps[] = [...$step, 'id' => $row->id, 'version' => $row->version_no, 'state' => $state, 'saved_state' => $detail['state'],
'applicability' => $applicable, 'reason' => $value === 'no' ? ($path['fact_reasons'][$step['branch']] ?? '') : ($detail['reason'] ?? ''),
'detail' => $detail, 'preparation_allowed' => $value !== 'no',
'action_gaps' => []];
}
$byCode = collect($steps)->keyBy('code');
foreach ($steps as &$step) {
foreach ($step['dependencies'] as $action => $dependencies) {
$step['action_gaps'][$action] = array_values(array_filter($dependencies, function ($code) use ($byCode) {
$dependency = $byCode->get($code);
// Branch dispensation is not evidence of any legal permission.
return ! in_array($dependency['state'], ['completed', 'approved'], true);
}));
}
}
unset($step);
foreach ($steps as &$step) {
if (in_array($step['state'], ['completed', 'submitted'], true)
&& count(array_filter($step['action_gaps'])) > 0) {
$step['state'] = 'correction_required';
$step['reason'] = 'Uma dependência desta acção foi reaberta; reveja o avanço. O registo original foi preservado.';
}
}
unset($step);
$owner = $this->desk->owns($actor, $case);
$manager = $actor->can('manage-portal');
$requests = DB::table('desk_requests')->where('case_id', $id)
->when(! $owner && ! $manager, fn ($q) => $q->where('analyst_id', $actor->id))
->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'version']);
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.case_id', $id)->whereNull('d.deleted_at')
->when(! $owner && ! $manager, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', $requests->pluck('id'))))
->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status']);
// Only the private draft owner can receive the financial snapshot/result. Dossier access alone is insufficient.
$results = (int) $case->user_id === $actor->id ? ($path['results'] ?? []) : [];
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
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'] ?? [],
'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,
'tasks' => DB::table('tasks')->where('desk_case_id', $id)
->whereNull('deleted_at')
->when(! $owner && ! $manager, fn ($q) => $q->where('assignee_user_id', $actor->id))
->get(['id', 'title', 'status', 'version_no', 'due_at', 'assignee_user_id']),
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'definition'])
->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title']]),
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '') : null,
'desk' => '/balcao-virtual/dossiers/'.$id, 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id]];
}
/** @param array<string,mixed> $input */
public function facts(User $actor, string $id, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1',
'land_needed' => ['required', Rule::in(['yes', 'no', 'unknown'])], 'external_funding' => ['required', Rule::in(['yes', 'no', 'unknown'])],
'viability' => ['required', Rule::in(['unknown', 'proceed', 'reformulate', 'archive'])],
'reason' => 'required|string|min:3|max:3000'])->validate();
DB::transaction(function () use ($actor, $id, $data): void {
$case = $this->writable($actor, $id, $data['version']);
$payload = $this->desk->decode($case->payload);
foreach (['land_needed', 'external_funding', 'viability'] as $key) {
$payload['investor_path']['facts'][$key] = $data[$key];
$payload['investor_path']['fact_reasons'][$key] = $data['reason'];
}
$this->savePayload($case, $payload);
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_applicability_declared', $data);
});
}
/** @param array<string,mixed> $input */
public function stage(User $actor, string $id, string $code, array $input): void
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'state' => ['required', Rule::in(array_diff(InvestorPathDefinition::STATES, ['dispensed']))],
'reason' => 'required|string|min:3|max:3000', 'action' => ['required', Rule::in(['prepare', 'submit', 'execute', 'operate', 'review', 'record_external'])],
'document_id' => 'nullable|uuid', 'authority' => 'nullable|string|max:200', 'reference' => 'nullable|string|max:300',
'decision_date' => 'nullable|date_format:Y-m-d|before_or_equal:today'])->validate();
DB::transaction(function () use ($actor, $id, $code, $data): void {
$case = $this->desk->case($actor, $id, false, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão actual.');
$view = $this->view($actor, $id);
$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'];
$internal = in_array($state, ['reviewing', 'correction_required'], true);
$external = in_array($state, ['approved', 'rejected', 'expired'], true);
$scope = 'investor_preparation';
if ($internal || $external) {
abort_unless($view['canReview'], 403, 'A conferência interna exige um responsável distinto do promotor.');
abort_unless($data['action'] === ($external ? 'record_external' : 'review'), 422);
$scope = $external ? 'external_document_recorded' : 'internal_validation';
} else {
abort_unless($view['canWrite'], 403);
abort_unless(! in_array($data['action'], ['review', 'record_external'], true), 422);
if ($state === 'submitted') {
abort_unless($data['action'] === 'submit' && ! empty($data['reference']), 422, 'Registe a referência da submissão; guardar não equivale a submeter.');
}
}
if ($external || $data['action'] !== 'prepare') {
abort_unless(empty($step['action_gaps'][$data['action']] ?? []), 422,
'Dependências reais da acção: '.implode(', ', $step['action_gaps'][$data['action']] ?? []));
}
if ($external) {
abort_unless(! empty($data['document_id']) && ! empty($data['authority']) && ! empty($data['reference']) && ! empty($data['decision_date']), 422, 'Registe documento, entidade, referência e data do acto externo.');
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)
->where('d.id', $data['document_id'])->whereNull('d.deleted_at')->first(['d.status', 'd.malware_scan_status', 'd.sha256', 'd.malware_scanned_sha256']);
abort_unless($doc && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento de decisão ainda não consultável.');
}
// Completion of a legal/finance/operation action requires the corresponding evidence; preparation can proceed independently.
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()];
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()]);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_stage_recorded', ['code' => $code, ...$detail]);
});
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function returnTool(Request $request, string $id, array $input): array
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'draft_id' => 'required|uuid', 'draft_version' => 'required|integer|min:1'])->validate();
return DB::transaction(function () use ($request, $id, $data): array {
$actor = $request->user();
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
abort_unless($case->simulation_id === $data['draft_id'] && (int) $case->user_id === $actor->id, 403, 'Ferramenta pertencente a outro contexto.');
$draft = app(SimulationFormDrafts::class)->find($data['draft_id'], $request);
abort_unless($draft->version_no === $data['draft_version'], 409, 'O rascunho mudou; aguarde a gravação e volte a recuperar o resultado.');
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$snapshot = $economic['financial_tools_snapshot'] ?? null;
abort_unless(is_string($snapshot) && strlen($snapshot) <= 30000, 422, 'Guarde primeiro as entradas da ferramenta financeira.');
$parsed = json_decode($snapshot, true);
abort_unless(is_array($parsed) && ($parsed['version'] ?? null) === 1 && is_array($parsed['data'] ?? null), 422, 'Snapshot financeiro incompatível.');
$payload = $this->desk->decode($case->payload);
$resultKey = hash('sha256', $draft->id.':'.$draft->version_no.':'.$snapshot);
foreach ($payload['investor_path']['results'] ?? [] as $result) {
if ($result['source_key'] === $resultKey) {
return $result;
}
}
abort_unless((int) $case->version === $data['version'], 409, 'Recupere a versão actual do dossier.');
$result = ['id' => (string) Str::uuid(), 'source_key' => $resultKey, 'draft_id' => $draft->id, 'draft_version' => $draft->version_no,
'snapshot_sha256' => $draft->snapshot_sha256, 'financial_snapshot' => $snapshot,
'currency' => $economic['currency'] ?? null, 'engine' => 'financial-calculators:v1',
'kind' => 'local_calculation_inputs', 'recorded_at' => now()->toIso8601String()];
$payload['investor_path']['results'][] = $result;
abort_unless(count($payload['investor_path']['results']) <= 100, 422, 'Limite de evidências financeiras deste dossier atingido.');
$this->savePayload($case, $payload);
$this->desk->event($this->desk->case($actor, $id), $actor, 'tool_evidence_returned', array_diff_key($result, ['financial_snapshot' => true]));
return $result;
});
}
/** @return list<array<string,mixed>> */
public function contexts(User $actor): array
{
if (! $this->available()) {
return [];
}
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$contexts = DB::table('desk_cases as c')->join('investor_journeys as j', 'j.id', '=', 'c.journey_id')->whereNotNull('j.path_definition_id')
->whereNull('j.deleted_at')->whereNull('c.closed_at')->where(fn ($q) => $q->where(fn ($p) => $p->where('c.user_id', $actor->id)->whereNull('c.organization_id'))->orWhereIn('c.organization_id', $organizations))
->orderByDesc('c.updated_at')->get(['c.id', 'c.title', 'c.version', 'c.updated_at'])
->map(fn ($row) => ['id' => $row->id, 'title' => $row->title, 'version' => $row->version, 'updated_at' => $row->updated_at])->all();
return array_values($contexts);
}
/** @param array<string,mixed> $input */
public function task(User $actor, string $id, array $input): string
{
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'code' => ['required', Rule::in(array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19)))],
'title' => 'required|string|min:3|max:200', 'due_at' => 'required|date|after:now', 'consent' => 'accepted'])->validate();
return DB::transaction(function () use ($actor, $id, $data): string {
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
$key = 'path:'.$data['code'];
$existing = DB::table('tasks')->where('desk_case_id', $id)->where('guidance_key', $key)->first();
if ($existing) {
abort_unless($existing->title === $data['title'] && (int) $existing->accepted_by === $actor->id
&& Carbon::parse($existing->due_at)->equalTo(Carbon::parse($data['due_at'])), 409, 'A tarefa desta etapa já existe com outros dados.');
return $existing->id;
}
$this->writable($actor, $id, $data['version']);
$step = $this->findStep($this->view($actor, $id), $data['code']);
abort_unless($step !== null && $step['preparation_allowed'], 422);
$task = CrmTask::create(['desk_case_id' => $id, 'guidance_key' => $key, 'title' => $data['title'], 'due_at' => $data['due_at'],
'status' => 'open', 'assignee_user_id' => $actor->id, 'accepted_by' => $actor->id, 'accepted_at' => now(),
'external_sync_status' => 'pending_authorization', 'data_classification' => 'confidential', 'source_system' => 'investor-path']);
$this->desk->event($case, $actor, 'path_task_accepted', ['task_id' => $task->id, 'code' => $data['code'], 'scope' => 'internal_crm']);
return $task->id;
});
}
private function writable(User $actor, string $id, int $version): \stdClass
{
abort_unless($this->available(), 404);
$case = $this->desk->case($actor, $id, true, true);
abort_if($case->closed_at, 409);
abort_unless((int) $case->version === $version, 409, 'Recupere a versão actual do dossier.');
$this->view($actor, $id);
return $case;
}
/** @param array<string,mixed> $view
* @return array<string,mixed>|null
*/
private function findStep(array $view, string $code): ?array
{
if (! is_array($view['steps'] ?? null)) {
return null;
}
foreach ($view['steps'] as $step) {
if (is_array($step) && ($step['code'] ?? null) === $code) {
return $step;
}
}
return null;
}
/** @param array<string,mixed> $payload */
private function savePayload(\stdClass $case, array $payload): void
{
DB::table('desk_cases')->where('id', $case->id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version + 1, 'updated_at' => now()]);
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Services;
final class InvestorPathDefinition
{
public const STATES = ['not_started', 'preparing', 'ready_to_submit', 'submitted', 'reviewing', 'correction_required', 'waiting_external', 'approved', 'rejected', 'dispensed', 'completed', 'expired'];
/** @return array<string,mixed> */
public static function snapshot(): array
{
$titles = ['Sistematizar a ideia', 'Análise preliminar', 'Decisão sobre a viabilidade', 'Estruturar o investimento',
'Constituição e registo', 'Preparar o dossier', 'Submeter quando aplicável', 'Licenciamento prévio',
'Necessidade de terra', 'Regularização da terra', 'Confirmar regularização aplicável',
'Necessidade e estrutura de financiamento', 'Diligência e negociação financeira', 'Decisão do financiador',
'Fecho e desembolso', 'Implementação', 'Inspecções, testes e licença de operação', 'Início de operação', 'Acompanhamento recorrente'];
$steps = [];
foreach ($titles as $index => $title) {
$n = $index + 1;
$steps[] = ['code' => sprintf('S%02d', $n), 'sequence' => $n, 'title' => $title,
'phase' => $n <= 4 ? 1 : ($n <= 7 ? 2 : ($n <= 11 ? 3 : ($n <= 15 ? 4 : 5))),
'source_paragraph' => 21 + $n,
'branch' => $n === 10 ? 'land_needed' : (in_array($n, [13, 14, 15], true) ? 'external_funding' : null),
// Preparation has no dependencies. These only constrain the named consequential action.
'dependencies' => match ($n) {
7 => ['submit' => ['S06']],
15 => ['execute' => ['S14']],
18 => ['operate' => ['S17']],
default => [],
}];
}
return ['kind' => 'investor-path', 'version' => 1,
'source_sha256' => 'aa13c53138ec15cd808de43d9dc2fc6808da86943d09d3352c9dd0944bdae364',
'phases' => [1 => 'Ideia e viabilidade', 2 => 'Formalização e dossier', 3 => 'Licenciamento e terra', 4 => 'Financiamento', 5 => 'Execução e acompanhamento'],
'states' => self::STATES, 'steps' => $steps,
'legacy_roadmaps' => ['virtual-desk:E0-E11', 'investor-guidance:7-phases', 'investment-roadmap:14-activities']];
}
/** @param array<string,mixed> $definition */
public static function validate(array $definition): void
{
$steps = $definition['steps'] ?? [];
$expected = array_map(fn ($n) => sprintf('S%02d', $n), range(1, 19));
if (count($definition['phases'] ?? []) !== 5 || array_column($steps, 'code') !== $expected
|| array_column($steps, 'sequence') !== range(1, 19)) {
throw new \LogicException('The five phases and nineteen source stages must remain traceable.');
}
$edges = [];
foreach ($steps as $step) {
if (! in_array($step['phase'], range(1, 5), true)
|| ! in_array($step['branch'], [null, 'land_needed', 'external_funding'], true)) {
throw new \LogicException('Unknown phase or applicability field.');
}
$edges[$step['code']] = [];
foreach ($step['dependencies'] as $action => $dependencies) {
if (! in_array($action, ['submit', 'execute', 'operate'], true)
|| array_diff($dependencies, $expected)) {
throw new \LogicException('Unknown action/dependency; preparation cannot be blocked.');
}
$edges[$step['code']] = array_merge($edges[$step['code']], $dependencies);
}
}
$visit = function (string $code, array $trail) use (&$visit, $edges): void {
if (in_array($code, $trail, true)) {
throw new \LogicException('Cyclic action dependencies.');
}
foreach ($edges[$code] as $next) {
$visit($next, [...$trail, $code]);
}
};
foreach ($expected as $code) {
$visit($code, []);
}
}
}
+26 -8
View File
@@ -18,6 +18,17 @@ class OpportunityManagement
public const FIELDS = ['title', 'summary', 'description', 'sector_id', 'promoter_name', 'promoter_type', 'maturity_level', 'maturity_label', 'financing_modality', 'expected_impact', 'estimated_investment_amount', 'estimated_investment_currency', 'opportunity_category', 'primary_territory_id', 'province', 'district', 'geography_scope'];
public const MATURITY_FIELDS = ['maturity_level', 'maturity_label', 'maturity_stage', 'maturity_catalogue_version'];
/** @return array<string,mixed> */
public function values(Opportunity $record): array
{
$base = $record->only(self::FIELDS);
$draft = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::MATURITY_FIELDS)))];
}
public function installed(): bool
{
return Schema::hasColumn('opportunities', 'management_version');
@@ -44,7 +55,9 @@ class OpportunityManagement
'title' => ['nullable', 'string', 'max:150'], 'summary' => ['nullable', 'string', 'max:500'],
'description' => ['nullable', 'string', 'max:50000'], 'promoter_name' => ['nullable', 'string', 'max:200'],
'promoter_type' => ['nullable', Rule::in(['public', 'private', 'ppp', 'cooperative', 'association', 'community', 'other', $id ? Opportunity::withTrashed()->findOrFail($id)->promoter_type : null])],
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
'maturity_level' => ['nullable', 'integer', 'between:1,8'],
'maturity_stage' => ['nullable', Rule::in(array_keys(OpportunityMaturity::STAGES))],
'maturity_catalogue_version' => ['nullable', Rule::in([OpportunityMaturity::VERSION, OpportunityMaturity::LEGACY])],
'financing_modality' => ['nullable', 'string', 'max:120'],
'expected_impact' => ['nullable', 'string', 'max:10000'],
'sector_id' => ['nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
@@ -54,12 +67,13 @@ class OpportunityManagement
'reason' => ['required', 'string', 'min:20', 'max:1000'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
])->validate();
$data = app(OpportunityMaturity::class)->normalize($data);
return DB::transaction(function () use ($actor, $data, $id) {
DB::select('SELECT pg_advisory_xact_lock(91026, 100000)');
if (! $id && ($existing = Opportunity::withTrashed()->where('management_creation_key', $data['creation_key'])->first())) {
$snapshot = $existing->management_draft ? json_decode($existing->management_draft, true) : $existing->only(self::FIELDS);
foreach (array_intersect_key($data, array_flip(self::FIELDS)) as $key => $value) {
$snapshot = $this->values($existing);
foreach (array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS])) as $key => $value) {
if (($snapshot[$key] ?? null) != $value) {
throw ValidationException::withMessages(['creation_key' => 'Esta chave já foi utilizada com dados diferentes.']);
}
@@ -73,11 +87,7 @@ class OpportunityManagement
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
}
$before = $record->getAttributes();
$changes = array_intersect_key($data, array_flip(self::FIELDS));
if (array_key_exists('maturity_level', $changes)) {
$labels = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
$changes['maturity_label'] = $labels[$changes['maturity_level'] ?? 0] ?? null;
}
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::MATURITY_FIELDS]));
if (array_intersect_key($data, InvestmentGeography::FIELDS) !== []) {
$path = app(InvestmentGeography::class)->selection($data, true);
$changes['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
@@ -101,8 +111,16 @@ class OpportunityManagement
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
} else {
foreach ($changes as $key => $value) {
if (in_array($key, ['maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
continue;
}
$record->{$key} = $value;
}
if (isset($changes['maturity_catalogue_version'])) {
// The existing draft JSON holds the versioned catalogue; legacy columns stay intact.
$previous = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::MATURITY_FIELDS))], JSON_THROW_ON_ERROR);
}
}
$record->save();
$this->audit($record, $actor, $before, $id ? 'draft_updated' : 'draft_created', $data['reason']);
@@ -14,6 +14,8 @@ class OpportunityManagementInstallation
{
$files = [__FILE__, app_path('Models/Opportunity.php'), app_path('Services/OpportunityManagement.php'), app_path('Http/Controllers/OpportunityManagementController.php'), app_path('Http/Controllers/PortalManagementController.php'), database_path('migrations/'.self::MIGRATION.'.php'), base_path('routes/web.php'), resource_path('js/pages/management/opportunity-draft.tsx'), resource_path('js/pages/management/opportunities.tsx')];
$files[] = app_path('Services/OpportunityMaturity.php');
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Services;
use Illuminate\Validation\ValidationException;
/** Catalogue versions are not interchangeable: historical positions keep their meaning. */
final class OpportunityMaturity
{
public const VERSION = 'spec-v2';
public const LEGACY = 'legacy-v1';
public const STAGES = [
'idea' => 'Ideia',
'concept' => 'Conceito',
'prefeasibility' => 'Pré-viabilidade',
'feasibility' => 'Viabilidade',
'structured' => 'Estruturado',
'investment_ready' => 'Pronto para investimento',
'implementation' => 'Implementação',
'operational' => 'Operacional',
];
public const LEGACY_LABELS = [1 => 'Ideia identificada', 'Pré-estudo disponível', 'Estudo de viabilidade em curso', 'Projecto estruturado', 'Pronto para investimento', 'Em negociação ou implementação'];
/** @param array<string,mixed> $data
* @return array<string,mixed> */
public function normalize(array $data): array
{
if (! array_key_exists('maturity_level', $data) && ! array_key_exists('maturity_stage', $data)) {
if (isset($data['maturity_catalogue_version'])) {
throw ValidationException::withMessages(['maturity_catalogue_version' => 'Seleccione também a etapa; mudar só a versão não converte o valor histórico.']);
}
unset($data['maturity_catalogue_version']);
return $data;
}
$level = isset($data['maturity_level']) ? (int) $data['maturity_level'] : null;
$version = $data['maturity_catalogue_version'] ?? ((isset($data['maturity_stage']) || ($level ?? 0) > 6) ? self::VERSION : self::LEGACY);
if ($version === self::LEGACY) {
if (($level ?? 0) > 6 || isset($data['maturity_stage'])) {
throw ValidationException::withMessages(['maturity_level' => 'O catálogo histórico tem seis níveis; seleccione explicitamente o catálogo de oito etapas.']);
}
return [...$data, 'maturity_catalogue_version' => self::LEGACY, 'maturity_stage' => null, 'maturity_label' => self::LEGACY_LABELS[$level ?? 0] ?? null];
}
$codes = array_keys(self::STAGES);
$stage = $data['maturity_stage'] ?? ($level !== null ? $codes[$level - 1] : null);
if ($stage !== null && $level !== null && $codes[$level - 1] !== $stage) {
throw ValidationException::withMessages(['maturity_stage' => 'O código da etapa e a posição no catálogo não correspondem.']);
}
return [...$data, 'maturity_catalogue_version' => self::VERSION, 'maturity_stage' => $stage,
'maturity_level' => $stage !== null ? array_search($stage, $codes, true) + 1 : null,
'maturity_label' => $stage !== null ? self::STAGES[$stage] : null];
}
}
@@ -16,6 +16,20 @@ class OpportunityResourceInstallation
$files = [...$files, app_path('Services/CountryCatalogue.php'), app_path('Services/DeclaredOriginStatistics.php'), app_path('Services/VirtualDesk.php'), app_path('Http/Controllers/CrmController.php'), app_path('Http/Controllers/InvestmentWorkspaceController.php'), app_path('Http/Controllers/InvestmentSubmissionController.php'), app_path('Http/Controllers/InvestmentDiscoveryController.php'), app_path('Http/Controllers/VirtualDeskController.php'), resource_path('data/iso3166.tab'), resource_path('js/components/country-select.tsx'), resource_path('js/components/investment-territory.tsx'), resource_path('js/pages/investment/profile.tsx'), resource_path('js/pages/investment/submission.tsx'), resource_path('js/pages/investment/catalogue.tsx'), resource_path('js/pages/desk/request.tsx'), resource_path('js/pages/desk/panel.tsx'), resource_path('js/pages/crm/leads.tsx')];
$files = [...$files, app_path('Http/Controllers/PortalServicesController.php'), app_path('Http/Controllers/PublicPortalController.php'), app_path('Http/Controllers/InvestorWorkspaceController.php'), app_path('Http/Controllers/PublicBusinessOpportunityController.php'), app_path('Http/Controllers/Api/V1/InterestRequestController.php'), app_path('Http/Requests/StoreInterestRequestRequest.php'), resource_path('js/pages/portal/services.tsx'), resource_path('js/pages/PortalInvestidor.tsx'), resource_path('js/pages/portfolio/workspace.tsx'), resource_path('js/pages/investment/business-interest.tsx'), resource_path('js/lib/portal-api.ts')];
$files = [...$files, app_path('Http/Controllers/PortalManagementController.php'), resource_path('js/pages/management/interest.tsx')];
$files = [...$files, app_path('Http/Controllers/Api/V1/ReferenceCatalogController.php'), base_path('routes/api.php'), resource_path('js/components/simulation-form.tsx')];
$files[] = app_path('Http/Requests/StoreSimulationFormDraftRequest.php');
$files = [...$files, app_path('Services/TerritoryGeometry.php'), app_path('Http/Controllers/InvestmentTerritoryController.php'), resource_path('js/components/territory-geometry-preview.tsx'), resource_path('js/components/interactive-investment-map.tsx'), resource_path('js/components/investment-map-panel.tsx')];
$files = [...$files, app_path('Services/OpportunityManagement.php'), app_path('Services/OpportunityMaturity.php'), app_path('Services/BusinessFormSchema.php'), app_path('Http/Controllers/ExistingBusinessController.php'), app_path('Http/Controllers/LandAssistanceController.php'), app_path('Http/Requests/StoreLandAssistanceCaseRequest.php'), resource_path('js/pages/investment/business-wizard.tsx'), resource_path('js/pages/investment/businesses.tsx'), resource_path('js/pages/investment/business.tsx'), resource_path('js/pages/land-assistance/form.tsx'), resource_path('js/pages/management/interests.tsx')];
$files = [...$files, app_path('Services/ExistingBusinessIntake.php'), resource_path('js/pages/land-assistance/case.tsx')];
$files = [...$files, resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx')];
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
}
@@ -29,7 +43,7 @@ class OpportunityResourceInstallation
$ready = ($proof['restore_verified'] ?? false) && ($proof['compatibility_verified'] ?? false) && ($proof['reversal_verified'] ?? false) && ($proof['qa_passed'] ?? false) && ($proof['code_hash'] ?? '') === $code && ($proof['target']['database'] ?? '') === $identity->database && (int) ($proof['target']['port'] ?? 0) === (int) $identity->port && strtotime($proof['verified_at'] ?? '') >= time() - 86400 && is_file($proof['dump_path'] ?? '') && hash_file('sha256', $proof['dump_path']) === ($proof['sha256'] ?? null);
$installed = app(OpportunityResources::class)->installed();
return ['installed' => $installed, 'ready' => $ready, 'target' => $identity, 'code_hash' => $code, 'hash' => hash('sha256', json_encode([$identity, $code, $ready, $installed], JSON_THROW_ON_ERROR)), 'migration' => self::MIGRATION, 'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Recursos privados de preparação ligados às oportunidades existentes, documents e geo_locations; nenhum dado existente alterado.', 'Originais cifrados; scan pendente bloqueia acesso aos binários, não preparação de metadados/localizações.', 'Versões, exclusão lógica e restauro com auditoria; nenhuma publicação automática.', 'Pendentes: ClamD real, derivadas seguras/revisão/publicação e compatibilidade com limites oficiais onde ausentes.'], 'rollback' => 'Reversão apenas com tabelas vazias e sem documentos cifrados; após utilização, preservar e reconciliar versões antes de uma ação autorizada.'];
return ['installed' => $installed, 'ready' => $ready, 'target' => $identity, 'code_hash' => $code, 'hash' => hash('sha256', json_encode([$identity, $code, $ready, $installed], JSON_THROW_ON_ERROR)), 'migration' => self::MIGRATION, 'backupDate' => $proof['verified_at'] ?? null, 'changes' => ['Recursos privados de preparação ligados às oportunidades existentes, documents e geo_locations; nenhum dado existente alterado.', 'Originais cifrados; scan pendente bloqueia acesso aos binários, não preparação de metadados/localizações.', 'Versões, exclusão lógica e restauro com auditoria; nenhuma publicação automática.', 'Scan de cada original/derivada, disponibilidade GD/WebP, revisão de divulgação e compatibilidade territorial têm critérios independentes; a instalação não os confirma. Consultar os estados por ficheiro e as evidências QA da revisão.'], 'rollback' => 'Reversão apenas com tabelas vazias e sem documentos cifrados; após utilização, preservar e reconciliar versões antes de uma ação autorizada.'];
}
public function apply(User $actor, string $hash): void
+60 -7
View File
@@ -23,13 +23,18 @@ final class SimulationFormDrafts
public function create(array $data, Request $request, string $key): array
{
[$actorId, $tokenHash] = $this->context($request);
$caseId = $request->input('context');
if ($caseId !== null) {
abort_unless(config('investor-path.enabled') && is_string($caseId) && Str::isUuid($caseId), 422, 'Contexto de investimento indisponível.');
abort_unless($request->user()?->hasVerifiedEmail(), 403);
}
$data = SimulationFormDraftPrivacyPolicy::apply($data, $actorId !== null);
$scope = $actorId === null ? 'anonymous:'.$tokenHash : 'user:'.$actorId;
$scope = ($actorId === null ? 'anonymous:'.$tokenHash : 'user:'.$actorId).($caseId ? ':case:'.$caseId : '');
$keyHash = hash_hmac('sha256', strtolower($key), (string) config('app.key'));
$canonicalPayload = json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
$payloadHash = hash('sha256', $canonicalPayload);
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $data): array {
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $data, $caseId, $request): array {
$this->setContext($actorId, $tokenHash);
DB::select('select pg_advisory_xact_lock(261010, hashtext(?))', [$scope]);
@@ -39,7 +44,13 @@ final class SimulationFormDrafts
->update(['deleted_at' => now()]);
}
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->first();
$case = $caseId ? app(VirtualDesk::class)->case($request->user(), $caseId, true, true) : null;
// Shared case access never grants ownership of a private simulator snapshot.
abort_if($case && ((int) $case->user_id !== $actorId || $case->closed_at), 403);
$query = $this->ownedQuery($actorId, $tokenHash);
$draft = $case
? ($case->simulation_id ? $query->whereKey($case->simulation_id)->lockForUpdate()->firstOrFail() : null)
: $this->unscoped($query, $actorId)->lockForUpdate()->first();
if ($draft) {
if (hash_equals($draft->create_key_hash, $keyHash)) {
abort_unless(hash_equals($draft->create_payload_hash, $payloadHash), 409, 'Idempotency-Key já foi utilizada com outros dados.');
@@ -57,6 +68,11 @@ final class SimulationFormDrafts
'expires_at' => $actorId === null ? now()->addDays(30) : null,
]);
if ($case) {
DB::table('desk_cases')->where('id', $case->id)->update(['simulation_id' => $draft->id, 'version' => $case->version + 1, 'updated_at' => now()]);
app(VirtualDesk::class)->event(app(VirtualDesk::class)->case($request->user(), $case->id), $request->user(), 'context_draft_created', ['draft_id' => $draft->id]);
}
return ['draft' => $draft, 'replayed' => false];
}, 3);
}
@@ -70,6 +86,7 @@ final class SimulationFormDrafts
return DB::transaction(function () use ($id, $data, $request, $actorId, $tokenHash): SimulationFormDraft {
$this->setContext($actorId, $tokenHash);
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
$this->checkContext($request, $draft);
$this->requireMatch($request, $draft);
$previousEconomic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
if (($data['economic_snapshot']['reuse_simulation'] ?? null) === 'no') {
@@ -162,10 +179,19 @@ final class SimulationFormDrafts
{
[$actorId, $tokenHash] = $this->context($request);
return DB::transaction(function () use ($actorId, $tokenHash): ?SimulationFormDraft {
return DB::transaction(function () use ($actorId, $tokenHash, $request): ?SimulationFormDraft {
$this->setContext($actorId, $tokenHash);
$query = $this->ownedQuery($actorId, $tokenHash);
if ($request->query('context') !== null) {
$id = $request->query('context');
abort_unless(config('investor-path.enabled') && $request->user()?->hasVerifiedEmail() && is_string($id) && Str::isUuid($id), 403);
$case = app(VirtualDesk::class)->case($request->user(), $id, true);
abort_unless((int) $case->user_id === $actorId, 403);
return $this->ownedQuery($actorId, $tokenHash)->orderByDesc('updated_at')->first();
return $case->simulation_id ? $query->whereKey($case->simulation_id)->firstOrFail() : null;
}
return $this->unscoped($query, $actorId)->orderByDesc('updated_at')->first();
});
}
@@ -327,10 +353,12 @@ final class SimulationFormDrafts
{
[$actorId, $tokenHash] = $this->context($request);
return DB::transaction(function () use ($id, $actorId, $tokenHash): SimulationFormDraft {
return DB::transaction(function () use ($id, $actorId, $tokenHash, $request): SimulationFormDraft {
$this->setContext($actorId, $tokenHash);
$draft = $this->ownedQuery($actorId, $tokenHash)->findOrFail($id);
$this->checkContext($request, $draft);
return $this->ownedQuery($actorId, $tokenHash)->findOrFail($id);
return $draft;
});
}
@@ -414,6 +442,31 @@ final class SimulationFormDrafts
: $query->where('owner_user_id', $actorId)->whereNull('anonymous_token_hash');
}
/** @param Builder<SimulationFormDraft> $query
* @return Builder<SimulationFormDraft>
*/
private function unscoped(Builder $query, ?int $actorId): Builder
{
if ($actorId !== null && config('investor-path.enabled') && app(VirtualDesk::class)->installed()) {
// The direct tool has its own current draft; context drafts are opened explicitly by ID/context.
$query->whereNotExists(fn ($q) => $q->selectRaw('1')->from('desk_cases')
->whereColumn('desk_cases.simulation_id', 'simulation_form_drafts.id'));
}
return $query;
}
private function checkContext(Request $request, SimulationFormDraft $draft): void
{
$context = $request->input('context');
if ($context === null) {
return;
}
abort_unless(config('investor-path.enabled') && $request->user()?->hasVerifiedEmail() && is_string($context) && Str::isUuid($context), 403);
$case = app(VirtualDesk::class)->case($request->user(), $context, true);
abort_unless((int) $case->user_id === $request->user()->id && $case->simulation_id === $draft->id, 403, 'Rascunho pertencente a outro contexto.');
}
/** @return array{id:string,title:string,updated_at:string|null,expires_at:string|null,version_no:int} */
private function summary(SimulationFormDraft $draft): array
{
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
/** Administrative context is never an investment site or a zone perimeter. */
final class TerritoryGeometry
{
/** @return array<string,mixed> */
public function context(string $id, bool $management = false): array
{
$geography = app(InvestmentGeography::class);
abort_unless($geography->references($management)->where('id', $id)->exists(), 404);
$path = $geography->path($id, $management);
$ids = array_map(fn ($node) => $node->id, $path);
$rows = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id')
->whereIn('g.geo_location_id', $ids)->whereNull('g.deleted_at')->whereNull('l.deleted_at')
->whereIn('g.data_classification', $management ? ['internal', 'public'] : ['public'])
->whereRaw("g.properties->>'purpose' = 'administrative_boundary'")
->whereIn('g.geometry_type', ['polygon', 'multipolygon'])
->whereRaw('ST_IsValid(g.geom) AND NOT ST_IsEmpty(g.geom) AND ST_SRID(g.geom)=4326')
->orderBy('g.geo_location_id')->orderBy('g.id')->limit(101)
->get(['g.id', 'g.geo_location_id', 'l.name', 'l.location_type', 'g.properties', 'g.data_classification',
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry')]);
$areas = $rows->take(100)->map(function ($row) use ($id) {
$source = json_decode($row->properties, true, 512, JSON_THROW_ON_ERROR);
return ['id' => $row->id, 'territory_id' => $row->geo_location_id, 'location_type' => $row->location_type,
'selected_territory' => $row->geo_location_id === $id, 'geometry' => json_decode($row->geometry, true, 512, JSON_THROW_ON_ERROR),
'title' => 'Limite administrativo: '.$row->name, 'purpose' => 'administrative_boundary',
'source_reference' => $source['authority'] ?? null, 'source_date' => $source['source_version'] ?? null,
'source_url' => $source['source_url'] ?? null, 'source_sha256' => $source['source_sha256'] ?? null,
'data_classification' => $row->data_classification, 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
})->all();
return ['territory_id' => $id, 'territory_registered' => true,
'selected_geometry_available' => $rows->contains('geo_location_id', $id), 'context_geometry_count' => count($areas),
'areas' => $areas, 'truncated' => $rows->count() > 100, 'investment_site' => false];
}
}
+214
View File
@@ -0,0 +1,214 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/** Imports only the retained, accepted INE edition. Publication is a separate action. */
class TerritoryGeometryImport
{
public function fingerprint(): string
{
return hash('sha256', implode('', array_map(fn ($f) => hash_file('sha256', $f), [__FILE__, config_path('geometry-import.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), base_path('routes/web.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')])));
}
private function guard(User $actor, bool $write = false): void
{
abort_unless($actor->can('manage-portal'), 403);
abort_unless(config('geometry-import.enabled'), 503, 'Importação cartográfica não disponibilizada.');
if (! $write) {
return;
}
abort_unless($actor->two_factor_confirmed_at && $actor->two_factor_secret, 403, 'Confirme a autenticação de dois factores para aplicar ou reverter cartografia.');
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$qa = app()->environment('testing') && str_ends_with($target->database, '_test') && (int) $target->port === 55441 && config('database.connections.pgsql.host') === '127.0.0.1';
if ($qa) {
return;
}
$file = storage_path('app/private/investmoz-v2/geometry-import-activation-proof.json');
$p = is_file($file) ? json_decode(file_get_contents($file), true) : [];
abort_unless(($p['restore_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['ui_passed'] ?? false)
&& ($p['code_hash'] ?? '') === $this->fingerprint() && ($p['target']['database'] ?? '') === $target->database
&& (int) ($p['target']['port'] ?? 0) === (int) $target->port && strtotime($p['verified_at'] ?? '') >= time() - 86400
&& is_file($p['dump_path'] ?? '') && hash_file('sha256', $p['dump_path']) === ($p['sha256'] ?? null)
&& ($p['files_verified'] ?? false) && is_file($p['files_path'] ?? '') && hash_file('sha256', $p['files_path']) === ($p['files_sha256'] ?? null), 422, 'Backup/restauro e provas desta revisão e alvo necessários; preparação não autoriza ativação.');
}
public function preview(User $actor, int $level): array
{
$this->guard($actor);
abort_unless(in_array($level, [1, 2, 3], true), 422);
$directory = config('geometry-import.directory');
$file = $directory.'/moz-adm'.$level.'-ine-20190607.geojson';
$metadata = $directory.'/moz-adm'.$level.'-ine-metadata.html';
abort_unless(is_file($file) && is_file($metadata), 422, 'Exemplar privado indisponível.');
$text = file_get_contents($metadata);
abort_unless(str_contains($text, 'Mozambique INE - Instituto Nacional de Estatistica') && str_contains($text, '2019-06-07'), 422, 'Metadados do exemplar divergentes.');
$sourceHash = hash_file('sha256', $file);
$source = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
abort_unless(($source['type'] ?? '') === 'FeatureCollection' && count($source['features'] ?? []) === [1 => 11, 2 => 159, 3 => 411][$level] && ! ($source['exceededTransferLimit'] ?? false), 422, 'Exemplar incompleto.');
$locations = DB::table('geo_locations')->where('location_type', [1 => 'province', 2 => 'district', 3 => 'admin_post'][$level])->whereNull('deleted_at')->get(['id', 'name', 'parent_id']);
$normalize = fn ($n) => strtolower(trim(Str::ascii($n)));
$countryNames = array_map($normalize, [$source['features'][0]['properties']['ADM0_PT'], $source['features'][0]['properties']['ADM0_EN']]);
$countries = DB::table('geo_locations')->where('location_type', 'country')->whereNull('deleted_at')->get(['id', 'name'])->filter(fn ($c) => in_array($normalize($c->name), $countryNames, true))->values();
$countryId = count($countries) === 1 ? $countries[0]->id : null;
$parentSourceHash = $level > 1 ? hash_file('sha256', $directory.'/moz-adm'.($level - 1).'-ine-20190607.geojson') : null;
$rows = [];
foreach ($source['features'] as $feature) {
$p = $feature['properties'];
abort_unless(($p['ADM0_PCODE'] ?? '') === 'MZ', 422, 'Âmbito territorial do exemplar divergente.');
$external = '2019-06-07:adm'.$level.':'.$p['ADM'.$level.'_PCODE'];
$parent = $level > 1 ? DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->where('external_id', '2019-06-07:adm'.($level - 1).':'.$p['ADM'.($level - 1).'_PCODE'])->where('properties->source_sha256', $parentSourceHash)->whereNull('deleted_at')->value('geo_location_id') : $countryId;
$matches = $locations->filter(fn ($l) => $normalize($l->name) === $normalize($p['ADM'.$level.'_PT']) && $parent && $l->parent_id === $parent)->values();
$row = ['external_id' => $external, 'name' => $p['ADM'.$level.'_PT'], 'parent_name' => $level > 1 ? $p['ADM'.($level - 1).'_PT'] : null,
'parent_code' => $level > 1 ? $p['ADM'.($level - 1).'_PCODE'] : null, 'candidates' => $matches->all(), 'location_id' => count($matches) === 1 ? $matches[0]->id : null,
'status' => count($matches) === 1 ? 'insert' : (! $parent ? 'parent_unresolved' : 'name_unresolved')];
if ($row['location_id']) {
$geometry = json_encode($feature['geometry'], JSON_THROW_ON_ERROR);
$valid = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_NDims(g)=2 AND GeometryType(g) IN (\'POLYGON\',\'MULTIPOLYGON\') AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) q', [$geometry]);
if (! $valid->valid) {
$row['status'] = 'invalid_geometry';
} else {
$existing = DB::table('geo_geometries')->where('source_system', 'ine-cod-ab')->where('external_id', $external)->first();
if ($existing) {
$props = json_decode($existing->properties, true);
$same = DB::selectOne('SELECT ST_Equals(geom,ST_SetSRID(ST_GeomFromGeoJSON(?),4326)) AS same FROM geo_geometries WHERE id=?', [$geometry, $existing->id])->same;
$row['status'] = $same && $existing->geo_location_id === $row['location_id'] && ($props['source_sha256'] ?? null) === $sourceHash && ! $existing->deleted_at ? 'reuse' : 'identity_conflict';
$row['geometry_id'] = $existing->id;
$row['version'] = $existing->version_no;
$row['classification'] = $existing->data_classification;
} elseif (DB::table('geo_geometries')->where('geo_location_id', $row['location_id'])->where('geometry_type', strtolower($feature['geometry']['type']))->whereNull('deleted_at')->exists()) {
$row['status'] = 'territory_geometry_conflict';
}
}
}
$rows[] = $row;
}
$scanFile = $directory.'/geometry-source-scans.json';
$scans = is_file($scanFile) ? json_decode(file_get_contents($scanFile), true) : [];
$scan = null;
foreach ($scans['files'] ?? [] as $s) {
if ($s['file'] === basename($file) && $s['sha256'] === $sourceHash) {
$scan = ($s['scan']['result'] ?? '') === 'clean' ? $s['scan'] : ($s['gis_scan'] ?? null);
}
}
$scanReady = ($scan['result'] ?? '') === 'clean' && ($scan['engine'] ?? '') === 'ClamAV' && strtotime($scans['captured_at'] ?? '') >= time() - config('geometry-import.scan_max_age_seconds');
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$plan = ['level' => $level, 'target' => $target, 'edition' => '2019-06-07', 'source_sha256' => $sourceHash, 'metadata_sha256' => hash_file('sha256', $metadata), 'code_hash' => $this->fingerprint(),
'expected' => count($rows), 'resolved' => count(array_filter($rows, fn ($r) => in_array($r['status'], ['insert', 'reuse'], true))), 'rows' => $rows, 'scan_ready' => $scanReady, 'scan' => $scan, 'scan_at' => $scans['captured_at'] ?? null, 'published' => false];
$plan['pending'] = $plan['expected'] - $plan['resolved'];
$plan['hash'] = hash_hmac('sha256', json_encode([$actor->id, $plan], JSON_THROW_ON_ERROR), config('app.key'));
return $plan;
}
public function apply(User $actor, array $input): array
{
$this->guard($actor, true);
$data = Validator::make($input, ['level' => 'required|integer|in:1,2,3', 'hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
return $this->receipt($actor, 'geometry-import-apply', $data, function () use ($actor, $data) {
$plan = $this->preview($actor, (int) $data['level']);
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Correspondências, fonte ou estado alterados; repita a pré-visualização.');
abort_unless($plan['scan_ready'], 423, 'Scan limpo atual ligado ao original necessário.');
abort_if(count(array_filter($plan['rows'], fn ($r) => str_contains($r['status'], 'conflict') || $r['status'] === 'invalid_geometry')) > 0, 409, 'Conflito de identidade/geometria: nenhuma escrita aplicada.');
$bytes = file_get_contents(config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-20190607.geojson');
abort_unless(hash('sha256', $bytes) === $plan['source_sha256'], 409);
$source = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
$metadata = config('geometry-import.directory').'/moz-adm'.$data['level'].'-ine-metadata.html';
$metadataScan = app(MalwareScanner::class)->scan($metadata, filesize($metadata), storage_path('app/private'));
abort_unless(($metadataScan['result'] ?? '') === 'clean', 423, 'Scan dos metadados do exemplar pendente ou inconclusivo.');
abort_unless(hash_file('sha256', $metadata) === $plan['metadata_sha256'], 409, 'Metadados alterados durante o scan.');
$metadataScan['signatures_at'] = $metadataScan['signatures_at']?->format(DATE_ATOM);
$batch = (string) Str::uuid();
$created = [];
$reused = [];
foreach ($plan['rows'] as $i => $row) {
if ($row['status'] === 'reuse') {
$reused[] = $row['geometry_id'];
}
if ($row['status'] !== 'insert') {
continue;
}
$feature = $source['features'][$i];
$id = (string) Str::uuid();
$trace = ['authority' => 'Mozambique INE - Instituto Nacional de Estatistica', 'provider' => 'UNOCHA; exemplar hosted by World Bank', 'source_version' => $plan['edition'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'source_url' => 'https://services.arcgis.com/iQ1dY19aHwbSDYIF/arcgis/rest/services/Mozambique/FeatureServer/'.($data['level'] + 2), 'source_properties' => $feature['properties'], 'source_scan' => $plan['scan'], 'batch_id' => $batch, 'purpose' => 'administrative_boundary', 'investment_site' => false, 'legal_currentness' => 'not_determined', 'match_basis' => 'unique_exact_name_and_matched_parent_after_case_and_diacritics'];
DB::insert('INSERT INTO geo_geometries(id,source_system,external_id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,?,?,?,ST_SetSRID(ST_GeomFromGeoJSON(?),4326),?::jsonb,?)', [$id, 'ine-cod-ab', $row['external_id'], $row['location_id'], strtolower($feature['geometry']['type']), json_encode($feature['geometry'], JSON_THROW_ON_ERROR), json_encode($trace, JSON_THROW_ON_ERROR), 'internal']);
$created[] = ['id' => $id, 'checksum' => $this->snapshotHash($id)];
}
$result = ['batch_id' => $batch, 'level' => $data['level'], 'preview_hash' => $plan['hash'], 'expected' => $plan['expected'], 'resolved' => $plan['resolved'], 'created' => $created, 'inserted' => count($created), 'reused' => count($reused), 'reused_ids' => $reused, 'pending' => $plan['pending'], 'source_sha256' => $plan['source_sha256'], 'metadata_sha256' => $plan['metadata_sha256'], 'metadata_scan' => $metadataScan, 'published' => false, 'reason' => $data['reason']];
$this->audit($actor, $batch, 'geometry_import_applied', $result);
return $result;
});
}
public function reverse(User $actor, string $batch, array $input): array
{
$this->guard($actor, true);
$data = Validator::make([...$input, 'batch_id' => $batch], ['batch_id' => 'required|uuid', 'idempotency_key' => 'required|uuid', 'reason' => 'required|string|min:20|max:1000', 'confirm' => 'required|accepted'])->validate();
return $this->receipt($actor, 'geometry-import-reverse', $data, function () use ($actor, $data, $batch) {
$event = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_applied')->first();
abort_unless($event, 404);
$old = DB::table('audit_events')->where('source_system', 'geometry-import')->where('entity_id', $batch)->where('action', 'geometry_import_reversed')->first();
if ($old) {
return json_decode($old->after_data, true);
}
$manifest = json_decode($event->after_data, true);
foreach ($manifest['created'] as $row) {
DB::table('geo_geometries')->where('id', $row['id'])->lockForUpdate()->first();
abort_unless($this->snapshotHash($row['id']) === $row['checksum'], 409, 'Geometria alterada ou publicada; reversão recusada.');
// Enumerate all real FKs, rather than assuming one consumer table.
$references = DB::select("SELECT n.nspname AS schema,t.relname AS table_name,a.attname AS column_name FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace n ON n.oid=t.relnamespace JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=c.conkey[1] WHERE c.contype='f' AND c.confrelid='geo_geometries'::regclass");
foreach ($references as $ref) {
abort_if(DB::table($ref->schema.'.'.$ref->table_name)->where($ref->column_name, $row['id'])->exists(), 409, 'Geometria associada a um consumidor; preserve a relação.');
}
}
foreach ($manifest['created'] as $row) {
DB::table('geo_geometries')->where('id', $row['id'])->update(['deleted_at' => now(), 'updated_at' => now(), 'version_no' => DB::raw('version_no+1')]);
}
$result = ['batch_id' => $batch, 'reversed' => count($manifest['created']), 'reused_preserved' => $manifest['reused'], 'published' => false, 'reason' => $data['reason']];
$this->audit($actor, $batch, 'geometry_import_reversed', $result);
return $result;
});
}
private function snapshotHash(string $id): string
{
$r = DB::selectOne('SELECT row_to_json(q)::text AS value FROM (SELECT *,encode(ST_AsEWKB(geom),\'hex\') AS binary_geometry FROM geo_geometries WHERE id=?) q', [$id]);
return hash('sha256', $r->value ?? 'missing');
}
private function receipt(User $actor, string $scope, array $data, callable $operation): array
{
return DB::transaction(function () use ($actor, $scope, $data, $operation) {
DB::select('SELECT pg_advisory_xact_lock(91026,20190607)');
DB::select('SELECT pg_advisory_xact_lock(280926,150000)');
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$receipt = DB::table('geo_write_receipts')->where('actor_id', $actor->id)->where('scope', $scope)->where('idempotency_key', $data['idempotency_key'])->first();
if ($receipt) {
abort_unless(hash_equals(trim($receipt->request_hash), $hash), 409, 'Chave reutilizada com outro pedido.');
return json_decode($receipt->response, true);
}
$result = $operation();
DB::table('geo_write_receipts')->insert(['id' => (string) Str::uuid(), 'actor_id' => $actor->id, 'scope' => $scope, 'idempotency_key' => $data['idempotency_key'], 'request_hash' => $hash, 'response' => json_encode($result, JSON_THROW_ON_ERROR), 'http_status' => 200]);
return $result;
});
}
private function audit(User $actor, string $batch, string $action, array $data): void
{
DB::table('audit_events')->insert(['source_system' => 'geometry-import', 'entity_type' => 'geo_geometries', 'entity_id' => $batch, 'correlation_id' => $batch, 'actor_user_id' => $actor->id, 'action' => $action, 'after_data' => json_encode($data, JSON_THROW_ON_ERROR), 'data_classification' => 'internal']);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Services;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\HeaderUtils;
/** Authorization/publication stays with the consumer; originals share integrity and cipher handling. */
class VerifiedDocumentBinary
{
public function respond(object $document, bool $inline = false): Response|BinaryFileResponse
{
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean'
&& ($document->deleted_at ?? null) === null && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
$disk = Storage::disk('local');
$root = realpath($disk->path(''));
$path = realpath($disk->path($document->storage_key));
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
$headers = ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store'];
if ($inline) {
$headers['Content-Type'] = $document->media_type;
$headers['Content-Security-Policy'] = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
}
if (($document->storage_encryption ?? null) === 'laravel') {
try {
$bytes = Crypt::decryptString($disk->get($document->storage_key));
} catch (DecryptException) {
abort(404);
}
abort_unless(hash_equals(trim($document->sha256), hash('sha256', $bytes)), 404);
$headers['Content-Type'] = $document->media_type;
$headers['Content-Disposition'] = HeaderUtils::makeDisposition($inline ? 'inline' : 'attachment', basename($document->file_name), 'document');
return response($bytes, 200, $headers);
}
abort_unless(($document->storage_encryption ?? null) === null, 404);
$checksum = hash_file('sha256', $path);
abort_unless(is_string($checksum) && hash_equals(trim($document->sha256), $checksum), 404);
return $inline ? response()->file($path, $headers)->setContentDisposition('inline', basename($document->file_name)) : response()->download($path, basename($document->file_name), $headers);
}
}
+20 -3
View File
@@ -5,7 +5,9 @@ namespace App\Services;
use App\Models\InvestmentSubmission;
use App\Models\Investor;
use App\Models\InvestorJourney;
use App\Models\SimulationFormDraft;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
@@ -186,6 +188,14 @@ class VirtualDesk
$id = (string) Str::uuid();
$base = $this->decode($case->payload);
$payload = ['title' => $case->title, 'description' => $base['investment']['objective'] ?? '', 'regime' => 'unknown'];
if (config('investor-path.enabled') && $case->simulation_id && (int) $case->user_id === $actor->id) {
$draftRequest = Request::create('/');
$draftRequest->setUserResolver(fn () => $actor);
$draft = app(SimulationFormDrafts::class)->find($case->simulation_id, $draftRequest);
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
$payload['description'] = $economic['project_summary'] ?? $payload['description'];
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
}
DB::table('desk_requests')->insert(['id' => $id, 'case_id' => $caseId, 'service_version_id' => $serviceId, 'client_key' => $clientKey, 'payload' => $this->encode($payload), 'created_at' => now(), 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'draft_created', [], $request);
@@ -205,7 +215,8 @@ class VirtualDesk
* @return array<string,mixed> */
public function validateFields(array $payload, array $definition, bool $submitting): array
{
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'declared_origin_country_code'])],
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code'])],
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()]];
foreach ($definition['fields'] as $key => $field) {
$active = ! isset($field['when']) || ($payload[$field['when']['field']] ?? null) === $field['when']['equals'];
@@ -219,8 +230,14 @@ class VirtualDesk
$rules['payload.'.$key] = $rule;
}
$validated = Validator::make(['payload' => $payload], $rules)->validate()['payload'];
foreach ($definition['fields'] as $key => $field) {
if ($field['type'] === 'territory' && ! empty($validated[$key])) {
if (! app(InvestmentGeography::class)->publicReferences()->where('id', $validated[$key])->exists()) {
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione uma localização disponível no cadastro territorial.']);
}
}
}
if ($validated['territory_id'] ?? null) {
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $validated['territory_id'])->exists(), 422, 'Localização indisponível.');
if ($submitting && trim($validated['location_source'] ?? '') === '') {
throw ValidationException::withMessages(['payload.location_source' => 'Indique a fonte da localização.']);
}
@@ -320,7 +337,7 @@ class VirtualDesk
}
$editable = $data['editable_fields'] ?? [];
abort_if($data['status'] === 'returned' && ! $editable, 422, 'Indique os campos autorizados para correção.');
abort_if(array_diff($editable, array_keys($this->definition($request)['fields'])) !== [], 422);
abort_if(array_diff($editable, [...array_keys($this->definition($request)['fields']), 'country', 'declared_origin_country_code']) !== [], 422);
DB::table('desk_requests')->where('id', $id)->update(['status' => $data['status'], 'version' => $request->version + 1, 'editable_fields' => json_encode($editable), 'closed_at' => in_array($data['status'], ['closed', 'cancelled'], true) ? now() : null, 'updated_at' => now()]);
$request = DB::table('desk_requests')->where('id', $id)->firstOrFail();
$this->event($case, $actor, 'request_'.$data['status'], ['reason' => $data['reason'], 'editable_fields' => $editable], $request);
+28 -5
View File
@@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Schema;
class VirtualDeskInstallation
{
public const MIGRATIONS = ['2026_10_07_190000_create_internal_virtual_desk', '2026_10_08_120000_extend_desk_investor_guidance'];
public const MIGRATIONS = ['2026_10_07_190000_create_internal_virtual_desk', '2026_10_08_120000_extend_desk_investor_guidance', '2026_10_09_190000_prepare_investor_path'];
public function fingerprint(): string
{
@@ -20,6 +20,17 @@ class VirtualDeskInstallation
resource_path('js/lib/business-financial-plan.ts'), resource_path('js/lib/financial-calculators.ts'), resource_path('js/lib/project-dossier.ts'),
...array_map(fn ($name) => database_path('migrations/'.$name.'.php'), self::MIGRATIONS),
...(glob(resource_path('js/pages/desk/*.tsx')) ?: []), resource_path('js/components/investor-guidance.tsx'), resource_path('js/components/journey-companion.tsx'), resource_path('js/components/desk-internal-operations.tsx'), resource_path('js/layouts/portal-navigation.tsx'), resource_path('js/layouts/app/app-sidebar-layout.tsx'), resource_path('js/pages/investment/shared.tsx'), resource_path('js/lib/investor-guidance-finance.ts')];
$files = [...$files, app_path('Services/InvestorPath.php'), app_path('Services/InvestorPathDefinition.php'),
app_path('Services/SimulationFormDrafts.php'), app_path('Http/Requests/StoreSimulationFormDraftRequest.php'),
app_path('Http/Controllers/InvestorPathController.php'), app_path('Http/Controllers/DashboardController.php'),
base_path('routes/investor-path.php'), base_path('routes/web.php'), config_path('investor-path.php'),
resource_path('js/pages/dashboard.tsx'), resource_path('js/components/simulation-form.tsx'), resource_path('js/lib/investor-path.ts'),
database_path('migrations/2026_10_01_000200_create_simulation_execution_core.php'),
resource_path('js/components/investment-map-panel.tsx'), resource_path('js/pages/investment/detail.tsx'), resource_path('js/pages/partnerships/catalogue.tsx'),
...(glob(resource_path('js/pages/investor-path/*.tsx')) ?: [])];
$files = [...$files, app_path('Services/VerifiedDocumentBinary.php'), app_path('Services/TerritoryGeometryImport.php'), app_path('Http/Controllers/TerritoryGeometryImportController.php'), config_path('geometry-import.php'), resource_path('js/pages/management/territory-geometry-import.tsx'),
base_path('bootstrap/app.php'), app_path('Providers/FortifyServiceProvider.php'), config_path('fortify.php'),
resource_path('js/pages/auth/login.tsx'), resource_path('js/pages/auth/two-factor-challenge.tsx')];
sort($files);
return hash('sha256', json_encode(array_map(fn ($file) => hash_file('sha256', $file), $files), JSON_THROW_ON_ERROR));
@@ -57,20 +68,29 @@ class VirtualDeskInstallation
foreach (['desk_cases', 'desk_requests', 'desk_documents', 'desk_messages', 'tasks', 'investor_accounts', 'investment_submissions'] as $table) {
$counts[$table] = Schema::hasTable($table) ? DB::table($table)->count() : null;
}
$installed = app(VirtualDesk::class)->installed();
$pathInstalled = Schema::hasColumn('investor_journeys', 'path_definition_id') && Schema::hasColumn('journey_steps', 'path_detail');
$installed = app(VirtualDesk::class)->installed() && $pathInstalled
&& DB::table('migrations')->where('migration', '2026_10_09_190000_prepare_investor_path')->exists();
$pathQa = $read('investor-path-qa-evidence.json');
$pathQaVerified = ($pathQa['code_hash'] ?? null) === $code && ($pathQa['api_persistence_passed'] ?? false)
&& ($pathQa['integrated_ui_ab_passed'] ?? false) && str_ends_with($pathQa['database'] ?? '', '_test') && (int) ($pathQa['port'] ?? 0) === 55441;
$privileges = DB::selectOne("select has_schema_privilege(current_user, 'public', 'CREATE') as can_create,
pg_has_role(current_user, (select tableowner from pg_tables where schemaname='public' and tablename='tasks'), 'USAGE') as can_alter_tasks");
$databaseReady = (bool) ($privileges->can_create && $privileges->can_alter_tasks);
return ['hash' => hash('sha256', json_encode([$identity, $code, $counts, $backupVerified, $qaVerified, $compatibilityVerified, $databaseReady], JSON_THROW_ON_ERROR)), 'code_hash' => $code,
'installed' => $installed, 'target' => $identity, 'counts' => $counts, 'backupVerified' => $backupVerified, 'qaVerified' => $qaVerified,
return ['hash' => hash('sha256', json_encode([$identity, $code, $counts, $backupVerified, $qaVerified, $compatibilityVerified, $databaseReady, $pathQaVerified, $pathInstalled, (bool) config('investor-path.enabled')], JSON_THROW_ON_ERROR)), 'code_hash' => $code,
'installed' => $installed, 'baseDeskInstalled' => app(VirtualDesk::class)->installed(), 'pathInstalled' => $pathInstalled,
'pathEnabled' => (bool) config('investor-path.enabled'), 'pathQaVerified' => $pathQaVerified,
'target' => $identity, 'counts' => $counts, 'backupVerified' => $backupVerified, 'qaVerified' => $qaVerified,
'compatibilityVerified' => $compatibilityVerified, 'backupDate' => $backup['verified_at'] ?? null,
'databaseReady' => $databaseReady,
'scanner' => app(MalwareScanner::class)->health(),
'pendingMigrations' => array_values(array_filter(self::MIGRATIONS, fn ($name) => ! DB::table('migrations')->where('migration', $name)->exists())),
'rollback' => 'Reversão vazia ensaiada em cópia isolada. Com dados novos, preservar/exportar pedidos e tarefas; o down recusa eliminar dados. Restauro integral só numa janela autorizada, após reconciliar alterações posteriores ao backup.',
'changes' => ['Completar o Balcão Virtual existente, preservando pedidos anteriores.', 'Acrescentar associações opcionais ao investidor, projecto e percurso existentes.',
'Reutilizar tasks do CRM para acções expressamente assumidas; sem envio externo.', 'Nenhuma publicação de serviço, documento ou candidatura automática.']];
'Reutilizar tasks do CRM para acções expressamente assumidas; sem envio externo.', 'Nenhuma publicação de serviço, documento ou candidatura automática.',
'Preparar duas colunas nas entidades existentes e uma versão publicada do percurso de 19 etapas. Não converter dossiers existentes.',
'Não habilitar a navegação por instalação: configuração INVESTOR_PATH_ENABLED permanece uma acção separada.']];
}
public function apply(string $hash, User $actor): void
@@ -84,7 +104,9 @@ class VirtualDeskInstallation
return;
}
abort_unless($preview['backupVerified'] && $preview['qaVerified'] && $preview['compatibilityVerified'] && $preview['databaseReady'], 422, 'Backup/restauro atualizado, compatibilidade/reversão, permissões da base e QA desta versão continuam necessários.');
abort_unless($preview['pathQaVerified'], 422, 'Demonstração A/B na interface e evidência API/persistência desta versão ainda necessárias.');
config(['virtual-desk.installation_authorized' => true]);
config(['investor-path.authenticated_installation' => true]);
try {
foreach (self::MIGRATIONS as $name) {
if (! DB::table('migrations')->where('migration', $name)->exists()) {
@@ -94,6 +116,7 @@ class VirtualDeskInstallation
}
} finally {
config(['virtual-desk.installation_authorized' => false]);
config(['investor-path.authenticated_installation' => false]);
}
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_cases', 'actor_user_id' => $actor->id,
'action' => 'desk_installed', 'after_data' => json_encode(['preview_hash' => $hash, 'code_hash' => $preview['code_hash'], 'prior_counts' => $preview['counts']])]);