222 lines
16 KiB
PHP
222 lines
16 KiB
PHP
<?php
|
|
|
|
use App\Models\PurchaseAward;
|
|
use App\Models\Quotation;
|
|
use App\Models\Requisition;
|
|
use App\Services\ExternalPaymentWorkflow;
|
|
use App\Services\ProcurementPayableInsights;
|
|
use App\Services\ProcurementPaymentInsights;
|
|
use App\Services\SupplierBankWorkflow;
|
|
use App\Services\SupplierPayables;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Inertia\Testing\AssertableInertia as Assert;
|
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
|
|
require_once __DIR__.'/../Support/PaymentFixture.php';
|
|
|
|
test('supplier payment groups paginate independently while the export projection retains every group', function () {
|
|
$f = $this->f;
|
|
$this->actingAs($f['validator']);
|
|
// Synthetic invoice chains for read coverage; payment originals use the native registration/review workflow.
|
|
$originalAward = PurchaseAward::query()->findOrFail($f['order']->purchase_award_id);
|
|
$originalQuote = Quotation::query()->findOrFail($originalAward->quotation_id);
|
|
foreach (range(1, 21) as $index) {
|
|
$request = $f['r']->replicate();
|
|
$request->fill(['number' => 'SYNTHETIC-GROUP-'.$index])->save();
|
|
$supplier = $f['supplier']->replicate();
|
|
$supplier->fill(['name' => $index === 21 ? '=1+1' : 'Synthetic supplier '.$index, 'nuit' => (string) (500000000 + $index)])->save();
|
|
$quote = $originalQuote->replicate();
|
|
$quote->fill(['requisition_id' => $request->id, 'supplier_id' => $supplier->id, 'reference' => 'SYNTHETIC-GROUP-'.$index])->save();
|
|
$award = $originalAward->replicate();
|
|
$award->fill(['requisition_id' => $request->id, 'quotation_id' => $quote->id])->save();
|
|
$order = $f['order']->replicate();
|
|
$order->fill(['requisition_id' => $request->id, 'supplier_id' => $supplier->id, 'purchase_award_id' => $award->id, 'number' => 'SYNTHETIC-GROUP-'.$index,
|
|
'snapshot' => [...$f['order']->snapshot, 'supplier' => $supplier->only(['name', 'nuit'])]])->save();
|
|
$invoice = $f['invoice']->fresh()->replicate();
|
|
$invoice->fill(['supplier_id' => $supplier->id, 'purchase_order_id' => $order->id, 'number' => 'SYNTHETIC-GROUP-'.$index,
|
|
'snapshot' => [...$f['invoice']->snapshot, 'supplier' => $supplier->only(['name', 'nuit']), 'order_number' => $order->number]])->save();
|
|
$this->actingAs($f['issuer']);
|
|
$bank = app(SupplierBankWorkflow::class)->propose($f['issuer'], $supplier,
|
|
[...$f['bank_data'], 'account_identifier' => 'SYNTHETIC-GROUP-'.$index]);
|
|
foreach ([$f['author'], $f['validator']] as $reviewer) {
|
|
$this->actingAs($reviewer);
|
|
app(SupplierBankWorkflow::class)->review($reviewer, $bank, 'approved', 'Independent synthetic account review');
|
|
}
|
|
$this->actingAs($f['author']);
|
|
$payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $invoice,
|
|
[...$f['payment_data'], 'supplier_bank_detail_id' => $bank->id, 'external_reference' => 'SYNTHETIC-GROUP-'.$index]);
|
|
$this->actingAs($f['validator']);
|
|
app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Independent synthetic payment evidence review');
|
|
}
|
|
$service = app(ProcurementPaymentInsights::class);
|
|
$query = Requisition::query()->visibleTo($f['validator']);
|
|
$first = $service->build($f['validator'], clone $query, null, null, 1);
|
|
$last = $service->build($f['validator'], clone $query, null, null, 2);
|
|
$all = $service->build($f['validator'], clone $query, null, null, null);
|
|
expect($first['suppliers']['data'])->toHaveCount(20)->and($last['suppliers']['data'])->toHaveCount(1)
|
|
->and($all['suppliers']['data'])->toHaveCount(21)->and($all['suppliers']['total'])->toBe(21)
|
|
->and($first['currencies'])->toBe($last['currencies'])->and($all['currencies'][0]['amount_minor'])->toBe('84000')
|
|
->and($all['coverage']['confirmed_payments'])->toBe(21)
|
|
->and(array_intersect(array_column($first['suppliers']['data'], 'supplier_id'), array_column($last['suppliers']['data'], 'supplier_id')))->toBe([]);
|
|
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 supplier report fixture.');
|
|
}
|
|
DB::commit();
|
|
$this->committedInsightsFixture = true;
|
|
}
|
|
$before = [DB::table('external_payments')->count(), DB::table('audit_logs')->count()];
|
|
$this->get('/relatorios?supplier_page=2')->assertOk()->assertInertia(fn (Assert $page) => $page->has('paymentInsights.suppliers.data', 1)
|
|
->where('paymentInsights.suppliers.current_page', 2)->where('paymentInsights.suppliers.total', 21));
|
|
$csv = $this->get('/relatorios/despesa.csv?supplier_page=2')->assertOk()->assertDownload()->streamedContent();
|
|
expect(substr_count($csv, 'Synthetic supplier'))->toBe(20)->and($csv)->toContain(";'=1+1;MZN;1;4000")
|
|
->and([DB::table('external_payments')->count(), DB::table('audit_logs')->count()])->toBe($before);
|
|
});
|
|
|
|
beforeEach(function () {
|
|
$this->f = paymentFixture();
|
|
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'insights-fixture-instance']);
|
|
foreach ([$this->f['author'], $this->f['validator']] as $user) {
|
|
foreach (['view', 'prepare', 'validate'] as $action) {
|
|
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0,
|
|
'user_id' => $user->id, 'person' => 'insights-person-'.$user->id, 'action' => $action]);
|
|
}
|
|
}
|
|
$this->actingAs($this->f['author']);
|
|
$prepared = app(SupplierPayables::class)->engine($this->f['author'])->command('prepare', $this->f['invoice']->id, 'Preparação sintética para consulta', (string) Str::uuid());
|
|
$this->actingAs($this->f['validator']);
|
|
app(SupplierPayables::class)->engine($this->f['validator'])->command('validate', $prepared['proposal_id'], 'Conferência sintética independente', (string) Str::uuid());
|
|
});
|
|
|
|
afterEach(function () {
|
|
if ($this->committedInsightsFixture ?? false) {
|
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
|
|
throw new LogicException('Read report fixture cleanup requires the disposable database.');
|
|
}
|
|
DB::statement('DROP SCHEMA public CASCADE');
|
|
DB::statement('CREATE SCHEMA public');
|
|
}
|
|
});
|
|
|
|
test('financial insights use native positions across authorised filtered requests without modifying sources', function () {
|
|
$copy = $this->f['invoice']->replicate();
|
|
$copy->number = 'UNRECOGNISED-INSIGHTS';
|
|
$copy->save();
|
|
receiptFixture(); // Another company is never included.
|
|
$this->actingAs($this->f['validator']);
|
|
if (DB::getDriverName() === 'pgsql') {
|
|
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
|
throw new LogicException('Commit only the disposable report test fixture.');
|
|
}
|
|
DB::commit();
|
|
$this->committedInsightsFixture = true;
|
|
}
|
|
$tables = ['pa_obligations', 'pa_sources', 'pa_proposals', 'pa_events', 'pa_commands', 'invoices', 'external_payments', 'audit_logs'];
|
|
$before = [];
|
|
foreach ($tables as $table) {
|
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
|
}
|
|
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page
|
|
->where('payableInsights.coverage', ['invoices' => 2, 'recognised' => 1, 'unrecognised' => 1, 'indeterminate' => 0])
|
|
->where('payableInsights.currencies.0.currency', 'MZN')->where('payableInsights.currencies.0.principal_minor', '6000')
|
|
->where('payableInsights.currencies.0.balance_minor', '6000')->where('payableInsights.currencies.0.confirmed_payments_minor', '0')
|
|
->where('payableInsights.currencies.0.allocated_payments_minor', '0')->missing('payableInsights.bank_snapshot'));
|
|
$this->get('/relatorios?search=NO-MATCH-INSIGHTS')->assertOk()->assertInertia(fn (Assert $page) => $page
|
|
->where('payableInsights.coverage.invoices', 0)->where('payableInsights.currencies', []));
|
|
$csv = $this->get('/relatorios/obrigacoes.csv')->assertOk()->assertDownload();
|
|
expect($csv->streamedContent())->toContain('MZN;1;6000;0;0;6000')->toContain('2;1;1;0')->not->toContain('bank_snapshot');
|
|
$this->actingAs($this->f['issuer'])->get('/relatorios/obrigacoes.csv')->assertForbidden();
|
|
foreach ($tables as $table) {
|
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
|
|
}
|
|
});
|
|
|
|
test('a divergent native position is counted as indeterminate and never replaced by zero', function () {
|
|
DB::table('invoices')->where('id', $this->f['invoice']->id)->update(['total_minor' => 6001]);
|
|
$result = app(ProcurementPayableInsights::class)->build($this->f['validator'], Requisition::query()->visibleTo($this->f['validator']));
|
|
expect($result['coverage']['indeterminate'])->toBe(1)->and($result['coverage']['recognised'])->toBe(0)->and($result['currencies'])->toBe([]);
|
|
});
|
|
|
|
test('native imported history is counted once and pending payments do not reduce the reported balance', function () {
|
|
$f = paymentFixture();
|
|
config(['common-payables.history_enabled' => true]);
|
|
foreach ([$f['author'], $f['validator']] as $user) {
|
|
foreach (['view', 'prepare', 'validate'] as $action) {
|
|
DB::table('pa_access')->insert(['tenant_id' => $user->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $user->id,
|
|
'person' => 'history-insights-'.$user->id, 'action' => $action]);
|
|
}
|
|
}
|
|
$this->actingAs($f['author']);
|
|
$payments = app(ExternalPaymentWorkflow::class);
|
|
$payment = $payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '30.00']);
|
|
$this->actingAs($f['validator']);
|
|
$payments->review($f['validator'], $payment, 'confirmed', 'Conferência histórica sintética');
|
|
$this->actingAs($f['author']);
|
|
$payments->register($f['author'], $f['invoice'], [...$f['payment_data'], 'amount' => '10.00', 'external_reference' => 'INSIGHTS-PENDING']);
|
|
$adapter = app(SupplierPayables::class);
|
|
$proposal = $adapter->engine($f['author'])->command('prepare_history', $f['invoice']->id, 'Importação histórica sintética', (string) Str::uuid());
|
|
$this->actingAs($f['validator']);
|
|
$adapter->engine($f['validator'])->command('validate_history', $proposal['proposal_id'], 'Conferência independente do histórico', (string) Str::uuid());
|
|
$result = app(ProcurementPayableInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']));
|
|
expect($result['coverage']['recognised'])->toBe(1)->and($result['currencies'][0]['principal_minor'])->toBe('6000')
|
|
->and($result['currencies'][0]['confirmed_payments_minor'])->toBe('3000')->and($result['currencies'][0]['allocated_payments_minor'])->toBe('0')
|
|
->and($result['currencies'][0]['balance_minor'])->toBe('3000');
|
|
$confirmed = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->format('Y-m-d'), today()->format('Y-m-d'));
|
|
expect($confirmed['coverage']['confirmed_payments'])->toBe(1)
|
|
->and($confirmed['currencies'])->toBe([['currency' => 'MZN', 'count' => 1, 'amount_minor' => '3000']]);
|
|
$outside = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'));
|
|
expect($outside['currencies'])->toBe([]);
|
|
});
|
|
|
|
test('payment period follows confirmation instead of the original payment or requisition date and reports broken evidence', function () {
|
|
$f = paymentFixture();
|
|
foreach (['view', 'prepare', 'validate'] as $action) {
|
|
DB::table('pa_access')->insert(['tenant_id' => $f['validator']->tenant_id, 'company_id' => 0, 'unit_id' => 0,
|
|
'user_id' => $f['validator']->id, 'person' => 'period-person', 'action' => $action]);
|
|
}
|
|
$this->actingAs($f['author']);
|
|
$payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $f['payment_data']);
|
|
$this->travel(1)->days();
|
|
$this->actingAs($f['validator']);
|
|
app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Conferência sintética independente');
|
|
$query = Requisition::query()->visibleTo($f['validator']);
|
|
$service = app(ProcurementPaymentInsights::class);
|
|
expect($service->build($f['validator'], clone $query, today()->format('Y-m-d'), today()->format('Y-m-d'))['currencies'][0]['amount_minor'])->toBe('4000')
|
|
->and($service->build($f['validator'], clone $query, null, null)['suppliers']['data'][0])->toMatchArray([
|
|
'supplier_id' => $f['supplier']->id, 'supplier_name' => $f['invoice']->snapshot['supplier']['name'],
|
|
'currency' => 'MZN', 'count' => 1, 'amount_minor' => '4000'])
|
|
->and($service->build($f['validator'], clone $query, today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'))['currencies'])->toBe([]);
|
|
if (DB::getDriverName() === 'pgsql') {
|
|
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
|
|
throw new LogicException('Commit only the disposable report test fixture.');
|
|
}
|
|
DB::commit();
|
|
$this->committedInsightsFixture = true;
|
|
}
|
|
$this->get('/relatorios?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()
|
|
->assertInertia(fn (Assert $page) => $page->where('records.total', 0)
|
|
->where('paymentInsights.coverage.confirmed_payments', 1)->where('paymentInsights.currencies.0.amount_minor', '4000'));
|
|
$csv = $this->get('/relatorios/despesa.csv?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()->assertDownload();
|
|
expect($csv->streamedContent())->toContain('MZN;1;4000')->toContain('Nome conservado na factura')
|
|
->toContain((string) $f['supplier']->id)->not->toContain('bank_snapshot')->not->toContain('account_identifier');
|
|
$this->actingAs($f['issuer'])->get('/relatorios/despesa.csv')->assertForbidden();
|
|
$this->actingAs($f['validator']);
|
|
DB::table('external_payments')->where('id', $payment->id)->update(['reviewed_at' => null]);
|
|
$broken = $service->build($f['validator'], clone $query, null, null);
|
|
expect($broken['coverage']['indeterminate'])->toBe(1)->and($broken['currencies'])->toBe([]);
|
|
});
|
|
|
|
test('read composition rejects commands and revalidates withdrawn native financial access', function () {
|
|
$actor = $this->f['validator'];
|
|
$engine = app(SupplierPayables::class)->readEngine($actor);
|
|
$commands = DB::table('pa_commands')->count();
|
|
expect(fn () => $engine->command('prepare', $this->f['invoice']->id, 'Proibido na composição de leitura', (string) Str::uuid()))->toThrow(LogicException::class);
|
|
expect(DB::table('pa_commands')->count())->toBe($commands);
|
|
DB::table('pa_access')->where('user_id', $actor->id)->where('action', 'view')->delete();
|
|
expect(fn () => $engine->positionForSource($this->f['invoice']->id))->toThrow(HttpException::class);
|
|
expect(app(ProcurementPayableInsights::class)->build($actor, Requisition::query()->visibleTo($actor)))->toBeNull();
|
|
$this->actingAs($this->f['issuer']);
|
|
expect(app(ProcurementPayableInsights::class)->build($this->f['issuer'], Requisition::query()->visibleTo($this->f['issuer'])))->toBeNull();
|
|
});
|