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} {--operator= : Named deployment operator}
{--reason= : Recorded installation or recovery reason} {--reason= : Recorded installation or recovery reason}
{--apply : Apply the explicitly selected installation} {--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}'; {--rebind : Preserve restored schema and register a new installation binding}';
protected $description = 'Preparar explicitamente a composição independente; pré-visualizar por defeito'; 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 public function handle(StandaloneInstallation $installation): int
{ {
$result = $installation->prepare((string) $this->option('expected-database'), (string) $this->option('expected-role'), $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)); $this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return self::SUCCESS; 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\Models\User;
use App\Services\GeneralLedger; use App\Services\GeneralLedger;
use App\Services\StandaloneRuntime;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response; use Illuminate\Http\Response;
@@ -12,6 +13,14 @@ use Tempo\Finance\GeneralLedger\ReportsWorkspace;
final class GeneralLedgerController extends Controller 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 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']); $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()->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 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); abort_if(array_diff(array_keys($r->query()), ['page']) !== [], 422);
$data = $ledger->workspace($this->actor($r), (int) ($d['page'] ?? 1)); $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 public function command(Request $r, string $action, GeneralLedger $ledger): JsonResponse
@@ -6,6 +6,7 @@ use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Services\AdministrativeGeography; use App\Services\AdministrativeGeography;
use App\Services\AiPreparationPlan; use App\Services\AiPreparationPlan;
use App\Services\CommonFinanceAdministration;
use App\Services\CompanyDetails; use App\Services\CompanyDetails;
use App\Services\ComparisonPolicy; use App\Services\ComparisonPolicy;
use App\Services\IntelligencePolicy; use App\Services\IntelligencePolicy;
@@ -49,6 +50,7 @@ class OrganizationConfigurationController extends Controller
'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'), 'companyDetailsReady' => Schema::hasColumn('tenants', 'company_details'),
'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(), 'approvalLevelsReady' => app(RequisitionApprovalLevels::class)->ready(),
'expiryReady' => app(RequisitionExpiry::class)->ready(), 'expiryReady' => app(RequisitionExpiry::class)->ready(),
'financeConfigurationReady' => app(CommonFinanceAdministration::class)->ready(),
'urgentReviewsReady' => app(UrgentRequisitionReviews::class)->ready(), 'urgentReviewsReady' => app(UrgentRequisitionReviews::class)->ready(),
'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [], 'requisitionCategoryOptions' => app(RequisitionCategories::class)->available() ? RequisitionCategories::LABELS : [],
'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy, 'approvalLevels' => Tenant::query()->findOrFail($actor->tenant_id)->requisition_approval_policy,
@@ -11,6 +11,7 @@ use App\Services\SupplierPayables;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Tempo\Finance\Payables\SettlementHttp; use Tempo\Finance\Payables\SettlementHttp;
use Tempo\Finance\Payables\SupplierSettlements;
final class SupplierPaymentsController extends SettlementHttp final class SupplierPaymentsController extends SettlementHttp
{ {
@@ -18,6 +19,14 @@ final class SupplierPaymentsController extends SettlementHttp
protected const SERVICE = SupplierPayables::class; 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 protected function guard(): void
{ {
if (! app(StandaloneRuntime::class)->enabled()) { if (! app(StandaloneRuntime::class)->enabled()) {
@@ -34,7 +43,10 @@ final class SupplierPaymentsController extends SettlementHttp
{ {
$user = $request->user(); $user = $request->user();
abort_unless($user instanceof User, 403); 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'])) { if (app(StandaloneRuntime::class)->enabled() && app(ExpenseAllocations::class)->ready() && $user->hasFunctions(['admin', 'finance'])) {
$settings['expense_allocation_base_url'] = '/afectacoes-fornecedores/'; $settings['expense_allocation_base_url'] = '/afectacoes-fornecedores/';
} }
@@ -4,12 +4,16 @@ namespace App\Http\Middleware;
use App\Models\User; use App\Models\User;
use App\Services\CapitalRegister; use App\Services\CapitalRegister;
use App\Services\CommonFinanceAdministration;
use App\Services\GeneralLedger;
use App\Services\OperationalOrders; use App\Services\OperationalOrders;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use App\Services\PrivateAuditAccess; use App\Services\PrivateAuditAccess;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables; use App\Services\SupplierPayables;
use App\Services\WorkContext; use App\Services\WorkContext;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Inertia\Middleware; use Inertia\Middleware;
@@ -66,6 +70,7 @@ class HandleInertiaRequests extends Middleware
'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor), 'profileLabel' => app(OrganizationAccess::class)->profileLabel($actor),
], ],
'payablesAvailable' => $actor !== null && app(SupplierPayables::class)->can($actor, 'view'), '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'), 'orderCancellationAvailable' => $actor !== null && (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(), 'operationalOrdersAvailable' => $actor !== null && app(OperationalOrders::class)->ready(),
'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::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', '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(),
];
}
} }
+15 -3
View File
@@ -27,13 +27,25 @@ class AppServiceProvider extends ServiceProvider
$this->app->scoped(AdministrativeGeography::class); $this->app->scoped(AdministrativeGeography::class);
$this->app->scoped(StandaloneRuntime::class, fn () => new StandaloneRuntime(config('standalone-runtime'), new StandaloneArtifact)); $this->app->scoped(StandaloneRuntime::class, fn () => new StandaloneRuntime(config('standalone-runtime'), new StandaloneArtifact));
$runtime = $this->app->make(StandaloneRuntime::class); $runtime = $this->app->make(StandaloneRuntime::class);
$loader = $runtime;
$paths = null; $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) { if (config('common-finance-bundle.root') !== null || config('budget-distributions.enabled') === true) {
throw new \LogicException('COMPRAS_RUNTIME_MIXED_COMPOSITION'); throw new \LogicException('COMPRAS_RUNTIME_MIXED_COMPOSITION');
} }
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()); $paths = $runtime->configure(DB::connection());
$runtime->assertLoadedPackages(allowMissing: true); }
$loader->assertLoadedPackages(allowMissing: true);
config(['common-budget.path' => $paths['budget-control'], 'common-payables.path' => $paths['payables'], config(['common-budget.path' => $paths['budget-control'], 'common-payables.path' => $paths['payables'],
'general-ledger.path' => $paths['general-ledger']]); 'general-ledger.path' => $paths['general-ledger']]);
} }
@@ -49,7 +61,7 @@ class AppServiceProvider extends ServiceProvider
require_once $payables.'/bootstrap.php'; require_once $payables.'/bootstrap.php';
if ($paths !== null) { if ($paths !== null) {
require_once $paths['general-ledger'].'/bootstrap.php'; 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()) { 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.']); 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()); app(RequisitionWorkflow::class)->audit($user, 'equipment.technical_'.$decision, $requisition, null, $review->toArray());
return $review; 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.'); $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); $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'); $this->audit($user, $invoice, $payment, 'payment.registered');
return $payment; return $payment;
+7
View File
@@ -128,6 +128,13 @@ final class GeneralLedger
$engine = $this->engine($user); $engine = $this->engine($user);
$data = $engine->cycleListing($page); $data = $engine->cycleListing($page);
$data['book'] = $engine->listing(['page' => $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']; $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)); $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, $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'], ...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis'],
...(OrderPartsAccess::applies($order) ? ['exchange_sources' => $order->snapshot['exchange_sources']] : [])]), ...(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)) { if (app(RequisitionBudgetDistributions::class)->applies($request)) {
$distribution = app(InvoiceBudgetDistributions::class)->prepare($user, $invoice, $order, $data, $lines); $distribution = app(InvoiceBudgetDistributions::class)->prepare($user, $invoice, $order, $data, $lines);
$invoice->snapshot = [...$invoice->snapshot, 'budget_distribution' => $distribution]; $invoice->snapshot = [...$invoice->snapshot, 'budget_distribution' => $distribution];
+1 -1
View File
@@ -249,7 +249,7 @@ final class OrderPartsWorkflow
...($operational === [] ? [] : ['operational_orders' => $operational]), ...($operational === [] ? [] : ['operational_orders' => $operational]),
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']), 'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue, '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'], 'order_parts' => ['version' => 1, 'order_key' => $orderKey, 'preparation_fingerprint' => $prepared['fingerprint'],
'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]]; 'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]];
$order = new PurchaseOrder(['tenant_id' => $actor->tenant_id, 'requisition_id' => $first['requisition_id'], $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) === '') { if (! in_array($award->status, ['pending', 'approved', 'rejected']) || trim($reason) === '') {
$this->invalid('Estado ou fundamento inválido para cancelamento.'); $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]); app(RequisitionWorkflow::class)->audit($actor, 'cancellation.requested', $request, null, ['cancellation_id' => $cancellation->id, 'award_id' => $award->id, 'policy_id' => $policy->id]);
return $cancellation; return $cancellation;
+1 -1
View File
@@ -184,7 +184,7 @@ class PurchaseWorkflow
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings), ...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)]), ...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]), ...($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), 'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $award->total_minor, $award->subtotal_minor, $quote),
'investment_rules' => $award->investment_snapshot, 'investment_rules' => $award->investment_snapshot,
'equipment_requests' => $requisition->items()->where('purchase_type', 'equipment')->get()->map(fn ($line) => $line->only(['id', 'description', 'production_area']))->all(), '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, '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, 'idempotency_key' => $data['idempotency_key'], 'payload_hash' => $hash, 'delivery_note' => $deliveryNote,
'received_on' => $data['received_on'], 'status' => 'partial', 'confirmed_at' => now(), '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) { foreach ($lines as $line) {
$item = $receipt->items()->create($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))];
}
}
+28 -2
View File
@@ -8,7 +8,8 @@ use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Explicit additive installation only; never called by application boot or a business request. */ /** Explicit additive installation only; never called by application boot or a business request. */
final class StandaloneExtensionSchema 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 = config('standalone-runtime');
$settings['enabled'] = true; $settings['enabled'] = true;
@@ -35,23 +36,48 @@ final class StandaloneExtensionSchema
} }
$schemas[] = [$schema, $contract, $connectionArgument]; $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']]); $db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', [$settings['installation_id']]);
$runtime->assertInstallation($db); $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', 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) { 'budget_requisition_cycles', 'gl_accounts', 'ps_payments', 'ps_reversals', 'gl_corrections'] as $table) {
if ($db->getSchemaBuilder()->hasTable($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'); throw new \LogicException('COMPRAS_RUNTIME_EXTENSION_SCHEMA_EXISTS');
} }
} }
// The normal application migrations already install the common payables schema. // The normal application migrations already install the common payables schema.
StandaloneSchema::verify($db->getSchemaBuilder(), ['supplier-payables' => true]); StandaloneSchema::verify($db->getSchemaBuilder(), ['supplier-payables' => true]);
if (! in_array('budget-distributions-v1', $reused, true)) {
BudgetDistributionSchema::install(); BudgetDistributionSchema::install();
}
BudgetOrderPartsSchema::install($db); BudgetOrderPartsSchema::install($db);
PurchaseOrderSourcesSchema::install($db); PurchaseOrderSourcesSchema::install($db);
BudgetLandedCostSchema::install($db); BudgetLandedCostSchema::install($db);
RequisitionCycleSchema::install($db); RequisitionCycleSchema::install($db);
foreach ($schemas as [$schema, $contract, $connectionArgument]) { 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)]; $arguments = [$contract, fn () => $runtime->assertInstallation($db)];
if ($connectionArgument) { if ($connectionArgument) {
array_unshift($arguments, $db); array_unshift($arguments, $db);
+18 -5
View File
@@ -10,15 +10,21 @@ use LogicException;
final class StandaloneInstallation final class StandaloneInstallation
{ {
/** @return array<string,mixed> */ /** @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'), [ Validator::make(compact('database', 'role', 'operator', 'reason'), [
'database' => 'required|string|max:200', 'role' => 'required|string|max:200', 'database' => 'required|string|max:200', 'role' => 'required|string|max:200',
'operator' => 'required|string|min:3|max:200', 'reason' => 'required|string|min:10|max:4000', 'operator' => 'required|string|min:3|max:200', 'reason' => 'required|string|min:10|max:4000',
])->validate(); ])->validate();
if ($rebind && $reuseComponents) {
throw new LogicException('Recovery binding and initial component reuse are separate operations.');
}
if (config('standalone-runtime.enabled') === true) { if (config('standalone-runtime.enabled') === true) {
throw new LogicException('Disable runtime activation before explicit installation or recovery.'); 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 = config('standalone-runtime');
$settings['enabled'] = true; $settings['enabled'] = true;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, 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) { if ($identity === null || $identity->database_name !== $database || $identity->role_name !== $role) {
throw new LogicException('COMPRAS_RUNTIME_EXPECTED_DESTINATION'); 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'], $plan = ['contract' => StandaloneArtifact::CONTRACT, 'installation_id' => $settings['installation_id'],
'manifest_sha256' => $settings['manifest_sha256'], 'database' => $database, 'role' => $role, '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) { if (! $apply) {
return $plan + ['state' => 'preview', 'written' => false]; 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']); $db->selectOne('SELECT pg_advisory_xact_lock(hashtextextended(?, 0))', ['COMPRAS-STANDALONE-INSTALLATION']);
$schema = $db->getSchemaBuilder(); $schema = $db->getSchemaBuilder();
if (! $schema->hasTable('compras_runtime_installations')) { if (! $schema->hasTable('compras_runtime_installations')) {
@@ -63,10 +76,10 @@ final class StandaloneInstallation
$db->table('compras_runtime_installations')->insert([ $db->table('compras_runtime_installations')->insert([
'id' => $settings['installation_id'], 'product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT, 'id' => $settings['installation_id'], 'product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT,
'manifest_sha256' => $settings['manifest_sha256'], 'database_binding_sha256' => $binding, '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) { if (! $rebind) {
StandaloneExtensionSchema::install($db); StandaloneExtensionSchema::install($db, $reuseComponents, $reused);
} }
$runtime->assertInstallation($db); $runtime->assertInstallation($db);
StandaloneSchema::verify($schema, $settings['features']); 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', 'urgent-reviews', 'urgent-quotations', 'conflict-releases', 'private-audit', 'expense-allocations',
'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier', 'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier',
'import-bank-support', 'import-readiness', 'import-estimates', 'import-landed-costs', 'budget-distributions', '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 */ /** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
private ?array $artifact = null; private ?array $artifact = null;
@@ -30,6 +30,16 @@ final class StandaloneRuntime
return $this->enabled() && ($this->settings['features'][$feature] ?? false) === true; 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 */ /** @return array<string,string>|null */
public function configure(Connection $db): ?array public function configure(Connection $db): ?array
{ {
@@ -46,6 +56,17 @@ final class StandaloneRuntime
public function assertLoadedPackages(bool $allowMissing = false): void public function assertLoadedPackages(bool $allowMissing = false): void
{ {
$artifact = $this->artifact(); $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 ([ foreach ([
'Tempo\\Finance\\Budget\\BudgetControl' => 'budget-control/src/BudgetControl.php', 'Tempo\\Finance\\Budget\\BudgetControl' => 'budget-control/src/BudgetControl.php',
'Tempo\\Purchasing\\Internal\\InternalRequisitions' => 'purchasing/src/InternalRequisitions.php', 'Tempo\\Purchasing\\Internal\\InternalRequisitions' => 'purchasing/src/InternalRequisitions.php',
@@ -64,12 +85,30 @@ final class StandaloneRuntime
} }
} }
if (! $allowMissing) { 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')) { if ($this->requested('general-ledger')) {
$journal = new \ReflectionClass('Tempo\\Finance\\GeneralLedger\\PayableJournal'); $journal = new \ReflectionClass('Tempo\\Finance\\GeneralLedger\\PayableJournal');
if (! $journal->hasConstant('HOST_POLICY') || $journal->getConstant('HOST_POLICY') !== 'COMMON-PAYABLE-JOURNAL-v1' 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)) { || ! in_array('hostPolicy', array_map(fn ($parameter) => $parameter->getName(), $journal->getConstructor()?->getParameters() ?? []), true)) {
throw new LogicException('COMPRAS_RUNTIME_JOURNAL_POLICY'); 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'); $budget = new \ReflectionClass('Tempo\\Finance\\Budget\\BudgetControl');
foreach ([ foreach ([
@@ -114,6 +153,7 @@ final class StandaloneRuntime
throw new LogicException('COMPRAS_RUNTIME_CONFIGURATION'); throw new LogicException('COMPRAS_RUNTIME_CONFIGURATION');
} }
$artifact = $this->verifier->verify($root, $pin); $artifact = $this->verifier->verify($root, $pin);
$this->syntheticOnly();
$features = $this->settings['features'] ?? []; $features = $this->settings['features'] ?? [];
if (! is_array($features)) { if (! is_array($features)) {
throw new LogicException('COMPRAS_RUNTIME_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'], foreach (['import-legal' => ['import-tariffs'], 'import-bank-support' => ['import-dossier'],
'import-readiness' => ['import-dossier'], 'general-ledger' => ['supplier-payables'], '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) { foreach ($dependencies as $dependency) {
if (($features[$feature] ?? false) === true && ($features[$dependency] ?? false) !== true) { if (($features[$feature] ?? false) === true && ($features[$dependency] ?? false) !== true) {
throw new LogicException('COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency); throw new LogicException('COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
@@ -51,6 +52,8 @@ final class StandaloneSchema
'ps_reversal_proposals' => ['id'], 'ps_reversals' => ['id']], 'ps_reversal_proposals' => ['id'], 'ps_reversals' => ['id']],
'general-ledger-cycle' => ['gl_corrections' => ['id'], 'gl_correction_results' => ['id'], 'general-ledger-cycle' => ['gl_corrections' => ['id'], 'gl_correction_results' => ['id'],
'gl_period_checks' => ['id'], 'gl_period_reviews' => ['id'], 'gl_period_closures' => ['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 => [], default => [],
}; };
foreach ($required as $table => $columns) { foreach ($required as $table => $columns) {
+9 -4
View File
@@ -125,7 +125,7 @@ class StockWorkflow
'equipment_id' => $equipment?->id, 'spare_part_id' => $part?->id, 'equipment_id' => $equipment?->id, 'spare_part_id' => $part?->id,
'payload_hash' => $hash, 'destination' => $data['destination'] ?? null, 'reason' => $data['reason'], 'payload_hash' => $hash, 'destination' => $data['destination'] ?? null, 'reason' => $data['reason'],
'quantity_milli' => $quantity, 'theoretical_milli' => $balance['quantity'], 'ledger_version' => $balance['version'], 'recorded_at' => now(), '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) { if ($adjustment !== null) {
foreach ([['decrease_milli', -1, 'adjustment_out'], ['increase_milli', 1, 'adjustment_in']] as [$key, $sign, $type]) { 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 private function movement(User $actor, StockOperation $operation, int $warehouse, int $quantity, string $type): StockMovement
{ {
if($type==='issue'&&$operation->kind==='issue'){ if ($type === 'issue' && $operation->kind === 'issue') {
$writer=app(StockIssueMovement::class)->for($actor);$result=$writer->write($operation->id,$writer->preview($operation->id)); $writer = app(StockIssueMovement::class)->for($actor);
if(!is_int($result['movement_id']??null)||$result['movement_id']<1)throw new \LogicException('Referência de movimento devolvida pelo escritor incompatível.'); $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()->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()]); 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\DB;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Tempo\Finance\Payables\Payables; use Tempo\Finance\Payables\Payables;
use Tempo\Finance\Payables\SupplierSettlements;
final class SupplierPayables 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 public static function enabled(): bool
{ {
if (app(StandaloneRuntime::class)->enabled()) { if (app(StandaloneRuntime::class)->enabled()) {
+3
View File
@@ -3,14 +3,17 @@
// Deployment settings only. No installation, feature or permission is enabled by default. // Deployment settings only. No installation, feature or permission is enabled by default.
return [ return [
'enabled' => env('COMPRAS_RUNTIME_ENABLED', false), 'enabled' => env('COMPRAS_RUNTIME_ENABLED', false),
'prepare_only' => env('COMPRAS_RUNTIME_PREPARE_ONLY', false),
'root' => env('COMPRAS_RUNTIME_ROOT'), 'root' => env('COMPRAS_RUNTIME_ROOT'),
'manifest_sha256' => env('COMPRAS_RUNTIME_SHA256'), 'manifest_sha256' => env('COMPRAS_RUNTIME_SHA256'),
'installation_id' => env('COMPRAS_RUNTIME_INSTALLATION_ID'), 'installation_id' => env('COMPRAS_RUNTIME_INSTALLATION_ID'),
'synthetic_only' => env('COMPRAS_RUNTIME_SYNTHETIC_ONLY', true),
'features' => [ 'features' => [
'supplier-payables' => env('COMPRAS_SUPPLIER_PAYABLES_ENABLED', false), 'supplier-payables' => env('COMPRAS_SUPPLIER_PAYABLES_ENABLED', false),
'general-ledger' => env('COMPRAS_GENERAL_LEDGER_ENABLED', false), 'general-ledger' => env('COMPRAS_GENERAL_LEDGER_ENABLED', false),
'general-ledger-cycle' => env('COMPRAS_GENERAL_LEDGER_CYCLE_ENABLED', false), 'general-ledger-cycle' => env('COMPRAS_GENERAL_LEDGER_CYCLE_ENABLED', false),
'supplier-settlements' => env('COMPRAS_SUPPLIER_SETTLEMENTS_ENABLED', false), 'supplier-settlements' => env('COMPRAS_SUPPLIER_SETTLEMENTS_ENABLED', false),
'finance-configuration' => env('COMPRAS_FINANCE_CONFIGURATION_ENABLED', false),
'budget-distributions' => env('COMPRAS_BUDGET_DISTRIBUTIONS_ENABLED', false), 'budget-distributions' => env('COMPRAS_BUDGET_DISTRIBUTIONS_ENABLED', false),
'capital-register' => env('COMPRAS_CAPITAL_REGISTER_ENABLED', false), 'capital-register' => env('COMPRAS_CAPITAL_REGISTER_ENABLED', false),
'operational-orders' => env('COMPRAS_OPERATIONAL_ORDERS_ENABLED', false), 'operational-orders' => env('COMPRAS_OPERATIONAL_ORDERS_ENABLED', false),
+24
View File
@@ -1,5 +1,29 @@
# Desenvolvimento do SGC # Desenvolvimento do SGC
29/11/2026 — instalação no piloto expressamente autorizada e executada: runtime `80483320` em pasta privada própria, cinco migrações delimitadas e um recibo da instalação. Nova salvaguarda/restauro119tabelas,118tabelas de negócio e todas as colunas anteriores conservadas; histórico de migrações preservado. Transacção única ensaiada na cópia, bloqueio das escritas e recusa se houver diferença face à salvaguarda antes da alteração; repetição sem duplicação. Base/role temporárias removidas. Configuração activa, .env, manifesto e acessos preservados. Conferência readonly independente validou recibo/identidade não elevada, recusou UUID errado e conferiu24schemas; HTTP /avaliar200 e/login302. Novas capacidades continuam desligadas. Pré-conferência da activação passou em processo separado com PostgreSQL forçado a só leitura:24capacidades e185assets conferidos, sem publicação ou alteração activa. Activação e publicação da interface partilhada estão delimitadas em `compras-standalone-pilot-activation-proposal.json`, ainda por autorizar. Não repetir a instalação. Provas `compras-standalone-pilot-installation.json`, `compras-standalone-pilot-installation-check.json` e `compras-standalone-pilot-activation-preflight.json`; aplicação integral não declarada concluída.
29/11/2026 — actualização privada autorizada: `php scripts/check-standalone-private-recovery.php --run-authorized-private-copy`. Confere hash da proposta/autorização, destino e runtime; snapshot readonly, salvaguarda fora do repositório, restauro sob identidade própria, comparação integral das colunas anteriores, cinco migrações delimitadas e preparação/repetição sem escrita adicional. Não serve a cópia por HTTP nem envia correio/jobs.119tabelas inicialmente idênticas e118tabelas de negócio conservadas; histórico de migrações preservado,24capacidades conferidas, base/role temporárias removidas. Prova `proofs/compras-standalone-pilot-recovery.json`; não equivale a instalação/activação do piloto.
Candidata actual `80483320a54af6f1`: balancete e razão conservam o intervalo e a página na impressão, escondem controlos e distinguem linhas da página de totais do filtro. Dez testes integrados/218 asserções passaram; impressão real pré-visualizada numa folha e apresentação móvel390×526/100% conferida, sem impressão física. Configuração e menu móveis conferidos; aviso nativo de preparação pendente preservou texto ao cancelar a navegação. Limites restantes constam da prova operacional.
### Reutilização explícita dos componentes existentes — QA
`compras:runtime:prepare --reuse-components` pré-visualiza a reutilização dos perfis completos `budget-distributions-v1`, `supplier-settlements-v1` e `supplier-payables-v1`, pelas assinaturas de `StandaloneComponentSchema::SUPPORTED`. Acrescentar `--apply` executa a alteração aditiva. Colunas, constraints, índices, triggers e funções são conferidos novamente sob bloqueio. Sem a opção, componentes existentes continuam recusados; estruturas desconhecidas não são reparadas. O recibo conserva a selecção e os hashes. `--rebind` é uma operação separada.
`node scripts/requisition-ledger-qa-check.mjs --standalone-upgrade-only`: três testes/169 asserções passaram, com pré-visualização sem escrita, aplicação única, repetição, conservação de todas as colunas anteriores e do pagamento parcial confirmado, reversão integral de falha intermédia e repetição segura. Base sintética e role removidos. Inventário estrutural readonly do piloto em `proofs/standalone-pilot-schema-inventory.json`; sem valores de negócio ou instalação. Tabelas preexistentes não autorizam marcar migrações antigas como executadas. Uma instalação real exige autorização própria e selecção exacta dos caminhos aplicáveis; não executar migração genérica sobre essas tabelas.
## Candidata independente autorizada — 29/11/2026
Configuração financeira disponível em `/administracao/financeiro`, sob a capacidade opt-in `finance-configuration` e Administração da própria empresa. Cadastro explícito de identidades/competências, contasMZN, períodos e regras versionadas pelo writer comum; não concede funções por consulta nem cria operações financeiras. O menu Administração e a parametrização ligam ao cadastro; Finanças apresenta pagamentos/afectações e diário/balancete/razão apenas com capacidades e direitos próprios, com navegação integral para as páginas dos pacotes. Provas: PostgreSQL10/209, frontend473/93ficheiros e revisão real do cadastro/recarga/menu, com oito conjuntos financeiros/stock preservados. `--standalone-runtime-only --standalone-finance-preview` prepara exclusivamente uma revisão local sintética de20minutos, após arranque/restauro da candidata, com verificação final de conservação e remoção dos recursos próprios. Não usar esse runner no activo.
Autorização e evidência em `proofs/compras-operational-candidate-authorization.json` e `proofs/compras-operational-candidate.json`. O empacotador `scripts/standalone-runtime-artifact.php` recebe `--financial-source` e `--output`, cria uma pasta/ZIP novos por hash e confere cada byte; nunca substitui pacotes instalados ou bundles congelados. A execução instalada permanece independente da pasta de desenvolvimento SGF.
Procedimento preparado e exercitado exclusivamente em QA: extrair o ZIP conferido para uma pasta própria e definir `COMPRAS_RUNTIME_ROOT`, `COMPRAS_RUNTIME_SHA256` e `COMPRAS_RUNTIME_INSTALLATION_ID`. Durante a preparação de consola, usar `COMPRAS_RUNTIME_PREPARE_ONLY=true` e `COMPRAS_RUNTIME_ENABLED=false`: o carregador verifica o manifesto e todos os ficheiros antes de executar os quatro pacotes; a aplicação de negócio permanece desligada. Não seleccionar pacotes por caminhos avulsos para preparar a candidata. Conservar o bundle QA e a activação antiga de distribuições desligados. A base própria tem de possuir as migrações normais, com role PostgreSQL sem privilégios elevados. `PAYABLE_SOURCE_INSTANCE` identifica explicitamente as origens da instalação. Terminar o modo de preparação antes de qualquer arranque de negócio; a activação exige a autorização e configuração correspondentes.
`compras:runtime:prepare --expected-database=<base-própria> --expected-role=<role-própria> --operator=<nome> --reason=<motivo>` apresenta a pré-visualização. `--apply` executa a preparação explícita numa transacção; uma repetição válida não escreve outro recibo nem reinstala o schema. Não cria contas empresariais, permissões ou activação de módulos. A configuração opt-in de cada capacidade continua separada. Após restauro para outra base/role, a identidade antiga é recusada; com UUID novo, `--rebind --apply` verifica o schema e acrescenta um recibo, preservando dados e o recibo anterior. Nunca eliminar histórico para ultrapassar uma recusa de downgrade ou composição parcial.
Estes comandos não foram executados no piloto/produção. Uma instalação real continua a exigir o destino exacto e a autorização própria com backup/restauro e validação. A candidata ainda conserva limites de referências/apresentação sintéticas a concluir, além dos percursos visuais já registados. As provas técnicas não encerram a aplicação.
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 — 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. 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.
+12
View File
@@ -1,5 +1,17 @@
# Matriz reconciliada do SGC — 03/11/2026 # Matriz reconciliada do SGC — 03/11/2026
29/11/2026 — instalação no piloto expressamente autorizada e executada: runtime `80483320` em pasta privada própria, cinco migrações delimitadas e um recibo da instalação. Nova salvaguarda/restauro119tabelas,118tabelas de negócio e todas as colunas anteriores conservadas; histórico de migrações preservado. Transacção única ensaiada na cópia, bloqueio das escritas e recusa se houver diferença face à salvaguarda antes da alteração; repetição sem duplicação. Base/role temporárias removidas. Configuração activa, .env, manifesto e acessos preservados. Conferência readonly independente validou recibo/identidade não elevada, recusou UUID errado e conferiu24schemas; HTTP /avaliar200 e/login302. Novas capacidades continuam desligadas. Pré-conferência da activação passou em processo separado com PostgreSQL forçado a só leitura:24capacidades e185assets conferidos, sem publicação ou alteração activa. Activação e publicação da interface partilhada estão delimitadas em `compras-standalone-pilot-activation-proposal.json`, ainda por autorizar. Não repetir a instalação. Provas `compras-standalone-pilot-installation.json`, `compras-standalone-pilot-installation-check.json` e `compras-standalone-pilot-activation-preflight.json`; aplicação integral não declarada concluída.
29/11/2026 — candidata actual `80483320`, 67 ficheiros/68 entradas. Balancete/razão com impressão compacta, intervalo e paginação explícitos; Edge confirmou uma folha sem controlos de pesquisa e apresentação a390×526/100%. Configuração financeira móvel legível, atalhos em linhas e salto ao plano abaixo do cabeçalho; ligação visível do menu abriu o diário. Comando AX anterior atingiu rodapé porque a ligação estava fora da área visível; sessão e destino correcto conferidos, sem alterar código por inferência. Aviso nativo de saída conservou o fundamento ao cancelar e deixou de aparecer após limpar o rascunho. Dez testes integrados/218 asserções, Pint e PHPStan passaram. Ensaio privado expressamente autorizado: restauro idêntico de119tabelas,118tabelas de negócio conservadas após cinco migrações delimitadas, histórico das migrações preservado,24capacidades verificadas e um recibo/repetição sem escrita. Bases/roles temporárias removidas, salvaguarda privada preservada; origem, permissões, configuração e assets activos intactos. Provas `compras-operational-candidate.json` e `compras-standalone-pilot-recovery.json`. Instalação/activação do piloto e aceitação integral continuam por autorizar/verificar.
29/11/2026 — continuidade financeira da candidata: corrigida a recarga automática dos ecrãs comuns de pagamentos/diário que podia apagar a preparação de outro formulário. No modo autónomo, operação concluída conserva as outras preparações e oferece actualização explícita; saída avisa apenas quando há alterações, falha de rede conserva valores/UUID e submissão pendente não cria outra chamada. Sem armazenamento persistente novo no navegador. Dez testes executam os scripts do ZIP realmente extraído; comportamento QA anterior preservado. Novo manifesto `106ab6bd9d0e4cb9721ba02200dd4207100d7c4845653f920faa866dcbbcc07b`,67ficheiros/68entradas. Arranque/restauro/recusas passaram; duas rondas com dois processos PHP independentes confirmam uma conta/comando/evento/auditoria, repetição segura ou recusa da preparação desactualizada, oito conjuntos financeiros/stock intactos e nenhuma concessão automática. Negócio PostgreSQL10/209 e PHPStan aprovados; bases/roles removidos. Revisão nativa deste delta continua separada. Prova `proofs/compras-operational-candidate.json`.
29/11/2026 — C2 confirmado após acção manual do proprietário («ja feito»): estado Aprovado visível com Finanças independente; worker em transacção somente leitura passou, conservando a ordem emitida integral, os valores/relações de15conjuntos, uma solicitação/uma decisão e respectivas auditorias. Estado operacional cancelado e apenas a requisição de origem cancelada; sem reversão financeira fictícia no original legado não controlado. Base/roleQA removidos. A confirmação final deixou de estar pendente; móvel/impressão e fecho do separador continuam sem nova prova, porque o controlo da janela devolveu geometria indisponível em duas tentativas. Prova `proofs/product-review-20261122.json`, secção `native_cancellation_manual_review_pending_20261129`, agora verificada.
29/11/2026 — delta verificado da candidata autorizada: 24 capacidades, quatro pacotes, 67 ficheiros/68 entradas ZIP, manifesto `c6e458cb9d8b5eb6db9e5729706b1d32cd12291dd4a733e3ab893e95cd33252f`. Preparação exclusiva de consola verifica os bytes antes do carregamento; arranque/restauro/recusas e preservação aprovados. Configuração financeira pela empresa e menus condicionados aos direitos explícitos: PostgreSQL10/209, frontend integral473/93ficheiros, tipos/PHPStan/Pint aprovados. O ciclo real de reconhecimento/diário utiliza o cadastro de acessos, contas, período e regra pelo serviço da empresa. Navegador: conta fictícia registada, formulário limpo, recarga persistente e entrada Administração conferidos; oito conjuntos financeiros/stock intactos e bases/roles removidos. Ajuda específica acrescentada após a observação. Prova `proofs/compras-operational-candidate.json`. C2 continua sem decisão nativa confirmada; interrupção da ferramenta não foi contornada. Instalação/activação no piloto e aceitação integral permanecem separadas.
29/11/2026 — delta da promoção expressamente autorizada: candidata independente com 23 capacidades opt-in e quatro pacotes comuns verificados, ZIP de 67 entradas, sem instalação/activação no piloto. Registo próprio da instalação, contratos/schema/dependências, recusa de runtime antigo e classe estrangeira, migrações aditivas com definição única e CLI nominativa com pré-visualização/repetição/restauro. Negócio na candidata: PostgreSQL 7 testes/102 asserções, incluindo conta por linha, reserva revista, expiração nativa, recusa de escrita sem direitos, diário equilibrado com contas configuradas, imputação explícita de 40 MZN em 15+25 e pagamento único de 70 MZN repartido por duas facturas em 30+40. Auditoria/expense SQLite19/653 e frontend4 aprovados; PostgreSQL de auditoria e nova conferência do ZIP em curso. Referência: `proofs/compras-operational-candidate.json`. Preservar os limites históricos; a promoção não encerra as referências sintéticas, revisão visual restante, C2 nem a aplicação integral.
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 — 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. 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.
+12
View File
@@ -1,5 +1,17 @@
# Continuidade do desenvolvimento do SGC # Continuidade do desenvolvimento do SGC
29/11/2026 — instalação no piloto expressamente autorizada e executada: runtime `80483320` em pasta privada própria, cinco migrações delimitadas e um recibo da instalação. Nova salvaguarda/restauro119tabelas,118tabelas de negócio e todas as colunas anteriores conservadas; histórico de migrações preservado. Transacção única ensaiada na cópia, bloqueio das escritas e recusa se houver diferença face à salvaguarda antes da alteração; repetição sem duplicação. Base/role temporárias removidas. Configuração activa, .env, manifesto e acessos preservados. Conferência readonly independente validou recibo/identidade não elevada, recusou UUID errado e conferiu24schemas; HTTP /avaliar200 e/login302. Novas capacidades continuam desligadas. Pré-conferência da activação passou em processo separado com PostgreSQL forçado a só leitura:24capacidades e185assets conferidos, sem publicação ou alteração activa. Activação e publicação da interface partilhada estão delimitadas em `compras-standalone-pilot-activation-proposal.json`, ainda por autorizar. Não repetir a instalação. Provas `compras-standalone-pilot-installation.json`, `compras-standalone-pilot-installation-check.json` e `compras-standalone-pilot-activation-preflight.json`; aplicação integral não declarada concluída.
29/11/2026 — candidata actual `80483320`, 67 ficheiros/68 entradas. Balancete/razão com impressão compacta, intervalo e paginação explícitos; Edge confirmou uma folha sem controlos de pesquisa e apresentação a390×526/100%. Configuração financeira móvel legível, atalhos em linhas e salto ao plano abaixo do cabeçalho; ligação visível do menu abriu o diário. Comando AX anterior atingiu rodapé porque a ligação estava fora da área visível; sessão e destino correcto conferidos, sem alterar código por inferência. Aviso nativo de saída conservou o fundamento ao cancelar e deixou de aparecer após limpar o rascunho. Dez testes integrados/218 asserções, Pint e PHPStan passaram. Ensaio privado expressamente autorizado: restauro idêntico de119tabelas,118tabelas de negócio conservadas após cinco migrações delimitadas, histórico das migrações preservado,24capacidades verificadas e um recibo/repetição sem escrita. Bases/roles temporárias removidas, salvaguarda privada preservada; origem, permissões, configuração e assets activos intactos. Provas `compras-operational-candidate.json` e `compras-standalone-pilot-recovery.json`. Instalação/activação do piloto e aceitação integral continuam por autorizar/verificar.
29/11/2026 — candidata actual `106ab6bd`,67ficheiros/68entradas, substitui apenas a selecção de testes, sem sobrescrever pacotes anteriores. Corrigida perda das outras preparações por recarga após sucesso nos ecrãs comuns de pagamentos/diário. Protecção de saída por alterações, conservação do UUID após resultado desconhecido, bloqueio de submissão simultânea e botão de actualização explícita quando há outro rascunho; sem localStorage/sessionStorage novos. Dez testes dos scripts do ZIP extraído passaram. Arranque/restauro/recusas passaram com24capacidades; duas corridas reais com dois processos: mesma chave guarda uma vez/repetição, chaves diferentes sobre a mesma base guardam uma vez/recusam a segunda preparação. Uma conta/comando/evento/auditoria por ronda, oito conjuntos protegidos conservados e zero concessões. PostgreSQL10/209 e PHPStan passaram; recursosQA removidos. Confirmar visualmente este delta quando a geometria do Edge estiver recuperada; pedida apenas restauração/maximização da janela, não nova decisãoC2. A resposta «ja feito» já encerrou a confirmaçãoC2 e não deve ser pedida outra vez.
29/11/2026 — proprietário executou a confirmação nativa C2 e respondeu «ja feito». Aprovado observado emQAa14258b549a5 com Finanças independente; conferência final passou: ordem emitida original imutável, estado operacional cancelado, apenas requisição de origem cancelada,15conjuntos protegidos intactos e uma auditoria de pedido/uma de aprovação. Sem criar reversão fictícia para a origem legada explicitamente não controlada. Base/role removidos; não pedir nem executar novamente esta confirmação. A ligação de origem não pôde ser accionada: duas respostas de geometria indisponível após recuperação da janela; parar essa frente. Móvel/impressão e fecho do separador ainda não demonstrados. Prova `product-review-20261122.json`; os parágrafos abaixo sobre a confirmação pendente são históricos, não reabrem a validação já recebida.
29/11/2026 — estado seguinte verificado: a promoção autorizada já tem 24 capacidades e ZIP de 68 entradas, manifesto `c6e458cb9d8b5eb6db9e5729706b1d32cd12291dd4a733e3ab893e95cd33252f`. A referência anterior a21capacidades é histórica. Modo `COMPRAS_RUNTIME_PREPARE_ONLY` exclusivo da consola confere todo o pacote antes de o executar, mantendo negócio desligado; arranque/restauro/recusas aprovados. Configuração financeira própria: Admin escolhe pessoa/competências, contas, períodos sem sobreposição e versões de regras; preserva competências de outros contratos e não lança valores. Menus novos de pagamentos/afectações, diário/balancete/razão e configuração dependem das capacidades e direitos; páginas comuns usam navegação integral. PostgreSQL10/209 inclui configuração pelo serviço no ciclo financeiro, HTTP, âmbito estrangeiro, repetição, preparação desactualizada e revogação. Frontend integral473/93, tipos e PHPStan aprovados. Revisão real Edge sobre candidata extraída: cadastro da conta sintéticaQA-FIN-320, limpeza após sucesso, persistência após recarga e menu Administração; oito conjuntos financeiros/stock preservados, base/role original e restaurados removidos. Ajuda financeira específica acrescentada após detectar uma remissão indevida para auditoria. Nenhuma concessão ou instalação real.
Última tentativa C2: composiçãoQA3f41b9c4c6e6 criou pedido por autor e preparou Aprovar/fundamento com Finanças independente; ferramenta voltou a interromper no diálogo por não confirmar oURL. A conferência final recusou a ausência de decisão aprovada; não é perda do original nem prova de aprovação. Base/role removidos. O diálogo foi depois cancelado e o separadorQA fechado sem submissão; separador original conservado. Não repetir automaticamente a mesma frente nem executar a decisão por outra interface. A confirmação nativa final precisa de intervenção manual numa composição nova. Formalização de Pessoas continua adiada por decisão expressa; revisão visual/impressão restante e autorização própria de instalação/activação mantêm-se abertas.
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 — 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 — 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.
+307 -22
View File
@@ -1,30 +1,73 @@
{ {
"date": "2026-11-29", "date": "2026-11-29",
"state": "in_progress_not_installed_or_activated", "state": "pilot_schema_and_runtime_installed_new_capabilities_not_activated",
"authorization": "compras-operational-candidate-authorization.json", "authorization": "compras-operational-candidate-authorization.json",
"artifact": { "artifact": {
"root": "storage/framework/testing/compras-standalone-afe98e1ede5b9b4b", "root": "storage/framework/testing/compras-standalone-80483320a54af6f1",
"contract": "COMPRAS-STANDALONE-v1", "contract": "COMPRAS-STANDALONE-v1",
"manifest_sha256": "afe98e1ede5b9b4b184fb99f613d264a471d6b2eb4d29566377db7f824dd58a4", "manifest_sha256": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"files": 66, "files": 67,
"packages": ["budget-control", "purchasing", "payables", "general-ledger"] "packages": [
"budget-control",
"purchasing",
"payables",
"general-ledger"
],
"archive": "storage/framework/testing/compras-standalone-80483320a54af6f1.zip",
"archive_sha256": "bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76",
"archive_entries": 68
}, },
"implemented": [ "implemented": [
"Pinned complete inventory before executable loading; explicit own installation identity and non-elevated PostgreSQL role", "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", "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", "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", "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" "24 opt-in module adapters retain current permissions, history and single financial writer; explicit account submission fails closed",
"Named installation CLI previews by default, refuses a wrong database/role, applies atomically and repeats without new writes; explicit rebind preserves old receipts",
"Versioned host journal policy uses explicitly configured own chart accounts, preserving the old QA policy and all balance/source/independence constraints",
"Common original confirmed payment allocations connect to explicit Finance category attribution, without copying native payments; same numeric identifiers remain separated by source kind",
"One common payment allocated across invoices is counted once while documentary monetary portions are summed exactly; pending or reversed allocations remain visibly indeterminate",
"Private audit includes common settlement and ledger-cycle datasets with own tenant/company/unit scope; bank reference fields and full snapshots remain outside the settlement payment projection",
"Explicit host settlement reference policy keeps legacy SIM behaviour and synthetic provenance as independent concerns",
"Ledger host forms select configured periods and rules without fixed demo dates or values; configured correction reverses original accounts and amounts exactly",
"Fresh native document snapshots use declared data classification, defaulting to synthetic; historical snapshots are never rewritten",
"Console-only explicit preparation mode validates every candidate byte before loading executable code while keeping business capabilities disabled",
"Own company administrator UI for explicit financial person/access assignments, append-only chart and periods, versioned rules and bounded configuration history; no posting or automatic grant from reading",
"Permission-aware main menu links for common payments and ledger workspace, with full navigation for package HTML; administrator configuration link and specific journey guide",
"Host financial forms preserve other pending preparations after success, warn before leaving edited forms, retain command identity after unknown results and reject concurrent duplicate submits; no browser storage introduced"
], ],
"verification": { "verification": {
"foundation_and_actual_payables_schema": {"tests": 45, "assertions": 159, "result": "passed"}, "foundation_and_actual_payables_schema": {
"initial_module_regression_sqlite": {"tests": 87, "assertions": 1466, "result": "passed"}, "tests": 46,
"import_expense_regression_sqlite": {"tests": 78, "passed": 39, "skipped_optional_runtime": 39, "assertions": 395}, "assertions": 164,
"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"}, "result": "passed"
"frozen_orders_after_print_fix": {"tests": 13, "assertions": 497, "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": { "standalone_postgresql_startup_and_recovery": {
"result": "passed", "result": "passed",
"available_modules": 21, "available_modules": 24,
"environment": "standalone-qa; outside testing/payable-testing", "environment": "standalone-qa; outside testing/payable-testing",
"own_disposable_database_and_role_names": true, "own_disposable_database_and_role_names": true,
"project_create_replay_archive_history": true, "project_create_replay_archive_history": true,
@@ -32,22 +75,264 @@
"private_audit_authority_not_inherited": true, "private_audit_authority_not_inherited": true,
"financial_and_stock_frames_preserved": 6, "financial_and_stock_frames_preserved": 6,
"immutable_installation_checks": 3, "immutable_installation_checks": 3,
"rejected": ["foreign loaded package", "wrong pin", "missing dependency", "older incomplete package", "restored database with old binding"], "rejected": [
"foreign loaded package",
"wrong pin",
"missing dependency",
"older incomplete package",
"restored database with old binding",
"wrong preparation pin before package loading"
],
"restored_originals_and_relations": "14 table frames verified before new synthetic operations", "restored_originals_and_relations": "14 table frames verified before new synthetic operations",
"explicit_new_binding_preserves_old_receipt": true, "explicit_new_binding_preserves_old_receipt": true,
"original_and_restored_databases_roles_removed": true "original_and_restored_databases_roles_removed": true,
"cli": "preview, wrong destination refusal, atomic prepare, repeated prepare without new writes, explicit recovery rebind",
"unverified_ledger_host_checks": 2,
"note": "Latest extracted 106ab6bd archive passed startup/recovery and invalid composition refusals, after host financial preparation changes"
}, },
"static_analysis": "focused PHPStan and Pint passed", "static_analysis": "Full PHPStan passed; focused Pint passed",
"counts_overlap_do_not_sum": true "counts_overlap_do_not_sum": true,
"standalone_business_postgresql": {
"tests": 10,
"assertions": 209,
"result": "passed",
"cases": [
"explicit line accounts and replay",
"revised budget cycle without rewriting history",
"native expiry returns same request and preserves prior decisions before fresh submission",
"HTTP financial reads, write denial and disabled module denial",
"one balanced independently reviewed journal with configured accounts and immediate PostgreSQL constraint validation",
"40 MZN partial payment with 15+25 category attribution and preserved reversal history",
"one 70 MZN payment across two invoices with 30+40 documentary portions and no duplicate count",
"Explicit configured correction rules; incorrect inverse mapping refused without proposals",
"Injected interruption after first correction journal rolls back the pair; retry applies exactly once",
"Original source journal retained and unchanged principal; independent period review and idempotent closure",
"Ordinary documentary payment references accepted by host contract while legacy SIM contract still rejects them; QA source remains marked synthetic",
"Administrator-only explicit financial access, stale basis refusal, idempotence and revocation after role removal",
"Own chart unique codes, non-overlapping periods and rule versioning; no journals/payments/stock from configuration; real configuration page DTO",
"Configuration HTTP foreign target and identity contract refusals; unknown grants preserved; stale Inertia preparation has inline errors",
"Server shared menu capabilities distinguish no grant, explicit reader, administrator setup and disabled module; full financial cycle consumes company setup writer"
],
"runtime_manifest_sha256": "106ab6bd9d0e4cb9721ba02200dd4207100d7c4845653f920faa866dcbbcc07b"
},
"audit_and_expense_regression_sqlite": {
"tests": 19,
"assertions": 653,
"result": "passed"
},
"expense_frontend": {
"files": 1,
"tests": 4,
"result": "passed",
"types": "passed"
},
"installed_runtime_integrity": {
"files": 18,
"result": "passed",
"sgf_folder_dependency": false
},
"private_audit_postgresql": {
"tests": 19,
"assertions": 584,
"result": "passed",
"scope": "Own company/unit; common settlement outbox; bank reference omission"
},
"expense_and_purchase_frontend": {
"files": 2,
"tests": 17,
"result": "passed",
"types": "passed"
},
"frontend_private_build": {
"root": "storage/framework/testing/sgc-standalone-finance-help-qa-20261129",
"state": "passed",
"modules": 2482,
"manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b"
},
"finance_configuration_frontend": {
"tests": 3,
"result": "passed",
"types": "passed",
"lint": "passed",
"format": "passed"
},
"frontend_complete_regression": {
"tests": 473,
"files": 93,
"result": "passed",
"types": "passed"
},
"finance_configuration_native": {
"build_manifest_sha256": "d9787e59a8eeb53a1b92a3ecfd862720966751098d1b8165920a5b0c134cb35d",
"runtime_manifest_sha256": "c6e458cb9d8b5eb6db9e5729706b1d32cd12291dd4a733e3ab893e95cd33252f",
"environment": "own loopback standalone-qa installation; extracted ZIP",
"account_created": "QA-FIN-320; entirely synthetic",
"form_cleared_after_success": true,
"reload_preserves_original": true,
"administration_menu_entry_observed": true,
"protected_financial_stock_frames": 8,
"no_initial_financial_grants": true,
"original_and_restored_database_roles_removed": true,
"own_browser_tab_closed": true,
"original_browser_tab_preserved": true,
"limitation": "Desktop account/menu delta only; help correction subsequently covered by the full frontend suite, not re-observed in this build"
},
"native_cancellation_manual_followup": {
"result": "passed",
"owner_response": "ja feito",
"visible_approved_status": true,
"protected_frames_preserved": 15,
"original_order_preserved": true,
"one_request_one_decision": true,
"synthetic_only": true,
"database_role_removed": true,
"reference": "product-review-20261122.json#native_cancellation_manual_review_pending_20261129"
},
"standalone_configuration_concurrency": {
"result": "passed",
"runtime_manifest_sha256": "106ab6bd9d0e4cb9721ba02200dd4207100d7c4845653f920faa866dcbbcc07b",
"actual_independent_php_processes": 2,
"rounds": 2,
"same_operation": "one saved, one replayed",
"different_operations_same_basis": "one saved, one stale refusal",
"per_round": "one own account, command, common event and native audit",
"protected_financial_stock_frames": 8,
"no_automatic_grants": true,
"original_and_restored_database_roles_removed": true
},
"host_financial_preparation_scripts": {
"tests": 10,
"result": "passed from the verified extracted 106ab6bd ZIP",
"cases": [
"clean/edit/revert departure",
"successful one-form command preserves the other draft",
"network failure retains values and exact command identity",
"pending submit does not start second request",
"legacy mode retains refresh behaviour"
],
"does_not_imply_native_visual_acceptance": true
},
"canonical_component_upgrade_postgresql": {
"result": "passed",
"tests": 3,
"assertions": 169,
"command": "node scripts/requisition-ledger-qa-check.mjs --standalone-upgrade-only",
"cli_preview_apply_replay": true,
"original_columns_preserved": true,
"synthetic_invoice_minor": 6000,
"confirmed_payment_minor": 4000,
"remaining_balance_minor": 2000,
"currency": "MZN",
"partial_or_modified_components_refused": true,
"mid_upgrade_failure_rolled_back": true,
"isolated_database_and_role_removed": true,
"pilot_writes": false,
"metadata_inventory": "standalone-pilot-schema-inventory.json"
},
"native_finance_desktop_20261129": {
"result": "observed",
"runtime_manifest": "106ab6bd9d0e4cb9721ba02200dd4207100d7c4845653f920faa866dcbbcc07b",
"build_manifest": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
"observed": [
"Own disposable QA administrator explicitly saved synthetic financial identity and selected rights",
"Finan?as menu displayed payment and ledger destinations",
"Ledger workspace loaded with empty own configured periods and sources",
"Trial balance displayed inclusive dates, zero accounts and explicit no-postings message"
],
"protected_frames_preserved": 8,
"isolated_original_and_restored_resources_removed": true,
"owned_qa_tab_closed": true,
"original_public_tab_preserved": true,
"limits": [
"Desktop only",
"No native financial posting performed",
"Dirty-form guard not exercised natively in this pass"
]
},
"native_finance_preparation_guard_20261129": {
"runtime_manifest": "106ab6bd9d0e4cb9721ba02200dd4207100d7c4845653f920faa866dcbbcc07b",
"edited_reason_triggered_native_beforeunload": true,
"escape_cancelled_navigation_and_preserved_exact_text": true,
"cleared_reason_allowed_report_navigation_without_warning": true,
"protected_frames_preserved": 8,
"original_and_restored_resources_removed": true,
"qa_tab_closed_original_preserved": true,
"limits": [
"Success retaining another preparation remains verified by executable script tests only"
]
},
"native_report_print_review_20261129": {
"before_change": "Native preview loaded and exposed excessive spacing and interactive search controls across two sheets; cancelled without printing",
"change": "Compact print style hides controls and navigation, retains date interval, page count, row count, full-filter totals distinction and basis; narrower screen spacing and contained tables",
"candidate_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"new_native_review": "Verified after window state changed: one sheet, interval and page context, readable totals and basis; no search controls. Cancelled without physical printing.",
"startup_recovery_and_concurrency": "passed on new candidate",
"protected_frames": 8,
"temporary_resources_removed": true,
"physical_printing": false,
"mobile_review": "390x526 at 100 percent: report title, date filters, totals and empty state fit; table horizontal movement remains within its region. Own financial configuration links wrap, account form uses one column, anchor lands below the header. Visible mobile finance link opens ledger by full-page navigation.",
"input_diagnostic": "An initial AX click on an offscreen mobile link reached the footer home link. Session was preserved; scrolling the menu and clicking the visible ledger link confirmed the correct destination. No product defect inferred.",
"owned_tools_tab_closed_original_dashboard_preserved": true
},
"standalone_business_latest": {
"tests": 10,
"assertions": 218,
"result": "passed",
"runtime_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"includes_applied_journal_trial_balance_and_account_ledger_print_context": true,
"owned_database_role_removed": true
},
"private_pilot_restored_copy": {
"authorization": "compras-standalone-pilot-recovery-authorization.json",
"proof": "compras-standalone-pilot-recovery.json",
"result": "passed",
"source_tables_restored_identically": 119,
"original_business_tables_preserved": 118,
"historical_migrations_preserved": true,
"selected_additive_migrations": 5,
"available_modules": 24,
"one_receipt_and_safe_replay": true,
"source_writes": false,
"temporary_resources_removed": true
},
"pilot_installation": {
"authorization": "compras-standalone-pilot-installation-authorization.json",
"proof": "compras-standalone-pilot-installation.json",
"read_only_check": "compras-standalone-pilot-installation-check.json",
"result": "passed",
"original_business_tables_preserved": 118,
"selected_migrations": 5,
"one_receipt_safe_replay": true,
"active_settings_env_and_asset_manifest_preserved": true,
"temporary_resources_removed": true,
"http": {
"/avaliar": 200,
"/login": 302
},
"new_capability_activation": false
},
"pilot_activation_preflight": {
"reference": "compras-standalone-pilot-activation-preflight.json",
"database_enforced_read_only": true,
"capabilities_started": 24,
"frontend_files_verified": 185,
"active_changes": false,
"activation_authorized": false
}
}, },
"remaining": [ "remaining": [
"Complete standalone business regressions and remaining financial composition paths", "Remaining native visual/print journeys and whole application acceptance; final C2 decision and conservation already verified",
"Distributable installation procedure", "New capability activation in the pilot requires its own concrete authorization; schema/runtime installation is now authorized, executed and verified",
"Remaining native visual/print journeys in the existing matrix; C2 final confirmation remains unconfirmed" "Production publication/installation not authorized"
], ],
"frozen_manifests_preserved": ["182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df", "fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a"], "frozen_manifests_preserved": [
"pilot_or_production_installation": false, "182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df",
"fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a"
],
"pilot_or_production_installation": true,
"pilot_or_production_activation": false, "pilot_or_production_activation": false,
"sgf_operational_changes": false, "sgf_operational_changes": false,
"application_complete": false "application_complete": false,
"pilot_installation": true,
"production_installation": false
} }
@@ -0,0 +1,11 @@
{
"date": "2026-11-29",
"state": "approved",
"decision": "aautorizo",
"proposal": "compras-standalone-pilot-activation-proposal.json",
"proposal_sha256": "cefcc1bcde848e13831404c114aec98e1a167a1ca3614e19e38a60761bdb1709",
"scope": "pilot_24_module_activation_and_shared_frontend_assets",
"new_grants_or_users": false,
"new_business_operations": false,
"public_domain_runtime_activation": false
}
@@ -0,0 +1,11 @@
{
"date": "2026-11-29T13:58:13+00:00",
"state": "passed",
"database_enforced_read_only": true,
"all_24_capabilities_start_with_pinned_installed_packages": true,
"source_instance_preserved": true,
"frontend_assets_verified": 185,
"active_settings_changed": false,
"assets_published": false,
"new_grants_or_business_commands": false
}
@@ -0,0 +1,291 @@
{
"date": "2026-11-29",
"state": "prepared_not_authorized_or_executed",
"scope": "pilot_24_module_activation_and_shared_frontend_assets",
"decision": "Autorizar activar as 24 capacidades já instaladas no piloto e publicar a compilação de interface conferida. Não conceder competências, configurar políticas empresariais ou executar operações de negócio.",
"important_shared_frontend_impact": "O manifesto public/build é partilhado com o domínio público da aplicação. A nova compilação também será entregue nesse domínio, mantendo os acessos e flags próprios do respectivo ambiente. Não activar aí o runtime nem novas capacidades. Esta publicação da interface requer autorização expressa; não está incluída na autorização de instalação anterior.",
"origin_of_required_decision": "A autorização anterior exclui expressamente activação, configuração activa e substituição de assets; AGENTS.md secção 6.",
"pilot_data_classification": "Conservar o âmbito de ensaio do piloto para novas operações, declaradas sintéticas. Não reescrever a classificação, snapshots ou história dos documentos anteriores.",
"procedure": [
"Conferir novamente o recibo, a identidade da base, o schema, o runtime e os hashes dos ficheiros/configuração indicados; recusar deriva.",
"Preservar configuração e manifesto anteriores em pasta privada. Conferir os 185 assets da candidata; acrescentar apenas ficheiros novos ou já idênticos, sem sobrescrever chunks divergentes. Trocar o manifesto apenas após a conferência integral.",
"Alterar apenas as chaves proposed_runtime_settings na configuração privada do piloto, preservando a origem financeira PAYABLE_SOURCE_INSTANCE e todas as demais chaves. Não alterar .env ou configuração do domínio público.",
"Conferir arranque, menus por perfil, recusas de acesso, ausência de concessões automáticas e conservação dos dados; sem novas operações empresariais."
],
"recovery": "Se o arranque/compatibilidade falhar, repor apenas as chaves de configuração e o manifesto anteriores a partir das cópias privadas, após conferir que não houve edição concorrente. Manter o schema aditivo e o histórico; não efectuar downgrade ou sobrescrever a base. Conservar os chunks anteriores para o restauro do manifesto.",
"excluded": [
"Activar o runtime ou novas capacidades no domínio público/produção",
"Conceder acessos, criar pessoas, contas, regras, políticas fiscais ou parâmetros empresariais",
"MFA, geografia operacional G3, envio SGF, fiscalidade/bancos/JUE e formalização de Pessoas",
"Novas migrações, operações empresariais ou alterações operacionais ao SGF"
],
"target": "http://127.0.0.1:8005",
"installation_proof": "compras-standalone-pilot-installation.json",
"installation_id": "0602a856-0413-480f-9ef3-1a1f3238bb90",
"runtime_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"runtime_directory": "C:/laragon/data/compras/runtime/80483320a54af6f1",
"proposed_runtime_settings": {
"COMPRAS_RUNTIME_ENABLED": "true",
"COMPRAS_RUNTIME_PREPARE_ONLY": "false",
"COMPRAS_RUNTIME_ROOT": "C:/laragon/data/compras/runtime/80483320a54af6f1",
"COMPRAS_RUNTIME_SHA256": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"COMPRAS_RUNTIME_INSTALLATION_ID": "0602a856-0413-480f-9ef3-1a1f3238bb90",
"COMPRAS_RUNTIME_SYNTHETIC_ONLY": "true",
"SGC_BUDGET_DISTRIBUTIONS_ENABLED": "false",
"SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED": "false",
"COMMON_FINANCE_BUNDLE_ROOT": "(null)",
"COMMON_FINANCE_BUNDLE_SHA256": "(null)",
"COMMON_PAYABLES_PATH": "C:/laragon/data/compras/runtime/80483320a54af6f1/payables",
"COMMON_BUDGET_PATH": "C:/laragon/data/compras/runtime/80483320a54af6f1/budget-control",
"COMMON_PURCHASING_PATH": "C:/laragon/data/compras/runtime/80483320a54af6f1/purchasing",
"COMPRAS_SUPPLIER_PAYABLES_ENABLED": "true",
"COMPRAS_GENERAL_LEDGER_ENABLED": "true",
"COMPRAS_GENERAL_LEDGER_CYCLE_ENABLED": "true",
"COMPRAS_SUPPLIER_SETTLEMENTS_ENABLED": "true",
"COMPRAS_FINANCE_CONFIGURATION_ENABLED": "true",
"COMPRAS_BUDGET_DISTRIBUTIONS_ENABLED": "true",
"COMPRAS_CAPITAL_REGISTER_ENABLED": "true",
"COMPRAS_OPERATIONAL_ORDERS_ENABLED": "true",
"COMPRAS_REQUISITION_ACCOUNTS_ENABLED": "true",
"COMPRAS_REQUISITION_EXPIRY_ENABLED": "true",
"COMPRAS_URGENT_REVIEWS_ENABLED": "true",
"COMPRAS_URGENT_QUOTATIONS_ENABLED": "true",
"COMPRAS_CONFLICT_RELEASES_ENABLED": "true",
"COMPRAS_PRIVATE_AUDIT_ENABLED": "true",
"COMPRAS_EXPENSE_ALLOCATIONS_ENABLED": "true",
"COMPRAS_AGREEMENT_LIMITS_ENABLED": "true",
"COMPRAS_ORDER_PARTS_ENABLED": "true",
"COMPRAS_IMPORT_TARIFFS_ENABLED": "true",
"COMPRAS_IMPORT_LEGAL_ENABLED": "true",
"COMPRAS_IMPORT_DOSSIER_ENABLED": "true",
"COMPRAS_IMPORT_BANK_SUPPORT_ENABLED": "true",
"COMPRAS_IMPORT_READINESS_ENABLED": "true",
"COMPRAS_IMPORT_ESTIMATES_ENABLED": "true",
"COMPRAS_IMPORT_LANDED_COSTS_ENABLED": "true"
},
"feature_names": [
"supplier-payables",
"general-ledger",
"general-ledger-cycle",
"supplier-settlements",
"finance-configuration",
"budget-distributions",
"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"
],
"preserve_source_instance": true,
"new_grants_or_users": false,
"new_business_configuration_or_operations": false,
"new_migrations": false,
"frontend": {
"candidate_root": "storage/framework/testing/sgc-standalone-finance-help-qa-20261129",
"manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
"previous_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
"files": {
"assets/Combination-Cf-uZSDM.js": "cb6de0edf2a5bc431766866135d9c8868a5671cd0bcc7894cfd8d425db1ea41d",
"assets/administrative-location-q1YBJn1l.js": "6b6963bba9f363dde629dc9ae8c4275d530cb89da9d55f67feec38be551db0af",
"assets/agreement-order-bindings-CsGilIRe.js": "fb13dc88d5539f655970551007b734735fcd648d3a43086ac0f9ac3f0170dfb6",
"assets/ai-preparation-preview-B5B4Jl8K.js": "8b902935251b5f484f4abeef6dc46e0f4f6475ef58b2ded60c95bf9a4cd99e8b",
"assets/arrow-right-jQM5Ljhm.js": "460657b89c0a22dd8c648c59408ab9b5d89cda0a2f77fdb5aafb5d4cd81ee047",
"assets/budget-distribution-fields-B0szbRQd.js": "6e6798536ce8cf9b483606ea78c9e7e7fd10111637eb61ee933edbb9e5ed04d6",
"assets/button-CSyysFhi.js": "a0c7c2d62ff1c139a6b5e6ff2e4c7cc778682337a935a3eee0e2df5ac36607b9",
"assets/candidate-availability-BBYAjwDY.js": "848c1b093b9016d4dbbc7795f44c281eb3776bfebf82b2a84ca943c70f5df1aa",
"assets/candidate-documents-DzSJVuya.js": "3f5131f76ab32a1477614e2318e09a5fbe736f5b6fc75fe306fdba5802f28482",
"assets/check-B0y1oDcN.js": "2b0f7b1e72a08a1106cae81a5910d88a308d1bc92c729def81b0c38b743c7c59",
"assets/clock-3-Cy_zSYUr.js": "b8bf146f2a287cd2bf356687ab0dfdcb0bef6f0213bfda494985dd98d97d20a0",
"assets/comparison-policy-summary-C80JsjfA.js": "13b64488a4166adec1678d172588b46cf6834382c575b87054c49ba587b69fa8",
"assets/conflict-BelUpYxR.js": "19efa315d126114e8d34439393364583a3fc1b735b3afc41f401c3da8aaf33b4",
"assets/correction-source-search-BlskK11K.js": "6ad55ada5e896411e415d9fa99f34f0d388cc8f54aa88fe05625915253eddf7a",
"assets/createLucideIcon-Bl2ij0Zm.js": "88026a98f925baf2a85f5c6091f3dce5d35689ec432417ba87ac3fba450aa326",
"assets/dist-Bm7wFECT.js": "ec7a8f48099bdb15bd706858c566dff3c664ea77420b2973463f9482c5c66aa0",
"assets/dist-Cxy2kTRX.js": "7884e24de234f6d592ec16f228c0eaba69ee5adf28fcbedb0d59383d184958c8",
"assets/dist-DSfJglKD.js": "7e5239388df8e9e9251bc5d432701c3a1798b8940371f88e42683e6426f0c6f2",
"assets/download-d-ik75sA.js": "ac23d0b10fe748b8664965a4ebb479336cbc75e4d08e570577e5f70519bfde1c",
"assets/eye-BcFYyvf-.js": "eccd97f0bfeab1e54e9d1abdcd96184794449a6b6277d096598489f52f61e9cf",
"assets/file-text-BMumQ0Wt.js": "9af4fdf5c0527694f24719af17256ac1ebb7061ddd738e5135fdd411f5b3a3ac",
"assets/fonts-C9MNnjVw.css": "3846a9bb60bfad92960eadcccaf0b4e129d74b11d48791506c8d1a827a385cc8",
"assets/import-estimate-money-C8In-mMc.js": "a55799be92061737217e27d9d22baf042cd085b35da5c49f64ef8abb819205a5",
"assets/import-tariff-summary-DD1KFUFU.js": "986f9e557a2a243338df9085965d9d61996d128a844fc88028e48237c5df9d4d",
"assets/input-error-B1DjHZT7.js": "00286fd9e30543b59027b37606d63c96944efdf4f58339aba7afd0cd08629ace",
"assets/instrument-sans-400-normal-D1W7dsQl.woff": "797bd3eaa70edbd4757650ab44dad75fbfbfdf18bacedb4b71022c04621d30ad",
"assets/instrument-sans-400-normal-DRC__1Mx.woff2": "9a91efaa3599a6ef01b2f49e9ec670e3a2f39baeef09c73198f1052cf3bb0850",
"assets/instrument-sans-500-normal-Dk9ku72i.woff2": "9d3547da16d950d12a677c772a3ff9b69846e60e7dcd1b5efd540993f7286532",
"assets/instrument-sans-500-normal-Z6ESRlEs.woff": "bd6a8dc8b0dc0cced0c32d3eda93f0e0e82c58ddefea8b53b3307b0c48da3089",
"assets/instrument-sans-600-normal-B7fBEWYG.woff2": "efb770916eda95a0e31d80cccde9651d4e8617010b21220e9f227c4820d675da",
"assets/instrument-sans-600-normal-B9e8oLYv.woff": "9b4ce1f2b26be7cb087fd87d6f99a202136292ec820af75bd38ab9e53895cf28",
"assets/inventory-B5h3Ukug.js": "4e5464e66e4f4436f82f06de10587dbde46c3b7c92d964b09eaa31e6d9f4fb2e",
"assets/inventory-BF2HrsoH.js": "fa3e4a56bae767f93e7f7d0202c4efecc8d08583c0ca6761db8560acda64ddc9",
"assets/inventory-correction-filters-K-RY6cU2.js": "4d7d4b58fd6fcccc19f29e6adf0bd972ccece878a0e6a2051f78fe65505c695e",
"assets/inventory-event-actions-B8W-9A-a.js": "08c93354ccd5c6cb1acec75dd1378cf8f813b10564bda05bc5af53ec87b13285",
"assets/jsx-runtime-Cjjuc_0N.js": "239501f6701a312b0fbef99c9067ea0d62f11aeeb3a8b388ec4c7528b0493500",
"assets/label-Dn4U5SHB.js": "d273f9faf668fc6fc998709fa86dbb3d424a23271725cc48a9b88a8b2d8e399c",
"assets/loader-circle-YS2_4W2r.js": "4648de3680be9df8d38d808bb954b6cee541cf3b376321926a10c3edddb96345",
"assets/order-document-links-CY7gGohw.js": "a94c6e359ec9ab4cb143177522e2822c9aaacc462f636ab5fccfe09c45cdc43c",
"assets/order-parts-CW5t2gcS.js": "4bf1d746291eded17bfeceaedcfbab1f4daf5fe0f384739196110a8f98b5db9b",
"assets/package-check--ZYjz2oi.js": "ce6074fe092e03473ff914cfe088a47acd57852fe4faef54f239fd04ccd6ab83",
"assets/password-DSVT9zkL.js": "e9f8a7ef9b436a3e046d49f9ab56bdb4ca736bc98f69fc89efe36ec0a9bd08aa",
"assets/password-input-CSxNuD3_.js": "f117f12fe3ac3767485754a3650ffedcc2a6c6eebcc6a6eeb88a312e89e92b7b",
"assets/pencil--NTa5x5n.js": "ffc5e9c22501ed8196d21f31e016d351f91796821392ec9942716d7a70b9c022",
"assets/people-hiring-0ebERuf_.js": "443ff16989484ecbb7576eb060a5339fccd2fc720015d72a2af828e91d12461c",
"assets/printer-D0Qc0KdJ.js": "6a29144df3944867ae389bb8e8194205099314ffa04c41f0fb054226f27b3566",
"assets/procurement-8XN9qCAY.js": "e0b77fdaa81057b59fd44d459d3e234a3edb98ebcf1be15e85360c55734d56b8",
"assets/procurement-payable-insights-DfwHG-cE.js": "55a6bfd4d4429d80b6c54ac8a2299e1aa7a0b11ea82183a6d2edeb73c8aa89f6",
"assets/quotation-exchange-panel-Cy3DHM6W.js": "0e3d3b0e557822946420d7ba54900753b03100856a6a2077efbcca62273c3fd9",
"assets/receipt-conversion-C5-TjG0i.js": "5abdc73cb84a05fc1d4f9a7a1072d4d56bad3a449487cacb819cfba41b9d9f75",
"assets/requisition-category-fields-DKZso-VO.js": "3ccb225b1afb3080e80165f14e40624b077020d818771b29583b70d3a839ef30",
"assets/requisition-history-Dsahm4kA.js": "cd35dcf01ae95f608899009f3795ba78255ef294566e97ca24b70204ff2fa033",
"assets/rolldown-runtime-WkwZ5CU-.js": "2629f2ad3cb75a57d98de697127f5af7d777ef572bbcdfa6e3ce8f438cd4527e",
"assets/spinner-CpJAdIKb.js": "9c8f8fb08c631cae61ecdf41cd766fbc3e777fd184fa707b6351c3d460eef059",
"assets/supplier-DbZ754P4.js": "5617827f9283736a34edb62fe4ea4e6c8df48961c617dd66f416fb054dd92ab4",
"assets/supplier-evaluation-fields-CeoZG0uI.js": "fcaf27e8e2bac729bb6038ab8d4d77b913114f072f88b51f1097184d705cceb7",
"assets/supply-pagination-CnzjlbVc.js": "8537e2e4e48a836f41a2b2176f635ced2b1c62734485d1109bc4469168a1cb28",
"assets/territorial-filter-De2XLPLa.js": "fc12d319adb0cfe9cc44e371c1414559e39c8b42ecefebaca642e8ef8eeb2c3e",
"assets/text-link-CydDNIng.js": "9ddf76c1a4d33cb5d25315e38395f2893250091a23c156adc582bbb2bcad85b9",
"assets/use-inventory-preparation-identity-DcCfUMXu.js": "43e5cb96c4ef1bd19574442166c972db05be7d25e5f5ba76a8a0086646eaa0f8",
"assets/use-preparation-dirty-MDWP6eOW.js": "e4eff3b06a4127a38321af9cd542069423a99bdc14649d12acac4a0330070611",
"assets/use-procurement-preparation-identity-NZ7gcqOB.js": "09315e79db9d28ab8e584c1e6978ee3da38a849f1be28c0499301e1b3f98d115",
"assets/utils-DJPu_GY6.js": "7b162681baff9e9a115823fd6070404fcaddf53d058b311edbe98be7f2662ef4",
"assets/wayfinder-Dp7PqxvV.js": "3d4c90228fda731e37f541f3087fdf5387d9d59433e35b267b64a97196f70781",
"assets/app-gFUcHXMG.css": "1e5f6e98f7165bf48430bde976c4c7839ced8e5c5db30ab897108149770a020f",
"assets/app-BRwRZlcU.js": "740764296a25f44aa94fd86b479ed0cb3b81bef06a761f6aff81577df54cfa78",
"assets/metadata-DNESZTTn.js": "67dc1a25793e11f1192c67725c0dee4b1b2d2640a43b89d95c71263e3790b165",
"assets/private-mRjYV8Eo.js": "661f54187f8c129e833bc62205b811b3cac788aae0bf43bce841bbf7faa8f8be",
"assets/confirm-password-BQfnWvvZ.js": "8fc566ec082b1c7ff725743865357c17614c209e6ef491b02c38bda288143a50",
"assets/forgot-password-C5VEt_1O.js": "84f8e1b90922a36b7f17860c50009cebc142483afa8ab7c1d5673a8539c098bf",
"assets/login-DAfDfzpC.js": "3eaa5b674de183641916a4d2c682f7c8ceffeef668e985054ae776da33a32510",
"assets/register-DiO46XTg.js": "216f207333555ce56e0a5e88689bad68c19a6e029094ca4a9a6c91b7744d27a4",
"assets/reset-password-D5jxdIKB.js": "1dfd528b22f0e85853b48081d1a7722f10c9c9c838d091ae9bd3eabd6870fef9",
"assets/two-factor-challenge-B0m3AXbn.js": "94fb5d0c3d8ade83121f5676b78013b0d203262c2545b7cc918585498e1f214a",
"assets/budgets-CRhm1x9a.js": "8a47db0dbba77e1238654a9d5ce69d662599f78921c28fe01e8a4fa435aded2e",
"assets/access-DX0p-ALd.js": "47a2476846ee63ce459197c02878f8ae12b688a6e1b628f1be59efedf66ceed9",
"assets/entry-DhIghaCT.js": "eab7d47dc01e43fcbd14adb2fb8194522392b18f05aba13850b63aa8fd81f77b",
"assets/opportunity-Cfl4ItuR.js": "ed2b4cc034627b211c4672e5b69e807e86148099044835b46ba79b7234ebdb46",
"assets/profile-CUfa_SGH.js": "24c858e016ac8c607bc0c87e5bc9fad09830afd31b956780f69616db80b9181d",
"assets/receipt-CX6COlya.js": "a20578c41e007f6000ff25baf9e53e7c39312d6541432b98edaa66d2355461d8",
"assets/candidate-portal-rcW6aAtc.js": "54b069ded082be6743c4a667a8f09adeb5b2eb10d315eda4fae139defc250739",
"assets/finance-DVUt4zPS.js": "1596b2fd3128b555b1d6e104d1b051ab410ee10af8904dbeae056b8cc599be73",
"assets/geography-review-inSJC1uH.js": "bb3344fc24c43623c16824dfc04bf61b38d514ea7772aab9440a9e3f0ed0cd96",
"assets/company-uuDr3Lkh.js": "835c39bb5d6d4ad9bd0a98e3201a3d4803ea8d4f6c89606995f24176577f16a9",
"assets/parameters-Bn2f0Lwp.js": "39ce8d90b87da592fde07810a2daaabf0e0439c75fd360f077045e32dc1ae8a7",
"assets/setup-Cf1u8DlQ.js": "1fc837a2077768a9d132ce5e54a5ea5a9566fd1a6eedf0d11e2ae8b36b073a4f",
"assets/submission-forms-Brn8SVMi.js": "d93f2f3bc362b662190097a1911ed7294ee750053956aba37ffed6f13615a1c1",
"assets/conflicts-DULjQj60.js": "b4ced9106803dcb5d94ba7396f42d5b676182da6ef8c839a0fedce58ea9014f7",
"assets/show-CXUxrvsc.js": "ee5f42d70c94e53b8a1b2348dbc2c193e4e082871c023ccf98681477ea0bd7c4",
"assets/dashboard-Bmch_aF3.js": "ce62a3b21812d4877dd96609eeb3f6c890f438aa35a129da59c343004a374bd0",
"assets/capital-register-3rPxBO08.js": "605667112b8f553cfaab58dbd68198fb797fbbb7dacf45a89253fa7e6fa6447b",
"assets/equipment-D3gDCksW.js": "8311c9df7935248582612877b1faa15b2e006868fbd5239e0f644369491968a1",
"assets/show-BDM1VNm0.js": "e53a5b3172ab78908cced37331aee4764788470960252618e107a8289d02c169",
"assets/home-DMxsrrQu.js": "474dc7396c1c78abb261af1b3586c35897c7d3e82ad35fb56715cc1b6f0bdaa6",
"assets/investment-4rM40ZqR.js": "e090786efc535abf2e06a4076efa433082ba99f46bfce0304333852ce1f8c3a6",
"assets/invoices-xVbn64mb.js": "f97711eb0f466c7cec3e1ae51ddc852cfba1e0d08427e0251e210645d920d0e7",
"assets/approval-timeouts-gpIkUgKf.js": "2f53712d7f5df65ca1d51def1f8074f0ae0be0fc5e16912742803c7137334318",
"assets/urgent-review-policy-saBWEW4K.js": "0169a815e2866d0bf9ab0fe47edfa32ea1f2c9824808fae73b9f83e4d144f14a",
"assets/expense-allocation-dy8GmT6Z.js": "023a3d30e53a02cb14ca01a7af5d33f4f831ef49a64ef9e61c3227de937a8169",
"assets/payments-DYJyIzFd.js": "79dc922c04b7329d7b2207e8e08d725b72471c0412541bb09b2d9b59d02cc1d5",
"assets/access-C50xmS7f.js": "9634b1f3a97ea32ef4bf7931a83854f5040cfce6ff87f02311c66db334ab4426",
"assets/people-BFLmm0Bb.js": "3a7d10a58f105aabd91d4fba36471e466c3c4486ffe2770cf6a668042ae0f16a",
"assets/registry-Cii3MIJf.js": "305d5da40fdcc22c13395cd874b5d85ec09003d2cb3a4ddc15495f4c6d2748a5",
"assets/reports-SqRwBlij.js": "80119f7c66eaa3bf4fb1811839c1166b2eed81ad7df29ab5c0dfedfd8784792b",
"assets/show-C2qF15oG.js": "d27b328d33f171277e9bf349b0f90a2817a3ade65a51b755b27b0b1ab3ef3d49",
"assets/submissions-8aMZoWGn.js": "01772b8c3ce56609269ed55f9fc0715b3cb5f5fb12e721dd7cc0214eb192dc95",
"assets/planning-BPSSc6GP.js": "af4081de94d339147b11ce4cc953b86b7c696c866c11bf6a12b35c126df3f735",
"assets/admission-ivkTJEz-.js": "37eb8f30383e8c07b91d58e72d470654b72bb251da8c8e5ffb839753d67c3d8f",
"assets/preview-DV4Cduza.js": "47efa257617f1da79297ca63f5c960e64c71400e15036d723170434120d7b9b0",
"assets/inventory-demo-BQHwsz5E.js": "9d75dbc858a3773a5eab3ba3f968670541a18d53396957619bf6e347f404f362",
"assets/principal-B8ISfUJG.js": "a15a047299a131e419afe09904412a695d7b67dae7eef98a4d2c1151afeacb0b",
"assets/qualification-Dakz_jSp.js": "73c910bac82c660967a6e1f5b57f54b03f32fd4532d4c2522d0a4ec6e70d3e10",
"assets/recommendation-CmXhWQb0.js": "bd94e5819d677d31e7a346cef3c38c6edde3d525d912ff3bdbaba91d7bd0ac79",
"assets/purchase-controls-h4XNByZA.js": "0ffb85c63602c5770010b7bae1448489ada9d41ec6bbd08013b19e3b6716a7de",
"assets/orders-D1xyxniL.js": "90ace9693b47ae4124b4ee640e8236b622bc6968bbfd377a6d689a24a92c7a8f",
"assets/admission-policy-Bxl9q7Ze.js": "804c979b05198f62edc3290f6e16b0dd0bf74aea5abcadf736ccf13aaca92327",
"assets/admission-BNHy6k1Q.js": "0701f16cc80fa99f57b1401383d2d5656ca44b7058365bb87b47e96a9d1acfd8",
"assets/award-bocVxC5W.js": "31accaef4b58573549bedaa6bf21e04318a3267637571e21600144b44b32f38d",
"assets/distribution-amendment-DysAGRsZ.js": "fbba801ba75693729b95226074051a27b45b7a1c097900fa0fb3ece03d9a269a",
"assets/purchases-D8K6y_yO.js": "6abef5a6023a841eae1edc18ab0567e261a5d000207cf5271836f146eb3db9da",
"assets/opening-Bv3scXa4.js": "27f49fa9a09b7e43a281fde77efedc57f294793cbb40cc49f7e30bc878e0b8e3",
"assets/order-parts-amendment-T2lDSXKh.js": "323540acb12b25242e81e189c75922db0d968fde708c49bdd68715416827a538",
"assets/parts-C10oKRBw.js": "9675e418ead6bf42c4aa2e316c40d20096c2f2a3a4d6440e5e4b5dd4edbedbd1",
"assets/process-Djvt8rha.js": "f52e1c19c2ab9a972a941672d55834752dabc5e97535a6467a52b4b34855bb9a",
"assets/qualification-CIRpe48K.js": "14d05519ff649a79a16850f6986f02ac09f9c2529c2f346b2a6b83c8ad1667b6",
"assets/recommendation-policy-DHa_RO5T.js": "913a0c94fd948a87f90aa54bda9d14e94db8d87447e3f8bb6d54d37d4fc7dfcf",
"assets/recommendation-7jZxHHI2.js": "f309415b27d575f8ed54d586f58fcf0e620c82cafe5a51748fd7f6eb5238b391",
"assets/review-report-DJEzGNwj.js": "12c055ea08c71d67e390c123e4c875856da753665dd859a33856f3d6be93781b",
"assets/show-7RCwnMHY.js": "153c28e30d45e32ecfd811152265a5c6db039ae1906e03e043e82017dcf3e97c",
"assets/quotations-DP49MVx6.js": "d0662d0c91a9f27b4a6ff0a530c363f9888bc9b09fa54dbc7c65f908fe7322d4",
"assets/show-0VhmR9II.js": "93f71542b303548b071f26271bb66d1f8109fee2a9e28b3ec69126006d33453a",
"assets/receipts-BCX0N8MC.js": "ad95665f532e70aa499eb8624799a7542a0655be9efa144bd249dc09d84ddfa6",
"assets/order-2hWRc75B.js": "9c25145cd0765f32c9109b26321f47f3c70cd8bbeae1ec9e9213934d35d13e97",
"assets/show-CBNwrwQj.js": "f762a503e2cfbfc15c5ca589c5b9eeb39038695ab0fdc8f80347ec658f2abbb7",
"assets/procurement-DVyUQgY4.js": "bf24f89fe28db2fe18f352baaad4061db84412828afa9a5bc42da9e7cd15148b",
"assets/supplier-improvements-H_pHn-cg.js": "e8f601462f5dbbb82eebf6c47eccd728077e17b5795adcb832f85a1a6dc5c07f",
"assets/accounts-r4LlW9r8.js": "1c199e2ca96b809a41adc603a407f30f0285247b8e3d425acea605b49be831ed",
"assets/capital-assignments-j69vqlUT.js": "2cde54c863dc7bc8a07cb9aee4f3de0a5aecd0a3595be5d70aaae437e52cc613",
"assets/distributions-Dnozjk5P.js": "ff15954e4b4e5b3bb841a7fc37b9b66dd886ea5a7f66ed91e1edc334e7d7a77b",
"assets/expiry-DH4pava_.js": "1c94dbe747c7d35bc475779ddd4acb7416b8a4714d5621a02ae0763bdd11d9f6",
"assets/form-Dr9FHncJ.js": "35821a0a3e874ae27489dea2d5e407f92bb2be83d3c16a90156c6fff9f4f6550",
"assets/requisitions-B89ydqrJ.js": "d4f4ca2c19f996fdd9ccaff3c1034aee2696afd7f0de4d88a3600b45aa094076",
"assets/operational-orders-BC6e8svZ.js": "414ac55b221dfc957ac8e77586909b6a6e5d31bfd2f44dd37a6a2313ad4432ab",
"assets/show-DAW4Xkgt.js": "9fd82a91d7b25110bc1f25ba3e4828a074803bf226dd9a1bcb7fb6b7b05008c3",
"assets/urgent-review-CR1NjmkK.js": "5ecaf558d81af4261a7c34688898b67610a370cadc03b1dd3e70f2003d8bae65",
"assets/urgent-reviews-BFFw2b7z.js": "d6f02a28141baa66ba122a300967d17c84e576dca9b3df6974a8be6d8a5bd8a5",
"assets/urgent-stock-CGVLVL-u.js": "ac3a0de26754b0e47fddbb0998618422d64a62d6e7407f01f0bfca64ff231bb3",
"assets/procurement-BS7xH9pD.js": "d722d909b48db18bc30b60ede455a4727191d1ab8612f15ca4f4f1572bc8bb7b",
"assets/appearance-DTLkICZ0.js": "dcf74e881903f09c418212245ee70a999dd3ab86fc4c1c68ad9bcd3d70c795da",
"assets/profile-Cc9DSa-j.js": "4e01859f23a4a9690d2ad2d649816995b985de366132a87446df3de27b011594",
"assets/security-DQoiFFcJ.js": "ca3866044dfbda0a1e0cf06902b3a13842f35539e7d8c16bb33170da6a46c733",
"assets/availability-DXUlX6Ah.js": "9dc054ae9af3fcda6269ca149a9056fa1be53531e4aec8764476c7477d59e2d5",
"assets/catalogue-DVR9ftZR.js": "451d2742659a2cf7f0686d9f9e765d8f0a8c3744e4683d6c2f285a1c4d7708e9",
"assets/dispositions-C1oAb9Zn.js": "d0dd5669270b26d2f04c216298ee2ae22a2162b4444d78a5976c48c82db943f2",
"assets/stock-lXsySti4.js": "fc3af4c76c0786bc8b107f14048aacbb719975fe1cfbe92a17ccd0b8ff4594f3",
"assets/lots-DFg5vqya.js": "928ae98ff325557afa7bc286bc5864e78ff7db971b599a4e14dedcc7438ba687",
"assets/operations-B4qhyY85.js": "b140f28368d5c5ae40d61d9e0c81bee0798167225728e549079a13ee457404b1",
"assets/pilot-CS10xOhC.js": "a3aea682593c9bb101544d7f4e0b21b2224fb34269c719bf4f5fd961abd21d25",
"assets/replenishment-CPd5Jus0.js": "bef9632d2b3dce693529c8f8d4d1383907cdd278746c6b058f039a3584a0742e",
"assets/request-DAMxCEAW.js": "e8b86fa82f815d01bb27994d1864e81695ae81bd23430e4e7afdd368f799ea16",
"assets/requests-B511eeSz.js": "dab4fc5048fd0cf99b5e13490a0a6cc5e225ccea65c300066dfdca1bfe4f7c8f",
"assets/returns-BIwxpXom.js": "d4104f823d5cda6ece4a3590a08ecde7ae32ca2b0fbeb2e7f63f36bcb72add56",
"assets/reversals-BP1xMk2u.js": "3ecc0a7e5870d175d2cc5d738116ce1232e9e00f29bdbe7870158e600817813a",
"assets/bank-lC6lGLBX.js": "2bb2906b8d81edf206a0fb7fde8e2496525973ebce71260b986e97a477121c8b",
"assets/edit-CLtNr60H.js": "fb9acf8d87a85a2988d1b521046f71f680919ba0540eb5649e96e81da9545d74",
"assets/evaluation-D6Q_8mDA.js": "2aadc5208bed11b06dc5adfe8ae226c25c07bf49aeaad115cc0105a5e7ab3685",
"assets/evaluations-D-xOv-2P.js": "13e96b44260bf03d7784dc960598a6a7f117d2b2f8065465aae27b2e871c3244",
"assets/suppliers-CKTQMlS_.js": "ca3a61f48bf8089109fcf2215c9adcafd90f67b7c14a470ca3d0bff5311d0a80",
"assets/show-D2l_JDTd.js": "56e2914ad5967717d78931b5d7e1df4cf9a9750a9586ec38bb2d882f017a4729",
"assets/agreement-followup-DKmKswG8.js": "7eb103928d73d1e46e80e3e34f7820db0a76b4090f70948dfe995fe6be728c77",
"assets/coordination-C4CfgzMQ.js": "455e0fdd3f939ee5d8a8e8aebc4bdd9a26f38386a7a336c8ac359da878ce0928",
"assets/history-B4HKgGRn.js": "e14def2d6f09950419bf3c3770319841d8c58d3aaf52e335d5d675a94907a639",
"assets/import-bank-support-BakXSWY2.js": "6f4f1759b498193fd5c8de154d833c5c0c13d7738bd1e4f892866b5139d46cf6",
"assets/import-costs-B8aNNhIA.js": "62caebe9df8cd374802c3785691058d965ca371e11cd5484142ba0ad74a9968c",
"assets/import-dossier-zGo_X6s7.js": "da762e34f0a13b9cd8a72d715b4333f550f9204e3d29d45b6c1c90680d00ffcf",
"assets/import-estimate-Xzmh8niR.js": "00d88681b91ce7a23963b583910993147abc5c9154944ac67f73adb90c8cc0c1",
"assets/import-legal-B1JQHCrs.js": "b4ad6595627afd4c53aa9026037cad019c87223e058d9611da0aeb4c1d4319b3",
"assets/import-readiness-D3ea7cE1.js": "8a98fe5e985f4acfb7cd0b5eae6005622b0b5dfa07dda5bf77fa91a299d16595",
"assets/import-tariffs-BrZctl0c.js": "c25fa35aa7d338d8dd3bc5c4b6c2499364176f168de94f430b9de30b19c8dbe6",
"assets/supply-uD7BTenT.js": "6ae7304176acec13b2a4930723049e52256a72b4b28a84567e75b203901b0736",
"assets/suggestions-FRi50_51.js": "95d82dfbe16a2947f2d9f90ce5c1e163d678c835081fa4c91bdb1abbe1af8b3a",
"assets/welcome-CRjlUHIF.js": "8755772cba7a83237cb6acbae5cfae38d8ee5564f60cc5396529c4e7bff6e1f6",
"assets/work-context-Dv3-1YAs.js": "ebf09eb4c2391814456fd52f928040b64ed028f83ff768893a15505fc3996851",
"assets/notices-DeGfoWRy.js": "bee56aacec93994728d4b5057e3f46c0580818b041011fb5777eee80a4513a07",
"assets/tasks-CYqFoxtM.js": "d560cdac3c41fa7030317e8a4aa80bb3e3576b8fd1c576bf987259e25bc86288"
},
"shared_public_root": true
},
"active_settings_sha256": "9b3f235153404a616b7783ab4cb1f35fc1d47d50b0c5b66cddbe871dff0e7c5b",
"application_complete": false
}
@@ -0,0 +1,22 @@
{
"date": "2026-11-29T13:59:22+00:00",
"state": "passed",
"authorization": "compras-standalone-pilot-activation-authorization.json",
"target": "http:\/\/127.0.0.1:8005",
"backup_directory": "C:\/laragon\/data\/compras\/backups\/activation-20261129-135921-e4e3ef971526",
"runtime_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"frontend_manifest": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
"new_grants_or_users": false,
"business_commands": false,
"capabilities_enabled": 24,
"assets_verified": 185,
"all_database_tables_preserved": 150,
"unrelated_settings_preserved": true,
"source_instance_preserved": true,
"public_env_preserved": true,
"http": {
"\/avaliar": 200,
"\/login": 302
},
"public_domain_runtime_activated": false
}
@@ -0,0 +1,12 @@
{
"date": "2026-11-29",
"state": "approved",
"decision": "autorizo",
"proposal": "compras-standalone-pilot-installation-proposal.json",
"proposal_sha256": "fb2b6311560a26934c55ada8e6fb31b64d41494d6123c315baec238564d8f87a",
"scope": "pilot_schema_and_pinned_runtime_only",
"new_capability_activation": false,
"active_configuration_changes": false,
"asset_changes": false,
"permission_changes": false
}
@@ -0,0 +1,15 @@
{
"date": "2026-11-29T13:52:54+00:00",
"state": "passed",
"read_only_database_transaction": true,
"receipt_and_non_elevated_binding_verified": true,
"wrong_installation_id_refused": true,
"all_24_module_schemas_verified": true,
"runtime_activation_stays_disabled": true,
"http": {
"\/avaliar": 200,
"\/login": 302
},
"business_commands": false,
"permission_changes": false
}
@@ -0,0 +1,43 @@
{
"date": "2026-11-29",
"state": "proposed_not_authorized_or_executed",
"decision": "Autorizar a instalação aditiva do schema e do runtime conferido exclusivamente no piloto Compras de http://127.0.0.1:8005, mantendo a activação actual e sem activar as novas capacidades.",
"source_of_required_authorization": "A autorização da promoção exclui instalação no piloto; a autorização posterior de salvaguarda/ensaio permite apenas a cópia privada restaurada. AGENTS.md, secção 6, exige autorização concreta para migrações no destino activo.",
"runtime": {
"manifest_sha256": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"archive_sha256": "bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76",
"private_installation_directory": "C:/laragon/data/compras/runtime/80483320a54af6f1",
"old_artifacts": "Preservar integralmente; não sobrescrever pacotes instalados ou congelados"
},
"exact_schema_selection": {
"normal_migrations": "Exactamente os cinco caminhos/hashes de compras-standalone-pilot-recovery-proposal.json:selected_normal_migrations_in_restored_copy_only; conferir novamente antes de executar",
"extensions": "StandaloneInstallation e StandaloneExtensionSchema já ensaiados, com --reuse-components e os três perfis canónicos completos",
"not_selected": "Migrações históricas de pa_sources/pa_obligations, importação financeira, decisões legadas de pagamentos, geografia operacional e envio SGF; não marcar migrações anteriores como executadas por inferência",
"receipt": "UUID próprio novo da instalação, nome/role exactos conferidos no servidor, operador/motivo e hashes registados; repetição sem outra escrita"
},
"procedure": [
"Pré-visualizar identidade e selecção, confirmar que o schema e o runtime não mudaram desde as provas; recusar deriva ou recibo incompatível.",
"Obter nova salvaguarda consistente privada e confirmar restauro/conservação antes da escrita no piloto; preservar configurações e manifestos anteriores.",
"Preparar o pacote numa nova pasta privada, conferir todos os bytes e aplicar apenas as cinco migrações e a instalação aditiva já ensaiada. Não executar migrate genérico.",
"Comparar todas as colunas anteriores e os registos históricos das migrações, permitindo apenas os cinco registos novos e o recibo técnico previsto.",
"Conferir recusas e repetição, disponibilidade anterior e configuração inalterada. Relatar a instalação sem a confundir com activação ou aceitação integral."
],
"acceptance": [
"118 tabelas anteriores de negócio preservadas, com todas as colunas e valores anteriores; migrações anteriores preservadas.",
"Cinco migrações delimitadas, schema das 24 capacidades disponível e um recibo imutável; repetição sem duplicação.",
"Configuração, concessões, MFA, dados bancários, parâmetros fiscais, assets e activação dos módulos permanecem como estavam.",
"Nenhum documento, aprovação, pagamento, movimento de stock ou lançamento criado para demonstrar a instalação."
],
"recovery": "Falha de transacção reverte a sua alteração. Preservar salvaguarda e diagnóstico. Não apagar história nem efectuar downgrade sobre dados novos. Se for necessária reposição da base inteira, interromper e apresentar o impacto concreto antes de sobrescrever a origem.",
"excluded": [
"Activar as novas capacidades, substituir assets ou alterar configurações da aplicação activa",
"Conceder acessos, criar utilizadores, contas, regras ou decisões empresariais",
"Instalação em produção ou alteração do domínio público",
"Operações ou alterações ao SGF"
],
"evidence": [
"compras-standalone-pilot-recovery.json:119 tabelas restauradas idênticas,118 tabelas de negócio e histórico de migrações conservados,24 capacidades verificadas e repetição sem escrita",
"compras-operational-candidate.json: testes integrados10/218, actualização sintética3/169, arranque/restauro/recusas e concorrência real; menus móveis e impressão observados"
],
"application_complete": false
}
@@ -0,0 +1,45 @@
{
"date": "2026-11-29T13:51:56+00:00",
"state": "passed",
"source_read_only": false,
"source_writes": "five_selected_migrations_and_runtime_schema_receipt_only",
"private_backup_directory": "C:\/laragon\/data\/sgf-tempo\/backups\/compras-standalone-recovery-20261129-135155-902f3bf53999",
"temporary_database": "compras_private_restore_902f3bf53999",
"temporary_role": "compras_private_app_902f3bf53999",
"runtime_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"pilot_installation_or_activation": "installation_only",
"backup_sha256": "86fc60039377cbb80706801b7536e4a1e0e08b1a18e6e3df9f0bb6fce62dfcfd",
"initial_tables_preserved": 119,
"upgrade": {
"verified": true,
"selected_migrations": 5,
"available_modules": 24,
"one_receipt_replay_without_write": true,
"configuration_stays_disabled": true,
"existing_components": [
"budget-distributions-v1",
"supplier-settlements-v1",
"supplier-payables-v1"
]
},
"historical_migration_records_preserved": true,
"original_business_tables_preserved": 118,
"pilot_upgrade": {
"verified": true,
"selected_migrations": 5,
"available_modules": 24,
"one_receipt_replay_without_write": true,
"configuration_stays_disabled": true,
"existing_components": [
"budget-distributions-v1",
"supplier-settlements-v1",
"supplier-payables-v1"
]
},
"pilot_activation": false,
"runtime_directory": "C:\/laragon\/data\/compras\/runtime\/80483320a54af6f1",
"installation_id": "0602a856-0413-480f-9ef3-1a1f3238bb90",
"active_settings_env_and_asset_manifest_preserved": true,
"temporary_database_removed": true,
"temporary_role_removed": true
}
@@ -0,0 +1,10 @@
{
"date": "2026-11-29",
"state": "approved",
"decision": "Autorizar salvaguarda e ensaio na cópia privada",
"proposal": "compras-standalone-pilot-recovery-proposal.json",
"proposal_sha256": "81a9fb3a7aee43c0bed63f900e8b3e53d76f944b0143a3a0288bd054dc079292",
"source_writes": false,
"pilot_installation_or_activation": false,
"private_local_restore_only": true
}
@@ -0,0 +1,56 @@
{
"date": "2026-11-29",
"state": "proposed_not_authorized_or_executed",
"decision": "Autorizar exclusivamente a salvaguarda e o ensaio privado de actualização numa cópia restaurada do piloto de Compras; sem escrita, instalação ou activação na base original.",
"target": {
"source": "Piloto de Compras http://127.0.0.1:8005, identidade exacta conferida pela configuração privada e pelo servidor",
"metadata_inventory": "standalone-pilot-schema-inventory.json",
"restored_destination": "Nova base local própria, nome e role únicos registados antes da criação; sem servidor HTTP, jobs, correio ou integrações",
"runtime_manifest_sha256": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"runtime_archive_sha256": "bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76"
},
"reason": "Os ensaios sintéticos passaram, mas não demonstram a compatibilidade com todos os registos anteriores do piloto. A autorização existente limita os ensaios a dados sintéticos; uma cópia dos dados anteriores exige esta decisão específica.",
"operations": [
"Conferir identidade, configuração e manifesto de origem sem os alterar; obter snapshot consistente readonly e salvaguarda privada local.",
"Restaurar para base e role novas e próprias; comparar todas as tabelas e todas as colunas anteriores com o snapshot, sem expor os seus valores em provas.",
"Na cópia exclusivamente, aplicar apenas as migrações normais necessárias à composição seleccionada e a preparação do runtime conferido com --reuse-components. Conferir cada ficheiro/hash no plano antes da alteração; não executar migrate genérico nem marcar migrações históricas como executadas por inferência.",
"Verificar os três perfis canónicos completos antes da reutilização, recibo da nova instalação, recusas, repetição e conservação de todos os valores anteriores; não criar utilizadores, permissões, contas, regras, documentos ou operações financeiras.",
"Remover apenas a base/role temporárias próprias após a conferência; preservar a salvaguarda privada com hash e relatório agregado para revisão."
],
"acceptance": [
"Origem sem alterações de schema, dados, configurações, permissões, assets ou disponibilidade.",
"Cópia inicial idêntica ao snapshot; colunas anteriores conservadas após a actualização, salvo tabelas exclusivamente técnicas cuja alteração esteja expressamente prevista no plano.",
"Um recibo de instalação; repetição sem duplicação; módulos desligados e nenhuma operação de negócio.",
"Falha não permite avanço ao piloto; diagnóstico delimitado e recursos próprios identificados para recuperação."
],
"excluded": [
"Instalação, migração, activação ou substituição de assets no piloto, domínio público ou produção",
"Concessões de acesso, MFA, novos actores, decisões de negócio ou operações financeiras",
"Envio de dados a serviços externos, abertura da cópia por HTTP ou utilização dos seus contactos para mensagens",
"Alterações operacionais ao SGF ou activação fiscal/bancária/JUE"
],
"recovery": "A origem é apenas lida. Interromper o ensaio, preservar diagnóstico sem valores privados e remover somente recursos temporários comprovadamente criados por este ensaio. A salvaguarda não será restaurada sobre a origem por esta autorização.",
"evidence_already_available": {
"synthetic_upgrade_tests": 3,
"synthetic_upgrade_assertions": 169,
"latest_business_tests": 10,
"latest_business_assertions": 218,
"startup_recovery_and_real_process_concurrency": "passed",
"previous_canonical_artifacts_preserved": true
},
"application_complete": false,
"selected_normal_migrations_in_restored_copy_only": {
"database/migrations/2026_11_03_000003_create_order_cancellations.php": "c60bf9123b9c9e2ef56687779f1e90b063a34a22d957df5c045dc4d2230f17d3",
"database/migrations/2026_11_22_000005_add_requisition_category_context.php": "1fb94b43d7754ecc254ccd4f671dd5ca684fbc3384831a464a70a6b1087364aa",
"database/migrations/2026_11_22_000006_create_procurement_saved_searches.php": "03aa7b18f59fe9d65da94b96545919277cafe17588975c6ae4cca9cba3c10a6c",
"database/migrations/2026_11_28_000001_create_conflict_releases.php": "a0f24ccc5961de00a3ed0ec9ddb9c6f45db022b2638c0c81c1507306b3f10af4",
"database/migrations/2026_11_28_000002_create_private_audit_exports.php": "df843191283851fbc2fd0f4bb33ad1f3c1e945c8c87feaf4bce71e55900a84d5"
},
"normal_migrations_explicitly_not_selected": [
"2026_10_29_000021_create_supplier_payables: existing canonical schema must match; preserve historical migration records",
"2026_10_29_000022_create_payable_history_imports",
"2026_10_29_000023_create_payable_payment_decisions",
"2026_11_03_000005_add_operational_geography_references",
"2026_11_10_000001_create_sgf_invoice_dispatches"
]
}
@@ -0,0 +1,29 @@
{
"date": "2026-11-29T13:51:41+00:00",
"state": "passed",
"source_read_only": true,
"source_writes": false,
"private_backup_directory": "C:\/laragon\/data\/sgf-tempo\/backups\/compras-standalone-recovery-20261129-135141-e0767c75981d",
"temporary_database": "compras_private_restore_e0767c75981d",
"temporary_role": "compras_private_app_e0767c75981d",
"runtime_manifest": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
"pilot_installation_or_activation": false,
"backup_sha256": "f22ef85aa81cc15ea83f3f90efce027eb99d785db0f8d97f9502d143716601b4",
"initial_tables_preserved": 119,
"upgrade": {
"verified": true,
"selected_migrations": 5,
"available_modules": 24,
"one_receipt_replay_without_write": true,
"configuration_stays_disabled": true,
"existing_components": [
"budget-distributions-v1",
"supplier-settlements-v1",
"supplier-payables-v1"
]
},
"historical_migration_records_preserved": true,
"original_business_tables_preserved": 118,
"temporary_database_removed": true,
"temporary_role_removed": true
}
@@ -160,5 +160,43 @@
}, },
"final_worker": "Refused because native approved cancellation absent. Not a passing complete-cycle conservation proof.", "final_worker": "Refused because native approved cancellation absent. Not a passing complete-cycle conservation proof.",
"operational_changes": false "operational_changes": false
},
"native_manual_final_verified_20261129": {
"state": "manual_decision_and_conservation_verified",
"private_root": "storage/framework/testing/rq01-ledger-qa-a14258b549a5",
"url": "http://localhost:64010/ordens/cancelamentos",
"runner_session": 81503,
"stop_file": "storage/framework/testing/rq01-ledger-qa-a14258b549a5/stop-review",
"synthetic_only": true,
"source_order": "OC-TEST-pRGeu1s5nE",
"request_submitted_by_author": true,
"independent_finance_identity": "qa-finance@example.invalid",
"approval_option_and_reason_prepared": true,
"decision_not_submitted": false,
"manual_step": "User clicks Registar decisao and confirms the native dialog in the own QA tab; return control for conservation checks",
"native_final_approval_confirmed": true,
"duration_minutes": 60,
"cleanup": {
"isolated_database_removed": true,
"isolated_role_removed": true,
"operational_changes": false,
"owned_tab_closure_not_verified_geometry_unavailable": true
},
"original_browser_tab_preserved": true,
"owner_response": "ja feito",
"verification": {
"visible_status": "Aprovado",
"independent_finance_decision": true,
"original_order_preserved": true,
"original_status": "issued",
"operational_status": "cancelled",
"source_request_cancelled_only": true,
"protected_frames_preserved": 15,
"no_fabricated_legacy_reversal": true,
"one_request_one_decision": true,
"readonly_transaction": true,
"synthetic_only": true
},
"remaining": "Native mobile/print delta not verified; source-link input stopped after two geometry-unavailable attempts. No failed confirmation repeated."
} }
} }
+54 -1
View File
@@ -699,7 +699,7 @@
"adapted_drawer_closes_after_navigation": true, "adapted_drawer_closes_after_navigation": true,
"agreements_to_contracts_link_followed": true, "agreements_to_contracts_link_followed": true,
"header_links_separated_and_wrapped": true, "header_links_separated_and_wrapped": true,
"new_label": "Novo contrato com vários artigos", "new_label": "Novo contrato com v\u00e1rios artigos",
"document_title": "Contrato QA-VISUAL-CONTRACT", "document_title": "Contrato QA-VISUAL-CONTRACT",
"readable_without_horizontal_page_overflow": true "readable_without_horizontal_page_overflow": true
}, },
@@ -863,5 +863,58 @@
"result": "passed", "result": "passed",
"duration_seconds": 55.18, "duration_seconds": 55.18,
"does_not_imply_application_acceptance": true "does_not_imply_application_acceptance": true
},
"native_cancellation_followup_20261129": {
"private_root": "storage/framework/testing/rq01-ledger-qa-3f41b9c4c6e6",
"state": "native final approval still unconfirmed",
"observation": "Author submitted synthetic request; separate Finance identity selected approval and entered reason; Computer Use stopped at native confirmation because URL could not be established",
"mandatory_final_conservation_worker": "failed because approved cancellation absent; not a passing full-cycle proof",
"cleanup": {
"database_removed": true,
"role_removed": true,
"native_confirmation_cancelled_later": true,
"own_tab_closed_later": true,
"original_browser_tab_preserved": true
},
"no_alternative_interface_execution": true,
"next": "Manual final native confirmation in a fresh isolated QA composition; do not repeat blocked automation"
},
"native_cancellation_manual_review_pending_20261129": {
"state": "manual_decision_and_conservation_verified",
"private_root": "storage/framework/testing/rq01-ledger-qa-a14258b549a5",
"url": "http://localhost:64010/ordens/cancelamentos",
"runner_session": 81503,
"stop_file": "storage/framework/testing/rq01-ledger-qa-a14258b549a5/stop-review",
"synthetic_only": true,
"source_order": "OC-TEST-pRGeu1s5nE",
"request_submitted_by_author": true,
"independent_finance_identity": "qa-finance@example.invalid",
"approval_option_and_reason_prepared": true,
"decision_not_submitted": false,
"manual_step": "User clicks Registar decisao and confirms the native dialog in the own QA tab; return control for conservation checks",
"native_final_approval_confirmed": true,
"duration_minutes": 60,
"cleanup": {
"isolated_database_removed": true,
"isolated_role_removed": true,
"operational_changes": false,
"owned_tab_closure_not_verified_geometry_unavailable": true
},
"original_browser_tab_preserved": true,
"owner_response": "ja feito",
"verification": {
"visible_status": "Aprovado",
"independent_finance_decision": true,
"original_order_preserved": true,
"original_status": "issued",
"operational_status": "cancelled",
"source_request_cancelled_only": true,
"protected_frames_preserved": 15,
"no_fabricated_legacy_reversal": true,
"one_request_one_decision": true,
"readonly_transaction": true,
"synthetic_only": true
},
"remaining": "Native mobile/print delta not verified; source-link input stopped after two geometry-unavailable attempts. No failed confirmation repeated."
} }
} }
File diff suppressed because it is too large Load Diff
@@ -29,6 +29,7 @@ import {
activeProcurementEntry, activeProcurementEntry,
procurementNavigation, procurementNavigation,
} from '@/lib/procurement-navigation'; } from '@/lib/procurement-navigation';
import type { CommonFinanceNavigation } from '@/lib/procurement-navigation';
import { roleLabels } from '@/types/procurement'; import { roleLabels } from '@/types/procurement';
import type { WorkContextState } from '@/types/work-context'; import type { WorkContextState } from '@/types/work-context';
import { WorkContextChange } from '@/components/work-context-change'; import { WorkContextChange } from '@/components/work-context-change';
@@ -54,6 +55,9 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
permissions: string[]; permissions: string[];
} | null; } | null;
const context = page.props.workContext as WorkContextState | null; const context = page.props.workContext as WorkContextState | null;
const commonFinance = page.props.commonFinanceNavigation as
| CommonFinanceNavigation
| undefined;
const scopedEntries = new Set( const scopedEntries = new Set(
procurementNavigation( procurementNavigation(
context?.permissions ?? [], context?.permissions ?? [],
@@ -63,6 +67,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
page.props.operationalOrdersAvailable === true, page.props.operationalOrdersAvailable === true,
page.props.privateAuditAvailable === true, page.props.privateAuditAvailable === true,
page.props.capitalRegisterAvailable === true, page.props.capitalRegisterAvailable === true,
commonFinance,
).flatMap((group) => group.entries.map((entry) => entry.id)), ).flatMap((group) => group.entries.map((entry) => entry.id)),
); );
const groups = procurementNavigation( const groups = procurementNavigation(
@@ -73,6 +78,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
page.props.operationalOrdersAvailable === true, page.props.operationalOrdersAvailable === true,
page.props.privateAuditAvailable === true, page.props.privateAuditAvailable === true,
page.props.capitalRegisterAvailable === true, page.props.capitalRegisterAvailable === true,
commonFinance,
) )
.map((group) => ({ .map((group) => ({
...group, ...group,
+19
View File
@@ -37,6 +37,25 @@ function topic(
} }
export const journeyHelp: JourneyHelp[] = [ export const journeyHelp: JourneyHelp[] = [
topic(
'company-finance',
'Configurar o livro financeiro da empresa',
['company/finance'],
'Registar as pessoas, competências, contas, períodos e regras utilizados no núcleo financeiro da própria empresa.',
[
'Seleccione expressamente o utilizador e as competências pretendidas. Utilize a mesma referência de pessoa para contas que pertencem à mesma pessoa.',
'Registe os códigos e designações do plano de contas. Assinale as contas de movimento que podem ser usadas nas regras.',
'Defina períodos sem sobreposição e regras com efeito, duas contas distintas e vigência explícitos. Fundamente cada alteração.',
'Confira o histórico. Uma nova versão da regra preserva os lançamentos e as decisões anteriores.',
],
[
'A administração configura; as competências de preparação, revisão e aplicação financeira são escolhidas separadamente. Consultar a página não concede acessos.',
'O cadastro não cria dívidas, pagamentos, lançamentos ou movimentos de stock. O fecho de período exige o circuito de conferência independente.',
'Revogar competências deste contrato conserva acessos de outros contratos e o histórico. Uma pessoa não pode rever o seu próprio trabalho por usar outra conta.',
],
'Se a configuração mudou, actualize a preparação e confira novamente os valores antes de guardar. Se não sabe se a operação foi registada, consulte o histórico antes de repetir.',
'Os intervenientes com competência explícita podem prosseguir para as obrigações, pagamentos e diário no menu Finanças.',
),
topic( topic(
'private-audit', 'private-audit',
'Preparar uma exportação privada de auditoria', 'Preparar uma exportação privada de auditoria',
@@ -24,6 +24,11 @@ export type ProcurementGroup = {
icon: LucideIcon; icon: LucideIcon;
entries: ProcurementEntry[]; entries: ProcurementEntry[];
}; };
export type CommonFinanceNavigation = {
payments?: boolean;
ledger?: boolean;
configuration?: boolean;
};
const readers = ['admin', 'procurement', 'finance', 'department_head']; const readers = ['admin', 'procurement', 'finance', 'department_head'];
const finance = ['admin', 'finance']; const finance = ['admin', 'finance'];
const inventory = [...readers, 'warehouse']; const inventory = [...readers, 'warehouse'];
@@ -36,6 +41,7 @@ export function procurementNavigation(
operationalOrders = false, operationalOrders = false,
privateAudit = false, privateAudit = false,
capitalRegister = false, capitalRegister = false,
commonFinance: CommonFinanceNavigation = {},
): ProcurementGroup[] { ): ProcurementGroup[] {
const groups: ProcurementGroup[] = [ const groups: ProcurementGroup[] = [
{ {
@@ -455,6 +461,28 @@ export function procurementNavigation(
}, },
] ]
: []), : []),
...(commonFinance.payments === true
? [
{
id: 'supplier_settlements',
label: 'Pagamentos e afectações a facturas',
path: '/supplier-payments',
roles: finance,
fullPage: true,
},
]
: []),
...(commonFinance.ledger === true
? [
{
id: 'general_ledger',
label: 'Diário, balancete e razão',
path: '/general-ledger/cycle',
roles: finance,
fullPage: true,
},
]
: []),
{ {
id: 'payments', id: 'payments',
label: 'Pagamentos externos', label: 'Pagamentos externos',
@@ -480,6 +508,16 @@ export function procurementNavigation(
label: 'Administração e controlo', label: 'Administração e controlo',
icon: ShieldCheck, icon: ShieldCheck,
entries: [ entries: [
...(commonFinance.configuration === true
? [
{
id: 'finance_configuration',
label: 'Configuração financeira',
path: '/administracao/financeiro',
roles: ['admin'],
},
]
: []),
{ {
id: 'company', id: 'company',
label: 'Empresa, equipa e centros', label: 'Empresa, equipa e centros',
+871
View File
@@ -0,0 +1,871 @@
import { Head, Link, router, useForm } from '@inertiajs/react';
import { useState } from 'react';
import type { FormEvent, ReactNode } from 'react';
import {
PageTitle,
Panel,
FormErrors,
TableViewport,
controlClass,
} from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { usePreparationDirty } from '@/hooks/use-preparation-dirty';
import { useProcurementPreparationIdentity } from '@/hooks/use-procurement-preparation-identity';
type Row = Record<string, string | number | boolean | null>;
type Basis<T = Row> = { hash: string; rows: T[] };
type Account = {
id: number;
code: string;
label: string;
currency: string;
is_movement: boolean;
};
type Person = { id: number; name: string; email: string };
type Page<T> = {
data: T[];
prev_page_url: string | null;
next_page_url: string | null;
};
type Access = Basis & {
user: Person;
eligible: boolean;
person: string;
actions: string[];
other_actions: string[];
identity_inconsistent: boolean;
};
type Props = {
actorId: number;
tenantId: number;
q: string;
users: Page<Person>;
selectedAccess: Access | null;
accounts: Basis<Account>;
periods: Basis;
rules: Basis;
actions: Record<string, string>;
effects: Record<string, string>;
history: Page<{
id: number;
actor_id: number;
kind: string;
reason: string;
before: Basis;
after: Basis;
created_at: string;
}>;
};
type Kind = 'access' | 'account' | 'period' | 'rule';
type Data = {
operation_key: string;
basis_hash: string;
reason: string;
user_id?: number;
person?: string;
actions?: string[];
code?: string;
label?: string;
currency?: string;
is_movement?: boolean;
period_key?: string;
starts_on?: string;
ends_on?: string;
rule_key?: string;
effect_type?: string;
valid_from?: string;
valid_to?: string;
debit_account_id?: string;
credit_account_id?: string;
};
const base = '/administracao/financeiro';
function useConfigurationForm(
kind: Kind,
hash: string,
identity: string,
fields: Partial<Data>,
clearAfterSave = true,
) {
const initial: Data = {
...fields,
operation_key: '',
basis_hash: hash,
reason: '',
};
const form = useForm<Data>(identity, initial);
const ref = usePreparationDirty(form.isDirty);
const current = form.data.basis_hash === hash;
const review = () => {
form.setData({ ...form.data, operation_key: '', basis_hash: hash });
form.clearErrors();
};
const submit = (event: FormEvent) => {
event.preventDefault();
if (!current || form.processing) return;
const operation = form.data.operation_key || crypto.randomUUID();
form.setData('operation_key', operation);
form.transform((data) => ({ ...data, operation_key: operation }));
form.post(`${base}/${kind}`, {
preserveScroll: true,
onSuccess: (page) => {
const source =
page.props[
kind === 'access'
? 'selectedAccess'
: kind === 'account'
? 'accounts'
: kind === 'period'
? 'periods'
: 'rules'
];
if (
!source ||
typeof source !== 'object' ||
!('hash' in source) ||
typeof source.hash !== 'string'
)
return;
const next = {
...(clearAfterSave ? initial : form.data),
operation_key: '',
basis_hash: source.hash,
reason: '',
};
form.setData(next);
form.setDefaults(next);
form.clearErrors();
},
});
};
return { form, ref, current, review, submit };
}
function Reason({
value,
change,
id,
}: {
value: string;
change: (value: string) => void;
id: string;
}) {
return (
<label className="grid gap-2" htmlFor={id}>
Motivo da alteração
<textarea
className={controlClass}
id={id}
required
minLength={10}
maxLength={2000}
value={value}
onChange={(event) => change(event.target.value)}
/>
</label>
);
}
function Review({ current, review }: { current: boolean; review: () => void }) {
return current ? null : (
<div
className="rounded-lg border border-amber-300 bg-amber-50 p-4 text-amber-950"
role="status"
>
<p>
A configuração foi actualizada. Compare os dados actuais com a
sua preparação antes de continuar.
</p>
<Button type="button" variant="outline" onClick={review}>
Rever preparação com a configuração actual
</Button>
</div>
);
}
function Pagination({ page, label }: { page: Page<unknown>; label: string }) {
return (
<nav aria-label={label} className="flex flex-wrap gap-5">
{page.prev_page_url && (
<Link className="underline" href={page.prev_page_url}>
Anterior
</Link>
)}
{page.next_page_url && (
<Link className="underline" href={page.next_page_url}>
Seguinte
</Link>
)}
</nav>
);
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="grid min-w-0 gap-2">
{label}
{children}
</label>
);
}
function AccessForm({
access,
labels,
identity,
}: {
access: Access;
labels: Record<string, string>;
identity: string;
}) {
const state = useConfigurationForm(
'access',
access.hash,
identity,
{
user_id: access.user.id,
person: access.person,
actions: access.actions,
},
false,
);
const { form } = state;
const selected = form.data.actions ?? [];
return (
<form ref={state.ref} onSubmit={state.submit} className="grid gap-5">
<h3 className="font-semibold">
{access.user.name} · {access.user.email}
</h3>
<p>
Use a mesma referência de pessoa quando duas contas de acesso
pertencem à mesma pessoa. A revisão independente considera essa
identidade.
</p>
<p className="text-sm">
Identidade actualmente registada:{' '}
{access.person || 'Por definir'}. Permissões actuais:{' '}
{access.actions
.map((action) => labels[action] ?? action)
.join('; ') || 'Nenhuma deste contrato'}
.
</p>
{!access.eligible && (
<p role="status">
Este utilizador precisa de uma função de Finanças ou
Administração em Compras internas para receber acessos. Pode
preparar a revogação dos acessos existentes.
</p>
)}
{access.identity_inconsistent && (
<p role="status">
Os acessos actuais contêm identidades diferentes. Confira a
identidade antes de guardar.
</p>
)}
{access.other_actions.length > 0 && (
<p>
Acessos de outros contratos preservados:{' '}
{access.other_actions.join(', ')}.
</p>
)}
<FormErrors errors={form.errors} />
<Review current={state.current} review={state.review} />
<Field label="Referência nominativa da pessoa">
<input
className={controlClass}
maxLength={160}
required={selected.length > 0}
value={form.data.person ?? ''}
onChange={(event) =>
form.setData('person', event.target.value)
}
/>
</Field>
<fieldset className="grid gap-3 sm:grid-cols-2">
<legend className="mb-3 font-semibold">
Competências expressamente atribuídas
</legend>
{Object.entries(labels).map(([action, label]) => (
<label className="flex items-start gap-3" key={action}>
<input
type="checkbox"
disabled={!access.eligible}
checked={selected.includes(action)}
onChange={(event) =>
form.setData(
'actions',
event.target.checked
? [...selected, action]
: selected.filter(
(value) => value !== action,
),
)
}
/>
<span>{label}</span>
</label>
))}
</fieldset>
<p className="text-sm">
Seleccione também a consulta de obrigações para conceder outros
acessos, a consulta de pagamentos para preparar ou rever
afectações e a consulta contabilística para actuar no diário.
</p>
<Reason
id="finance-access-reason"
value={form.data.reason}
change={(value) => form.setData('reason', value)}
/>
<div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap">
<Button
disabled={
!state.current ||
form.processing ||
(!access.eligible && selected.length > 0)
}
>
Guardar acessos explícitos
</Button>
<Button
type="button"
variant="outline"
onClick={() => form.setData('actions', [])}
>
Preparar revogação deste contrato
</Button>
</div>
<p className="text-sm">
Mudar a identidade ou retirar competências pode impedir a
aplicação de propostas anteriores. O histórico e as decisões
anteriores são preservados.
</p>
</form>
);
}
function AccountForm({
basis,
identity,
}: {
basis: Basis<Account>;
identity: string;
}) {
const state = useConfigurationForm('account', basis.hash, identity, {
code: '',
label: '',
is_movement: false,
currency: 'MZN',
});
const { form } = state;
return (
<form ref={state.ref} onSubmit={state.submit} className="grid gap-4">
<FormErrors errors={form.errors} />
<Review current={state.current} review={state.review} />
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Código da conta">
<input
className={controlClass}
required
maxLength={80}
value={form.data.code ?? ''}
onChange={(event) =>
form.setData('code', event.target.value)
}
/>
</Field>
<Field label="Designação">
<input
className={controlClass}
required
maxLength={200}
value={form.data.label ?? ''}
onChange={(event) =>
form.setData('label', event.target.value)
}
/>
</Field>
</div>
<label className="flex items-start gap-3">
<input
type="checkbox"
checked={form.data.is_movement ?? false}
onChange={(event) =>
form.setData('is_movement', event.target.checked)
}
/>
Conta de movimento, disponível para regras de lançamento
</label>
<p className="text-sm">
Este livro contabilístico utiliza MZN. Os códigos e as contas
registadas são preservados.
</p>
<Reason
id="finance-account-reason"
value={form.data.reason}
change={(value) => form.setData('reason', value)}
/>
<Button
className="justify-self-start"
disabled={!state.current || form.processing}
>
Registar conta
</Button>
</form>
);
}
function PeriodForm({ basis, identity }: { basis: Basis; identity: string }) {
const state = useConfigurationForm('period', basis.hash, identity, {
period_key: '',
starts_on: '',
ends_on: '',
});
const { form } = state;
return (
<form ref={state.ref} onSubmit={state.submit} className="grid gap-4">
<FormErrors errors={form.errors} />
<Review current={state.current} review={state.review} />
<Field label="Referência do período">
<input
className={controlClass}
required
maxLength={80}
value={form.data.period_key ?? ''}
onChange={(event) =>
form.setData('period_key', event.target.value)
}
/>
</Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Início">
<input
className={controlClass}
type="date"
required
value={form.data.starts_on ?? ''}
onChange={(event) =>
form.setData('starts_on', event.target.value)
}
/>
</Field>
<Field label="Fim">
<input
className={controlClass}
type="date"
required
value={form.data.ends_on ?? ''}
onChange={(event) =>
form.setData('ends_on', event.target.value)
}
/>
</Field>
</div>
<p className="text-sm">
Escolha um intervalo distinto dos períodos registados. O fecho
exige conferência independente e não é alterado por este
cadastro.
</p>
<Reason
id="finance-period-reason"
value={form.data.reason}
change={(value) => form.setData('reason', value)}
/>
<Button
className="justify-self-start"
disabled={!state.current || form.processing}
>
Criar período aberto
</Button>
</form>
);
}
function RuleForm({
basis,
accounts,
effects,
identity,
}: {
basis: Basis;
accounts: Account[];
effects: Record<string, string>;
identity: string;
}) {
const state = useConfigurationForm('rule', basis.hash, identity, {
rule_key: '',
effect_type: '',
valid_from: '',
valid_to: '',
debit_account_id: '',
credit_account_id: '',
});
const { form } = state;
const movement = accounts.filter(
(account) => account.is_movement && account.currency === 'MZN',
);
return (
<form ref={state.ref} onSubmit={state.submit} className="grid gap-4">
<FormErrors errors={form.errors} />
<Review current={state.current} review={state.review} />
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Referência da regra">
<input
className={controlClass}
required
maxLength={80}
value={form.data.rule_key ?? ''}
onChange={(event) =>
form.setData('rule_key', event.target.value)
}
/>
</Field>
<Field label="Efeito financeiro">
<select
className={controlClass}
required
value={form.data.effect_type ?? ''}
onChange={(event) =>
form.setData('effect_type', event.target.value)
}
>
<option value="">Seleccione o efeito</option>
{Object.entries(effects).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
</Field>
</div>
<div className="grid gap-4 sm:grid-cols-2">
{(['debit_account_id', 'credit_account_id'] as const).map(
(name) => (
<Field
key={name}
label={
name === 'debit_account_id'
? 'Conta a debitar'
: 'Conta a creditar'
}
>
<select
className={controlClass}
required
value={form.data[name] ?? ''}
onChange={(event) =>
form.setData(name, event.target.value)
}
>
<option value="">
Seleccione a conta de movimento
</option>
{movement.map((account) => (
<option key={account.id} value={account.id}>
{account.code} · {account.label}
</option>
))}
</select>
</Field>
),
)}
</div>
{movement.length < 2 && (
<p role="status">
Registe duas contas de movimento distintas antes de definir
a regra.
</p>
)}
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Vigência desde">
<input
className={controlClass}
type="date"
required
value={form.data.valid_from ?? ''}
onChange={(event) =>
form.setData('valid_from', event.target.value)
}
/>
</Field>
<Field label="Vigência até">
<input
className={controlClass}
type="date"
required
value={form.data.valid_to ?? ''}
onChange={(event) =>
form.setData('valid_to', event.target.value)
}
/>
</Field>
</div>
<p className="text-sm">
A mesma referência cria uma nova versão. As próximas capturas
usam essa versão; propostas afectadas exigem nova conferência.
Os lançamentos aplicados conservam a regra e as contas
utilizadas.
</p>
<Reason
id="finance-rule-reason"
value={form.data.reason}
change={(value) => form.setData('reason', value)}
/>
<Button
className="justify-self-start"
disabled={
!state.current || form.processing || movement.length < 2
}
>
Registar versão da regra
</Button>
</form>
);
}
function HistoryRows({
kind,
rows,
labels,
effects,
}: {
kind: string;
rows: Row[];
labels: Record<string, string>;
effects: Record<string, string>;
}) {
return rows.length === 0 ? (
<p>Sem registos neste estado.</p>
) : (
<ul className="grid gap-2">
{rows.map((row, index) => (
<li key={index} className="break-words">
{kind === 'configuration.access'
? `${labels[String(row.action)] ?? row.action} · pessoa ${row.person} · utilizador #${row.user_id}`
: kind === 'configuration.account'
? `${row.code} · ${row.label}`
: kind === 'configuration.period'
? `${row.period_key} · versão ${row.version} · ${row.status} · ${row.starts_on} a ${row.ends_on}`
: `${row.rule_key} · versão ${row.version} · ${effects[String(row.effect_type)] ?? row.effect_type} · débito #${row.debit_account_id} / crédito #${row.credit_account_id}`}
</li>
))}
</ul>
);
}
export default function FinanceConfiguration(props: Props) {
const scope = useProcurementPreparationIdentity(
`common-finance:${props.tenantId}:${props.actorId}`,
);
const [term, setTerm] = useState(props.q);
return (
<div className="mx-auto grid w-full max-w-6xl gap-6 p-5 lg:p-8">
<Head title="Configuração financeira" />
<PageTitle
eyebrow="SGC · Administração"
title="Configuração financeira"
description="Defina explicitamente quem intervém e quais as contas, períodos e regras utilizados no livro da empresa. O cadastro não regista dívidas, pagamentos ou lançamentos."
/>
<Link className="underline" href="/administracao/parametrizacao">
Voltar à parametrização da empresa
</Link>
<nav aria-label="Áreas da configuração financeira">
<ul className="flex flex-wrap gap-4">
{[
['finance-access', 'Pessoas e acessos'],
['finance-accounts', 'Plano de contas'],
['finance-periods', 'Períodos'],
['finance-rules', 'Regras'],
['finance-history', 'Histórico'],
].map(([id, label]) => (
<li key={id}>
<a className="underline" href={`#${id}`}>
{label}
</a>
</li>
))}
</ul>
</nav>
<Panel
id="finance-access"
title="Pessoas e competências financeiras"
description="A atribuição é nominativa. As competências de consulta, preparação, revisão e aplicação são escolhidas separadamente."
>
<div className="grid gap-6">
<form
className="flex flex-col gap-3 sm:flex-row"
onSubmit={(event) => {
event.preventDefault();
router.get(
base,
{ q: term },
{ preserveScroll: true },
);
}}
>
<label className="grid flex-1 gap-2">
Pesquisar utilizadores
<input
className={controlClass}
value={term}
maxLength={100}
onChange={(event) =>
setTerm(event.target.value)
}
/>
</label>
<Button className="self-start sm:self-end">
Pesquisar
</Button>
</form>
<ul className="grid gap-3 sm:grid-cols-2">
{props.users.data.map((person) => (
<li key={person.id}>
<Link
className="underline"
href={`${base}?${new URLSearchParams({ user: String(person.id), q: props.q })}`}
>
{person.name} · {person.email}
</Link>
</li>
))}
</ul>
<Pagination
page={props.users}
label="Páginas dos utilizadores"
/>
{props.selectedAccess ? (
<AccessForm
key={`${scope}:access:${props.selectedAccess.user.id}`}
access={props.selectedAccess}
labels={props.actions}
identity={`${scope}:access:${props.selectedAccess.user.id}`}
/>
) : (
<p>
Seleccione expressamente o utilizador a configurar.
</p>
)}
</div>
</Panel>
<Panel id="finance-accounts" title="Plano de contas próprio">
<div className="grid gap-6">
<AccountForm
key={`${scope}:account`}
identity={`${scope}:account`}
basis={props.accounts}
/>
{props.accounts.rows.length > 0 && (
<TableViewport label="Contas registadas">
<table className="w-full text-left text-sm">
<thead>
<tr>
<th className="p-2">Código</th>
<th className="p-2">Designação</th>
<th className="p-2">Tipo</th>
</tr>
</thead>
<tbody>
{props.accounts.rows.map((account) => (
<tr key={account.id}>
<td className="p-2 break-all">
{account.code}
</td>
<td className="p-2">
{account.label}
</td>
<td className="p-2">
{account.is_movement
? 'Movimento'
: 'Agrupamento'}{' '}
· {account.currency}
</td>
</tr>
))}
</tbody>
</table>
</TableViewport>
)}
</div>
</Panel>
<Panel id="finance-periods" title="Períodos do livro">
<div className="grid gap-6">
<PeriodForm
key={`${scope}:period`}
identity={`${scope}:period`}
basis={props.periods}
/>
<HistoryRows
kind="configuration.period"
rows={props.periods.rows}
labels={props.actions}
effects={props.effects}
/>
</div>
</Panel>
<Panel id="finance-rules" title="Regras de lançamento">
<div className="grid gap-6">
<RuleForm
key={`${scope}:rule`}
identity={`${scope}:rule`}
basis={props.rules}
accounts={props.accounts.rows}
effects={props.effects}
/>
<HistoryRows
kind="configuration.rule"
rows={props.rules.rows}
labels={props.actions}
effects={props.effects}
/>
</div>
</Panel>
<Panel id="finance-history" title="Histórico da configuração">
<div className="grid gap-5">
{props.history.data.length === 0 ? (
<p>Sem alterações registadas neste percurso.</p>
) : (
props.history.data.map((event) => (
<article
key={event.id}
className="grid gap-3 border-b pb-5"
>
<h3 className="font-semibold">
Operador #{event.actor_id} ·{' '}
<time dateTime={event.created_at}>
{event.created_at}
</time>
</h3>
<p>{event.reason}</p>
<details>
<summary className="cursor-pointer font-medium">
Conferir alteração preservada
</summary>
<div className="mt-3 grid gap-4 sm:grid-cols-2">
<section>
<h4 className="mb-2 font-semibold">
Antes
</h4>
<HistoryRows
kind={event.kind}
rows={event.before.rows}
labels={props.actions}
effects={props.effects}
/>
</section>
<section>
<h4 className="mb-2 font-semibold">
Depois
</h4>
<HistoryRows
kind={event.kind}
rows={event.after.rows}
labels={props.actions}
effects={props.effects}
/>
</section>
</div>
</details>
</article>
))
)}
<Pagination
page={props.history}
label="Páginas do histórico financeiro"
/>
</div>
</Panel>
</div>
);
}
+13
View File
@@ -200,6 +200,7 @@ function ParameterFields({
approvalLevels, approvalLevels,
approvalLevelsReady = false, approvalLevelsReady = false,
expiryReady = false, expiryReady = false,
financeConfigurationReady = false,
urgentReviewsReady = false, urgentReviewsReady = false,
requisitionCategoryOptions = {}, requisitionCategoryOptions = {},
companyDetails, companyDetails,
@@ -234,6 +235,7 @@ function ParameterFields({
approvalLevels?: RequisitionApprovalPlan | null; approvalLevels?: RequisitionApprovalPlan | null;
approvalLevelsReady?: boolean; approvalLevelsReady?: boolean;
expiryReady?: boolean; expiryReady?: boolean;
financeConfigurationReady?: boolean;
urgentReviewsReady?: boolean; urgentReviewsReady?: boolean;
requisitionCategoryOptions?: Record<string, string>; requisitionCategoryOptions?: Record<string, string>;
companyDetails: CompanyDetails | null; companyDetails: CompanyDetails | null;
@@ -502,6 +504,17 @@ function ParameterFields({
</Link> </Link>
</li> </li>
)} )}
{financeConfigurationReady && (
<li>
<Link
className="font-medium underline underline-offset-4"
href="/administracao/financeiro"
>
Configuração financeira: acessos, contas e
períodos
</Link>
</li>
)}
{urgentReviewsReady && ( {urgentReviewsReady && (
<li> <li>
<Link <Link
+1 -1
View File
@@ -226,7 +226,7 @@ export default function Invoices({
className="m-6 inline-block underline" className="m-6 inline-block underline"
href="/obrigacoes-fornecedores" href="/obrigacoes-fornecedores"
> >
Obrigações a fornecedores — ensaio sintético Obrigações a fornecedores
</a> </a>
)} )}
<div className="mx-auto grid w-full max-w-6xl gap-6 p-6"> <div className="mx-auto grid w-full max-w-6xl gap-6 p-6">
+6 -2
View File
@@ -164,10 +164,14 @@ export default function OrderShow({
} }
/> />
<div className="rounded-xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100"> <div className="rounded-xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-100">
{snapshot.development_only !== false && (
<>
<strong> <strong>
Documento de desenvolvimento. Não autoriza compras Documento de desenvolvimento. Não autoriza
reais. compras reais.
</strong>{' '} </strong>{' '}
</>
)}
{snapshot.budget_checked === true {snapshot.budget_checked === true
? 'Controlo orçamental registado na emissão. ' ? 'Controlo orçamental registado na emissão. '
: 'Este documento não preserva confirmação do controlo orçamental. '}{' '} : 'Este documento não preserva confirmação do controlo orçamental. '}{' '}
+1
View File
@@ -111,6 +111,7 @@ export type PurchaseOrder = {
>; >;
import_tariffs?: Record<number, FrozenImportTariff>; import_tariffs?: Record<number, FrozenImportTariff>;
budget_checked?: boolean; budget_checked?: boolean;
development_only?: boolean;
agreement_bindings?: Record<string, FrozenOrderAgreement>; agreement_bindings?: Record<string, FrozenOrderAgreement>;
exchange_basis?: ExchangeBasis; exchange_basis?: ExchangeBasis;
reference_amounts?: { reference_amounts?: {
+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> <p>Subtotal sem IVA: {{ $money($order->subtotal_minor) }}<br>IVA: {{ $money($order->tax_minor) }}<br>Total com IVA: {{ $money($order->total_minor) }}</p>
@else @else
<p>{{ $snapshot['company']['name'] }} · {{ $snapshot['requisition']['number'] }}</p> <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) @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="notice">@if(($snapshot['development_only'] ?? true) !== false)<strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>@endif @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 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>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> <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>
+4 -1
View File
@@ -3,12 +3,12 @@
use App\Http\Controllers\AdministrativeGeographyController; use App\Http\Controllers\AdministrativeGeographyController;
use App\Http\Controllers\AgreementFollowupController; use App\Http\Controllers\AgreementFollowupController;
use App\Http\Controllers\AuditMetadataController; use App\Http\Controllers\AuditMetadataController;
use App\Http\Controllers\PrivateAuditController;
use App\Http\Controllers\AutomaticPurchaseController; use App\Http\Controllers\AutomaticPurchaseController;
use App\Http\Controllers\BudgetController; use App\Http\Controllers\BudgetController;
use App\Http\Controllers\BudgetReinforcementController; use App\Http\Controllers\BudgetReinforcementController;
use App\Http\Controllers\CandidatePortalController; use App\Http\Controllers\CandidatePortalController;
use App\Http\Controllers\CapitalRegisterController; use App\Http\Controllers\CapitalRegisterController;
use App\Http\Controllers\CommonFinanceAdministrationController;
use App\Http\Controllers\CommonStockReadController; use App\Http\Controllers\CommonStockReadController;
use App\Http\Controllers\CompanyController; use App\Http\Controllers\CompanyController;
use App\Http\Controllers\ConflictDeclarationController; use App\Http\Controllers\ConflictDeclarationController;
@@ -39,6 +39,7 @@ use App\Http\Controllers\OrganizationConfigurationController;
use App\Http\Controllers\PeopleHiringController; use App\Http\Controllers\PeopleHiringController;
use App\Http\Controllers\PeopleRegistryController; use App\Http\Controllers\PeopleRegistryController;
use App\Http\Controllers\PeopleReportController; use App\Http\Controllers\PeopleReportController;
use App\Http\Controllers\PrivateAuditController;
use App\Http\Controllers\ProcurementReportController; use App\Http\Controllers\ProcurementReportController;
use App\Http\Controllers\ProcurementReviewReportController; use App\Http\Controllers\ProcurementReviewReportController;
use App\Http\Controllers\ProcurementSearchController; use App\Http\Controllers\ProcurementSearchController;
@@ -388,6 +389,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('requisicoes/{requisition}/cotacoes', [QuotationController::class, 'store'])->name('quotations.store'); Route::post('requisicoes/{requisition}/cotacoes', [QuotationController::class, 'store'])->name('quotations.store');
Route::post('cotacoes/{quotation}/avaliar', [QuotationController::class, 'evaluate'])->name('quotations.evaluate'); Route::post('cotacoes/{quotation}/avaliar', [QuotationController::class, 'evaluate'])->name('quotations.evaluate');
Route::get('empresa', [CompanyController::class, 'index'])->name('company.index'); Route::get('empresa', [CompanyController::class, 'index'])->name('company.index');
Route::get('administracao/financeiro', [CommonFinanceAdministrationController::class, 'show']);
Route::post('administracao/financeiro/{kind}', [CommonFinanceAdministrationController::class, 'store'])->whereIn('kind', ['access', 'account', 'period', 'rule']);
Route::post('empresa/departamentos', [CompanyController::class, 'department'])->name('company.departments'); Route::post('empresa/departamentos', [CompanyController::class, 'department'])->name('company.departments');
Route::post('empresa/centros-de-custo', [CompanyController::class, 'costCenter'])->name('company.cost-centers'); Route::post('empresa/centros-de-custo', [CompanyController::class, 'costCenter'])->name('company.cost-centers');
Route::post('empresa/utilizadores', [CompanyController::class, 'user'])->name('company.users'); Route::post('empresa/utilizadores', [CompanyController::class, 'user'])->name('company.users');
+169
View File
@@ -0,0 +1,169 @@
<?php
use App\Services\StandaloneArtifact;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
if (! in_array('--apply-authorized', $argv, true)) {
throw new LogicException('EXPLICIT_STANDALONE_ACTIVATION_REQUIRED');
}
$proposalPath = $root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json';
$plan = json_decode(file_get_contents($proposalPath), true, 512, JSON_THROW_ON_ERROR);
$approval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$resultPath = $root.'/docs/proofs/compras-standalone-pilot-activation.json';
if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== $plan['scope']
|| ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $proposalPath)) || is_file($resultPath)) {
throw new LogicException('STANDALONE_ACTIVATION_AUTHORIZATION_OR_PREVIOUS_RESULT');
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$manifestPath = $root.'/public/build/manifest.json';
$before = file_get_contents($settingsPath);
$manifestBefore = file_get_contents($manifestPath);
$settings = json_decode($before, true, 32, JSON_THROW_ON_ERROR);
if (! hash_equals($plan['active_settings_sha256'], hash('sha256', $before))
|| ! hash_equals($plan['frontend']['previous_manifest_sha256'], hash('sha256', $manifestBefore))
|| $settings['APP_ENV'] !== 'payable-testing' || $settings['DB_HOST'] !== '127.0.0.1'
|| realpath($settings['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'], $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('STANDALONE_ACTIVATION_TARGET_CHANGED');
}
(new StandaloneArtifact)->verify($plan['runtime_directory'], $plan['runtime_manifest']);
$assets = $root.'/'.$plan['frontend']['candidate_root'];
$manifest = file_get_contents($assets.'/manifest.json');
if (! hash_equals($plan['frontend']['manifest_sha256'], hash('sha256', $manifest))) {
throw new LogicException('STANDALONE_ACTIVATION_FRONTEND_CHANGED');
}
foreach ($plan['frontend']['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('STANDALONE_ACTIVATION_ASSET_CONFLICT');
}
}
$after = [...$settings, ...$plan['proposed_runtime_settings']];
$protectedBefore = $settings;
$protectedAfter = $after;
foreach (array_keys($plan['proposed_runtime_settings']) as $key) {
unset($protectedBefore[$key], $protectedAfter[$key]);
}
if ($protectedBefore !== $protectedAfter || $settings['PAYABLE_SOURCE_INSTANCE'] !== $after['PAYABLE_SOURCE_INSTANCE']) {
throw new LogicException('STANDALONE_ACTIVATION_UNRELATED_SETTINGS');
}
$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
$directory = 'C:/laragon/data/compras/backups/activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
if (! mkdir($directory, 0700, true)) {
throw new LogicException('STANDALONE_ACTIVATION_BACKUP_UNAVAILABLE');
}
file_put_contents($directory.'/settings.before.private.json', $before, LOCK_EX);
file_put_contents($directory.'/manifest.before.json', $manifestBefore, LOCK_EX);
if (! hash_equals(hash('sha256', $before), hash_file('sha256', $directory.'/settings.before.private.json'))
|| ! hash_equals(hash('sha256', $manifestBefore), hash_file('sha256', $directory.'/manifest.before.json'))) {
throw new RuntimeException('STANDALONE_ACTIVATION_BACKUP_INCOMPLETE');
}
$envHash = hash_file('sha256', $root.'/.env');
$db = new PDO('pgsql:host=127.0.0.1;port='.(int) $settings['DB_PORT'].';dbname='.$settings['DB_DATABASE'],
$settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$frames = static function () use ($db): array {
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$result = [];
foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
$quoted = '"'.str_replace('"', '""', $table).'"';
$rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$result[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
$db->commit();
return $result;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
};
$baseline = $frames();
file_put_contents($directory.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
$replace = static function (string $path, string $bytes, string $expected): void {
if (! hash_equals($expected, hash_file('sha256', $path))) {
throw new LogicException('STANDALONE_ACTIVATION_CONCURRENT_EDIT');
}
$temporary = $path.'.standalone-'.bin2hex(random_bytes(6)).'.tmp';
$stream = fopen($temporary, 'x');
if ($stream === false) {
throw new RuntimeException('STANDALONE_ACTIVATION_STAGE_FAILED');
}
try {
if (fwrite($stream, $bytes) !== strlen($bytes) || ! fflush($stream)) {
throw new RuntimeException('STANDALONE_ACTIVATION_STAGE_INCOMPLETE');
}
} finally {
fclose($stream);
}
if (! hash_equals($expected, hash_file('sha256', $path)) || ! rename($temporary, $path)) {
throw new RuntimeException('STANDALONE_ACTIVATION_ATOMIC_REPLACE_FAILED');
}
};
$manifestChanged = $settingsChanged = false;
$report = ['date' => gmdate('c'), 'state' => 'in_progress', 'authorization' => 'compras-standalone-pilot-activation-authorization.json',
'target' => $plan['target'], 'backup_directory' => $directory, 'runtime_manifest' => $plan['runtime_manifest'],
'frontend_manifest' => $plan['frontend']['manifest_sha256'], 'new_grants_or_users' => false, 'business_commands' => false];
file_put_contents($directory.'/progress.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
try {
foreach ($plan['frontend']['files'] as $file => $hash) {
$destination = $root.'/public/build/'.$file;
if (! is_file($destination)) {
$out = fopen($destination, 'x');
if ($out === false) {
throw new RuntimeException('STANDALONE_ACTIVATION_ASSET_WRITE');
}
$bytes = file_get_contents($assets.'/'.$file);
try {
if (fwrite($out, $bytes) !== strlen($bytes)) {
throw new RuntimeException('STANDALONE_ACTIVATION_ASSET_INCOMPLETE');
}
} finally {
fclose($out);
}
}
if (! hash_equals($hash, hash_file('sha256', $destination))) {
throw new LogicException('STANDALONE_ACTIVATION_ASSET_COPY_CHANGED');
}
}
$replace($manifestPath, $manifest, hash('sha256', $manifestBefore));
$manifestChanged = true;
$replace($settingsPath, $encoded, hash('sha256', $before));
$settingsChanged = true;
$http = [];
foreach (['/avaliar', '/login'] as $path) {
$body = file_get_contents($plan['target'].$path, false, stream_context_create(['http' => ['timeout' => 5, 'follow_location' => 0, 'ignore_errors' => true]]));
if (! is_string($body) || ! preg_match('/^HTTP\/\S+ (200|302)\b/', $http_response_header[0] ?? '', $status)) {
throw new RuntimeException('STANDALONE_ACTIVATION_HTTP_FAILED');
}
$http[$path] = (int) $status[1];
}
if ($frames() !== $baseline || hash_file('sha256', $root.'/.env') !== $envHash
|| json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
throw new LogicException('STANDALONE_ACTIVATION_CONSERVATION_FAILED');
}
$report += ['capabilities_enabled' => count($plan['feature_names']), 'assets_verified' => count($plan['frontend']['files']),
'all_database_tables_preserved' => count($baseline), 'unrelated_settings_preserved' => true, 'source_instance_preserved' => true,
'public_env_preserved' => true, 'http' => $http, 'public_domain_runtime_activated' => false];
$report['state'] = 'passed';
} catch (Throwable $error) {
if ($settingsChanged) {
$replace($settingsPath, $before, hash('sha256', $encoded));
}
if ($manifestChanged) {
$replace($manifestPath, $manifestBefore, hash('sha256', $manifest));
}
$report['state'] = 'failed_configuration_and_manifest_restored';
$report['failure_class'] = get_class($error);
throw $error;
} finally {
file_put_contents($directory.'/result.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($resultPath, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
}
echo json_encode(['state' => $report['state'], 'capabilities_enabled' => $report['capabilities_enabled'],
'assets_verified' => $report['assets_verified'], 'database_tables_preserved' => $report['all_database_tables_preserved'],
'business_commands' => false, 'new_grants' => false], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,62 @@
<?php
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('READ_ONLY_ACTIVATION_PREFLIGHT_REQUIRED');
}
$root = dirname(__DIR__);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json'), true, 512, JSON_THROW_ON_ERROR);
$sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$source = json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR);
if (! hash_equals($plan['active_settings_sha256'], hash_file('sha256', $sourcePath))
|| $source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1'
|| realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| trim($source['PAYABLE_SOURCE_INSTANCE'] ?? '') === '') {
throw new LogicException('ACTIVATION_PREFLIGHT_SOURCE_CHANGED');
}
$assets = $root.'/'.$plan['frontend']['candidate_root'];
if (! hash_equals($plan['frontend']['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
|| ! hash_equals($plan['frontend']['previous_manifest_sha256'], hash_file('sha256', $root.'/public/build/manifest.json'))) {
throw new LogicException('ACTIVATION_PREFLIGHT_MANIFEST_CHANGED');
}
foreach ($plan['frontend']['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('ACTIVATION_PREFLIGHT_ASSET_MISMATCH');
}
}
$environment = [...$source, ...$plan['proposed_runtime_settings'], 'APP_ENV' => 'pilot-readonly', 'APP_DEBUG' => 'false',
'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-pilot-readonly-config.php', 'LOG_CHANNEL' => 'stderr'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
if ($db->selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
throw new LogicException('ACTIVATION_PREFLIGHT_DATABASE_NOT_READ_ONLY');
}
$runtime = app(StandaloneRuntime::class);
$runtime->configure($db);
$runtime->assertLoadedPackages();
if (! $runtime->enabled() || count(array_filter(StandaloneRuntime::FEATURES, fn ($name) => $runtime->requested($name))) !== 24) {
throw new LogicException('ACTIVATION_PREFLIGHT_CAPABILITIES_INCOMPLETE');
}
if (! hash_equals($plan['active_settings_sha256'], hash_file('sha256', $sourcePath))) {
throw new LogicException('ACTIVATION_PREFLIGHT_SETTINGS_CHANGED');
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'database_enforced_read_only' => true,
'all_24_capabilities_start_with_pinned_installed_packages' => true, 'source_instance_preserved' => true,
'frontend_assets_verified' => count($plan['frontend']['files']), 'active_settings_changed' => false,
'assets_published' => false, 'new_grants_or_business_commands' => false];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-activation-preflight.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,70 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use App\Services\StandaloneSchema;
use Illuminate\Database\PostgresConnection;
use Illuminate\Support\Str;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('EXPLICIT_READ_ONLY_CHECK_REQUIRED');
}
$root = dirname(__DIR__);
$proof = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation.json'), true, 32, JSON_THROW_ON_ERROR);
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if ($proof['state'] !== 'passed' || $proof['pilot_activation'] !== false || $source['APP_ENV'] !== 'payable-testing'
|| $source['DB_HOST'] !== '127.0.0.1' || realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('PILOT_INSTALLATION_READ_TARGET');
}
$pdo = new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$source['DB_DATABASE'],
$source['DB_USERNAME'], $source['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->beginTransaction();
try {
$pdo->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$db = new PostgresConnection($pdo, $source['DB_DATABASE'], '', ['driver' => 'pgsql', 'search_path' => 'public']);
$settings = ['enabled' => true, 'root' => $proof['runtime_directory'], 'manifest_sha256' => $proof['runtime_manifest'],
'installation_id' => $proof['installation_id'], 'features' => array_fill_keys(StandaloneRuntime::FEATURES, true)];
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->assertInstallation($db);
StandaloneSchema::verify($db->getSchemaBuilder(), $settings['features']);
if ((int) $pdo->query('SELECT count(*) FROM compras_runtime_installations')->fetchColumn() !== 1
|| filter_var($source['COMPRAS_RUNTIME_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
throw new LogicException('PILOT_INSTALLATION_RECEIPT_OR_ACTIVATION');
}
$wrong = $settings;
$wrong['installation_id'] = Str::uuid()->toString();
$rejected = false;
try {
(new StandaloneRuntime($wrong, new StandaloneArtifact))->assertInstallation($db);
} catch (LogicException $error) {
$rejected = $error->getMessage() === 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH';
}
if (! $rejected) {
throw new LogicException('PILOT_INSTALLATION_WRONG_ID_ACCEPTED');
}
$pdo->commit();
} finally {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
}
$http = [];
foreach (['/avaliar', '/login'] as $path) {
$headers = [];
$context = stream_context_create(['http' => ['timeout' => 5, 'follow_location' => 0, 'ignore_errors' => true]]);
$body = file_get_contents('http://127.0.0.1:8005'.$path, false, $context);
$headers = $http_response_header ?? [];
if (! is_string($body) || ! preg_match('/^HTTP\/\S+ (200|302)\b/', $headers[0] ?? '', $status)) {
throw new LogicException('PILOT_INSTALLATION_HTTP_UNAVAILABLE');
}
$http[$path] = (int) $status[1];
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'read_only_database_transaction' => true,
'receipt_and_non_elevated_binding_verified' => true, 'wrong_installation_id_refused' => true,
'all_24_module_schemas_verified' => true, 'runtime_activation_stays_disabled' => true, 'http' => $http,
'business_commands' => false, 'permission_changes' => false];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-installation-check.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+103
View File
@@ -0,0 +1,103 @@
<?php
// In-process GET validation only: existing actors, array sessions, pre-execution SQL write refusal.
// No routes, login shortcuts, users, grants or changes are installed by this checker.
use App\Models\User;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
if (! in_array('--read-only', $argv, true)) {
throw new LogicException('READ_ONLY_PROFILE_CHECK_REQUIRED');
}
$root = dirname(__DIR__);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation-proposal.json'), true, 512, JSON_THROW_ON_ERROR);
$result = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation.json'), true, 32, JSON_THROW_ON_ERROR);
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if ($result['state'] !== 'passed' || ($source['COMPRAS_RUNTIME_ENABLED'] ?? null) !== 'true'
|| $source['COMPRAS_RUNTIME_INSTALLATION_ID'] !== $plan['installation_id'] || $source['DB_HOST'] !== '127.0.0.1'
|| $source['APP_ENV'] !== 'payable-testing' || realpath($source['HOST_ROOT']) !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'], $match)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('ACTIVATED_PILOT_PROFILE_TARGET');
}
$environment = [...$source, 'PGOPTIONS' => '', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '',
'APP_DEBUG' => 'false', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null',
'MAIL_MAILER' => 'array', 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-profile-check.php', 'LOG_CHANNEL' => 'stderr'];
foreach ($environment as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require $root.'/bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$kernel->bootstrap();
$onlyReads = static function (string $sql): void {
if (! preg_match('/^\s*(SELECT\b|SHOW\b|SET\s+LOCAL\b|SET\s+CONSTRAINTS\b)/i', $sql)) {
throw new LogicException('PROFILE_CHECK_SQL_WRITE_REFUSED');
}
};
foreach (['UPDATE users SET name=name', 'DELETE FROM users', 'INSERT INTO users DEFAULT VALUES'] as $forbidden) {
$refused = false;
try {
$onlyReads($forbidden); // Test the guard without sending the statement to PostgreSQL.
} catch (LogicException $error) {
$refused = $error->getMessage() === 'PROFILE_CHECK_SQL_WRITE_REFUSED';
}
if (! $refused) {
throw new LogicException('PROFILE_CHECK_GUARD_REGRESSION');
}
}
DB::connection()->beforeExecuting($onlyReads);
$frames = static function (): array {
$out = [];
foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.str_replace('"', '""', $table->tablename).'" t ORDER BY row_to_json(t)::text');
$out[$table->tablename] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $out;
};
$before = $frames();
app(StandaloneRuntime::class)->assertLoadedPackages();
$results = [];
foreach (['admin', 'procurement', 'finance', 'warehouse'] as $role) {
$actor = User::query()->where('email', 'avaliacao-'.$role.'@example.test')->firstOrFail();
foreach (['/dashboard', '/requisicoes', '/projectos-imobilizado', '/ordens-operacionais', '/administracao/financeiro',
'/administracao/prazos-aprovacao', '/administracao/revisao-urgencias', '/requisicoes/urgencias/revisoes',
'/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa'] as $path) {
$app->forgetScopedInstances();
$request = Request::create('http://127.0.0.1:8005'.$path, 'GET', server: ['REMOTE_ADDR' => '127.0.0.1',
'HTTP_ACCEPT' => 'application/json', 'HTTP_X_INERTIA' => 'true']);
$app->instance('request', $request);
$request->headers->set('X-Inertia-Version', app(\App\Http\Middleware\HandleInertiaRequests::class)->version($request));
Auth::guard('web')->setUser($actor);
$session = app('session')->driver();
$session->start();
$session->put('work_context', ['user_id' => $actor->id, 'tenant_id' => $actor->tenant_id, 'key' => 'procurement.internal']);
$request->setLaravelSession($session);
$request->setUserResolver(fn () => $actor);
$response = $kernel->handle($request);
$status = $response->getStatusCode();
if (! in_array($status, [200, 403], true) || ($path === '/administracao/financeiro' && $status !== ($role === 'admin' ? 200 : 403))) {
throw new LogicException('PROFILE_CHECK_UNEXPECTED_STATUS:'.$role.':'.$path.':'.$status);
}
$page = json_decode($response->getContent(), true);
$navigation = $page['props']['commonFinanceNavigation'] ?? null;
if ($status === 200 && is_array($navigation) && $navigation['configuration'] !== ($role === 'admin')) {
throw new LogicException('PROFILE_CHECK_CONFIGURATION_VISIBILITY:'.$role);
}
$results[] = ['role' => $role, 'path' => $path, 'status' => $status, 'finance_navigation' => $navigation];
}
}
if ($frames() !== $before) {
throw new LogicException('PROFILE_CHECK_DATA_CHANGED');
}
$proof = ['date' => gmdate('c'), 'state' => 'passed', 'mode' => 'in_process_gets_existing_actors_array_sessions',
'sql_writes_refused_before_execution' => true, 'write_guard_regression_cases' => 3, 'all_tables_preserved' => count($before),
'new_grants_or_users' => false, 'business_commands' => false, 'results' => $results];
file_put_contents($root.'/docs/proofs/compras-standalone-pilot-profiles.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['state' => 'passed', 'profile_get_checks' => count($results), 'sql_write_guard_and_conservation' => true,
'new_grants_or_users' => false], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,215 @@
<?php
use App\Services\StandaloneArtifact;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
$install = in_array('--install-authorized-pilot', $argv, true);
if (! in_array('--run-authorized-private-copy', $argv, true) && ! $install) {
throw new LogicException('EXPLICIT_PRIVATE_RECOVERY_REQUIRED');
}
$proposalPath = $root.'/docs/proofs/compras-standalone-pilot-recovery-proposal.json';
$authorization = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-recovery-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if (($authorization['state'] ?? null) !== 'approved' || ($authorization['private_local_restore_only'] ?? null) !== true
|| ! hash_equals($authorization['proposal_sha256'], hash_file('sha256', $proposalPath))) {
throw new LogicException('PRIVATE_RECOVERY_AUTHORIZATION_MISMATCH');
}
$proposal = json_decode(file_get_contents($proposalPath), true, 32, JSON_THROW_ON_ERROR);
if ($install) {
$installPlan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$installApproval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
if (($installApproval['state'] ?? null) !== 'approved' || ($installApproval['scope'] ?? null) !== 'pilot_schema_and_pinned_runtime_only'
|| ! hash_equals($installApproval['proposal_sha256'], hash_file('sha256', $root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'))
|| is_file($root.'/docs/proofs/compras-standalone-pilot-installation.json')) {
throw new LogicException('PILOT_INSTALLATION_AUTHORIZATION_OR_PREVIOUS_RESULT');
}
}
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
$adminSettings = Dotenv\Dotenv::parse(file_get_contents($root.'/.env'));
if (($source['APP_ENV'] ?? null) !== 'payable-testing' || realpath($source['HOST_ROOT'] ?? '') !== realpath($root)
|| ($source['DB_HOST'] ?? null) !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $source['DB_DATABASE'] ?? '', $sourceMatch)
|| $source['DB_USERNAME'] !== 'payable_qa_'.$sourceMatch[1] || ($adminSettings['DB_CONNECTION'] ?? null) !== 'pgsql'
|| ($adminSettings['DB_HOST'] ?? null) !== '127.0.0.1' || $adminSettings['DB_PORT'] !== $source['DB_PORT']) {
throw new LogicException('PRIVATE_RECOVERY_SOURCE_IDENTITY');
}
$connect = static fn (string $database, string $user, string $password) => new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$database,
$user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db = $connect($source['DB_DATABASE'], $source['DB_USERNAME'], $source['DB_PASSWORD']);
$admin = $connect('postgres', $adminSettings['DB_USERNAME'], $adminSettings['DB_PASSWORD']);
$identity = $db->query('SELECT current_database() AS database_name,current_user AS role_name')->fetch(PDO::FETCH_ASSOC);
if ($identity['database_name'] !== $source['DB_DATABASE'] || $identity['role_name'] !== $source['DB_USERNAME']) {
throw new LogicException('PRIVATE_RECOVERY_SOURCE_MISMATCH');
}
$id = bin2hex(random_bytes(6));
$database = 'compras_private_restore_'.$id;
$role = 'compras_private_app_'.$id;
$password = bin2hex(random_bytes(32));
$installation = Str::uuid()->toString();
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-standalone-recovery-'.gmdate('Ymd-His').'-'.$id;
if (! mkdir($directory, 0700, true)) {
throw new LogicException('PRIVATE_RECOVERY_STORAGE_UNAVAILABLE');
}
$runtime = $root.'/storage/framework/testing/compras-standalone-80483320a54af6f1';
$artifact = new StandaloneArtifact;
$artifact->verify($runtime, $proposal['target']['runtime_manifest_sha256']);
if ($install) {
$archive = $runtime.'.zip';
if (! hash_equals($installPlan['runtime']['archive_sha256'], hash_file('sha256', $archive))) {
throw new LogicException('PILOT_INSTALLATION_ARCHIVE_CHANGED');
}
$target = $installPlan['runtime']['private_installation_directory'];
if ($target !== 'C:/laragon/data/compras/runtime/80483320a54af6f1') {
throw new LogicException('PILOT_INSTALLATION_PACKAGE_DESTINATION');
}
if (! is_dir($target)) {
if (! mkdir($target, 0700, true)) {
throw new LogicException('PILOT_INSTALLATION_PACKAGE_STORAGE');
}
$zip = new ZipArchive;
if ($zip->open($archive) !== true || ! $zip->extractTo($target)) {
throw new LogicException('PILOT_INSTALLATION_PACKAGE_EXTRACTION');
}
$zip->close();
}
$artifact->verify($target, $installPlan['runtime']['manifest_sha256']);
$runtime = $target;
}
$protectedFiles = [$root.'/.env', $root.'/public/build/manifest.json', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'];
$protectedHashes = array_map(static fn ($path) => hash_file('sha256', $path), $protectedFiles);
$fingerprint = static function (PDO $connection, array $columns): array {
$frames = [];
foreach ($columns as $table => $names) {
$quoted = implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = $connection->query('SELECT row_to_json(t)::text AS row FROM (SELECT '.$quoted.' FROM "'.str_replace('"', '""', $table).'") t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
$frames[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
}
return $frames;
};
$pg = static function (string $binary, array $arguments, string $user, string $password) use ($source): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'], 'PGUSER' => $user, 'PGPASSWORD' => $password], timeout: 120);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('PRIVATE_RECOVERY_'.$binary.'_FAILED');
}
};
$createdRole = $createdDatabase = false;
$report = ['date' => gmdate('c'), 'state' => 'in_progress', 'source_read_only' => true, 'source_writes' => false,
'private_backup_directory' => $directory, 'temporary_database' => $database, 'temporary_role' => $role,
'runtime_manifest' => $proposal['target']['runtime_manifest_sha256'], 'pilot_installation_or_activation' => false];
file_put_contents($directory.'/ownership.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
try {
$db->beginTransaction();
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$columns = [];
foreach ($db->query("SELECT table_name,column_name FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,ordinal_position")->fetchAll(PDO::FETCH_ASSOC) as $row) {
$columns[$row['table_name']][] = $row['column_name'];
}
$before = $fingerprint($db, $columns);
$originalMigrations = $db->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN);
$baseline = ['columns' => $columns, 'frames' => $before, 'migrations' => $originalMigrations];
file_put_contents($directory.'/baseline.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
$snapshot = $db->query('SELECT pg_export_snapshot()')->fetchColumn();
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$directory.'/before.dump', '--dbname='.$source['DB_DATABASE']], $source['DB_USERNAME'], $source['DB_PASSWORD']);
$db->commit();
$report['backup_sha256'] = hash_file('sha256', $directory.'/before.dump');
$admin->exec('CREATE ROLE "'.$role.'" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD '.$admin->quote($password));
$createdRole = true;
$admin->exec('CREATE DATABASE "'.$database.'" OWNER "'.$role.'" TEMPLATE template0');
$createdDatabase = true;
$pg('pg_restore', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='.$database, $directory.'/before.dump'], $role, $password);
$copy = $connect($database, $role, $password);
if ($fingerprint($copy, $columns) !== $before) {
throw new LogicException('PRIVATE_RECOVERY_INITIAL_DATA_MISMATCH');
}
$report['initial_tables_preserved'] = count($before);
$environment = ['APP_ENV' => 'private-recovery', 'APP_DEBUG' => 'false', 'APP_KEY' => 'base64:'.base64_encode(random_bytes(32)),
'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => $source['DB_PORT'],
'DB_DATABASE' => $database, 'DB_USERNAME' => $role, 'DB_PASSWORD' => $password,
'COMPRAS_RUNTIME_ROOT' => $runtime, 'COMPRAS_RUNTIME_SHA256' => $proposal['target']['runtime_manifest_sha256'],
'COMPRAS_RUNTIME_INSTALLATION_ID' => $installation, 'COMPRAS_RUNTIME_ENABLED' => 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY' => 'true',
'COMPRAS_RUNTIME_SYNTHETIC_ONLY' => 'false', 'COMMON_FINANCE_BUNDLE_ROOT' => '(null)', 'COMMON_FINANCE_BUNDLE_SHA256' => '(null)',
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'false', 'SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED' => 'false',
'COMMON_PAYABLES_PATH' => $runtime.'/payables', 'COMMON_BUDGET_PATH' => $runtime.'/budget-control', 'COMMON_PURCHASING_PATH' => $runtime.'/purchasing',
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array', 'BROADCAST_CONNECTION' => 'null',
'APP_CONFIG_CACHE' => $directory.'/absent-config.php', 'LOG_CHANNEL' => 'stderr',
'COMPRAS_INSTALLATION_BASELINE' => $directory.'/baseline.private.json'];
$process = new Process(['php', 'tests/Support/standalone-pilot-recovery-worker.php'], $root, $environment, timeout: 120);
$process->run();
file_put_contents($directory.'/worker.private.log', $process->getOutput().$process->getErrorOutput());
if (! $process->isSuccessful()) {
file_put_contents($directory.'/worker.private.log', $process->getOutput().$process->getErrorOutput());
throw new RuntimeException('PRIVATE_RECOVERY_WORKER_FAILED_PRIVATE_DIAGNOSTIC_SAVED');
}
$output = json_decode(trim($process->getOutput()), true);
if (! is_array($output) || ($output['verified'] ?? false) !== true) {
throw new RuntimeException('PRIVATE_RECOVERY_WORKER_INVALID_RESULT_PRIVATE_DIAGNOSTIC_SAVED');
}
$report['upgrade'] = $output;
$expectedMigrations = [...$originalMigrations, ...array_map(static fn ($path) => basename($path, '.php'),
array_keys($proposal['selected_normal_migrations_in_restored_copy_only']))];
sort($expectedMigrations, SORT_STRING);
if ($copy->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN) !== $expectedMigrations) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_HISTORY_CHANGED');
}
$report['historical_migration_records_preserved'] = true;
$after = $fingerprint($copy, $columns);
unset($after['migrations'], $before['migrations']);
if ($after !== $before) {
throw new LogicException('PRIVATE_RECOVERY_ORIGINAL_COLUMNS_CHANGED');
}
$report['original_business_tables_preserved'] = count($before);
if ($install) {
$pilotEnvironment = [...$environment, 'DB_DATABASE' => $source['DB_DATABASE'], 'DB_USERNAME' => $source['DB_USERNAME'],
'DB_PASSWORD' => $source['DB_PASSWORD'], 'COMPRAS_RUNTIME_INSTALLATION_ID' => Str::uuid()->toString(),
'COMPRAS_INSTALLATION_BASELINE' => $directory.'/baseline.private.json'];
$process = new Process(['php', 'tests/Support/standalone-pilot-recovery-worker.php', '--install-authorized-pilot'], $root, $pilotEnvironment, timeout: 120);
$process->run();
file_put_contents($directory.'/installation.private.log', $process->getOutput().$process->getErrorOutput());
$output = json_decode(trim($process->getOutput()), true);
if (! $process->isSuccessful() || ! is_array($output) || ($output['verified'] ?? false) !== true) {
throw new RuntimeException('PILOT_INSTALLATION_FAILED_PRIVATE_DIAGNOSTIC_SAVED');
}
$report['pilot_upgrade'] = $output;
$report['pilot_installation_or_activation'] = 'installation_only';
$report['pilot_activation'] = false;
$report['source_read_only'] = false;
$report['source_writes'] = 'five_selected_migrations_and_runtime_schema_receipt_only';
$report['runtime_directory'] = $runtime;
$report['installation_id'] = $pilotEnvironment['COMPRAS_RUNTIME_INSTALLATION_ID'];
if ($protectedHashes !== array_map(static fn ($path) => hash_file('sha256', $path), $protectedFiles)) {
throw new LogicException('PILOT_INSTALLATION_PROTECTED_FILES_CHANGED');
}
$report['active_settings_env_and_asset_manifest_preserved'] = true;
}
$report['state'] = 'passed';
} catch (Throwable $error) {
$report['state'] = 'failed';
$report['failure_class'] = get_class($error);
throw $error;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
$copy = null;
if ($createdDatabase) {
// Exact generated identifier, separately recorded before creation; never the source.
if ($database === $source['DB_DATABASE'] || ! preg_match('/^compras_private_restore_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('PRIVATE_RECOVERY_CLEANUP_TARGET');
}
$admin->exec('DROP DATABASE "'.$database.'"');
$report['temporary_database_removed'] = true;
}
if ($createdRole) {
$admin->exec('DROP ROLE "'.$role.'"');
$report['temporary_role_removed'] = true;
}
file_put_contents($directory.'/result.private.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($root.'/docs/proofs/'.($install ? 'compras-standalone-pilot-installation.json' : 'compras-standalone-pilot-recovery.json'), json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
}
echo json_encode(['state' => $report['state'], 'initial_tables_preserved' => $report['initial_tables_preserved'],
'original_business_tables_preserved' => $report['original_business_tables_preserved'], 'temporary_resources_removed' => true,
'source_writes' => $report['source_writes']], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,53 @@
<?php
use App\Services\StandaloneComponentSchema;
use Illuminate\Database\PostgresConnection;
// Metadata only. No application bootstrap, migrations, business rows or configuration writes.
if (! in_array('--inspect-pilot-schema', $argv, true)) {
throw new LogicException('Explicit read-only pilot schema inspection required.');
}
$root = dirname(__DIR__);
require $root.'/vendor/autoload.php';
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|| ($settings['DB_USERNAME'] ?? '') !== 'payable_qa_'.$match[1]
|| ! is_scalar($settings['DB_PORT'] ?? null) || ! ctype_digit((string) $settings['DB_PORT'])
|| (int) $settings['DB_PORT'] < 1 || (int) $settings['DB_PORT'] > 65535) {
throw new LogicException('Pilot metadata target identity mismatch.');
}
$db = new PDO('pgsql:host=127.0.0.1;port='.(int) $settings['DB_PORT'].';dbname='.$settings['DB_DATABASE'],
$settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$db->beginTransaction();
try {
$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity = $db->query('SELECT current_database() AS database_name, current_user AS role_name')->fetch(PDO::FETCH_ASSOC);
if ($identity['database_name'] !== $settings['DB_DATABASE'] || $identity['role_name'] !== $settings['DB_USERNAME']) {
throw new LogicException('Pilot metadata connection identity mismatch.');
}
$tables = [];
foreach ($db->query("SELECT table_name,column_name,data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,ordinal_position")->fetchAll(PDO::FETCH_ASSOC) as $row) {
$tables[$row['table_name']][] = ['name' => $row['column_name'], 'type' => $row['data_type'], 'nullable' => $row['is_nullable'] === 'YES'];
}
$migrations = $db->query('SELECT migration FROM migrations ORDER BY migration')->fetchAll(PDO::FETCH_COLUMN);
$connection = new PostgresConnection($db, $settings['DB_DATABASE'], '', ['driver' => 'pgsql', 'search_path' => 'public']);
$profiles = [];
foreach (array_keys(StandaloneComponentSchema::GROUPS) as $group) {
$profiles[$group] = StandaloneComponentSchema::inspect($connection, $group);
}
$report = ['checked_at' => gmdate('c'), 'environment' => 'http://127.0.0.1:8005', 'inspection_only' => true,
'consistent_read_only' => true, 'business_values_read' => false, 'configuration_or_permission_changes' => false,
'tables' => $tables, 'applied_migrations' => $migrations, 'component_profiles' => $profiles];
$db->commit();
$output = $root.'/docs/proofs/standalone-pilot-schema-inventory.json';
file_put_contents($output, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['inspection_only' => true, 'table_count' => count($tables), 'migrations' => count($migrations),
'business_values_read' => false, 'component_profiles' => $profiles,
'proof' => 'docs/proofs/standalone-pilot-schema-inventory.json'], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->inTransaction()) {
$db->rollBack();
}
}
+51 -17
View File
@@ -9,12 +9,17 @@ import { createServer } from 'node:net';
const id = crypto.randomBytes(6).toString('hex'); const id = crypto.randomBytes(6).toString('hex');
const workspace = path.resolve('C:/laragon/www/compras'); const workspace = path.resolve('C:/laragon/www/compras');
const standaloneOnly = process.argv.includes('--standalone-runtime-only'); const standaloneOnly = process.argv.includes('--standalone-runtime-only');
const standaloneBusiness = process.argv.includes('--standalone-business-only'); const financePreview = process.argv.includes('--standalone-finance-preview');
if (standaloneOnly && process.argv.slice(2).some(flag => flag !== '--standalone-runtime-only')) throw Error('Standalone composition requires its own isolated invocation'); const componentProfile = process.argv.includes('--standalone-component-profile');
if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== '--standalone-business-only')) throw Error('Standalone business regression requires its own isolated invocation'); if (componentProfile && (!standaloneOnly || financePreview)) throw Error('Component profile requires its own standalone invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-3320fac5a70fe44e'); if (financePreview && !standaloneOnly) throw Error('Finance preview requires the isolated standalone runtime');
const standalonePin = '3320fac5a70fe44ed54e11af90385b5da6b204ef854984cd934882a4378211e1'; const standaloneUpgrade = process.argv.includes('--standalone-upgrade-only');
const standaloneArchivePin = 'a544d5930feb916c4d4941ed8ef0b453985c1629720e9d0224bdbf0d322fb536'; const standaloneBusiness = process.argv.includes('--standalone-business-only') || standaloneUpgrade;
if (standaloneOnly && process.argv.slice(2).some(flag => !['--standalone-runtime-only', '--standalone-finance-preview', '--standalone-component-profile'].includes(flag))) throw Error('Standalone composition requires its own isolated invocation');
if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== (standaloneUpgrade ? '--standalone-upgrade-only' : '--standalone-business-only'))) throw Error('Standalone business regression requires its own isolated invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-80483320a54af6f1');
const standalonePin = '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7';
const standaloneArchivePin = 'bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76';
const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes=')); const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes='));
const reviewDurationMinutes = reviewDurationArgs.length === 0 ? 20 : Number(reviewDurationArgs[0].slice('--review-minutes='.length)); 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'); 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');
@@ -132,12 +137,19 @@ try {
if (fs.lstatSync(archive).isSymbolicLink() || crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== standaloneArchivePin) throw Error('Pinned standalone archive mismatch'); 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'); activeStandaloneRoot = path.join(root, 'runtime');
fs.mkdirSync(activeStandaloneRoot); 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 code = '$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==68||!$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' }); 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'); if (extracted.status !== 0 || extracted.stdout !== 'extracted') throw Error('Owned standalone extraction failed');
verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 66); verifyPrivateRuntime(activeStandaloneRoot, standalonePin, 67);
const uiTest = spawnSync(process.execPath, ['--test', 'tests/Support/financial-preparation.test.mjs'], {
cwd: workspace, windowsHide: true, encoding: 'utf8',
env: { ...process.env, COMPRAS_FINANCE_UI_PACKAGE_ROOT: activeStandaloneRoot },
});
if (uiTest.status !== 0) throw Error('Pinned financial preparation UI regression failed: '+(uiTest.stdout || uiTest.stderr || ''));
console.log(JSON.stringify({ pinned_financial_preparation_tests: 10, result: 'passed', extracted_runtime: true }));
} }
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', const environment = { ...process.env, APP_ENV: 'testing', APP_DEBUG: 'false', COMPRAS_RUNTIME_ENABLED: 'false', COMPRAS_RUNTIME_PREPARE_ONLY: 'false', COMPRAS_RUNTIME_SYNTHETIC_ONLY: 'true', 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', DB_DATABASE: database, DB_USERNAME: role, DB_PASSWORD: password, CACHE_STORE: 'array', SESSION_DRIVER: 'array',
MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null', MAIL_MAILER: 'array', QUEUE_CONNECTION: 'sync', BROADCAST_CONNECTION: 'null',
COMMON_BUDGET_PATH: standaloneOnly || standaloneBusiness ? path.join(activeStandaloneRoot, 'budget-control') : 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',
@@ -160,12 +172,14 @@ try {
delete environment.COMMON_FINANCE_BUNDLE_SHA256; delete environment.COMMON_FINANCE_BUNDLE_SHA256;
if (standaloneOnly || standaloneBusiness) { if (standaloneOnly || standaloneBusiness) {
environment.COMPRAS_RUNTIME_ENABLED = 'false'; environment.COMPRAS_RUNTIME_ENABLED = 'false';
environment.COMPRAS_RUNTIME_PREPARE_ONLY = 'true';
environment.COMMON_PAYABLES_PATH = path.join(activeStandaloneRoot, 'payables'); environment.COMMON_PAYABLES_PATH = path.join(activeStandaloneRoot, 'payables');
environment.COMMON_PURCHASING_PATH = path.join(activeStandaloneRoot, 'purchasing'); environment.COMMON_PURCHASING_PATH = path.join(activeStandaloneRoot, 'purchasing');
environment.COMPRAS_RUNTIME_ROOT = activeStandaloneRoot; environment.COMPRAS_RUNTIME_ROOT = activeStandaloneRoot;
environment.COMPRAS_RUNTIME_SHA256 = standalonePin; environment.COMPRAS_RUNTIME_SHA256 = standalonePin;
environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID(); environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness ? '1' : '0'; environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness ? '1' : '0';
environment.COMPRAS_STANDALONE_UPGRADE_QA = standaloneUpgrade ? '1' : '0';
} }
if (frozenRuntime) { if (frozenRuntime) {
environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot; environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot;
@@ -220,15 +234,23 @@ try {
if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition'); 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'); 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'); if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', standaloneUpgrade ? 'tests/Feature/StandaloneComponentUpgradeTest.php' : 'tests/Feature/StandaloneBusinessCompositionTest.php');
const result = spawnSync('php', args, { const result = spawnSync('php', args, {
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment, 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]')); if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((result.stderr || '').replaceAll(password, '[private]')); process.stderr.write((result.stderr || '').replaceAll(password, '[private]'));
process.exitCode = result.status === 0 ? 0 : 1; process.exitCode = result.status === 0 ? 0 : 1;
if (result.status === 0 && standaloneOnly) { if (result.status === 0 && componentProfile) {
const standaloneEnvironment = { ...environment, APP_ENV: 'standalone-qa', const profile = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, 'prepare-component-profile'], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'standalone-qa', SGC_STANDALONE_QA_ROOT: root },
});
process.stdout.write(profile.stdout || '');
process.stderr.write(profile.stderr || '');
if (profile.status !== 0 || !(profile.stdout || '').includes('synthetic_canonical_component_profiles')) throw Error('Canonical component profile fixture failed');
}
if (result.status === 0 && standaloneOnly && !componentProfile) {
const standaloneEnvironment = { ...environment, APP_ENV: 'standalone-qa', COMPRAS_RUNTIME_PREPARE_ONLY: 'false',
COMPRAS_RUNTIME_ROOT: activeStandaloneRoot, COMPRAS_RUNTIME_SHA256: standalonePin, COMPRAS_RUNTIME_ROOT: activeStandaloneRoot, COMPRAS_RUNTIME_SHA256: standalonePin,
COMPRAS_RUNTIME_INSTALLATION_ID: crypto.randomUUID(), SGC_STANDALONE_QA_ROOT: root, COMPRAS_RUNTIME_INSTALLATION_ID: crypto.randomUUID(), SGC_STANDALONE_QA_ROOT: root,
PAYABLE_SOURCE_INSTANCE: `standalone-synthetic-${id}`, PAYABLE_SOURCE_INSTANCE: `standalone-synthetic-${id}`,
@@ -238,11 +260,11 @@ try {
for (const feature of ['BUDGET_DISTRIBUTIONS', 'REQUISITION_ACCOUNTS', 'REQUISITION_EXPIRY', 'EXPENSE_ALLOCATIONS', 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', 'AGREEMENT_LIMITS', 'ORDER_PARTS', 'IMPORT_TARIFFS', 'IMPORT_LEGAL', 'IMPORT_DOSSIER', 'IMPORT_BANK_SUPPORT',
'IMPORT_READINESS', 'IMPORT_ESTIMATES', 'IMPORT_LANDED_COSTS', 'SUPPLIER_PAYABLES', 'GENERAL_LEDGER', 'IMPORT_READINESS', 'IMPORT_ESTIMATES', 'IMPORT_LANDED_COSTS', 'SUPPLIER_PAYABLES', 'GENERAL_LEDGER',
'SUPPLIER_SETTLEMENTS', 'GENERAL_LEDGER_CYCLE']) standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true'; 'SUPPLIER_SETTLEMENTS', 'GENERAL_LEDGER_CYCLE', 'FINANCE_CONFIGURATION']) standaloneEnvironment[`COMPRAS_${feature}_ENABLED`] = 'true';
for (const mode of ['prepare', 'verify']) { for (const mode of ['prepare', 'verify']) {
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], { const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: mode === 'verify' ? 'true' : 'false' }, env: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: mode === 'verify' ? 'true' : 'false', COMPRAS_RUNTIME_PREPARE_ONLY: mode === 'prepare' ? 'true' : 'false' },
}); });
process.stdout.write((check.stdout || '').replaceAll(password, '[private]')); process.stdout.write((check.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(password, '[private]')); process.stderr.write((check.stderr || '').replaceAll(password, '[private]'));
@@ -252,9 +274,10 @@ try {
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; } if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
} }
if (process.exitCode === 0) { if (process.exitCode === 0) {
for (const mode of ['reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old']) { for (const mode of ['reject-foreign', 'reject-pin', 'reject-prepare-pin', 'reject-dependency', 'reject-old']) {
const invalid = { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' }; const invalid = { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' };
if (mode === 'reject-pin') invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64); if (mode === 'reject-prepare-pin') { invalid.COMPRAS_RUNTIME_ENABLED = 'false'; invalid.COMPRAS_RUNTIME_PREPARE_ONLY = 'true'; }
if (mode === 'reject-pin' || mode === 'reject-prepare-pin') invalid.COMPRAS_RUNTIME_SHA256 = '0'.repeat(64);
if (mode === 'reject-dependency') invalid.COMPRAS_IMPORT_DOSSIER_ENABLED = 'false'; if (mode === 'reject-dependency') invalid.COMPRAS_IMPORT_DOSSIER_ENABLED = 'false';
if (mode === 'reject-old') { if (mode === 'reject-old') {
invalid.COMPRAS_RUNTIME_ROOT = path.join(workspace, 'storage/framework/testing/compras-standalone-730845de0bddd000'); invalid.COMPRAS_RUNTIME_ROOT = path.join(workspace, 'storage/framework/testing/compras-standalone-730845de0bddd000');
@@ -289,7 +312,7 @@ try {
if (mode === 'rebind') restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID(); if (mode === 'rebind') restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', restoreDatabase, mode], { const check = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', restoreDatabase, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024,
env: { ...restored, COMPRAS_RUNTIME_ENABLED: mode === 'rebind' ? 'false' : 'true' }, env: { ...restored, COMPRAS_RUNTIME_ENABLED: mode === 'rebind' ? 'false' : 'true', COMPRAS_RUNTIME_PREPARE_ONLY: mode === 'rebind' ? 'true' : 'false' },
}); });
process.stdout.write((check.stdout || '').replaceAll(restoredPassword, '[private]')); process.stdout.write((check.stdout || '').replaceAll(restoredPassword, '[private]'));
process.stderr.write((check.stderr || '').replaceAll(restoredPassword, '[private]')); process.stderr.write((check.stderr || '').replaceAll(restoredPassword, '[private]'));
@@ -299,6 +322,17 @@ try {
if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; } if (check.status !== 0 || receipt?.[expected] !== true) { process.exitCode = 1; break; }
} }
} }
if (process.exitCode === 0) {
const { verifyConfigurationConcurrency } = await import('./standalone-configuration-race.mjs');
await verifyConfigurationConcurrency(workspace, root, database, { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' });
}
if (process.exitCode === 0 && financePreview) {
const { reviewStandaloneFinance } = await import('./standalone-finance-preview.mjs');
await reviewStandaloneFinance({ workspace, root, database,
environment: { ...standaloneEnvironment, COMPRAS_RUNTIME_ENABLED: 'true' },
assets: path.join(privateParent, 'sgc-standalone-finance-help-qa-20261129'),
manifestPin: '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b' });
}
} }
if (result.status === 0 && raceOnly) { if (result.status === 0 && raceOnly) {
const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], { const race = spawnSync('php', ['tests/Concurrency/requisition-account-worker.php', database, 'race'], {
+50
View File
@@ -0,0 +1,50 @@
import fs from 'node:fs';
import path from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
export async function verifyConfigurationConcurrency(workspace, root, database, environment) {
if (environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false') throw Error('Verified standalone configuration required');
const worker = (mode, round) => {
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode, round], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment,
});
if (result.status !== 0) throw Error('Standalone configuration fixture/read worker failed');
return JSON.parse(result.stdout.trim());
};
for (const round of ['same', 'different']) {
if (worker('prepare-configuration-race', round).prepared !== true) throw Error('Race fixture not prepared');
const children = [0, 1].map(index => {
const child = spawn('php', ['tests/Support/standalone-runtime-worker.php', database, 'run-configuration-race', round, String(index)], {
cwd: workspace, windowsHide: true, env: environment,
});
let output = '';
child.stdout.on('data', chunk => { output += chunk.toString(); });
child.stderr.on('data', () => {});
const complete = new Promise(resolve => child.on('close', code => resolve({ code, output })));
return { child, complete };
});
try {
const until = Date.now() + 15000;
while (![0, 1].every(index => fs.existsSync(path.join(root, `configuration-${round}-${index}.ready`)))) {
if (Date.now() > until || children.some(({ child }) => child.exitCode !== null)) throw Error('Concurrent candidate workers did not reach the gate');
await new Promise(resolve => setTimeout(resolve, 20));
}
fs.writeFileSync(path.join(root, `configuration-${round}.go`), 'go', { flag: 'wx' });
const results = await Promise.race([
Promise.all(children.map(({ complete }) => complete)),
new Promise((_, reject) => { const timer = setTimeout(() => reject(Error('Concurrent candidate writers timed out')), 20000); timer.unref(); }),
]);
if (results.some(result => result.code !== 0)) throw Error('Concurrent candidate writer failed');
const outcomes = results.map(result => JSON.parse(result.output.trim()));
if (outcomes.filter(result => result.state === 'saved' && result.replayed === false).length !== 1
|| (round === 'same' ? outcomes.filter(result => result.state === 'saved' && result.replayed === true).length !== 1
: outcomes.filter(result => result.state === 'stale').length !== 1)) throw Error('Unexpected concurrent configuration outcome');
const proof = worker('read-configuration-race', round);
if (proof.verified !== true) throw Error('Concurrent configuration conservation missing');
console.log(JSON.stringify({ standalone_configuration_concurrency: true, ...proof, outcomes }));
} finally {
for (const { child } of children) if (child.exitCode === null) child.kill();
await Promise.all(children.map(({ complete }) => complete));
}
}
}
+69
View File
@@ -0,0 +1,69 @@
// Called only by the owned standalone QA runner after package/schema/recovery checks.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { createServer } from 'node:net';
export async function reviewStandaloneFinance({ workspace, root, database, environment, assets, manifestPin }) {
const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
const owned = fs.realpathSync(root);
const match = /^compras_standalone_qa_([a-f0-9]{12})$/.exec(database);
if (!match || path.dirname(owned) !== parent || path.basename(owned) !== `rq01-ledger-qa-${match[1]}`
|| environment.DB_DATABASE !== database || environment.DB_USERNAME !== `compras_standalone_app_${match[1]}`
|| environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false'
|| environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned synthetic standalone preview required');
const worker = mode => {
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment, maxBuffer: 1024 * 1024,
});
if (result.status !== 0) throw Error('Standalone UI fixture/conservation failed');
return JSON.parse(result.stdout.trim());
};
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) {
fs.mkdirSync(path.join(root, relative), { recursive: true });
}
const fixture = worker('prepare-ui');
if (fixture.ui_prepared !== true || fixture.no_initial_financial_grants !== true) throw Error('UI setup inherited grants');
const bytes = fs.readFileSync(path.join(assets, 'manifest.json'));
if (crypto.createHash('sha256').update(bytes).digest('hex') !== manifestPin) throw Error('Pinned UI build required');
for (const entry of Object.values(JSON.parse(bytes))) {
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('UI build entry missing');
}
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) {
fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
}
const port = await new Promise((resolve, reject) => {
const socket = createServer(); socket.on('error', reject);
socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
});
const url = `http://localhost:${port}`;
const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-qa-http-router.php'], {
cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
env: { ...environment, APP_URL: url, SGC_STANDALONE_QA_PORT: String(port), SESSION_DRIVER: 'file', SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false' },
});
try {
let ready = false;
for (let attempt = 0; attempt < 20 && !ready; attempt++) {
try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
}
if (!ready) throw Error('Standalone UI did not start');
const stop = path.join(root, 'stop-finance-review');
console.log(JSON.stringify({ standalone_finance_preview: true, url, stop_file: stop, manifest_sha256: manifestPin, ...fixture }));
const until = Date.now() + 20 * 60 * 1000;
while (!fs.existsSync(stop) && Date.now() < until) {
if (server.exitCode !== null) throw Error('Standalone UI stopped unexpectedly');
await new Promise(resolve => setTimeout(resolve, 200));
}
const proof = worker('read-ui');
if (proof.ui_conservation_verified !== true) throw Error('UI conservation not verified');
console.log(JSON.stringify(proof));
} finally {
if (server.exitCode === null) {
const closed = new Promise(resolve => server.once('exit', resolve));
server.kill(); await closed;
}
}
}
@@ -4,8 +4,10 @@ use App\Enums\PurchasingRole;
use App\Models\Budget; use App\Models\Budget;
use App\Models\Requisition; use App\Models\Requisition;
use App\Models\SupplyRecord; use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Services\CommonBudget; use App\Services\CommonBudget;
use App\Services\CommonFinanceAdministration;
use App\Services\CommonPaymentFacts; use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations; use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger; use App\Services\GeneralLedger;
@@ -21,6 +23,7 @@ use App\Services\SupplierPayables;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\Budget\BudgetFailure; use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php'; require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -36,6 +39,7 @@ beforeEach(function () {
} }
$settings = config('standalone-runtime'); $settings = config('standalone-runtime');
$settings['enabled'] = true; $settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true); $settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']); config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact); $runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
@@ -175,6 +179,9 @@ test('standalone financial pages use explicit read rights and refuse writes or d
'purchasing_role' => PurchasingRole::Finance]); 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->get('/api/supplier-payments')->assertForbidden(); $this->actingAs($finance)->get('/api/supplier-payments')->assertForbidden();
$this->get('/api/general-ledger/cycle')->assertForbidden(); $this->get('/api/general-ledger/cycle')->assertForbidden();
$this->withoutVite()->get('/dashboard')->assertOk()->assertInertia(fn ($page) => $page
->where('commonFinanceNavigation.payments', false)->where('commonFinanceNavigation.ledger', false)
->where('commonFinanceNavigation.configuration', false));
foreach (['view', 'payments_view', 'general_ledger.view'] as $action) { 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, 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]); 'user_id' => $finance->id, 'person' => 'synthetic-financial-reader-'.$finance->id, 'action' => $action]);
@@ -187,6 +194,9 @@ test('standalone financial pages use explicit read rights and refuse writes or d
->assertJsonPath('permissions.payment_prepare', false); ->assertJsonPath('permissions.payment_prepare', false);
$this->get('/supplier-payments')->assertOk()->assertHeader('Cache-Control', 'no-store, private'); $this->get('/supplier-payments')->assertOk()->assertHeader('Cache-Control', 'no-store, private');
$this->get('/api/general-ledger/cycle')->assertOk(); $this->get('/api/general-ledger/cycle')->assertOk();
$this->get('/dashboard')->assertOk()->assertInertia(fn ($page) => $page
->where('commonFinanceNavigation.payments', true)->where('commonFinanceNavigation.ledger', true)
->where('commonFinanceNavigation.configuration', false));
$this->get('/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/supplier-payments/payment-prepare', [])->assertForbidden();
$this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/general-ledger/prepare', [ $this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/general-ledger/prepare', [
@@ -205,11 +215,23 @@ test('standalone financial pages use explicit read rights and refuse writes or d
test('standalone candidate recognises one invoice and posts one balanced journal using explicitly configured own chart accounts', function () { test('standalone candidate recognises one invoice and posts one balanced journal using explicitly configured own chart accounts', function () {
$f = paymentFixture(); $f = paymentFixture();
$admin = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$configuration = function (string $kind, array $data) use ($admin) {
$this->actingAs($admin);
$service = app(CommonFinanceAdministration::class);
$space = $service->workspace($admin, $data['user_id'] ?? null);
$basis = $space[match ($kind) {
'access' => 'selectedAccess', 'account' => 'accounts', 'period' => 'periods', 'rule' => 'rules'
}];
return $service->save($admin, $kind, $data + ['operation_key' => (string) Str::uuid(),
'basis_hash' => $basis['hash'], 'reason' => 'Explicit synthetic company setup for the real financial cycle']);
};
foreach ([$f['author'], $f['validator']] as $actor) { 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) { $configuration('access', ['user_id' => $actor->id, 'person' => 'synthetic-independent-person-'.$actor->id,
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'actions' => ['view', 'prepare', 'validate', 'general_ledger.view', 'general_ledger.prepare', 'general_ledger.validate', 'general_ledger.post',
'user_id' => $actor->id, 'person' => 'synthetic-independent-person-'.$actor->id, 'action' => $action]); 'general_ledger.correct_prepare', 'general_ledger.correct_validate', 'general_ledger.correct_post',
} 'general_ledger.period_prepare', 'general_ledger.period_validate', 'general_ledger.period_close']]);
} }
$payables = app(SupplierPayables::class); $payables = app(SupplierPayables::class);
$this->actingAs($f['author']); $this->actingAs($f['author']);
@@ -220,15 +242,13 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$scope = ['tenant_id' => $f['author']->tenant_id, 'company_id' => 0, 'unit_id' => 0]; $scope = ['tenant_id' => $f['author']->tenant_id, 'company_id' => 0, 'unit_id' => 0];
$accounts = []; $accounts = [];
foreach (['630100' => 'Synthetic configured expense account', '420100' => 'Synthetic configured supplier account'] as $code => $label) { 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]); $accounts[] = $configuration('account', ['code' => (string) $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true])['id'];
} }
DB::table('gl_periods')->insert($scope + ['period_key' => 'EXPLICIT', 'version' => 1, 'starts_on' => today()->startOfYear()->toDateString(), $configuration('period', ['period_key' => 'EXPLICIT', 'starts_on' => today()->startOfYear()->toDateString(),
'ends_on' => today()->endOfYear()->toDateString(), 'status' => 'open', 'created_by' => $f['author']->id, 'ends_on' => today()->endOfYear()->toDateString()]);
'reason' => 'Explicit synthetic accounting period', 'created_at' => now()]); $configuration('rule', ['rule_key' => 'EXPLICIT-SUPPLIER', 'effect_type' => 'supplier_payable.recognised',
DB::table('gl_rules')->insert($scope + ['rule_key' => 'EXPLICIT-SUPPLIER', 'version' => 1, 'policy' => 'COMMON-PAYABLE-JOURNAL-v1', 'valid_from' => today()->startOfYear()->toDateString(), 'valid_to' => today()->endOfYear()->toDateString(),
'effect_type' => 'supplier_payable.recognised', 'currency' => 'MZN', 'valid_from' => today()->startOfYear()->toDateString(), 'debit_account_id' => $accounts[0], 'credit_account_id' => $accounts[1]]);
'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); $ledger = app(GeneralLedger::class);
$this->actingAs($f['author']); $this->actingAs($f['author']);
$input = ['obligation_id' => $validated['obligation_id'], 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT', $input = ['obligation_id' => $validated['obligation_id'], 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT',
@@ -244,6 +264,7 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$post = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Apply the independently reviewed synthetic journal']; $post = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Apply the independently reviewed synthetic journal'];
$ledger->engine($f['author'])->command('post', $post, $operation); $ledger->engine($f['author'])->command('post', $post, $operation);
DB::statement('SET CONSTRAINTS ALL IMMEDIATE'); DB::statement('SET CONSTRAINTS ALL IMMEDIATE');
DB::statement('SET CONSTRAINTS ALL DEFERRED');
expect($ledger->engine($f['author'])->command('post', $post, $operation)['replayed'])->toBeTrue() 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(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('debit_minor'))->toBe(6000)
@@ -252,6 +273,67 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$snapshot = json_decode(DB::table('gl_journals')->value('snapshot'), true, 128, JSON_THROW_ON_ERROR); $snapshot = json_decode(DB::table('gl_journals')->value('snapshot'), true, 128, JSON_THROW_ON_ERROR);
expect($snapshot['contract'])->toBe('COMMON-LEDGER-PAYABLE-v1') expect($snapshot['contract'])->toBe('COMMON-LEDGER-PAYABLE-v1')
->and(array_column($snapshot['lines'], 'account_id'))->toBe($accounts); ->and(array_column($snapshot['lines'], 'account_id'))->toBe($accounts);
$this->get('/general-ledger/cycle')->assertOk()->assertSee('EXPLICIT-SUPPLIER')->assertSee('EXPLICIT')
->assertDontSee('value="2026-10-29"', false)->assertDontSee('value="QA-PAYABLE-JOURNAL"', false);
$interval = http_build_query(['from_on' => today()->startOfYear()->toDateString(), 'to_on' => today()->toDateString()]);
$this->get('/general-ledger/trial-balance?'.$interval)->assertOk()
->assertSee('2 de 2 contas')->assertSee('60,00')->assertSee('print-context')
->assertSee('os totais abrangem todo o filtro');
$this->get('/general-ledger/account-ledger?'.$interval.'&account_id='.$accounts[0])->assertOk()
->assertSee('1 de 1 linhas')->assertSee('60,00')->assertSee(today()->toDateString());
$original = DB::table('gl_journals')->first();
$correctedAccount = DB::table('gl_accounts')->insertGetId($scope + ['code' => '630200',
'label' => 'Explicit synthetic corrected expense account', 'currency' => 'MZN', 'is_movement' => true]);
$baseRule = (array) DB::table('gl_rules')->first();
unset($baseRule['id']);
foreach ([['REVERSE', 'journal.reversal', $accounts[1], $accounts[0]],
['REPLACE', 'journal.replacement', $correctedAccount, $accounts[1]],
['BAD-REVERSE', 'journal.reversal', $accounts[0], $accounts[1]]] as [$key, $effect, $debit, $credit]) {
DB::table('gl_rules')->insert([...$baseRule, 'rule_key' => $key, 'effect_type' => $effect,
'debit_account_id' => $debit, 'credit_account_id' => $credit]);
}
$correctionInput = ['journal_id' => $original->id, 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT',
'reverse_rule_key' => 'REVERSE', 'replacement_rule_key' => 'REPLACE', 'reason' => 'Explicit synthetic correction of account classification'];
expect(fn () => $ledger->engine($f['author'])->command('correct-prepare', [...$correctionInput, 'reverse_rule_key' => 'BAD-REVERSE'], (string) Str::uuid()))
->toThrow(DomainException::class);
expect(DB::table('gl_proposals')->count())->toBe(1)->and(DB::table('gl_journals')->count())->toBe(1);
$correction = $ledger->engine($f['author'])->command('correct-prepare', $correctionInput, (string) Str::uuid());
$this->actingAs($f['validator']);
$ledger->engine($f['validator'])->command('correct-validate', ['correction_id' => $correction['correction_id'],
'revision' => $correction['revision'], 'decision' => 'approved', 'reason' => 'Independent review of both exact synthetic correction impacts'], (string) Str::uuid());
$this->actingAs($f['author']);
$correctionPost = ['correction_id' => $correction['correction_id'], 'revision' => $correction['revision'], 'reason' => 'Apply the independently reviewed synthetic pair'];
$correctionOperation = (string) Str::uuid();
$fault = function (string $checkpoint) {
if ($checkpoint === 'after_correction_first') {
throw new RuntimeException('SYNTHETIC_CORRECTION_INTERRUPTION');
}
};
expect(fn () => $ledger->engine($f['author'], $fault)->command('correct-post', $correctionPost, $correctionOperation))
->toThrow(RuntimeException::class, 'SYNTHETIC_CORRECTION_INTERRUPTION');
expect(DB::table('gl_journals')->count())->toBe(1)->and(DB::table('gl_correction_results')->count())->toBe(0);
$ledger->engine($f['author'])->command('correct-post', $correctionPost, $correctionOperation);
DB::statement('SET CONSTRAINTS ALL IMMEDIATE');
DB::statement('SET CONSTRAINTS ALL DEFERRED');
expect($ledger->engine($f['author'])->command('correct-post', $correctionPost, $correctionOperation)['replayed'])->toBeTrue()
->and((array) DB::table('gl_journals')->where('id', $original->id)->first())->toBe((array) $original)
->and(DB::table('gl_journals')->count())->toBe(3)->and(DB::table('gl_correction_results')->count())->toBe(1)
->and((int) DB::table('gl_lines')->where('account_id', $accounts[0])->sum('debit_minor')
- (int) DB::table('gl_lines')->where('account_id', $accounts[0])->sum('credit_minor'))->toBe(0)
->and((int) DB::table('gl_lines')->where('account_id', $correctedAccount)->sum('debit_minor'))->toBe(6000)
->and(DB::table('pa_obligations')->count())->toBe(1)->and((int) DB::table('pa_obligations')->sum('principal_minor'))->toBe(6000);
$check = $ledger->engine($f['author'])->command('period-prepare', ['period_key' => 'EXPLICIT', 'reason' => 'Synthetic close preparation after complete postings'], (string) Str::uuid());
$this->actingAs($f['validator']);
$ledger->engine($f['validator'])->command('period-validate', ['check_id' => $check['check_id'], 'revision' => $check['revision'],
'decision' => 'approved', 'reason' => 'Independent synthetic review of the closed-period evidence'], (string) Str::uuid());
$this->actingAs($f['author']);
$closeOperation = (string) Str::uuid();
$close = ['check_id' => $check['check_id'], 'revision' => $check['revision'], 'reason' => 'Apply the independently reviewed synthetic period closure'];
$ledger->engine($f['author'])->command('period-close', $close, $closeOperation);
expect($ledger->engine($f['author'])->command('period-close', $close, $closeOperation)['replayed'])->toBeTrue()
->and(DB::table('gl_period_closures')->count())->toBe(1)
->and(DB::table('gl_periods')->orderByDesc('version')->value('status'))->toBe('closed')
->and(DB::table('external_payments')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
}); });
test('common partial payment attribution uses explicit Finance categories without duplicate native payments and preserves reversed history', function () { test('common partial payment attribution uses explicit Finance categories without duplicate native payments and preserves reversed history', function () {
@@ -270,16 +352,23 @@ test('common partial payment attribution uses explicit Finance categories withou
$run = function (User $actor, string $action, array $data) use ($payables): array { $run = function (User $actor, string $action, array $data) use ($payables): array {
$this->actingAs($actor); $this->actingAs($actor);
return $payables->engine($actor)->settlements()->command($action, $data, (string) Str::uuid()); return $payables->settlements($actor)->command($action, $data, (string) Str::uuid());
}; };
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'], $paymentInput = ['obligation_id' => $recognised['obligation_id'],
'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), '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']); 'fact_reference' => 'DOC-COMMON-PARTIAL', 'evidence_reference' => 'DOC-COMMON-EVIDENCE', 'reason' => 'Explicit synthetic confirmed payment fact'];
$this->actingAs($f['author']);
expect(fn () => $payables->engine($f['author'])->settlements()->command('payment-prepare', $paymentInput, (string) Str::uuid()))
->toThrow(InvalidArgumentException::class);
expect(DB::table('ps_payments')->count())->toBe(0);
$payment = $run($f['author'], 'payment-prepare', $paymentInput);
$paymentSnapshot = json_decode(DB::table('ps_payments')->where('id', $payment['payment_id'])->value('snapshot'), true, 32, JSON_THROW_ON_ERROR);
expect($paymentSnapshot['synthetic_only'])->toBeTrue();
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed', $run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-COMMON-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']); 'evidence_reference' => 'DOC-COMMON-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
$report = fn () => app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->whereKey($f['r']->id), null, null); $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([]); 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', $allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DOC-ALLOCATION-EXPLICIT',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']], 'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
'reason' => 'Explicit synthetic invoice allocation of the confirmed payment']); 'reason' => 'Explicit synthetic invoice allocation of the confirmed payment']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed', $run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
@@ -347,7 +436,7 @@ test('one common payment shared across two invoices is counted once while explic
$run = function (User $actor, string $action, array $data) use ($adapter): array { $run = function (User $actor, string $action, array $data) use ($adapter): array {
$this->actingAs($actor); $this->actingAs($actor);
return $adapter->engine($actor)->settlements()->command($action, $data, (string) Str::uuid()); return $adapter->settlements($actor)->command($action, $data, (string) Str::uuid());
}; };
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $obligations[0]['obligation_id'], 'source_revision' => $obligations[0]['source_revision'], $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', 'amount' => '70.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'SIM-TWO-INVOICES',
@@ -376,3 +465,100 @@ test('one common payment shared across two invoices is counted once while explic
->and(DB::table('ps_payments')->count())->toBe(1)->and(DB::table('ps_allocations')->count())->toBe(2) ->and(DB::table('ps_payments')->count())->toBe(1)->and(DB::table('ps_allocations')->count())->toBe(2)
->and(DB::table('external_payments')->count())->toBe(0); ->and(DB::table('external_payments')->count())->toBe(0);
}); });
test('company finance configuration requires an administrator and records explicit access with safe replay and revocation', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $admin->tenant_id, 'department_id' => $admin->department_id,
'purchasing_role' => PurchasingRole::Finance]);
$service = app(CommonFinanceAdministration::class);
$this->actingAs($finance)->get('/administracao/financeiro')->assertForbidden();
$before = DB::table('pa_access')->count();
$this->actingAs($admin);
$space = $service->workspace($admin, $finance->id);
expect($space['selectedAccess']['actions'])->toBe([])->and(DB::table('pa_access')->count())->toBe($before);
$payload = ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['selectedAccess']['hash'],
'reason' => 'Explicit synthetic company financial access', 'user_id' => $finance->id,
'person' => 'synthetic-person-finance', 'actions' => ['view', 'payments_view']];
$result = $service->save($admin, 'access', $payload);
expect($result['replayed'])->toBeFalse()->and($service->save($admin, 'access', $payload)['replayed'])->toBeTrue()
->and(DB::table('pa_access')->where('user_id', $finance->id)->count())->toBe(2)
->and(DB::table('gl_events')->where('kind', 'configuration.access')->count())->toBe(1);
expect(fn () => $service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'actions' => ['view']]))
->toThrow(DomainException::class);
$finance->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
$fresh = $service->workspace($admin, $finance->id);
expect($fresh['selectedAccess']['eligible'])->toBeFalse();
expect(fn () => $service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'basis_hash' => $fresh['selectedAccess']['hash']]))
->toThrow(ValidationException::class);
$service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'basis_hash' => $fresh['selectedAccess']['hash'], 'actions' => [], 'person' => '']);
expect(DB::table('pa_access')->where('user_id', $finance->id)->count())->toBe(0)
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
});
test('company finance configuration creates own chart periods and versioned rules without financial postings', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$service = app(CommonFinanceAdministration::class);
$this->actingAs($admin);
$save = function (string $kind, array $data) use ($service, $admin) {
$space = $service->workspace($admin);
return $service->save($admin, $kind, $data + ['operation_key' => (string) Str::uuid(),
'basis_hash' => $space[match ($kind) {
'account' => 'accounts', 'period' => 'periods', 'rule' => 'rules'
}]['hash'],
'reason' => 'Explicit synthetic own company financial configuration']);
};
$debit = $save('account', ['code' => '32001', 'label' => 'Synthetic inventory', 'currency' => 'MZN', 'is_movement' => true]);
$credit = $save('account', ['code' => '42001', 'label' => 'Synthetic suppliers', 'currency' => 'MZN', 'is_movement' => true]);
expect(fn () => $save('account', ['code' => '32001', 'label' => 'Duplicate', 'currency' => 'MZN', 'is_movement' => true]))->toThrow(DomainException::class);
$save('period', ['period_key' => 'OWN-2026', 'starts_on' => '2026-01-01', 'ends_on' => '2026-12-31']);
expect(fn () => $save('period', ['period_key' => 'OVERLAP', 'starts_on' => '2026-12-01', 'ends_on' => '2027-01-31']))->toThrow(DomainException::class);
$rule = ['rule_key' => 'OWN-SUPPLIER', 'effect_type' => 'supplier_payable.recognised', 'valid_from' => '2026-01-01',
'valid_to' => '2026-12-31', 'debit_account_id' => $debit['id'], 'credit_account_id' => $credit['id']];
$save('rule', $rule);
$save('rule', $rule);
expect(DB::table('gl_rules')->where('rule_key', 'OWN-SUPPLIER')->orderBy('version')->pluck('version')->all())->toBe([1, 2]);
expect(fn () => $save('rule', [...$rule, 'credit_account_id' => $debit['id']]))->toThrow(ValidationException::class);
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0)
->and(DB::table('stock_movements')->count())->toBe(0);
$this->withoutVite()->actingAs($admin)->get('/administracao/financeiro')->assertOk()
->assertInertia(fn ($page) => $page->component('company/finance')->has('accounts.rows', 2)->has('rules.rows', 2)
->where('commonFinanceNavigation.configuration', true)->where('commonFinanceNavigation.payments', false)
->where('commonFinanceNavigation.ledger', false))
->assertHeader('Cache-Control', 'max-age=0, no-store, private');
});
test('financial configuration HTTP rejects foreign targets and preserves permissions belonging to another contract', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $admin->tenant_id, 'department_id' => $admin->department_id,
'purchasing_role' => PurchasingRole::Finance]);
$foreign = User::factory()->create(['tenant_id' => Tenant::query()->create(['name' => 'Other synthetic company'])->id,
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($admin);
$service = app(CommonFinanceAdministration::class);
DB::table('pa_access')->insert(['tenant_id' => $admin->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $finance->id, 'person' => 'shared-synthetic-person', 'action' => 'other-contract.read']);
$space = $service->workspace($admin, $finance->id);
$payload = ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['selectedAccess']['hash'],
'reason' => 'Explicit synthetic configuration HTTP test', 'user_id' => $finance->id,
'person' => 'shared-synthetic-person', 'actions' => ['view']];
$this->get('/administracao/financeiro?user='.$foreign->id)->assertNotFound();
$this->postJson('/administracao/financeiro/access', [...$payload, 'user_id' => $foreign->id])->assertNotFound();
$this->postJson('/administracao/financeiro/access', [...$payload, 'person' => 'changed-synthetic-person'])->assertConflict();
$this->from('/administracao/financeiro?user='.$finance->id)->post('/administracao/financeiro/access', $payload)->assertRedirect();
$events = DB::table('gl_events')->count();
$this->postJson('/administracao/financeiro/access', $payload)->assertRedirect();
expect(DB::table('gl_events')->count())->toBe($events);
$stale = [...$payload, 'operation_key' => (string) Str::uuid()];
$this->postJson('/administracao/financeiro/access', $stale)->assertConflict();
$this->withHeader('X-Inertia', 'true')->post('/administracao/financeiro/access', $stale)
->assertRedirect()->assertSessionHasErrors('configuration');
$fresh = $service->workspace($admin, $finance->id);
$service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(),
'basis_hash' => $fresh['selectedAccess']['hash'], 'actions' => [], 'person' => '']);
expect(DB::table('pa_access')->where('user_id', $finance->id)->pluck('action')->all())->toBe(['other-contract.read'])
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
});
@@ -0,0 +1,138 @@
<?php
use App\Services\BudgetDistributionSchema;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneComponentSchema;
use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\Payables\SettlementSchema;
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_UPGRADE_QA') !== '1') {
$this->markTestSkipped('Use the owned standalone upgrade 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())
|| config('standalone-runtime.enabled') === true || config('standalone-runtime.prepare_only') !== true) {
throw new LogicException('Owned synthetic legacy component fixture required.');
}
BudgetDistributionSchema::install();
SettlementSchema::install();
config(['common-payables.source_instance' => 'synthetic-legacy-component-upgrade']);
$this->installer = app(StandaloneInstallation::class);
$this->arguments = [DB::connection()->getDatabaseName(), DB::connection()->getConfig('username'),
'Synthetic named upgrade operator', 'Explicit synthetic preservation of recognised canonical components'];
});
test('existing canonical components require explicit selection and unknown or partial structures are refused before writes', function () {
expect(StandaloneComponentSchema::reusable(DB::connection()))->toBe(array_keys(StandaloneComponentSchema::SUPPORTED));
expect(fn () => $this->installer->prepare(...[...$this->arguments, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_EXTENSION_SCHEMA_EXISTS');
expect(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse();
DB::statement('ALTER TABLE ps_payments DISABLE TRIGGER ps_history_immutable');
expect(fn () => $this->installer->prepare(...[...$this->arguments, false, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
DB::statement('ALTER TABLE ps_payments ENABLE TRIGGER ps_history_immutable');
DB::statement('ALTER TABLE ps_payments ADD COLUMN unknown_contract text');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
DB::statement('ALTER TABLE ps_payments DROP COLUMN unknown_contract');
DB::statement('ALTER TABLE ps_outbox RENAME TO ps_outbox_unsupported');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
expect(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse();
});
test('explicit component upgrade preserves an independently confirmed partial payment and all original columns', function () {
$f = paymentFixture();
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-upgrade-person-'.$actor->id, 'action' => $action]);
}
}
$payables = app(SupplierPayables::class);
$this->actingAs($f['author']);
$proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Legacy synthetic invoice capture', (string) Str::uuid());
$this->actingAs($f['validator']);
$recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent legacy recognition', (string) Str::uuid());
$run = function ($actor, $action, $data) use ($payables) {
$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-UPGRADE-PAYMENT', 'evidence_reference' => 'SIM-UPGRADE-EVIDENCE', 'reason' => 'Existing synthetic partial payment']);
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-UPGRADE-CONFIRMED', 'reason' => 'Independent legacy payment confirmation']);
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-UPGRADE-ALLOCATION',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
'reason' => 'Explicit legacy invoice allocation']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
'reason' => 'Independent legacy allocation confirmation']);
$columns = $before = [];
foreach (DB::getSchemaBuilder()->getTableListing() as $table) {
$columns[$table] = DB::getSchemaBuilder()->getColumnListing($table);
$before[$table] = DB::table($table)->select($columns[$table])->orderByRaw('1')->get()->toJson();
}
$prepare = function (bool $apply): array {
$arguments = ['--expected-database' => $this->arguments[0], '--expected-role' => $this->arguments[1],
'--operator' => $this->arguments[2], '--reason' => $this->arguments[3], '--reuse-components' => true];
if ($apply) {
$arguments['--apply'] = true;
}
expect(Artisan::call('compras:runtime:prepare', $arguments))->toBe(0);
return json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
};
$preview = $prepare(false);
expect($preview['written'])->toBeFalse()->and($preview['existing_components'])->toBe(array_keys(StandaloneComponentSchema::SUPPORTED))
->and(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse();
$applied = $prepare(true);
expect($applied['state'])->toBe('prepared')->and($applied['written'])->toBeTrue();
expect($prepare(true)['state'])->toBe('already_prepared');
foreach ($before as $table => $expected) {
expect(DB::table($table)->select($columns[$table])->orderByRaw('1')->get()->toJson(), $table)->toBe($expected);
}
expect(DB::table('compras_runtime_installations')->count())->toBe(1)
->and(DB::table('compras_runtime_installations')->value('reason'))->toContain('supplier-settlements-v1')
->and(DB::table('ps_proposals')->where('id', $allocation['proposal_id'])->value('allocation_cycle'))->toBe(0);
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
config(['standalone-runtime' => $settings]);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
app()->instance(StandaloneRuntime::class, $runtime);
$runtime->configure(DB::connection());
$this->actingAs($f['validator']);
$listing = $payables->settlements($f['validator'])->listing();
expect($listing['payments'])->toHaveCount(1)->and($listing['allocations'])->toHaveCount(1)
->and($listing['payments'][0]['amount_minor'])->toBe(4000)
->and($payables->engine($f['validator'])->positionForSource($f['invoice']->id)['balance_minor'])->toBe(2000)
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('external_payments')->count())->toBe(0);
});
test('a failure during additive component upgrade rolls back all new schema and permits one safe retry', function () {
DB::statement('CREATE VIEW ps_reversals AS SELECT 1 AS synthetic_conflict');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(QueryException::class);
expect(StandaloneComponentSchema::reusable(DB::connection()))->toBe(array_keys(StandaloneComponentSchema::SUPPORTED))
->and(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('budget_order_commands'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasColumn('ps_proposals', 'allocation_cycle'))->toBeFalse();
DB::statement('DROP VIEW ps_reversals');
expect($this->installer->prepare(...[...$this->arguments, true, false, true])['state'])->toBe('prepared')
->and(DB::table('compras_runtime_installations')->count())->toBe(1);
});
@@ -0,0 +1,86 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Tenant;
use App\Models\User;
use App\Services\CommonFinanceAdministration;
use App\Services\StandaloneRuntime;
use Illuminate\Support\Str;
// Included only after the standalone worker validates its own QA cluster/root/role.
$runtime = app(StandaloneRuntime::class);
$runtime->assertInstallation($db);
$runtime->assertLoadedPackages();
if (! $runtime->syntheticOnly() || ! in_array($argv[3] ?? '', ['same', 'different'], true)) {
throw new LogicException('Explicit synthetic configuration race required.');
}
$round = $argv[3];
$file = $root.'/configuration-race-'.$round.'.json';
$frames = static function () use ($db): array {
$rows = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_journals', 'gl_lines', 'ps_payments', 'ps_allocations'] as $table) {
$rows[$table] = hash('sha256', $db->table($table)->orderBy('id')->get()->toJson());
}
return $rows;
};
if ($mode === 'prepare-configuration-race') {
if (is_file($file)) {
throw new LogicException('Configuration race already prepared.');
}
$tenant = Tenant::query()->create(['name' => 'Synthetic configuration concurrency '.$round]);
$actor = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
auth()->guard()->setUser($actor);
$basis = app(CommonFinanceAdministration::class)->workspace($actor)['accounts']['hash'];
$command = ['basis_hash' => $basis, 'reason' => 'Synthetic concurrent company account configuration',
'code' => 'RACE-OWN', 'label' => 'Synthetic movement account', 'currency' => 'MZN', 'is_movement' => true];
$key = (string) Str::uuid();
file_put_contents($file, json_encode(['actor_id' => $actor->id, 'tenant_id' => $tenant->id, 'frames' => $frames(),
'commands' => [$command + ['operation_key' => $key], $command + ['operation_key' => $round === 'same' ? $key : (string) Str::uuid()]]], JSON_THROW_ON_ERROR));
echo json_encode(['prepared' => true], JSON_THROW_ON_ERROR);
exit;
}
$saved = json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($saved['actor_id']);
auth()->guard()->setUser($actor);
if ($mode === 'run-configuration-race') {
$index = $argv[4] ?? '';
if (! in_array($index, ['0', '1'], true)) {
throw new LogicException('Two explicit concurrent actors required.');
}
file_put_contents($root.'/configuration-'.$round.'-'.$index.'.ready', 'ready');
$until = microtime(true) + 20;
while (! is_file($root.'/configuration-'.$round.'.go')) {
if (microtime(true) > $until) {
throw new LogicException('Configuration concurrency gate timed out.');
}
usleep(10000);
}
try {
$result = app(CommonFinanceAdministration::class)->save($actor, 'account', $saved['commands'][(int) $index]);
echo json_encode(['state' => 'saved', 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (DomainException $error) {
// A conflicting preparation must be rejected, not silently rewritten.
if ($round !== 'different' || ! str_contains($error->getMessage(), 'configuração mudou')) {
throw $error;
}
echo json_encode(['state' => 'stale'], JSON_THROW_ON_ERROR);
}
exit;
}
if ($mode !== 'read-configuration-race') {
throw new LogicException('Unknown configuration concurrency mode.');
}
$db->transaction(function () use ($db, $saved, $frames) {
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
if ($saved['frames'] !== $frames() || $db->table('gl_accounts')->where('tenant_id', $saved['tenant_id'])->count() !== 1
|| $db->table('gl_commands')->where('tenant_id', $saved['tenant_id'])->count() !== 1
|| $db->table('gl_events')->where('tenant_id', $saved['tenant_id'])->where('kind', 'configuration.account')->count() !== 1
|| $db->table('pa_access')->where('tenant_id', $saved['tenant_id'])->exists()
|| $db->table('audit_logs')->where('tenant_id', $saved['tenant_id'])->where('action', 'company.finance_configuration_changed')->count() !== 1) {
throw new LogicException('Concurrent configuration duplicated a record or changed protected facts.');
}
});
echo json_encode(['verified' => true, 'round' => $round, 'one_account_command_event_audit' => true,
'protected_financial_stock_frames' => 8, 'no_automatic_grants' => true], JSON_THROW_ON_ERROR);
exit;
@@ -0,0 +1,113 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import test from 'node:test';
import assert from 'node:assert/strict';
const root = process.env.COMPRAS_FINANCE_UI_PACKAGE_ROOT;
if (!root) throw Error('Explicit verified candidate package root required');
function workspace(file, host = true) {
const forms = [0, 1].map(() => ({
dataset: { action: file.startsWith('general-ledger') ? 'prepare' : 'payment-prepare' },
values: new Map([['reason', '']]), button: { disabled: false }, appended: [],
querySelector(selector) { return selector === 'button' ? this.button : null; },
querySelectorAll(selector) { return selector === 'button' ? [this.button] : []; },
append(...nodes) { this.appended.push(...nodes); },
}));
const nodes = Object.fromEntries(['#finance', '#reload', '#status', '#error', 'main'].map(id => [id, { textContent: '', focus() {}, prepend() {} }]));
const events = new Map();
const state = { reloads: 0, requests: [], response: async () => ({ ok: true, json: async () => ({ state: 'saved' }) }) };
const settings = { api: '/api/supplier-payments', csrf: 'synthetic', host_journal_policy: host, host_settlement_policy: host };
const source = readFileSync(path.join(root, file), 'utf8');
const script = source.match(/<script>([\s\S]*?)<\/script>/)[1]
.replace(/const settings=<\?=[\s\S]*?\?>;/, `const settings=${JSON.stringify(settings)};`);
let key = 0;
const context = vm.createContext({
document: {
querySelector: selector => nodes[selector],
querySelectorAll: selector => selector === '[data-action]' ? forms : [],
createElement: () => ({ textContent: '', setAttribute() {} }),
},
FormData: class { constructor(form) { this.form = form; } [Symbol.iterator]() { return this.form.values.entries(); } },
window: { addEventListener: (event, callback) => events.set(event, callback) },
location: { reload: () => state.reloads++, assign() {} },
crypto: { randomUUID: () => `synthetic-operation-${++key}` },
fetch: async (url, options) => { state.requests.push({ url, ...options }); return state.response(); },
});
vm.runInContext(script, context);
const leaving = () => {
const event = { prevented: false, preventDefault() { this.prevented = true; } };
events.get('beforeunload')?.(event);
return event.prevented;
};
const submit = form => form.onsubmit({ preventDefault() {} });
return { forms, state, leaving, submit, nodes };
}
for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php']) {
test(`${file}: only an edited preparation warns before leaving`, () => {
const w = workspace(file);
assert.equal(w.leaving(), false);
w.forms[0].values.set('reason', 'Explicit synthetic draft');
assert.equal(w.leaving(), true);
w.forms[0].values.set('reason', '');
assert.equal(w.leaving(), false);
});
test(`${file}: successful command keeps the other form draft and provides explicit refresh`, async () => {
const w = workspace(file);
w.forms[0].values.set('reason', 'Complete this synthetic command');
w.forms[1].values.set('reason', 'Preserve this separate preparation');
await w.submit(w.forms[0]);
assert.equal(w.state.reloads, 0);
assert.equal(w.forms[0].button.disabled, true);
assert.equal(w.forms[1].values.get('reason'), 'Preserve this separate preparation');
assert.equal(w.leaving(), true);
assert.equal(w.forms[0].appended.length, 2);
assert.match(w.forms[0].appended[0].textContent, /registada/);
assert.equal(w.forms[0].appended[1].type, 'button');
await w.submit(w.forms[0]);
assert.equal(w.state.requests.length, 1);
await w.submit(w.forms[1]);
assert.equal(w.state.reloads, 1);
assert.equal(w.leaving(), false);
});
test(`${file}: unknown network result preserves values and retries the same command identity`, async () => {
const w = workspace(file);
w.forms[0].values.set('reason', 'Do not lose an interrupted synthetic operation');
w.state.response = async () => { throw Error('Synthetic lost response'); };
await w.submit(w.forms[0]);
assert.equal(w.forms[0].button.disabled, false);
assert.equal(w.state.reloads, 0);
assert.equal(w.leaving(), true);
const key = w.state.requests[0].headers['Idempotency-Key'];
assert.ok(key);
w.state.response = async () => ({ ok: true, json: async () => ({}) });
await w.submit(w.forms[0]);
assert.equal(w.state.requests[1].headers['Idempotency-Key'], key);
assert.equal(w.forms[0].values.get('reason'), 'Do not lose an interrupted synthetic operation');
assert.equal(w.state.reloads, 1);
});
test(`${file}: a second submit while pending cannot start another request`, async () => {
const w = workspace(file);
let finish;
w.state.response = () => new Promise(resolve => { finish = resolve; });
const pending = w.submit(w.forms[0]);
await w.submit(w.forms[0]);
assert.equal(w.state.requests.length, 1);
finish({ ok: true, json: async () => ({}) });
await pending;
assert.equal(w.state.reloads, 1);
});
test(`${file}: existing legacy mode retains its original refresh behaviour`, async () => {
const w = workspace(file, false);
w.forms[1].values.set('reason', 'Legacy QA preparation');
assert.equal(w.leaving(), false);
await w.submit(w.forms[0]);
assert.equal(w.state.reloads, 1);
});
}
@@ -0,0 +1,114 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = getenv('DB_DATABASE');
$pilot = in_array('--install-authorized-pilot', $argv, true);
$root = dirname(__DIR__, 2);
$destinationValid = preg_match('/^compras_private_restore_([a-f0-9]{12})$/D', $database ?: '', $match)
&& getenv('DB_USERNAME') === 'compras_private_app_'.$match[1];
if ($pilot) {
$approval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
$destinationValid = ($approval['state'] ?? null) === 'approved' && ($approval['scope'] ?? null) === 'pilot_schema_and_pinned_runtime_only'
&& hash_equals($approval['proposal_sha256'], hash_file('sha256', $root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'))
&& ($source['APP_ENV'] ?? null) === 'payable-testing' && realpath($source['HOST_ROOT']) === realpath($root)
&& preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database ?: '', $sourceMatch)
&& $database === $source['DB_DATABASE'] && getenv('DB_USERNAME') === 'payable_qa_'.$sourceMatch[1]
&& getenv('DB_USERNAME') === $source['DB_USERNAME'] && getenv('DB_PORT') === $source['DB_PORT']
&& realpath(getenv('COMPRAS_RUNTIME_ROOT')) === realpath($plan['runtime']['private_installation_directory'])
&& getenv('COMPRAS_RUNTIME_SHA256') === $plan['runtime']['manifest_sha256'];
}
if (! $destinationValid || getenv('DB_HOST') !== '127.0.0.1'
|| getenv('APP_ENV') !== 'private-recovery' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'false'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'true' || getenv('QUEUE_CONNECTION') !== 'null') {
throw new LogicException('PRIVATE_RECOVERY_DESTINATION_REQUIRED');
}
$proposal = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-recovery-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$identity = $db->selectOne('SELECT current_database() AS database_name,current_user AS role_name');
if ($identity->database_name !== $database || $identity->role_name !== getenv('DB_USERNAME')) {
throw new LogicException('PRIVATE_RECOVERY_IDENTITY_MISMATCH');
}
$baseline = null;
if (getenv('COMPRAS_INSTALLATION_BASELINE') !== false) {
$baselinePath = realpath(getenv('COMPRAS_INSTALLATION_BASELINE') ?: '');
$boundary = realpath('C:/laragon/data/sgf-tempo/backups');
if ($baselinePath === false || $boundary === false || ! str_starts_with(str_replace('\\', '/', $baselinePath), str_replace('\\', '/', $boundary).'/')) {
throw new LogicException('PILOT_INSTALLATION_PRIVATE_BASELINE_REQUIRED');
}
$baseline = json_decode(file_get_contents($baselinePath), true, 128, JSON_THROW_ON_ERROR);
$db->beginTransaction();
$db->statement("SET LOCAL lock_timeout = '5s'");
$tables = array_keys($baseline['columns']);
$tables = array_values(array_diff($tables, ['tenants']));
array_unshift($tables, 'tenants');
$db->statement('LOCK TABLE '.implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $tables)).' IN SHARE ROW EXCLUSIVE MODE');
}
$frames = static function () use ($db, $baseline): array {
$out = [];
foreach ($baseline['columns'] as $table => $names) {
$quoted = implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = array_column($db->select('SELECT row_to_json(t)::text AS row FROM (SELECT '.$quoted.' FROM "'.str_replace('"', '""', $table).'") t ORDER BY row_to_json(t)::text'), 'row');
$out[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
}
return $out;
};
if ($baseline !== null && $frames() !== $baseline['frames']) {
throw new LogicException('PILOT_CHANGED_AFTER_VERIFIED_BACKUP');
}
$paths = array_keys($proposal['selected_normal_migrations_in_restored_copy_only']);
foreach ($proposal['selected_normal_migrations_in_restored_copy_only'] as $path => $hash) {
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$path))) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_CHANGED');
}
}
if (Artisan::call('migrate', ['--path' => $paths, '--force' => true, '--no-interaction' => true]) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_FAILED');
}
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Authorised private recovery verification', '--reason' => 'Owner authorised upgrade rehearsal on private restored copy only',
'--reuse-components' => true];
$invoke = static function (array $arguments): array {
if (Artisan::call('compras:runtime:prepare', $arguments) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_PREPARATION_FAILED');
}
return json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
};
$preview = $invoke($arguments);
$applied = $invoke($arguments + ['--apply' => true]);
$repeated = $invoke($arguments + ['--apply' => true]);
if ($preview['written'] !== false || $applied['state'] !== 'prepared' || $repeated['state'] !== 'already_prepared'
|| $repeated['written'] !== false || $db->table('compras_runtime_installations')->count() !== 1) {
throw new LogicException('PRIVATE_RECOVERY_REPLAY_FAILED');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->configure($db);
if ($baseline !== null) {
$after = $frames();
$before = $baseline['frames'];
unset($after['migrations'], $before['migrations']);
$expected = [...$baseline['migrations'], ...array_map(static fn ($path) => basename($path, '.php'), $paths)];
sort($expected, SORT_STRING);
if ($before !== $after || $db->table('migrations')->orderBy('migration')->pluck('migration')->all() !== $expected) {
throw new LogicException('PILOT_INSTALLATION_CONSERVATION_FAILED');
}
$db->commit();
}
echo json_encode(['verified' => true, 'selected_migrations' => count($paths), 'available_modules' => count(StandaloneRuntime::FEATURES),
'one_receipt_replay_without_write' => true, 'configuration_stays_disabled' => config('standalone-runtime.enabled') === false,
'existing_components' => $preview['existing_components']], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,33 @@
<?php
// Owned loopback QA only; the application still uses the verified candidate loader.
use Illuminate\Http\Request;
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$database = getenv('DB_DATABASE') ?: '';
if (getenv('APP_ENV') !== 'standalone-qa' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'true'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'false' || getenv('COMPRAS_RUNTIME_SYNTHETIC_ONLY') !== 'true'
|| ! preg_match('/^compras_standalone_qa_([a-f0-9]{12})$/D', $database, $matches)
|| getenv('DB_USERNAME') !== 'compras_standalone_app_'.$matches[1]
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_STANDALONE_QA_PORT')
|| $root === false || $boundary === false || dirname($root) !== $boundary || basename($root) !== 'rq01-ledger-qa-'.$matches[1]) {
http_response_code(503);
exit;
}
require __DIR__.'/../../vendor/autoload.php';
$public = $root.'/public';
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
readfile($asset);
exit;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/storage');
$app->usePublicPath($public);
$app->handleRequest(Request::capture());
+75 -4
View File
@@ -5,7 +5,9 @@ use App\Models\Department;
use App\Models\Tenant; use App\Models\Tenant;
use App\Models\User; use App\Models\User;
use App\Services\AgreementOrderLimits; use App\Services\AgreementOrderLimits;
use App\Services\BudgetDistributionSchema;
use App\Services\CapitalRegister; use App\Services\CapitalRegister;
use App\Services\CommonFinanceAdministration;
use App\Services\ConflictReleases; use App\Services\ConflictReleases;
use App\Services\ExpenseAllocations; use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger; use App\Services\GeneralLedger;
@@ -22,6 +24,8 @@ use App\Services\PrivateAuditAccess;
use App\Services\RequisitionBudgetDistributions; use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry; use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts; use App\Services\RequisitionLedgerAccounts;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneComponentSchema;
use App\Services\StandaloneInstallation; use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime; use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables; use App\Services\SupplierPayables;
@@ -33,7 +37,9 @@ use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerConfiguration;
use Tempo\Finance\GeneralLedger\LedgerSchema; use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\Payables\SettlementSchema;
require dirname(__DIR__, 2).'/vendor/autoload.php'; require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? ''; $database = $argv[1] ?? '';
@@ -44,8 +50,9 @@ if (! preg_match('/^compras_standalone_qa_([a-f0-9]{12})(_restored)?$/D', $datab
|| $root === false || $parent === false || dirname($root) !== $parent || basename($root) !== 'rq01-ledger-qa-'.$match[1] || $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_DATABASE') !== $database || getenv('DB_USERNAME') !== 'compras_standalone_app_'.$match[1].($match[2] ?? '')
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439' || getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| getenv('APP_ENV') !== 'standalone-qa' || ! in_array($mode, ['prepare', 'verify', 'reject-restore', 'rebind', || getenv('APP_ENV') !== 'standalone-qa' || ! in_array($mode, ['prepare', 'verify', 'prepare-ui', 'read-ui', 'reject-restore', 'rebind',
'reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old'], true)) { 'prepare-configuration-race', 'run-configuration-race', 'read-configuration-race', 'prepare-component-profile',
'reject-foreign', 'reject-pin', 'reject-prepare-pin', 'reject-dependency', 'reject-old'], true)) {
throw new LogicException('Owned standalone QA composition required.'); throw new LogicException('Owned standalone QA composition required.');
} }
$app = require dirname(__DIR__, 2).'/bootstrap/app.php'; $app = require dirname(__DIR__, 2).'/bootstrap/app.php';
@@ -56,7 +63,7 @@ if ($mode === 'reject-foreign') {
$expectedRejection = match ($mode) { $expectedRejection = match ($mode) {
'reject-restore' => 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH', 'reject-restore' => 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH',
'reject-foreign' => 'COMPRAS_RUNTIME_CLASS_LOCATION', 'reject-foreign' => 'COMPRAS_RUNTIME_CLASS_LOCATION',
'reject-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH', 'reject-pin', 'reject-prepare-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH',
'reject-dependency' => 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:import-bank-support:import-dossier', 'reject-dependency' => 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:import-bank-support:import-dossier',
'reject-old' => 'COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE', 'reject-old' => 'COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE',
default => null, default => null,
@@ -67,6 +74,9 @@ try {
if ($expectedRejection === null || $e->getMessage() !== $expectedRejection) { if ($expectedRejection === null || $e->getMessage() !== $expectedRejection) {
throw $e; throw $e;
} }
if ($mode === 'reject-prepare-pin' && class_exists(LedgerConfiguration::class, false)) {
throw new LogicException('Unverified preparation executed a candidate package.');
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL; echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
exit; exit;
} }
@@ -78,6 +88,67 @@ $identity = $db->selectOne("SELECT current_database() AS d,current_setting('clus
if ($identity->d !== $database || $identity->c !== 'sgf_modular_regression_'.$match[1]) { if ($identity->d !== $database || $identity->c !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned standalone QA database identity mismatch.'); throw new LogicException('Owned standalone QA database identity mismatch.');
} }
if ($mode === 'prepare-component-profile') {
if (config('standalone-runtime.prepare_only') !== true || config('standalone-runtime.enabled') === true) {
throw new LogicException('Profile fixture requires disabled business runtime and verified console composition.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$loader = new StandaloneRuntime($settings, new StandaloneArtifact);
$loader->artifact();
$loader->assertLoadedPackages();
BudgetDistributionSchema::install();
SettlementSchema::installForHost('COMMON-PAYABLE-SETTLEMENT-HOST-SCHEMA-v1', function ($connection) use ($database) {
if ($connection->getDatabaseName() !== $database) {
throw new LogicException('Synthetic component fixture changed database.');
}
});
$profiles = [];
foreach (array_keys(StandaloneComponentSchema::GROUPS) as $group) {
$profiles[$group] = StandaloneComponentSchema::inspect($db, $group);
}
echo json_encode(['synthetic_canonical_component_profiles' => $profiles], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if (in_array($mode, ['prepare-configuration-race', 'run-configuration-race', 'read-configuration-race'], true)) {
require __DIR__.'/StandaloneConfigurationRace.php';
exit;
}
if (in_array($mode, ['prepare-ui', 'read-ui'], true)) {
$runtime = app(StandaloneRuntime::class);
$runtime->assertInstallation($db);
$runtime->assertLoadedPackages();
if (! $runtime->syntheticOnly()) {
throw new LogicException('Only synthetic UI review allowed.');
}
$frames = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_journals', 'gl_lines', 'ps_payments', 'ps_allocations'] as $table) {
$frames[$table] = hash('sha256', $db->table($table)->orderBy('id')->get()->toJson());
}
if ($mode === 'read-ui') {
$saved = json_decode(file_get_contents($root.'/standalone-ui.json'), true, 32, JSON_THROW_ON_ERROR);
if ($saved['frames'] !== $frames) {
throw new LogicException('UI setup changed protected financial or stock facts.');
}
echo json_encode(['ui_conservation_verified' => true, 'protected_frames' => count($frames), 'synthetic_only' => true], JSON_THROW_ON_ERROR);
exit;
}
if (is_file($root.'/standalone-ui.json')) {
throw new LogicException('UI fixture already prepared.');
}
$tenant = Tenant::query()->create(['name' => 'Synthetic standalone finance UI review']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Synthetic company']);
$admin = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'name' => 'QA Finance Administrator', 'email' => 'qa-finance-admin@example.invalid', 'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'name' => 'QA Financial Reviewer', 'email' => 'qa-finance-reviewer@example.invalid', 'purchasing_role' => PurchasingRole::Finance]);
$proof = ['admin_login' => $admin->email, 'finance_login' => $finance->email, 'finance_id' => $finance->id,
'tenant_id' => $tenant->id, 'frames' => $frames, 'no_initial_financial_grants' => ! $db->table('pa_access')->where('tenant_id', $tenant->id)->exists()];
file_put_contents($root.'/standalone-ui.json', json_encode($proof, JSON_THROW_ON_ERROR));
unset($proof['frames']);
echo json_encode(['ui_prepared' => true] + $proof, JSON_THROW_ON_ERROR);
exit;
}
if (in_array($mode, ['prepare', 'rebind'], true)) { if (in_array($mode, ['prepare', 'rebind'], true)) {
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'), $arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Synthetic named QA deployment operator', '--reason' => 'Authorised candidate installation and recovery verification']; '--operator' => 'Synthetic named QA deployment operator', '--reason' => 'Authorised candidate installation and recovery verification'];
@@ -140,7 +211,7 @@ if (in_array($mode, ['prepare', 'rebind'], true)) {
$runtime = app(StandaloneRuntime::class); $runtime = app(StandaloneRuntime::class);
$runtime->assertLoadedPackages(); $runtime->assertLoadedPackages();
$checks = 0; $checks = 0;
foreach ([CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class, foreach ([CommonFinanceAdministration::class, CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class,
UrgentQuotationBasis::class, UrgentRequisitionReviews::class, RequisitionLedgerAccounts::class, UrgentQuotationBasis::class, UrgentRequisitionReviews::class, RequisitionLedgerAccounts::class,
RequisitionExpiry::class, RequisitionBudgetDistributions::class, RequisitionExpiry::class, RequisitionBudgetDistributions::class,
ExpenseAllocations::class, AgreementOrderLimits::class, OrderPartsPreparation::class, ExpenseAllocations::class, AgreementOrderLimits::class, OrderPartsPreparation::class,
+8
View File
@@ -59,3 +59,11 @@ test('standalone binding rejects other drivers without querying them', function
$db->shouldReceive('getDriverName')->once()->andReturn('sqlite'); $db->shouldReceive('getDriverName')->once()->andReturn('sqlite');
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_DRIVER'); expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_DRIVER');
}); });
test('standalone data classification remains explicit and defaults to synthetic', function () {
expect((new StandaloneRuntime([], new StandaloneArtifact))->syntheticOnly())->toBeTrue()
->and((new StandaloneRuntime(['enabled' => true], new StandaloneArtifact))->syntheticOnly())->toBeTrue()
->and((new StandaloneRuntime(['enabled' => true, 'synthetic_only' => false], new StandaloneArtifact))->syntheticOnly())->toBeFalse();
expect(fn () => (new StandaloneRuntime(['enabled' => true, 'synthetic_only' => 'false'], new StandaloneArtifact))->syntheticOnly())
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATA_CLASSIFICATION');
});
+129
View File
@@ -0,0 +1,129 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Finance from '@/pages/company/finance';
import { procurementNavigation } from '@/lib/procurement-navigation';
const empty = { data: [], prev_page_url: null, next_page_url: null };
const basis = { hash: 'a'.repeat(64), rows: [] };
function render(selectedAccess: Record<string, unknown> | null = null) {
return renderToStaticMarkup(
<App
initialComponent={Finance}
initialPage={{
component: 'company/finance',
url: '/administracao/financeiro',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
actorId: 1,
tenantId: 1,
q: '',
users: empty,
selectedAccess,
accounts: basis,
periods: basis,
rules: basis,
actions: {
view: 'View supplier debts',
prepare: 'Prepare recognition',
},
effects: {
'supplier_payable.recognised': 'Recognise payable',
},
history: empty,
},
}}
/>,
);
}
test('company setup starts without an implicit target grants accounts dates or posting rules', () => {
const html = render();
expect(html).toContain('href="#finance-access"');
expect(html).not.toContain('checked=""');
expect(html).not.toContain('2026-01-01');
expect(html).not.toContain('QA-2026');
expect(html).not.toContain('value="supplier_payable.recognised" selected');
expect(html).not.toContain('View supplier debts');
});
test('explicit target is escaped and no permission is selected by reading an empty grant list', () => {
const html = render({
...basis,
user: { id: 3, name: '<Finance>', email: 'qa@example.invalid' },
eligible: true,
person: '',
actions: [],
other_actions: [],
identity_inconsistent: false,
});
expect(html).toContain('&lt;Finance&gt;');
expect(html).toContain('View supplier debts');
expect(html).not.toContain('checked=""');
expect(html).not.toContain('<Finance>');
});
test('financial menus expose only explicit capabilities and use full navigation for common package pages', () => {
const menu = (role: string, flags = {}) =>
procurementNavigation(
role,
false,
undefined,
false,
false,
false,
false,
flags,
).flatMap((group) => group.entries);
expect(menu('admin').some((entry) => entry.id === 'general_ledger')).toBe(
false,
);
const flags = { payments: true, ledger: true, configuration: true };
const admin = menu('admin', flags);
expect(admin.find((entry) => entry.id === 'general_ledger')).toMatchObject({
path: '/general-ledger/cycle',
fullPage: true,
});
expect(
admin.find((entry) => entry.id === 'supplier_settlements'),
).toMatchObject({ path: '/supplier-payments', fullPage: true });
expect(
admin.find((entry) => entry.id === 'finance_configuration'),
).toMatchObject({ path: '/administracao/financeiro' });
expect(
menu('finance', flags).some(
(entry) => entry.id === 'finance_configuration',
),
).toBe(false);
expect(
menu('requester', flags).some((entry) =>
[
'general_ledger',
'supplier_settlements',
'finance_configuration',
].includes(entry.id),
),
).toBe(false);
const publicMenu = procurementNavigation(
'admin',
false,
['/dashboard'],
false,
false,
false,
false,
flags,
).flatMap((group) => group.entries);
expect(
publicMenu.some((entry) =>
[
'general_ledger',
'supplier_settlements',
'finance_configuration',
].includes(entry.id),
),
).toBe(false);
});
@@ -65,6 +65,59 @@ test('incomplete detail identifies the missing original and preserves documented
expect(html).not.toContain('Aprovações do valor final'); expect(html).not.toContain('Aprovações do valor final');
}); });
test.each([true, false, undefined])(
'complete order preserves its recorded development classification: %s',
(development) => {
const html = render(Show, {
order: {
...order,
subtotal_minor: 10000,
tax_minor: 0,
snapshot: {
...order.snapshot,
development_only: development,
budget_checked: true,
supplier: {
name: 'Synthetic supplier',
nuit: '000000000',
contact: '',
phone: '',
email: '',
address: '',
},
department: { name: 'Synthetic operations' },
cost_center: { code: 'SYN', name: 'Synthetic centre' },
requisition: { number: 'RQ-SYN' },
issuer: { name: 'Synthetic issuer' },
requester: { name: 'Synthetic requester' },
quotation: {
reference: 'PROP-SYN',
payment_terms: 'Synthetic documentary terms',
},
award: {
justification: 'Synthetic approved example',
delivery_date: '2026-11-29',
delivery_location: 'Synthetic location',
},
approval_rules: {
approval_includes_tax: true,
rules_provisional: false,
},
decision_matrix: [],
final_approvals: [],
},
},
history: [],
snapshotComplete: true,
});
expect(html.includes('Documento de desenvolvimento')).toBe(
development !== false,
);
expect(html).toContain('Controlo orçamental registado na emissão');
expect(html).toContain('RQ-SYN');
},
);
test.each([ test.each([
{ {
state: 'issued', state: 'issued',
+14
View File
@@ -128,4 +128,18 @@ final class CycleWorkspace
* @param array<array-key,mixed> $settings */ * @param array<array-key,mixed> $settings */
public static function render(array $data, array $settings): string { throw new \LogicException('Static analysis declaration only.'); } public static function render(array $data, array $settings): string { throw new \LogicException('Static analysis declaration only.'); }
} }
// general-ledger/src/LedgerConfiguration.php SHA-256 d605eed371d49078a3cb08d7cc5990c2d394dcfd041bbc152108f09342fbbcda
final class LedgerConfiguration
{
public const VERSION = 'COMMON-FINANCE-CONFIGURATION-v1';
public const ACTIONS = ['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm', 'reversal_prepare', 'reversal_confirm', 'general_ledger.view', 'general_ledger.prepare', 'general_ledger.validate', 'general_ledger.post', 'general_ledger.correct_prepare', 'general_ledger.correct_validate', 'general_ledger.correct_post', 'general_ledger.period_prepare', 'general_ledger.period_validate', 'general_ledger.period_close'];
public const EFFECTS = ['supplier_payable.recognised', 'allocation.confirmed', 'allocation.reversed', 'journal.reversal', 'journal.replacement'];
/** @param array<string,int> $scope */
public function __construct(\Illuminate\Database\ConnectionInterface $db, array $scope, int $actor, \Closure $authorize, \Closure $audit) { throw new \LogicException('Static analysis declaration only.'); }
/** @return array{hash:string,rows:array<int,array<string,mixed>>} */
public function basis(string $kind, int $user = 0): array { throw new \LogicException('Static analysis declaration only.'); }
/** @param array<string,mixed> $data
* @return array<string,mixed> */
public function command(string $action, array $data, string $operation): array { throw new \LogicException('Static analysis declaration only.'); }
}
} }