markTestSkipped('Select the explicitly authorized unpublished common source for isolated QA.'); } $this->f = receiptFixture(); budgetDistributionFixtureSchema(); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up(); $this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]); $this->actingAs($this->finance); $this->budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->f['r']->cost_center_id, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotação exclusivamente sintética para ordens parciais.']); $this->actingAs($this->reviewer); app(CommonBudget::class)->for($this->reviewer)->approve($this->budget); $this->actingAs($this->f['issuer']); }); /** Synthetic financial source contract; deliberately not a claim of native purchase issuance. */ function orderPartsSource(object $test, int $amount, string $allocation = 'same-key'): array { $source = unissuedOrderPartsSource($test->f, $amount); $line = $source->items()->sole(); $lines = [$line->id => ['subtotal_minor' => $amount, 'total_minor' => $amount, 'required_kind' => 'operating']]; $plan = [['allocation_key' => $allocation, 'line_id' => $line->id, 'centre_id' => $test->f['r']->cost_center_id, 'subtotal_minor' => $amount, 'total_minor' => $amount]]; $control = app(CommonBudget::class)->for($test->f['issuer']); $control->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid()); $award = $control->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid()); return ['origin' => $source->id, 'version' => 0, 'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => $allocation, 'subtotal_minor' => $amount, 'total_minor' => $amount]]]; } function orderPartsAmount(array $source, int $amount, int $version): array { $source['version'] = $version; $source['allocations'][0]['subtotal_minor'] = $amount; $source['allocations'][0]['total_minor'] = $amount; return $source; } function orderPartsInvoice(object $test, int $amount): Invoice { return Invoice::query()->create(['tenant_id' => $test->finance->tenant_id, 'purchase_order_id' => $test->f['order']->id, 'supplier_id' => $test->f['order']->supplier_id, 'created_by' => $test->finance->id, 'number' => 'QA-PARTS-'.Str::random(12), 'issued_on' => today(), 'status' => 'pending', 'subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount, 'snapshot' => ['synthetic_contract_fixture' => true]]); } function orderPartsBalance(object $test): array { $test->actingAs($test->finance); $balance = app(CommonBudget::class)->for($test->finance)->balance($test->budget); $test->actingAs($test->f['issuer']); return $balance; } test('one approved synthetic source commits forty then sixty without committing the unissued portion', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); $operation = (string) Str::uuid(); $input = [orderPartsAmount($source, 4000, 0)]; $control = app(CommonBudget::class)->for($this->f['issuer']); expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeFalse(); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000, 'consumed_minor' => 0, 'available_minor' => 90000]); expect($control->commitOrderParts($order, $input, $operation)['replayed'])->toBeTrue(); $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 1)], (string) Str::uuid()); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000, 'consumed_minor' => 0]); expect(DB::table('budget_order_commands')->count())->toBe(2)->and(DB::table('budget_order_bindings')->count())->toBe(2) ->and(Requisition::query()->findOrFail($source['origin'])->status)->toBe('approved'); }); test('two origins keep identical allocation keys separate and consume one invoice atomically', function () { $a = orderPartsSource($this, 10000); $b = orderPartsSource($this, 20000); $order = (string) Str::uuid(); app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$b, $a], (string) Str::uuid()); $this->actingAs($this->finance); $invoice = orderPartsInvoice($this, 15000); $input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 10000, 1)]; foreach ($input as &$source) { $source['allocations'][0]['order_key'] = $order; } unset($source); $operation = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->finance); $control->checkOrderPartsConsumption($input); expect(DB::table('budget_order_consumptions')->count())->toBe(0); $result = $control->consumeOrderParts($invoice->id, $input, $operation); expect($result['replayed'])->toBeFalse()->and($control->consumeOrderParts($invoice->id, array_reverse($input), $operation)['replayed'])->toBeTrue(); expect(DB::table('budget_order_consumptions')->count())->toBe(2)->and(Invoice::query()->whereKey($invoice->id)->count())->toBe(1) ->and(DB::table('budget_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(0); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 15000, 'consumed_minor' => 15000, 'available_minor' => 70000]); }); test('one bad source rejects the complete order before effects, phase or versions change', function () { $a = orderPartsSource($this, 10000); $b = orderPartsSource($this, 20000); $bad = orderPartsAmount($b, 20001, 0); $before = DB::table('budget_distribution_entries')->count(); expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts((string) Str::uuid(), [$a, $bad], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_order_bindings')->count())->toBe(0) ->and(DB::table('budget_distribution_entries')->count())->toBe($before) ->and(DB::table('budget_distributions')->where('phase', 'award')->count())->toBe(2); }); test('stale versions and changed replay amounts cannot issue another part', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); $key = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->f['issuer']); $control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], $key); expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 0)], (string) Str::uuid()))->toThrow(BudgetFailure::class) ->and(fn () => $control->commitOrderParts($order, [orderPartsAmount($source, 4001, 0)], $key))->toThrow(BudgetFailure::class); expect(DB::table('budget_order_commands')->count())->toBe(1); }); test('one invoice may consume two parts of the same source with one journal effect per allocation', function () { $source = orderPartsSource($this, 10000); $first = (string) Str::uuid(); $second = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->f['issuer']); $control->commitOrderParts($first, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid()); $control->commitOrderParts($second, [orderPartsAmount($source, 6000, 1)], (string) Str::uuid()); $input = orderPartsAmount($source, 2000, 2); $input['allocations'][0]['order_key'] = $first; $input['allocations'][] = ['allocation_key' => 'same-key', 'order_key' => $second, 'subtotal_minor' => 3000, 'total_minor' => 3000]; $this->actingAs($this->finance); $invoice = orderPartsInvoice($this, 5000); app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid()); expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2) ->and(DB::table('budget_distribution_entries')->where('kind', 'like', 'order-invoice-%')->count())->toBe(1); expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]); }); test('cancellation releases only its unconsumed issued part and never replenishes issuance capacity', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->f['issuer']); $control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid()); $key = (string) Str::uuid(); $input = [orderPartsAmount($source, 4000, 1)]; expect($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse() ->and($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue(); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]); expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class); $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid()); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 6000]); }); test('consumed orders reject cancellation and over-consumption without changing the invoice effect', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid()); $this->actingAs($this->finance); $input = orderPartsAmount($source, 5000, 1); $input['allocations'][0]['order_key'] = $order; $invoice = orderPartsInvoice($this, 5000); app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid()); $next = orderPartsAmount($source, 5001, 2); $next['allocations'][0]['order_key'] = $order; expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class); $this->actingAs($this->f['issuer']); expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]); }); test('mutating order commands require the current procurement actor and consuming requires Finance', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); $this->actingAs($this->finance); expect(fn () => app(CommonBudget::class)->for($this->finance)->commitOrderParts($order, [$source], (string) Str::uuid()))->toThrow(HttpException::class); $this->actingAs($this->f['issuer']); app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid()); $input = orderPartsAmount($source, 100, 1); $input['allocations'][0]['order_key'] = $order; expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->checkOrderPartsConsumption([$input]))->toThrow(HttpException::class); }); test('invalid shapes, duplicate sources and empty parts fail before a command is recorded', function () { $source = orderPartsSource($this, 10000); $control = app(CommonBudget::class)->for($this->f['issuer']); foreach ([[], [$source, $source], [orderPartsAmount($source, -1, 0)], [[...$source, 'version' => '0']], [[...$source, 'origin' => -1]]] as $input) { expect(fn () => $control->commitOrderParts((string) Str::uuid(), $input, (string) Str::uuid()))->toThrow(BudgetFailure::class); } expect(DB::table('budget_order_commands')->count())->toBe(0)->and(orderPartsBalance($this)['reserved_minor'])->toBe(10000); }); test('an explicit zero-cent native rounding remainder retains lineage without inventing another cent', function () { $source = orderPartsSource($this, 1); $first = (string) Str::uuid(); $remainder = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->f['issuer']); $control->commitOrderParts($first, [$source], (string) Str::uuid()); $control->commitOrderParts($remainder, [orderPartsAmount($source, 0, 1)], (string) Str::uuid()); $this->actingAs($this->finance); $invoice = orderPartsInvoice($this, 0); $input = orderPartsAmount($source, 0, 2); $input['allocations'][0]['order_key'] = $remainder; app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid()); expect(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->value('amount_minor'))->toBe(0) ->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 1, 'consumed_minor' => 0, 'available_minor' => 99999]); }); test('bad invoice allocation rolls back every origin and an unconsumed cancelled order cannot be invoiced', function () { $a = orderPartsSource($this, 10000); $b = orderPartsSource($this, 20000); $order = (string) Str::uuid(); $control = app(CommonBudget::class)->for($this->f['issuer']); $control->commitOrderParts($order, [$a, $b], (string) Str::uuid()); $this->actingAs($this->finance); $input = [orderPartsAmount($a, 5000, 1), orderPartsAmount($b, 20001, 1)]; foreach ($input as &$source) { $source['allocations'][0]['order_key'] = $order; } unset($source); $invoice = orderPartsInvoice($this, 25001); expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1); $this->actingAs($this->f['issuer']); $control->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid()); $this->actingAs($this->finance); $cancelled = orderPartsAmount($a, 100, 2); $cancelled['allocations'][0]['order_key'] = $order; expect(fn () => app(CommonBudget::class)->for($this->finance)->checkOrderPartsConsumption([$cancelled]))->toThrow(BudgetFailure::class); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 0, 'available_minor' => 100000]); }); test('operation identifiers cannot cross V1 and partial order contracts', function () { $source = orderPartsSource($this, 10000); $control = app(CommonBudget::class)->for($this->f['issuer']); $oldOperation = DB::table('budget_distribution_events')->value('operation_key'); expect(fn () => $control->commitOrderParts((string) Str::uuid(), [$source], $oldOperation))->toThrow(BudgetFailure::class); $operation = (string) Str::uuid(); $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 4000, 0)], $operation); $line = Requisition::query()->findOrFail($source['origin'])->items()->sole(); $lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $plan = [['allocation_key' => 'same-key', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]]; expect(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), $operation))->toThrow(BudgetFailure::class) ->and(fn () => $control->recordDistribution($source['origin'], 'commit', $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000]); }); test('a complete order command is invisible and unusable from another company', function () { $source = orderPartsSource($this, 10000); $other = receiptFixture(); $this->actingAs($other['issuer']); expect(fn () => app(CommonBudget::class)->for($other['issuer'])->commitOrderParts((string) Str::uuid(), [$source], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_order_commands')->count())->toBe(0); }); test('legacy consumption cannot consume an invoice already used by an order-part command', function () { $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid()); $this->actingAs($this->finance); $invoice = orderPartsInvoice($this, 5000); $input = orderPartsAmount($source, 5000, 1); $input['allocations'][0]['order_key'] = $order; $control = app(CommonBudget::class)->for($this->finance); $control->consumeOrderParts($invoice->id, [$input], (string) Str::uuid()); expect(fn () => $control->consume($this->f['r']->id, $invoice->id, 5000, 5000))->toThrow(BudgetFailure::class); expect(DB::table('budget_consumptions')->count())->toBe(0)->and(DB::table('budget_order_consumptions')->count())->toBe(1); }); test('explicit adoption preserves all old entries and the exact balance before partial issuance', function () { $control = app(CommonBudget::class)->for($this->f['issuer']); $request = unissuedOrderPartsSource($this->f, 10000); $origin = $request->id; $centre = $this->f['r']->cost_center_id; $line = $request->items()->sole(); expect(PurchaseOrder::query()->where('requisition_id', $origin)->exists())->toBeFalse(); $control->record($origin, $centre, 'operating', 'reserve', 10000, 10000); $control->record($origin, $centre, 'operating', 'award', 10000, 10000); $original = DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->get()->toArray(); $before = orderPartsBalance($this); $lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 10000, 'total_minor' => 10000]]; $key = (string) Str::uuid(); $adopt = $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key); expect($adopt['replayed'])->toBeFalse() ->and($control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), $key)['replayed'])->toBeTrue() ->and(orderPartsBalance($this))->toBe($before) ->and(DB::table('budget_entries')->where('requisition_id', $origin)->orderBy('id')->limit(2)->get()->toArray())->toEqual($original) ->and(DB::table('budget_entries')->where('kind', 'order-adoption')->count())->toBe(1); $input = ['origin' => $origin, 'version' => 0, 'plan_hash' => $adopt['plan_hash'], 'allocations' => [['allocation_key' => 'native-line', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]; $control->commitOrderParts((string) Str::uuid(), [$input], (string) Str::uuid()); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 4000]) ->and(fn () => $control->record($origin, $centre, 'operating', 'commit', 10000, 10000))->toThrow(BudgetFailure::class); }); test('adoption rejects a changed amount and an already committed source without compensating values', function () { $control = app(CommonBudget::class)->for($this->f['issuer']); $request = unissuedOrderPartsSource($this->f, 10000); $origin = $request->id; $centre = $this->f['r']->cost_center_id; $line = $request->items()->sole(); $control->record($origin, $centre, 'operating', 'reserve', 10000, 10000); $control->record($origin, $centre, 'operating', 'award', 10000, 10000); $lines = [$line->id => ['subtotal_minor' => 9999, 'total_minor' => 9999, 'required_kind' => 'operating']]; $plan = [['allocation_key' => 'native-line', 'line_id' => $line->id, 'centre_id' => $centre, 'subtotal_minor' => 9999, 'total_minor' => 9999]]; expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class); $control->record($origin, $centre, 'operating', 'commit', 10000, 10000); $lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 10000; $plan[0]['subtotal_minor'] = $plan[0]['total_minor'] = 10000; expect(fn () => $control->adoptOrderSource($origin, $plan, $lines, str_repeat('b', 64), (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_order_commands')->count())->toBe(0)->and(DB::table('budget_distributions')->count())->toBe(0) ->and(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 10000]); }); test('order-part schema cannot be installed in an operational environment or silently reinstalled', function () { $migration = require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php'; expect(fn () => $migration->up())->toThrow(LogicException::class); app()->instance('env', 'production'); try { expect(fn () => $migration->up())->toThrow(LogicException::class, 'guarded disposable QA') ->and(fn () => $migration->down())->toThrow(LogicException::class); } finally { app()->instance('env', 'testing'); } }); test('PostgreSQL rejects mutation or deletion of each partial-order history table', function () { if (DB::getDriverName() !== 'pgsql') { $this->markTestSkipped('PostgreSQL append-only triggers require the disposable PostgreSQL run.'); } $source = orderPartsSource($this, 10000); $order = (string) Str::uuid(); app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid()); $this->actingAs($this->finance); $invoice = orderPartsInvoice($this, 5000); $input = orderPartsAmount($source, 5000, 1); $input['allocations'][0]['order_key'] = $order; app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, [$input], (string) Str::uuid()); foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'] as $table) { $row = DB::table($table)->orderBy('id')->first(); expect($row)->not->toBeNull(); expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->update(['tenant_id' => $row->tenant_id]))) ->toThrow(QueryException::class); expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $row->id)->delete())) ->toThrow(QueryException::class); expect(DB::table($table)->where('id', $row->id)->first())->toEqual($row); } });