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
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Console\Commands;
use App\Services\Ai\EvidenceRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class AiBenchmark extends Command
{
protected $signature = 'ai:benchmark';
protected $description = 'Mede recuperação lexical PT/EN com dados sintéticos e rollback numa base *_test';
public function handle(EvidenceRepository $evidence): int
{
if (! app()->environment('testing') || DB::connection()->getDriverName() !== 'pgsql'
|| ! str_ends_with(DB::connection()->getDatabaseName(), '_test')
|| DB::connection()->getDatabaseName() !== DB::selectOne('select current_database() as name')->name) {
$this->error('Apenas numa base PostgreSQL isolada *_test, com APP_ENV=testing.');
return self::FAILURE;
}
$cases = [
['pt', 'formação técnica', 'Exemplo sintético: formação técnica de electricistas em oficinas.', true],
['pt', 'cadeia logística', 'Exemplo sintético: a cadeia logística inclui armazenamento e transporte.', true],
['pt', 'energia solar', 'Exemplo sintético: manutenção de equipamentos de energia solar.', true],
['pt', 'taxa oficial', 'Exemplo sintético sem informação legal.', false],
['en', 'vocational training', 'Synthetic example: vocational training for equipment maintenance.', true],
['en', 'logistics corridor', 'Synthetic example: a logistics corridor connects warehouses and transport hubs.', true],
['en', 'solar energy', 'Synthetic example: solar energy equipment requires maintenance.', true],
['en', 'official tax', 'Synthetic example with no legal information.', false],
];
DB::beginTransaction();
try {
// Unique synthetic fixtures are visible only within this transaction.
$author = DB::table('users')->insertGetId(['name' => 'Synthetic benchmark author', 'email' => Str::uuid().'@example.invalid', 'password' => 'unused']);
$reviewer = DB::table('users')->insertGetId(['name' => 'Synthetic benchmark reviewer', 'email' => Str::uuid().'@example.invalid', 'password' => 'unused']);
$measurements = [];
$passed = 0;
foreach ($cases as [$language, $query, $text, $expected]) {
$document = (string) Str::uuid();
$source = (string) Str::uuid();
DB::table('documents')->insert(['id' => $document, 'file_name' => 'synthetic.txt', 'media_type' => 'text/plain',
'storage_key' => 'synthetic-'.$document, 'sha256' => hash('sha256', $text), 'status' => 'active', 'data_classification' => 'internal']);
DB::table('ai_sources')->insert(['id' => $source, 'document_id' => $document, 'document_version' => 1,
'document_checksum' => hash('sha256', $text), 'title' => 'Synthetic benchmark', 'language' => $language,
'nature' => 'illustrative', 'source_url' => 'https://example.org/synthetic', 'source_owner' => 'Test fixture',
'evidence_reference' => 'Synthetic benchmark only', 'source_date' => now()->toDateString(),
'valid_until' => now()->addDay()->toDateString(), 'status' => 'approved', 'submitted_by' => $author,
'reviewed_by' => $reviewer, 'reviewed_at' => now()]);
DB::table('ai_chunks')->insert(['id' => (string) Str::uuid(), 'source_id' => $source, 'position' => 0,
'language' => $language, 'content' => $text, 'checksum' => hash('sha256', $text)]);
$latencies = [];
for ($i = 0; $i < 5; $i++) {
$start = hrtime(true);
$results = $evidence->search($query, $language, ['source_id' => $source]);
$latencies[] = round((hrtime(true) - $start) / 1000000, 3);
}
$ok = ($results !== []) === $expected;
$passed += $ok ? 1 : 0;
sort($latencies);
$measurements[] = ['language' => $language, 'query' => $query, 'expected_match' => $expected,
'passed' => $ok, 'p50_ms' => $latencies[2], 'max_ms' => $latencies[4]];
}
$this->line(json_encode(['executed_at' => now()->toIso8601String(), 'backend' => 'PostgreSQL FTS', 'model' => null,
'synthetic' => true, 'passed' => $passed, 'cases' => count($cases), 'repetitions_per_case' => 5,
'measurements' => $measurements, 'generative_benchmark' => 'not_executed_no_runtime_or_model',
'limitations' => ['small_single_source_cases', 'not_a_representative_benchmark', 'not_human_validated_PT_MZ', 'no_concurrency_or_load_test']], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
return $passed === count($cases) ? self::SUCCESS : self::FAILURE;
} finally {
DB::rollBack();
}
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Models\InvestmentDossier;
use Database\Seeders\InvestmentPortfolioSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ImportInvestmentPortfolio extends Command
{
protected $signature = 'portfolio:import {--approval= : Recorded approval from the document owner}';
protected $description = 'Import the v4 portfolio and optionally publish unchanged documentary dossiers with owner approval';
public function handle(): int
{
$approval = trim((string) $this->option('approval'));
if ($approval !== '' && (mb_strlen($approval) < 15 || mb_strlen($approval) > 3000)) {
$this->error('A autorização deve conter entre 15 e 3000 caracteres.');
return self::FAILURE;
}
$data = json_decode(File::get(database_path('data/investment-portfolio.json')), true, 512, JSON_THROW_ON_ERROR);
$published = 0;
$preserved = 0;
DB::transaction(function () use ($data, $approval, &$published, &$preserved) {
app(InvestmentPortfolioSeeder::class)->run();
foreach (['projects' => ['project_id', 'projects'], 'clusters' => ['cluster_id', 'economic_clusters'], 'corridors' => ['corridor_id', 'development_corridors']] as $kind => [$foreign, $table]) {
foreach ($data[$kind] as $item) {
$entity = DB::table($table)->where('code', $item['code'])->where('source_system', 'upgrade-v4')->whereNull('deleted_at')->value('id');
$dossier = InvestmentDossier::where($foreign, $entity)->lockForUpdate()->first();
// Approval of this document never approves subsequent human edits or restores archived records.
if (! $dossier || $dossier->title !== $item['name'] || $dossier->content != [...$item, 'notice' => $data['notice']] || $dossier->editor_id) {
$preserved++;
continue;
}
if ($approval === '' || $dossier->publication_status === 'published') {
continue;
}
$dossier->update(['version_no' => $dossier->version_no + 1, 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => $approval]);
DB::table('audit_events')->insert(['source_system' => 'portfolio-import', 'entity_type' => 'investment_dossiers',
'entity_id' => $dossier->id, 'action' => 'owner_approved', 'after_data' => json_encode([
'code' => $item['code'], 'approval_basis' => 'document_owner',
'approval_sha256' => hash('sha256', $approval),
'dataset_sha256' => hash_file('sha256', database_path('data/investment-portfolio.json')),
], JSON_THROW_ON_ERROR)]);
$published++;
}
}
});
$this->info("Carteira importada: 15 projectos, 8 clusters, 6 corredores. Publicados: {$published}. Fichas alteradas/arquivadas preservadas: {$preserved}.");
return self::SUCCESS;
}
}
@@ -0,0 +1,116 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Laravel\Chisel\Chisel;
use Laravel\Chisel\Question;
use Laravel\Chisel\Script;
use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\spin;
class InstallFeaturesCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'install:features
{--answers= : JSON string of answers to skip interactive prompts}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Choose which starter kit features to keep';
public function handle(): int
{
if ($this->shouldDeferInstallerHooks()) {
return self::SUCCESS;
}
if (! file_exists(base_path('chisel.php'))) {
return self::SUCCESS;
}
/** @var Script $script */
$script = require base_path('chisel.php');
$providedAnswers = $this->option('answers') === null
? []
: json_decode((string) $this->option('answers'), true, 512, JSON_THROW_ON_ERROR);
$answers = $script
->collectAnswers()
->onQuestion(fn (Question $question) => multiselect(
label: $question->label,
options: $question->options,
default: $question->default ?? [],
required: $question->required,
hint: $question->hint,
))
->interactive($this->input->isInteractive())
->withAnswers($providedAnswers);
$skipNode = $this->shouldSkipNode();
if (! $skipNode) {
$this->installNodeDependencies();
}
$script->chisel($answers);
if (! $skipNode) {
$this->buildAssets();
}
return self::SUCCESS;
}
protected function shouldDeferInstallerHooks(): bool
{
if ($this->option('answers') !== null) {
return false;
}
return $this->installerFlag('LARAVEL_INSTALLER_DEFER_HOOKS');
}
protected function shouldSkipNode(): bool
{
return $this->installerFlag('LARAVEL_INSTALLER_NO_NODE');
}
protected function installerFlag(string $name): bool
{
return filter_var(
$_ENV[$name] ?? $_SERVER[$name] ?? getenv($name),
FILTER_VALIDATE_BOOL,
);
}
protected function installNodeDependencies(): void
{
$npm = Chisel::in(base_path())->npm();
$packageManager = $npm->packageManager();
spin(
fn () => $npm->install(),
"Installing dependencies with {$packageManager->value}...",
);
}
protected function buildAssets(): void
{
$npm = Chisel::in(base_path())->npm();
spin(
fn () => $npm->run('build'),
'Building assets...',
);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class PortalReadiness extends Command
{
protected $signature = 'portal:readiness';
protected $description = 'Verifica requisitos de publicação sem alterar dados nem revelar segredos';
public function handle(): int
{
$checks = [
'PHP >= 8.4.1' => version_compare(PHP_VERSION, '8.4.1', '>='),
'Driver PostgreSQL' => extension_loaded('pdo_pgsql'),
'Ambiente production' => app()->isProduction(),
'Debug desactivado' => ! config('app.debug'),
'APP_KEY definida' => filled(config('app.key')),
'APP_URL HTTPS' => str_starts_with(config('app.url'), 'https://'),
'Cookies seguros' => (bool) config('session.secure'),
'Assets compilados' => is_file(public_path('build/manifest.json')),
'Sem ficheiro Vite hot' => ! is_file(public_path('hot')),
'Storage gravável' => is_writable(storage_path()) && is_writable(base_path('bootstrap/cache')),
'Gestores configurados' => count(config('portal.managers')) > 0,
'Correio real configurado' => ! in_array(config('mail.default'), ['log', 'array'], true),
];
try {
DB::select('select 1');
$checks['Ligação à base de dados'] = true;
$checks['PostGIS instalado'] = (bool) DB::selectOne("select exists(select 1 from pg_extension where extname = 'postgis') as installed")->installed;
$checks['Migrations aplicadas'] = count(array_diff(
array_keys(app('migrator')->getMigrationFiles(database_path('migrations'))),
app('migration.repository')->getRan(),
)) === 0;
} catch (\Throwable) {
$checks['Base de dados e migrations verificáveis'] = false;
}
if (config('portal.notifications_enabled')) {
$checks['Destinatários válidos'] = count(config('portal.notification_recipients')) > 0
&& collect(config()->array('portal.notification_recipients'))->every(fn ($email) => filter_var($email, FILTER_VALIDATE_EMAIL) !== false);
$checks['Fila database na mesma ligação'] = ! config('queue.connections.database.after_commit')
&& (! config('queue.connections.database.connection') || config('queue.connections.database.connection') === config('database.default'));
}
foreach ($checks as $label => $passed) {
$this->line(($passed ? '[OK] ' : '[PENDENTE] ').$label);
}
$this->line('Este diagnóstico não testa entrega de email, TLS externo, backups ou execução do worker.');
return in_array(false, $checks, true) ? self::FAILURE : self::SUCCESS;
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Models\Opportunity;
use App\Services\InvestmentIdentity;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ReconcileInvestmentIdentity extends Command
{
protected $signature = 'investment:reconcile-identities {--apply : Apply direct opportunity-ID mappings after backup}';
protected $description = 'Dry-run or apply idempotent canonical mappings without changing legacy records or merging projects';
public function handle(InvestmentIdentity $identity): int
{
if (! app()->environment('local', 'testing')) {
$this->error('This migration command is restricted to local/testing environments.');
return self::FAILURE;
}
$report = DB::transaction(function () use ($identity) {
$ids = Opportunity::orderBy('id')->pluck('id');
$missing = $ids->diff(DB::table('investment_item_opportunities')->pluck('opportunity_id'))->values();
if ($this->option('apply')) {
foreach ($missing as $id) {
$identity->forOpportunity($id);
}
}
return ['generated_at' => now()->toIso8601String(), 'mode' => $this->option('apply') ? 'apply' : 'dry-run',
'opportunity_count' => $ids->count(), 'missing_before' => $missing->count(),
'missing_after' => $ids->diff(DB::table('investment_item_opportunities')->pluck('opportunity_id'))->count(),
'unmapped_project_count' => DB::table('projects')->whereNull('deleted_at')->whereNotIn('id', DB::table('investment_item_projects')->select('project_id'))->count(),
'changes_to_legacy_records' => 0, 'automatic_project_merges' => 0,
'rule' => 'Map stable opportunity primary keys only. Project correspondence requires documentary reconciliation.'];
});
$path = 'zone-reconciliation/'.now()->format('Ymd-His').'-'.Str::uuid().'.json';
Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
$this->line(json_encode([...$report, 'private_report' => $path], JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Integrations\SuiteCrm\SuiteCrmClient;
use App\Integrations\SuiteCrm\SuiteCrmException;
use Illuminate\Console\Command;
use Throwable;
class SuiteCrmProbe extends Command
{
protected $signature = 'suitecrm:probe {--module=Contacts : Modulo cujos metadados serao consultados}';
protected $description = 'Verifica OAuth e leitura de metadados sem escrever registos comerciais';
public function handle(SuiteCrmClient $client): int
{
try {
$response = $client->fields((string) $this->option('module'));
if (! isset($response['data']) || ! is_array($response['data']) || $response['data'] === []) {
$this->error('Resposta sem metadados utilizaveis. Integracao nao validada.');
return self::FAILURE;
}
} catch (SuiteCrmException $exception) {
$this->error('SuiteCRM indisponivel: '.$exception->reason);
return self::FAILURE;
} catch (Throwable) {
// Cache/database exceptions may contain secrets: never render their messages.
$this->error('Falha interna no diagnostico. Verifique cache, chave da aplicacao e configuracao.');
return self::FAILURE;
}
$this->info('OAuth e leitura de metadados confirmados. Nenhum registo comercial alterado.');
$this->warn('Este teste nao valida permissoes de escrita, sincronizacao, reconciliacao ou prontidao para producao.');
return self::SUCCESS;
}
}