first commit
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-09-28 10:01:09 +02:00
commit 250ac35fd1
481 changed files with 92144 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Services\Ai;
use App\Models\AiRun;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final class AiGateway
{
public function __construct(private EvidenceRepository $evidence, private AssistiveRules $rules) {}
/** @param array<string, mixed> $input */
public function execute(User $actor, array $input): AiRun
{
abort_unless(config('investmoz_ai.enabled') && $actor->can('manage-portal'), 403);
$capability = $input['capability'];
abort_unless(in_array($capability, config('investmoz_ai.capabilities'), true), 422);
$purpose = match ($capability) {
'classify' => 'interest_triage', 'quality' => 'data_quality', 'sla' => 'execution_monitoring', default => 'investment_information',
};
abort_unless(($input['purpose'] ?? null) === $purpose, 422, 'Finalidade incompatível.');
abort_unless(DB::table('ai_controls')->where('capability', $capability)->where('suspended', false)->exists(), 503, 'Capacidade suspensa.');
$start = hrtime(true);
$language = $input['language'] ?? 'pt';
$items = match ($capability) {
'assistant', 'search' => $this->evidence->search($input['query'], $language, $input),
'summary' => $this->evidence->excerpts($input['source_id']),
'recommend' => $this->rules->recommend($input),
'classify' => $this->rules->classify((int) $input['interest_id']),
'quality' => $this->rules->quality(),
'sla' => $this->rules->sla(),
default => abort(422),
};
$mode = match ($capability) {
'assistant', 'search' => 'lexical_evidence', 'summary' => 'extractive_preview', default => 'structured_rules',
};
$result = [
'items' => $items, 'mode' => $mode, 'model' => null, 'language' => $language,
'status' => $items === [] ? 'no_evidence_or_matches' : 'review_required',
'confidence' => 'not_calibrated', 'generated_claims' => [], 'predictions' => [],
'limitations' => ['not_an_official_decision', 'no_return_or_approval_guarantee', 'no_generative_model',
'no_semantic_search', 'human_review_required', 'bounded_results_not_exhaustive'],
'computed_at' => now()->toIso8601String(),
'human_handoff_url' => '/management/ai',
];
$sourceIds = array_values(array_unique(array_filter(array_column($items, 'source_id'))));
return DB::transaction(function () use ($actor, $input, $capability, $mode, $result, $sourceIds, $start): AiRun {
// Recheck suspension and evidence immediately before retaining a result.
abort_unless(DB::table('ai_controls')->where('capability', $capability)->lockForUpdate()->value('suspended') === false, 503);
abort_unless($this->evidence->allStillEligible($sourceIds), 409, 'A autorização de uma fonte mudou.');
$run = AiRun::create([
'actor_id' => $actor->id, 'capability' => $capability, 'purpose' => $input['purpose'], 'mode' => $mode,
'rules_version' => config('investmoz_ai.rules_version'), 'prompt_version' => config('investmoz_ai.prompt_version'),
'input_hash' => hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR), (string) config('app.key')),
'result' => $result, 'source_ids' => $sourceIds,
'latency_ms' => (int) ((hrtime(true) - $start) / 1000000),
]);
DB::table('audit_events')->insert(['source_system' => 'ai-gateway', 'entity_type' => 'ai_runs',
'entity_id' => $run->id, 'actor_user_id' => $actor->id, 'action' => 'assistance_generated',
'after_data' => json_encode(['capability' => $capability, 'mode' => $mode, 'source_ids' => $sourceIds,
'rules_version' => config('investmoz_ai.rules_version'), 'latency_ms' => $run->latency_ms], JSON_THROW_ON_ERROR)]);
return $run;
});
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace App\Services\Ai;
use App\Models\CrmTask;
use App\Models\InterestRequest;
use App\Models\Lead;
use App\Models\Opportunity;
use Illuminate\Support\Facades\DB;
final class AssistiveRules
{
/** @param array<string, mixed> $input
* @return list<array<string, mixed>>
*/
public function recommend(array $input): array
{
$query = Opportunity::published();
$factors = [];
foreach (['sector_id', 'province', 'maturity_level'] as $field) {
if (isset($input[$field]) && $input[$field] !== '') {
$query->where($field, $input[$field]);
$factors[] = $field;
}
}
if ($factors === []) {
return [];
}
return array_values($query->orderBy('id')->limit(10)->get()->map(fn ($opportunity) => [
'record_type' => 'opportunity', 'record_id' => $opportunity->id, 'title' => $opportunity->title,
'source_url' => '/oportunidades/'.$opportunity->slug,
'score' => count($factors), 'score_max' => 3, 'score_meaning' => 'matched_declared_filters',
'favourable_factors' => $factors, 'incompatibilities' => [],
'eliminatory_conditions' => ['not_published', 'mismatch_with_any_selected_filter'],
'missing_data' => array_filter(['budget', 'time_horizon', 'risk_profile',
$opportunity->last_validated_at ? null : 'validation_date']),
'source_date' => $opportunity->last_validated_at?->toIso8601String(),
'semantic_similarity' => null,
])->all());
}
/** @return list<array<string, mixed>> */
public function classify(int $id): array
{
$interest = InterestRequest::findOrFail($id);
$consent = DB::table('consents')->where('subject_ref', $interest->reference)->where('purpose', 'ai_assistance')
->where('status', 'granted')->whereNotNull('granted_at')->where('granted_at', '<=', now())->whereNull('deleted_at')->whereNull('withdrawn_at')->exists();
abort_unless($consent, 422, 'É necessário consentimento específico registado para assistência sobre este pedido.');
// No name, email, phone, message or sensitive attribute is used.
return [[
'record_type' => 'interest', 'record_id' => $interest->id,
'source_url' => '/management/interests/'.$interest->id,
'sector_declared' => $interest->sector_interest,
'investment_range_declared' => $interest->investment_range,
'intention' => $interest->opportunity_id ? 'interest_in_identified_opportunity' : 'general_information',
'priority' => 'human_review_required', 'suggested_owner' => null,
'next_action' => config('investmoz_ai.classification.next_action'),
'missing_data' => ['confirmed_capacity', 'time_horizon', 'responsible_person', 'institutional_priority'],
'source_date' => $interest->created_at?->toIso8601String(),
]];
}
/** @return list<array<string, mixed>> */
public function quality(): array
{
$alerts = [];
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereNull('owner_user_id')->orderBy('id')->limit(20)->get(['id']) as $lead) {
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_owner', 'source_url' => '/management/crm/leads/'.$lead->id];
}
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['new', 'qualified'])->whereDoesntHave('tasks', fn ($q) => $q->whereIn('status', ['open', 'in_progress']))
->orderBy('id')->limit(20)->get(['id']) as $lead) {
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_next_action', 'source_url' => '/management/crm/leads/'.$lead->id];
}
foreach (DB::table('ai_sources')->where('valid_until', '<', now()->toDateString())->orderBy('id')->limit(20)->get(['id', 'valid_until']) as $source) {
$alerts[] = ['record_type' => 'source', 'record_id' => $source->id, 'rule' => 'expired_source', 'valid_until' => $source->valid_until];
}
foreach (DB::table('documents')->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])
->select('sha256')->selectRaw('count(*) as copies')->groupBy('sha256')->havingRaw('count(*) > 1')->limit(20)->get() as $duplicate) {
$alerts[] = ['record_type' => 'document_group', 'rule' => 'duplicate_document_checksum', 'copies' => (int) $duplicate->copies];
}
foreach (DB::table('geo_geometries')->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])
->whereRaw('NOT ST_IsValid(geom)')->limit(20)->get(['id']) as $geometry) {
$alerts[] = ['record_type' => 'geometry', 'record_id' => $geometry->id, 'rule' => 'invalid_geometry'];
}
return $alerts;
}
/** @return list<array<string, mixed>> */
public function sla(): array
{
return array_values(CrmTask::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())->orderBy('due_at')->limit(50)
->get()->map(fn ($task) => [
'record_type' => 'task', 'record_id' => $task->id, 'rule' => 'overdue_open_task',
'due_at' => $task->getAttribute('due_at')?->toIso8601String(), 'lead_id' => $task->lead_id,
'source_url' => $task->lead_id ? '/management/crm/leads/'.$task->lead_id : null,
'suggested_action' => 'review_owner_deadline_and_dependencies',
'impact' => 'not_estimated', 'priority' => 'human_review_required',
])->all());
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Services\Ai;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
final class EvidenceRepository
{
public function eligible(): Builder
{
return DB::table('ai_sources as s')->join('documents as d', 'd.id', '=', 's.document_id')
->where('s.status', 'approved')->where('s.purpose', 'investment_information')
->where('s.valid_until', '>=', now()->toDateString())->where('s.source_date', '<=', now()->toDateString())
->where('d.status', 'active')->whereNull('d.deleted_at')->whereIn('d.data_classification', ['public', 'internal'])
->whereColumn('s.document_version', 'd.version_no')->whereColumn('s.document_checksum', 'd.sha256');
}
/** @param array<string, mixed> $filters
* @return list<array<string, mixed>>
*/
public function search(string $query, string $language, array $filters = []): array
{
$configuration = $language === 'pt' ? 'portuguese' : 'english';
$builder = $this->eligible()->join('ai_chunks as c', 'c.source_id', '=', 's.id')
->where('s.language', $language)->whereRaw('c.lexical @@ websearch_to_tsquery(?::regconfig, ?)', [$configuration, $query])
->select(['c.id as chunk_id', 's.id as source_id', 's.document_id', 's.document_version', 's.title', 's.language',
's.nature', 's.source_url', 's.source_date', 's.valid_until', 'c.content', 'c.checksum'])
->selectRaw('ts_rank_cd(c.lexical, websearch_to_tsquery(?::regconfig, ?)) as rank', [$configuration, $query]);
if (! empty($filters['source_id'])) {
$builder->where('s.id', $filters['source_id']);
}
if (! empty($filters['nature'])) {
$builder->where('s.nature', $filters['nature']);
}
return array_values($builder->orderByDesc('rank')->orderBy('c.id')->limit((int) config('investmoz_ai.retrieval_limit', 5))
->get()->map(fn ($row) => (array) $row)->all());
}
/** @return list<array<string, mixed>> */
public function excerpts(string $id): array
{
return array_values($this->eligible()->join('ai_chunks as c', 'c.source_id', '=', 's.id')->where('s.id', $id)
->select(['c.id as chunk_id', 's.id as source_id', 's.document_id', 's.document_version', 's.title', 's.language',
's.nature', 's.source_url', 's.source_date', 's.valid_until', 'c.content', 'c.checksum'])
->orderBy('c.position')->limit(3)->get()->map(fn ($row) => (array) $row)->all());
}
/** @param array<array-key, string> $ids */
public function allStillEligible(array $ids): bool
{
return $ids === [] || $this->eligible()->whereIn('s.id', $ids)->count() === count(array_unique($ids));
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Services\Ai;
final class HybridFusion
{
/**
* Fuse already authorised lexical/vector rankings. Scores are ranking signals, not probabilities.
*
* @param list<string> $lexical
* @param list<string> $vector
* @param list<string> $authorised
* @return list<array{id:string,score:float}>
*/
public function rank(array $lexical, array $vector, array $authorised, int $limit = 10): array
{
$scores = [];
foreach ([$lexical, $vector] as $ranking) {
foreach (array_values(array_unique($ranking)) as $position => $id) {
if (in_array($id, $authorised, true)) {
$scores[$id] = ($scores[$id] ?? 0.0) + 1.0 / (60 + $position + 1);
}
}
}
$items = [];
foreach ($scores as $id => $score) {
$items[] = ['id' => $id, 'score' => $score];
}
usort($items, fn ($a, $b) => ($b['score'] <=> $a['score']) ?: strcmp($a['id'], $b['id']));
return array_slice($items, 0, max(0, min(100, $limit)));
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Services\Ai;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
final class SourceIngestion
{
/** @param array<string, mixed> $data */
public function ingest(array $data, int $actor): string
{
return DB::transaction(function () use ($data, $actor): string {
$document = DB::table('documents')->where('id', $data['document_id'])->whereNull('deleted_at')->lockForUpdate()->first();
if (! $document || $document->status !== 'active' || $document->media_type !== 'text/plain'
|| ! in_array($document->data_classification, ['public', 'internal'], true)) {
throw ValidationException::withMessages(['document_id' => 'Documento activo de texto autorizado necessário; fontes confidenciais/restritas não são admitidas.']);
}
$root = realpath(storage_path('app/private'));
$path = realpath(Storage::disk('local')->path($document->storage_key));
if (! $root || ! $path || ! str_starts_with(str_replace('\\', '/', $path), str_replace('\\', '/', $root).'/')
|| ! is_file($path) || filesize($path) > (int) config('investmoz_ai.max_text_bytes')) {
throw ValidationException::withMessages(['document_id' => 'Ficheiro privado inexistente ou acima do limite.']);
}
$text = file_get_contents($path);
if ($text === false || ! mb_check_encoding($text, 'UTF-8') || str_contains($text, "\0") || trim($text) === ''
|| ! hash_equals($document->sha256, hash('sha256', $text))) {
throw ValidationException::withMessages(['document_id' => 'Formato, conteúdo ou checksum inválido.']);
}
if (DB::table('ai_sources')->where('document_id', $document->id)->where('document_version', $document->version_no)->exists()) {
throw ValidationException::withMessages(['document_id' => 'Esta versão já foi registada. Reveja a fonte existente.']);
}
$id = (string) Str::uuid();
DB::table('ai_sources')->insert([
...$data, 'id' => $id, 'document_version' => $document->version_no, 'document_checksum' => $document->sha256,
'submitted_by' => $actor, 'status' => 'pending', 'purpose' => 'investment_information', 'created_at' => now(), 'updated_at' => now(),
]);
$size = max(100, min(5000, (int) config('investmoz_ai.chunk_characters', 1800)));
foreach (mb_str_split($text, $size) as $position => $chunk) {
DB::table('ai_chunks')->insert(['id' => (string) Str::uuid(), 'source_id' => $id, 'position' => $position,
'language' => $data['language'], 'content' => $chunk, 'checksum' => hash('sha256', $chunk)]);
}
DB::table('audit_events')->insert(['actor_user_id' => $actor, 'entity_type' => 'ai_sources', 'entity_id' => $id,
'action' => 'submitted', 'source_system' => 'ai-gateway', 'after_data' => json_encode(['document_version' => $document->version_no], JSON_THROW_ON_ERROR)]);
return $id;
});
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Services;
use App\Models\Contact;
use App\Models\CrmTask;
use App\Models\InterestRequest;
use App\Models\Investor;
use App\Models\Lead;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ConvertInterestToLead
{
/** @param array{investor_id?: string|null, legal_name?: string|null, investor_type?: string|null, owner_user_id: int, title: string, next_action: string, due_at: string} $data */
public function convert(InterestRequest $interest, array $data, int $actor): Lead
{
return DB::transaction(function () use ($interest, $data, $actor) {
$interest = InterestRequest::lockForUpdate()->findOrFail($interest->id);
$existing = Lead::withTrashed()->where('interest_request_id', $interest->id)->first();
if ($existing) {
if ($existing->trashed()) {
throw ValidationException::withMessages(['investor_id' => 'Este pedido já tem um lead arquivado. Reveja o registo existente.']);
}
return $existing;
}
if (! $interest->privacy_consent) {
throw ValidationException::withMessages(['investor_id' => 'O pedido não tem consentimento de contacto registado.']);
}
$email = strtolower(trim($interest->email));
$journeyInvestor = DB::table('investor_journeys')->where('interest_request_id', $interest->id)->whereNull('deleted_at')->value('investor_id');
if ($journeyInvestor && ($data['investor_id'] ?? null) !== $journeyInvestor) {
throw ValidationException::withMessages(['investor_id' => 'Seleccione o investidor associado à jornada original para preservar a identidade.']);
}
// Serialise intake by normalised email without merging unrelated identities.
DB::select('select pg_advisory_xact_lock(170925, hashtext(?))', [$email]);
$contacts = Contact::whereRaw('lower(trim(email)) = ?', [$email])->get();
if ($contacts->count() > 1) {
throw ValidationException::withMessages(['investor_id' => 'Existem contactos duplicados com este email. É necessária revisão antes da conversão.']);
}
$contact = $contacts->first();
$linkedInvestors = $contact ? DB::table('investor_contacts')->where('contact_id', $contact->id)->pluck('investor_id') : collect();
if (empty($data['investor_id']) && $linkedInvestors->isNotEmpty()) {
throw ValidationException::withMessages(['investor_id' => 'Este contacto já representa um investidor. Seleccione o registo existente.']);
}
$investor = ! empty($data['investor_id']) ? Investor::findOrFail($data['investor_id']) : new Investor;
if (! $investor->exists) {
if (empty($data['legal_name']) || empty($data['investor_type'])) {
throw ValidationException::withMessages(['legal_name' => 'Identifique o novo investidor e o seu tipo.']);
}
PortalAudit::save($investor, ['legal_name' => $data['legal_name'], 'investor_type' => $data['investor_type'], 'status' => 'prospect'], $actor);
}
if (! $contact) {
$contact = new Contact;
PortalAudit::save($contact, ['full_name' => $interest->full_name, 'email' => $email, 'phone' => $interest->phone], $actor);
}
DB::table('investor_contacts')->insertOrIgnore(['investor_id' => $investor->id, 'contact_id' => $contact->id, 'is_primary' => false]);
$lead = new Lead;
PortalAudit::save($lead, ['investor_id' => $investor->id, 'owner_user_id' => $data['owner_user_id'],
'interest_request_id' => $interest->id, 'title' => $data['title'], 'status' => 'new',
'first_source' => 'portal:'.$interest->reference, 'last_source' => 'portal:'.$interest->reference,
'source_system' => 'portal-intake', 'external_id' => $interest->reference], $actor);
PortalAudit::save(new CrmTask, ['lead_id' => $lead->id, 'assignee_user_id' => $data['owner_user_id'],
'title' => $data['next_action'], 'status' => 'open', 'due_at' => $data['due_at']], $actor);
return $lead;
});
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Services;
use InvalidArgumentException;
final class EducationGapCalculator
{
/** @return array{state:string, people:?int} */
public function observed(?int $demand, ?int $available, bool $comparable, bool $current): array
{
if (($demand !== null && $demand < 0) || ($available !== null && $available < 0)) {
throw new InvalidArgumentException('Quantities cannot be negative.');
}
if (! $current) {
return ['state' => 'expired', 'people' => null];
}
if (! $comparable) {
return ['state' => 'incomparable', 'people' => null];
}
if ($demand === null || $available === null) {
return ['state' => 'insufficient_data', 'people' => null];
}
return ['state' => 'observed_unvalidated', 'people' => max(0, $demand - $available)];
}
}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace App\Services;
final class IdempotencyConflict extends \RuntimeException {}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Services;
use App\Models\InterestRequest;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use SensitiveParameter;
final class InterestSubmission
{
/**
* @param array<string, mixed> $payload Validated business fields only.
* @param Closure(): InterestRequest $create
*/
public function receive(#[SensitiveParameter] array $payload, #[SensitiveParameter] ?string $key, Closure $create): InterestRequest
{
$canonical = array_replace(['phone' => null, 'opportunityReference' => null, 'investmentRange' => null], $payload);
$canonical['email'] = strtolower(trim($canonical['email']));
$canonical['fullName'] = trim($canonical['fullName']);
$canonical['message'] = trim($canonical['message']);
$canonical['privacyConsent'] = true; // FormRequest requires acceptance.
ksort($canonical);
$payloadHash = hash_hmac('sha256', json_encode($canonical, JSON_THROW_ON_ERROR), config()->string('app.key'));
$keyHash = $key === null ? null : hash('sha256', strtolower($key));
return DB::transaction(function () use ($keyHash, $payloadHash, $create): InterestRequest {
if ($keyHash !== null) {
// Serialise concurrent submissions of this key across all web workers.
DB::select('select pg_advisory_xact_lock(250925, hashtext(?))', [$keyHash]);
$receipt = DB::table('interest_submission_receipts')->where('key_hash', $keyHash)->first();
if ($receipt) {
if (! hash_equals($receipt->payload_hash, $payloadHash)) {
throw new IdempotencyConflict;
}
return InterestRequest::withTrashed()->where('id', $receipt->interest_request_id)->firstOrFail();
}
}
$interest = $create();
$integrationId = (string) Str::uuid();
$interest->forceFill(['integration_id' => $integrationId])->save();
DB::table('outbox_events')->insert([
'source_system' => 'portal-intake',
'external_id' => 'ExpressionOfInterestSubmitted:'.$integrationId,
'aggregate_type' => 'interest_request', 'aggregate_id' => $integrationId,
'event_type' => 'ExpressionOfInterestSubmitted', 'data_classification' => 'confidential',
'correlation_id' => $integrationId, 'status' => 'pending',
'payload' => json_encode(['schema_version' => 1, 'interest_id' => $integrationId], JSON_THROW_ON_ERROR),
]);
if ($keyHash !== null) {
DB::table('interest_submission_receipts')->insert([
'key_hash' => $keyHash, 'payload_hash' => $payloadHash,
'interest_request_id' => $interest->id, 'created_at' => now(),
]);
}
return $interest;
});
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\Opportunity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class InvestmentCatalogue
{
public const RELATIONS = ['clusters' => ['cluster_id', 'economic_clusters'], 'corridors' => ['corridor_id', 'development_corridors'],
'projects' => ['project_id', 'projects'], 'locations' => ['geo_location_id', 'geo_locations']];
/** @return array<string,mixed> */
public function filters(Request $request): array
{
return $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
'province' => ['nullable', 'string', 'max:100'], 'district' => ['nullable', 'string', 'max:100'],
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'],
'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined'],
'maturity_level' => ['nullable', 'integer', 'between:1,6'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'],
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
}
/**
* @param array<string,mixed> $filters
* @return Builder<Opportunity>
*/
public function query(array $filters): Builder
{
$query = Opportunity::published()->with('sector:id,name,slug');
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $filters['dimension'])->select('mapping.opportunity_id'));
}
foreach (['cluster' => 'clusters', 'corridor' => 'corridors'] as $dimension => $relation) {
if (($filters['dimension'] ?? null) === $dimension) {
$foreign = $dimension.'_id';
$query->whereIn('opportunities.id', DB::table('opportunity_'.$relation)->whereIn($foreign, InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign))->select('opportunity_id'));
}
}
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $field => $category) {
if (! empty($filters[$field])) {
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()
->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $category)
->where('zl.zone_id', $filters[$field])->select('mapping.opportunity_id'));
}
}
if (! empty($filters['q'])) {
$term = '%'.$filters['q'].'%';
$query->where(fn ($q) => $q->where('title', 'ilike', $term)->orWhere('summary', 'ilike', $term)->orWhere('reference', 'ilike', $term)
->orWhere('province', 'ilike', $term)->orWhereHas('sector', fn ($s) => $s->where('name', 'ilike', $term)));
}
if (! empty($filters['sector'])) {
$query->whereHas('sector', fn ($s) => $s->where('slug', $filters['sector']));
}
foreach (['province', 'district', 'maturity_level'] as $field) {
if (! empty($filters[$field])) {
$query->where($field, $filters[$field]);
}
}
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
if (! empty($filters[$foreign])) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
->when($relation === 'locations', fn ($q) => $q->where('target.data_classification', 'public'),
fn ($q) => $q->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign))));
}
}
if (! empty($filters['education'])) {
$query->where(fn ($q) => $q->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('is_education', true))
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('education_investment_proposals')->whereColumn('opportunity_id', 'opportunities.id')->whereNull('deleted_at')));
}
foreach ($filters['facets'] ?? [] as $option) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_facets')->whereColumn('opportunity_id', 'opportunities.id')->where('option_id', $option));
}
foreach (['min_amount' => '>=', 'max_amount' => '<='] as $field => $operator) {
if (isset($filters[$field])) {
$query->where('estimated_investment_amount', $operator, $filters[$field]);
}
}
if (! empty($filters['currency'])) {
$query->where('estimated_investment_currency', $filters['currency']);
}
if (! empty($filters['before'])) {
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
}
$sort = $filters['sort'] ?? 'recent';
// Monetary sorting stays grouped by currency; no undocumented FX conversion.
return match ($sort) {
'title' => $query->orderBy('title')->orderBy('id'),
'amount_asc', 'amount_desc' => $query->orderBy('estimated_investment_currency')->orderBy('estimated_investment_amount', $sort === 'amount_asc' ? 'asc' : 'desc')->orderBy('id'),
default => $query->orderByDesc('published_at')->orderByDesc('id'),
};
}
/** @return array<string,mixed> */
public function references(bool $management = false): array
{
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug'])];
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
$query = DB::table($table)->whereNull('deleted_at');
if (! $management) {
if ($relation === 'locations') {
$query->where('data_classification', 'public');
} else {
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
}
}
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
}
$result['zones'] = app(InvestmentZones::class)->visible()->orderBy('name')->get(['id', 'name', 'category']);
return $result;
}
/** @return array<string,mixed> */
public function context(int $id, bool $management = false): array
{
$result = ['profile' => DB::table('opportunity_profiles')->where('opportunity_id', $id)->first(),
'facets' => DB::table('opportunity_facets as f')->join('investment_reference_options as o', 'o.id', '=', 'f.option_id')
->where('f.opportunity_id', $id)->get(['o.id', 'o.group', 'o.label'])];
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
$query = DB::table('opportunity_'.$relation.' as l')->join($table.' as t', 't.id', '=', 'l.'.$foreign)->where('l.opportunity_id', $id)->whereNull('t.deleted_at');
if (! $management) {
if ($relation === 'locations') {
$query->where('t.data_classification', 'public');
} else {
$query->whereIn('t.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
}
}
$result[$relation] = $query->get(['t.id', 't.name']);
}
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id)
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
return $result;
}
/**
* @param array<string,mixed> $filters
* @return array<string,mixed>
*/
public function map(array $filters): array
{
$ids = $this->query($filters)->reorder()->select('opportunities.id');
$points = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')->join('opportunities as o', 'o.id', '=', 'l.opportunity_id')
->whereIn('o.id', $ids)->where('g.data_classification', 'public')->where('shape.data_classification', 'public')
->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')->limit(1000)
->get(['o.id', 'o.title', 'o.slug', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')]);
return ['type' => 'FeatureCollection', 'limit' => 1000, 'features' => $points->map(fn ($p) => ['type' => 'Feature',
'geometry' => json_decode($p->geometry, true), 'properties' => ['id' => $p->id, 'title' => $p->title, 'location' => $p->name, 'url' => '/oportunidades/'.$p->slug]])->all()];
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Services;
use App\Models\InvestmentItem;
use App\Models\Opportunity;
use Illuminate\Support\Facades\DB;
final class InvestmentIdentity
{
public function forOpportunity(int $id): string
{
return DB::transaction(function () use ($id) {
$opportunity = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
$mapping = DB::table('investment_item_opportunities')->where('opportunity_id', $id)->first();
if ($mapping) {
return $mapping->item_id;
}
$item = InvestmentItem::create(['code' => 'opportunity:'.$id, 'title' => $opportunity->title, 'kind' => 'opportunity']);
DB::table('investment_item_opportunities')->insert(['item_id' => $item->id, 'opportunity_id' => $id,
'mapping_evidence' => 'Direct correspondence to existing opportunity primary key; no inferred merge or change of validation status.',
'created_at' => now(), 'updated_at' => now()]);
return $item->id;
});
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Services;
use App\Models\InvestmentSpecificNeed;
use App\Models\InvestmentSubmission;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class InvestmentWorkspace
{
/** @param array<string,mixed> $payload */
public function notify(int $userId, InvestmentSubmission $submission, string $kind, string $eventKey, array $payload = []): void
{
DB::table('investment_notifications')->insertOrIgnore(['id' => (string) Str::uuid(), 'user_id' => $userId,
'submission_id' => $submission->id, 'kind' => $kind, 'event_key' => $eventKey,
'payload' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)), 'created_at' => now()]);
}
public function snapshot(InvestmentSubmission $submission): void
{
$snapshot = ['payload' => $submission->payload, 'status' => $submission->status,
'zone_origin' => DB::table('investment_submission_zones')->where('submission_id', $submission->id)->first(['zone_id', 'zone_version', 'intent']),
'needs' => InvestmentSpecificNeed::where('submission_id', $submission->id)->get()->toArray(),
'attachment_ids' => DB::table('investment_submission_attachments')->where('submission_id', $submission->id)->pluck('id')->all()];
DB::table('investment_submission_revisions')->insert(['submission_id' => $submission->id, 'version' => $submission->version,
'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR)), 'created_at' => now()]);
}
/** @return array<string,mixed> */
public function account(int $userId): array
{
$row = DB::table('investment_accounts')->where('user_id', $userId)->first();
return ['version' => $row->version ?? 0, 'payload' => $row ? json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR) : []];
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace App\Services;
use App\Models\User;
final class InvestmentZoneAccess
{
public static function requireRole(User $user, string $role): void
{
abort_unless(in_array(strtolower($user->email), config('investment-zones.'.$role, []), true), 403,
'O perfil não está designado para esta revisão. A configuração de funções é feita pela administração.');
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace App\Services;
use App\Models\InvestmentZone;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class InvestmentZones
{
public function links(bool $territorial = false): \Illuminate\Database\Query\Builder
{
return DB::table(($territorial ? 'investment_zone_relations' : 'investment_zone_links').' as zl')->where('zl.validation_status', 'validated')
->whereIn('zl.zone_id', $this->visible()->select('investment_zones.id'))
->whereDate('zl.valid_from', '<=', today())->where(fn ($q) => $q->whereNull('zl.valid_until')->orWhereDate('zl.valid_until', '>=', today()))
->where(function ($q) {
$q->whereNull('zl.legal_source_id')->orWhereExists(fn ($s) => $s->selectRaw('1')->from('investment_legal_sources as ls')
->whereColumn('ls.id', 'zl.legal_source_id')->where('ls.validation_status', 'validated')->whereDate('ls.valid_from', '<=', today())
->where(fn ($s) => $s->whereNull('ls.valid_until')->orWhereDate('ls.valid_until', '>=', today())));
});
}
/** @return Builder<InvestmentZone> */
public function visible(): Builder
{
return InvestmentZone::query()->where('publication_status', 'published')->where('validation_status', 'validated')
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
->whereDate('source.valid_from', '<=', today())
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())))
->whereExists(fn ($q) => $q->selectRaw('1')->from('organizations')->whereColumn('organizations.id', 'investment_zones.operator_id')->whereNull('organizations.deleted_at'));
}
/** @param array<string,mixed> $data */
public function save(?string $id, array $data, int $actor): InvestmentZone
{
return DB::transaction(function () use ($id, $data, $actor) {
$zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone;
abort_if($id && (int) $zone->version_no !== (int) $data['version_no'], 409, 'Versão alterada. Recarregue antes de guardar.');
$version = $id ? (int) $zone->version_no + 1 : 1;
unset($data['version_no']);
$zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null,
'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save();
$this->snapshot($zone, $actor, 'saved');
return $zone;
});
}
public function publish(string $id, int $version, int $actor): InvestmentZone
{
return DB::transaction(function () use ($id, $version, $actor) {
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.');
abort_if((int) $zone->editor_id === $actor, 403, 'A revisão exige outro gestor autorizado.');
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Fonte jurídica válida e revista em falta.');
abort_unless($zone->category !== 'pending' && $zone->operator_id && trim((string) $zone->name_en) !== ''
&& trim((string) $zone->description) !== '' && trim((string) $zone->description_en) !== '', 422, 'Categoria, operador e conteúdo PT/EN são obrigatórios.');
abort_unless(DB::table('organizations')->where('id', $zone->operator_id)->whereNull('deleted_at')->exists(), 422, 'Operador indisponível.');
$zone->fill(['version_no' => $version + 1, 'reviewer_id' => $actor, 'publication_status' => 'published',
'validation_status' => 'validated', 'published_at' => now()])->save();
$this->snapshot($zone, $actor, 'published');
return $zone;
});
}
public function suspend(string $id, int $version, int $actor): InvestmentZone
{
return DB::transaction(function () use ($id, $version, $actor) {
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada.');
$zone->fill(['version_no' => $version + 1, 'publication_status' => 'suspended'])->save();
$this->snapshot($zone, $actor, 'suspended');
return $zone;
});
}
private function snapshot(InvestmentZone $zone, int $actor, string $action): void
{
$json = $zone->toJson(JSON_THROW_ON_ERROR);
DB::table('investment_zone_revisions')->insert(['id' => (string) Str::uuid(), 'zone_id' => $zone->id,
'version_no' => $zone->version_no, 'actor_id' => $actor, 'action' => $action,
'snapshot' => Crypt::encryptString($json), 'sha256' => hash('sha256', $json)]);
DB::table('audit_events')->insert(['source_system' => 'investment-zones', 'entity_type' => 'investment_zones',
'entity_id' => $zone->id, 'actor_user_id' => $actor, 'action' => $action,
'after_data' => json_encode(['version_no' => $zone->version_no, 'sha256' => hash('sha256', $json)], JSON_THROW_ON_ERROR)]);
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Services;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class PortalAudit
{
/** @param array<string, mixed> $data */
public static function save(Model $record, array $data, int $actor): void
{
DB::transaction(function () use ($record, $data, $actor) {
$created = ! $record->exists;
if (! $created) {
$locked = $record->newQuery()->where($record->getKeyName(), $record->getKey())->lockForUpdate()->firstOrFail();
$record->setRawAttributes($locked->getAttributes(), true);
}
// Exclude free text and personal data from the immutable event payload.
$fields = ['version_no', 'status', 'is_active', 'is_featured', 'sort_order', 'sector_id', 'maturity_level',
'estimated_investment_amount', 'estimated_investment_currency', 'owner_user_id', 'assignee_user_id', 'due_at',
'cluster_id', 'project_id', 'corridor_id', 'dossier_id', 'interest_request_id', 'publication_status', 'editor_id', 'reviewer_id', 'role', 'stage', 'value_chain_id', 'from_value_chain_id', 'to_value_chain_id', 'link_type', 'deleted_at'];
$before = array_intersect_key($record->getAttributes(), array_flip($fields));
$record->fill($data);
$changed = array_keys($record->getDirty());
$record->save();
if (! $changed) {
return;
}
DB::table('audit_events')->insert([
'source_system' => 'portal-management', 'actor_user_id' => $actor,
'entity_type' => $record->getTable(), 'entity_id' => Str::isUuid((string) $record->getKey()) ? $record->getKey() : null,
'action' => $created ? 'created' : 'updated',
'before_data' => json_encode(['record_id' => $record->getKey(), 'values' => $before], JSON_THROW_ON_ERROR),
'after_data' => json_encode(['record_id' => $record->getKey(), 'changed_fields' => $changed,
'values' => array_intersect_key($record->getAttributes(), array_flip($fields))], JSON_THROW_ON_ERROR),
]);
});
}
}