commit compras5 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 20:19:21 +02:00
parent 7486007fcf
commit d58b75c87a
57 changed files with 2803 additions and 116 deletions
+110 -4
View File
@@ -46,6 +46,7 @@ use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementContractInsights;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -274,7 +275,7 @@ function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $qu
return compact('agreement', 'binding', 'stock', 'warehouse');
}
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed) {
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed, bool $partial = false) {
$f = perOrderAgreement($this, '100.00', '1.000');
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
@@ -303,7 +304,9 @@ test('per order global contract sums different articles and freezes its own appr
'contract_key' => $contract->record_key, 'reference' => 'QA-CONTRACT-ARTICLE-'.($second ? '2' : '1')]));
$this->actingAs($this->finance);
$agreement = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
if (! $partial || ! $second) {
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
}
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
@@ -317,14 +320,17 @@ test('per order global contract sums different articles and freezes its own appr
$response->assertRedirect();
$order = PurchaseOrder::query()->sole();
foreach ($order->snapshot['agreement_bindings'] as $row) {
expect($row['contract']['checked_order_value_minor'])->toBe(20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
expect($row['contract']['checked_order_value_minor'])->toBe($partial ? 10000 : 20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
->and($row['contract']['version'])->toBe($contract->version)->and($row['checked_order_value_minor'])->toBe(10000);
}
$insights = app(ProcurementContractInsights::class)->build($this->buyer, Requisition::query()->whereKey($this->r->id));
expect($insights['coverage'][$partial ? 'partial' : 'contract'])->toBe(1)
->and($insights['currencies'][0]['amount_minor'])->toBe('20000');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Contrato global: QA-GLOBAL-CONTRACT');
$this->withoutVite()->get('/compras/fornecimento?view=contracts')->assertOk();
$this->get('/compras/fornecimento?view=agreements&linked_contract_key='.$contract->record_key)
->assertOk()->assertInertia(fn (Assert $page) => $page->component('supply/index')->has('records', 2)->where('linkedContractKey', $contract->record_key));
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false]]);
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false], ['200.00', true, true]]);
test('per order contract rejects incompatible association and stale approval without changing earlier versions', function () {
$f = perOrderAgreement($this);
@@ -848,6 +854,9 @@ test('award starts a new approval cycle and order freezes all agreed data', func
expect($award->approvals()->firstOrFail()->decision)->toBe('pending');
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
$order = issuePurchaseOrder($this, $award);
$contracts = app(ProcurementContractInsights::class)->build($this->buyer, Requisition::query()->whereKey($this->r->id));
expect($contracts['coverage']['without_contract'])->toBe(1)->and($contracts['coverage']['unknown'])->toBe(0)
->and($contracts['currencies'][0]['amount_minor'])->toBe('10000');
expect($order->number)->toMatch('/^OC-\d{4}-\d{6}$/')->and($order->total_minor)->toBe(10000);
expect($order->snapshot['supplier']['name'])->toBe('Fornecedor 0')->and($order->snapshot['quotation']['payment_terms'])->toBe('30 dias');
expect($order->snapshot['budget_checked'])->toBeFalse()->and($order->snapshot['development_only'])->toBeTrue();
@@ -1903,6 +1912,66 @@ test('native partial-order receipts and independent invoice validation consume e
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(10000)
->and(DB::table('budget_distribution_consumptions')->count())->toBe(0)
->and(DB::table('budget_consumptions')->count())->toBe(0);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/requisicoes/'.$this->r->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 2)->has('report.fulfilment.receipts', 2)->has('report.fulfilment.invoices', 2)
->where('report.orders.0.number', $first->number)->where('report.orders.1.number', $second->number)
->where('report.fulfilment.invoices.1.order_number', $second->number));
$csv = $this->get('/requisicoes/'.$this->r->id.'/relatorio.csv')->assertOk()->getContent();
expect($csv)->toContain($first->number)->toContain($second->number)->toContain('FT-PART-'.$first->id)->toContain('FT-PART-'.$second->id);
});
function commitNativeReviewReportFixture(object $test): void
{
if (DB::getDriverName() !== 'pgsql') {
return;
}
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Native review report requires an isolated committed test fixture.');
}
DB::commit();
$test->committedConsolidatedReportFixture = true;
}
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function () {
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
$service = app(\App\Services\ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), \Carbon\CarbonImmutable::now(), null, 'all');
expect($read()['coverage']['pending'])->toBe(1);
$due = \Carbon\CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$this->travelTo($due);
expect($read()['coverage']['pending'])->toBe(1);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'DELIVERY-QA', 'name' => 'Armazém sintético']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'DELIVERY-QA', 'name' => 'Material sintético', 'unit' => 'un']);
$payload = fn ($quantity) => ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'DELIVERY-'.Str::random(8),
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->sole()->id,
'received_quantity' => $quantity, 'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.400'));
$this->travel(1)->days();
$this->actingAs($this->buyer);
$late = $read();
expect($late['coverage']['pending_late'])->toBe(1)->and($late['records']['data'][0]['late_days'])->toBe(1)
->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.600'));
$this->actingAs($this->buyer);
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$complete = $read();
expect($complete['coverage']['completed_late'])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and($complete['records']['data'][0]['late_lines'][0]['completed_on'])->toBe(today()->toDateString())
->and([DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/relatorios?delivery_state=completed_late')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.completed_late', 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state=completed_late')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain('Recepção integral depois da data acordada')->toContain('0.000');
$this->travelBack();
});
function secondNativeOrderPartsOrigin(object $test): array
@@ -1939,12 +2008,24 @@ function secondNativeOrderPartsOrigin(object $test): array
return [$secondRequest, $quotes];
}
afterEach(function () {
if ($this->committedConsolidatedReportFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Consolidated report cleanup requires the disposable local PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
test('native consolidated order retains both origins and consumes a single invoice without duplicate stock or debt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$first = nativeOrderPartsAward($this);
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
$this->selection['delivery_date'] = today()->addWeeks(2)->toDateString();
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
@@ -1954,10 +2035,29 @@ test('native consolidated order retains both origins and consumes a single invoi
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$delivery = app(\App\Services\ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
\Carbon\CarbonImmutable::now()->addDays(8), null, 'all');
expect($delivery['coverage']['pending_late'])->toBe(1)->and($delivery['unknown_lines'])->toBe(0)
->and($delivery['records']['data'][0]['late_lines'])->toHaveCount(1)
->and($delivery['records']['data'][0]['late_lines'][0]['id'])->toBe($order->items()->where('requisition_item_id', $this->item->id)->value('id'));
$this->withoutVite();
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn (array $page) => count($page['props']['orderPartsSources']) === 2);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee($this->r->number)->assertSee($request->number)
->assertSee('Origens desta ordem')->assertSee('Controlo orçamental confirmado para as parcelas emitidas.');
expect(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereKey($request->id))->count())->toBe(1)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereIn('id', [$this->r->id, $request->id]))->count())->toBe(1)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereKey(999999))->count())->toBe(0);
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('Consolidated report snapshot requires an isolated committed test fixture.');
}
DB::commit();
$this->committedConsolidatedReportFixture = true;
}
$this->get('/relatorios?search='.urlencode($request->number))->assertOk()
->assertInertia(fn (Assert $page) => $page->where('records.data.0.order_number', $order->number));
$this->get('/relatorios?attention=approved_without_order&search='.urlencode($request->number))->assertOk()
->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
@@ -1985,16 +2085,22 @@ test('native consolidated order retains both origins and consumes a single invoi
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(15000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(15000)
->and(StockMovement::query()->count())->toBe(2)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(2000);
$this->get('/requisicoes/'.$request->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 1)->has('report.orders.0.origins', 2)->has('report.fulfilment.receipts', 1)->has('report.fulfilment.invoices', 1)
->where('report.orders.0.total_minor', 30000)->where('report.fulfilment.invoices.0.total_minor', '15000'));
$this->actingAs($this->owner);
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
$request->forceFill(['requester_id' => $this->head->id])->save();
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
expect(PurchaseOrder::query()->visibleTo($this->owner)->forRequisitions(Requisition::query()->whereKey($this->r->id))->count())->toBe(0);
// The search must respect every consolidated origin after a current department change,
// while keeping the native company-wide warehouse reader's receipt access.
$otherDepartment = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro departamento sintético']);
$request->forceFill(['department_id' => $otherDepartment->id])->save();
$this->actingAs($this->head)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 0));
$this->get('/requisicoes/'.$this->r->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 0)->has('report.fulfilment.receipts', 0)->where('report.fulfilment.invoices', null));
$this->actingAs($receiver)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
});