@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user