@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Services\ExpenseAllocations;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
require_once __DIR__.'/../Support/PaymentFixture.php';
|
||||
|
||||
afterEach(function () {
|
||||
if ($this->committedExpenseReportFixture ?? 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('Expense report cleanup requires the disposable local PostgreSQL database.');
|
||||
}
|
||||
DB::statement('DROP SCHEMA public CASCADE');
|
||||
DB::statement('CREATE SCHEMA public');
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = paymentFixture(['Material', 'Serviços']);
|
||||
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]);
|
||||
foreach ([$this->f['author'], $this->f['validator']] as $actor) {
|
||||
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id,
|
||||
'person' => 'expense-qa-'.$actor->id, 'action' => 'view']);
|
||||
}
|
||||
$this->actingAs($this->f['author']);
|
||||
$this->payment = app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], $this->f['payment_data']);
|
||||
$this->actingAs($this->f['validator']);
|
||||
app(ExternalPaymentWorkflow::class)->review($this->f['validator'], $this->payment, 'confirmed', 'Conferência de evidência estritamente sintética');
|
||||
$this->service = app(ExpenseAllocations::class);
|
||||
$this->source = $this->service->source($this->f['validator'], $this->payment->id);
|
||||
$this->input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $this->source['fingerprint'],
|
||||
'reason' => 'Imputação explícita de Finanças no ensaio sintético',
|
||||
'allocations' => [['category' => 'Material', 'amount' => '15.00'], ['category' => 'Serviços', 'amount' => '25.00']]];
|
||||
});
|
||||
|
||||
test('Finance explicitly attributes a partial confirmed payment and replays without changing any financial source', function () {
|
||||
$this->withoutVite();
|
||||
$before = [];
|
||||
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'stock_movements', 'pa_commands'] as $table) {
|
||||
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
expect($this->source['categories'])->toBe(['Material', 'Serviços'])
|
||||
->and($this->service->projection($this->f['validator'], $this->payment->id)['state'])->toBe('unallocated');
|
||||
$url = '/pagamentos/'.$this->payment->id.'/categorias';
|
||||
$this->postJson($url, $this->input)->assertRedirect();
|
||||
$this->postJson($url, $this->input)->assertRedirect();
|
||||
$current = $this->service->current($this->payment->id);
|
||||
expect($current->data['allocations'])->toBe([['category' => 'Material', 'amount_minor' => '1500'], ['category' => 'Serviços', 'amount_minor' => '2500']])
|
||||
->and(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(1)
|
||||
->and(DB::table('audit_logs')->where('action', 'expense.allocation_recorded')->count())->toBe(1);
|
||||
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
|
||||
->component('payments/expense-allocation')->where('canWrite', true)->where('payment.amount_minor', '4000')
|
||||
->where('current.version', 1)->has('history.data', 1)->missing('payment.bank_snapshot')->missing('payment.external_reference')
|
||||
->missing('current.snapshot')->missing('current.operation_key')->missing('history.data.0.snapshot'));
|
||||
foreach ($before as $table => $rows) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||
}
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
if (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('Commit only the disposable expense report fixture.');
|
||||
}
|
||||
DB::commit();
|
||||
$this->committedExpenseReportFixture = true;
|
||||
}
|
||||
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('paymentInsights.currencies.0.amount_minor', '4000')->where('paymentInsights.category_attribution.coverage.allocated', 1)
|
||||
->where('paymentInsights.category_attribution.groups.data.0.amount_minor', '1500')
|
||||
->where('paymentInsights.category_attribution.groups.data.1.amount_minor', '2500')->has('paymentInsights.category_attribution.unassigned', 0));
|
||||
$csv = $this->get('/relatorios/despesa.csv')->assertOk()->assertDownload()->streamedContent();
|
||||
expect($csv)->toContain('Material;MZN;1;1500')->toContain('Serviços;MZN;1;2500');
|
||||
});
|
||||
|
||||
test('allocation rejects incorrect totals foreign categories stale sources and reused operations while retaining previous versions', function () {
|
||||
$actor = $this->f['validator'];
|
||||
$bad = $this->input;
|
||||
$bad['allocations'][0]['amount'] = '14.99';
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(ValidationException::class);
|
||||
$bad = $this->input;
|
||||
$bad['allocations'][0]['category'] = 'Categoria alheia';
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(ValidationException::class);
|
||||
$bad = [...$this->input, 'fingerprint' => str_repeat('0', 64)];
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(HttpException::class);
|
||||
$first = $this->service->save($actor, $this->payment->id, $this->input);
|
||||
$before = $first->fresh()->toArray();
|
||||
$next = [...$this->input, 'operation_key' => (string) Str::uuid(), 'version' => 1,
|
||||
'allocations' => [['category' => 'Material', 'amount' => '10.00'], ['category' => 'Serviços', 'amount' => '30.00']]];
|
||||
$second = $this->service->save($actor, $this->payment->id, $next);
|
||||
expect($second->version)->toBe(2)->and($first->fresh()->toArray())->toBe($before)
|
||||
->and($this->service->projection($actor, $this->payment->id)['allocations'][0]['amount_minor'])->toBe('1000');
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, [...$next, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, [...$this->input, 'reason' => 'Outro conteúdo com a mesma operação']))->toThrow(HttpException::class);
|
||||
});
|
||||
|
||||
test('allocation enforces current Finance access and refuses unavailable or unaudited payment sources', function () {
|
||||
$actor = $this->f['validator'];
|
||||
$this->actingAs($this->f['issuer']);
|
||||
expect(fn () => $this->service->save($this->f['issuer'], $this->payment->id, $this->input))->toThrow(HttpException::class);
|
||||
$this->actingAs($actor);
|
||||
DB::table('pa_access')->where('user_id', $actor->id)->delete();
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, $this->input))->toThrow(HttpException::class);
|
||||
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('incomplete confirmation or missing allocation audit keeps analytical attribution indeterminate', function () {
|
||||
$actor = $this->f['validator'];
|
||||
$this->service->save($actor, $this->payment->id, $this->input);
|
||||
expect($this->service->projection($actor, $this->payment->id)['state'])->toBe('allocated');
|
||||
DB::table('audit_logs')->where('action', 'expense.allocation_recorded')->delete();
|
||||
expect($this->service->projection($actor, $this->payment->id)['state'])->toBe('indeterminate');
|
||||
DB::table('external_payments')->where('id', $this->payment->id)->update(['reviewed_at' => null]);
|
||||
expect(fn () => $this->service->source($actor, $this->payment->id))->toThrow(HttpException::class);
|
||||
config(['expense-allocations.qa_enabled' => false]);
|
||||
expect(fn () => $this->service->save($actor, $this->payment->id, $this->input))->toThrow(HttpException::class);
|
||||
});
|
||||
|
||||
test('administrative read access does not grant Finance attribution and foreign payment identity stays private', function () {
|
||||
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
DB::table('pa_access')->insert(['tenant_id' => $admin->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $admin->id,
|
||||
'person' => 'expense-admin-qa', 'action' => 'view']);
|
||||
$this->actingAs($admin);
|
||||
expect($this->service->workspace($admin, $this->payment->id)['canWrite'])->toBeFalse();
|
||||
expect(fn () => $this->service->save($admin, $this->payment->id, $this->input))->toThrow(HttpException::class);
|
||||
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
|
||||
$foreign = expenseAllocationQaFixture();
|
||||
$this->actingAs($this->f['validator']);
|
||||
$this->getJson('/pagamentos/'.$foreign['payment']->id.'/categorias')->assertNotFound();
|
||||
});
|
||||
Reference in New Issue
Block a user