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

This commit is contained in:
2026-11-29 16:03:11 +02:00
parent 7da8d6c87a
commit 30bfb1a773
72 changed files with 10998 additions and 98 deletions
@@ -13,6 +13,7 @@ final class PrepareStandaloneRuntime extends Command
{--operator= : Named deployment operator}
{--reason= : Recorded installation or recovery reason}
{--apply : Apply the explicitly selected installation}
{--reuse-components : Reuse only complete recognised canonical V1 components; reject partial or changed schemas}
{--rebind : Preserve restored schema and register a new installation binding}';
protected $description = 'Preparar explicitamente a composição independente; pré-visualizar por defeito';
@@ -20,7 +21,8 @@ final class PrepareStandaloneRuntime extends Command
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);
(string) $this->option('operator'), (string) $this->option('reason'), $this->option('apply') === true, $this->option('rebind') === true,
$this->option('reuse-components') === true);
$this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return self::SUCCESS;
@@ -0,0 +1,48 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\CommonFinanceAdministration;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class CommonFinanceAdministrationController extends Controller
{
public function show(Request $request, CommonFinanceAdministration $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$data = $request->validate(['user' => 'nullable|integer|min:1', 'q' => 'nullable|string|max:100',
'users_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000']);
Inertia::encryptHistory();
$response = Inertia::render('company/finance', $service->workspace($actor, isset($data['user']) ? (int) $data['user'] : null, $data['q'] ?? ''))->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function store(Request $request, string $kind, CommonFinanceAdministration $service): RedirectResponse
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
try {
$service->save($actor, $kind, $request->all());
} catch (\DomainException $error) {
if ($request->header('X-Inertia')) {
throw ValidationException::withMessages(['configuration' => $error->getMessage()]);
}
abort(409, $error->getMessage());
} catch (\InvalidArgumentException $error) {
if ($request->header('X-Inertia')) {
throw ValidationException::withMessages(['configuration' => $error->getMessage()]);
}
abort(422, $error->getMessage());
}
return back()->with('success', 'Configuração financeira registada com histórico.');
}
}
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Models\User;
use App\Services\GeneralLedger;
use App\Services\StandaloneRuntime;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@@ -12,6 +13,14 @@ use Tempo\Finance\GeneralLedger\ReportsWorkspace;
final class GeneralLedgerController extends Controller
{
/** @return array<string,mixed> */
private function presentation(): array
{
return app(StandaloneRuntime::class)->enabled() ? ['host_journal_policy' => true,
'synthetic_only' => app(StandaloneRuntime::class)->syntheticOnly(),
'reports_from' => today()->startOfYear()->toDateString(), 'reports_to' => today()->toDateString()] : [];
}
public function report(Request $r, string $kind, GeneralLedger $ledger): Response|JsonResponse
{
$d = $r->validate(['from_on' => 'required|date_format:Y-m-d', 'to_on' => 'required|date_format:Y-m-d|after_or_equal:from_on', 'account_id' => 'sometimes|required|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|in:25,100']);
@@ -27,7 +36,7 @@ final class GeneralLedgerController extends Controller
return response()->json($data)->header('Cache-Control', 'no-store');
}
return response(ReportsWorkspace::render($data, ['host' => 'SGC autónomo', 'return_url' => '/general-ledger/cycle']))->header('Cache-Control', 'no-store');
return response(ReportsWorkspace::render($data, ['host' => 'SGC autónomo', 'return_url' => '/general-ledger/cycle'] + $this->presentation()))->header('Cache-Control', 'no-store');
}
private function actor(Request $r): User
@@ -44,7 +53,7 @@ final class GeneralLedgerController extends Controller
abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
$data = $ledger->workspace($this->actor($r), (int) ($d['page'] ?? 1));
return response(CycleWorkspace::render($data, ['host' => 'SGC autónomo', 'csrf' => csrf_token(), 'financial_url' => '/supplier-payments', 'return_url' => '/obrigacoes-fornecedores', 'page_url' => '/general-ledger/cycle']))->header('Cache-Control', 'no-store');
return response(CycleWorkspace::render($data, ['host' => 'SGC autónomo', 'csrf' => csrf_token(), 'financial_url' => '/supplier-payments', 'return_url' => '/obrigacoes-fornecedores', 'page_url' => '/general-ledger/cycle'] + $this->presentation()))->header('Cache-Control', 'no-store');
}
public function command(Request $r, string $action, GeneralLedger $ledger): JsonResponse
@@ -6,6 +6,7 @@ use App\Models\Tenant;
use App\Models\User;
use App\Services\AdministrativeGeography;
use App\Services\AiPreparationPlan;
use App\Services\CommonFinanceAdministration;
use App\Services\CompanyDetails;
use App\Services\ComparisonPolicy;
use App\Services\IntelligencePolicy;
@@ -49,6 +50,7 @@ class OrganizationConfigurationController extends Controller
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
'expiryReady' => app(RequisitionExpiry::class)->ready(),
'financeConfigurationReady' => app(CommonFinanceAdministration::class)->ready(),
'urgentReviewsReady' => app(UrgentRequisitionReviews::class)->ready(),
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
@@ -11,6 +11,7 @@ use App\Services\SupplierPayables;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tempo\Finance\Payables\SettlementHttp;
use Tempo\Finance\Payables\SupplierSettlements;
final class SupplierPaymentsController extends SettlementHttp
{
@@ -18,6 +19,14 @@ final class SupplierPaymentsController extends SettlementHttp
protected const SERVICE = SupplierPayables::class;
protected function settlementEngine(Request $request): SupplierSettlements
{
$user = $request->user();
abort_unless($user instanceof User, 403);
return app(SupplierPayables::class)->settlements($user);
}
protected function guard(): void
{
if (! app(StandaloneRuntime::class)->enabled()) {
@@ -34,7 +43,10 @@ final class SupplierPaymentsController extends SettlementHttp
{
$user = $request->user();
abort_unless($user instanceof User, 403);
$settings = [];
$settings = app(StandaloneRuntime::class)->enabled() ? [
'host_settlement_policy' => true, 'synthetic_only' => app(StandaloneRuntime::class)->syntheticOnly(),
'return_url' => '/dashboard',
] : [];
if (app(StandaloneRuntime::class)->enabled() && app(ExpenseAllocations::class)->ready() && $user->hasFunctions(['admin', 'finance'])) {
$settings['expense_allocation_base_url'] = '/afectacoes-fornecedores/';
}
@@ -4,12 +4,16 @@ namespace App\Http\Middleware;
use App\Models\User;
use App\Services\CapitalRegister;
use App\Services\CommonFinanceAdministration;
use App\Services\GeneralLedger;
use App\Services\OperationalOrders;
use App\Services\OrganizationAccess;
use App\Services\PrivateAuditAccess;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use App\Services\WorkContext;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Middleware;
@@ -66,6 +70,7 @@ class HandleInertiaRequests extends Middleware
'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor),
],
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'),
'commonFinanceNavigation' => $this->financeNavigation($actor),
'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(),
'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::class)->ready(),
@@ -73,4 +78,21 @@ class HandleInertiaRequests extends Middleware
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
];
}
/** @return array{payments:bool,ledger:bool,configuration:bool} */
private function financeNavigation(?User $actor): array
{
$hidden = ['payments' => false, 'ledger' => false, 'configuration' => false];
if ($actor === null || ! app(StandaloneRuntime::class)->enabled()
|| ! $actor->hasFunctions(['admin', 'finance']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
return $hidden;
}
return [
'payments' => app(StandaloneRuntime::class)->feature('supplier-settlements', DB::connection())
&& app(SupplierPayables::class)->can($actor, 'view') && app(SupplierPayables::class)->can($actor, 'payments_view'),
'ledger' => app(GeneralLedger::class)->cycleEnabled() && app(GeneralLedger::class)->can($actor, 'view'),
'configuration' => $actor->hasFunctions(['admin']) && app(CommonFinanceAdministration::class)->ready(),
];
}
}
+16 -4
View File
@@ -27,13 +27,25 @@ class AppServiceProvider extends ServiceProvider
$this->app->scoped(AdministrativeGeography::class);
$this->app->scoped(StandaloneRuntime::class, fn () => new StandaloneRuntime(config('standalone-runtime'), new StandaloneArtifact));
$runtime = $this->app->make(StandaloneRuntime::class);
$loader = $runtime;
$paths = null;
if ($runtime->enabled()) {
$preparing = config('standalone-runtime.prepare_only') === true;
if ($preparing && (! $this->app->runningInConsole() || $runtime->enabled())) {
throw new \LogicException('COMPRAS_RUNTIME_PREPARATION_CONSOLE_ONLY');
}
if ($runtime->enabled() || $preparing) {
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);
if ($preparing) {
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$loader = new StandaloneRuntime($settings, new StandaloneArtifact);
$paths = $loader->artifact()['paths'];
} else {
$paths = $runtime->configure(DB::connection());
}
$loader->assertLoadedPackages(allowMissing: true);
config(['common-budget.path' => $paths['budget-control'], 'common-payables.path' => $paths['payables'],
'general-ledger.path' => $paths['general-ledger']]);
}
@@ -49,7 +61,7 @@ class AppServiceProvider extends ServiceProvider
require_once $payables.'/bootstrap.php';
if ($paths !== null) {
require_once $paths['general-ledger'].'/bootstrap.php';
$runtime->assertLoadedPackages();
$loader->assertLoadedPackages();
}
}
@@ -0,0 +1,145 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\GeneralLedger\LedgerConfiguration;
/** Own-company setup over the common configuration writer; never grants a role or enables a deployment. */
final class CommonFinanceAdministration
{
public const LABELS = [
'view' => 'Consultar obrigações a fornecedores', 'prepare' => 'Preparar reconhecimento de obrigações',
'validate' => 'Validar reconhecimento de forma independente', 'payments_view' => 'Consultar pagamentos e afectações',
'payment_prepare' => 'Registar um facto de pagamento', 'payment_confirm' => 'Confirmar um facto de pagamento',
'allocation_prepare' => 'Propor afectações a facturas', 'allocation_confirm' => 'Confirmar afectações',
'reversal_prepare' => 'Propor reversão de uma afectação', 'reversal_confirm' => 'Confirmar reversão de forma independente',
'general_ledger.view' => 'Consultar o diário, balancete e razão', 'general_ledger.prepare' => 'Preparar lançamento contabilístico',
'general_ledger.validate' => 'Rever lançamento de forma independente', 'general_ledger.post' => 'Aplicar o lançamento revisto',
'general_ledger.correct_prepare' => 'Preparar estorno e substituição', 'general_ledger.correct_validate' => 'Rever o par de correcção',
'general_ledger.correct_post' => 'Aplicar o par revisto', 'general_ledger.period_prepare' => 'Preparar conferência do período',
'general_ledger.period_validate' => 'Rever conferência de forma independente', 'general_ledger.period_close' => 'Aplicar o fecho revisto',
];
public const EFFECT_LABELS = [
'supplier_payable.recognised' => 'Reconhecimento da obrigação', 'allocation.confirmed' => 'Afectação confirmada',
'allocation.reversed' => 'Reversão confirmada', 'journal.reversal' => 'Estorno exacto do original', 'journal.replacement' => 'Substituição do lançamento',
];
public function ready(): bool
{
return app(StandaloneRuntime::class)->enabled()
&& app(StandaloneRuntime::class)->feature('finance-configuration', DB::connection())
&& class_exists(LedgerConfiguration::class, false)
&& (new \ReflectionClass(LedgerConfiguration::class))->getConstant('VERSION') === 'COMMON-FINANCE-CONFIGURATION-v1';
}
private function actor(User $actor): User
{
abort_unless($this->ready(), 503);
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Admin]);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
return $actor;
}
private function eligible(User $target): bool
{
$access = app(OrganizationAccess::class);
$permissions = $access->active($target->tenant_id) ? $access->configuredPermissions($target, 'procurement.internal') : $access->permissions($target);
return ! $access->maintenanceOnly($target) && array_intersect($permissions, ['admin', 'finance']) !== [];
}
private function writer(User $actor): LedgerConfiguration
{
return new LedgerConfiguration(DB::connection(), ['tenant_id' => (int) $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0], $actor->id,
function (string $action, array $data) use ($actor) {
$fresh = $this->actor($actor);
if (isset($data['user_id'])) {
if (! is_int($data['user_id']) || $data['user_id'] < 1) {
throw new \InvalidArgumentException('Identificador nominativo inválido.');
}
$target = User::query()->where('tenant_id', $fresh->tenant_id)->whereKey($data['user_id'])->lockForUpdate()->firstOrFail();
if ($action === 'access' && ($data['actions'] ?? []) !== [] && ! $this->eligible($target)) {
throw ValidationException::withMessages(['user_id' => 'Atribua primeiro uma função de Finanças ou Administração no contexto de Compras internas. A manutenção temporária não recebe estes acessos.']);
}
}
},
fn (string $action, array $before, array $after, array $result) => app(RequisitionWorkflow::class)->audit($actor,
'company.finance_configuration_changed', null, $before, ['configuration_action' => $action, 'result' => $result, 'configuration' => $after]));
}
/** @return array<string,mixed> */
public function workspace(User $actor, ?int $selected = null, string $term = ''): array
{
return DB::transaction(function () use ($actor, $selected, $term) {
$actor = $this->actor($actor);
$writer = $this->writer($actor);
$target = $selected === null ? null : User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($selected);
$access = $target === null ? null : $writer->basis('access', $target->id);
if ($access !== null) {
$identities = array_values(array_unique(array_column($access['rows'], 'person')));
$access += ['user' => $target->only(['id', 'name', 'email']), 'eligible' => $this->eligible($target),
'person' => collect($access['rows'])->firstWhere('action', 'view')['person'] ?? ($identities[0] ?? ''),
'identity_inconsistent' => count($identities) > 1,
'actions' => array_values(array_intersect(array_column($access['rows'], 'action'), LedgerConfiguration::ACTIONS)),
'other_actions' => array_values(array_diff(array_column($access['rows'], 'action'), LedgerConfiguration::ACTIONS))];
}
$needle = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($term));
$people = User::query()->where('tenant_id', $actor->tenant_id)
->when($needle !== '', fn ($query) => $query->where(fn ($filter) => $filter->whereRaw("LOWER(name) LIKE LOWER(?) ESCAPE '!'", ['%'.$needle.'%'])
->orWhereRaw("LOWER(email) LIKE LOWER(?) ESCAPE '!'", ['%'.$needle.'%'])))
->orderBy('name')->orderBy('id')->paginate(25, ['id', 'name', 'email'], 'users_page')->withQueryString();
$scope = ['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0];
$history = DB::table('gl_events')->where($scope)->where('kind', 'like', 'configuration.%')->orderByDesc('id')
->paginate(15, ['id', 'actor_id', 'kind', 'reason', 'previous', 'subsequent', 'created_at'], 'history_page')->withQueryString()
->through(fn ($row) => ['id' => (int) $row->id, 'actor_id' => (int) $row->actor_id, 'kind' => $row->kind,
'reason' => $row->reason, 'before' => json_decode($row->previous, true, 64, JSON_THROW_ON_ERROR),
'after' => json_decode($row->subsequent, true, 64, JSON_THROW_ON_ERROR), 'created_at' => $row->created_at]);
return ['actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'users' => $people, 'selectedAccess' => $access,
'accounts' => $writer->basis('account'), 'periods' => $writer->basis('period'), 'rules' => $writer->basis('rule'),
'actions' => self::LABELS, 'effects' => self::EFFECT_LABELS, 'q' => $term, 'history' => $history];
});
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, string $kind, array $input): array
{
abort_unless($this->ready(), 503);
$rules = ['operation_key' => 'required|uuid', 'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:2000'];
$rules += match ($kind) {
'access' => ['user_id' => 'required|integer|min:1', 'person' => 'present|nullable|string|max:160',
'actions' => 'present|array|list|max:20', 'actions.*' => ['required', 'string', 'distinct:strict', Rule::in(LedgerConfiguration::ACTIONS)]],
'account' => ['code' => 'required|string|max:80', 'label' => 'required|string|max:200', 'currency' => 'required|in:MZN', 'is_movement' => 'required|boolean'],
'period' => ['period_key' => 'required|string|max:80', 'starts_on' => 'required|date_format:Y-m-d', 'ends_on' => 'required|date_format:Y-m-d|after_or_equal:starts_on'],
'rule' => ['rule_key' => 'required|string|max:80', 'effect_type' => ['required', Rule::in(LedgerConfiguration::EFFECTS)],
'valid_from' => 'required|date_format:Y-m-d', 'valid_to' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
'debit_account_id' => 'required|integer|min:1', 'credit_account_id' => 'required|integer|min:1|different:debit_account_id'],
default => throw new \InvalidArgumentException('Unknown financial configuration action.'),
};
$data = Validator::make($input, $rules)->validate();
$operation = strtolower($data['operation_key']);
unset($data['operation_key']);
if ($kind === 'access') {
$data['user_id'] = (int) $data['user_id'];
$data['person'] = $data['person'] ?? '';
sort($data['actions'], SORT_STRING);
} elseif ($kind === 'account') {
$data['is_movement'] = (bool) $data['is_movement'];
} elseif ($kind === 'rule') {
$data['debit_account_id'] = (int) $data['debit_account_id'];
$data['credit_account_id'] = (int) $data['credit_account_id'];
}
return $this->writer($actor)->command($kind, $data, $operation);
}
}
+1 -1
View File
@@ -86,7 +86,7 @@ class EquipmentWorkflow
if (TechnicalReview::query()->where('requisition_id', $requisition->id)->where('basis_hash', $basis)->exists()) {
throw ValidationException::withMessages(['technical' => 'Esta versão já tem uma decisão técnica. A decisão anterior permanece no histórico.']);
}
$review = TechnicalReview::query()->create(['tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'reviewed_by' => $user->id, 'basis_hash' => $basis, 'decision' => $decision, 'reason' => $reason, 'reviewed_at' => now(), 'snapshot' => ['reviewer' => $user->only(['id', 'name', 'department_id']), 'items' => $requisition->items()->get()->toArray(), 'development_only' => true, 'budget_checked' => false]]);
$review = TechnicalReview::query()->create(['tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'reviewed_by' => $user->id, 'basis_hash' => $basis, 'decision' => $decision, 'reason' => $reason, 'reviewed_at' => now(), 'snapshot' => ['reviewer' => $user->only(['id', 'name', 'department_id']), 'items' => $requisition->items()->get()->toArray(), 'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'budget_checked' => false]]);
app(RequisitionWorkflow::class)->audit($user, 'equipment.technical_'.$decision, $requisition, null, $review->toArray());
return $review;
+1 -1
View File
@@ -127,7 +127,7 @@ class ExternalPaymentWorkflow
$this->invalid('Referência, evidência e data válida do exercício actual são obrigatórias.');
}
$bank = $this->bank($user, $invoice, (int) $data['supplier_bank_detail_id'], $amount);
$payment = ExternalPayment::query()->create(['tenant_id' => $user->tenant_id, 'invoice_id' => $invoice->id, 'supplier_bank_detail_id' => $bank->id, 'created_by' => $user->id, 'amount_minor' => $amount, 'currency' => $bank->currency, 'paid_on' => $data['paid_on'], 'external_reference' => $reference, 'reference_hash' => $referenceHash, 'payload_hash' => $hash, 'evidence_reference' => trim($data['evidence_reference']), 'bank_snapshot' => ['bank_id' => $bank->id, 'revision' => $bank->revision, 'bank_name' => $bank->bank_name, 'country' => $bank->country, 'currency' => $bank->currency, 'beneficiary' => $bank->beneficiary, 'account_identifier' => $bank->account_identifier, 'reviewer_ids' => SupplierBankReview::query()->where('supplier_bank_detail_id', $bank->id)->pluck('reviewed_by')->all(), 'development_only' => true, 'bank_transfer_executed' => false]]);
$payment = ExternalPayment::query()->create(['tenant_id' => $user->tenant_id, 'invoice_id' => $invoice->id, 'supplier_bank_detail_id' => $bank->id, 'created_by' => $user->id, 'amount_minor' => $amount, 'currency' => $bank->currency, 'paid_on' => $data['paid_on'], 'external_reference' => $reference, 'reference_hash' => $referenceHash, 'payload_hash' => $hash, 'evidence_reference' => trim($data['evidence_reference']), 'bank_snapshot' => ['bank_id' => $bank->id, 'revision' => $bank->revision, 'bank_name' => $bank->bank_name, 'country' => $bank->country, 'currency' => $bank->currency, 'beneficiary' => $bank->beneficiary, 'account_identifier' => $bank->account_identifier, 'reviewer_ids' => SupplierBankReview::query()->where('supplier_bank_detail_id', $bank->id)->pluck('reviewed_by')->all(), 'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'bank_transfer_executed' => false]]);
$this->audit($user, $invoice, $payment, 'payment.registered');
return $payment;
+7
View File
@@ -128,6 +128,13 @@ final class GeneralLedger
$engine = $this->engine($user);
$data = $engine->cycleListing($page);
$data['book'] = $engine->listing(['page' => $page]);
if (app(StandaloneRuntime::class)->enabled()) {
$context = app(SupplierPayables::class)->readContext($user);
$rules = DB::table('gl_rules')->where($context['scope'])->orderByDesc('version')->get()
->unique('rule_key')->values()->map(fn ($rule) => (array) $rule)->all();
$data['configuration'] = ['rules' => $rules];
$data['synthetic_only'] = app(StandaloneRuntime::class)->syntheticOnly();
}
$actions = ['prepare', 'validate', 'post', 'correct_prepare', 'correct_validate', 'correct_post', 'period_prepare', 'period_validate', 'period_close'];
$data['permissions'] = array_combine($actions, array_map(fn ($a) => $this->can($user, $a), $actions));
+1 -1
View File
@@ -127,7 +127,7 @@ class InvoiceWorkflow
$invoice = new Invoice(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => $order->currency,
...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis'],
...(OrderPartsAccess::applies($order) ? ['exchange_sources' => $order->snapshot['exchange_sources']] : [])]),
'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
if (app(RequisitionBudgetDistributions::class)->applies($request)) {
$distribution = app(InvoiceBudgetDistributions::class)->prepare($user, $invoice, $order, $data, $lines);
$invoice->snapshot = [...$invoice->snapshot, 'budget_distribution' => $distribution];
+1 -1
View File
@@ -249,7 +249,7 @@ final class OrderPartsWorkflow
...($operational === [] ? [] : ['operational_orders' => $operational]),
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
'budget_control' => $commit, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'budget_checked' => true,
'order_parts' => ['version' => 1, 'order_key' => $orderKey, 'preparation_fingerprint' => $prepared['fingerprint'],
'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]];
$order = new PurchaseOrder(['tenant_id' => $actor->tenant_id, 'requisition_id' => $first['requisition_id'],
+1 -1
View File
@@ -57,7 +57,7 @@ class PurchaseRevisionWorkflow
if (! in_array($award->status, ['pending', 'approved', 'rejected']) || trim($reason) === '') {
$this->invalid('Estado ou fundamento inválido para cancelamento.');
}
$cancellation = AwardCancellation::query()->create(['tenant_id' => $actor->tenant_id, 'purchase_award_id' => $award->id, 'purchase_control_policy_id' => $policy->id, 'created_by' => $actor->id, 'reason' => trim($reason), 'basis_hash' => $this->basis($award), 'snapshot' => ['policy' => $policy->only(['id', 'revision', 'mode', 'enabled', 'valid_from', 'valid_until']), 'award' => $award->toArray(), 'requisition_id' => $request->id, 'development_only' => true]]);
$cancellation = AwardCancellation::query()->create(['tenant_id' => $actor->tenant_id, 'purchase_award_id' => $award->id, 'purchase_control_policy_id' => $policy->id, 'created_by' => $actor->id, 'reason' => trim($reason), 'basis_hash' => $this->basis($award), 'snapshot' => ['policy' => $policy->only(['id', 'revision', 'mode', 'enabled', 'valid_from', 'valid_until']), 'award' => $award->toArray(), 'requisition_id' => $request->id, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()]]);
app(RequisitionWorkflow::class)->audit($actor, 'cancellation.requested', $request, null, ['cancellation_id' => $cancellation->id, 'award_id' => $award->id, 'policy_id' => $policy->id]);
return $cancellation;
+1 -1
View File
@@ -184,7 +184,7 @@ class PurchaseWorkflow
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
'development_only' => true,
'development_only' => app(StandaloneRuntime::class)->syntheticOnly(),
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $award->total_minor, $award->subtotal_minor, $quote),
'investment_rules' => $award->investment_snapshot,
'equipment_requests' => $requisition->items()->where('purchase_type', 'equipment')->get()->map(fn ($line) => $line->only(['id', 'description', 'production_area']))->all(),
+1 -1
View File
@@ -244,7 +244,7 @@ class ReceiptWorkflow
'tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'received_by' => $user->id, 'warehouse_id' => $warehouse?->id,
'idempotency_key' => $data['idempotency_key'], 'payload_hash' => $hash, 'delivery_note' => $deliveryNote,
'received_on' => $data['received_on'], 'status' => 'partial', 'confirmed_at' => now(),
'snapshot' => ['order' => $order->only(['id', 'number']), 'supplier' => $order->snapshot['supplier'], 'receiver' => $user->only(['id', 'name']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'development_only' => true, 'budget_checked' => false],
'snapshot' => ['order' => $order->only(['id', 'number']), 'supplier' => $order->snapshot['supplier'], 'receiver' => $user->only(['id', 'name']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'budget_checked' => false],
]);
foreach ($lines as $line) {
$item = $receipt->items()->create($line);
@@ -0,0 +1,71 @@
<?php
namespace App\Services;
use Illuminate\Database\Connection;
use LogicException;
/** Structural identity only; never reads business rows or repairs an existing component. */
final class StandaloneComponentSchema
{
public const GROUPS = [
'budget-distributions-v1' => ['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'],
'supplier-settlements-v1' => ['ps_payments', 'ps_payment_decisions', 'ps_proposals', 'ps_allocation_aliases', 'ps_allocation_decisions', 'ps_allocations', 'ps_commands', 'ps_events', 'ps_outbox'],
'supplier-payables-v1' => ['pa_access', 'pa_sources', 'pa_proposals', 'pa_obligations', 'pa_commands', 'pa_events', 'pa_outbox'],
];
// Measured from the canonical definitions in an owned synthetic PostgreSQL17 composition.
// Pilot metadata was compared separately; it was not used as the authority for these identities.
public const SUPPORTED = [
'budget-distributions-v1' => '4239f48f64e2beb0cf34d3dc8730aca3a0c54aef9cb0dff2c69d03c0e8b1c2e1',
'supplier-settlements-v1' => '11b1522f8b62c32944cf53a6180046d28d51c5c295e6e390633ac809d72bf05a',
'supplier-payables-v1' => 'cda146acf4e674c72b7676fc02cf9b8c5e89208d1dd099193950d785c4dd8452',
];
/** @return list<string> */
public static function reusable(Connection $db): array
{
$groups = [];
foreach (self::SUPPORTED as $group => $expected) {
$actual = self::inspect($db, $group);
if ($actual['present'] === []) {
continue;
}
if ($actual['sha256'] === null || ! hash_equals($expected, $actual['sha256'])) {
throw new LogicException('COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:'.$group);
}
$groups[] = $group;
}
return $groups;
}
/** @return array{present:array<int,string>,sha256:?string} */
public static function inspect(Connection $db, string $group): array
{
if ($db->getDriverName() !== 'pgsql' || ! isset(self::GROUPS[$group])) {
throw new LogicException('COMPRAS_RUNTIME_COMPONENT_PROFILE');
}
$tables = self::GROUPS[$group];
$present = array_values(array_filter($tables, fn ($table) => $db->getSchemaBuilder()->hasTable($table)));
if (count($present) !== count($tables)) {
return ['present' => $present, 'sha256' => null];
}
$frames = [];
sort($tables, SORT_STRING);
foreach ($tables as $table) {
$oid = $db->selectOne('SELECT to_regclass(?)::oid AS id', ['public.'.$table])->id;
$frames[$table] = [
'columns' => $db->select('SELECT a.attname AS name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS required,pg_get_expr(d.adbin,d.adrelid) AS default_value FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum WHERE a.attrelid=? AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum', [$oid]),
'constraints' => $db->select('SELECT conname AS name,contype AS kind,condeferrable AS deferrable,condeferred AS deferred,convalidated AS validated,pg_get_constraintdef(oid,true) AS definition FROM pg_constraint WHERE conrelid=? ORDER BY conname', [$oid]),
'indexes' => $db->select('SELECT ci.relname AS name,pg_get_indexdef(i.indexrelid) AS definition,i.indisvalid AS valid FROM pg_index i JOIN pg_class ci ON ci.oid=i.indexrelid WHERE i.indrelid=? ORDER BY ci.relname', [$oid]),
'triggers' => $db->select('SELECT t.tgname AS name,t.tgenabled AS enabled,pg_get_triggerdef(t.oid,true) AS definition,pg_get_functiondef(t.tgfoid) AS function_definition FROM pg_trigger t WHERE t.tgrelid=? AND NOT t.tgisinternal ORDER BY t.tgname', [$oid]),
];
}
if ($group === 'budget-distributions-v1') {
$frames['anchors'] = $db->select("SELECT a.attname AS name,format_type(a.atttypid,a.atttypmod) AS type,a.attnotnull AS required FROM pg_attribute a WHERE a.attrelid='public.requisitions'::regclass AND a.attname='budget_distribution_preparation' AND NOT a.attisdropped");
}
return ['present' => $present, 'sha256' => hash('sha256', json_encode($frames, JSON_THROW_ON_ERROR))];
}
}
+29 -3
View File
@@ -8,7 +8,8 @@ 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
/** @param list<string> $expectedComponents */
public static function install(Connection $db, bool $reuseComponents = false, array $expectedComponents = []): void
{
$settings = config('standalone-runtime');
$settings['enabled'] = true;
@@ -35,23 +36,48 @@ final class StandaloneExtensionSchema
}
$schemas[] = [$schema, $contract, $connectionArgument];
}
$db->transaction(function () use ($db, $runtime, $settings, $schemas) {
$db->transaction(function () use ($db, $runtime, $settings, $schemas, $reuseComponents, $expectedComponents) {
$db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', [$settings['installation_id']]);
$runtime->assertInstallation($db);
$reused = [];
if ($reuseComponents) {
// Same company-first ordering as business writers; no schema adoption in a request.
$db->statement('LOCK TABLE tenants,requisitions,approval_steps,workflow_notices,budget_entries IN SHARE ROW EXCLUSIVE MODE');
foreach (StandaloneComponentSchema::GROUPS as $tables) {
foreach ($tables as $table) {
if ($db->getSchemaBuilder()->hasTable($table)) {
$db->statement('LOCK TABLE '.$table.' IN SHARE ROW EXCLUSIVE MODE');
}
}
}
$reused = StandaloneComponentSchema::reusable($db);
if ($reused !== $expectedComponents) {
throw new \LogicException('COMPRAS_RUNTIME_COMPONENT_PLAN_CHANGED');
}
}
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)) {
if (($table === 'budget_distributions' && in_array('budget-distributions-v1', $reused, true))
|| ($table === 'ps_payments' && in_array('supplier-settlements-v1', $reused, true))) {
continue;
}
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();
if (! in_array('budget-distributions-v1', $reused, true)) {
BudgetDistributionSchema::install();
}
BudgetOrderPartsSchema::install($db);
PurchaseOrderSourcesSchema::install($db);
BudgetLandedCostSchema::install($db);
RequisitionCycleSchema::install($db);
foreach ($schemas as [$schema, $contract, $connectionArgument]) {
if ($contract === 'COMMON-PAYABLE-SETTLEMENT-HOST-SCHEMA-v1' && in_array('supplier-settlements-v1', $reused, true)) {
continue;
}
$arguments = [$contract, fn () => $runtime->assertInstallation($db)];
if ($connectionArgument) {
array_unshift($arguments, $db);
+18 -5
View File
@@ -10,15 +10,21 @@ use LogicException;
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
public function prepare(string $database, string $role, string $operator, string $reason, bool $apply = false, bool $rebind = false, bool $reuseComponents = 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 ($rebind && $reuseComponents) {
throw new LogicException('Recovery binding and initial component reuse are separate operations.');
}
if (config('standalone-runtime.enabled') === true) {
throw new LogicException('Disable runtime activation before explicit installation or recovery.');
}
if (config('standalone-runtime.prepare_only') !== true) {
throw new LogicException('Use explicit console preparation mode to verify the pinned packages before loading executable files.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
@@ -35,14 +41,21 @@ final class StandaloneInstallation
if ($identity === null || $identity->database_name !== $database || $identity->role_name !== $role) {
throw new LogicException('COMPRAS_RUNTIME_EXPECTED_DESTINATION');
}
$already = $db->getSchemaBuilder()->hasTable('compras_runtime_installations')
&& $db->table('compras_runtime_installations')->where('id', $settings['installation_id'])->exists();
if ($already) {
$runtime->assertInstallation($db);
}
$reused = $reuseComponents && ! $already ? StandaloneComponentSchema::reusable($db) : [];
$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];
'feature_activation' => false, 'actor_grants' => false, 'rebind' => $rebind,
'reuse_components' => $reuseComponents, 'existing_components' => $reused];
if (! $apply) {
return $plan + ['state' => 'preview', 'written' => false];
}
return $db->transaction(function () use ($db, $runtime, $settings, $binding, $operator, $reason, $rebind, $plan) {
return $db->transaction(function () use ($db, $runtime, $settings, $binding, $operator, $reason, $rebind, $plan, $reuseComponents, $reused) {
$db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', ['COMPRAS-STANDALONE-INSTALLATION']);
$schema = $db->getSchemaBuilder();
if (! $schema->hasTable('compras_runtime_installations')) {
@@ -63,10 +76,10 @@ final class StandaloneInstallation
$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(),
'recorded_by' => $operator, 'reason' => $reason.($reused === [] ? '' : "\nReused canonical components: ".json_encode(array_intersect_key(StandaloneComponentSchema::SUPPORTED, array_flip($reused)), JSON_THROW_ON_ERROR)), 'installed_at' => now(),
]);
if (! $rebind) {
StandaloneExtensionSchema::install($db);
StandaloneExtensionSchema::install($db, $reuseComponents, $reused);
}
$runtime->assertInstallation($db);
StandaloneSchema::verify($schema, $settings['features']);
+41 -1
View File
@@ -12,7 +12,7 @@ final class StandaloneRuntime
'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'];
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration'];
/** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
private ?array $artifact = null;
@@ -30,6 +30,16 @@ final class StandaloneRuntime
return $this->enabled() && ($this->settings['features'][$feature] ?? false) === true;
}
public function syntheticOnly(): bool
{
$value = $this->enabled() ? ($this->settings['synthetic_only'] ?? true) : true;
if (! is_bool($value)) {
throw new LogicException('COMPRAS_RUNTIME_DATA_CLASSIFICATION');
}
return $value;
}
/** @return array<string,string>|null */
public function configure(Connection $db): ?array
{
@@ -46,6 +56,17 @@ final class StandaloneRuntime
public function assertLoadedPackages(bool $allowMissing = false): void
{
$artifact = $this->artifact();
foreach ([...get_declared_classes(), ...get_declared_interfaces(), ...get_declared_traits()] as $class) {
if (! str_starts_with($class, 'Tempo\\Finance\\Budget\\') && ! str_starts_with($class, 'Tempo\\Purchasing\\')
&& ! str_starts_with($class, 'Tempo\\Finance\\Payables\\') && ! str_starts_with($class, 'Tempo\\Finance\\GeneralLedger\\')) {
continue;
}
$loaded = (new \ReflectionClass($class))->getFileName();
$root = realpath($artifact['root']);
if (! is_string($loaded) || $root === false || ! str_starts_with(realpath($loaded) ?: '', $root.DIRECTORY_SEPARATOR)) {
throw new LogicException('COMPRAS_RUNTIME_CLASS_LOCATION');
}
}
foreach ([
'Tempo\\Finance\\Budget\\BudgetControl' => 'budget-control/src/BudgetControl.php',
'Tempo\\Purchasing\\Internal\\InternalRequisitions' => 'purchasing/src/InternalRequisitions.php',
@@ -64,12 +85,30 @@ final class StandaloneRuntime
}
}
if (! $allowMissing) {
if ($this->requested('finance-configuration')) {
$configuration = 'Tempo\\Finance\\GeneralLedger\\LedgerConfiguration';
if (! class_exists($configuration, false) || (new \ReflectionClass($configuration))->getConstant('VERSION') !== 'COMMON-FINANCE-CONFIGURATION-v1') {
throw new LogicException('COMPRAS_RUNTIME_FINANCE_CONFIGURATION');
}
}
if ($this->requested('supplier-settlements')) {
$settlements = new \ReflectionClass('Tempo\\Finance\\Payables\\SupplierSettlements');
$payables = new \ReflectionClass('Tempo\\Finance\\Payables\\Payables');
if (! $settlements->hasConstant('HOST_POLICY') || $settlements->getConstant('HOST_POLICY') !== 'COMMON-SUPPLIER-SETTLEMENT-v1'
|| ! $payables->hasMethod('hostSettlements')) {
throw new LogicException('COMPRAS_RUNTIME_SETTLEMENT_POLICY');
}
}
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');
}
if ($this->requested('general-ledger-cycle') && (! $journal->hasConstant('CONFIGURED_CORRECTIONS_VERSION')
|| $journal->getConstant('CONFIGURED_CORRECTIONS_VERSION') !== 'COMMON-LEDGER-CONFIGURED-CORRECTION-v1')) {
throw new LogicException('COMPRAS_RUNTIME_CORRECTION_POLICY');
}
}
$budget = new \ReflectionClass('Tempo\\Finance\\Budget\\BudgetControl');
foreach ([
@@ -114,6 +153,7 @@ final class StandaloneRuntime
throw new LogicException('COMPRAS_RUNTIME_CONFIGURATION');
}
$artifact = $this->verifier->verify($root, $pin);
$this->syntheticOnly();
$features = $this->settings['features'] ?? [];
if (! is_array($features)) {
throw new LogicException('COMPRAS_RUNTIME_FEATURES');
+4 -1
View File
@@ -13,7 +13,8 @@ final class StandaloneSchema
{
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) {
'supplier-settlements' => ['supplier-payables'], 'general-ledger-cycle' => ['general-ledger', 'supplier-settlements'],
'finance-configuration' => ['supplier-payables', 'general-ledger']] 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);
@@ -51,6 +52,8 @@ final class StandaloneSchema
'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']],
'finance-configuration' => ['pa_access' => ['id', 'user_id', 'person', 'action'], 'gl_accounts' => ['id'],
'gl_rules' => ['id'], 'gl_periods' => ['id'], 'gl_commands' => ['id'], 'gl_events' => ['id']],
default => [],
};
foreach ($required as $table => $columns) {
+9 -4
View File
@@ -125,7 +125,7 @@ class StockWorkflow
'equipment_id' => $equipment?->id, 'spare_part_id' => $part?->id,
'payload_hash' => $hash, 'destination' => $data['destination'] ?? null, 'reason' => $data['reason'],
'quantity_milli' => $quantity, 'theoretical_milli' => $balance['quantity'], 'ledger_version' => $balance['version'], 'recorded_at' => now(),
'snapshot' => [...$lotSnapshot, 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => true],
'snapshot' => [...$lotSnapshot, 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()],
]);
if ($adjustment !== null) {
foreach ([['decrease_milli', -1, 'adjustment_out'], ['increase_milli', 1, 'adjustment_in']] as [$key, $sign, $type]) {
@@ -278,11 +278,16 @@ class StockWorkflow
private function movement(User $actor, StockOperation $operation, int $warehouse, int $quantity, string $type): StockMovement
{
if($type==='issue'&&$operation->kind==='issue'){
$writer=app(StockIssueMovement::class)->for($actor);$result=$writer->write($operation->id,$writer->preview($operation->id));
if(!is_int($result['movement_id']??null)||$result['movement_id']<1)throw new \LogicException('Referência de movimento devolvida pelo escritor incompatível.');
if ($type === 'issue' && $operation->kind === 'issue') {
$writer = app(StockIssueMovement::class)->for($actor);
$result = $writer->write($operation->id, $writer->preview($operation->id));
if (! is_int($result['movement_id'] ?? null) || $result['movement_id'] < 1) {
throw new \LogicException('Referência de movimento devolvida pelo escritor incompatível.');
}
return StockMovement::query()->findOrFail($result['movement_id']);
}
return StockMovement::query()->create(['tenant_id' => $actor->tenant_id, 'stock_operation_id' => $operation->id, 'stock_item_id' => $operation->stock_item_id, 'warehouse_id' => $warehouse, 'equipment_id' => $operation->equipment_id, 'spare_part_id' => $operation->spare_part_id, 'moved_by' => $actor->id, 'movement_type' => $type, 'quantity_milli' => $quantity, 'snapshot' => [...$operation->snapshot, 'warehouse' => Warehouse::query()->findOrFail($warehouse)->only(['id', 'code', 'name']), 'reference' => $operation->reference, 'reason' => $operation->reason], 'moved_at' => now()]);
}
}
+19
View File
@@ -10,9 +10,28 @@ use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tempo\Finance\Payables\Payables;
use Tempo\Finance\Payables\SupplierSettlements;
final class SupplierPayables
{
public function settlements(User $actor): SupplierSettlements
{
$runtime = app(StandaloneRuntime::class);
if (! $runtime->enabled()) {
return $this->engine($actor)->settlements();
}
abort_unless($runtime->feature('supplier-settlements', DB::connection()), 403);
$engine = $this->engine($actor);
$class = new \ReflectionClass($engine);
abort_unless($class->hasMethod('hostSettlements'), 503, 'Contrato financeiro de instalação incompatível.');
$settlements = $class->getMethod('hostSettlements')->invoke($engine, 'COMMON-SUPPLIER-SETTLEMENT-v1', $runtime->syntheticOnly());
if (! $settlements instanceof SupplierSettlements) {
throw new \LogicException('COMPRAS_RUNTIME_SETTLEMENT_ENGINE');
}
return $settlements;
}
public static function enabled(): bool
{
if (app(StandaloneRuntime::class)->enabled()) {