Files
compras/tests/Feature/PrivateAuditSourcesTest.php
T
nala 448948a487
tests / ci (push) Waiting to run
commit compras1 2911
2026-11-29 05:28:30 +02:00

190 lines
12 KiB
PHP

<?php
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\SupplierBankDetail;
use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditSourceReader;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['private-audit.qa_enabled' => true]);
$this->f = receiptFixture();
$this->actor = $this->f['issuer'];
$this->actingAs($this->actor);
supplyGrant($this->actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
if (DB::getDriverName() === 'pgsql') {
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Audit source fixtures require the disposable PostgreSQL database.');
}
DB::commit();
$this->committedAuditSourceFixture = true;
}
});
afterEach(function () {
if ($this->committedAuditSourceFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Audit source cleanup requires its disposable PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
/** Test collector only; the production packager consumes each generator directly. */
function collectedPrivateAuditSources(User $actor, array $families): array
{
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 0) {
return DB::transaction(function () use ($actor, $families) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return collectedPrivateAuditSources($actor, $families);
});
}
$result = [];
foreach (app(PrivateAuditSourceReader::class)->datasets($actor, $families) as $dataset) {
$rows = $dataset['rows'];
$result[$dataset['family'].':'.$dataset['source']] = [...$dataset, 'rows' => $rows === null ? null : iterator_to_array($rows, false)];
}
return $result;
}
test('private audit source pagination includes every selected company row and no other company data', function () {
for ($index = 0; $index < 131; $index++) {
Department::query()->create(['tenant_id' => $this->actor->tenant_id, 'name' => 'AUDIT-DEPARTMENT-'.str_pad((string) $index, 3, '0', STR_PAD_LEFT)]);
}
$foreign = Tenant::query()->create(['name' => 'FOREIGN-AUDIT-COMPANY']);
Department::query()->create(['tenant_id' => $foreign->id, 'name' => 'FOREIGN-AUDIT-DEPARTMENT']);
$before = DB::table('departments')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['configuration']);
$rows = $sources['configuration:departments']['rows'];
expect($rows)->toHaveCount(132)
->and(array_column($rows, 'name'))->toContain('AUDIT-DEPARTMENT-130')
->and(json_encode($sources, JSON_THROW_ON_ERROR))->not->toContain('FOREIGN-AUDIT-DEPARTMENT')->not->toContain('FOREIGN-AUDIT-COMPANY')
->and(DB::table('departments')->orderBy('id')->get()->toJson())->toBe($before);
});
test('private audit preserves ordinary data while excluding bank coordinates credentials people payloads and storage paths', function () {
$this->f['tenant']->update(['company_details' => ['legal_name' => 'AUDIT-LEGAL-NAME', 'bank_accounts' => [['account_number' => 'BANK-FULL-NEVER-EXPORT']], 'establishments' => [['name' => 'AUDIT-LOCATION']]]]);
SupplierBankDetail::query()->create(['tenant_id' => $this->actor->tenant_id, 'supplier_id' => $this->f['order']->supplier_id,
'created_by' => $this->actor->id, 'revision' => 1, 'bank_name' => 'PRIVATE-BANK-NOT-IN-SCOPE', 'country' => 'MZ', 'currency' => 'MZN',
'beneficiary' => 'PRIVATE-BANK-HOLDER', 'account_identifier' => 'BANK-FULL-NEVER-EXPORT', 'evidence_reference' => 'PRIVATE-BANK-EVIDENCE', 'reason' => 'Synthetic bank record outside the approved audit scope.', 'created_at' => now()]);
$snapshot = [...$this->f['order']->snapshot, 'bank_snapshot' => ['account_identifier' => 'BANK-NESTED-NEVER-EXPORT'], 'api_key' => 'API-KEY-NEVER-EXPORT'];
// Synthetic exclusion markers only; documentary values and financial amounts remain unchanged.
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode($snapshot, JSON_THROW_ON_ERROR)]);
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'people.application.created',
'after' => ['candidate_document' => 'PEOPLE-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id, 'action' => 'organization.profile',
'before' => null, 'after' => ['name' => 'AUDIT-PROFILE-NAME', 'permissions' => ['procurement'], 'password' => 'PASSWORD-NEVER-EXPORT', 'unmapped_private_payload' => 'UNKNOWN-PRIVATE-NEVER-EXPORT'], 'created_at' => now()]);
$sources = collectedPrivateAuditSources($this->actor, ['configuration', 'purchasing', 'stock', 'finance']);
$body = json_encode($sources, JSON_THROW_ON_ERROR);
expect($body)->toContain('AUDIT-LEGAL-NAME')->toContain('AUDIT-LOCATION')->toContain('AUDIT-PROFILE-NAME')
->not->toContain('BANK-FULL-NEVER-EXPORT')->not->toContain('BANK-NESTED-NEVER-EXPORT')
->not->toContain('PRIVATE-BANK-NOT-IN-SCOPE')->not->toContain('PRIVATE-BANK-EVIDENCE')
->not->toContain('API-KEY-NEVER-EXPORT')->not->toContain('PASSWORD-NEVER-EXPORT')
->not->toContain('PEOPLE-PRIVATE-NEVER-EXPORT')->not->toContain('UNKNOWN-PRIVATE-NEVER-EXPORT');
foreach ($sources['configuration:users']['rows'] as $user) {
expect($user)->not->toHaveKey('password')->not->toHaveKey('two_factor_secret')->not->toHaveKey('remember_token');
}
$event = collect($sources['configuration:audit_logs']['rows'])->firstWhere('action', 'organization.profile');
expect($event)->toHaveKey('after_projected')->not->toHaveKey('after');
});
test('purchasing audit includes supplier follow up events without bank events or foreign company history', function () {
$included = ['supplier.created', 'supplier.updated', 'supplier.reviewed', 'supplier.document_uploaded', 'supplier.document_downloaded',
'supplier_evaluation.approved', 'supplier_improvement.closed', 'supplier_response.decided'];
$excluded = ['supplier.bank_viewed', 'supplier.bank_proposed', 'supplier.bank_approved', 'supplier.bank_rejected', 'supplier.future_private_action'];
$foreign = Tenant::query()->create(['name' => 'FOREIGN-SUPPLIER-AUDIT']);
$foreignActor = User::factory()->create(['tenant_id' => $foreign->id]);
foreach ([...$included, ...$excluded] as $action) {
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id,
'action' => $action, 'after' => ['evidence' => 'SYNTHETIC-PRIVATE-PAYLOAD'], 'created_at' => now()]);
AuditLog::query()->create(['tenant_id' => $foreign->id, 'user_id' => $foreignActor->id, 'action' => $action,
'after' => ['evidence' => 'FOREIGN-SYNTHETIC-PRIVATE-PAYLOAD'], 'created_at' => now()]);
}
$before = DB::table('audit_logs')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['purchasing']);
$events = $sources['purchasing:audit_logs']['rows'];
foreach ($included as $action) {
$matches = array_values(array_filter($events, fn ($row) => $row['action'] === $action));
expect($matches)->toHaveCount(1)
->and((int) $matches[0]['tenant_id'])->toBe($this->actor->tenant_id)
->and($matches[0])->not->toHaveKey('after')->not->toHaveKey('before');
}
expect(array_column($events, 'action'))->not->toContain(...$excluded)
->and(json_encode($events, JSON_THROW_ON_ERROR))->not->toContain('SYNTHETIC-PRIVATE-PAYLOAD')
->and(DB::table('audit_logs')->orderBy('id')->get()->toJson())->toBe($before);
foreach (['stock', 'finance', 'configuration'] as $family) {
$other = collectedPrivateAuditSources($this->actor, [$family]);
expect(array_column($other[$family.':audit_logs']['rows'], 'action'))->not->toContain(...$included);
}
});
test('audit links planning cancellation and warehouse return events to their own source family', function () {
$families = ['purchasing' => ['planning.created', 'planning.linked', 'purchase_control.approved', 'cancellation.approved',
'order_cancellation.approved', 'order_cancellation_policy.approved'],
'stock' => ['warehouse_return.prepared', 'warehouse_return.confirmed', 'warehouse_return.cancelled']];
foreach ($families as $actions) {
foreach ($actions as $action) {
AuditLog::query()->create(['tenant_id' => $this->actor->tenant_id, 'user_id' => $this->actor->id,
'action' => $action, 'after' => ['synthetic' => true], 'created_at' => now()]);
}
}
$before = DB::table('audit_logs')->orderBy('id')->get()->toJson();
$sources = collectedPrivateAuditSources($this->actor, ['purchasing', 'stock', 'finance', 'configuration']);
foreach ($families as $family => $actions) {
expect(array_column($sources[$family.':audit_logs']['rows'], 'action'))->toContain(...$actions);
foreach (array_diff(['purchasing', 'stock', 'finance', 'configuration'], [$family]) as $other) {
expect(array_column($sources[$other.':audit_logs']['rows'], 'action'))->not->toContain(...$actions);
}
}
expect(DB::table('audit_logs')->orderBy('id')->get()->toJson())->toBe($before);
});
test('private audit exposes installed empty data separately from uninstalled optional common sources without calculations or writes', function () {
$before = [];
foreach (['budget_entries', 'stock_movements', 'external_payments', 'invoices', 'purchase_orders', 'audit_logs'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$sources = collectedPrivateAuditSources($this->actor, ['finance']);
expect($sources['finance:external_payments']['state'])->toBe('available')
->and($sources['finance:external_payments']['rows'])->toBe([]);
if (! DB::getSchemaBuilder()->hasTable('pa_obligations')) {
expect($sources['finance:pa_obligations']['state'])->toBe('not_installed')
->and($sources['finance:pa_obligations']['rows'])->toBeNull();
}
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('private audit includes versioned import document metadata but excludes bank specific documents', function () {
foreach (['packing_list', 'bank_commitment', 'bank_support'] as $type) {
SupplyRecord::query()->create(['tenant_id' => $this->actor->tenant_id, 'kind' => 'import_document',
'record_key' => (string) Str::uuid(), 'version' => 1, 'state' => 'recorded',
'purchase_order_id' => $this->f['order']->id, 'created_by' => $this->actor->id,
'data' => ['type' => $type, 'reference' => 'SYNTHETIC-'.$type],
'snapshot' => ['evidence' => ['path' => 'PRIVATE-PATH-NEVER-EXPORT', 'sha256' => hash('sha256', $type)]],
'reason' => 'Synthetic metadata scope regression; no document download is requested.',
'operation_key' => (string) Str::uuid(), 'input_hash' => hash('sha256', $type), 'created_at' => now()]);
}
$sources = collectedPrivateAuditSources($this->actor, ['purchasing']);
$rows = $sources['purchasing:supply_records']['rows'];
expect($rows)->toHaveCount(1)
->and($rows[0]['data']['type'])->toBe('packing_list')
->and($rows[0]['version'])->toBe(1)
->and($rows[0]['purchase_order_id'])->toBe($this->f['order']->id)
->and(json_encode($rows, JSON_THROW_ON_ERROR))->not->toContain('bank_commitment')->not->toContain('bank_support')->not->toContain('PRIVATE-PATH-NEVER-EXPORT');
});