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

This commit is contained in:
2026-11-27 13:49:31 +02:00
parent dc73540558
commit e709d900d1
81 changed files with 5352 additions and 107 deletions
+238 -4
View File
@@ -41,6 +41,7 @@ use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv;
@@ -1490,7 +1491,7 @@ test('optional partial-order preparation consolidates two independently approved
});
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null, ?int $secondCentre = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
@@ -1508,15 +1509,30 @@ function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quot
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
$allocations = $request->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
if ($secondCentre !== null) {
if (count($allocations) !== 1 || $allocations[0]['subtotal_minor'] !== 10000 || $allocations[0]['total_minor'] !== 10000) {
throw new LogicException('Explicit two-centre fixture requires a single synthetic 100 MZN line.');
}
$allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 5000;
$allocations[] = [...$allocations[0], 'allocation_key' => (string) Str::uuid(), 'centre_id' => $secondCentre];
}
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
if ($quote->currency !== 'MZN') {
if (count($allocations) !== 1) {
throw new LogicException('Foreign synthetic fixture requires explicit single-line allocation.');
}
$reference = app(QuotationExchange::class)->amounts($quote);
$allocations[0]['subtotal_minor'] = $reference['subtotal_minor'];
$allocations[0]['total_minor'] = $reference['total_minor'];
}
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
@@ -1535,13 +1551,186 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$line = $prepared['sources'][0]['items'][0];
$line = $prepared['sources'][0]['reference_amounts'] ?? $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$this->actingAs($this->finance);
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic origin-specific FX, not a market rate.']);
$quote = $this->quotes[0];
$quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
$quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
'exchange_basis' => $exchange->basis($this->r, 'USD')]);
$award = nativeOrderPartsAward($this);
$flow = app(OrderPartsWorkflow::class);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$first = $flow->issue($this->buyer, $input);
expect($first->currency)->toBe('USD')->and($first->total_minor)->toBe(89)
->and($exchange->orderAmounts($first, 89, 0)['total_minor'])->toBe(134)
->and($flow->issue($this->buyer, $input)->id)->toBe($first->id);
$this->withoutVite();
$this->get('/ordens/'.$first->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('Synthetic origin-specific FX');
$second = $flow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
expect($second->total_minor)->toBe(134)->and($exchange->orderAmounts($second, 134, 0)['total_minor'])->toBe(201)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(335);
$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);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic material', 'unit' => 'un']);
$line = $first->items()->sole();
app(ReceiptWorkflow::class)->confirm($receiver, $first, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-PART',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '0.400', 'accepted_quantity' => '0.400',
'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
$key = $input['budget_sources'][0]['allocations'][0]['allocation_key'];
foreach ([['0.45', '0.68'], ['0.44', '0.66']] as $index => [$documentary, $reference]) {
$this->actingAs($this->finance);
$data = ['number' => 'FX-PART-'.$index, 'issued_on' => today()->toDateString(), 'subtotal' => $documentary,
'tax' => '0.00', 'total' => $documentary, 'items' => [['purchase_order_item_id' => $line->id, 'quantity' => '0.200']],
'reason' => 'Explicit Finance reference for a synthetic foreign partial invoice.',
'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $key, 'subtotal' => $reference, 'total' => $reference]]];
$bad = $data;
$bad['order_part_allocations'][0]['subtotal'] = $documentary;
$bad['order_part_allocations'][0]['total'] = $documentary;
expect(fn () => app(InvoiceWorkflow::class)->register($this->finance, $first, $bad))->toThrow(ValidationException::class);
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $first, $data);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
}
expect(Invoice::query()->count())->toBe(2)->and(StockMovement::query()->count())->toBe(1)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(134)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(201)
->and($quote->fresh()->exchange_basis['rate'])->toBe('1.5000000000');
});
test('native consolidated order preserves two different foreign origin rates in the document and reference', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
foreach ([[$this->r, $this->quotes[0], '1.5'], [$request, $quotes[0], '2']] as [$origin, $quote, $rate]) {
$this->actingAs($this->finance);
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $origin, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => $rate,
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic separate origin rate '.$rate]);
$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($origin, 'USD')]);
}
$first = nativeOrderPartsAward($this);
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
$sources = [...$a['sources'], ...$b['sources']];
$flow = app(OrderPartsWorkflow::class);
$preview = $flow->preview($this->buyer, ['sources' => $sources]);
expect($preview['can_issue'])->toBeTrue();
$order = $flow->issue($this->buyer, [...$a, 'sources' => $sources, 'fingerprint' => $preview['prepared']['fingerprint'],
'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]]);
expect($order->total_minor)->toBe(200)->and($order->snapshot['exchange_basis'])->toBeNull()
->and($exchange->orderAmounts($order, 200, 0)['total_minor'])->toBe(350)
->and(array_column(array_column($order->snapshot['exchange_sources'], 'exchange_basis'), 'rate'))->toBe(['1.5000000000', '2.0000000000']);
$this->withoutVite();
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('2.0000000000');
expect(fn () => $exchange->orderAmounts($order, 100, 0))->toThrow(HttpException::class);
$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);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic material', 'unit' => 'un']);
$lines = $order->items()->orderBy('id')->get();
app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-CONSOL',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()]);
$this->actingAs($this->finance);
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, ['number' => 'FX-CONSOL', 'issued_on' => today()->toDateString(),
'subtotal' => '2.00', 'tax' => '0.00', 'total' => '2.00', 'reason' => 'Explicit Finance allocation preserving both source rates.',
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '1.000'])->all(),
'order_part_allocations' => [
['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '1.50', 'total' => '1.50'],
['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '2.00', 'total' => '2.00']]]);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
expect($invoice->fresh()->status)->toBe('validated')->and($invoice->fresh()->total_minor)->toBe(200)
->and(Invoice::query()->count())->toBe(1)->and(StockMovement::query()->count())->toBe(2)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(350)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
});
test('native partial-order postgres history refuses source line and header rewriting after issuance', function () {
if (DB::getDriverName() !== 'pgsql' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('PostgreSQL isolated optional contract required.');
}
$award = nativeOrderPartsAward($this);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$before = [$order->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()];
foreach ([
fn () => DB::table('purchase_orders')->where('id', $order->id)->update(['total_minor' => 1]),
fn () => DB::table('purchase_order_items')->where('purchase_order_id', $order->id)->update(['quantity_offset_milli' => 1]),
fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->update(['snapshot' => '{}']),
fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->delete(),
] as $mutation) {
expect(fn () => DB::transaction($mutation))->toThrow(QueryException::class);
}
expect([$order->fresh()->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()])->toEqual($before);
});
test('native partial-order Finance amendment exposes a recoverable form and preserves original order and unissued reserve', function () {
if (! method_exists(BudgetControl::class, 'amendOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
'code' => 'NATIVE-AMEND', 'name' => 'Synthetic second centre']);
$this->actingAs($this->finance);
$budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic native amendment capacity.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$award = nativeOrderPartsAward($this, secondCentre: $centre->id);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$distribution = DB::table('budget_distributions')->where('requisition_id', $this->r->id)->first();
$plan = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$input['budget_sources'][0]['allocations'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'],
'subtotal_minor' => 2000, 'total_minor' => 2000], $plan['allocations']);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
$original = $order->toArray();
$this->withoutVite();
$this->get('/ordens/'.$order->id.'/reafectacao')->assertForbidden();
$this->actingAs($this->finance);
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn ($page) => $page['props']['canAmendOrderParts'] === true);
$this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'purchases/order-parts-amendment' && $page['encryptHistory'] === true);
$service = app(OrderPartsAmendments::class);
$sources = $service->sources($this->finance, $order);
$data = ['operation_key' => (string) Str::uuid(), 'reason' => 'Explicit native independent Finance allocation.',
'sources' => array_map(fn ($source) => [...$source, 'allocations' => array_map(fn ($row, $index) => [
'allocation_key' => $row['allocation_key'], 'subtotal' => $index === 0 ? '10.00' : '30.00',
'total' => $index === 0 ? '10.00' : '30.00'], $source['allocations'], array_keys($source['allocations']))], $sources)];
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
expect($order->fresh()->toArray())->toEqual($original)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000)
->and(DB::table('budget_order_commands')->where('kind', 'amend')->count())->toBe(1)
->and(array_column($service->sources($this->finance, $order)[0]['allocations'], 'total'))->toBe(['10.00', '30.00']);
$this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => count($page['props']['history']) === 1);
$data['operation_key'] = (string) Str::uuid();
$data['reason'] = 'A different amendment cannot reuse a stale source version.';
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
});
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
@@ -1812,3 +2001,48 @@ test('native explicit adoption keeps the old reserve unchanged and supports repl
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});
test('native explicit adoption of a foreign legacy award requires exact reference lines and preserves its original reserve history', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$this->actingAs($this->finance);
$id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic foreign legacy reserve.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic explicit legacy origin rate.']);
$quote = $this->quotes[0];
$quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
$quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
'exchange_basis' => $exchange->basis($this->r, 'USD')]);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
$this->actingAs($this->buyer);
$this->withoutVite();
$operation = (string) Str::uuid();
$url = '/adjudicacoes/'.$award->id.'/parcelas/adoptar';
$this->post($url, ['operation_key' => $operation])->assertSessionHasErrors('reference_lines');
$data = ['operation_key' => $operation, 'reference_lines' => [['line_id' => $this->item->id, 'subtotal' => '3.35', 'total' => '3.35']]];
$bad = $data;
$bad['reference_lines'][0]['total'] = '3.34';
$this->post($url, $bad)->assertSessionHasErrors('reference_lines');
expect(DB::table('budget_order_commands')->count())->toBe(0);
$this->post($url, $data)->assertRedirect('/ordens/preparar');
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$this->post($url, $data)->assertRedirect('/ordens/preparar');
expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
->and($order->total_minor)->toBe(89)->and($order->snapshot['reference_amounts']['total_minor'])->toBe(134)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(201)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(134)
->and(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1);
});