@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\ProcurementReviewReportController;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use App\Services\QuotationExchange;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Events\QueryExecuted;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Base de teste inválida.');
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Worker não isolado.');
|
||||
}
|
||||
require __DIR__.'/../Support/QualificationFixture.php';
|
||||
$f = qualificationFixture();
|
||||
auth()->guard()->setUser($f['analyst']);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($f['analyst'], $f['r'], ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60.1234567890',
|
||||
'quoted_on' => today()->toDateString(), 'source' => '=FONTE-SINTETICA;sem execução']);
|
||||
$quote = $f['quote'];
|
||||
$quote->update(['currency' => 'USD', 'exchange_basis' => $exchange->basis($f['r'], 'USD')]);
|
||||
$line = $f['r']->items()->sole();
|
||||
$quote->items()->create(['tenant_id' => $quote->tenant_id, 'requisition_item_id' => $line->id, 'description' => $line->description,
|
||||
'quantity' => $line->quantity, 'unit_price_minor' => 10000, 'tax_rate' => 0, 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$before = DB::table('audit_logs')->count();
|
||||
$proof = null;
|
||||
$inspected = false;
|
||||
DB::listen(function (QueryExecuted $query) use (&$proof, &$inspected): void {
|
||||
if (! $inspected && str_contains($query->sql, 'from "quotations"')) {
|
||||
$inspected = true;
|
||||
$proof = DB::selectOne("select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only");
|
||||
}
|
||||
});
|
||||
$request = Request::create('/requisicoes/'.$f['r']->id.'/relatorio.csv');
|
||||
$request->setUserResolver(fn () => $f['issuer']);
|
||||
$response = app(ProcurementReviewReportController::class)->csv($request, $f['r'], app(ProcurementReviewReport::class), app(ProcurementReviewCsv::class));
|
||||
$content = $response->getContent();
|
||||
if ($response->getStatusCode() !== 200 || ! str_contains($content, '601235') || ! str_contains($content, "'=FONTE-SINTETICA")
|
||||
|| $proof?->isolation !== 'repeatable read' || $proof?->read_only !== 'on' || DB::table('audit_logs')->count() !== $before) {
|
||||
throw new RuntimeException('Exportação, exactidão, protecção de células ou leitura consistente não demonstradas.');
|
||||
}
|
||||
DB::table('users')->where('id', $f['issuer']->id)->update(['purchasing_role' => 'requester']);
|
||||
$revoked = false;
|
||||
try {
|
||||
app(ProcurementReviewReportController::class)->csv($request, $f['r'], app(ProcurementReviewReport::class), app(ProcurementReviewCsv::class));
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
$revoked = $error->getStatusCode() === 403;
|
||||
}
|
||||
if (! $revoked) {
|
||||
throw new RuntimeException('Revogação de acesso não reaplicada.');
|
||||
}
|
||||
echo json_encode(['result' => 'passed', 'checks' => ['controller_csv', 'exact_mzn_reference', 'formula_cell_protection', 'repeatable_read_read_only', 'no_audit_write', 'revoked_cached_actor']], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Base de teste inválida.');
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Worker não isolado.');
|
||||
}
|
||||
if (($argv[2] ?? '') === 'migrate') {
|
||||
if (Schema::getConnection()->getDatabaseName() !== $database || DB::connection('pgsql')->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Esquema fora da base isolada.');
|
||||
}
|
||||
Artisan::call('migrate', ['--database' => 'pgsql', '--force' => true]);
|
||||
echo json_encode(['isolated_schema_prepared' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
if (($argv[2] ?? '') === 'bank_prepare') {
|
||||
require __DIR__.'/../Support/PaymentFixture.php';
|
||||
$f = paymentFixture();
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'supplier' => $f['supplier']->id, 'bank_data' => $f['bank_data']], JSON_THROW_ON_ERROR);
|
||||
exit(0);
|
||||
}
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
require __DIR__.'/../Support/QualificationFixture.php';
|
||||
$f = qualificationFixture();
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['analyst']->id, 'request' => $f['r']->id], JSON_THROW_ON_ERROR);
|
||||
exit(0);
|
||||
}
|
||||
$input = json_decode($argv[3] ?? '', true, 16, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', (($argv[2] ?? '') === 'bank_write' ? 'sgc_bank_write_' : 'sgc_fx_write_').getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
if (($argv[2] ?? '') === 'bank_write') {
|
||||
$detail = app(SupplierBankWorkflow::class)->propose($actor, Supplier::query()->findOrFail($input['supplier']), $input['rate']);
|
||||
} else {
|
||||
app(QuotationExchange::class)->record($actor, Requisition::query()->findOrFail($input['request']), $input['rate']);
|
||||
}
|
||||
$status = 200;
|
||||
} catch (ValidationException) {
|
||||
$status = 422;
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
$status = $error->getStatusCode();
|
||||
}
|
||||
echo json_encode(['status' => $status, 'id' => isset($detail) ? $detail->id : null], JSON_THROW_ON_ERROR);
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Worker de conversão fora de QA.');
|
||||
}
|
||||
config(['inventory_conversion.qa_enabled' => true]);
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
require __DIR__.'/../Support/ReceiptFixture.php';
|
||||
$f = receiptFixture();
|
||||
$f['stock']->update(['unit' => 'un']);
|
||||
$body = receiptPayload($f, '1.000');
|
||||
$body['items'][0]['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de corrida', 'version' => 'QA-RACE-1'];
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['receiver']->id, 'order' => $f['order']->id, 'body' => $body], JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'write') {
|
||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_conversion_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::query()->findOrFail($input['order']), $input['body']);
|
||||
echo json_encode(['status' => 200, 'id' => $receipt->id], JSON_THROW_ON_ERROR);
|
||||
} catch (ValidationException) {
|
||||
echo json_encode(['status' => 422, 'id' => null], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
throw new InvalidArgumentException('Modo de worker inválido.');
|
||||
}
|
||||
foreach (['same_body', 'conflicting_body'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$workers = [];
|
||||
$db = DB::connection();
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
if ($i === 1 && $scenario === 'conflicting_body') {
|
||||
$input['body']['items'][0]['conversion']['numerator'] = '24';
|
||||
}
|
||||
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||
$workers[] = $worker;
|
||||
$worker->start();
|
||||
}
|
||||
$deadline = microtime(true) + 10;
|
||||
$blocked = 0;
|
||||
do {
|
||||
$db->select('select pg_stat_clear_snapshot()');
|
||||
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_conversion_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||
if ($blocked >= 2) {
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($blocked < 2) {
|
||||
throw new RuntimeException('Contenção real não demonstrada.');
|
||||
}
|
||||
$db->commit();
|
||||
$statuses = [];
|
||||
$ids = [];
|
||||
foreach ($workers as $worker) {
|
||||
$worker->wait();
|
||||
if (! $worker->isSuccessful()) {
|
||||
throw new RuntimeException($worker->getErrorOutput());
|
||||
}
|
||||
$result = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$statuses[] = $result['status'];
|
||||
if ($result['id'] !== null) {
|
||||
$ids[] = $result['id'];
|
||||
}
|
||||
}
|
||||
sort($statuses);
|
||||
$movements = $db->table('stock_movements')->where('tenant_id', $input['tenant'])->get();
|
||||
if ($statuses !== ($scenario === 'same_body' ? [200, 200] : [200, 422]) || count(array_unique($ids)) !== 1 || $movements->count() !== 1
|
||||
|| $db->table('goods_receipts')->where('purchase_order_id', $input['order'])->count() !== 1
|
||||
|| $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'receipt.confirmed')->count() !== 1) {
|
||||
throw new RuntimeException('Unicidade da recepção/movimento/auditoria não demonstrada.');
|
||||
}
|
||||
$movement = $movements->sole();
|
||||
$basis = json_decode($movement->snapshot, true, 32, JSON_THROW_ON_ERROR)['quantity_conversion'];
|
||||
if ((string) $movement->quantity_milli !== $basis['accepted_stock_milli'] || $basis['accepted_document_milli'] !== '1000') {
|
||||
throw new RuntimeException('Quantidades física/documental divergentes.');
|
||||
}
|
||||
echo json_encode(['conversion_scenario' => $scenario, 'real_lock_contention' => true, 'statuses' => $statuses, 'one_receipt_movement_audit' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
foreach ($workers as $worker) {
|
||||
if ($worker->isRunning()) {
|
||||
$worker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,12 +59,14 @@ test('bank revision does not hide a pending rejection but confirmation still rec
|
||||
$this->actingAs($this->f['issuer']);
|
||||
app(SupplierBankWorkflow::class)->propose($this->f['issuer'], $this->f['supplier'], [...$this->f['bank_data'], 'previous_id' => $this->f['bank']->id, 'account_identifier' => 'TEST-NEW-VERSION']);
|
||||
$this->actingAs($this->f['validator']);
|
||||
$this->get('/requisicoes/tarefas?module=finance')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1));
|
||||
$this->get('/requisicoes/tarefas?module=finance')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 2)
|
||||
->where('tasks.data', fn ($items) => collect($items)->pluck('task')->sort()->values()->all() === ['payment_review', 'supplier_bank_review']));
|
||||
$data = ['decision' => 'confirmed', 'reason' => 'Conferência sintética', 'independently_verified' => true];
|
||||
$this->postJson('/pagamentos/'.$this->payment->id.'/conferir', $data)->assertUnprocessable();
|
||||
expect($this->payment->fresh()->status)->toBe('pending');
|
||||
$this->post('/pagamentos/'.$this->payment->id.'/conferir', [...$data, 'decision' => 'rejected'])->assertRedirect();
|
||||
$this->get('/requisicoes/tarefas?module=finance')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
||||
$this->get('/requisicoes/tarefas?module=finance')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)
|
||||
->where('tasks.data.0.task', 'supplier_bank_review'));
|
||||
});
|
||||
|
||||
test('payment and invoice focus cannot cross companies', function () {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Department;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\DocumentaryQualificationWorkflow;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require_once __DIR__.'/../Support/QualificationFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = qualificationFixture();
|
||||
$this->url = '/requisicoes/'.$this->f['r']->id.'/relatorio.csv';
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
function reviewCsvRows(string $content): array
|
||||
{
|
||||
$file = fopen('php://temp', 'w+');
|
||||
fwrite($file, substr($content, 3));
|
||||
rewind($file);
|
||||
$rows = [];
|
||||
while (($row = fgetcsv($file, null, ';', '"', '')) !== false) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
fclose($file);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
test('complete review csv keeps missing scores distinct from zero and makes no business writes', function () {
|
||||
$before = AuditLog::query()->count();
|
||||
$response = $this->get($this->url)->assertOk()
|
||||
->assertHeader('Content-Type', 'text/csv; charset=UTF-8')
|
||||
->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||
->assertHeader('X-Content-Type-Options', 'nosniff');
|
||||
$rows = reviewCsvRows($response->getContent());
|
||||
expect($rows)->toContain(['Secção', 'Registo', 'Campo', 'Valor'])
|
||||
->toContain(['Proposta actual', (string) $this->f['quote']->id, 'Pontuação (centésimos de 10)', 'Não disponível'])
|
||||
->toContain(['Comparação actual', '', 'Comparação completa', 'Não'])
|
||||
->toContain(['Ordem', '', 'Registo disponível', 'Não'])
|
||||
->toContain(['Execução financeira', '', 'Consulta autorizada', 'Não'])
|
||||
->and(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
|
||||
test('complete review csv includes all proposals beyond the page boundary and protects spreadsheet cells', function () {
|
||||
$quote = $this->f['quote'];
|
||||
$this->f['r']->update(['justification' => " \t=HYPERLINK(\"https://example.invalid\")\nlinha;seguinte"]);
|
||||
for ($i = 0; $i < 21; $i++) {
|
||||
$supplier = $quote->supplier->replicate();
|
||||
$supplier->nuit = (string) (200000000 + $i);
|
||||
$supplier->save();
|
||||
$copy = $quote->replicate();
|
||||
$copy->supplier_id = $supplier->id;
|
||||
$copy->reference = 'PROPOSTA-ADICIONAL-'.$i;
|
||||
$copy->save();
|
||||
}
|
||||
$response = $this->get($this->url)->assertOk();
|
||||
$rows = collect(reviewCsvRows($response->getContent()));
|
||||
expect($rows->filter(fn ($row) => $row[0] === 'Proposta actual' && $row[2] === 'Referência'))->toHaveCount(22)
|
||||
->and($rows->first(fn ($row) => $row[0] === 'Pedido' && $row[2] === 'Fundamentação')[3])->toBe("' \t=HYPERLINK(\"https://example.invalid\")\nlinha;seguinte");
|
||||
});
|
||||
|
||||
test('complete review csv separates preserved documentary evidence from current proposals', function () {
|
||||
$workflow = app(DocumentaryQualificationWorkflow::class);
|
||||
$set = $workflow->define($this->f['issuer'], $this->f['r'], $this->f['definition']);
|
||||
$this->actingAs($this->f['analyst']);
|
||||
$workflow->assess($this->f['analyst'], $set, $this->f['assessment']);
|
||||
$this->f['quote']->update(['reference' => 'REFERENCIA-NOVA']);
|
||||
$rows = reviewCsvRows($this->get($this->url)->assertOk()->getContent());
|
||||
expect($rows)->toContain(['Proposta actual', (string) $this->f['quote']->id, 'Referência', 'REFERENCIA-NOVA'])
|
||||
->toContain(['Proposta na qualificação', (string) $this->f['quote']->id, 'Referência preservada', 'PROP-TEST'])
|
||||
->toContain(['Qualificação documental', (string) $set->id, 'Base corresponde às propostas actuais', 'Não']);
|
||||
expect(collect($rows)->contains(fn ($row) => $row[0] === 'Resposta documental' && $row[2] === 'Resultado' && $row[3] === 'pending'))->toBeTrue();
|
||||
});
|
||||
|
||||
test('complete review csv reapplies actor company department and guest access', function () {
|
||||
$this->actingAs($this->f['receiver'])->get($this->url)->assertForbidden();
|
||||
$other = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
|
||||
$this->actingAs(User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Admin]))->get($this->url)->assertNotFound();
|
||||
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro']);
|
||||
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get($this->url)->assertNotFound();
|
||||
$this->actingAs($this->f['analyst']);
|
||||
DB::table('users')->where('id', $this->f['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->get($this->url)->assertForbidden();
|
||||
auth()->logout();
|
||||
$this->get($this->url)->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('complete review csv excludes financial contents when permission is absent and preserves exact authorised amounts', function () {
|
||||
$report = app(ProcurementReviewReport::class)->build($this->f['issuer'], $this->f['r']->id);
|
||||
// Synthetic projection tests the export boundary independently of the database builder.
|
||||
$report['fulfilment']['invoices'] = [['id' => 99, 'number' => 'FACTURA-RESERVADA', 'status' => 'registered', 'issued_on' => '2026-11-21', 'total_minor' => '99999999999999', 'currency' => 'MZN']];
|
||||
$report['fulfilment']['payments'] = [['id' => 100, 'invoice_id' => 99, 'status' => 'confirmed', 'paid_on' => '2026-11-21', 'amount_minor' => '0', 'currency' => 'MZN']];
|
||||
$csv = app(ProcurementReviewCsv::class);
|
||||
expect($csv->render($report))->not->toContain('FACTURA-RESERVADA')->not->toContain('99999999999999');
|
||||
$report['fulfilment']['finance_visible'] = true;
|
||||
$rows = reviewCsvRows($csv->render($report));
|
||||
expect($rows)->toContain(['Factura', '99', 'Total (centavos)', '99999999999999'])
|
||||
->toContain(['Pagamento externo', '100', 'Montante (centavos)', '0']);
|
||||
});
|
||||
@@ -38,6 +38,7 @@ use App\Services\ProposalComparison;
|
||||
use App\Services\ProposalOpeningWorkflow;
|
||||
use App\Services\PurchaseControlPolicyWorkflow;
|
||||
use App\Services\PurchaseRevisionWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\RequisitionCatalogue;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Database\QueryException;
|
||||
@@ -47,6 +48,94 @@ use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
test('mixed currency comparison ranks the frozen mzn reference rather than raw foreign amounts', function () {
|
||||
$this->actingAs($this->finance);
|
||||
app(QuotationExchange::class)->record($this->finance, $this->r, [
|
||||
'operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Fonte sintética para comparação multimoeda',
|
||||
]);
|
||||
$quote = $this->quotes[0];
|
||||
$quote->update(['currency' => 'USD', 'exchange_basis' => app(QuotationExchange::class)->basis($this->r, 'USD')]);
|
||||
$result = app(ProposalComparison::class)->inspect($this->r);
|
||||
expect($result['ready'])->toBeTrue()->and($result['top_ids'])->toBe([$this->quotes[1]->id])
|
||||
->and($result['rows'][0]['total_minor'])->toBe(10000)
|
||||
->and($result['rows'][0]['reference_amounts']['total_minor'])->toBe(600000);
|
||||
});
|
||||
|
||||
test('foreign award approves and commits mzn while the immutable order keeps original currency and rate', function () {
|
||||
$this->actingAs($this->finance);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Fonte sintética congelada antes da proposta']);
|
||||
$quote = $this->quotes[0];
|
||||
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
||||
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
||||
$award = selectPurchaseAward($this);
|
||||
expect($award->total_minor)->toBe(6000);
|
||||
$order = issuePurchaseOrder($this, $award);
|
||||
expect($order->currency)->toBe('USD')->and($order->total_minor)->toBe(100)
|
||||
->and($order->items()->sole()->unit_price_minor)->toBe(100)
|
||||
->and($order->snapshot['reference_amounts']['total_minor'])->toBe(6000)
|
||||
->and($order->snapshot['exchange_basis'])->toBe($quote->exchange_basis);
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('USD')->assertSee('60.0000000000')->assertSee('Referência orçamental');
|
||||
});
|
||||
|
||||
test('foreign currency conversion determines final approval thresholds without changing estimate approvals', function () {
|
||||
$this->actingAs($this->finance);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '40000',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Taxa exclusivamente sintética para testar alçadas']);
|
||||
awardPrices($this, 5000000);
|
||||
$quote = $this->quotes[0];
|
||||
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
||||
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
||||
$before = $this->r->steps()->get()->toArray();
|
||||
$award = selectPurchaseAward($this);
|
||||
expect($award->total_minor)->toBe(4000000)->and($award->approvals()->count())->toBe(2)
|
||||
->and($this->r->steps()->get()->toArray())->toBe($before);
|
||||
});
|
||||
|
||||
test('foreign order cancellation reverses the mzn commitment while preserving the original foreign document', function () {
|
||||
$this->actingAs($this->finance);
|
||||
$exchange = app(\App\Services\QuotationExchange::class);
|
||||
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Taxa sintética para testar reversão do compromisso']);
|
||||
$quote = $this->quotes[0];
|
||||
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
||||
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
||||
Budget::query()->create(['tenant_id' => $this->tenant->id, 'cost_center_id' => $this->r->cost_center_id, 'year' => now()->year,
|
||||
'amount_minor' => 20000, 'includes_tax' => true, 'created_by' => $this->finance->id, 'approved_by' => $this->admin->id, 'reason' => 'Dotação sintética para cancelamento multimoeda']);
|
||||
DB::transaction(function () {
|
||||
app(ConflictGuard::class)->lockCompany($this->finance);
|
||||
app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000);
|
||||
});
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
expect((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->sum('committed_minor'))->toBe(6000);
|
||||
$original = $order->getAttributes();
|
||||
config(['order_cancellation.enabled' => true]);
|
||||
$admins = [$this->admin];
|
||||
foreach (range(1, 2) as $index) {
|
||||
$admins[] = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
}
|
||||
$this->actingAs($admins[0]);
|
||||
$policyWorkflow = app(\App\Services\OrderCancellationPolicyWorkflow::class);
|
||||
$policy = $policyWorkflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
|
||||
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Política exclusivamente sintética para cancelamento']);
|
||||
foreach (array_slice($admins, 1) as $reviewer) {
|
||||
$this->actingAs($reviewer);
|
||||
$policyWorkflow->review($reviewer, $policy, 'approved', 'Conferência sintética independente');
|
||||
}
|
||||
$this->actingAs($this->buyer);
|
||||
$flow = app(\App\Services\OrderCancellationWorkflow::class);
|
||||
$cancellation = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
|
||||
'reason' => 'Cancelamento sintético antes de qualquer execução', 'evidence' => 'Evidência documental exclusivamente sintética']);
|
||||
$this->actingAs($this->finance);
|
||||
$flow->decide($this->finance, $cancellation, 'approved', 'Conferência financeira sintética independente');
|
||||
expect((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->sum('committed_minor'))->toBe(0)
|
||||
->and((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->where('kind', 'order-cancel-'.$order->id)->value('committed_minor'))->toBe(-6000)
|
||||
->and($order->fresh()->getAttributes())->toBe($original);
|
||||
});
|
||||
|
||||
function awardPrices(object $test, int $firstPrice, int $taxRate = 0): void
|
||||
{
|
||||
$test->r->items()->update(['tax_rate' => $taxRate]);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetConsumption;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\BudgetWorkflow;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use App\Services\InvoiceWorkflow;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
require_once __DIR__.'/../Support/ProposalOpeningFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
// Entire source is synthetic and guarded by receiptFixture's isolated database check.
|
||||
$this->f = proposalOpeningFixture();
|
||||
$this->author = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->validator = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($this->author);
|
||||
$exchange = app(QuotationExchange::class);
|
||||
$exchange->record($this->author, $this->f['r'], ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '0.5',
|
||||
'quoted_on' => today()->toDateString(), 'source' => 'Taxa sintética para provar arredondamento cumulativo']);
|
||||
$basis = $exchange->basis($this->f['r'], 'USD');
|
||||
$requested = $this->f['r']->items()->sole();
|
||||
$requested->update(['quantity' => '3.000', 'unit_price_minor' => 1, 'subtotal_minor' => 3, 'total_minor' => 3]);
|
||||
$this->f['r']->update(['subtotal_minor' => 3, 'total_minor' => 3]);
|
||||
$quote = $this->f['quote'];
|
||||
$quote->update(['currency' => 'USD', 'subtotal_minor' => 3, 'tax_minor' => 0, 'total_minor' => 3, 'exchange_basis' => $basis]);
|
||||
$quote->items()->create(['tenant_id' => $quote->tenant_id, 'requisition_item_id' => $requested->id, 'description' => $requested->description,
|
||||
'quantity' => '3.000', 'unit_price_minor' => 1, 'tax_rate' => '0', 'subtotal_minor' => 3, 'tax_minor' => 0, 'total_minor' => 3]);
|
||||
$award = PurchaseAward::query()->create([...$this->f['award_attributes'], 'subtotal_minor' => 2, 'total_minor' => 2]);
|
||||
$orderAttributes = $this->f['order']->getAttributes();
|
||||
unset($orderAttributes['id']);
|
||||
$orderAttributes['purchase_award_id'] = $award->id;
|
||||
$orderAttributes['currency'] = 'USD';
|
||||
$orderAttributes['subtotal_minor'] = $orderAttributes['total_minor'] = 3;
|
||||
$orderAttributes['snapshot'] = [...$this->f['order']->snapshot, 'exchange_basis' => $basis, 'reference_amounts' => ['subtotal_minor' => 2, 'tax_minor' => 0, 'total_minor' => 2]];
|
||||
$this->order = PurchaseOrder::query()->create($orderAttributes);
|
||||
$this->line = $this->order->items()->create(['tenant_id' => $quote->tenant_id, 'requisition_item_id' => $requested->id,
|
||||
'description' => $requested->description, 'category' => $requested->category, 'purchase_type' => 'consumable', 'unit' => 'cx',
|
||||
'quantity' => '3.000', 'unit_price_minor' => 1, 'tax_rate' => '0', 'subtotal_minor' => 3, 'tax_minor' => 0, 'total_minor' => 3]);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->order, [
|
||||
'idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GUIA-USD', 'received_on' => today()->toDateString(), 'warehouse_id' => $this->f['warehouse']->id,
|
||||
'items' => [['purchase_order_item_id' => $this->line->id, 'received_quantity' => '3.000', 'accepted_quantity' => '3.000', 'quality_status' => 'compliant', 'stock_item_id' => $this->f['stock']->id]],
|
||||
]);
|
||||
$this->actingAs($this->author);
|
||||
Budget::query()->create(['tenant_id' => $this->author->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year,
|
||||
'amount_minor' => 100, 'includes_tax' => true, 'created_by' => $this->author->id, 'approved_by' => $this->validator->id, 'reason' => 'Dotação exclusivamente sintética']);
|
||||
DB::transaction(function () {
|
||||
app(ConflictGuard::class)->lockCompany($this->author);
|
||||
app(BudgetWorkflow::class)->record($this->author, $this->f['r'], 'reserve', 3, 3);
|
||||
app(BudgetWorkflow::class)->record($this->author, $this->f['r'], 'commit', 2, 2);
|
||||
});
|
||||
$this->invoiceData = ['number' => 'USD-1', 'issued_on' => today()->toDateString(), 'subtotal' => '0.01', 'tax' => '0.00', 'total' => '0.01',
|
||||
'items' => [['purchase_order_item_id' => $this->line->id, 'quantity' => '1.000', 'unit' => 'cx', 'unit_price' => '0.01', 'tax_rate' => '0']]];
|
||||
});
|
||||
|
||||
test('foreign partial invoices consume the frozen mzn commitment cumulatively including a calculated zero delta', function () {
|
||||
$effects = [];
|
||||
for ($i = 1; $i <= 3; $i++) {
|
||||
$this->actingAs($this->author);
|
||||
$invoice = app(InvoiceWorkflow::class)->register($this->author, $this->order, [...$this->invoiceData, 'number' => 'USD-'.$i]);
|
||||
$snapshot = $invoice->snapshot;
|
||||
$this->actingAs($this->validator);
|
||||
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
|
||||
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
|
||||
$invoice->refresh();
|
||||
$effects[] = (int) BudgetConsumption::query()->where('invoice_id', $invoice->id)->value('amount_minor');
|
||||
expect($invoice->total_minor)->toBe(1)->and($invoice->snapshot['currency'])->toBe('USD');
|
||||
expect($invoice->snapshot)->toBe($snapshot);
|
||||
}
|
||||
expect($effects)->toBe([1, 0, 1])->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe(2)
|
||||
->and(BudgetConsumption::query()->count())->toBe(3)->and((int) BudgetEntry::query()->sum('committed_minor'))->toBe(0);
|
||||
});
|
||||
|
||||
test('foreign external payment matches the original invoice currency with independent bank and payment confirmation', function () {
|
||||
$invoice = app(InvoiceWorkflow::class)->register($this->author, $this->order, $this->invoiceData);
|
||||
$this->actingAs($this->validator);
|
||||
app(InvoiceWorkflow::class)->validate($this->validator, $invoice);
|
||||
$supplier = Supplier::query()->findOrFail($this->order->supplier_id);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$bank = app(SupplierBankWorkflow::class)->propose($this->f['issuer'], $supplier, ['previous_id' => 0, 'bank_name' => 'Banco sintético', 'country' => 'MZ', 'currency' => 'USD',
|
||||
'beneficiary' => 'Titular sintético', 'account_identifier' => 'TEST-USD-ACCOUNT', 'evidence_reference' => 'Referência sintética', 'reason' => 'Somente para validação isolada']);
|
||||
foreach ([$this->author, $this->validator] as $reviewer) {
|
||||
$this->actingAs($reviewer);
|
||||
app(SupplierBankWorkflow::class)->review($reviewer, $bank, 'approved', 'Conferência independente sintética');
|
||||
}
|
||||
$this->actingAs($this->author);
|
||||
$workflow = app(ExternalPaymentWorkflow::class);
|
||||
$payment = $workflow->register($this->author, $invoice, ['supplier_bank_detail_id' => $bank->id, 'amount' => '0.01',
|
||||
'paid_on' => today()->toDateString(), 'external_reference' => 'USD-EXT-1', 'evidence_reference' => 'Evidência sintética de pagamento externo']);
|
||||
$this->actingAs($this->validator);
|
||||
$workflow->review($this->validator, $payment, 'confirmed', 'Conferência sintética da evidência');
|
||||
expect($payment->refresh()->currency)->toBe('USD')->and($payment->amount_minor)->toBe(1)
|
||||
->and($workflow->outstanding($invoice))->toBe(0)->and((int) BudgetConsumption::query()->sum('amount_minor'))->toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/QualificationFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = qualificationFixture();
|
||||
$this->actingAs($this->f['analyst']);
|
||||
$this->rateUrl = '/requisicoes/'.$this->f['r']->id.'/taxas-cambio';
|
||||
$this->rate = ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60.1234567890', 'quoted_on' => today()->toDateString(), 'source' => 'Fonte exclusivamente sintética para teste'];
|
||||
});
|
||||
|
||||
test('finance freezes an explicit process rate once and recovers the same operation without a second audit', function () {
|
||||
$this->post($this->rateUrl, $this->rate)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$before = AuditLog::query()->count();
|
||||
$this->post($this->rateUrl, $this->rate)->assertRedirect()->assertSessionHasNoErrors();
|
||||
expect(DB::table('quotation_exchange_rates')->count())->toBe(1)
|
||||
->and(DB::table('quotation_exchange_rates')->value('rate'))->toBe('60.1234567890')
|
||||
->and(AuditLog::query()->count())->toBe($before);
|
||||
$this->post($this->rateUrl, [...$this->rate, 'rate' => '61'])->assertStatus(409);
|
||||
$this->post($this->rateUrl, [...$this->rate, 'operation_id' => (string) Str::uuid(), 'rate' => '61'])->assertSessionHasErrors('currency');
|
||||
});
|
||||
|
||||
test('process exchange rates cannot be updated or deleted through native sql', function (string $command) {
|
||||
$this->post($this->rateUrl, $this->rate)->assertSessionHasNoErrors();
|
||||
expect(fn () => $command === 'update'
|
||||
? DB::table('quotation_exchange_rates')->update(['rate' => '1.0000000000'])
|
||||
: DB::table('quotation_exchange_rates')->delete())->toThrow(QueryException::class);
|
||||
})->with(['update', 'delete']);
|
||||
|
||||
test('only current finance authority can record rates in the visible process', function () {
|
||||
$this->actingAs($this->f['issuer'])->post($this->rateUrl, $this->rate)->assertForbidden();
|
||||
$this->actingAs($this->f['analyst']);
|
||||
DB::table('users')->where('id', $this->f['analyst']->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->post($this->rateUrl, $this->rate)->assertForbidden();
|
||||
$other = receiptFixture();
|
||||
$finance = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($finance)->post($this->rateUrl, $this->rate)->assertNotFound();
|
||||
expect(DB::table('quotation_exchange_rates')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('exchange rate refuses missing provenance zero negative and future-date assumptions', function (array $changes) {
|
||||
$this->post($this->rateUrl, [...$this->rate, ...$changes])->assertSessionHasErrors();
|
||||
expect(DB::table('quotation_exchange_rates')->count())->toBe(0);
|
||||
})->with([
|
||||
[['rate' => '0']], [['rate' => '-1']], [['rate' => '1e2']], [['source' => '']],
|
||||
[['quoted_on' => '2099-01-01']], [['currency' => 'MZN']], [['currency' => 'usd']],
|
||||
]);
|
||||
|
||||
test('foreign quotation preserves original prices and freezes finance provenance without accepting browser totals', function () {
|
||||
$this->post($this->rateUrl, $this->rate)->assertSessionHasNoErrors();
|
||||
$supplier = Supplier::query()->sole()->replicate();
|
||||
$supplier->nuit = '999999991';
|
||||
$supplier->save();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$url = '/requisicoes/'.$this->f['r']->id.'/cotacoes';
|
||||
$data = ['currency' => 'USD', 'supplier_id' => $supplier->id, 'reference' => 'USD-FICTICIO', 'delivery_days' => 5,
|
||||
'valid_until' => today()->addWeek()->toDateString(), 'payment_terms' => '30 dias', 'no_conflict' => true,
|
||||
'items' => [['requisition_item_id' => $this->f['r']->items()->sole()->id, 'unit_price' => '1.00']],
|
||||
'exchange_basis' => ['rate' => '1'], 'total_minor' => 999];
|
||||
$this->post($url, $data)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$quote = Quotation::query()->where('reference', 'USD-FICTICIO')->sole();
|
||||
expect($quote->currency)->toBe('USD')->and($quote->total_minor)->toBe(100)
|
||||
->and($quote->items()->sole()->unit_price_minor)->toBe(100)
|
||||
->and($quote->exchange_basis['rate'])->toBe('60.1234567890')
|
||||
->and(app(QuotationExchange::class)->amounts($quote)['total_minor'])->toBe(6012);
|
||||
$quote->update(['exchange_basis' => [...$quote->exchange_basis, 'rate' => '1.0000000000']]);
|
||||
$row = collect(app(ProposalComparison::class)->inspect($this->f['r'])['rows'])->firstWhere('id', $quote->id);
|
||||
expect($row['eligible'])->toBeFalse()->and($row['reference_amounts'])->toBeNull();
|
||||
});
|
||||
|
||||
test('foreign quotation without a finance rate fails atomically while legacy mzn still works', function () {
|
||||
$supplier = Supplier::query()->sole()->replicate();
|
||||
$supplier->nuit = '999999992';
|
||||
$supplier->save();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$data = ['currency' => 'EUR', 'supplier_id' => $supplier->id, 'reference' => 'SEM-TAXA', 'delivery_days' => 5,
|
||||
'valid_until' => today()->addWeek()->toDateString(), 'payment_terms' => '30 dias', 'no_conflict' => true,
|
||||
'items' => [['requisition_item_id' => $this->f['r']->items()->sole()->id, 'unit_price' => '1.00']]];
|
||||
$this->post('/requisicoes/'.$this->f['r']->id.'/cotacoes', $data)->assertSessionHasErrors('currency');
|
||||
expect(Quotation::query()->count())->toBe(1);
|
||||
unset($data['currency']);
|
||||
$this->post('/requisicoes/'.$this->f['r']->id.'/cotacoes', $data)->assertSessionHasNoErrors();
|
||||
expect(Quotation::query()->latest('id')->first()->currency)->toBe('MZN');
|
||||
});
|
||||
|
||||
test('quotation screen provides process-scoped rates and finance authority without changing the process', function () {
|
||||
$this->post($this->rateUrl, $this->rate)->assertSessionHasNoErrors();
|
||||
$before = AuditLog::query()->count();
|
||||
$this->get('/requisicoes/'.$this->f['r']->id.'/cotacoes')->assertInertia(fn (Assert $page) => $page
|
||||
->where('exchangeAvailable', true)->where('canRecordExchange', true)->has('exchangeRates', 1)
|
||||
->where('exchangeRates.0.rate', '60.1234567890'));
|
||||
expect(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
|
||||
test('exchange registration rolls back the frozen rate when its mandatory audit fails', function () {
|
||||
$audit = Mockery::mock(RequisitionWorkflow::class)->makePartial();
|
||||
$audit->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic audit failure'));
|
||||
app()->instance(RequisitionWorkflow::class, $audit);
|
||||
expect(fn () => app(QuotationExchange::class)->record($this->f['analyst'], $this->f['r'], $this->rate))->toThrow(RuntimeException::class);
|
||||
expect(DB::table('quotation_exchange_rates')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('foreign conversion overflow returns a form error and rolls back the whole quotation', function () {
|
||||
$this->post($this->rateUrl, [...$this->rate, 'rate' => '40000'])->assertSessionHasNoErrors();
|
||||
$supplier = Supplier::query()->sole()->replicate();
|
||||
$supplier->nuit = '999999993';
|
||||
$supplier->save();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$before = AuditLog::query()->count();
|
||||
$this->post('/requisicoes/'.$this->f['r']->id.'/cotacoes', ['currency' => 'USD', 'supplier_id' => $supplier->id,
|
||||
'reference' => 'LIMITE-SINTETICO', 'delivery_days' => 5, 'valid_until' => today()->addWeek()->toDateString(),
|
||||
'payment_terms' => '30 dias', 'no_conflict' => true,
|
||||
'items' => [['requisition_item_id' => $this->f['r']->items()->sole()->id, 'unit_price' => '1000000000.00']]])
|
||||
->assertSessionHasErrors('currency');
|
||||
expect(Quotation::query()->count())->toBe(1)->and(AuditLog::query()->count())->toBe($before);
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\User;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\InventoryDispositions;
|
||||
use App\Services\InventoryLots;
|
||||
use App\Services\InvoiceWorkflow;
|
||||
use App\Services\ReceiptStockMovement;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\StockWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
config(['inventory_conversion.qa_enabled' => true]);
|
||||
$this->f = receiptFixture();
|
||||
// New consistent synthetic process: 2 boxes x 100 MZN = 200 MZN. Original fixture is untouched.
|
||||
$request = $this->f['r']->replicate();
|
||||
$request->forceFill(['number' => 'QA-CONVERSION-REQUEST', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$requested = $this->f['r']->items()->sole()->replicate();
|
||||
$requested->forceFill(['requisition_id' => $request->id, 'quantity' => '2.000', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$oldAward = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id);
|
||||
$quote = Quotation::query()->findOrFail($oldAward->quotation_id)->replicate();
|
||||
$quote->forceFill(['requisition_id' => $request->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$award = $oldAward->replicate();
|
||||
$award->forceFill(['requisition_id' => $request->id, 'quotation_id' => $quote->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$order = $this->f['order']->replicate();
|
||||
$order->forceFill(['number' => 'QA-CONVERSION-ORDER', 'requisition_id' => $request->id, 'purchase_award_id' => $award->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$line = $this->f['line']->replicate();
|
||||
$line->forceFill(['purchase_order_id' => $order->id, 'requisition_item_id' => $requested->id, 'quantity' => '2.000', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
|
||||
$this->f['line'] = $line;
|
||||
$this->f['order'] = $order;
|
||||
$this->f['r'] = $request;
|
||||
$this->f['stock']->update(['unit' => 'un']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->url = '/ordens/'.$order->id.'/recepcoes';
|
||||
$this->conversion = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de teste', 'version' => 'QA-1'];
|
||||
$this->body = receiptPayload($this->f, '2.000');
|
||||
$this->body['items'][0]['conversion'] = $this->conversion;
|
||||
});
|
||||
|
||||
test('two boxes retain two documentary units and 200 MZN while crediting exactly 24 physical units once', function () {
|
||||
$id = $this->postJson($this->url, $this->body)->assertCreated()->json('id');
|
||||
$this->postJson($this->url, $this->body)->assertOk()->assertJsonPath('id', $id);
|
||||
$line = GoodsReceipt::query()->findOrFail($id)->items()->sole();
|
||||
$movement = StockMovement::query()->sole();
|
||||
expect($line->accepted_milli)->toBe(2000)->and($movement->quantity_milli)->toBe(24000)
|
||||
->and($this->f['order']->fresh()->total_minor)->toBe(20000)
|
||||
->and($this->f['line']->fresh()->unit_price_minor)->toBe(10000)
|
||||
->and($movement->snapshot['quantity_conversion']['source'])->toBe($this->conversion['source']);
|
||||
$result = DB::transaction(function () use ($line, $movement) {
|
||||
app(ConflictGuard::class)->lockCompany($this->f['receiver']);
|
||||
|
||||
return app(ReceiptStockMovement::class)->for($this->f['receiver'])->write($line->id, $movement->snapshot['inventory_source_hash']);
|
||||
});
|
||||
expect($result['replayed'])->toBeTrue()->and(StockMovement::query()->count())->toBe(1);
|
||||
$this->get('/recepcoes/'.$id.'/imprimir')->assertOk()->assertSee('Stock: 24,000')->assertSee('versão QA-1');
|
||||
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$this->actingAs($finance);
|
||||
$invoice = app(InvoiceWorkflow::class)->register($finance, $this->f['order'], [
|
||||
'number' => 'QA-BOXES', 'issued_on' => today()->toDateString(), 'subtotal' => '200.00', 'tax' => '0.00', 'total' => '200.00',
|
||||
'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '2.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']],
|
||||
]);
|
||||
expect($invoice->total_minor)->toBe(20000)->and($invoice->items()->sole()->quantity_milli)->toBe(2000);
|
||||
});
|
||||
|
||||
test('partial receipts freeze the factor article units source and version of the order line', function () {
|
||||
$body = $this->body;
|
||||
$body['items'][0]['received_quantity'] = $body['items'][0]['accepted_quantity'] = '1.500';
|
||||
$this->postJson($this->url, $body)->assertCreated();
|
||||
$next = receiptPayload($this->f, '0.500');
|
||||
$next['items'][0]['conversion'] = $this->conversion;
|
||||
$bad = $next;
|
||||
$bad['items'][0]['conversion']['numerator'] = '24';
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
$bad = $next;
|
||||
$bad['items'][0]['conversion']['version'] = 'QA-2';
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
$this->postJson($this->url, $next)->assertCreated();
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(24000)
|
||||
->and(app(ReceiptWorkflow::class)->progress($this->f['order'])['state'])->toBe('complete');
|
||||
});
|
||||
|
||||
test('missing source factor and nonrepresentable physical quantities never create a receipt', function () {
|
||||
$bad = $this->body;
|
||||
unset($bad['items'][0]['conversion']);
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
$bad = $this->body;
|
||||
$bad['items'][0]['conversion']['source'] = '';
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
$bad = $this->body;
|
||||
$bad['items'][0]['received_quantity'] = $bad['items'][0]['accepted_quantity'] = '0.001';
|
||||
$bad['items'][0]['conversion']['numerator'] = '1';
|
||||
$bad['items'][0]['conversion']['denominator'] = '2';
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('conversion is not enabled by its presence in a request and cannot escape the QA guard', function () {
|
||||
config(['inventory_conversion.qa_enabled' => false]);
|
||||
$this->postJson($this->url, $this->body)->assertUnprocessable();
|
||||
expect(StockMovement::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('legacy receipt facts retain the exact v1 hash and compatible replay without a conversion basis', function () {
|
||||
$this->f['stock']->update(['unit' => 'cx']);
|
||||
$body = $this->body;
|
||||
unset($body['items'][0]['conversion']);
|
||||
$this->postJson($this->url, $body)->assertCreated();
|
||||
$line = GoodsReceipt::query()->sole()->items()->sole();
|
||||
$movement = StockMovement::query()->sole();
|
||||
$facts = DB::table('goods_receipt_items AS l')->join('goods_receipts AS r', fn ($j) => $j->on('r.id', '=', 'l.goods_receipt_id')->on('r.tenant_id', '=', 'l.tenant_id'))
|
||||
->where('l.id', $line->id)->where('l.tenant_id', $this->f['tenant']->id)
|
||||
->select(['l.id', 'l.tenant_id', 'l.stock_item_id', 'l.received_milli', 'l.accepted_milli', 'l.rejected_milli', 'l.quality_status', 'l.notes',
|
||||
'l.snapshot AS line_snapshot', 'r.id AS receipt_id', 'r.purchase_order_id', 'r.received_by', 'r.warehouse_id', 'r.delivery_note', 'r.received_on', 'r.confirmed_at', 'r.snapshot AS receipt_snapshot'])->first();
|
||||
expect($movement->snapshot['inventory_source_hash'])->toBe(hash('sha256', json_encode((array) $facts, JSON_THROW_ON_ERROR)))
|
||||
->and($movement->quantity_milli)->toBe(2000)->and($line->snapshot)->not->toHaveKey('quantity_conversion');
|
||||
DB::transaction(function () use ($line, $movement) {
|
||||
app(ConflictGuard::class)->lockCompany($this->f['receiver']);
|
||||
expect(app(ReceiptStockMovement::class)->for($this->f['receiver'])->write($line->id, $movement->snapshot['inventory_source_hash'])['replayed'])->toBeTrue();
|
||||
});
|
||||
});
|
||||
|
||||
test('conversion cannot bypass actor eligibility and a failed audit rolls back the physical effect', function () {
|
||||
$this->actingAs($this->f['issuer'])->postJson($this->url, $this->body)->assertForbidden();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->mock(RequisitionWorkflow::class, function ($mock) {
|
||||
$mock->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
|
||||
});
|
||||
expect(fn () => app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $this->body))->toThrow(RuntimeException::class, 'Synthetic audit failure');
|
||||
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('a supplier return uses physical units and subtracts the exact documentary equivalent for invoicing', function () {
|
||||
$this->postJson($this->url, $this->body)->assertCreated();
|
||||
$source = GoodsReceipt::query()->sole()->items()->sole();
|
||||
supplyGrant($this->f['receiver'], ['warehouse', 'inventory_disposition_prepare']);
|
||||
supplyGrant($this->f['issuer'], ['procurement', 'inventory_disposition_review']);
|
||||
$data = ['kind' => 'supplier_return', 'reference' => 'QA-RETURN-BOX', 'stock_item_id' => $this->f['stock']->id,
|
||||
'warehouse_id' => $this->f['warehouse']->id, 'receipt_item_id' => $source->id, 'quantity' => '6.000'];
|
||||
$workflow = app(InventoryDispositions::class);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$draft = $workflow->save($this->f['receiver'], supplyInput($data));
|
||||
expect($draft->data['document_quantity_milli'])->toBe(500);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$approved = $workflow->save($this->f['issuer'], supplyInput([], 'approve', $draft));
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$workflow->save($this->f['receiver'], supplyInput(['event_on' => today()->toDateString(), 'evidence' => 'Guia sintética assinada para teste.'], 'execute', $approved));
|
||||
expect($workflow->returnedForReceipt($source->id))->toBe(6000)
|
||||
->and($workflow->returnedForOrderLine($this->f['line']->id))->toBe(500)
|
||||
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(18000)
|
||||
->and(app(ReceiptWorkflow::class)->progress($this->f['order'])['lines'][0]['effective_accepted_milli'])->toBe(1500);
|
||||
expect(fn () => $workflow->basis([...$data, 'quantity_milli' => 1]))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('lot allocation and quality follow converted physical quantities rather than boxes', function () {
|
||||
supplyGrant($this->f['issuer'], ['inventory_lot_prepare']);
|
||||
supplyGrant($this->f['receiver'], ['warehouse', 'inventory_lot_review']);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$lots = app(InventoryLots::class);
|
||||
$draft = $lots->save($this->f['issuer'], supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
|
||||
'requires_expiry' => true, 'minimum_remaining_days' => 0, 'lots' => []], 'prepare'));
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$lots->save($this->f['receiver'], supplyInput([], 'activate', $draft));
|
||||
$bad = $this->body;
|
||||
$bad['items'][0]['lots'] = [['code' => 'QA-BOX', 'expires_on' => today()->addYear()->toDateString(), 'quantity' => '2.000']];
|
||||
$this->postJson($this->url, $bad)->assertUnprocessable();
|
||||
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
|
||||
$bad['items'][0]['lots'][0]['quantity'] = '24.000';
|
||||
$this->postJson($this->url, $bad)->assertCreated();
|
||||
$context = $lots->context($this->f['stock']->id, $this->f['warehouse']->id);
|
||||
expect($context['reconciled'])->toBeTrue()->and($context['lots'][0]['quantity_milli'])->toBe(24000)
|
||||
->and($context['usable_milli'])->toBe(0);
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\CandidatePortalController;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\CandidateAccount;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
test('staff identity helper preserves the existing candidate controller inheritance and private staff method', function () {
|
||||
expect(is_subclass_of(CandidatePortalController::class, Controller::class))->toBeTrue();
|
||||
});
|
||||
|
||||
test('staff controllers resolve the web identity independently of a candidate identity in another realm', function () {
|
||||
$staff = new User;
|
||||
$candidate = new CandidateAccount;
|
||||
$request = Request::create('/empresa');
|
||||
$request->setUserResolver(fn ($guard) => $guard === 'web' ? $staff : $candidate);
|
||||
$controller = new class extends Controller
|
||||
{
|
||||
public function resolve(Request $request): User
|
||||
{
|
||||
return $this->staffIdentity($request);
|
||||
}
|
||||
};
|
||||
// A staff member without a company can still use the existing company setup.
|
||||
expect($controller->resolve($request))->toBe($staff)->and($staff->tenant_id)->toBeNull();
|
||||
});
|
||||
|
||||
test('staff controllers refuse candidate and missing identities without granting staff authority', function (bool $candidate) {
|
||||
$request = Request::create('/empresa');
|
||||
$request->setUserResolver(fn () => $candidate ? new CandidateAccount : null);
|
||||
$controller = new class extends Controller
|
||||
{
|
||||
public function resolve(Request $request): User
|
||||
{
|
||||
return $this->staffIdentity($request);
|
||||
}
|
||||
};
|
||||
try {
|
||||
$controller->resolve($request);
|
||||
$this->fail('A non-staff identity was accepted.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(403);
|
||||
}
|
||||
})->with([false, true]);
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use App\Services\WorkflowTaskInbox;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
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';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = paymentFixture();
|
||||
$this->workflow = app(SupplierBankWorkflow::class);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
});
|
||||
|
||||
function independentBankData(object $test, string $currency = 'USD'): array
|
||||
{
|
||||
return [...$test->f['bank_data'], 'account_key' => (string) Str::uuid(), 'previous_id' => 0,
|
||||
'currency' => $currency, 'bank_name' => 'Banco sintético '.$currency, 'account_identifier' => 'TEST-ACCOUNT-'.$currency];
|
||||
}
|
||||
|
||||
function approveIndependentBank(object $test, SupplierBankDetail $detail): void
|
||||
{
|
||||
foreach ([$test->f['author'], $test->f['validator']] as $actor) {
|
||||
$test->actingAs($actor);
|
||||
$test->workflow->review($actor, $detail, 'approved', 'Conferência independente sintética da conta');
|
||||
}
|
||||
}
|
||||
|
||||
test('adding an independent bank account preserves the approved legacy chain and its payment availability', function () {
|
||||
$original = $this->f['bank']->fresh()->getAttributes();
|
||||
$detail = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
expect($detail->account_key)->not->toBeNull()->and($detail->revision)->toBe(2)
|
||||
->and($this->workflow->currentAccounts($this->f['supplier']))->toHaveCount(2)
|
||||
->and($this->workflow->state($this->f['supplier']))->toBe('approved')
|
||||
->and($this->workflow->state($this->f['supplier'], $detail->account_key))->toBe('pending')
|
||||
->and($this->f['bank']->fresh()->getAttributes())->toBe($original);
|
||||
$this->actingAs($this->f['author']);
|
||||
$payment = app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], $this->f['payment_data']);
|
||||
expect($payment->supplier_bank_detail_id)->toBe($this->f['bank']->id)->and($payment->currency)->toBe('MZN');
|
||||
});
|
||||
|
||||
test('a newer independent account does not supersede another account awaiting independent reviews', function () {
|
||||
$usd = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
$eur = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this, 'EUR'));
|
||||
approveIndependentBank($this, $usd);
|
||||
expect($this->workflow->state($this->f['supplier'], $usd->account_key))->toBe('approved')
|
||||
->and($this->workflow->state($this->f['supplier'], $eur->account_key))->toBe('pending')
|
||||
->and($this->workflow->state($this->f['supplier']))->toBe('approved')
|
||||
->and(SupplierBankReview::query()->where('supplier_bank_detail_id', $usd->id)->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('revising the legacy account keeps independent approval and refuses payment against the superseded legacy version', function () {
|
||||
$usd = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
approveIndependentBank($this, $usd);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$replacement = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], [...$this->f['bank_data'],
|
||||
'previous_id' => $this->f['bank']->id, 'account_identifier' => 'LEGACY-REPLACEMENT']);
|
||||
expect($replacement->account_key)->toBeNull()->and($replacement->revision)->toBe(3)
|
||||
->and($this->workflow->state($this->f['supplier']))->toBe('pending')
|
||||
->and($this->workflow->state($this->f['supplier'], $usd->account_key))->toBe('approved');
|
||||
$this->actingAs($this->f['author']);
|
||||
expect(fn () => app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], $this->f['payment_data']))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('new-account response recovery preserves its identity even after a later revision without reactivating history', function () {
|
||||
$data = independentBankData($this);
|
||||
$original = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], $data);
|
||||
$replacement = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], [...$data, 'previous_id' => $original->id, 'account_identifier' => 'UPDATED-INDEPENDENT']);
|
||||
$before = AuditLog::query()->count();
|
||||
$recovered = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], array_reverse($data, true));
|
||||
expect($recovered->id)->toBe($original->id)->and($this->workflow->latest($this->f['supplier'], $data['account_key'])->id)->toBe($replacement->id)
|
||||
->and(SupplierBankDetail::query()->count())->toBe(3)->and(AuditLog::query()->count())->toBe($before);
|
||||
expect(fn () => $this->workflow->propose($this->f['issuer'], $this->f['supplier'], [...$data, 'currency' => 'EUR']))->toThrow(ValidationException::class);
|
||||
});
|
||||
|
||||
test('bank consultation selects the requested account while administration retains its original redacted view', function () {
|
||||
$data = independentBankData($this);
|
||||
$detail = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], $data);
|
||||
$url = '/fornecedores/'.$this->f['supplier']->id.'/dados-bancarios?account='.$detail->account_key;
|
||||
$this->get($url)->assertOk()->assertInertia(fn (Assert $page) => $page->where('current.id', $detail->id)
|
||||
->where('current.account_identifier', $data['account_identifier'])->where('accountKey', $detail->account_key)->has('accounts', 2));
|
||||
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$this->actingAs($admin)->get($url)->assertInertia(fn (Assert $page) => $page->where('current', null)
|
||||
->where('accounts.1.label', 'Conta #'.$detail->id.' · v'.$detail->revision)->where('canPropose', false)->where('canReview', false));
|
||||
$this->get('/fornecedores/'.$this->f['supplier']->id.'/dados-bancarios?account='.Str::uuid())->assertNotFound();
|
||||
});
|
||||
|
||||
test('independent bank root cannot be used to read another supplier or company', function () {
|
||||
$detail = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
$other = paymentFixture();
|
||||
$this->actingAs($other['issuer']);
|
||||
$this->get('/fornecedores/'.$other['supplier']->id.'/dados-bancarios?account='.$detail->account_key)->assertNotFound();
|
||||
$this->get('/fornecedores/'.$this->f['supplier']->id.'/dados-bancarios?account='.$detail->account_key)->assertNotFound();
|
||||
});
|
||||
|
||||
test('legacy bank workflow remains usable before the independent-account column is installed', function () {
|
||||
// The underlying fixture permits only the isolated test database.
|
||||
Schema::table('supplier_bank_details', function (Blueprint $table) {
|
||||
$table->dropIndex('supplier_bank_account_versions');
|
||||
$table->dropColumn('account_key');
|
||||
});
|
||||
expect($this->workflow->multipleReady())->toBeFalse()->and($this->workflow->state($this->f['supplier']))->toBe('approved');
|
||||
$legacy = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], [...$this->f['bank_data'], 'previous_id' => $this->f['bank']->id]);
|
||||
expect($legacy->fresh()->account_key)->toBeNull();
|
||||
try {
|
||||
$this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
$this->fail('An independent account was written without its schema.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(503);
|
||||
}
|
||||
});
|
||||
|
||||
test('payment selector requires a deliberate choice between two approved accounts in the invoice currency', function () {
|
||||
$detail = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this, 'MZN'));
|
||||
approveIndependentBank($this, $detail);
|
||||
$this->actingAs($this->f['author']);
|
||||
$this->get('/pagamentos?invoice_id='.$this->f['invoice']->id)->assertInertia(fn (Assert $page) => $page
|
||||
->where('invoices.0.bank_id', 0)->has('invoices.0.banks', 2)->missing('invoices.0.banks.0.account_identifier'));
|
||||
$payment = app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], [...$this->f['payment_data'], 'supplier_bank_detail_id' => $detail->id]);
|
||||
$this->actingAs($this->f['validator']);
|
||||
app(ExternalPaymentWorkflow::class)->review($this->f['validator'], $payment, 'confirmed', 'Conferência sintética da conta escolhida');
|
||||
expect($payment->refresh()->status)->toBe('confirmed')->and($payment->supplier_bank_detail_id)->toBe($detail->id)
|
||||
->and(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']))->toBe(2000);
|
||||
});
|
||||
|
||||
test('bank review tasks are per current account and disappear separately after each reviewers contribution', function () {
|
||||
$usd = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this));
|
||||
$eur = $this->workflow->propose($this->f['issuer'], $this->f['supplier'], independentBankData($this, 'EUR'));
|
||||
$this->actingAs($this->f['author']);
|
||||
$tasks = collect(app(WorkflowTaskInbox::class)->build($this->f['author'], 'procurement'))->where('task', 'supplier_bank_review');
|
||||
expect($tasks)->toHaveCount(2)->and($tasks->pluck('href')->all())->toContain('/fornecedores/'.$this->f['supplier']->id.'/dados-bancarios?account='.$usd->account_key);
|
||||
$this->workflow->review($this->f['author'], $usd, 'approved', 'Conferência sintética individual');
|
||||
$tasks = collect(app(WorkflowTaskInbox::class)->build($this->f['author'], 'procurement'))->where('task', 'supplier_bank_review');
|
||||
expect($tasks)->toHaveCount(1)->and($tasks->first()['href'])->toContain($eur->account_key);
|
||||
$this->actingAs($this->f['validator']);
|
||||
expect(collect(app(WorkflowTaskInbox::class)->build($this->f['validator'], 'procurement'))->where('task', 'supplier_bank_review'))->toHaveCount(2);
|
||||
});
|
||||
|
||||
test('independent-account proposal and mandatory audit roll back together', function () {
|
||||
$data = independentBankData($this);
|
||||
$audit = Mockery::mock(RequisitionWorkflow::class)->makePartial();
|
||||
$audit->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic audit failure'));
|
||||
app()->instance(RequisitionWorkflow::class, $audit);
|
||||
expect(fn () => $this->workflow->propose($this->f['issuer'], $this->f['supplier'], $data))->toThrow(RuntimeException::class);
|
||||
expect(SupplierBankDetail::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('native account forms normalise inputs redirect to the selected root and complete two independent reviews', function () {
|
||||
$data = independentBankData($this);
|
||||
$data['account_key'] = strtoupper($data['account_key']);
|
||||
$data['country'] = 'mz';
|
||||
$data['currency'] = 'usd';
|
||||
$data['account_identifier'] = ' test usd-123 ';
|
||||
$url = '/fornecedores/'.$this->f['supplier']->id.'/dados-bancarios';
|
||||
$target = $url.'?account='.strtolower($data['account_key']);
|
||||
$this->post($url, $data)->assertSessionHasNoErrors()->assertRedirect($target);
|
||||
$detail = SupplierBankDetail::query()->where('account_key', strtolower($data['account_key']))->sole();
|
||||
expect($detail->currency)->toBe('USD')->and($detail->country)->toBe('MZ')->and($detail->account_identifier)->toBe('TESTUSD-123');
|
||||
$reviewUrl = $url.'/'.$detail->id.'/validar';
|
||||
$decision = ['decision' => 'approved', 'reason' => 'Conferência sintética independente', 'independently_verified' => true];
|
||||
$this->post($reviewUrl, $decision)->assertForbidden();
|
||||
foreach ([$this->f['author'], $this->f['validator']] as $actor) {
|
||||
$this->actingAs($actor)->post($reviewUrl, $decision)->assertRedirect()->assertSessionHasNoErrors();
|
||||
}
|
||||
$this->get($target)->assertInertia(fn (Assert $page) => $page->where('state', 'approved')->where('current.id', $detail->id)->has('history', 1));
|
||||
expect($this->workflow->state($this->f['supplier']))->toBe('approved');
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierDocument;
|
||||
use App\Models\User;
|
||||
use App\Services\ConflictGuard;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
Storage::fake('supplier_documents');
|
||||
$this->supplier = Supplier::query()->sole();
|
||||
$this->bytes = 'EVIDENCIA-SINTETICA-ORIGINAL';
|
||||
$this->path = $this->supplier->tenant_id.'/'.$this->supplier->id.'/evidence.pdf';
|
||||
Storage::disk('supplier_documents')->put($this->path, $this->bytes);
|
||||
$this->document = SupplierDocument::query()->create([
|
||||
'tenant_id' => $this->supplier->tenant_id, 'supplier_id' => $this->supplier->id,
|
||||
'uploaded_by' => $this->f['issuer']->id, 'document_type' => 'other',
|
||||
'original_name' => 'evidence.pdf', 'path' => $this->path,
|
||||
'mime_type' => 'application/pdf', 'size' => strlen($this->bytes), 'sha256' => hash('sha256', $this->bytes),
|
||||
]);
|
||||
$this->url = '/fornecedores/'.$this->supplier->id.'/documentos/'.$this->document->id;
|
||||
});
|
||||
|
||||
test('supplier download returns verified private bytes and audits only successful preparation', function () {
|
||||
$before = AuditLog::query()->count();
|
||||
$response = $this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertHeader('Content-Type', 'application/octet-stream')
|
||||
->assertHeader('Content-Security-Policy', "default-src 'none'; sandbox");
|
||||
// Changes after response preparation must not replace the verified evidence.
|
||||
Storage::disk('supplier_documents')->put($this->path, 'SUBSTITUIDO-DEPOIS-DA-VERIFICACAO');
|
||||
expect($response->streamedContent())->toBe($this->bytes)
|
||||
->and(AuditLog::query()->count())->toBe($before + 1)
|
||||
->and(AuditLog::query()->latest('id')->first()->action)->toBe('supplier.document_downloaded');
|
||||
});
|
||||
|
||||
test('supplier upload preserves the authenticated author and reopens the native independent review', function () {
|
||||
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
|
||||
$bytes .= str_repeat("\0", 1100); // Meet the existing 1 KiB upload minimum.
|
||||
$this->post('/fornecedores/'.$this->supplier->id.'/documentos', ['document_type' => 'other',
|
||||
'file' => UploadedFile::fake()->createWithContent('evidence.png', $bytes)])->assertRedirect()->assertSessionHasNoErrors();
|
||||
$document = SupplierDocument::query()->latest('id')->first();
|
||||
expect($document->uploaded_by)->toBe($this->f['issuer']->id)
|
||||
->and($document->sha256)->toBe(hash('sha256', $bytes))
|
||||
->and($this->supplier->refresh()->status)->toBe('pending')
|
||||
->and($this->supplier->last_changed_by)->toBe($this->f['issuer']->id);
|
||||
});
|
||||
|
||||
test('supplier download refuses altered evidence of the same size without auditing a successful download', function () {
|
||||
$changed = $this->bytes;
|
||||
$changed[0] = 'X';
|
||||
Storage::disk('supplier_documents')->put($this->path, $changed);
|
||||
$before = AuditLog::query()->count();
|
||||
$this->get($this->url)->assertStatus(409);
|
||||
expect(AuditLog::query()->count())->toBe($before)
|
||||
->and(Storage::disk('supplier_documents')->get($this->path))->toBe($changed);
|
||||
});
|
||||
|
||||
test('supplier download refuses absent empty oversized and inconsistent-length evidence', function () {
|
||||
$disk = Storage::disk('supplier_documents');
|
||||
$disk->delete($this->path);
|
||||
$this->get($this->url)->assertNotFound();
|
||||
foreach (['', str_repeat('x', 2097153), $this->bytes.'extra'] as $content) {
|
||||
$disk->put($this->path, $content);
|
||||
$this->get($this->url)->assertStatus(409);
|
||||
}
|
||||
});
|
||||
|
||||
test('supplier download refuses references outside the owning supplier and traversal paths', function () {
|
||||
foreach (['999/999/evidence.pdf', $this->supplier->tenant_id.'/'.$this->supplier->id.'/../evidence.pdf'] as $path) {
|
||||
$this->document->update(['path' => $path]);
|
||||
$this->get($this->url)->assertStatus(409);
|
||||
}
|
||||
});
|
||||
|
||||
test('supplier document integrity does not grant documents to department heads or other companies', function () {
|
||||
$head = User::factory()->create(['tenant_id' => $this->supplier->tenant_id, 'department_id' => $this->f['issuer']->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get($this->url)->assertForbidden();
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['issuer'])->get($this->url)->assertNotFound();
|
||||
auth()->logout();
|
||||
$this->get($this->url)->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('supplier download reloads staff authority instead of trusting the cached authenticated object', function () {
|
||||
DB::table('users')->where('id', $this->f['issuer']->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->get($this->url)->assertForbidden();
|
||||
});
|
||||
|
||||
test('supplier upload rechecks authority after the company lock and removes only its uncommitted file on refusal', function () {
|
||||
$guard = Mockery::mock(ConflictGuard::class)->makePartial();
|
||||
$guard->shouldReceive('lockCompany')->once()->andReturnUsing(function () {
|
||||
DB::table('users')->where('id', $this->f['issuer']->id)->update(['purchasing_role' => 'requester']);
|
||||
});
|
||||
app()->instance(ConflictGuard::class, $guard);
|
||||
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=').str_repeat("\0", 1100);
|
||||
$this->post('/fornecedores/'.$this->supplier->id.'/documentos', ['document_type' => 'other',
|
||||
'file' => UploadedFile::fake()->createWithContent('revoked.png', $bytes)])->assertForbidden();
|
||||
expect(SupplierDocument::query()->count())->toBe(1)
|
||||
->and(Storage::disk('supplier_documents')->allFiles())->toBe([$this->path])
|
||||
->and($this->supplier->refresh()->status)->toBe('active');
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Inventory\QuantityConversion;
|
||||
|
||||
require_once __DIR__.'/../../packages/inventory-write/development/src/QuantityConversion.php';
|
||||
|
||||
test('explicit box conversion and partial quantities remain exact and reversible', function () {
|
||||
expect(QuantityConversion::toBase('2000', '12', '1'))->toBe('24000')
|
||||
->and(QuantityConversion::toBase('1500', '12', '1'))->toBe('18000')
|
||||
->and(QuantityConversion::toBase('500', '12', '1'))->toBe('6000')
|
||||
->and(QuantityConversion::fromBase('24000', '12', '1'))->toBe('2000')
|
||||
->and(QuantityConversion::toBase('2000', '3', '2'))->toBe('3000');
|
||||
});
|
||||
|
||||
test('a known zero quantity remains zero while the factor must still be explicit and positive', function () {
|
||||
expect(QuantityConversion::toBase('0', '12', '1'))->toBe('0');
|
||||
expect(fn () => QuantityConversion::toBase('0', '', '1'))->toThrow(InvalidArgumentException::class);
|
||||
});
|
||||
|
||||
test('conversion rejects nonrepresentable amounts instead of losing physical stock through rounding', function () {
|
||||
expect(fn () => QuantityConversion::toBase('1', '1', '2'))->toThrow(InvalidArgumentException::class)
|
||||
->and(fn () => QuantityConversion::fromBase('1', '12', '1'))->toThrow(InvalidArgumentException::class);
|
||||
});
|
||||
|
||||
test('conversion rejects absent zero negative and decimal assumptions', function (string $quantity, string $top, string $bottom) {
|
||||
expect(fn () => QuantityConversion::toBase($quantity, $top, $bottom))->toThrow(InvalidArgumentException::class);
|
||||
})->with([
|
||||
['1', '0', '1'], ['1', '1', '0'], ['1', '-1', '1'], ['-1', '1', '1'], ['1', '1.5', '1'], ['', '1', '1'],
|
||||
]);
|
||||
|
||||
test('conversion checks integer capacity before any host could cast or write the quantity', function () {
|
||||
expect(QuantityConversion::toBase((string) PHP_INT_MAX, '1', '1'))->toBe((string) PHP_INT_MAX);
|
||||
expect(fn () => QuantityConversion::toBase((string) PHP_INT_MAX, '2', '1'))->toThrow(InvalidArgumentException::class);
|
||||
expect(fn () => QuantityConversion::toBase('9999999999999999999', '1', '1'))->toThrow(InvalidArgumentException::class);
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import type { Page } from '@inertiajs/core';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
|
||||
import { QuotationExchangePanel } from '@/components/quotation-exchange-panel';
|
||||
import Comparison from '@/pages/quotations/show';
|
||||
import { money } from '@/types/procurement';
|
||||
|
||||
const rate = {
|
||||
id: 7,
|
||||
currency: 'USD',
|
||||
rate: '60.1234567890',
|
||||
quoted_on: '2026-11-21',
|
||||
source: 'Fonte sintética <script>ignorar</script>',
|
||||
recorded_by: 12,
|
||||
};
|
||||
const policy = {
|
||||
revision: 1,
|
||||
configured: true,
|
||||
minimum_proposals: 3,
|
||||
minimum_evaluators: 2,
|
||||
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
|
||||
};
|
||||
function render(
|
||||
Component: typeof Comparison | typeof QuotationExchangePanel,
|
||||
props: Record<string, unknown>,
|
||||
) {
|
||||
const page = {
|
||||
component: 'test',
|
||||
url: '/teste',
|
||||
version: null,
|
||||
props: { errors: {}, ...props },
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
} satisfies Page;
|
||||
return renderToString(
|
||||
<App initialPage={page} initialComponent={Component} />,
|
||||
);
|
||||
}
|
||||
|
||||
test.each([true, false])(
|
||||
'process rates retain provenance and restrict the finance form (%s)',
|
||||
(canRecord) => {
|
||||
const html = render(QuotationExchangePanel, {
|
||||
requisitionId: 42,
|
||||
rates: [rate],
|
||||
canRecord,
|
||||
});
|
||||
expect(html).toContain('60.1234567890');
|
||||
expect(html).toContain('Fonte sintética <script>');
|
||||
expect(html).not.toContain('<script>ignorar');
|
||||
expect(html.includes('Registar e congelar taxa')).toBe(canRecord);
|
||||
expect(html).toContain('duas casas decimais');
|
||||
},
|
||||
);
|
||||
|
||||
test('quotation matrix shows original currency alongside its separate mzn comparison reference', () => {
|
||||
const html = render(Comparison, {
|
||||
requisition: {
|
||||
id: 42,
|
||||
number: 'REQ-42',
|
||||
justification: 'Teste',
|
||||
items: [],
|
||||
},
|
||||
suppliers: [],
|
||||
canCreate: false,
|
||||
canEvaluate: false,
|
||||
ready: false,
|
||||
topIds: [],
|
||||
comparisonPolicy: policy,
|
||||
exchangeRates: [rate],
|
||||
exchangeAvailable: true,
|
||||
canRecordExchange: false,
|
||||
quotations: [
|
||||
{
|
||||
id: 1,
|
||||
reference: 'USD-ORIGINAL',
|
||||
supplier: { name: 'Fornecedor sintético' },
|
||||
currency: 'USD',
|
||||
subtotal_minor: 100,
|
||||
tax_minor: 0,
|
||||
total_minor: 100,
|
||||
exchange_basis: rate,
|
||||
reference_amounts: {
|
||||
subtotal_minor: 6012,
|
||||
tax_minor: 0,
|
||||
total_minor: 6012,
|
||||
},
|
||||
delivery_days: 5,
|
||||
valid_until: '2026-12-01',
|
||||
payment_terms: '30 dias',
|
||||
evaluations: [],
|
||||
evaluation_count: 0,
|
||||
eligible: true,
|
||||
conflict_blocked: false,
|
||||
score: null,
|
||||
items: [],
|
||||
ineligibility_reasons: [],
|
||||
commercial_terms: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).toContain('USD-ORIGINAL');
|
||||
expect(html).toContain('Referência:');
|
||||
expect(html).toContain('60.1234567890');
|
||||
expect(html).not.toContain('Registar e congelar taxa');
|
||||
});
|
||||
|
||||
test('foreign discount evidence uses its own currency and legacy amounts continue to default to mzn', () => {
|
||||
const html = renderToString(
|
||||
<QuotationCommercialTerms
|
||||
currency="USD"
|
||||
terms={{
|
||||
lines: [
|
||||
{
|
||||
requisition_item_id: 1,
|
||||
gross_unit_minor: 100,
|
||||
discount_type: 'amount',
|
||||
discount_value: '0.10',
|
||||
net_unit_minor: 90,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('USD/unidade');
|
||||
expect(html).not.toContain('MZN/unidade');
|
||||
expect(money(100)).toBe(money(100, 'MZN'));
|
||||
expect(money(100, 'USD')).not.toBe(money(100));
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import {
|
||||
ReceiptConversionFields,
|
||||
convertedQuantity,
|
||||
} from '@/components/receipt-conversion';
|
||||
|
||||
test('converted quantity display preserves exact millesimals beyond floating point precision', () => {
|
||||
expect(convertedQuantity('24000')).toBe('24,000');
|
||||
expect(convertedQuantity('1')).toBe('0,001');
|
||||
expect(convertedQuantity('999999999999999999')).toBe('999999999999999,999');
|
||||
expect(convertedQuantity('')).toBe('Não disponível');
|
||||
});
|
||||
|
||||
test('receipt conversion identifies both units and requires an explicit rational factor and documentary source', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ReceiptConversionFields
|
||||
documentUnit="cx"
|
||||
stockUnit="un"
|
||||
value={{
|
||||
numerator: '12',
|
||||
denominator: '1',
|
||||
source: 'Embalagem sintética',
|
||||
version: 'QA-1',
|
||||
}}
|
||||
onChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('Conversão de cx para un');
|
||||
expect(html).toContain('A compra conserva cx');
|
||||
expect(html).toContain('O stock e os lotes usam un');
|
||||
expect(html).toContain('Não há arredondamento automático');
|
||||
expect(html).toContain('Fonte do factor');
|
||||
expect(html).toContain('Versão da fonte');
|
||||
expect(html.match(/required=""/g)).toHaveLength(4);
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import type { Page } from '@inertiajs/core';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Bank from '@/pages/suppliers/bank';
|
||||
import Payments from '@/pages/payments/index';
|
||||
|
||||
const key = 'c1111111-1111-4111-8111-111111111111';
|
||||
const accounts = [
|
||||
{
|
||||
id: 1,
|
||||
key: null,
|
||||
revision: 1,
|
||||
label: 'Banco anterior · MZN',
|
||||
state: 'approved',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
key,
|
||||
revision: 2,
|
||||
label: 'Banco independente · USD',
|
||||
state: 'pending',
|
||||
},
|
||||
];
|
||||
function render(
|
||||
Component: typeof Bank | typeof Payments,
|
||||
props: Record<string, unknown>,
|
||||
) {
|
||||
const page = {
|
||||
component: 'test',
|
||||
url: '/teste',
|
||||
version: null,
|
||||
props: { errors: {}, ...props },
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
} satisfies Page;
|
||||
return renderToString(
|
||||
<App initialPage={page} initialComponent={Component} />,
|
||||
);
|
||||
}
|
||||
|
||||
test('supplier bank account links preserve the selected logical account and the independent creation action', () => {
|
||||
const html = render(Bank, {
|
||||
supplier: { id: 8, name: 'Fornecedor sintético' },
|
||||
current: null,
|
||||
currentId: 0,
|
||||
state: 'missing',
|
||||
history: [],
|
||||
reviews: [],
|
||||
canPropose: true,
|
||||
canReview: false,
|
||||
accounts,
|
||||
accountKey: null,
|
||||
multiAccountsAvailable: true,
|
||||
actorId: 12,
|
||||
});
|
||||
expect(html).toContain(`/fornecedores/8/dados-bancarios?account=${key}`);
|
||||
expect(html).toContain('Adicionar conta independente');
|
||||
expect(html).toContain('não substitui nem reactiva versões anteriores');
|
||||
});
|
||||
|
||||
test('legacy schema does not offer independent accounts or infer additional authority', () => {
|
||||
const html = render(Bank, {
|
||||
supplier: { id: 8, name: 'Fornecedor sintético' },
|
||||
current: null,
|
||||
currentId: 0,
|
||||
state: 'missing',
|
||||
history: [],
|
||||
reviews: [],
|
||||
canPropose: false,
|
||||
canReview: false,
|
||||
multiAccountsAvailable: false,
|
||||
actorId: 12,
|
||||
});
|
||||
expect(html).not.toContain('Adicionar conta independente');
|
||||
expect(html).not.toContain('Conferência independente');
|
||||
});
|
||||
|
||||
test('payment form leaves the deliberate choice empty when two approved same-currency accounts exist', () => {
|
||||
const html = render(Payments, {
|
||||
canManage: true,
|
||||
focusInvoiceId: 42,
|
||||
payments: {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
total: 0,
|
||||
per_page: 15,
|
||||
links: [],
|
||||
},
|
||||
invoices: [
|
||||
{
|
||||
id: 42,
|
||||
number: 'FT-42',
|
||||
currency: 'MZN',
|
||||
supplier_id: 8,
|
||||
supplier_name: 'Fornecedor sintético',
|
||||
total_minor: 100,
|
||||
outstanding_minor: 100,
|
||||
bank_id: 0,
|
||||
bank_revision: 0,
|
||||
bank_state: 'approved',
|
||||
banks: [
|
||||
{
|
||||
id: 1,
|
||||
revision: 1,
|
||||
currency: 'MZN',
|
||||
label: 'Conta A',
|
||||
state: 'approved',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
revision: 2,
|
||||
currency: 'MZN',
|
||||
label: 'Conta B',
|
||||
state: 'approved',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).toContain('Conta bancária na moeda da factura');
|
||||
expect(html).toContain('Conta A');
|
||||
expect(html).toContain('Conta B');
|
||||
expect(html).toContain('value="" selected=""');
|
||||
expect(html).toContain('Por seleccionar');
|
||||
});
|
||||
|
||||
test('bank identities and labels remain hidden when administration has no payment-management authority', () => {
|
||||
const html = render(Payments, {
|
||||
canManage: false,
|
||||
payments: {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
total: 0,
|
||||
per_page: 15,
|
||||
links: [],
|
||||
},
|
||||
invoices: [
|
||||
{
|
||||
id: 42,
|
||||
number: 'FT-42',
|
||||
currency: 'MZN',
|
||||
supplier_id: 8,
|
||||
supplier_name: 'Fornecedor sintético',
|
||||
total_minor: 100,
|
||||
outstanding_minor: 100,
|
||||
bank_id: 0,
|
||||
bank_revision: 0,
|
||||
bank_state: 'approved',
|
||||
banks: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).not.toContain('Conta bancária na moeda da factura');
|
||||
expect(html).not.toContain('Seleccione uma conta validada');
|
||||
});
|
||||
Reference in New Issue
Block a user