Files
compras/app/Services/CommonBudget.php
T
nala dc73540558
tests / ci (push) Waiting to run
commit melhorias compras6
2026-11-23 06:37:16 +02:00

98 lines
5.9 KiB
PHP

<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\Budget\BudgetContext;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
/** Local host adapter: auth, tenant lock and audit; no budget arithmetic. */
final class CommonBudget
{
public const DISTRIBUTIONS_CONTRACT = 'COMMON-BUDGET-DISTRIBUTION-QA-v1';
public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
public const LANDED_COSTS_CONTRACT = 'COMMON-BUDGET-LANDED-COST-QA-v2';
public function for(User $user): BudgetControl
{
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
$runtime = new \ReflectionClass(BudgetControl::class);
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
if (! $runtime->hasConstant('LANDED_COSTS_VERSION') || $runtime->getConstant('LANDED_COSTS_VERSION') !== self::LANDED_COSTS_CONTRACT
|| ! $runtime->hasMethod('reserveLandedCosts') || ! $runtime->hasMethod('transitionLandedCosts')) {
foreach ($landedPresent as $table) {
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503, 'Existem efeitos de aterragem; preserve o motor compatível antes de consultar saldos.');
}
}
$orderTables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
$orderPresent = array_values(array_filter($orderTables, fn ($table) => Schema::hasTable($table)));
abort_if(count($orderPresent) !== 0 && count($orderPresent) !== count($orderTables), 503,
'Estrutura de ordens parciais incompleta; saldo não presumido.');
if (! $runtime->hasConstant('ORDER_PARTS_VERSION') || $runtime->getConstant('ORDER_PARTS_VERSION') !== self::ORDER_PARTS_CONTRACT
|| ! $runtime->hasMethod('commitOrderParts') || ! $runtime->hasMethod('consumeOrderParts')) {
foreach ($orderPresent as $table) {
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503,
'Existem efeitos de ordens parciais; preserve a composição compatível antes de consultar saldos.');
}
}
$distributionsCompatible = $runtime->hasMethod('recordDistribution') && $runtime->hasConstant('DISTRIBUTIONS_VERSION')
&& $runtime->getConstant('DISTRIBUTIONS_VERSION') === self::DISTRIBUTIONS_CONTRACT;
if (! $distributionsCompatible) {
$present = array_values(array_filter(['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'], fn ($table) => Schema::hasTable($table)));
abort_if(count($present) !== 0 && count($present) !== 4, 503, 'Estrutura de distribuição incompleta; saldo não presumido.');
foreach ($present as $table) {
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503,
'Existem distribuições orçamentais; preserve a composição compatível antes de consultar ou movimentar saldos.');
}
}
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Controlo comum desta entrega suporta apenas MZN; câmbio permanece pendente.');
$context = new BudgetContext($user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN');
return new BudgetControl(DB::connection(), $context, '',
function (string $action) use ($user): void {
app(ConflictGuard::class)->lockCompany($user);
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
? [PurchasingRole::Admin, PurchasingRole::Finance]
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend', 'orders.cancel', 'landed.reserve', 'landed.commit', 'landed.consume', 'landed.cancel', 'landed.amend'], true) ? [PurchasingRole::Finance]
: (in_array($action, ['orders.commit', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
app(CurrentActor::class)->lock($user, $roles);
},
function (string $action, array $data, ?int $origin) use ($user): void {
// InvoiceWorkflow retains invoice.validated in the enclosing transaction.
if ($action !== 'budget.consumed') {
$request = $origin ? Requisition::query()->findOrFail($origin) : null;
app(RequisitionWorkflow::class)->audit($user, $action, $request, null, $data);
}
},
fn (int $id): bool => User::query()->where('tenant_id', $user->tenant_id)->whereKey($id)->lockForUpdate()->first()?->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) ?? false,
);
}
/**
* @template T
*
* @param callable(): T $command
* @return T
*/
public function execute(callable $command): mixed
{
try {
return $command();
} catch (BudgetFailure $e) {
abort_if($e->status !== 422, $e->status, $e->getMessage());
throw ValidationException::withMessages([$e->field => $e->getMessage()]);
}
}
}