commit compras2 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 10:48:22 +02:00
parent 448948a487
commit 7da8d6c87a
64 changed files with 2538 additions and 288 deletions
@@ -0,0 +1,28 @@
<?php
namespace App\Console\Commands;
use App\Services\StandaloneInstallation;
use Illuminate\Console\Command;
final class PrepareStandaloneRuntime extends Command
{
protected $signature = 'compras:runtime:prepare
{--expected-database= : Exact own database name}
{--expected-role= : Exact non-elevated database role}
{--operator= : Named deployment operator}
{--reason= : Recorded installation or recovery reason}
{--apply : Apply the explicitly selected installation}
{--rebind : Preserve restored schema and register a new installation binding}';
protected $description = 'Preparar explicitamente a composição independente; pré-visualizar por defeito';
public function handle(StandaloneInstallation $installation): int
{
$result = $installation->prepare((string) $this->option('expected-database'), (string) $this->option('expected-role'),
(string) $this->option('operator'), (string) $this->option('reason'), $this->option('apply') === true, $this->option('rebind') === true);
$this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}
@@ -11,6 +11,27 @@ use Symfony\Component\HttpFoundation\Response;
final class ExpenseAllocationController extends Controller
{
public function commonShow(Request $request, int $allocation, ExpenseAllocations $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
Inertia::encryptHistory();
$response = Inertia::render('payments/expense-allocation', $service->workspace($actor, $allocation, 'common_allocation'))->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function commonStore(Request $request, int $allocation, ExpenseAllocations $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$service->save($actor, $allocation, $request->all(), 'common_allocation');
return back()->with('success', 'Imputação da despesa por categoria preservada.');
}
public function show(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
{
$actor = $request->user('web');
@@ -49,7 +49,7 @@ final class GeneralLedgerController extends Controller
public function command(Request $r, string $action, GeneralLedger $ledger): JsonResponse
{
abort_unless(config('general-ledger.cycle_enabled') === true, 403);
abort_unless($ledger->cycleEnabled(), 403);
try {
return response()->json($ledger->engine($this->actor($r))->command($action, $r->all(), (string) $r->header('Idempotency-Key')))->header('Cache-Control', 'no-store');
} catch (\InvalidArgumentException $e) {
@@ -3,9 +3,13 @@
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\StandaloneRuntime;
use App\Services\StandaloneSchema;
use App\Services\SupplierPayables;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tempo\Finance\Payables\SettlementHttp;
final class SupplierPaymentsController extends SettlementHttp
@@ -14,15 +18,30 @@ final class SupplierPaymentsController extends SettlementHttp
protected const SERVICE = SupplierPayables::class;
protected function guard(): void
{
if (! app(StandaloneRuntime::class)->enabled()) {
parent::guard();
return;
}
abort_unless(app(StandaloneRuntime::class)->feature('supplier-settlements', DB::connection()), 403);
StandaloneSchema::verify(DB::getSchemaBuilder(), ['supplier-payables' => true, 'supplier-settlements' => true]);
}
/** @return array<string,mixed> */
protected function ledgerSettings(Request $request): array
{
if (config('general-ledger.cycle_enabled') !== true) {
return [];
}
$user = $request->user();
abort_unless($user instanceof User, 403);
$settings = [];
if (app(StandaloneRuntime::class)->enabled() && app(ExpenseAllocations::class)->ready() && $user->hasFunctions(['admin', 'finance'])) {
$settings['expense_allocation_base_url'] = '/afectacoes-fornecedores/';
}
if (app(GeneralLedger::class)->cycleEnabled() && app(GeneralLedger::class)->can($user, 'view')) {
$settings['ledger_cycle_url'] = '/general-ledger/cycle';
}
return app(GeneralLedger::class)->can($user, 'view') ? ['ledger_cycle_url' => '/general-ledger/cycle'] : [];
return $settings;
}
}
+19 -1
View File
@@ -7,6 +7,8 @@ use App\Services\BudgetDistributionArtifact;
use App\Services\FinanceBundle;
use App\Services\ReplenishmentRun;
use App\Services\RequisitionExpiryRun;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
@@ -23,7 +25,19 @@ class AppServiceProvider extends ServiceProvider
$this->app->singleton(ReplenishmentRun::class);
$this->app->singleton(RequisitionExpiryRun::class);
$this->app->scoped(AdministrativeGeography::class);
require_once base_path('packages/purchasing/bootstrap.php');
$this->app->scoped(StandaloneRuntime::class, fn () => new StandaloneRuntime(config('standalone-runtime'), new StandaloneArtifact));
$runtime = $this->app->make(StandaloneRuntime::class);
$paths = null;
if ($runtime->enabled()) {
if (config('common-finance-bundle.root') !== null || config('budget-distributions.enabled') === true) {
throw new \LogicException('COMPRAS_RUNTIME_MIXED_COMPOSITION');
}
$paths = $runtime->configure(DB::connection());
$runtime->assertLoadedPackages(allowMissing: true);
config(['common-budget.path' => $paths['budget-control'], 'common-payables.path' => $paths['payables'],
'general-ledger.path' => $paths['general-ledger']]);
}
require_once ($paths['purchasing'] ?? config('common-purchasing.path')).'/bootstrap.php';
$package = config('common-budget.path');
if (config('budget-distributions.enabled') === true) {
BudgetDistributionArtifact::verify($package,
@@ -33,6 +47,10 @@ class AppServiceProvider extends ServiceProvider
FinanceBundle::configure();
$payables = config('common-payables.path');
require_once $payables.'/bootstrap.php';
if ($paths !== null) {
require_once $paths['general-ledger'].'/bootstrap.php';
$runtime->assertLoadedPackages();
}
}
/**
+5
View File
@@ -22,6 +22,11 @@ final class AgreementOrderLimits
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('agreement-order-limits', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('agreement_order_limits.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()) === 1));
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Blueprint;
use LogicException;
/** Single additive schema definition shared by explicit installation and guarded QA. */
final class BudgetLandedCostSchema
{
public static function install(Connection $db): void
{
$schema = $db->getSchemaBuilder();
$tables = ['budget_landed_commands', 'budget_landed_entries'];
if ($schema->hasTable($tables[0]) || $schema->hasTable($tables[1])) {
throw new LogicException('Never reinstall or repair landed-cost financial history implicitly.');
}
$db->transaction(function () use ($schema, $db, $tables): void {
$schema->create('budget_landed_commands', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->uuid('operation_key');
$table->uuid('plan_key');
$table->unsignedInteger('plan_version');
$table->string('plan_hash', 64);
$table->string('kind', 20);
$table->string('payload_hash', 64);
$table->json('snapshot');
$table->timestamp('created_at');
$table->unique(['tenant_id', 'operation_key']);
$table->index(['tenant_id', 'plan_key', 'id']);
});
$schema->create('budget_landed_entries', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('command_id')->constrained('budget_landed_commands')->restrictOnDelete();
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
$table->string('source_key', 120);
$table->string('source_kind', 30);
$table->unsignedBigInteger('source_id');
$table->unsignedInteger('source_version');
$table->string('source_revision', 64);
$table->json('source_snapshot');
$table->bigInteger('reserved_minor');
$table->bigInteger('committed_minor');
$table->bigInteger('consumed_minor');
$table->unique(['command_id', 'source_key']);
$table->index(['tenant_id', 'source_key']);
});
foreach ($tables as $table) {
if ($db->getDriverName() === 'pgsql') {
$db->unprepared('CREATE FUNCTION preserve_'.$table.'() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION \'Preserve landed cost history\'; END $$;');
$db->statement('CREATE TRIGGER immutable_landed_history BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION preserve_'.$table.'()');
} else {
$db->unprepared('CREATE TRIGGER '.$table.'_update BEFORE UPDATE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
$db->unprepared('CREATE TRIGGER '.$table.'_delete BEFORE DELETE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
}
}
});
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Blueprint;
use LogicException;
/** Single additive schema definition shared by explicit installation and guarded QA. */
final class BudgetOrderPartsSchema
{
public static function install(Connection $db): void
{
$schema = $db->getSchemaBuilder();
$tables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
$found = count(array_filter($tables, fn ($table) => $schema->hasTable($table)));
if ($found !== 0) {
throw new LogicException('Order-parts schema must be installed once into an empty isolated composition.');
}
if (! $schema->hasTable('budget_distribution_entries')) {
throw new LogicException('Install the explicit V1 distribution schema first.');
}
$db->transaction(function () use ($schema, $db, $tables): void {
$schema->create('budget_order_commands', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->string('kind', 20);
$table->string('document_key', 60);
$table->uuid('operation_key');
$table->string('payload_hash', 64);
$table->json('result');
$table->json('snapshot');
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->timestamp('created_at');
$table->unique(['tenant_id', 'operation_key']);
$table->unique(['tenant_id', 'kind', 'document_key']);
});
$schema->create('budget_order_bindings', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('command_id')->constrained('budget_order_commands')->restrictOnDelete();
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
$table->unsignedInteger('source_version');
$table->unique(['distribution_id', 'source_version']);
$table->unique(['command_id', 'distribution_id']);
});
foreach (['budget_order_allocations', 'budget_order_consumptions'] as $name) {
$schema->create($name, function (Blueprint $table) use ($name): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('command_id')->constrained('budget_order_commands')->restrictOnDelete();
$table->foreignId('distribution_id')->constrained('budget_distributions')->restrictOnDelete();
$table->uuid('order_key');
$table->string('allocation_key', 120);
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
$table->bigInteger('subtotal_minor');
$table->bigInteger('total_minor');
$table->bigInteger('amount_minor');
if ($name === 'budget_order_consumptions') {
$table->foreignId('invoice_id')->constrained()->restrictOnDelete();
} else {
$table->string('kind', 20);
}
$table->unique(['command_id', 'distribution_id', 'order_key', 'allocation_key'], $name === 'budget_order_allocations' ? 'order_allocation_binding' : 'order_consumption_binding');
});
}
if ($db->getDriverName() === 'pgsql') {
// Existing function always raises; no mutation or deletion of accepted history.
foreach ($tables as $table) {
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
}
}
});
}
}
+5
View File
@@ -19,6 +19,11 @@ final class CapitalRegister
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('capital-register', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records') && $db->getSchemaBuilder()->hasTable('equipment');
}
return config('capital-register.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace App\Services;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\User;
use Brick\Math\BigInteger;
use DomainException;
use Illuminate\Support\Facades\DB;
/** Original confirmed common allocations, not copies of native payment history. No bank references. */
final class CommonPaymentFacts
{
/** @return array<string,mixed> */
public function source(User $actor, int $allocation): array
{
$adapter = app(SupplierPayables::class);
$context = $adapter->readContext($actor);
$scope = $context['scope'];
abort_unless(app(StandaloneRuntime::class)->enabled() && DB::getSchemaBuilder()->hasTable('ps_allocations'), 503);
$q = fn (string $table) => DB::table($table)->where($scope);
$row = $q('ps_allocations')->where('id', $allocation)->first();
abort_unless($row !== null, 404);
if ($q('ps_reversals')->where('allocation_id', $allocation)->exists()) {
throw new DomainException('Afectação revertida; conserve a imputação histórica.');
}
$obligation = $q('pa_obligations')->where('id', $row->obligation_id)->first();
$origin = $obligation === null ? null : $q('pa_sources')->where('id', $obligation->source_id)->first();
if ($origin === null) {
throw new DomainException('Origem da afectação incompleta.');
}
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
->whereKey($origin->local_source_id)->firstOrFail();
$position = $adapter->readEngine($actor)->positionForSource($invoice->id);
$payment = $q('ps_payments')->where('id', $row->payment_id)->first();
$decision = $q('ps_allocation_decisions')->where('id', $row->decision_id)->first();
$proposal = $decision === null ? null : $q('ps_proposals')->where('id', $decision->proposal_id)->first();
$confirmation = $q('ps_payment_decisions')->where('payment_id', $row->payment_id)->where('decision', 'confirmed')->first();
if ($position === null || $position['source_conflict'] || (int) $position['id'] !== (int) $row->obligation_id
|| $position['source_revision'] !== $row->source_revision || $payment === null || $decision === null || $proposal === null || $confirmation === null
|| $decision->decision !== 'confirmed' || (int) $proposal->payment_id !== (int) $row->payment_id
|| $decision->actor_id === $proposal->prepared_by || $decision->person === $proposal->prepared_person
|| $confirmation->actor_id === $payment->prepared_by || $confirmation->person === $payment->prepared_person
|| (int) $row->amount_minor <= 0 || $payment->currency !== 'MZN') {
throw new DomainException('Confirmação ou revisão da afectação indeterminada.');
}
$events = [];
foreach (['supplier_payment.confirmed' => $confirmation, 'supplier_allocation.confirmed' => $decision] as $kind => $evidence) {
$event = $q('ps_events')->where('kind', $kind)->where('actor_id', $evidence->actor_id)
->where('payload->decision_id', $evidence->id)->first(['id']);
if ($event === null) {
throw new DomainException('Confirmação sem evento financeiro compatível.');
}
$events[] = (int) $event->id;
}
return ['id' => $allocation, 'source_type' => 'common_allocation', 'common_payment_id' => (int) $row->payment_id,
'invoice_id' => $invoice->id, 'status' => 'confirmed', 'amount_minor' => (int) $row->amount_minor,
'currency' => 'MZN', 'reviewed_at' => $confirmation->created_at, 'reviewed_by' => (int) $confirmation->actor_id,
'source_revision' => $row->source_revision, 'allocation_decision_id' => (int) $decision->id,
'allocation_confirmed_at' => $decision->created_at, 'confirmation_id' => (int) $confirmation->id, 'event_ids' => $events];
}
/** @return list<array<string,mixed>> */
public function forInvoice(User $actor, int $invoice): array
{
if (! app(StandaloneRuntime::class)->enabled() || ! DB::getSchemaBuilder()->hasTable('ps_allocations')) {
return [];
}
$adapter = app(SupplierPayables::class);
$context = $adapter->readContext($actor);
$scope = $context['scope'];
$position = $adapter->readEngine($actor)->positionForSource($invoice);
if ($position === null) {
return [];
}
if ($position['source_conflict']) {
throw new DomainException('Origem financeira alterada; despesa indeterminada.');
}
$payments = DB::table('ps_payments')->where($scope)->where('obligation_id', $position['id'])
->whereIn('id', DB::table('ps_payment_decisions')->where($scope)->where('decision', 'confirmed')->select('payment_id'))->get();
foreach ($payments as $payment) {
$assigned = DB::table('ps_allocations')->where($scope)->where('payment_id', $payment->id)
->whereNotIn('id', DB::table('ps_reversals')->where($scope)->select('allocation_id'))->sum('amount_minor');
if (! BigInteger::of((string) $assigned)->isEqualTo((string) $payment->amount_minor)) {
throw new DomainException('Pagamento confirmado com afectação documental incompleta; despesa por factura indeterminada.');
}
}
$rows = DB::table('ps_allocations')->where($scope)->where('obligation_id', $position['id'])
->whereNotIn('id', DB::table('ps_reversals')->where($scope)->select('allocation_id'))->orderBy('id')->get(['id']);
$facts = [];
foreach ($rows as $row) {
$facts[] = $this->source($actor, (int) $row->id);
}
return $facts;
}
}
+4
View File
@@ -16,6 +16,10 @@ final class ConflictReleases
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('conflict-releases', $db) && Schema::hasTable('conflict_releases');
}
return config('conflict-releases.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+69 -24
View File
@@ -9,6 +9,7 @@ use App\Models\SupplyRecord;
use App\Models\User;
use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
@@ -22,6 +23,11 @@ final class ExpenseAllocations
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('expense-allocations', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('expense-allocations.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
@@ -29,14 +35,27 @@ final class ExpenseAllocations
}
/** @return array<string,mixed> */
public function source(User $actor, int $id): array
public function source(User $actor, int $id, string $sourceType = 'external_payment'): array
{
$payment = ExternalPayment::query()->whereKey($id)->firstOrFail();
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($payment->invoice_id)->firstOrFail();
try {
$facts = collect(app(SupplierPayables::class)->readPaymentHistory($actor, $invoice->id))->firstWhere('id', $id);
} catch (\DomainException) {
abort(409, 'O histórico auditado do pagamento está indeterminado.');
$this->validSource($sourceType);
$facts = null;
if ($sourceType === 'common_allocation') {
try {
$facts = app(CommonPaymentFacts::class)->source($actor, $id);
} catch (\DomainException $error) {
abort(409, $error->getMessage());
}
$invoiceId = $facts['invoice_id'];
} else {
$invoiceId = ExternalPayment::query()->whereKey($id)->firstOrFail()->invoice_id;
}
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($invoiceId)->firstOrFail();
if ($sourceType === 'external_payment') {
try {
$facts = collect(app(SupplierPayables::class)->readPaymentHistory($actor, $invoice->id))->firstWhere('id', $id);
} catch (\DomainException) {
abort(409, 'O histórico auditado do pagamento está indeterminado.');
}
}
abort_unless($facts !== null && $facts['status'] === 'confirmed', 409, 'A imputação exige um pagamento confirmado e o seu histórico auditado.');
abort_unless(is_int($facts['amount_minor']) && $facts['amount_minor'] > 0 && is_string($facts['currency'])
@@ -70,15 +89,33 @@ final class ExpenseAllocations
return $actor;
}
public function current(int $payment): ?SupplyRecord
private function validSource(string $sourceType): void
{
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->first();
if (! in_array($sourceType, ['external_payment', 'common_allocation'], true)) {
throw new \InvalidArgumentException('Unknown expense attribution source.');
}
}
/** @return Builder<SupplyRecord> */
private function records(int $payment, string $sourceType): Builder
{
$this->validSource($sourceType);
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)
->when($sourceType === 'external_payment',
fn ($query) => $query->where(fn ($source) => $source->whereNull('data->source_type')->orWhere('data->source_type', 'external_payment')),
fn ($query) => $query->where('data->source_type', 'common_allocation'));
}
public function current(int $payment, string $sourceType = 'external_payment'): ?SupplyRecord
{
return $this->records($payment, $sourceType)->latest('version')->first();
}
/** @return array<string,mixed> */
public function projection(User $actor, int $payment): array
public function projection(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
$record = $this->current($payment);
$record = $this->current($payment, $sourceType);
if ($record === null) {
return ['state' => 'unallocated', 'allocations' => []];
}
@@ -86,7 +123,7 @@ final class ExpenseAllocations
return ['state' => 'indeterminate', 'allocations' => []];
}
try {
$source = $this->source($actor, $payment);
$source = $this->source($actor, $payment, $sourceType);
} catch (HttpExceptionInterface $error) {
if (! in_array($error->getStatusCode(), [404, 409], true)) {
throw $error;
@@ -109,25 +146,26 @@ final class ExpenseAllocations
}
/** @return array<string,mixed> */
public function workspace(User $actor, int $payment): array
public function workspace(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
return DB::transaction(function () use ($actor, $payment) {
return DB::transaction(function () use ($actor, $payment, $sourceType) {
$actor = $this->actor($actor);
$source = $this->source($actor, $payment);
$current = $this->current($payment);
$source = $this->source($actor, $payment, $sourceType);
$current = $this->current($payment, $sourceType);
$row = fn (SupplyRecord $record) => ['id' => $record->id, 'version' => $record->version, 'reason' => $record->reason,
'data' => ['allocations' => $record->data['allocations']]];
return ['payment' => ['id' => $payment, 'invoice_id' => $source['invoice_id'], 'invoice_number' => $source['invoice_number'],
'amount_minor' => (string) $source['payment']['amount_minor'], 'currency' => $source['payment']['currency']],
'categories' => $source['categories'], 'fingerprint' => $source['fingerprint'], 'current' => $current === null ? null : $row($current),
'history' => SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->paginate(15)->withQueryString()->through($row),
'history' => $this->records($payment, $sourceType)->latest('version')->paginate(15)->withQueryString()->through($row),
...($sourceType === 'common_allocation' ? ['sourceType' => 'common_allocation', 'submitUrl' => '/afectacoes-fornecedores/'.$payment.'/imputacao'] : []),
'canWrite' => $actor->hasFunctions(['finance']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @param array<string,mixed> $input */
public function save(User $actor, int $payment, array $input): SupplyRecord
public function save(User $actor, int $payment, array $input, string $sourceType = 'external_payment'): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
'fingerprint' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
@@ -136,13 +174,19 @@ final class ExpenseAllocations
$data['operation_key'] = strtolower($data['operation_key']);
$data['version'] = (int) $data['version'];
usort($data['allocations'], fn ($a, $b) => strcmp($a['category'], $b['category']));
$hash = hash('sha256', json_encode([$payment, $data], JSON_THROW_ON_ERROR));
$this->validSource($sourceType);
$hash = hash('sha256', json_encode($sourceType === 'external_payment' ? [$payment, $data] : [$sourceType, $payment, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $payment, $data, $hash) {
return DB::transaction(function () use ($actor, $payment, $data, $hash, $sourceType) {
$actor = $this->actor($actor);
abort_unless($actor->hasFunctions(['finance']), 403);
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
$source = $this->source($actor, $payment);
if ($sourceType === 'external_payment') {
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
} else {
abort_unless(DB::table('ps_allocations')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0])
->where('id', $payment)->lockForUpdate()->first() !== null, 404);
}
$source = $this->source($actor, $payment, $sourceType);
$order = PurchaseOrder::query()->whereKey($source['purchase_order_id'])->firstOrFail();
app(OrderPartsAccess::class)->assertProcess($actor, $order, true);
abort_unless(hash_equals($source['fingerprint'], $data['fingerprint']), 409, 'As origens mudaram. Reveja a factura e o pagamento.');
@@ -152,7 +196,7 @@ final class ExpenseAllocations
return $retry;
}
$old = $this->current($payment);
$old = $this->current($payment, $sourceType);
abort_unless(($old->version ?? 0) === $data['version'], 409, 'A imputação mudou. Reveja a versão actual.');
$total = BigInteger::zero();
$allocations = [];
@@ -169,7 +213,8 @@ final class ExpenseAllocations
}
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'expense_allocation',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'allocated', 'created_by' => $actor->id,
'data' => ['payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'],
'data' => [...($sourceType === 'common_allocation' ? ['source_type' => 'common_allocation'] : []),
'payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'],
'amount_minor' => (string) $total, 'allocations' => $allocations], 'snapshot' => $source,
'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'expense.allocation_recorded', null, $old?->toArray(), ['record' => $record->toArray()]);
+26 -5
View File
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\PayableJournal;
use Tempo\Finance\GeneralLedger\ReportsWorkspace;
@@ -13,14 +14,25 @@ use Tempo\Finance\Payables\Payables;
/** Standalone adapter; same local package, native finance authority, no SGF remote service. */
final class GeneralLedger
{
public function cycleEnabled(): bool
{
return app(StandaloneRuntime::class)->enabled()
? app(StandaloneRuntime::class)->feature('general-ledger-cycle', DB::connection())
: config('general-ledger.cycle_enabled') === true;
}
/** @return array{actor:User,scope:array<string,int>,person:string} */
private function context(User $user): array
{
abort_unless(app()->environment('payable-testing') && config('general-ledger.synthetic_enabled') === true, 403);
$standalone = app(StandaloneRuntime::class)->enabled();
abort_unless($standalone ? app(StandaloneRuntime::class)->feature('general-ledger', DB::connection())
: app()->environment('payable-testing') && config('general-ledger.synthetic_enabled') === true, 403);
$package = config('general-ledger.path');
abort_unless(is_string($package) && is_file($package.'/bootstrap.php'), 503, 'Pacote contabilístico não composto.');
require_once $package.'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
if (! $standalone) {
LedgerSchema::assertSynthetic(DB::connection());
}
$context = app(SupplierPayables::class)->readContext($user);
abort_unless(DB::table('pa_access')->where($context['scope'])->where(['user_id' => $user->id, 'action' => 'general_ledger.view', 'person' => $context['person']])->exists(), 403);
@@ -29,7 +41,14 @@ final class GeneralLedger
public function can(User $user, string $action): bool
{
$c = $this->context($user);
try {
$c = $this->context($user);
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() === 403) {
return false;
}
throw $error;
}
return DB::table('pa_access')->where($c['scope'])->where(['user_id' => $user->id, 'action' => 'general_ledger.'.$action, 'person' => $c['person']])->exists();
}
@@ -49,7 +68,9 @@ final class GeneralLedger
abort_unless($this->can($user, $action), 403);
};
return new PayableJournal(DB::connection(), $scope, $user->id, $person, fn ($a) => $authorize($a), fn () => $authorize('view', false), fn ($id) => $this->source($user, $scope, $id), $fault);
$hostOptions = app(StandaloneRuntime::class)->enabled() ? ['hostPolicy' => 'COMMON-PAYABLE-JOURNAL-v1'] : [];
return new PayableJournal(DB::connection(), $scope, $user->id, $person, fn ($a) => $authorize($a), fn () => $authorize('view', false), fn ($id) => $this->source($user, $scope, $id), $fault, ...$hostOptions);
}
/** @param array<string,int> $scope
@@ -97,7 +118,7 @@ final class GeneralLedger
/** @return array<string,mixed> */
public function workspace(User $user, int $page = 1): array
{
abort_unless(config('general-ledger.cycle_enabled') === true, 403);
abort_unless($this->cycleEnabled(), 403);
$own = DB::transactionLevel() === 0;
return DB::transaction(function () use ($user, $page, $own) {
+4
View File
@@ -17,6 +17,10 @@ final class ImportBankSupport
{
public function ready(): bool
{
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-bank-support', DB::connection()) && app(ImportDossier::class)->ready();
}
return config('import-bank-support.qa_enabled') === true && app(ImportDossier::class)->ready();
}
+5
View File
@@ -29,6 +29,11 @@ final class ImportDossier
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-dossier', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('import-dossier.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
+5
View File
@@ -21,6 +21,11 @@ final class ImportEstimates
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-estimates', $db)
&& class_exists(BudgetImportEstimate::class) && Schema::hasTable('supply_records');
}
return config('import-estimates.qa_enabled') === true && app()->environment('testing')
&& class_exists(BudgetImportEstimate::class) && Schema::hasTable('supply_records')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+5
View File
@@ -23,6 +23,11 @@ final class ImportLandedCosts
public function ready(): bool
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-landed-costs', $db)
&& class_exists(BudgetLandedCostPlan::class);
}
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
+5
View File
@@ -21,6 +21,11 @@ final class ImportLegalRules
{
public function ready(): bool
{
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-legal', DB::connection())
&& app(ImportTariffCodes::class)->ready();
}
return config('import-legal.qa_enabled') === true && app(ImportTariffCodes::class)->ready();
}
+4
View File
@@ -15,6 +15,10 @@ final class ImportReadiness
{
public function ready(): bool
{
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-readiness', DB::connection()) && app(ImportDossier::class)->ready();
}
return config('import-readiness.qa_enabled') === true && app(ImportDossier::class)->ready();
}
+5
View File
@@ -51,6 +51,11 @@ final class ImportTariffCodes
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('import-tariffs', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('import-tariffs.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+4
View File
@@ -23,6 +23,10 @@ final class OperationalOrders
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('operational-orders', $db) && Schema::hasTable('supply_records');
}
return config('operational-orders.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+4 -1
View File
@@ -22,8 +22,11 @@ final class OrderPartsPreparation
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
$runtime = new \ReflectionClass(BudgetControl::class);
$available = app(StandaloneRuntime::class)->enabled()
? app(StandaloneRuntime::class)->feature('order-parts', $db)
: config('order-parts.qa_enabled') === true && app()->environment('testing') && $isolated;
return config('order-parts.qa_enabled') === true && app()->environment('testing') && $isolated
return $available
&& $runtime->hasMethod('commitOrderParts') && $runtime->hasConstant('ORDER_PARTS_VERSION')
&& $runtime->getConstant('ORDER_PARTS_VERSION') === CommonBudget::ORDER_PARTS_CONTRACT;
}
+4
View File
@@ -20,6 +20,10 @@ final class PrivateAuditAccess
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('private-audit', $db) && Schema::hasTable('private_audit_exports');
}
return config('private-audit.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+17
View File
@@ -98,6 +98,11 @@ final class PrivateAuditCatalogue
'gl_proposals' => 'id tenant_id company_id unit_id effect_key obligation_id capture_version revision snapshot prepared_by prepared_person reason created_at',
'gl_reviews' => 'id tenant_id company_id unit_id proposal_id revision decision reviewed_by reviewed_person reason created_at',
'gl_rules' => 'id tenant_id company_id unit_id rule_key version policy effect_type currency valid_from valid_to debit_account_id credit_account_id created_by reason created_at',
'gl_corrections' => 'id tenant_id company_id unit_id original_journal_id reverse_proposal_id replacement_proposal_id revision prepared_by prepared_person reason created_at',
'gl_correction_results' => 'id tenant_id company_id unit_id correction_id original_journal_id reverse_journal_id replacement_journal_id actor_id reason created_at',
'gl_period_checks' => 'id tenant_id company_id unit_id period_key revision snapshot prepared_by prepared_person reason created_at',
'gl_period_reviews' => 'id tenant_id company_id unit_id check_id revision decision actor_id person reason created_at',
'gl_period_closures' => 'id tenant_id company_id unit_id check_id review_id period_key period_version actor_id reason created_at',
'invoice_items' => 'id tenant_id invoice_id purchase_order_item_id quantity_milli subtotal_minor tax_minor snapshot',
'invoices' => 'id tenant_id purchase_order_id supplier_id created_by validated_by number issued_on status subtotal_minor tax_minor total_minor snapshot validated_at created_at updated_at',
'pa_commands' => 'id tenant_id company_id unit_id actor_id command_key request_hash result created_at',
@@ -109,6 +114,17 @@ final class PrivateAuditCatalogue
'pa_payment_decisions' => 'id tenant_id company_id unit_id obligation_id imported_payment_id sequence previous_hash history_hash payment_snapshot actor_id created_at',
'pa_proposals' => 'id tenant_id company_id unit_id source_id source_revision capture_version snapshot missing prepared_by prepared_person reason created_at',
'pa_sources' => 'id tenant_id company_id unit_id source_key local_source_id created_at',
'ps_payments' => 'id tenant_id company_id unit_id obligation_id fact_key evidence_key supplier_key currency amount_minor paid_on payload_hash prepared_by prepared_person reason created_at',
'ps_payment_decisions' => 'id tenant_id company_id unit_id payment_id decision actor_id person reason created_at',
'ps_proposals' => 'id tenant_id company_id unit_id payment_id reference_key plan_hash plan prepared_by prepared_person reason created_at allocation_cycle',
'ps_allocation_aliases' => 'id tenant_id company_id unit_id reference_key proposal_id actor_id created_at',
'ps_allocation_decisions' => 'id tenant_id company_id unit_id proposal_id decision actor_id person reason created_at',
'ps_allocations' => 'id tenant_id company_id unit_id payment_id obligation_id amount_minor source_revision decision_id created_at',
'ps_commands' => 'id tenant_id company_id unit_id actor_id command_key request_hash result created_at',
'ps_events' => 'id tenant_id company_id unit_id payment_id actor_id person kind payload created_at',
'ps_outbox' => 'event_id state',
'ps_reversal_proposals' => 'id tenant_id company_id unit_id allocation_id source_revision prepared_by prepared_person reason created_at',
'ps_reversals' => 'id tenant_id company_id unit_id allocation_id proposal_id payment_id obligation_id source_revision amount_minor actor_id person reason created_at',
'sgf_invoice_dispatch_events' => 'id dispatch_id tenant_id version actor_id action reason before_state after_state created_at',
'sgf_invoice_dispatches' => 'id tenant_id supplier_id reference number connection_id mapping_id mapping_snapshot mapping_hash document reason source_version version phase ever_sending approval_hash preview_actor_id source_context_hash operation_key lease_until receipt created_by created_at updated_at',
],
@@ -162,6 +178,7 @@ final class PrivateAuditCatalogue
'ps_allocations' => ['payload', 'result'],
'ps_commands' => ['payload', 'result'],
'ps_events' => ['payload'],
'gl_period_checks' => ['snapshot'],
'ps_payment_decisions' => ['payload', 'plan', 'result'],
'ps_payments' => ['payload', 'plan', 'result', 'snapshot'],
'ps_proposals' => ['payload', 'plan', 'result'],
+7 -5
View File
@@ -80,15 +80,17 @@ final class PrivateAuditSourceReader
if ($table === 'tenants') {
return $query->where('id', $actor->tenant_id);
}
if ($table === 'pa_outbox') {
return $query->join('pa_events', 'pa_events.id', '=', 'pa_outbox.event_id')
->where('pa_events.tenant_id', $actor->tenant_id)->where('pa_events.company_id', 0)->where('pa_events.unit_id', 0);
if (in_array($table, ['pa_outbox', 'ps_outbox'], true)) {
$events = $table === 'pa_outbox' ? 'pa_events' : 'ps_events';
return $query->join($events, $events.'.id', '=', $table.'.event_id')
->where($events.'.tenant_id', $actor->tenant_id)->where($events.'.company_id', 0)->where($events.'.unit_id', 0);
}
if (! in_array('tenant_id', $available, true)) {
throw new LogicException('Fonte sem âmbito de empresa explícito.');
}
$query->where($table.'.tenant_id', $actor->tenant_id);
if (str_starts_with($table, 'pa_') || str_starts_with($table, 'gl_')) {
if (str_starts_with($table, 'pa_') || str_starts_with($table, 'ps_') || str_starts_with($table, 'gl_')) {
// The standalone Compras adapters explicitly use company/unit zero inside the current tenant.
if (! in_array('company_id', $available, true) || ! in_array('unit_id', $available, true)) {
throw new LogicException('Preserve o âmbito do núcleo financeiro comum.');
@@ -108,7 +110,7 @@ final class PrivateAuditSourceReader
if ($columns === []) {
throw new LogicException('Fonte instalada sem campos conhecidos.');
}
$key = in_array('id', $columns, true) ? 'id' : ($table === 'pa_outbox' ? 'event_id' : 'tenant_id');
$key = in_array('id', $columns, true) ? 'id' : (in_array($table, ['pa_outbox', 'ps_outbox'], true) ? 'event_id' : 'tenant_id');
if ($table === 'external_payments') {
foreach (ExternalPayment::query()->select($columns)->orderBy('id')->lazy(100) as $payment) {
$row = [];
+30 -8
View File
@@ -34,11 +34,13 @@ class ProcurementPaymentInsights
$categoryCoverage = ['allocated' => 0, 'unallocated' => 0, 'indeterminate' => 0];
$categories = [];
$unassigned = [];
$seen = [];
foreach ($invoices->select(['id', 'supplier_id', 'snapshot'])->lazyById(200) as $invoice) {
$coverage['invoices']++;
$rows = [];
try {
foreach ($adapter->readPaymentHistory($actor, $invoice->id) as $payment) {
$facts = [...$adapter->readPaymentHistory($actor, $invoice->id), ...app(CommonPaymentFacts::class)->forInvoice($actor, $invoice->id)];
foreach ($facts as $payment) {
if ($payment['status'] !== 'confirmed') {
continue;
}
@@ -63,19 +65,30 @@ class ProcurementPaymentInsights
continue;
}
foreach ($rows as $payment) {
$identity = ($payment['source_type'] ?? 'external_payment') === 'common_allocation'
? 'common:'.$payment['common_payment_id'] : 'native:'.$payment['id'];
$currency = $payment['currency'];
$currencies[$currency] ??= ['currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$currencies[$currency]['count']++;
if (! isset($seen['currency'][$currency][$identity])) {
$currencies[$currency]['count']++;
$seen['currency'][$currency][$identity] = true;
}
$currencies[$currency]['amount_minor'] = (string) BigInteger::of($currencies[$currency]['amount_minor'])->plus($payment['amount_minor']);
$key = $invoice->getAttribute('supplier_id').':'.$currency;
$name = $invoice->snapshot['supplier']['name'] ?? null;
$suppliers[$key] ??= ['supplier_id' => (int) $invoice->getAttribute('supplier_id'),
'supplier_name' => is_string($name) && trim($name) !== '' ? $name : 'Fornecedor #'.$invoice->getAttribute('supplier_id'),
'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$suppliers[$key]['count']++;
if (! isset($seen['supplier'][$key][$identity])) {
$suppliers[$key]['count']++;
$seen['supplier'][$key][$identity] = true;
}
$suppliers[$key]['amount_minor'] = (string) BigInteger::of($suppliers[$key]['amount_minor'])->plus($payment['amount_minor']);
$attribution = app(ExpenseAllocations::class)->projection($actor, $payment['id']);
$categoryCoverage[$attribution['state']]++;
$attribution = app(ExpenseAllocations::class)->projection($actor, $payment['id'], $payment['source_type'] ?? 'external_payment');
if (! isset($seen['category_state'][$attribution['state']][$identity])) {
$categoryCoverage[$attribution['state']]++;
$seen['category_state'][$attribution['state']][$identity] = true;
}
if ($attribution['state'] === 'allocated') {
foreach ($attribution['allocations'] as $allocation) {
if ($allocation['amount_minor'] === '0') {
@@ -83,16 +96,25 @@ class ProcurementPaymentInsights
}
$categoryKey = json_encode([$allocation['category'], $currency], JSON_THROW_ON_ERROR);
$categories[$categoryKey] ??= ['category' => $allocation['category'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$categories[$categoryKey]['count']++;
if (! isset($seen['category'][$categoryKey][$identity])) {
$categories[$categoryKey]['count']++;
$seen['category'][$categoryKey][$identity] = true;
}
$categories[$categoryKey]['amount_minor'] = (string) BigInteger::of($categories[$categoryKey]['amount_minor'])->plus($allocation['amount_minor']);
}
} else {
$unassignedKey = $currency.':'.$attribution['state'];
$unassigned[$unassignedKey] ??= ['state' => $attribution['state'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$unassigned[$unassignedKey]['count']++;
if (! isset($seen['unassigned'][$unassignedKey][$identity])) {
$unassigned[$unassignedKey]['count']++;
$seen['unassigned'][$unassignedKey][$identity] = true;
}
$unassigned[$unassignedKey]['amount_minor'] = (string) BigInteger::of($unassigned[$unassignedKey]['amount_minor'])->plus($payment['amount_minor']);
}
$coverage['confirmed_payments']++;
if (! isset($seen['payment'][$identity])) {
$coverage['confirmed_payments']++;
$seen['payment'][$identity] = true;
}
}
}
ksort($currencies);
@@ -0,0 +1,63 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Blueprint;
use LogicException;
/** Single additive schema definition shared by explicit installation and guarded QA. */
final class PurchaseOrderSourcesSchema
{
public static function install(Connection $db): void
{
$schema = $db->getSchemaBuilder();
if ($schema->hasTable('purchase_order_sources') || $schema->hasColumn('purchase_orders', 'order_key') || ! $schema->hasTable('budget_order_commands')) {
throw new LogicException('Install the optional financial schema first; do not reinstall or repair a partial host schema automatically.');
}
$db->transaction(function () use ($db, $schema): void {
$schema->table('purchase_orders', function (Blueprint $table): void {
$table->dropUnique(['requisition_id']);
$table->dropUnique(['purchase_award_id']);
$table->uuid('order_key')->nullable();
$table->string('order_payload_hash', 64)->nullable();
$table->unsignedInteger('order_source_count')->nullable();
$table->unique(['tenant_id', 'order_key']);
});
$schema->table('purchase_order_items', function (Blueprint $table): void {
$table->foreignId('quotation_item_id')->nullable()->constrained()->restrictOnDelete();
$table->unsignedBigInteger('quantity_offset_milli')->nullable();
});
$schema->create('purchase_order_sources', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('purchase_order_id')->constrained()->restrictOnDelete();
$table->foreignId('requisition_id')->constrained()->restrictOnDelete();
$table->foreignId('purchase_award_id')->constrained()->restrictOnDelete();
$table->foreignId('quotation_id')->constrained()->restrictOnDelete();
$table->json('snapshot');
$table->unique(['purchase_order_id', 'requisition_id']);
});
if ($db->getDriverName() === 'pgsql') {
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON purchase_order_sources FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
$db->unprepared(<<<'SQL'
CREATE FUNCTION sgc_order_parts_header_guard() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF OLD.order_key IS NOT NULL THEN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Preserve partial order history'; END IF;
IF (to_jsonb(NEW) - 'number' - 'status') IS DISTINCT FROM (to_jsonb(OLD) - 'number' - 'status') THEN
RAISE EXCEPTION 'Preserve the frozen partial order';
END IF;
ELSIF TG_OP = 'UPDATE' AND NEW.order_key IS NOT NULL THEN
RAISE EXCEPTION 'Do not relabel an issued legacy order';
END IF;
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER order_parts_header_guard BEFORE UPDATE OR DELETE ON purchase_orders FOR EACH ROW EXECUTE FUNCTION sgc_order_parts_header_guard();
CREATE TRIGGER order_parts_line_guard BEFORE UPDATE OR DELETE ON purchase_order_items FOR EACH ROW WHEN (OLD.quotation_item_id IS NOT NULL) EXECUTE FUNCTION sgc_distribution_history_guard();
SQL);
}
});
}
}
@@ -123,7 +123,7 @@ final class RequisitionAccountAssignments
}
$frozen = $this->freezeForItems($actor, $ids);
if (! app(RequisitionLedgerAccounts::class)->ready()) {
abort_if(config('requisition-accounts.qa_enabled') === true && $items->isNotEmpty(),
abort_if((config('requisition-accounts.qa_enabled') === true || app(StandaloneRuntime::class)->requested('requisition-accounts')) && $items->isNotEmpty(),
503, 'Plano de contas indisponível. Não foram criadas reservas ou aprovações.');
return;
@@ -27,8 +27,10 @@ class RequisitionBudgetDistributions
: DB::getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName());
$deployment = config('budget-distributions.enabled') === true;
$qa = config('budget-distributions.qa_enabled') === true && app()->environment('testing') && $isolated;
if (! $deployment && ! $qa) {
$standalone = app(StandaloneRuntime::class)->enabled()
&& app(StandaloneRuntime::class)->feature('budget-distributions', DB::connection());
$qa = ! app(StandaloneRuntime::class)->enabled() && config('budget-distributions.qa_enabled') === true && app()->environment('testing') && $isolated;
if (! $deployment && ! $qa && ! $standalone) {
return false;
}
if ($deployment) {
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use Illuminate\Database\Schema\Blueprint;
use LogicException;
/** Single additive schema definition shared by explicit installation and guarded QA. */
final class RequisitionCycleSchema
{
public static function install(Connection $db): void
{
$schema = $db->getSchemaBuilder();
if ($schema->hasTable('budget_requisition_cycles') || $schema->hasColumn('requisitions', 'approval_cycle')
|| $schema->hasColumn('budget_entries', 'requisition_cycle') || $schema->hasColumn('workflow_notices', 'event_kind')) {
throw new LogicException('Do not reinstall or repair partial cycle structures automatically.');
}
$schema->table('requisitions', fn (Blueprint $table) => $table->unsignedInteger('approval_cycle')->default(1));
$schema->table('approval_steps', function (Blueprint $table) {
$table->unsignedInteger('approval_cycle')->default(1);
$table->dropUnique(['requisition_id', 'position']);
$table->unique(['requisition_id', 'approval_cycle', 'position'], 'approval_step_cycle_position');
});
$schema->table('budget_entries', function (Blueprint $table) {
$table->unsignedInteger('requisition_cycle')->default(1);
$table->dropUnique(['requisition_id', 'kind']);
$table->unique(['requisition_id', 'requisition_cycle', 'kind'], 'budget_entry_cycle_kind');
});
$schema->table('workflow_notices', function (Blueprint $table) {
$table->string('event_kind', 20)->default('task');
$table->dropUnique(['approval_step_id', 'recipient_id']);
$table->unique(['approval_step_id', 'recipient_id', 'event_kind'], 'workflow_notice_event_recipient');
});
if ($schema->hasTable('budget_distributions')) {
$schema->table('budget_distributions', function (Blueprint $table) {
$table->unsignedInteger('requisition_cycle')->default(1);
$table->dropUnique(['requisition_id']);
$table->unique(['requisition_id', 'requisition_cycle'], 'budget_distribution_cycle');
});
}
$schema->create('budget_requisition_cycles', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('requisition_id')->constrained()->restrictOnDelete();
$table->unsignedInteger('cycle');
$table->string('state', 20);
$table->uuid('open_operation');
$table->foreignId('opened_by')->constrained('users')->restrictOnDelete();
$table->timestamp('opened_at');
$table->uuid('close_operation')->nullable();
$table->foreignId('closed_by')->nullable()->constrained('users')->restrictOnDelete();
$table->timestamp('closed_at')->nullable();
$table->unique(['tenant_id', 'requisition_id', 'cycle'], 'budget_requisition_cycle');
$table->unique(['tenant_id', 'open_operation']);
$table->unique(['tenant_id', 'close_operation']);
});
}
}
+6 -3
View File
@@ -27,10 +27,13 @@ final class RequisitionExpiry
$db = DB::connection();
$purchasing = new \ReflectionClass(InternalRequisitions::class);
return config('requisition-expiry.qa_enabled') === true && app()->environment('testing')
$available = app(StandaloneRuntime::class)->enabled()
? app(StandaloneRuntime::class)->feature('requisition-expiry', $db)
: config('requisition-expiry.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:') || ($db->getDriverName() === 'pgsql'
&& $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
&& $purchasing->hasMethod('supportsExpiryCycles') && $purchasing->getMethod('supportsExpiryCycles')->invoke(null) === true
&& $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
return $available && $purchasing->hasMethod('supportsExpiryCycles') && $purchasing->getMethod('supportsExpiryCycles')->invoke(null) === true
&& defined(BudgetControl::class.'::REQUISITION_CYCLES_VERSION')
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
@@ -14,6 +14,11 @@ final class RequisitionLedgerAccounts
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('requisition-accounts', $db)
&& Schema::hasColumns('gl_accounts', ['id', 'tenant_id', 'company_id', 'unit_id', 'code', 'label', 'currency', 'is_movement']);
}
return config('requisition-accounts.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace App\Services;
use FilesystemIterator;
use LogicException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
/** Verify every byte before an executable standalone package can be loaded. */
final class StandaloneArtifact
{
public const CONTRACT = 'COMPRAS-STANDALONE-v1';
public const PACKAGES = ['budget-control', 'purchasing', 'payables', 'general-ledger'];
/** @return array{root:string,manifest:array<string,mixed>,paths:array<string,string>} */
public function verify(string $directory, string $pin): array
{
$root = realpath($directory);
if ($root === false || is_link($directory) || ! preg_match('/^[a-f0-9]{64}$/D', $pin)) {
throw new LogicException('COMPRAS_RUNTIME_LOCATION');
}
$manifestFile = $root.'/manifest.json';
if (! is_file($manifestFile) || is_link($manifestFile)) {
throw new LogicException('COMPRAS_RUNTIME_MANIFEST');
}
$bytes = file_get_contents($manifestFile);
if (! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
throw new LogicException('COMPRAS_RUNTIME_MANIFEST_HASH');
}
$manifest = json_decode($bytes, true, 64, JSON_THROW_ON_ERROR);
if (! is_array($manifest) || ($manifest['contract'] ?? null) !== self::CONTRACT
|| ($manifest['product'] ?? null) !== 'compras' || ($manifest['version'] ?? null) !== 1
|| ! is_array($manifest['files'] ?? null) || ! array_is_list($manifest['files']) || count($manifest['files']) < 4
|| ! is_array($manifest['capabilities'] ?? null) || ! array_is_list($manifest['capabilities'])
|| count(array_unique($manifest['capabilities'], SORT_REGULAR)) !== count($manifest['capabilities'])) {
throw new LogicException('COMPRAS_RUNTIME_CONTRACT');
}
foreach ($manifest['capabilities'] as $capability) {
if (! is_string($capability) || ! preg_match('/^[a-z][a-z0-9-]{1,63}$/D', $capability)) {
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY');
}
}
$seen = ['manifest.json' => true];
foreach ($manifest['files'] as $entry) {
if (! is_array($entry)) {
throw new LogicException('COMPRAS_RUNTIME_FILE_IDENTITY');
}
$file = $entry['file'] ?? null;
$expected = $entry['sha256'] ?? null;
if (! is_string($file) || ! preg_match('~^[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+$~D', $file)
|| in_array('.', explode('/', $file), true) || in_array('..', explode('/', $file), true)
|| isset($seen[$file]) || ! is_string($expected) || ! preg_match('/^[a-f0-9]{64}$/D', $expected)) {
throw new LogicException('COMPRAS_RUNTIME_FILE_IDENTITY');
}
$actual = realpath($root.'/'.$file);
$actualHash = $actual !== false && is_file($actual) ? hash_file('sha256', $actual) : false;
if ($actual === false || ! str_starts_with($actual, $root.DIRECTORY_SEPARATOR)
|| ! is_file($actual) || is_link($root.'/'.$file) || ! is_string($actualHash) || ! hash_equals($expected, $actualHash)) {
throw new LogicException('COMPRAS_RUNTIME_FILE_HASH');
}
$seen[$file] = true;
}
$actualFiles = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $file) {
if ($file->isLink() || (! $file->isFile() && ! $file->isDir())) {
throw new LogicException('COMPRAS_RUNTIME_LINK');
}
if ($file->isFile()) {
$actualFiles[] = str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1));
}
}
$expectedFiles = array_keys($seen);
sort($actualFiles);
sort($expectedFiles);
if ($actualFiles !== $expectedFiles) {
throw new LogicException('COMPRAS_RUNTIME_FILE_SET');
}
$paths = [];
foreach (self::PACKAGES as $package) {
if (! isset($seen[$package.'/bootstrap.php'])) {
throw new LogicException('COMPRAS_RUNTIME_PACKAGE_MISSING');
}
$paths[$package] = $root.'/'.$package;
}
return ['root' => $root, 'manifest' => $manifest, 'paths' => $paths];
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Explicit additive installation only; never called by application boot or a business request. */
final class StandaloneExtensionSchema
{
public static function install(Connection $db): void
{
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->assertInstallation($db);
$runtime->assertLoadedPackages(allowMissing: true);
$paths = $runtime->artifact()['paths'];
foreach (StandaloneArtifact::PACKAGES as $package) {
require_once $paths[$package].'/bootstrap.php';
}
$runtime->assertLoadedPackages();
$schemas = [];
foreach ([LedgerSchema::class => ['COMMON-LEDGER-HOST-SCHEMA-v1', true],
'Tempo\\Finance\\Payables\\SettlementSchema' => ['COMMON-PAYABLE-SETTLEMENT-HOST-SCHEMA-v1', false],
'Tempo\\Finance\\Payables\\ReversalSchema' => ['COMMON-PAYABLE-REVERSAL-HOST-SCHEMA-v1', false],
'Tempo\\Finance\\GeneralLedger\\CycleSchema' => ['COMMON-LEDGER-CYCLE-HOST-SCHEMA-v1', true]] as $class => [$contract, $connectionArgument]) {
if (! class_exists($class, false)) {
throw new \LogicException('COMPRAS_RUNTIME_FINANCE_SCHEMA_MISSING');
}
$schema = new \ReflectionClass($class);
if (! $schema->hasConstant('HOST_SCHEMA_CONTRACT') || $schema->getConstant('HOST_SCHEMA_CONTRACT') !== $contract
|| ! $schema->hasMethod('installForHost')) {
throw new \LogicException('COMPRAS_RUNTIME_FINANCE_SCHEMA_CONTRACT');
}
$schemas[] = [$schema, $contract, $connectionArgument];
}
$db->transaction(function () use ($db, $runtime, $settings, $schemas) {
$db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', [$settings['installation_id']]);
$runtime->assertInstallation($db);
foreach (['budget_distributions', 'budget_order_commands', 'purchase_order_sources', 'budget_landed_commands',
'budget_requisition_cycles', 'gl_accounts', 'ps_payments', 'ps_reversals', 'gl_corrections'] as $table) {
if ($db->getSchemaBuilder()->hasTable($table)) {
throw new \LogicException('COMPRAS_RUNTIME_EXTENSION_SCHEMA_EXISTS');
}
}
// The normal application migrations already install the common payables schema.
StandaloneSchema::verify($db->getSchemaBuilder(), ['supplier-payables' => true]);
BudgetDistributionSchema::install();
BudgetOrderPartsSchema::install($db);
PurchaseOrderSourcesSchema::install($db);
BudgetLandedCostSchema::install($db);
RequisitionCycleSchema::install($db);
foreach ($schemas as [$schema, $contract, $connectionArgument]) {
$arguments = [$contract, fn () => $runtime->assertInstallation($db)];
if ($connectionArgument) {
array_unshift($arguments, $db);
}
$schema->getMethod('installForHost')->invokeArgs(null, $arguments);
}
});
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use LogicException;
/** Deployment operation, separate from feature activation and all actor grants. */
final class StandaloneInstallation
{
/** @return array<string,mixed> */
public function prepare(string $database, string $role, string $operator, string $reason, bool $apply = false, bool $rebind = false): array
{
Validator::make(compact('database', 'role', 'operator', 'reason'), [
'database' => 'required|string|max:200', 'role' => 'required|string|max:200',
'operator' => 'required|string|min:3|max:200', 'reason' => 'required|string|min:10|max:4000',
])->validate();
if (config('standalone-runtime.enabled') === true) {
throw new LogicException('Disable runtime activation before explicit installation or recovery.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$artifact = $runtime->artifact();
$runtime->assertLoadedPackages(allowMissing: true);
foreach (StandaloneArtifact::PACKAGES as $package) {
require_once $artifact['paths'][$package].'/bootstrap.php';
}
$runtime->assertLoadedPackages();
$db = DB::connection();
$binding = StandaloneRuntime::databaseBinding($db);
$identity = $db->selectOne('SELECT current_database() AS database_name,current_user AS role_name');
if ($identity === null || $identity->database_name !== $database || $identity->role_name !== $role) {
throw new LogicException('COMPRAS_RUNTIME_EXPECTED_DESTINATION');
}
$plan = ['contract' => StandaloneArtifact::CONTRACT, 'installation_id' => $settings['installation_id'],
'manifest_sha256' => $settings['manifest_sha256'], 'database' => $database, 'role' => $role,
'feature_activation' => false, 'actor_grants' => false, 'rebind' => $rebind];
if (! $apply) {
return $plan + ['state' => 'preview', 'written' => false];
}
return $db->transaction(function () use ($db, $runtime, $settings, $binding, $operator, $reason, $rebind, $plan) {
$db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', ['COMPRAS-STANDALONE-INSTALLATION']);
$schema = $db->getSchemaBuilder();
if (! $schema->hasTable('compras_runtime_installations')) {
if ($rebind) {
throw new LogicException('COMPRAS_RUNTIME_RECOVERY_HISTORY_MISSING');
}
(require database_path('standalone-migrations/2026_11_29_000001_create_runtime_installations.php'))->up();
}
if ($db->table('compras_runtime_installations')->where('id', $settings['installation_id'])->exists()) {
$runtime->assertInstallation($db);
StandaloneSchema::verify($schema, $settings['features']);
return $plan + ['state' => 'already_prepared', 'written' => false];
}
if ($rebind) {
StandaloneSchema::verify($schema, $settings['features']);
}
$db->table('compras_runtime_installations')->insert([
'id' => $settings['installation_id'], 'product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT,
'manifest_sha256' => $settings['manifest_sha256'], 'database_binding_sha256' => $binding,
'recorded_by' => $operator, 'reason' => $reason, 'installed_at' => now(),
]);
if (! $rebind) {
StandaloneExtensionSchema::install($db);
}
$runtime->assertInstallation($db);
StandaloneSchema::verify($schema, $settings['features']);
return $plan + ['state' => $rebind ? 'rebound' : 'prepared', 'written' => true];
});
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use LogicException;
/** Explicit host composition. Verification grants no application capability to an actor. */
final class StandaloneRuntime
{
public const FEATURES = ['capital-register', 'operational-orders', 'requisition-accounts', 'requisition-expiry',
'urgent-reviews', 'urgent-quotations', 'conflict-releases', 'private-audit', 'expense-allocations',
'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier',
'import-bank-support', 'import-readiness', 'import-estimates', 'import-landed-costs', 'budget-distributions',
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle'];
/** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
private ?array $artifact = null;
/** @param array<string,mixed> $settings */
public function __construct(private readonly array $settings, private readonly StandaloneArtifact $verifier) {}
public function enabled(): bool
{
return ($this->settings['enabled'] ?? false) === true;
}
public function requested(string $feature): bool
{
return $this->enabled() && ($this->settings['features'][$feature] ?? false) === true;
}
/** @return array<string,string>|null */
public function configure(Connection $db): ?array
{
if (! $this->enabled()) {
return null;
}
$this->assertInstallation($db);
StandaloneSchema::verify($db->getSchemaBuilder(), $this->settings['features'] ?? []);
return $this->artifact()['paths'];
}
/** Refuse a process that loaded an older package before selecting this composition. */
public function assertLoadedPackages(bool $allowMissing = false): void
{
$artifact = $this->artifact();
foreach ([
'Tempo\\Finance\\Budget\\BudgetControl' => 'budget-control/src/BudgetControl.php',
'Tempo\\Purchasing\\Internal\\InternalRequisitions' => 'purchasing/src/InternalRequisitions.php',
'Tempo\\Finance\\Payables\\Payables' => 'payables/src/Payables.php',
'Tempo\\Finance\\GeneralLedger\\LedgerSchema' => 'general-ledger/src/LedgerSchema.php',
] as $class => $file) {
if (! class_exists($class, false)) {
if ($allowMissing) {
continue;
}
throw new LogicException('COMPRAS_RUNTIME_CLASS_MISSING');
}
$loaded = (new \ReflectionClass($class))->getFileName();
if (! is_string($loaded) || realpath($loaded) !== realpath($artifact['root'].'/'.$file)) {
throw new LogicException('COMPRAS_RUNTIME_CLASS_LOCATION');
}
}
if (! $allowMissing) {
if ($this->requested('general-ledger')) {
$journal = new \ReflectionClass('Tempo\\Finance\\GeneralLedger\\PayableJournal');
if (! $journal->hasConstant('HOST_POLICY') || $journal->getConstant('HOST_POLICY') !== 'COMMON-PAYABLE-JOURNAL-v1'
|| ! in_array('hostPolicy', array_map(fn ($parameter) => $parameter->getName(), $journal->getConstructor()?->getParameters() ?? []), true)) {
throw new LogicException('COMPRAS_RUNTIME_JOURNAL_POLICY');
}
}
$budget = new \ReflectionClass('Tempo\\Finance\\Budget\\BudgetControl');
foreach ([
'budget-distributions' => ['DISTRIBUTIONS_VERSION', CommonBudget::DISTRIBUTIONS_CONTRACT, ['recordDistribution', 'consumeDistribution', 'amendDistribution']],
'order-parts' => ['ORDER_PARTS_VERSION', CommonBudget::ORDER_PARTS_CONTRACT, ['commitOrderParts', 'consumeOrderParts', 'cancelOrderParts']],
'import-landed-costs' => ['LANDED_COSTS_VERSION', CommonBudget::LANDED_COSTS_CONTRACT, ['reserveLandedCosts', 'transitionLandedCosts']],
'import-estimates' => ['IMPORT_ESTIMATE_VERSION', CommonBudget::IMPORT_ESTIMATE_CONTRACT, ['reserveImportEstimate', 'releaseImportEstimate']],
'requisition-expiry' => ['REQUISITION_CYCLES_VERSION', CommonBudget::REQUISITION_CYCLES_CONTRACT, ['beginRequisitionCycle', 'closeRequisitionCycle']],
] as $feature => [$constant, $contract, $methods]) {
if (! $this->requested($feature)) {
continue;
}
if (! $budget->hasConstant($constant) || $budget->getConstant($constant) !== $contract) {
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_CONTRACT:'.$feature);
}
foreach ($methods as $method) {
if (! $budget->hasMethod($method)) {
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_METHOD:'.$feature);
}
}
}
if ($this->requested('requisition-expiry')) {
$purchasing = new \ReflectionClass('Tempo\\Purchasing\\Internal\\InternalRequisitions');
if (! $purchasing->hasMethod('supportsExpiryCycles') || $purchasing->getMethod('supportsExpiryCycles')->invoke(null) !== true) {
throw new LogicException('COMPRAS_RUNTIME_PURCHASING_CYCLES');
}
}
}
}
/** @return array{root:string,manifest:array<string,mixed>,paths:array<string,string>} */
public function artifact(): array
{
if ($this->artifact !== null) {
return $this->artifact;
}
$root = $this->settings['root'] ?? null;
$pin = $this->settings['manifest_sha256'] ?? null;
$id = $this->settings['installation_id'] ?? null;
if (! $this->enabled() || ! is_string($root) || ! is_string($pin) || ! is_string($id)
|| ! preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/D', $id)) {
throw new LogicException('COMPRAS_RUNTIME_CONFIGURATION');
}
$artifact = $this->verifier->verify($root, $pin);
$features = $this->settings['features'] ?? [];
if (! is_array($features)) {
throw new LogicException('COMPRAS_RUNTIME_FEATURES');
}
foreach ($features as $feature => $enabled) {
if (! is_string($feature) || ! in_array($feature, self::FEATURES, true) || ! is_bool($enabled)
|| ($enabled && ! in_array($feature, $artifact['manifest']['capabilities'], true))) {
throw new LogicException('COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE');
}
}
return $this->artifact = $artifact;
}
/** No query when the composition is off; no schema creation or repair during a request. */
public function feature(string $feature, Connection $db): bool
{
if (! $this->requested($feature)) {
return false;
}
$this->assertInstallation($db);
return true;
}
public function assertInstallation(Connection $db): void
{
$this->artifact();
$binding = self::databaseBinding($db);
if (! $db->getSchemaBuilder()->hasTable('compras_runtime_installations')) {
throw new LogicException('COMPRAS_RUNTIME_INSTALLATION_MISSING');
}
$receipt = $db->table('compras_runtime_installations')->where('id', $this->settings['installation_id'])->first();
if ($receipt === null || $receipt->product !== 'compras' || $receipt->contract !== StandaloneArtifact::CONTRACT
|| ! hash_equals($this->settings['manifest_sha256'], (string) $receipt->manifest_sha256)
|| ! hash_equals($binding, (string) $receipt->database_binding_sha256)) {
throw new LogicException('COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
}
}
/** Database and runtime role are bound explicitly, without an SGF or test naming convention. */
public static function databaseBinding(Connection $db): string
{
if ($db->getDriverName() !== 'pgsql') {
throw new LogicException('COMPRAS_RUNTIME_DATABASE_DRIVER');
}
$identity = $db->selectOne('SELECT current_database() AS database_name, current_user AS role_name,
(SELECT oid::text FROM pg_database WHERE datname=current_database()) AS database_oid,
inet_server_addr()::text AS server_address, inet_server_port() AS server_port,
CASE WHEN rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls THEN 1 ELSE 0 END AS elevated
FROM pg_roles WHERE rolname=current_user');
if ($identity === null || (int) $identity->elevated !== 0 || $identity->server_address === null || $identity->server_port === null) {
throw new LogicException('COMPRAS_RUNTIME_DATABASE_IDENTITY');
}
return hash('sha256', json_encode([
'product' => 'compras', 'database' => $identity->database_name, 'oid' => $identity->database_oid,
'role' => $identity->role_name, 'address' => $identity->server_address, 'port' => (int) $identity->server_port,
], JSON_THROW_ON_ERROR));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Services;
use Illuminate\Database\Schema\Builder;
use LogicException;
/** Read-only startup preflight; never installs, repairs or enables a module. */
final class StandaloneSchema
{
/** @param array<string,mixed> $features */
public static function verify(Builder $schema, array $features): void
{
foreach (['import-legal' => ['import-tariffs'], 'import-bank-support' => ['import-dossier'],
'import-readiness' => ['import-dossier'], 'general-ledger' => ['supplier-payables'],
'supplier-settlements' => ['supplier-payables'], 'general-ledger-cycle' => ['general-ledger', 'supplier-settlements']] as $feature => $dependencies) {
foreach ($dependencies as $dependency) {
if (($features[$feature] ?? false) === true && ($features[$dependency] ?? false) !== true) {
throw new LogicException('COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
}
}
}
$tables = ['supply_records' => ['id', 'tenant_id', 'kind', 'record_key', 'version', 'data', 'snapshot', 'operation_key'],
'requisitions' => ['id', 'tenant_id', 'status'], 'users' => ['id', 'tenant_id']];
foreach ($features as $feature => $enabled) {
if ($enabled !== true) {
continue;
}
$required = match ($feature) {
'capital-register' => ['equipment' => ['id', 'tenant_id', 'department_id']],
'private-audit' => ['private_audit_exports' => ['id', 'tenant_id']],
'conflict-releases' => ['conflict_releases' => ['id', 'tenant_id']],
'requisition-accounts' => ['gl_accounts' => ['id', 'tenant_id', 'company_id', 'unit_id', 'code', 'label', 'currency', 'is_movement']],
'requisition-expiry' => ['budget_requisition_cycles' => ['id', 'requisition_id', 'cycle', 'state'],
'requisitions' => ['approval_cycle', 'process_version'], 'approval_steps' => ['approval_cycle'],
'budget_entries' => ['requisition_cycle'], 'workflow_notices' => ['event_kind'], 'requisition_commands' => ['id']],
'budget-distributions' => ['budget_distributions' => ['id', 'tenant_id'], 'budget_distribution_events' => ['id'],
'budget_distribution_entries' => ['id'], 'budget_distribution_consumptions' => ['id'],
'requisitions' => ['budget_distribution_preparation']],
'order-parts' => ['budget_order_commands' => ['id', 'tenant_id'], 'budget_order_bindings' => ['id'],
'budget_order_allocations' => ['id'], 'budget_order_consumptions' => ['id'], 'purchase_order_sources' => ['id']],
'import-landed-costs' => ['budget_landed_commands' => ['id', 'tenant_id'], 'budget_landed_entries' => ['id']],
'supplier-payables' => ['pa_sources' => ['id', 'tenant_id'], 'pa_proposals' => ['id'], 'pa_obligations' => ['id'],
'pa_events' => ['id'], 'pa_outbox' => ['event_id', 'state'], 'pa_commands' => ['id'], 'pa_access' => ['user_id', 'person', 'action']],
'general-ledger' => ['gl_accounts' => ['id', 'tenant_id'], 'gl_periods' => ['id'], 'gl_rules' => ['id'],
'gl_proposals' => ['id'], 'gl_reviews' => ['id'], 'gl_journals' => ['id'], 'gl_lines' => ['id'],
'gl_commands' => ['id'], 'gl_events' => ['id']],
'supplier-settlements' => ['ps_payments' => ['id', 'tenant_id'], 'ps_payment_decisions' => ['id'],
'ps_proposals' => ['id', 'allocation_cycle'], 'ps_allocation_aliases' => ['id'], 'ps_allocation_decisions' => ['id'],
'ps_allocations' => ['id'], 'ps_commands' => ['id'], 'ps_events' => ['id'], 'ps_outbox' => ['event_id', 'state'],
'ps_reversal_proposals' => ['id'], 'ps_reversals' => ['id']],
'general-ledger-cycle' => ['gl_corrections' => ['id'], 'gl_correction_results' => ['id'],
'gl_period_checks' => ['id'], 'gl_period_reviews' => ['id'], 'gl_period_closures' => ['id']],
default => [],
};
foreach ($required as $table => $columns) {
$tables[$table] = array_values(array_unique([...($tables[$table] ?? []), ...$columns]));
}
}
foreach ($tables as $table => $columns) {
if (! $schema->hasColumns($table, $columns)) {
throw new LogicException('COMPRAS_RUNTIME_SCHEMA_INCOMPLETE:'.$table);
}
}
}
}
+10 -1
View File
@@ -15,6 +15,12 @@ final class SupplierPayables
{
public static function enabled(): bool
{
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('supplier-payables', DB::connection())
&& is_string(config('common-payables.source_instance')) && trim(config('common-payables.source_instance')) !== ''
&& Schema::hasTable('pa_obligations') && Schema::hasTable('pa_access');
}
$isolated = app()->environment(['testing', 'payable-testing']) && DB::connection()->getDriverName() === 'pgsql'
&& (bool) preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName());
@@ -207,7 +213,10 @@ final class SupplierPayables
$engine = $this->engine($u);
$d = $engine->listing(Invoice::query()->where('tenant_id', $u->tenant_id)->pluck('id')->all());
$d['permissions'] = ['prepare' => $this->can($u, 'prepare'), 'validate' => $this->can($u, 'validate')];
$d['payments_available'] = app()->environment('payable-testing') && Schema::hasTable('ps_payments') && $this->can($u, 'payments_view');
$payments = app(StandaloneRuntime::class)->enabled()
? app(StandaloneRuntime::class)->feature('supplier-settlements', DB::connection())
: app()->environment('payable-testing');
$d['payments_available'] = $payments && Schema::hasTable('ps_payments') && $this->can($u, 'payments_view');
$d['history_import_available'] = self::historyEnabled();
$d['history_decisions_available'] = self::historyDecisionsEnabled();
+5
View File
@@ -20,6 +20,11 @@ final class UrgentQuotationBasis
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('urgent-quotations', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('urgent-quotations.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
@@ -17,6 +17,11 @@ final class UrgentRequisitionReviews
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('urgent-reviews', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('urgent-reviews.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'