markTestSkipped('Use the owned standalone candidate business regression runner.'); } 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())) { throw new LogicException('Synthetic standalone business database required.'); } $settings = config('standalone-runtime'); $settings['enabled'] = true; $settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true); config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']); $runtime = new StandaloneRuntime($settings, new StandaloneArtifact); $runtime->artifact(); (require base_path('database/standalone-migrations/2026_11_29_000001_create_runtime_installations.php'))->up(); DB::table('compras_runtime_installations')->insert(['id' => $settings['installation_id'], 'product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT, 'manifest_sha256' => $settings['manifest_sha256'], 'database_binding_sha256' => StandaloneRuntime::databaseBinding(DB::connection()), 'recorded_by' => 'Synthetic standalone business regression', 'reason' => 'Authorised isolated candidate verification', 'installed_at' => now()]); (require base_path('database/standalone-migrations/2026_11_29_000002_install_standalone_extensions.php'))->up(); config(['standalone-runtime' => $settings]); app()->instance(StandaloneRuntime::class, $runtime); $paths = $runtime->configure(DB::connection()); config(['general-ledger.path' => $paths['general-ledger']]); $runtime->assertLoadedPackages(); $this->f = receiptFixture(); $this->actingAs($this->f['issuer']); }); test('standalone candidate preserves explicit line account attribution without a journal or a parallel budget writer', function () { $request = $this->f['r']; $request->update(['status' => 'draft']); $account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0, 'code' => 'OWN-CANDIDATE', 'label' => 'Synthetic standalone movement account', 'currency' => 'MZN', 'is_movement' => true]); expect(config('requisition-accounts.qa_enabled'))->toBeFalse()->and(app(RequisitionLedgerAccounts::class)->ready())->toBeTrue(); $service = app(RequisitionAccountAssignments::class); $space = $service->workspace($this->f['issuer'], $request); $selected = $space['accounts']['data'][0]; expect($selected['id'])->toBe($account); $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $space['items'][0]['id'], 'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Explicit synthetic standalone account attribution', 'allocations' => [['account_id' => $account, 'source_hash' => $selected['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]]; $record = $service->save($this->f['issuer'], $request, $input); expect($service->save($this->f['issuer'], $request, $input)->id)->toBe($record->id) ->and($record->data['allocations'][0]['account']['code'])->toBe('OWN-CANDIDATE') ->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0); $this->actingAs($this->f['receiver']); expect(fn () => $service->save($this->f['receiver'], $request, [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(ModelNotFoundException::class); expect(DB::table('supply_records')->where('kind', 'req_account')->count())->toBe(1); }); test('standalone candidate closes an old reservation cycle and reserves a revised amount once without rewriting history', function () { $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic standalone cycle budget', 'created_by' => $this->f['issuer']->id, 'approved_by' => $finance->id]); $origin = $this->f['r']->id; $service = app(CommonBudget::class); $first = $service->for($this->f['issuer'], [$origin => 1]); $first->beginRequisitionCycle($origin, 1, (string) Str::uuid()); $first->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000); expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class); $first->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'); $close = (string) Str::uuid(); $first->closeRequisitionCycle($origin, 1, $close); $original = DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson(); expect($first->closeRequisitionCycle($origin, 1, $close)['replayed'])->toBeTrue(); $second = $service->for($this->f['issuer'], [$origin => 2]); $second->beginRequisitionCycle($origin, 2, (string) Str::uuid()); $second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000); expect(DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson())->toBe($original) ->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(12000) ->and(DB::table('stock_movements')->count())->toBe(0)->and(DB::table('gl_journals')->count())->toBe(0); }); test('standalone candidate returns an expired request to its owner and requires new approvals and reservation on resubmission', function () { $staff = fn (PurchasingRole $role) => User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => $role]); $admin = $staff(PurchasingRole::Admin); $head = $staff(PurchasingRole::DepartmentHead); $finance = $staff(PurchasingRole::Finance); $owner = $this->f['issuer']; $this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]); Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic standalone resubmission budget', 'created_by' => $owner->id, 'approved_by' => $finance->id]); $expiry = app(RequisitionExpiry::class); $this->actingAs($admin); $expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement']), 'reason' => 'Explicit synthetic elapsed deadlines for candidate verification']); $this->actingAs($owner); $workflow = app(RequisitionWorkflow::class); $input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic standalone request with independent resubmission', 'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]; $request = $workflow->save($owner, $input); $account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $owner->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'code' => 'EXPLICIT-CANDIDATE', 'label' => 'Synthetic cycle account', 'currency' => 'MZN', 'is_movement' => true]); $assign = function (string $amount) use ($owner, $request, $account) { $service = app(RequisitionAccountAssignments::class); $space = $service->workspace($owner, $request); $line = $space['items'][0]; $old = SupplyRecord::query()->where('kind', 'req_account')->where('data->requisition_item_id', $line['id'])->latest('id')->first(); $selected = $space['accounts']['data'][0]; $service->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => $old?->version ?? 0, 'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Explicit candidate account for the current reviewed line', 'allocations' => [['account_id' => $account, 'source_hash' => $selected['source_hash'], 'subtotal' => $amount, 'total' => $amount]]]); }; $assign('100.00'); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); $this->actingAs($head); $workflow->decide($head, $request, 'approved', 'Independent synthetic first-stage decision', (string) Str::uuid(), $request->process_version); $request->refresh(); $approved = $request->steps()->where('decision', 'approved')->sole()->toArray(); $this->travel(31)->minutes(); $deadline = $expiry->deadline($request); $this->actingAs($owner); $body = ['basis_hash' => $deadline['basis_hash'], 'operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version]; $this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect(); $this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect(); $request->refresh(); expect($request->status)->toBe('draft')->and($request->requester_id)->toBe($owner->id)->and($request->approval_cycle)->toBe(2) ->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved) ->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0) ->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1); $input['operation_key'] = (string) Str::uuid(); $input['process_version'] = $request->process_version; $input['items'][0]['unit_price'] = '120.00'; $workflow->save($owner, $input, $request); $request->refresh(); $assign('120.00'); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); expect($request->status)->toBe('pending')->and($request->steps()->count())->toBe(2) ->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4) ->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000) ->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0); }); test('standalone financial pages use explicit read rights and refuse writes or disabled modules', function () { $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->actingAs($finance)->get('/api/supplier-payments')->assertForbidden(); $this->get('/api/general-ledger/cycle')->assertForbidden(); foreach (['view', 'payments_view', 'general_ledger.view'] as $action) { DB::table('pa_access')->insert(['tenant_id' => $finance->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $finance->id, 'person' => 'synthetic-financial-reader-'.$finance->id, 'action' => $action]); } $before = []; foreach (['ps_payments', 'ps_allocations', 'ps_commands', 'ps_events', 'gl_journals', 'gl_commands', 'gl_events', 'budget_entries', 'stock_movements'] as $table) { $before[$table] = DB::table($table)->orderBy('id')->get()->toJson(); } $this->get('/api/supplier-payments')->assertOk()->assertJsonPath('payments', [])->assertJsonPath('allocations', []) ->assertJsonPath('permissions.payment_prepare', false); $this->get('/supplier-payments')->assertOk()->assertHeader('Cache-Control', 'no-store, private'); $this->get('/api/general-ledger/cycle')->assertOk(); $this->get('/general-ledger/cycle')->assertOk(); $this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/supplier-payments/payment-prepare', [])->assertForbidden(); $this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/general-ledger/prepare', [ 'obligation_id' => 1, 'journal_on' => today()->toDateString(), 'period_key' => 'QA', 'rule_key' => 'QA', 'reason' => 'Synthetic attempt without writer authority'])->assertForbidden(); $settings = config('standalone-runtime'); $settings['features']['supplier-settlements'] = false; $settings['features']['general-ledger-cycle'] = false; app()->instance(StandaloneRuntime::class, new StandaloneRuntime($settings, new StandaloneArtifact)); $this->get('/api/supplier-payments')->assertForbidden(); $this->get('/api/general-ledger/cycle')->assertForbidden(); foreach ($before as $table => $frame) { expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($frame); } }); test('standalone candidate recognises one invoice and posts one balanced journal using explicitly configured own chart accounts', function () { $f = paymentFixture(); foreach ([$f['author'], $f['validator']] as $actor) { foreach (['view', 'prepare', 'validate', 'general_ledger.view', 'general_ledger.prepare', 'general_ledger.validate', 'general_ledger.post'] as $action) { DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id, 'person' => 'synthetic-independent-person-'.$actor->id, 'action' => $action]); } } $payables = app(SupplierPayables::class); $this->actingAs($f['author']); $prepared = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Explicit synthetic invoice review', (string) Str::uuid()); $this->actingAs($f['validator']); $validated = $payables->engine($f['validator'])->command('validate', $prepared['proposal_id'], 'Independent synthetic recognition', (string) Str::uuid()); expect($validated['state'])->toBe('recognised')->and(DB::table('pa_obligations')->count())->toBe(1); $scope = ['tenant_id' => $f['author']->tenant_id, 'company_id' => 0, 'unit_id' => 0]; $accounts = []; foreach (['630100' => 'Synthetic configured expense account', '420100' => 'Synthetic configured supplier account'] as $code => $label) { $accounts[] = DB::table('gl_accounts')->insertGetId($scope + ['code' => $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true]); } DB::table('gl_periods')->insert($scope + ['period_key' => 'EXPLICIT', 'version' => 1, 'starts_on' => today()->startOfYear()->toDateString(), 'ends_on' => today()->endOfYear()->toDateString(), 'status' => 'open', 'created_by' => $f['author']->id, 'reason' => 'Explicit synthetic accounting period', 'created_at' => now()]); DB::table('gl_rules')->insert($scope + ['rule_key' => 'EXPLICIT-SUPPLIER', 'version' => 1, 'policy' => 'COMMON-PAYABLE-JOURNAL-v1', 'effect_type' => 'supplier_payable.recognised', 'currency' => 'MZN', 'valid_from' => today()->startOfYear()->toDateString(), 'valid_to' => today()->endOfYear()->toDateString(), 'debit_account_id' => $accounts[0], 'credit_account_id' => $accounts[1], 'created_by' => $f['author']->id, 'reason' => 'Explicit synthetic own chart accounting rule', 'created_at' => now()]); $ledger = app(GeneralLedger::class); $this->actingAs($f['author']); $input = ['obligation_id' => $validated['obligation_id'], 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT', 'rule_key' => 'EXPLICIT-SUPPLIER', 'reason' => 'Prepare the explicitly configured synthetic journal']; $proposal = $ledger->engine($f['author'])->command('prepare', $input, (string) Str::uuid()); expect(fn () => $ledger->engine($f['author'])->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'decision' => 'approved', 'reason' => 'Forbidden self review'], (string) Str::uuid()))->toThrow(DomainException::class); $this->actingAs($f['validator']); $ledger->engine($f['validator'])->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'decision' => 'approved', 'reason' => 'Independent review of the explicit synthetic rule'], (string) Str::uuid()); $this->actingAs($f['author']); $operation = (string) Str::uuid(); $post = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Apply the independently reviewed synthetic journal']; $ledger->engine($f['author'])->command('post', $post, $operation); DB::statement('SET CONSTRAINTS ALL IMMEDIATE'); expect($ledger->engine($f['author'])->command('post', $post, $operation)['replayed'])->toBeTrue() ->and(DB::table('gl_journals')->count())->toBe(1)->and(DB::table('gl_lines')->count())->toBe(2) ->and((int) DB::table('gl_lines')->sum('debit_minor'))->toBe(6000) ->and((int) DB::table('gl_lines')->sum('credit_minor'))->toBe(6000) ->and(DB::table('external_payments')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0); $snapshot = json_decode(DB::table('gl_journals')->value('snapshot'), true, 128, JSON_THROW_ON_ERROR); expect($snapshot['contract'])->toBe('COMMON-LEDGER-PAYABLE-v1') ->and(array_column($snapshot['lines'], 'account_id'))->toBe($accounts); }); test('common partial payment attribution uses explicit Finance categories without duplicate native payments and preserves reversed history', function () { $f = paymentFixture(['Material', 'Serviços']); $payables = app(SupplierPayables::class); foreach ([$f['author'], $f['validator']] as $actor) { foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm', 'reversal_prepare', 'reversal_confirm'] as $action) { DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id, 'person' => 'synthetic-common-finance-'.$actor->id, 'action' => $action]); } } $this->actingAs($f['author']); $proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Synthetic partial payment invoice', (string) Str::uuid()); $this->actingAs($f['validator']); $recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent synthetic invoice recognition', (string) Str::uuid()); $run = function (User $actor, string $action, array $data) use ($payables): array { $this->actingAs($actor); return $payables->engine($actor)->settlements()->command($action, $data, (string) Str::uuid()); }; $payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'SIM-COMMON-PARTIAL', 'evidence_reference' => 'SIM-COMMON-EVIDENCE', 'reason' => 'Explicit synthetic confirmed payment fact']); $run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed', 'evidence_reference' => 'SIM-COMMON-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']); $report = fn () => app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->whereKey($f['r']->id), null, null); expect($report()['coverage']['indeterminate'])->toBe(1)->and($report()['currencies'])->toBe([]); $allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-ALLOCATION-EXPLICIT', 'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']], 'reason' => 'Explicit synthetic invoice allocation of the confirmed payment']); $run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed', 'reason' => 'Independent synthetic allocation confirmation']); $allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id'); $facts = app(CommonPaymentFacts::class)->source($f['validator'], $allocationId); expect($facts['amount_minor'])->toBe(4000)->and($report()['currencies'][0]['amount_minor'])->toBe('4000') ->and($report()['category_attribution']['coverage']['unallocated'])->toBe(1); $service = app(ExpenseAllocations::class); $source = $service->source($f['validator'], $allocationId, 'common_allocation'); $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'], 'reason' => 'Finance explicitly attributes the synthetic partial payment', 'allocations' => [['category' => 'Material', 'amount' => '15.00'], ['category' => 'Serviços', 'amount' => '25.00']]]; $frames = []; foreach (['ps_payments', 'ps_payment_decisions', 'ps_allocations', 'ps_commands', 'ps_events', 'pa_obligations', 'gl_journals', 'external_payments', 'stock_movements', 'budget_entries'] as $table) { $frames[$table] = DB::table($table)->orderBy('id')->get()->toJson(); } $url = '/afectacoes-fornecedores/'.$allocationId.'/imputacao'; $this->withoutVite(); $this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['sourceType'] === 'common_allocation' && $page['props']['submitUrl'] === $url && $page['props']['payment']['amount_minor'] === '4000'); $this->postJson($url, $input)->assertRedirect(); $this->postJson($url, $input)->assertRedirect(); $this->get('/supplier-payments')->assertOk()->assertSee($url); expect($service->current($allocationId))->toBeNull() ->and($service->current($allocationId, 'common_allocation')->data['source_type'])->toBe('common_allocation') ->and(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(1) ->and($report()['category_attribution']['groups']['data'])->toBe([ ['category' => 'Material', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '1500'], ['category' => 'Serviços', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '2500'], ]); foreach ($frames as $table => $frame) { expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($frame); } $reversal = $run($f['author'], 'reversal-prepare', ['allocation_id' => $allocationId, 'source_revision' => $recognised['source_revision'], 'reason' => 'Synthetic reversal preserves the earlier analytical record']); $run($f['validator'], 'reversal-confirm', ['proposal_id' => $reversal['proposal_id'], 'reason' => 'Independent synthetic reversal confirmation']); expect($service->projection($f['validator'], $allocationId, 'common_allocation')['state'])->toBe('indeterminate') ->and($service->current($allocationId, 'common_allocation')->version)->toBe(1) ->and($report()['coverage']['indeterminate'])->toBe(1)->and(DB::table('external_payments')->count())->toBe(0); }); test('one common payment shared across two invoices is counted once while explicit category amounts are summed exactly', function () { $f = paymentFixture(); $this->actingAs($f['author']); $secondInput = [...$f['data'], 'number' => 'FT-CANDIDATE-SECOND', 'subtotal' => '40.00', 'tax' => '0.00', 'total' => '40.00']; $secondInput['items'][0]['quantity'] = '0.400'; $second = app(InvoiceWorkflow::class)->register($f['author'], $f['order'], $secondInput); $this->actingAs($f['validator']); app(InvoiceWorkflow::class)->validate($f['validator'], $second); foreach ([$f['author'], $f['validator']] as $actor) { foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) { DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id, 'person' => 'synthetic-multiple-invoice-'.$actor->id, 'action' => $action]); } } $adapter = app(SupplierPayables::class); $obligations = []; foreach ([$f['invoice'], $second] as $invoice) { $this->actingAs($f['author']); $prepared = $adapter->engine($f['author'])->command('prepare', $invoice->id, 'Explicit synthetic multi-invoice source', (string) Str::uuid()); $this->actingAs($f['validator']); $obligations[] = $adapter->engine($f['validator'])->command('validate', $prepared['proposal_id'], 'Independent synthetic invoice confirmation', (string) Str::uuid()); } $run = function (User $actor, string $action, array $data) use ($adapter): array { $this->actingAs($actor); return $adapter->engine($actor)->settlements()->command($action, $data, (string) Str::uuid()); }; $payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $obligations[0]['obligation_id'], 'source_revision' => $obligations[0]['source_revision'], 'amount' => '70.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'SIM-TWO-INVOICES', 'evidence_reference' => 'SIM-TWO-INVOICES-EVIDENCE', 'reason' => 'One explicit synthetic supplier payment covering two invoices']); $run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed', 'evidence_reference' => 'SIM-TWO-INVOICES-CONFIRMED', 'reason' => 'Independent confirmation of one synthetic payment']); $plan = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-TWO-INVOICE-PLAN', 'allocations' => [ ['obligation_id' => $obligations[0]['obligation_id'], 'source_revision' => $obligations[0]['source_revision'], 'amount' => '30.00'], ['obligation_id' => $obligations[1]['obligation_id'], 'source_revision' => $obligations[1]['source_revision'], 'amount' => '40.00'], ], 'reason' => 'Explicit synthetic invoice split of the single supplier payment']); $run($f['validator'], 'allocation-decide', ['proposal_id' => $plan['proposal_id'], 'decision' => 'confirmed', 'reason' => 'Independent confirmation of the explicit invoice split']); foreach (DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->orderBy('id')->get() as $row) { $service = app(ExpenseAllocations::class); $source = $service->source($f['validator'], (int) $row->id, 'common_allocation'); $service->save($f['validator'], (int) $row->id, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'], 'reason' => 'Finance explicitly chooses the documentary category for this invoice portion', 'allocations' => [['category' => 'Material', 'amount' => (int) $row->amount_minor === 3000 ? '30.00' : '40.00']]], 'common_allocation'); } $report = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->whereKey($f['r']->id), null, null); expect($report['coverage']['confirmed_payments'])->toBe(1) ->and($report['currencies'])->toBe([['currency' => 'MZN', 'count' => 1, 'amount_minor' => '7000']]) ->and($report['suppliers']['data'][0]['count'])->toBe(1) ->and($report['category_attribution']['groups']['data'])->toBe([['category' => 'Material', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '7000']]) ->and(DB::table('ps_payments')->count())->toBe(1)->and(DB::table('ps_allocations')->count())->toBe(2) ->and(DB::table('external_payments')->count())->toBe(0); });