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'
+64 -19
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,15 +35,28 @@ 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();
$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'])
&& preg_match('/^[A-Z]{3}$/D', $facts['currency']) && is_string($facts['reviewed_at']) && trim($facts['reviewed_at']) !== ''
@@ -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);
if ($sourceType === 'external_payment') {
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
$source = $this->source($actor, $payment);
} 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()]);
+24 -3
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';
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
{
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 = [];
+24 -2
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'];
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'];
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']);
$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'];
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'];
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']);
}
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'
+4
View File
@@ -0,0 +1,4 @@
<?php
// Package selection does not enable a feature or grant actor authority.
return ['path' => env('COMMON_PURCHASING_PATH', base_path('packages/purchasing'))];
+34
View File
@@ -0,0 +1,34 @@
<?php
// Deployment settings only. No installation, feature or permission is enabled by default.
return [
'enabled' => env('COMPRAS_RUNTIME_ENABLED', false),
'root' => env('COMPRAS_RUNTIME_ROOT'),
'manifest_sha256' => env('COMPRAS_RUNTIME_SHA256'),
'installation_id' => env('COMPRAS_RUNTIME_INSTALLATION_ID'),
'features' => [
'supplier-payables' => env('COMPRAS_SUPPLIER_PAYABLES_ENABLED', false),
'general-ledger' => env('COMPRAS_GENERAL_LEDGER_ENABLED', false),
'general-ledger-cycle' => env('COMPRAS_GENERAL_LEDGER_CYCLE_ENABLED', false),
'supplier-settlements' => env('COMPRAS_SUPPLIER_SETTLEMENTS_ENABLED', false),
'budget-distributions' => env('COMPRAS_BUDGET_DISTRIBUTIONS_ENABLED', false),
'capital-register' => env('COMPRAS_CAPITAL_REGISTER_ENABLED', false),
'operational-orders' => env('COMPRAS_OPERATIONAL_ORDERS_ENABLED', false),
'requisition-accounts' => env('COMPRAS_REQUISITION_ACCOUNTS_ENABLED', false),
'requisition-expiry' => env('COMPRAS_REQUISITION_EXPIRY_ENABLED', false),
'urgent-reviews' => env('COMPRAS_URGENT_REVIEWS_ENABLED', false),
'urgent-quotations' => env('COMPRAS_URGENT_QUOTATIONS_ENABLED', false),
'conflict-releases' => env('COMPRAS_CONFLICT_RELEASES_ENABLED', false),
'private-audit' => env('COMPRAS_PRIVATE_AUDIT_ENABLED', false),
'expense-allocations' => env('COMPRAS_EXPENSE_ALLOCATIONS_ENABLED', false),
'agreement-order-limits' => env('COMPRAS_AGREEMENT_LIMITS_ENABLED', false),
'order-parts' => env('COMPRAS_ORDER_PARTS_ENABLED', false),
'import-tariffs' => env('COMPRAS_IMPORT_TARIFFS_ENABLED', false),
'import-legal' => env('COMPRAS_IMPORT_LEGAL_ENABLED', false),
'import-dossier' => env('COMPRAS_IMPORT_DOSSIER_ENABLED', false),
'import-bank-support' => env('COMPRAS_IMPORT_BANK_SUPPORT_ENABLED', false),
'import-readiness' => env('COMPRAS_IMPORT_READINESS_ENABLED', false),
'import-estimates' => env('COMPRAS_IMPORT_ESTIMATES_ENABLED', false),
'import-landed-costs' => env('COMPRAS_IMPORT_LANDED_COSTS_ENABLED', false),
],
];
@@ -1,7 +1,7 @@
<?php
use App\Services\BudgetOrderPartsSchema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Optional contract structure. Deliberately outside normal and deployment migrations.
@@ -15,66 +15,7 @@ return new class extends Migration
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Order parts require the guarded disposable QA database.');
}
$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()');
}
}
});
BudgetOrderPartsSchema::install($db);
}
public function down(): void
@@ -1,7 +1,7 @@
<?php
use App\Services\PurchaseOrderSourcesSchema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Approved multi-order host adaptation, exclusively on disposable QA.
@@ -15,54 +15,7 @@ return new class extends Migration
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Order-source schema requires disposable QA.');
}
$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);
}
});
PurchaseOrderSourcesSchema::install($db);
}
public function down(): void
@@ -1,7 +1,7 @@
<?php
use App\Services\BudgetLandedCostSchema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Explicit isolated QA only; not a default or deployment migration.
@@ -15,54 +15,7 @@ return new class extends Migration
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Landed cost effects require a guarded disposable QA database.');
}
$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;");
}
}
});
BudgetLandedCostSchema::install($db);
}
public function down(): void
@@ -1,7 +1,7 @@
<?php
use App\Services\RequisitionCycleSchema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Explicit cycle-contract QA only. Never discovered by operational migrate.
@@ -15,50 +15,7 @@ return new class extends Migration
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Approval and budget cycle schema requires isolated QA.');
}
$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']);
});
RequisitionCycleSchema::install($db);
}
public function down(): void
@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Explicit installation path; never discovered by the application's normal migrate command.
return new class extends Migration
{
public function up(): void
{
$db = DB::connection();
if ($db->getDriverName() !== 'pgsql') {
throw new LogicException('COMPRAS_RUNTIME_DATABASE_DRIVER');
}
$db->getSchemaBuilder()->create('compras_runtime_installations', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('product', 20);
$table->string('contract', 60);
$table->string('manifest_sha256', 64);
$table->string('database_binding_sha256', 64);
$table->string('recorded_by', 200);
$table->text('reason');
$table->timestampTz('installed_at');
});
$db->unprepared("CREATE FUNCTION compras_runtime_preserve() RETURNS trigger LANGUAGE plpgsql AS \$\$
BEGIN RAISE EXCEPTION 'Preserve standalone installation history'; END \$\$;
CREATE TRIGGER compras_runtime_immutable BEFORE UPDATE OR DELETE ON compras_runtime_installations
FOR EACH ROW EXECUTE FUNCTION compras_runtime_preserve();
CREATE TRIGGER compras_runtime_no_truncate BEFORE TRUNCATE ON compras_runtime_installations
FOR EACH STATEMENT EXECUTE FUNCTION compras_runtime_preserve();");
}
public function down(): void
{
throw new LogicException('Preserve standalone installation history; use an explicitly reviewed recovery procedure.');
}
};
@@ -0,0 +1,19 @@
<?php
use App\Services\StandaloneExtensionSchema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
// Requires a separately recorded explicit installation; no activation or actor grants.
return new class extends Migration
{
public function up(): void
{
StandaloneExtensionSchema::install(DB::connection());
}
public function down(): void
{
throw new LogicException('Use a verified compatible recovery; never delete financial or approval history.');
}
};
+2
View File
@@ -1,5 +1,7 @@
# Continuidade do desenvolvimento do SGC
29/11/2026 — promoção autorizada por «autorizo», conforme `compras-operational-candidate-authorization.json`; a proposta anterior já não aguarda essa decisão. Candidata independente `afe98e1e`, 66 ficheiros, 21 capacidades opt-in, hashes verificados antes do carregamento, identidade própria da instalação/base/role e schema conferidos. Arranque e restauro em PostgreSQL fora de `testing`, com nomes próprios: projecto criado/repetido/arquivado, plano de contas próprio, consulta contabilística com direitos sintéticos explícitos, seis conjuntos financeiros/stock preservados, três recusas de mutação do recibo e cinco recusas de composição inválida. Restauro conserva 14 conjuntos de dados/relações e o recibo antigo; requer vínculo novo explícito. Bases/roles originais e restaurados removidos. Definições de schema únicas entre QA e instalação; guardas e bundles congelados preservados. Fundamentos45/159, regressão inicial87/1466; ordens13/497 após repor a indicação de controlo das parcelas na impressão. A promoção continua em execução: regressões de negócio, composição financeira restante, procedimento distribuível e percursos nativos pendentes. Não equivale a instalação/activação no piloto, alteração operacional SGF ou conclusão integral. Prova `compras-operational-candidate.json`.
29/11/2026 — continuação para candidata operacional: interface integral466testes/92ficheiros aprovada. Conferidos por bytes68ficheiros dos dois runtimes congelados e184entradas da compilação99b07243. Inventariados27adaptadores e5migraçõesQA na proposta compras-operational-candidate-proposal.json, sem promoção, instalação ou activação executadas. Pedida decisão específica de promoção de contratos/artefactos porque a autorização anterior exclui publicação/instalação operacional. C2: confirmação antiga cancelada e preparação descartada com original preservado; nova tentativa, já comURL/identidade conferidos e observação conjunta, voltou a ser interrompida pela ferramenta no diálogo nativo. Não confirmar a decisão por outra interface nem declarar aprovação; frente visual parada, bases/roles removidos. Corrigidas24notas próprias e4rótulos documentais com acentos corrompidos, escritaUTF-8 e round-trip conferidos. A promoção aguarda resposta; aplicação integral não declarada concluída.
29/11/2026 — cancelamento C2 legado: a revisão nativa encontrou o ramo de documento incompleto sem estado/formulário operacional, apesar da autorização existente. Reposto o componente comum apenas com o DTO autorizado, preservando desconhecidos. Frontend18/2ficheiros, tipos/análise/build aprovados, manifesto99b07243/184entradas. Edge demonstrou pedido com fundamento/suporte, autor sem decisão e origem suspensa; Finanças independente recusou fundamento vazio e seleccionou Aprovar. Ao preencher motivo/accionar decisão, a ferramenta interrompeu o turno por não conseguir confirmar o URL; confirmação/aprovação final não observadas. Não repetir uma acção incerta. A conferência final não passou por faltar cancelamento aprovado. Base/roleQA removidos; separador/possível diálogo não puderam ser fechados. Retomar em nova composição isolada e confirmar decisão/conservação/móvel/impressão. Provas issued-order-cancellation.json/product-review-20261122.json; aplicação integral continua aberta.
@@ -0,0 +1,53 @@
{
"date": "2026-11-29",
"state": "in_progress_not_installed_or_activated",
"authorization": "compras-operational-candidate-authorization.json",
"artifact": {
"root": "storage/framework/testing/compras-standalone-afe98e1ede5b9b4b",
"contract": "COMPRAS-STANDALONE-v1",
"manifest_sha256": "afe98e1ede5b9b4b184fb99f613d264a471d6b2eb4d29566377db7f824dd58a4",
"files": 66,
"packages": ["budget-control", "purchasing", "payables", "general-ledger"]
},
"implemented": [
"Pinned complete inventory before executable loading; explicit own installation identity and non-elevated PostgreSQL role",
"Opt-in features disabled by default; schema, dependency, loaded package and financial contract checks",
"Immutable installation receipts; single schema definitions reused by guarded QA and explicit standalone migration path",
"Canonical ledger host-verified schema installer retains the original guarded QA entry point",
"21 module adapters retain current permissions, history and single financial writer; account submission fails closed"
],
"verification": {
"foundation_and_actual_payables_schema": {"tests": 45, "assertions": 159, "result": "passed"},
"initial_module_regression_sqlite": {"tests": 87, "assertions": 1466, "result": "passed"},
"import_expense_regression_sqlite": {"tests": 78, "passed": 39, "skipped_optional_runtime": 39, "assertions": 395},
"frozen_integrated_before_print_fix": {"tests": 50, "passed": 49, "assertions": 1600, "failed": 1, "cause": "Missing consolidated-order budget confirmation text; fixed without weakening its assertion"},
"frozen_orders_after_print_fix": {"tests": 13, "assertions": 497, "result": "passed"},
"standalone_postgresql_startup_and_recovery": {
"result": "passed",
"available_modules": 21,
"environment": "standalone-qa; outside testing/payable-testing",
"own_disposable_database_and_role_names": true,
"project_create_replay_archive_history": true,
"own_chart_lookup_and_explicit_read_only_ledger_rights": true,
"private_audit_authority_not_inherited": true,
"financial_and_stock_frames_preserved": 6,
"immutable_installation_checks": 3,
"rejected": ["foreign loaded package", "wrong pin", "missing dependency", "older incomplete package", "restored database with old binding"],
"restored_originals_and_relations": "14 table frames verified before new synthetic operations",
"explicit_new_binding_preserves_old_receipt": true,
"original_and_restored_databases_roles_removed": true
},
"static_analysis": "focused PHPStan and Pint passed",
"counts_overlap_do_not_sum": true
},
"remaining": [
"Complete standalone business regressions and remaining financial composition paths",
"Distributable installation procedure",
"Remaining native visual/print journeys in the existing matrix; C2 final confirmation remains unconfirmed"
],
"frozen_manifests_preserved": ["182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df", "fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a"],
"pilot_or_production_installation": false,
"pilot_or_production_activation": false,
"sgf_operational_changes": false,
"application_complete": false
}
@@ -35,6 +35,8 @@ type Props = {
canWrite: boolean;
actorId: number;
tenantId: number;
sourceType?: 'common_allocation';
submitUrl?: string;
};
const decimal = (value: string) => {
const digits = value.padStart(3, '0');
@@ -44,7 +46,9 @@ const decimal = (value: string) => {
export default function ExpenseAllocation(props: Props) {
const payment = props.payment;
const form = useForm(
`expense-allocation:${props.tenantId}:${props.actorId}:${payment.id}`,
props.sourceType === 'common_allocation'
? `expense-allocation:common-allocation:${props.tenantId}:${props.actorId}:${payment.id}`
: `expense-allocation:${props.tenantId}:${props.actorId}:${payment.id}`,
{
operation_key: '',
version: props.current?.version || 0,
@@ -80,12 +84,16 @@ export default function ExpenseAllocation(props: Props) {
<Head title="Imputação da despesa por categoria" />
<PageTitle
title="Imputação da despesa por categoria"
eyebrow={`Pagamento #${payment.id} · ${payment.invoice_number}`}
eyebrow={`${props.sourceType === 'common_allocation' ? 'Afectação' : 'Pagamento'} #${payment.id} · ${payment.invoice_number}`}
description="Finanças atribui explicitamente o pagamento confirmado às categorias das linhas da factura. A soma deve coincidir exactamente com o pagamento; o pagamento e o saldo permanecem preservados."
/>
<Link
className="underline"
href={`/pagamentos?payment_id=${payment.id}`}
href={
props.sourceType === 'common_allocation'
? '/supplier-payments'
: `/pagamentos?payment_id=${payment.id}`
}
>
Voltar ao pagamento
</Link>
@@ -134,7 +142,10 @@ export default function ExpenseAllocation(props: Props) {
(row) => row.amount !== '',
),
}));
form.post(`/pagamentos/${payment.id}/categorias`, {
form.post(
props.submitUrl ??
`/pagamentos/${payment.id}/categorias`,
{
preserveScroll: true,
onSuccess: (page) => {
const saved = page.props
@@ -151,7 +162,8 @@ export default function ExpenseAllocation(props: Props) {
form.setDefaults(data);
form.clearErrors();
},
});
},
);
}}
>
<FormErrors errors={form.errors} />
+1 -1
View File
@@ -38,7 +38,7 @@
<p>Subtotal sem IVA: {{ $money($order->subtotal_minor) }}<br>IVA: {{ $money($order->tax_minor) }}<br>Total com IVA: {{ $money($order->total_minor) }}</p>
@else
<p>{{ $snapshot['company']['name'] }} · {{ $snapshot['requisition']['number'] }}</p>
<div class="notice"><strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>@if(($snapshot['budget_checked'] ?? false) === true) Controlo orçamental registado na emissão. @else Este documento não preserva confirmação do controlo orçamental. @endif @if($snapshot['approval_rules']['rules_provisional']) Regras de aprovação provisórias. @endif</div>
<div class="notice"><strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>@if(($snapshot['budget_checked'] ?? false) === true) @if(!empty($snapshot['order_parts']['frames'])) Controlo orçamental confirmado para as parcelas emitidas. @else Controlo orçamental registado na emissão. @endif @else Este documento não preserva confirmação do controlo orçamental. @endif @if($snapshot['approval_rules']['rules_provisional']) Regras de aprovação provisórias. @endif</div>
<div class="columns">
<div><h2>Fornecedor</h2><strong>{{ $snapshot['supplier']['name'] }}</strong><br>NUIT {{ $snapshot['supplier']['nuit'] }}<br><span class="pre">{{ $snapshot['supplier']['address'] }}</span><br>{{ $snapshot['supplier']['contact'] }}<br>{{ $snapshot['supplier']['phone'] }} · {{ $snapshot['supplier']['email'] }}</div>
<div><h2>Condições</h2>Entrega: {{ $snapshot['award']['delivery_date'] }}<br><span class="pre">{{ $snapshot['award']['delivery_location'] }}</span><br>Pagamento: {{ $snapshot['quotation']['payment_terms'] }}<br>Proposta: {{ $snapshot['quotation']['reference'] }}<br>{{ $snapshot['department']['name'] }} · {{ $snapshot['cost_center']['code'] }}<br>Emitente: {{ $snapshot['issuer']['name'] }}<br>Emissão: {{ $order->issued_at->format('Y-m-d H:i:s') }}</div>
+2
View File
@@ -305,6 +305,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('facturas/{invoice}/pagamentos', [ExternalPaymentController::class, 'store'])->name('payments.store');
Route::post('pagamentos/{payment}/conferir', [ExternalPaymentController::class, 'review'])->name('payments.review');
Route::get('pagamentos/{payment}/categorias', [ExpenseAllocationController::class, 'show'])->name('payments.expense-allocation');
Route::get('afectacoes-fornecedores/{allocation}/imputacao', [ExpenseAllocationController::class, 'commonShow'])->whereNumber('allocation');
Route::post('afectacoes-fornecedores/{allocation}/imputacao', [ExpenseAllocationController::class, 'commonStore'])->whereNumber('allocation');
Route::post('pagamentos/{payment}/categorias', [ExpenseAllocationController::class, 'store'])->name('payments.expense-allocation.store');
Route::get('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'show'])->name('suppliers.bank');
Route::post('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'store'])->name('suppliers.bank.store');
+105 -4
View File
@@ -8,6 +8,13 @@ import { createServer } from 'node:net';
const id = crypto.randomBytes(6).toString('hex');
const workspace = path.resolve('C:/laragon/www/compras');
const standaloneOnly = process.argv.includes('--standalone-runtime-only');
const standaloneBusiness = process.argv.includes('--standalone-business-only');
if (standaloneOnly && process.argv.slice(2).some(flag => flag !== '--standalone-runtime-only')) throw Error('Standalone composition requires its own isolated invocation');
if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== '--standalone-business-only')) throw Error('Standalone business regression requires its own isolated invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-3320fac5a70fe44e');
const standalonePin = '3320fac5a70fe44ed54e11af90385b5da6b204ef854984cd934882a4378211e1';
const standaloneArchivePin = 'a544d5930feb916c4d4941ed8ef0b453985c1629720e9d0224bdbf0d322fb536';
const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes='));
const reviewDurationMinutes = reviewDurationArgs.length === 0 ? 20 : Number(reviewDurationArgs[0].slice('--review-minutes='.length));
if (reviewDurationArgs.length > 1 || !Number.isInteger(reviewDurationMinutes) || reviewDurationMinutes < 1 || reviewDurationMinutes > 60 || (reviewDurationArgs.length > 0 && !process.argv.includes('--native-review'))) throw Error('Native review duration must be one explicit value from1to60minutes');
@@ -78,8 +85,8 @@ const root = path.join(privateParent, `rq01-ledger-qa-${id}`);
const cluster = path.join(root, 'postgres');
if (path.dirname(root) !== privateParent || !/^rq01-ledger-qa-[a-f0-9]{12}$/.test(path.basename(root))) throw Error('Private QA root refused');
fs.mkdirSync(root);
const database = `compras_receipts_test_${id}`;
const role = `payable_history_native_${id}`;
const database = standaloneOnly ? `compras_standalone_qa_${id}` : `compras_receipts_test_${id}`;
const role = standaloneOnly ? `compras_standalone_app_${id}` : `payable_history_native_${id}`;
const password = crypto.randomBytes(30).toString('hex');
const adminPassword = crypto.randomBytes(30).toString('hex');
const passwordFile = path.join(root, 'admin-password.txt');
@@ -119,10 +126,21 @@ try {
sql(`CREATE DATABASE ${database} OWNER ${role};`);
createdDatabase = true;
sql(`REVOKE ALL ON DATABASE ${database} FROM PUBLIC;`);
let activeStandaloneRoot = standaloneRoot;
if (standaloneOnly) {
const archive = standaloneRoot+'.zip';
if (fs.lstatSync(archive).isSymbolicLink() || crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== standaloneArchivePin) throw Error('Pinned standalone archive mismatch');
activeStandaloneRoot = path.join(root, 'runtime');
fs.mkdirSync(activeStandaloneRoot);
const code = '$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==67||!$z->extractTo($argv[2]))throw new LogicException("Owned candidate extraction failed");$z->close();echo "extracted";';
const extracted = spawnSync('php', ['-r', code, archive, activeStandaloneRoot], { windowsHide: true, encoding: 'utf8' });
if (extracted.status !== 0 || extracted.stdout !== 'extracted') throw Error('Owned standalone extraction failed');
verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 66);
}
const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', APP_KEY: 'base64:'+crypto.randomBytes(32).toString('base64'), DB_CONNECTION: 'pgsql', DB_URL: '', DB_HOST: '127.0.0.1', DB_PORT: '55439',
DB_DATABASE: database, DB_USERNAME: role, DB_PASSWORD: password, CACHE_STORE: 'array', SESSION_DRIVER: 'array',
MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null',
COMMON_BUDGET_PATH: frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control',
COMMON_BUDGET_PATH: standaloneOnly || standaloneBusiness ? path.join(activeStandaloneRoot, 'budget-control') : frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control',
RQ01_LEDGER_QA_SOURCE: frozenRuntime ? path.join(financeRoot, 'general-ledger') : 'C:/laragon/www/sgf-tempo/packages/general-ledger',
RQ01_LEDGER_INTEGRATED_SCHEMA: process.argv.includes('--integrated-schema') ? '1' : '0',
RQ01_NATIVE_OFFICE_JOURNEY: process.argv.some(flag => ['--native-office-http-only', '--native-office-preview'].includes(flag)) ? '1' : '0',
@@ -140,6 +158,15 @@ try {
RQ01_QA_PRINT_PAGINATION: process.argv.includes('--print-pagination-preview') ? '1' : '0' };
delete environment.COMMON_FINANCE_BUNDLE_ROOT;
delete environment.COMMON_FINANCE_BUNDLE_SHA256;
if (standaloneOnly || standaloneBusiness) {
environment.COMPRAS_RUNTIME_ENABLED = 'false';
environment.COMMON_PAYABLES_PATH = path.join(activeStandaloneRoot, 'payables');
environment.COMMON_PURCHASING_PATH = path.join(activeStandaloneRoot, 'purchasing');
environment.COMPRAS_RUNTIME_ROOT = activeStandaloneRoot;
environment.COMPRAS_RUNTIME_SHA256 = standalonePin;
environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness ? '1' : '0';
}
if (frozenRuntime) {
environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot;
environment.COMMON_FINANCE_BUNDLE_SHA256 = financePin;
@@ -153,7 +180,7 @@ try {
const nativeOfficePreview = process.argv.includes('--native-office-preview');
const nativeOfficeOnly = process.argv.includes('--native-office-http-only') || nativeOfficePreview;
const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly || nativeAuditSchemaOnly;
const setupOnly = raceOnly || recoveryOnly || nativeReview;
const setupOnly = standaloneOnly || raceOnly || recoveryOnly || nativeReview;
const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=minimal purchasing catalogue|chart references reject|native line account assignment|classified line requires|native submission requires account|zero monetary line retains|native order preserves common ledger|native office purchase'];
if (process.argv.includes('--runtime-guard-only')) {
@@ -193,12 +220,86 @@ try {
if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition');
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=native expiry returns the same request');
}
if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/StandaloneBusinessCompositionTest.php');
const result = spawnSync('php', args, {
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
});
if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((result.stderr || '').replaceAll(password, '[private]'));
process.exitCode = result.status === 0 ? 0 : 1;
if (result.status === 0 && standaloneOnly) {
const standaloneEnvironment = { ...environment, APP_ENV: 'standalone-qa',
COMPRAS_RUNTIME_ROOT: activeStandaloneRoot, COMPRAS_RUNTIME_SHA256: standalonePin,
COMPRAS_RUNTIME_INSTALLATION_ID: crypto.randomUUID(), SGC_STANDALONE_QA_ROOT: root,
PAYABLE_SOURCE_INSTANCE: `standalone-synthetic-${id}`,
COMPRAS_CAPITAL_REGISTER_ENABLED: 'true', COMPRAS_OPERATIONAL_ORDERS_ENABLED: 'true',
COMPRAS_PRIVATE_AUDIT_ENABLED: 'true', COMPRAS_CONFLICT_RELEASES_ENABLED: 'true',
COMPRAS_URGENT_REVIEWS_ENABLED: 'true', COMPRAS_URGENT_QUOTATIONS_ENABLED: 'true' };
for (const feature of ['BUDGET_DISTRIBUTIONS', 'REQUISITION_ACCOUNTS', 'REQUISITION_EXPIRY', 'EXPENSE_ALLOCATIONS',
'AGREEMENT_LIMITS', 'ORDER_PARTS', 'IMPORT_TARIFFS', 'IMPORT_LEGAL', 'IMPORT_DOSSIER', 'IMPORT_BANK_SUPPORT',
'IMPORT_READINESS', 'IMPORT_ESTIMATES', 'IMPORT_LANDED_COSTS', 'SUPPLIER_PAYABLES', 'GENERAL_LEDGER',
'SUPPLIER_SETTLEMENTS', 'GENERAL_LEDGER_CYCLE']) standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true';
for (const mode of ['prepare', 'verify']) {
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: mode === 'verify' ? 'true' : 'false' },
});
process.stdout.write((check.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(password, '[private]'));
const expected = mode === 'prepare' ? 'prepared' : 'verified';
let receipt = null;
try { receipt = JSON.parse((check.stdout || '').trim()); } catch {}
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
}
if (process.exitCode === 0) {
for (const mode of ['reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old']) {
const invalid = { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' };
if (mode === 'reject-pin') invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64);
if (mode === 'reject-dependency') invalid.COMPRAS_IMPORT_DOSSIER_ENABLED = 'false';
if (mode === 'reject-old') {
invalid.COMPRAS_RUNTIME_ROOT = path.join(workspace, 'storage/framework/testing/compras-standalone-730845de0bddd000');
invalid.COMPRAS_RUNTIME_SHA256 = '730845de0bddd0007845dd57599c084c4002f3c0672d05e89c582d8e0346fc7b';
}
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: invalid,
});
process.stdout.write((check.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(password, '[private]'));
let receipt = null;
try { receipt = JSON.parse((check.stdout || '').trim()); } catch {}
if (check.status !== 0 || receipt?.rejected !== true) { process.exitCode = 1; break; }
}
}
if (process.exitCode === 0) {
const pgCommand = (binary, args, env) => {
const check = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8',
env: { ...process.env, PGHOST: '127.0.0.1', PGPORT: '55439', PGUSER: env.DB_USERNAME, PGPASSWORD: env.DB_PASSWORD } });
if (check.status !== 0) throw Error('Standalone private backup/restore failed');
};
const dump = path.join(root, 'standalone.dump');
pgCommand('pg_dump.exe', ['--format=custom', '--no-owner', '--no-acl', '--file='+dump, '--dbname='+database], environment);
const restoredPassword = crypto.randomBytes(30).toString('hex');
restoreRole = role+'_restored';
restoreDatabase = database+'_restored';
sql(`CREATE ROLE ${restoreRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`);
sql(`CREATE DATABASE ${restoreDatabase} OWNER ${restoreRole}; REVOKE ALL ON DATABASE ${restoreDatabase} FROM PUBLIC;`);
const restored = { ...standaloneEnvironment, DB_DATABASE: restoreDatabase, DB_USERNAME: restoreRole, DB_PASSWORD: restoredPassword };
pgCommand('pg_restore.exe', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='+restoreDatabase, dump], restored);
for (const mode of ['reject-restore', 'rebind', 'verify']) {
if (mode === 'rebind') restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', restoreDatabase, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...restored, COMPRAS_RUNTIME_ENABLED: mode === 'rebind' ? 'false' : 'true' },
});
process.stdout.write((check.stdout || '').replaceAll(restoredPassword, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(restoredPassword, '[private]'));
let receipt = null;
try { receipt = JSON.parse((check.stdout || '').trim()); } catch {}
const expected = mode === 'reject-restore' ? 'rejected' : mode === 'rebind' ? 'prepared' : 'verified';
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
}
}
}
if (result.status === 0 && raceOnly) {
const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], {
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
+116
View File
@@ -0,0 +1,116 @@
<?php
// Build only: no application bootstrap, database connection, installation or activation.
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
require dirname(__DIR__).'/vendor/autoload.php';
$options = getopt('', ['financial-source:', 'output:']);
$source = isset($options['financial-source']) && is_string($options['financial-source']) ? realpath($options['financial-source']) : false;
$output = isset($options['output']) && is_string($options['output']) ? realpath($options['output']) : false;
if ($source === false || $output === false || ! is_dir($source) || ! is_dir($output) || is_link($options['output'])) {
throw new LogicException('Explicit existing canonical source and output directories required.');
}
$sources = [];
foreach (StandaloneArtifact::PACKAGES as $package) {
$directory = $package === 'purchasing' ? dirname(__DIR__).'/packages/purchasing' : $source.'/'.$package;
foreach (['bootstrap.php', 'README.md', 'module.json'] as $file) {
if (is_file($directory.'/'.$file)) {
$sources[$package.'/'.$file] = $directory.'/'.$file;
}
}
foreach (['src', 'ui'] as $subdirectory) {
if (! is_dir($directory.'/'.$subdirectory)) {
continue;
}
foreach (new DirectoryIterator($directory.'/'.$subdirectory) as $file) {
if ($file->isDot()) {
continue;
}
if (! $file->isFile() || $file->isLink() || ! preg_match('/^[A-Za-z0-9_-]+\.php$/D', $file->getFilename())) {
throw new LogicException('Unexpected canonical runtime file.');
}
$sources[$package.'/'.$subdirectory.'/'.$file->getFilename()] = $file->getPathname();
}
}
}
ksort($sources, SORT_STRING);
$content = [];
$files = [];
foreach ($sources as $name => $file) {
if (is_link($file) || ! is_file($file)) {
throw new LogicException('Canonical source must contain regular files.');
}
$bytes = file_get_contents($file);
if (! is_string($bytes)) {
throw new LogicException('Unable to read canonical runtime source.');
}
$content[$name] = $bytes;
$files[] = ['file' => $name, 'sha256' => hash('sha256', $bytes)];
}
$manifest = json_encode(['contract' => StandaloneArtifact::CONTRACT, 'product' => 'compras', 'version' => 1,
'capabilities' => StandaloneRuntime::FEATURES, 'files' => $files], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
$pin = hash('sha256', $manifest);
$target = $output.'/compras-standalone-'.substr($pin, 0, 16);
if (! file_exists($target)) {
if (! mkdir($target, 0700)) {
throw new LogicException('Unable to create candidate directory.');
}
foreach ($content as $name => $bytes) {
$destination = $target.'/'.$name;
if (! is_dir(dirname($destination)) && ! mkdir(dirname($destination), 0700, true)) {
throw new LogicException('Unable to create candidate package directory.');
}
$handle = fopen($destination, 'x');
if ($handle === false || fwrite($handle, $bytes) !== strlen($bytes)) {
throw new LogicException('Unable to write candidate package.');
}
fclose($handle);
}
$handle = fopen($target.'/manifest.json', 'x');
if ($handle === false || fwrite($handle, $manifest) !== strlen($manifest)) {
throw new LogicException('Unable to write candidate manifest.');
}
fclose($handle);
}
(new StandaloneArtifact)->verify($target, $pin);
$archive = $target.'.zip';
if (is_link($archive)) {
throw new LogicException('Candidate archive links refused.');
}
if (! file_exists($archive)) {
$zip = new ZipArchive;
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new LogicException('Unable to create candidate archive.');
}
foreach (array_keys($content) as $name) {
if (! $zip->addFile($target.'/'.$name, $name)) {
throw new LogicException('Unable to archive candidate package file.');
}
}
$zip->addFile($target.'/manifest.json', 'manifest.json');
if (! $zip->close()) {
throw new LogicException('Unable to finish candidate archive.');
}
}
$zip = new ZipArchive;
if ($zip->open($archive) !== true || $zip->numFiles !== count($files) + 1) {
throw new LogicException('Candidate archive inventory mismatch.');
}
$expected = ['manifest.json' => $manifest, ...$content];
$seen = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if (! is_string($name) || isset($seen[$name]) || ! isset($expected[$name]) || $zip->getFromIndex($i) !== $expected[$name]) {
throw new LogicException('Candidate archive bytes mismatch.');
}
$seen[$name] = true;
}
$zip->close();
$archiveHash = hash_file('sha256', $archive);
if (! is_string($archiveHash)) {
throw new LogicException('Unable to hash candidate archive.');
}
echo json_encode(['root' => $target, 'manifest_sha256' => $pin, 'files' => count($files),
'archive' => $archive, 'archive_sha256' => $archiveHash,
'state' => 'candidate_requires_operational_validation', 'installed_or_activated' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+46
View File
@@ -8,6 +8,7 @@ use App\Models\Tenant;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditSourceReader;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -187,3 +188,48 @@ test('private audit includes versioned import document metadata but excludes ban
->and($rows[0]['purchase_order_id'])->toBe($this->f['order']->id)
->and(json_encode($rows, JSON_THROW_ON_ERROR))->not->toContain('bank_commitment')->not->toContain('bank_support')->not->toContain('PRIVATE-PATH-NEVER-EXPORT');
});
test('private financial audit scopes common settlement rows and outbox by tenant company and unit without bank references', function () {
$schema = DB::getSchemaBuilder();
foreach (['ps_payments', 'ps_events'] as $name) {
$schema->create($name, function (Blueprint $table) use ($name) {
$table->id();
$table->unsignedBigInteger('tenant_id');
$table->unsignedBigInteger('company_id');
$table->unsignedBigInteger('unit_id');
if ($name === 'ps_payments') {
$table->bigInteger('amount_minor');
$table->string('fact_reference');
$table->string('evidence_reference');
$table->json('snapshot');
} else {
$table->unsignedBigInteger('payment_id');
$table->unsignedBigInteger('actor_id');
$table->string('kind');
$table->json('payload');
}
});
}
$schema->create('ps_outbox', function (Blueprint $table) {
$table->unsignedBigInteger('event_id')->primary();
$table->string('state');
});
$foreign = Tenant::query()->create(['name' => 'Synthetic other common payment tenant']);
$own = null;
foreach ([[$this->actor->tenant_id, 0, 0], [$this->actor->tenant_id, 7, 0], [$this->actor->tenant_id, 0, 9], [$foreign->id, 0, 0]] as [$tenant, $company, $unit]) {
$scope = ['tenant_id' => $tenant, 'company_id' => $company, 'unit_id' => $unit];
$payment = DB::table('ps_payments')->insertGetId($scope + ['amount_minor' => 123,
'fact_reference' => 'PRIVATE-BANK-FACT-SENTINEL', 'evidence_reference' => 'PRIVATE-BANK-EVIDENCE-SENTINEL',
'snapshot' => json_encode(['account_identifier' => 'PRIVATE-BANK-SNAPSHOT-SENTINEL'], JSON_THROW_ON_ERROR)]);
$event = DB::table('ps_events')->insertGetId($scope + ['payment_id' => $payment, 'actor_id' => $this->actor->id,
'kind' => 'supplier_payment.confirmed', 'payload' => json_encode(['amount_minor' => 123,
'account_identifier' => 'PRIVATE-BANK-PAYLOAD-SENTINEL'], JSON_THROW_ON_ERROR)]);
DB::table('ps_outbox')->insert(['event_id' => $event, 'state' => 'captured']);
$own ??= ['payment' => $payment, 'event' => $event];
}
$sources = collectedPrivateAuditSources($this->actor, ['finance']);
expect(array_column($sources['finance:ps_payments']['rows'], 'id'))->toBe([$own['payment']])
->and(array_column($sources['finance:ps_events']['rows'], 'id'))->toBe([$own['event']])
->and($sources['finance:ps_outbox']['rows'])->toBe([['event_id' => $own['event'], 'state' => 'captured']])
->and(json_encode($sources, JSON_THROW_ON_ERROR))->not->toContain('PRIVATE-BANK-');
});
@@ -0,0 +1,378 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\RequisitionWorkflow;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_BUSINESS_QA') !== '1') {
$this->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);
});
@@ -0,0 +1,11 @@
<?php
use App\Services\StandaloneSchema;
use Illuminate\Support\Facades\DB;
test('standalone preflight accepts the actual common payables schema including event keyed outbox', function () {
StandaloneSchema::verify(DB::getSchemaBuilder(), ['supplier-payables' => true]);
expect(DB::getSchemaBuilder()->hasColumn('pa_outbox', 'event_id'))->toBeTrue()
->and(DB::getSchemaBuilder()->hasColumn('pa_outbox', 'id'))->toBeFalse()
->and(DB::table('pa_access')->count())->toBe(0);
});
+257
View File
@@ -0,0 +1,257 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\CapitalRegister;
use App\Services\ConflictReleases;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
use App\Services\ImportLegalRules;
use App\Services\ImportReadiness;
use App\Services\ImportTariffCodes;
use App\Services\OperationalOrders;
use App\Services\OrderPartsPreparation;
use App\Services\PrivateAuditAccess;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use App\Services\UrgentQuotationBasis;
use App\Services\UrgentRequisitionReviews;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
$parent = realpath(dirname(__DIR__, 2).'/storage/framework/testing');
if (! preg_match('/^compras_standalone_qa_([a-f0-9]{12})(_restored)?$/D', $database, $match)
|| $root === false || $parent === false || dirname($root) !== $parent || basename($root) !== 'rq01-ledger-qa-'.$match[1]
|| getenv('DB_DATABASE') !== $database || getenv('DB_USERNAME') !== 'compras_standalone_app_'.$match[1].($match[2] ?? '')
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| getenv('APP_ENV') !== 'standalone-qa' || ! in_array($mode, ['prepare', 'verify', 'reject-restore', 'rebind',
'reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old'], true)) {
throw new LogicException('Owned standalone QA composition required.');
}
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->useStoragePath($root.'/storage');
if ($mode === 'reject-foreign') {
require dirname(__DIR__, 2).'/packages/purchasing/bootstrap.php';
}
$expectedRejection = match ($mode) {
'reject-restore' => 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH',
'reject-foreign' => 'COMPRAS_RUNTIME_CLASS_LOCATION',
'reject-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH',
'reject-dependency' => 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:import-bank-support:import-dossier',
'reject-old' => 'COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE',
default => null,
};
try {
$app->make(Kernel::class)->bootstrap();
} catch (LogicException $e) {
if ($expectedRejection === null || $e->getMessage() !== $expectedRejection) {
throw $e;
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if ($expectedRejection !== null) {
throw new LogicException('Invalid standalone composition started without refusal.');
}
$db = DB::connection();
$identity = $db->selectOne("SELECT current_database() AS d,current_setting('cluster_name') AS c");
if ($identity->d !== $database || $identity->c !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned standalone QA database identity mismatch.');
}
if (in_array($mode, ['prepare', 'rebind'], true)) {
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Synthetic named QA deployment operator', '--reason' => 'Authorised candidate installation and recovery verification'];
if ($mode === 'rebind') {
$arguments['--rebind'] = true;
}
$invoke = static function (array $arguments): array {
if (Artisan::call('compras:runtime:prepare', $arguments) !== 0) {
throw new LogicException('Standalone installation CLI failed.');
}
$result = json_decode(trim(Artisan::output()), true, 32, JSON_THROW_ON_ERROR);
if (! is_array($result) || ($result['feature_activation'] ?? null) !== false || ($result['actor_grants'] ?? null) !== false) {
throw new LogicException('Standalone CLI result changed feature or actor authority.');
}
return $result;
};
$preview = $invoke($arguments);
if ($preview['state'] !== 'preview' || $preview['written'] !== false
|| $db->getSchemaBuilder()->hasTable('compras_runtime_installations') !== ($mode === 'rebind')) {
throw new LogicException('Standalone CLI preview wrote an installation.');
}
try {
app(StandaloneInstallation::class)->prepare($database.'_unexpected', getenv('DB_USERNAME'),
'Synthetic named QA operator', 'Synthetic destination mismatch refusal', true);
throw new LogicException('Wrong standalone CLI destination was accepted.');
} catch (LogicException $e) {
if ($e->getMessage() !== 'COMPRAS_RUNTIME_EXPECTED_DESTINATION') {
throw $e;
}
}
$hostChecks = 0;
if ($mode === 'prepare') {
$ledger = new ReflectionClass(LedgerSchema::class);
foreach (['wrong-contract', 'failed-host-verification'] as $check) {
try {
$ledger->getMethod('installForHost')->invoke(null, $db,
$check === 'wrong-contract' ? 'INCOMPATIBLE' : 'COMMON-LEDGER-HOST-SCHEMA-v1',
fn () => throw new LogicException('SYNTHETIC_HOST_INSTALLATION_REFUSED'));
throw new LogicException('Unverified host installed ledger DDL.');
} catch (LogicException $e) {
$expected = $check === 'wrong-contract' ? 'LEDGER_HOST_SCHEMA_CONTRACT' : 'SYNTHETIC_HOST_INSTALLATION_REFUSED';
if ($e->getMessage() !== $expected || $db->getSchemaBuilder()->hasTable('gl_accounts')) {
throw $e;
}
$hostChecks++;
}
}
}
$applied = $invoke([...$arguments, '--apply' => true]);
$replayed = $invoke([...$arguments, '--apply' => true]);
if ($applied['state'] !== ($mode === 'rebind' ? 'rebound' : 'prepared') || $applied['written'] !== true
|| $replayed['state'] !== 'already_prepared' || $replayed['written'] !== false) {
throw new LogicException('Standalone installation CLI replay changed history.');
}
echo json_encode(['prepared' => true, 'synthetic_only' => true, 'cli_preview_and_replay' => true,
'wrong_destination_refused' => true, 'unverified_ledger_host_checks' => $hostChecks], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
$runtime = app(StandaloneRuntime::class);
$runtime->assertLoadedPackages();
$checks = 0;
foreach ([CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class,
UrgentQuotationBasis::class, UrgentRequisitionReviews::class, RequisitionLedgerAccounts::class,
RequisitionExpiry::class, RequisitionBudgetDistributions::class,
ExpenseAllocations::class, AgreementOrderLimits::class, OrderPartsPreparation::class,
ImportTariffCodes::class, ImportLegalRules::class, ImportDossier::class,
ImportBankSupport::class, ImportReadiness::class, ImportEstimates::class,
ImportLandedCosts::class] as $service) {
if (! app($service)->ready()) {
throw new LogicException('Standalone module unavailable: '.$service);
}
$checks++;
}
if ($app->environment('testing') || config('capital-register.qa_enabled') === true
|| $runtime->feature('not-configured', $db) !== false || $db->table('compras_runtime_installations')->count() !== (isset($match[2]) ? 2 : 1)) {
throw new LogicException('Standalone composition inherited QA activation or an unselected capability.');
}
if (! SupplierPayables::enabled() || ! $runtime->feature('general-ledger', $db)
|| ! $runtime->feature('supplier-settlements', $db) || ! app(GeneralLedger::class)->cycleEnabled()) {
throw new LogicException('Standalone common financial modules unavailable.');
}
$checks += 4;
$snapshot = static function () use ($db): string {
$frames = [];
foreach (['tenants', 'users', 'departments', 'supply_records', 'audit_logs', 'gl_accounts', 'gl_journals',
'budget_entries', 'purchase_orders', 'invoices', 'stock_movements', 'budget_requisition_cycles', 'approval_steps', 'pa_access'] as $table) {
$frames[$table] = $db->table($table)->orderBy('id')->get()->toArray();
}
return hash('sha256', json_encode($frames, JSON_THROW_ON_ERROR));
};
if (isset($match[2])) {
$saved = file_get_contents($root.'/standalone-preservation.sha256');
if (! is_string($saved) || ! hash_equals($saved, $snapshot())) {
throw new LogicException('Standalone restore changed original data or relations.');
}
}
$tenant = Tenant::query()->create(['name' => 'Synthetic standalone candidate QA']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Synthetic purchasing department']);
$actor = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'purchasing_role' => PurchasingRole::Procurement]);
auth()->guard()->setUser($actor);
if ($db->table('pa_access')->where('tenant_id', $tenant->id)->exists() || app(SupplierPayables::class)->can($actor, 'view')) {
throw new LogicException('Standalone composition automatically granted financial authority.');
}
$finance = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Finance]);
foreach (['view', 'payments_view', 'general_ledger.view'] as $action) {
$db->table('pa_access')->insert(['tenant_id' => $tenant->id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $finance->id, 'person' => 'synthetic-standalone-finance-'.$finance->id, 'action' => $action]);
}
auth()->guard()->setUser($finance);
app(GeneralLedger::class)->listing($finance);
app(GeneralLedger::class)->workspace($finance);
app(SupplierPayables::class)->engine($finance)->settlements()->listing();
if (app(GeneralLedger::class)->can($finance, 'prepare')) {
throw new LogicException('Read-only common ledger access acquired a writer capability.');
}
auth()->guard()->setUser($actor);
$account = $db->table('gl_accounts')->insertGetId(['tenant_id' => $tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'STANDALONE-ONLY', 'label' => 'Synthetic own chart movement account', 'currency' => 'MZN', 'is_movement' => true]);
$options = app(RequisitionLedgerAccounts::class)->options($actor, 'STANDALONE-ONLY');
if (count($options['data']) !== 1 || $options['data'][0]['id'] !== $account) {
throw new LogicException('Standalone chart lookup lost own company scope.');
}
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_accounts', 'gl_journals'] as $table) {
$before[$table] = $db->table($table)->orderBy('id')->get()->toJson();
}
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
'code' => 'STANDALONE-QA', 'name' => 'Synthetic standalone project', 'department_id' => $department->id,
'equipment_id' => null, 'reference' => 'Synthetic candidate acceptance source', 'state' => 'active',
'reason' => 'Authorised isolated candidate regression verification'];
$register = app(CapitalRegister::class);
$first = $register->save($actor, $input);
$retry = $register->save($actor, $input);
$archived = $register->save($actor, [...$input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived']);
if ($first->id !== $retry->id || $first->fresh()->state !== 'active' || $archived->version !== 2) {
throw new LogicException('Standalone project replay or history changed.');
}
foreach ($before as $table => $frame) {
if ($db->table($table)->orderBy('id')->get()->toJson() !== $frame) {
throw new LogicException('Documentary project changed a financial or physical writer.');
}
}
try {
app(PrivateAuditAccess::class)->current($actor);
throw new LogicException('Standalone composition granted private audit authority.');
} catch (HttpExceptionInterface $e) {
if ($e->getStatusCode() !== 403) {
throw $e;
}
}
$immutableChecks = 0;
foreach (["UPDATE compras_runtime_installations SET reason='changed'", 'DELETE FROM compras_runtime_installations',
'TRUNCATE compras_runtime_installations'] as $statement) {
try {
$db->transaction(fn () => $db->unprepared($statement));
throw new LogicException('Installation history mutation was accepted.');
} catch (QueryException $e) {
if (($e->errorInfo[0] ?? null) !== 'P0001') {
throw $e;
}
$immutableChecks++;
}
}
if (! isset($match[2])) {
if (file_put_contents($root.'/standalone-preservation.sha256', $snapshot()) !== 64) {
throw new LogicException('Unable to record private preservation evidence.');
}
}
echo json_encode(['verified' => true, 'available_modules' => $checks, 'outside_testing_environment' => true,
'own_database_and_role_names' => true, 'runtime_classes_pinned' => true, 'project_replay_and_history' => true,
'private_audit_authority_not_inherited' => true, 'financial_stock_frames_preserved' => count($before),
'immutable_installation_checks' => $immutableChecks, 'restored_originals_preserved' => isset($match[2]),
'common_ledger_read_with_explicit_synthetic_rights' => true, 'real_operations' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+138
View File
@@ -0,0 +1,138 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Schema\Builder as SchemaBuilder;
beforeEach(function () {
$this->artifactParent = realpath(__DIR__.'/../../storage/framework/testing');
expect($this->artifactParent)->not->toBeFalse();
$this->artifactRoot = $this->artifactParent.'/standalone-artifact-'.bin2hex(random_bytes(6));
mkdir($this->artifactRoot, 0700);
$this->manifest = ['contract' => StandaloneArtifact::CONTRACT, 'product' => 'compras', 'version' => 1,
'capabilities' => ['capital-register'], 'files' => []];
foreach (StandaloneArtifact::PACKAGES as $package) {
mkdir($this->artifactRoot.'/'.$package, 0700);
$bytes = '<?php throw new RuntimeException("VERIFIER_MUST_NOT_EXECUTE_PACKAGE");';
file_put_contents($this->artifactRoot.'/'.$package.'/bootstrap.php', $bytes);
$this->manifest['files'][] = ['file' => $package.'/bootstrap.php', 'sha256' => hash('sha256', $bytes)];
}
$this->writeArtifactManifest = function (): string {
$bytes = json_encode($this->manifest, JSON_THROW_ON_ERROR);
file_put_contents($this->artifactRoot.'/manifest.json', $bytes);
return hash('sha256', $bytes);
};
$this->artifactPin = ($this->writeArtifactManifest)();
});
afterEach(function () {
$root = realpath($this->artifactRoot);
if ($root === false || dirname($root) !== $this->artifactParent || ! preg_match('/^standalone-artifact-[a-f0-9]{12}$/D', basename($root))) {
throw new LogicException('Owned artifact fixture cleanup refused.');
}
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) {
$file->isDir() && ! $file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
}
rmdir($root);
});
test('standalone artifact verifies the complete portable package without executing it', function () {
$result = (new StandaloneArtifact)->verify($this->artifactRoot, $this->artifactPin);
expect($result['manifest']['product'])->toBe('compras')
->and($result['manifest']['capabilities'])->toBe(['capital-register']);
foreach (StandaloneArtifact::PACKAGES as $package) {
expect(realpath($result['paths'][$package]))->toBe(realpath($this->artifactRoot.'/'.$package));
}
});
test('standalone artifact rejects changed source bytes and unlisted files before execution', function (string $mutation) {
if ($mutation === 'changed') {
file_put_contents($this->artifactRoot.'/payables/bootstrap.php', '<?php echo "ALTERED";');
} else {
file_put_contents($this->artifactRoot.'/payables/extra.php', '<?php echo "UNLISTED";');
}
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, $this->artifactPin))->toThrow(LogicException::class);
})->with(['changed', 'unlisted']);
test('standalone artifact rejects incompatible metadata duplicate and escaping identities', function (string $mutation) {
match ($mutation) {
'product' => $this->manifest['product'] = 'sgf',
'version' => $this->manifest['version'] = 2,
'contract' => $this->manifest['contract'] = 'QA-UNPUBLISHED',
'duplicate-file' => $this->manifest['files'][] = $this->manifest['files'][0],
'escaping-file' => $this->manifest['files'][0]['file'] = 'budget-control/../../outside.php',
'absolute-file' => $this->manifest['files'][0]['file'] = 'C:/outside.php',
'malformed-file' => $this->manifest['files'][0] = 'budget-control/bootstrap.php',
'duplicate-capability' => $this->manifest['capabilities'][] = 'capital-register',
'invalid-capability' => $this->manifest['capabilities'][] = ['capital-register'],
'missing-package' => $this->manifest['files'][0]['file'] = 'budget-control/other.php',
};
if ($mutation === 'missing-package') {
rename($this->artifactRoot.'/budget-control/bootstrap.php', $this->artifactRoot.'/budget-control/other.php');
}
$pin = ($this->writeArtifactManifest)();
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, $pin))->toThrow(LogicException::class);
})->with(['product', 'version', 'contract', 'duplicate-file', 'escaping-file', 'absolute-file', 'malformed-file', 'duplicate-capability', 'invalid-capability', 'missing-package']);
test('standalone artifact requires the caller pin even for an otherwise valid package', function () {
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, str_repeat('0', 64)))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_MANIFEST_HASH');
});
test('standalone composition rejects capabilities absent from its pinned package', function (mixed $features) {
$runtime = new StandaloneRuntime(['enabled' => true, 'root' => $this->artifactRoot,
'manifest_sha256' => $this->artifactPin, 'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99',
'features' => $features], new StandaloneArtifact);
expect(fn () => $runtime->artifact())->toThrow(LogicException::class);
})->with([
'unsupported enabled feature' => [['private-audit' => true]],
'truthy string' => [['capital-register' => 'true']],
'malformed feature collection' => ['capital-register'],
]);
test('standalone composition accepts explicitly disabled unavailable capabilities', function () {
$runtime = new StandaloneRuntime(['enabled' => true, 'root' => $this->artifactRoot,
'manifest_sha256' => $this->artifactPin, 'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99',
'features' => ['capital-register' => true, 'private-audit' => false]], new StandaloneArtifact);
expect($runtime->artifact()['manifest']['capabilities'])->toBe(['capital-register']);
});
test('standalone feature checks the installation receipt before permitting availability', function (string $mutation) {
$settings = ['enabled' => true, 'root' => $this->artifactRoot, 'manifest_sha256' => $this->artifactPin,
'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99', 'features' => ['capital-register' => true]];
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$db->shouldReceive('selectOne')->once()->andReturn((object) ['database_name' => 'purchasing_company',
'role_name' => 'purchasing_app', 'database_oid' => '45000', 'server_address' => '192.0.2.10',
'server_port' => 5432, 'elevated' => 0]);
$schema = Mockery::mock(SchemaBuilder::class);
$db->shouldReceive('getSchemaBuilder')->once()->andReturn($schema);
$schema->shouldReceive('hasTable')->with('compras_runtime_installations')->once()->andReturn($mutation !== 'schema');
if ($mutation !== 'schema') {
$query = Mockery::mock(Builder::class);
$db->shouldReceive('table')->with('compras_runtime_installations')->once()->andReturn($query);
$query->shouldReceive('where')->with('id', $settings['installation_id'])->once()->andReturnSelf();
$receipt = (object) ['product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT,
'manifest_sha256' => $this->artifactPin, 'database_binding_sha256' => hash('sha256', json_encode([
'product' => 'compras', 'database' => 'purchasing_company', 'oid' => '45000', 'role' => 'purchasing_app',
'address' => '192.0.2.10', 'port' => 5432,
], JSON_THROW_ON_ERROR))];
match ($mutation) {
'product' => $receipt->product = 'sgf',
'contract' => $receipt->contract = 'OLD',
'manifest' => $receipt->manifest_sha256 = str_repeat('0', 64),
'database' => $receipt->database_binding_sha256 = str_repeat('0', 64),
default => null,
};
$query->shouldReceive('first')->once()->andReturn($mutation === 'missing' ? null : $receipt);
}
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
if ($mutation === 'valid') {
expect($runtime->feature('capital-register', $db))->toBeTrue();
} else {
expect(fn () => $runtime->feature('capital-register', $db))->toThrow(LogicException::class,
$mutation === 'schema' ? 'COMPRAS_RUNTIME_INSTALLATION_MISSING' : 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
}
})->with(['valid', 'schema', 'missing', 'product', 'contract', 'manifest', 'database']);
+61
View File
@@ -0,0 +1,61 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Database\Connection;
test('disabled standalone composition does not inspect the database or package', function () {
$db = Mockery::mock(Connection::class);
$runtime = new StandaloneRuntime([], new StandaloneArtifact);
expect($runtime->enabled())->toBeFalse()
->and($runtime->requested('capital-register'))->toBeFalse()
->and($runtime->feature('capital-register', $db))->toBeFalse();
});
test('standalone feature opt in requires a boolean rather than a truthy setting', function (mixed $value) {
$db = Mockery::mock(Connection::class);
$runtime = new StandaloneRuntime(['enabled' => $value, 'features' => ['capital-register' => true]], new StandaloneArtifact);
expect($runtime->feature('capital-register', $db))->toBeFalse();
})->with([false, 1, 'true', 'false', null]);
test('standalone requested features remain explicit before readiness validation', function () {
$runtime = new StandaloneRuntime(['enabled' => true, 'features' => ['requisition-accounts' => true]], new StandaloneArtifact);
expect($runtime->requested('requisition-accounts'))->toBeTrue()
->and($runtime->requested('private-audit'))->toBeFalse();
expect(fn () => $runtime->artifact())->toThrow(LogicException::class, 'COMPRAS_RUNTIME_CONFIGURATION');
});
test('standalone database binding accepts an ordinary own installation without QA names', function () {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$db->shouldReceive('selectOne')->once()->andReturn((object) [
'database_name' => 'purchasing_company', 'role_name' => 'purchasing_app', 'database_oid' => '45000',
'server_address' => '192.0.2.10', 'server_port' => 5432, 'elevated' => 0,
]);
expect(StandaloneRuntime::databaseBinding($db))->toBe(hash('sha256', json_encode([
'product' => 'compras', 'database' => 'purchasing_company', 'oid' => '45000', 'role' => 'purchasing_app',
'address' => '192.0.2.10', 'port' => 5432,
], JSON_THROW_ON_ERROR)));
});
test('standalone binding rejects elevated or unavailable database identities', function (string $failure) {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$identity = (object) ['database_name' => 'own', 'role_name' => 'app', 'database_oid' => '1',
'server_address' => '127.0.0.1', 'server_port' => 5432, 'elevated' => 0];
if ($failure === 'elevated') {
$identity->elevated = 1;
} elseif ($failure === 'address') {
$identity->server_address = null;
} elseif ($failure === 'port') {
$identity->server_port = null;
}
$db->shouldReceive('selectOne')->once()->andReturn($failure === 'missing' ? null : $identity);
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_IDENTITY');
})->with(['elevated', 'address', 'port', 'missing']);
test('standalone binding rejects other drivers without querying them', function () {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('sqlite');
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_DRIVER');
});
+47
View File
@@ -0,0 +1,47 @@
<?php
use App\Services\StandaloneSchema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\SQLiteConnection;
beforeEach(function () {
$this->standaloneDb = new SQLiteConnection(new PDO('sqlite::memory:'), ':memory:', '', ['driver' => 'sqlite']);
$this->standaloneSchema = $this->standaloneDb->getSchemaBuilder();
foreach (['supply_records' => ['id', 'tenant_id', 'kind', 'record_key', 'version', 'data', 'snapshot', 'operation_key'],
'requisitions' => ['id', 'tenant_id', 'status'], 'users' => ['id', 'tenant_id']] as $table => $columns) {
$this->standaloneSchema->create($table, function (Blueprint $definition) use ($columns) {
foreach ($columns as $column) {
$definition->text($column)->nullable();
}
});
}
});
test('standalone preflight does not create optional structures when no feature is selected', function () {
StandaloneSchema::verify($this->standaloneSchema, ['private-audit' => false]);
expect($this->standaloneSchema->hasTable('private_audit_exports'))->toBeFalse()
->and($this->standaloneDb->table('supply_records')->count())->toBe(0);
});
test('standalone preflight rejects an incomplete own chart instead of activating account attribution', function () {
$this->standaloneSchema->create('gl_accounts', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->string('label');
});
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, ['requisition-accounts' => true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_SCHEMA_INCOMPLETE:gl_accounts');
expect($this->standaloneSchema->hasColumn('gl_accounts', 'tenant_id'))->toBeFalse();
});
test('standalone preflight preserves documented import module dependencies', function (string $feature, string $dependency) {
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, [$feature => true, $dependency => false]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
})->with([['import-legal', 'import-tariffs'], ['import-bank-support', 'import-dossier'], ['import-readiness', 'import-dossier']]);
test('standalone preflight rejects an incomplete cycle schema without repairing it', function () {
$this->standaloneSchema->create('budget_requisition_cycles', fn (Blueprint $table) => $table->id());
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, ['requisition-expiry' => true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_SCHEMA_INCOMPLETE:requisitions');
expect($this->standaloneSchema->hasColumn('requisitions', 'approval_cycle'))->toBeFalse();
});
+15 -1
View File
@@ -4,7 +4,7 @@ import { expect, test } from 'vitest';
import ExpenseAllocation from '../../resources/js/pages/payments/expense-allocation';
import { ProcurementCategoryInsights } from '../../resources/js/components/procurement-category-insights';
function render(canWrite: boolean) {
function render(canWrite: boolean, common = false) {
return renderToStaticMarkup(
<App
initialComponent={ExpenseAllocation}
@@ -15,6 +15,12 @@ function render(canWrite: boolean) {
clearHistory: false,
encryptHistory: true,
props: {
...(common
? {
sourceType: 'common_allocation',
submitUrl: '/afectacoes-fornecedores/1/imputacao',
}
: {}),
errors: {},
canWrite,
actorId: 1,
@@ -63,6 +69,14 @@ test('Finance starts with blank amounts and deliberately chooses whether to reus
expect(html).toContain('Guardar imputação');
});
test('common allocation keeps its own source and returns to the common financial workspace', () => {
const html = render(true, true);
expect(html).toContain('Afectação #1');
expect(html).toContain('href="/supplier-payments"');
expect(html).not.toContain('href="/pagamentos?payment_id=1"');
expect(html).toContain('Guardar imputação');
});
test('category summary preserves unassigned expenses and separates currencies without allocating them automatically', () => {
const html = renderToStaticMarkup(
<ProcurementCategoryInsights
+3 -2
View File
@@ -82,13 +82,14 @@ final class LedgerSchema
}
namespace Tempo\Finance\GeneralLedger {
// general-ledger/src/PayableJournal.php SHA-256 2c45e2c5635d4ae60577f6261bf749f9ca91bb09435fcbe373d58a265583c1be
// general-ledger/src/PayableJournal.php SHA-256 d8e7a0f00c13544e17793e0ceaf63f69d66198eb9f33c876f7c4d981e1bf6d14
final class PayableJournal
{
public const POLICY = 'QA-PAYABLE-JOURNAL-v1';
public const HOST_POLICY = 'COMMON-PAYABLE-JOURNAL-v1';
/** @param array<array-key,mixed> $scope
* @param array<array-key,mixed>|null $financialScope */
public function __construct(\Illuminate\Database\ConnectionInterface $db, array $scope, int $actor, string $person, \Closure $authorize, \Closure $readAuthorize, \Closure $source, ?\Closure $checkpoint = NULL, ?\Closure $additionalSource = NULL, ?\Closure $additionalPeriod = NULL, ?array $financialScope = NULL) { throw new \LogicException('Static analysis declaration only.'); }
public function __construct(\Illuminate\Database\ConnectionInterface $db, array $scope, int $actor, string $person, \Closure $authorize, \Closure $readAuthorize, \Closure $source, ?\Closure $checkpoint = NULL, ?\Closure $additionalSource = NULL, ?\Closure $additionalPeriod = NULL, ?array $financialScope = NULL, ?string $hostPolicy = NULL) { throw new \LogicException('Static analysis declaration only.'); }
/** @param array<array-key,mixed> $data
* @return array<array-key,mixed> */
public function command(string $action, array $data, string $key): array { throw new \LogicException('Static analysis declaration only.'); }