commit compras1 3011
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-30 09:33:36 +02:00
parent 96b30368bc
commit 47649bd46c
163 changed files with 9419 additions and 145 deletions
+120
View File
@@ -0,0 +1,120 @@
<?php
use App\Models\PurchaseOrder;
use App\Models\Supplier;
use App\Models\User;
use App\Services\CommonFinanceAdministration;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\SupplierBankWorkflow;
use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (($argv[1] ?? '') !== '--initialize-authorized-synthetic' || config('app.demonstration') !== true
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129' || DB::table('invoices')->exists()) {
throw new LogicException('Only a new isolated synthetic receipt and finance journey is allowed.');
}
try {
// Each native command commits with its own actor, including its after-commit work.
$result = (function () {
$people = [];
foreach (['admin', 'procurement', 'finance', 'finance_review', 'warehouse'] as $key) {
$people[$key] = User::query()->where('email', $key.'@demo.compras.tempo.co.mz')->sole();
}
$acting = function (string $key) use ($people): User {
if (DB::transactionLevel() !== 0) {
throw new LogicException('Do not defer native actor-bound callbacks across demonstration identities.');
}
auth()->guard()->setUser($people[$key]);
return $people[$key];
};
$receiver = $acting('warehouse');
$order = PurchaseOrder::query()->sole();
$line = $order->items()->sole();
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(),
'delivery_note' => 'DEMO-GUIA-001', 'received_on' => today()->toDateString(), 'warehouse_id' => 1,
'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '10.000', 'accepted_quantity' => '10.000',
'quality_status' => 'compliant', 'stock_item_id' => 1, 'notes' => 'Recepção fictícia para apresentação.']]]);
$finance = $acting('finance');
$invoice = app(InvoiceWorkflow::class)->register($finance, $order, ['number' => 'DEMO-FT-001', 'issued_on' => today()->toDateString(),
'subtotal' => '1000.00', 'tax' => '0.00', 'total' => '1000.00', 'items' => [['purchase_order_item_id' => $line->id,
'quantity' => '10.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$reviewer = $acting('finance_review');
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
$buyer = $acting('procurement');
$supplier = Supplier::query()->findOrFail($order->supplier_id);
$bank = app(SupplierBankWorkflow::class)->propose($buyer, $supplier, ['account_key' => (string) Str::uuid(), 'previous_id' => 0,
'bank_name' => 'Banco Fictício — Demonstração', 'country' => 'MZ', 'currency' => 'MZN', 'beneficiary' => 'Fornecedor Fictício DEMO',
'account_identifier' => 'DEMO-SEM-CONTA-REAL', 'evidence_reference' => 'DEMO sem comprovativo bancário real', 'reason' => 'Cadastro estritamente fictício para apresentação.']);
foreach (['finance', 'finance_review'] as $key) {
$actor = $acting($key);
app(SupplierBankWorkflow::class)->review($actor, $bank, 'approved', 'Conferência fictícia independente para demonstração.');
}
$payables = app(SupplierPayables::class);
$acting('finance');
$proposal = $payables->engine($finance)->command('prepare', $invoice->id, 'Reconhecimento fictício da factura de demonstração', (string) Str::uuid());
$acting('finance_review');
$recognised = $payables->engine($reviewer)->command('validate', $proposal['proposal_id'], 'Conferência independente da obrigação fictícia', (string) Str::uuid());
$acting('admin');
$administration = app(CommonFinanceAdministration::class);
$space = $administration->workspace($people['admin']);
$accounts = DB::table('gl_accounts')->where('tenant_id', $finance->tenant_id)->pluck('id', 'code');
$administration->save($people['admin'], 'rule', ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['rules']['hash'],
'rule_key' => 'DEMO-OBRIGACAO', 'effect_type' => 'supplier_payable.recognised', 'valid_from' => today()->startOfYear()->toDateString(),
'valid_to' => today()->endOfYear()->toDateString(), 'debit_account_id' => $accounts['DEMO-CUSTO'], 'credit_account_id' => $accounts['DEMO-FORNECEDORES'],
'reason' => 'Regra contabilística ilustrativa exclusiva da empresa fictícia.']);
$ledger = app(GeneralLedger::class);
$acting('finance');
$journal = $ledger->engine($finance)->command('prepare', ['obligation_id' => $recognised['obligation_id'], 'journal_on' => today()->toDateString(),
'period_key' => 'DEMO-'.now()->year, 'rule_key' => 'DEMO-OBRIGACAO', 'reason' => 'Lançamento fictício no plano ilustrativo configurado'], (string) Str::uuid());
$acting('finance_review');
$ledger->engine($reviewer)->command('validate', ['proposal_id' => $journal['proposal_id'], 'revision' => $journal['revision'],
'decision' => 'approved', 'reason' => 'Revisão independente do lançamento fictício'], (string) Str::uuid());
$acting('finance');
$ledger->engine($finance)->command('post', ['proposal_id' => $journal['proposal_id'], 'revision' => $journal['revision'],
'reason' => 'Aplicação do lançamento fictício revisto'], (string) Str::uuid());
$payment = $payables->settlements($finance)->command('payment-prepare', ['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'],
'amount' => '400.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'DEMO-PAGAMENTO-001',
'evidence_reference' => 'DEMO-SEM-TRANSFERENCIA', 'reason' => 'Facto de pagamento fictício, sem transferência bancária'], (string) Str::uuid());
$acting('finance_review');
$payables->settlements($reviewer)->command('payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'DEMO-CONFERENCIA-001', 'reason' => 'Confirmação independente de facto exclusivamente fictício'], (string) Str::uuid());
$acting('finance');
$allocation = $payables->settlements($finance)->command('allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DEMO-AFECTACAO-001',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '400.00']],
'reason' => 'Afectação explícita do pagamento fictício à factura'], (string) Str::uuid());
$acting('finance_review');
$payables->settlements($reviewer)->command('allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
'reason' => 'Confirmação independente da afectação fictícia'], (string) Str::uuid());
$allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
$expenses = app(ExpenseAllocations::class);
$source = $expenses->source($reviewer, $allocationId, 'common_allocation');
$expenses->save($reviewer, $allocationId, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'],
'reason' => 'Imputação expressa por Finanças do pagamento fictício à categoria de origem.',
'allocations' => [['category' => 'Material de escritório', 'amount' => '400.00']]], 'common_allocation');
if (DB::table('external_payments')->count() !== 0 || DB::table('ps_payments')->count() !== 1
|| (int) DB::table('gl_lines')->sum('debit_minor') !== 100000 || (int) DB::table('gl_lines')->sum('credit_minor') !== 100000) {
throw new LogicException('Synthetic financial reconciliation failed.');
}
return ['state' => 'passed', 'order_id' => $order->id, 'receipt_id' => $receipt->id, 'invoice_id' => $invoice->id,
'invoice_minor' => 100000, 'payment_minor' => 40000, 'remaining_minor' => 60000, 'payment_id' => $payment['payment_id'],
'allocation_id' => $allocationId, 'stock_milli' => (int) DB::table('stock_movements')->sum('quantity_milli'),
'journal_debit_minor' => 100000, 'journal_credit_minor' => 100000, 'external_bank_transaction' => false];
})();
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
} catch (Throwable $error) {
fwrite(STDERR, $error::class.': '.$error->getMessage().PHP_EOL);
foreach (array_slice($error->getTrace(), 0, 8) as $frame) {
fwrite(STDERR, ($frame['file'] ?? '').':'.($frame['line'] ?? 0).' '.$frame['function'].PHP_EOL);
}
exit(1);
}