diff --git a/app/Http/Controllers/BudgetController.php b/app/Http/Controllers/BudgetController.php index 81f8e08..d9c071e 100644 --- a/app/Http/Controllers/BudgetController.php +++ b/app/Http/Controllers/BudgetController.php @@ -9,6 +9,7 @@ use App\Models\BudgetEntry; use App\Models\BudgetReinforcement; use App\Models\CostCenter; use App\Services\ConflictGuard; +use App\Services\CurrentActor; use App\Services\RequisitionWorkflow; use Brick\Math\BigDecimal; use Illuminate\Http\RedirectResponse; @@ -37,7 +38,7 @@ class BudgetController extends Controller $total = $budget->approvedTotalMinor(); - return [...$budget->toArray(), 'reinforced_minor' => $total - $budget->amount_minor, 'approved_total_minor' => $total, 'reserved_minor' => $reserved, 'committed_minor' => $committed, 'consumed_minor' => $consumed, 'available_minor' => $total - $reserved - $committed - $consumed]; + return [...$budget->toArray(), 'reinforced_minor' => $total - $budget->amount_minor, 'approved_total_minor' => $budget->approved_by ? $total : 0, 'reserved_minor' => $reserved, 'committed_minor' => $committed, 'consumed_minor' => $consumed, 'available_minor' => $budget->approved_by ? $total - $reserved - $committed - $consumed : 0]; }), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)]); } @@ -48,6 +49,7 @@ class BudgetController extends Controller $kind = $request->validate(['kind' => ['sometimes', Rule::in(['operating', 'investment'])]])['kind'] ?? 'operating'; DB::transaction(function () use ($request, $data, $kind) { app(ConflictGuard::class)->lockCompany($request->user()); + app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]); abort_if(Budget::query()->where('cost_center_id', $data['cost_center_id'])->where('year', $data['year'])->exists(), 409, 'Já existe dotação para este centro e exercício.'); $budget = Budget::query()->create(['tenant_id' => $request->user()->tenant_id, 'created_by' => $request->user()->id, 'cost_center_id' => $data['cost_center_id'], 'year' => $data['year'], 'kind' => $kind, 'includes_tax' => $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]); app(RequisitionWorkflow::class)->audit($request->user(), 'budget.created', null, null, $budget->toArray()); @@ -61,6 +63,7 @@ class BudgetController extends Controller $this->access($request); DB::transaction(function () use ($request, $budget) { app(ConflictGuard::class)->lockCompany($request->user()); + app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]); $budget = Budget::query()->lockForUpdate()->findOrFail($budget->id); abort_if($budget->created_by === $request->user()->id, 403); if ($budget->approved_by) { diff --git a/app/Http/Controllers/Settings/SecurityController.php b/app/Http/Controllers/Settings/SecurityController.php index 3811fe9..9582a37 100644 --- a/app/Http/Controllers/Settings/SecurityController.php +++ b/app/Http/Controllers/Settings/SecurityController.php @@ -33,7 +33,7 @@ class SecurityController extends Controller 'password' => $request->password, ]); - Inertia::flash('toast', ['type' => 'success', 'message' => __('Password updated.')]); + Inertia::flash('toast', ['type' => 'success', 'message' => __('Palavra-passe actualizada.')]); return back(); } diff --git a/app/Services/CurrentActor.php b/app/Services/CurrentActor.php new file mode 100644 index 0000000..7651ff5 --- /dev/null +++ b/app/Services/CurrentActor.php @@ -0,0 +1,25 @@ +|null $roles + */ + public function lock(User $actor, ?array $roles = null): User + { + abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403); + if (DB::connection()->transactionLevel() === 0) { + throw new \LogicException('Revalidar o operador dentro da transacção.'); + } + $user = User::query()->where('tenant_id', $actor->tenant_id)->lockForUpdate()->findOrFail($actor->id); + abort_unless($roles === null || in_array($user->purchasing_role, $roles, true), 403); + + return $user; + } +} diff --git a/app/Services/EquipmentWorkflow.php b/app/Services/EquipmentWorkflow.php index 7270275..91ad74c 100644 --- a/app/Services/EquipmentWorkflow.php +++ b/app/Services/EquipmentWorkflow.php @@ -66,6 +66,7 @@ class EquipmentWorkflow { return DB::transaction(function () use ($user, $requisition, $basis, $decision, $reason) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::DepartmentHead]); $requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id); abort_unless($this->canReview($user, $requisition), 403); app(ConflictGuard::class)->assertParticipation($user, $requisition); @@ -88,7 +89,14 @@ class EquipmentWorkflow return; } $review = TechnicalReview::query()->where('requisition_id', $requisition->id)->where('basis_hash', $this->basis($requisition))->first(); - $user = $review ? User::query()->where('tenant_id', $requisition->tenant_id)->find($review->reviewed_by) : null; + $user = null; + if ($review) { + $query = User::query()->where('tenant_id', $requisition->tenant_id); + if (DB::connection()->transactionLevel() > 0) { + $query->lockForUpdate(); + } + $user = $query->find($review->reviewed_by); + } if (! $review || $review->decision !== 'approved' || ! $user || ! $this->eligible($user, $requisition)) { throw ValidationException::withMessages(['technical' => 'É necessária validação técnica válida do responsável da área, distinto do solicitante, para a versão actual.']); } diff --git a/app/Services/InvoiceWorkflow.php b/app/Services/InvoiceWorkflow.php index f1afd82..f14ff4c 100644 --- a/app/Services/InvoiceWorkflow.php +++ b/app/Services/InvoiceWorkflow.php @@ -75,6 +75,7 @@ class InvoiceWorkflow return DB::transaction(function () use ($user, $order, $data) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]); $order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id); $request = Requisition::query()->findOrFail($order->requisition_id); app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user); @@ -107,6 +108,7 @@ class InvoiceWorkflow abort_unless($invoice->tenant_id === $user->tenant_id && $invoice->created_by !== $user->id, 403); DB::transaction(function () use ($user, $invoice) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]); $invoice = Invoice::query()->lockForUpdate()->findOrFail($invoice->id); if ($invoice->status === 'validated') { return; diff --git a/app/Services/PurchaseWorkflow.php b/app/Services/PurchaseWorkflow.php index 84fe9f9..b03e24a 100644 --- a/app/Services/PurchaseWorkflow.php +++ b/app/Services/PurchaseWorkflow.php @@ -26,6 +26,7 @@ class PurchaseWorkflow { return DB::transaction(function () use ($user, $requisition, $data) { $this->guard->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]); $requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id); abort_unless($user->purchasing_role === PurchasingRole::Procurement && $user->id !== $requisition->requester_id, 403); if (PurchaseAward::query()->where('requisition_id', $requisition->id)->exists()) { @@ -73,6 +74,7 @@ class PurchaseWorkflow { DB::transaction(function () use ($user, $award, $decision, $comment) { $this->guard->lockCompany($user); + $user = app(CurrentActor::class)->lock($user); $requisition = Requisition::query()->lockForUpdate()->findOrFail($award->requisition_id); $award = PurchaseAward::query()->lockForUpdate()->findOrFail($award->id); abort_unless($this->canDecide($user, $award, $requisition), 403); @@ -94,6 +96,7 @@ class PurchaseWorkflow { return DB::transaction(function () use ($user, $award) { $this->guard->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]); abort_unless($user->purchasing_role === PurchasingRole::Procurement, 403); $requisition = Requisition::query()->lockForUpdate()->findOrFail($award->requisition_id); $award = PurchaseAward::query()->lockForUpdate()->findOrFail($award->id); @@ -262,7 +265,7 @@ class PurchaseWorkflow throw ValidationException::withMessages(['approvals' => 'O ciclo de aprovação do valor final está incompleto.']); } foreach ($steps as $index => $step) { - $user = User::query()->where('tenant_id', $requisition->tenant_id)->find($step->approver_id); + $user = User::query()->where('tenant_id', $requisition->tenant_id)->lockForUpdate()->find($step->approver_id); if (! $user || $step->decision !== 'approved' || $step->decided_at === null || $step->role !== $roles[$index] || $user->purchasing_role->value !== $step->role || ($step->role === 'department_head' && $user->department_id !== $requisition->department_id) || in_array($user->id, $seen, true)) { throw ValidationException::withMessages(['approvals' => 'As aprovações do valor final devem continuar elegíveis e ser de pessoas distintas.']); diff --git a/app/Services/ReceiptWorkflow.php b/app/Services/ReceiptWorkflow.php index ceeee7b..0874796 100644 --- a/app/Services/ReceiptWorkflow.php +++ b/app/Services/ReceiptWorkflow.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Enums\PurchasingRole; use App\Models\GoodsReceipt; use App\Models\GoodsReceiptItem; use App\Models\PurchaseOrder; @@ -66,8 +67,9 @@ class ReceiptWorkflow { return DB::transaction(function () use ($user, $order, $data) { $this->conflicts->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Warehouse]); $order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id); - Gate::authorize('create', [GoodsReceipt::class, $order]); + Gate::forUser($user)->authorize('create', [GoodsReceipt::class, $order]); $deliveryNote = Str::squish(Str::upper($data['delivery_note'])); if ($deliveryNote === '') { throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']); diff --git a/app/Services/RequisitionWorkflow.php b/app/Services/RequisitionWorkflow.php index 796352d..70537e6 100644 --- a/app/Services/RequisitionWorkflow.php +++ b/app/Services/RequisitionWorkflow.php @@ -3,6 +3,7 @@ namespace App\Services; use App\Models\AuditLog; +use App\Models\CostCenter; use App\Models\Requisition; use App\Models\Tenant; use App\Models\User; @@ -18,6 +19,10 @@ class RequisitionWorkflow { return DB::transaction(function () use ($user, $data, $existing) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user); + if (! $user->department_id || ! CostCenter::query()->whereKey($data['cost_center_id'])->where('department_id', $user->department_id)->exists()) { + throw ValidationException::withMessages(['cost_center_id' => 'O departamento ou centro de custo mudou. Actualize o pedido antes de guardar.']); + } $requisition = $existing ? Requisition::query()->lockForUpdate()->findOrFail($existing->id) : new Requisition; if ($existing) { abort_unless($requisition->requester_id === $user->id && $requisition->status === 'draft', 403); @@ -70,8 +75,12 @@ class RequisitionWorkflow { DB::transaction(function () use ($user, $requisition) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user); $requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id); abort_unless($requisition->requester_id === $user->id && $requisition->status === 'draft', 403); + if ($user->department_id !== $requisition->department_id) { + throw ValidationException::withMessages(['submission' => 'O departamento do solicitante mudou. Reveja o rascunho e o centro de custo antes de submeter.']); + } app(ConflictGuard::class)->assertParticipation($user, $requisition); foreach ($requisition->items()->get() as $item) { app(EquipmentWorkflow::class)->line($item->toArray(), $requisition->department_id, $requisition->priority); @@ -103,6 +112,7 @@ class RequisitionWorkflow { DB::transaction(function () use ($user, $requisition, $decision, $comment) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user); $requisition = Requisition::query()->lockForUpdate()->findOrFail($requisition->id); $requisition->load('steps'); abort_unless($requisition->canDecide($user), 403); diff --git a/app/Services/StockWorkflow.php b/app/Services/StockWorkflow.php index e026d73..e2195d9 100644 --- a/app/Services/StockWorkflow.php +++ b/app/Services/StockWorkflow.php @@ -32,6 +32,7 @@ class StockWorkflow return DB::transaction(function () use ($actor, $data) { // Same first lock as receipts: includes empty balances and concurrent receipts. app(ConflictGuard::class)->lockCompany($actor); + $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]); $hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR)); $existing = StockOperation::query()->where('idempotency_key', $data['idempotency_key'])->first(); if ($existing) { diff --git a/app/Services/SupplierBankWorkflow.php b/app/Services/SupplierBankWorkflow.php index 835a203..a88bbef 100644 --- a/app/Services/SupplierBankWorkflow.php +++ b/app/Services/SupplierBankWorkflow.php @@ -28,6 +28,7 @@ class SupplierBankWorkflow return DB::transaction(function () use ($user, $supplier, $data) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]); $supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id); $this->actor($user, $supplier); $latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first(); @@ -49,6 +50,7 @@ class SupplierBankWorkflow } DB::transaction(function () use ($user, $detail, $decision, $reason) { app(ConflictGuard::class)->lockCompany($user); + $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]); $supplier = Supplier::query()->lockForUpdate()->findOrFail($detail->supplier_id); $this->actor($user, $supplier); $latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->firstOrFail(); diff --git a/docs/autorizacao-concorrencia-postgresql.json b/docs/autorizacao-concorrencia-postgresql.json new file mode 100644 index 0000000..3519686 --- /dev/null +++ b/docs/autorizacao-concorrencia-postgresql.json @@ -0,0 +1,19 @@ +{ + "tested_at_utc": "2026-10-28T15:16:34+00:00", + "database": "compras_receipts_test_0612e6280f36", + "separate_database": true, + "transport": "Laravel HTTP kernel in independent PHP processes; real PostgreSQL connections", + "scenarios": [ + { + "name": "role_revoked_while_waiting", + "passed": true, + "overlapping_lock_waits": 2, + "statuses": [403, 403], + "receipts": 0, + "stock_movements": 0 + } + ], + "passed": true, + "test_database_dropped": true, + "live_user_count_unchanged": true +} diff --git a/docs/bancos-concorrencia-postgresql.json b/docs/bancos-concorrencia-postgresql.json index 0c6eeac..3461a2a 100644 --- a/docs/bancos-concorrencia-postgresql.json +++ b/docs/bancos-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T12:32:47+00:00", + "tested_at_utc": "2026-10-28T15:07:45+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ diff --git a/docs/compatibilidade.md b/docs/compatibilidade.md index e43b1e2..624c639 100644 --- a/docs/compatibilidade.md +++ b/docs/compatibilidade.md @@ -23,6 +23,15 @@ Preservar enums, políticas, modelos relacionais, Brick Math e isolamento por em ## Verificação actual +Revisão transversal: **407 aprovados, 2 ignorados (MFA desligado), 2.964 asserções**. +32 cenários concorrentes PostgreSQL aprovados; bases temporárias eliminadas. +Perfis e departamentos são novamente verificados dentro da transacção; +dotações pendentes não apresentam fundos disponíveis. Evidências, âmbito e +pendências em [validação técnica](validacao-tecnica.md). Revisão visual, +cancelamento, MFA e validação operacional integral continuam pendentes. + +### Histórico da entrega de investimento + Regras de investimento entregues por empresa, com parâmetros explícitos e duas aprovações administrativas independentes. Dotação classificada, reserva e Finanças obrigatórias para equipamento; regra congelada e revalidada antes de emitir. diff --git a/docs/desenvolvimento.md b/docs/desenvolvimento.md index efb3485..c9e663e 100644 --- a/docs/desenvolvimento.md +++ b/docs/desenvolvimento.md @@ -1,5 +1,26 @@ # Desenvolvimento do SGC +## Revisão transversal de autorização e validação + +Corrigidas verificações de perfil que aconteciam antes de esperar pelo bloqueio +da empresa: o operador é agora recarregado e bloqueado na transacção nos módulos +de facturas, banco, armazém, requisições e compras. Departamento/centro de custo +também são revalidados. Dotação não aprovada deixou de mostrar verba disponível. +Corrigido um teste indevidamente ignorado com MFA desligado e traduzidos os textos +da página de segurança. Configuração de fontes alinhada com a dependência opcional +ausente, sem mudança de fonte ou instalação de pacotes. + +Suite: **407 aprovados, 2 ignorados, 2.964 asserções**. Os dois ignorados são de +MFA activado, que continua desligado. **32 cenários concorrentes PostgreSQL** +aprovados, incluindo revogação real de perfil enquanto dois pedidos aguardam +bloqueio: ambos responderam 403, sem movimentos. Bases temporárias eliminadas. +Sem migrações ou alterações de contas/dados de negócio reais nesta revisão. + +Detalhes das correcções, evidências e pendências estão em +[validação técnica](validacao-tecnica.md). Revisão visual e validação operacional +integral permanecem pendentes. Funcionalidades não implementadas, incluindo +revisão/cancelamento, não foram tratadas como se já existissem. + ## Regras de investimento por empresa Implementadas em `/regras-investimento`, sem montantes predefinidos ou regras diff --git a/docs/facturas-concorrencia-postgresql.json b/docs/facturas-concorrencia-postgresql.json index d04470f..887c2b9 100644 --- a/docs/facturas-concorrencia-postgresql.json +++ b/docs/facturas-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T12:19:17+00:00", + "tested_at_utc": "2026-10-28T15:07:45+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ diff --git a/docs/investimento-concorrencia-postgresql.json b/docs/investimento-concorrencia-postgresql.json index eb8a09f..93179a7 100644 --- a/docs/investimento-concorrencia-postgresql.json +++ b/docs/investimento-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T13:24:32+00:00", + "tested_at_utc": "2026-10-28T15:07:45+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ diff --git a/docs/orcamento-concorrencia-postgresql.json b/docs/orcamento-concorrencia-postgresql.json index 6c0c224..dfbca3e 100644 --- a/docs/orcamento-concorrencia-postgresql.json +++ b/docs/orcamento-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T12:11:20+00:00", + "tested_at_utc": "2026-10-28T15:07:45+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ diff --git a/docs/pagamentos-concorrencia-postgresql.json b/docs/pagamentos-concorrencia-postgresql.json index f156974..95965c1 100644 --- a/docs/pagamentos-concorrencia-postgresql.json +++ b/docs/pagamentos-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T12:49:13+00:00", + "tested_at_utc": "2026-10-28T15:07:45+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ diff --git a/docs/recepcao-concorrencia-postgresql.json b/docs/recepcao-concorrencia-postgresql.json index 0e1f22e..b232f7a 100644 --- a/docs/recepcao-concorrencia-postgresql.json +++ b/docs/recepcao-concorrencia-postgresql.json @@ -1,6 +1,6 @@ { - "tested_at_utc": "2026-10-28T10:56:15+00:00", - "database": "compras_receipts_test_84e8492cd8f3", + "tested_at_utc": "2026-10-28T15:07:45+00:00", + "database": "compras_receipts_test_c9a6d4b5eeb5", "separate_database": true, "transport": "Laravel HTTP kernel in independent PHP processes; real PostgreSQL connections", "scenarios": [ @@ -9,19 +9,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 201, - "id": 1, - "created": true, - "error_fields": [], - "backend_pid": 4688 - }, { "status": 422, "id": null, "created": null, "error_fields": ["items"], - "backend_pid": 2068 + "backend_pid": 24512 + }, + { + "status": 201, + "id": 1, + "created": true, + "error_fields": [], + "backend_pid": 15424 } ], "receipts": 1, @@ -34,19 +34,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 201, - "id": 2, - "created": true, - "error_fields": [], - "backend_pid": 9064 - }, { "status": 200, "id": 2, "created": false, "error_fields": [], - "backend_pid": 1036 + "backend_pid": 6580 + }, + { + "status": 201, + "id": 2, + "created": true, + "error_fields": [], + "backend_pid": 5964 } ], "receipts": 1, @@ -59,19 +59,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 201, - "id": 4, - "created": true, - "error_fields": [], - "backend_pid": 3020 - }, { "status": 201, "id": 3, "created": true, "error_fields": [], - "backend_pid": 24624 + "backend_pid": 26176 + }, + { + "status": 201, + "id": 4, + "created": true, + "error_fields": [], + "backend_pid": 24244 } ], "receipts": 2, @@ -84,19 +84,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 422, - "id": null, - "created": null, - "error_fields": ["delivery_note"], - "backend_pid": 22120 - }, { "status": 201, "id": 5, "created": true, "error_fields": [], - "backend_pid": 4720 + "backend_pid": 21524 + }, + { + "status": 422, + "id": null, + "created": null, + "error_fields": ["delivery_note"], + "backend_pid": 25700 } ], "receipts": 1, diff --git a/docs/reforcos-concorrencia-postgresql.json b/docs/reforcos-concorrencia-postgresql.json index b937cf8..079d24a 100644 --- a/docs/reforcos-concorrencia-postgresql.json +++ b/docs/reforcos-concorrencia-postgresql.json @@ -1,5 +1,5 @@ { - "tested_at_utc": "2026-10-28T12:59:44+00:00", + "tested_at_utc": "2026-10-28T15:07:46+00:00", "separate_database": true, "transport": "Independent PHP service transactions and PostgreSQL connections", "scenarios": [ @@ -24,7 +24,7 @@ "passed": true, "overlapping_lock_waits": 2, "approved_total_minor": 12000, - "reserved_minor": 10000, + "reserved_minor": 0, "original_allocation_unchanged": true } ], diff --git a/docs/stock-concorrencia-postgresql.json b/docs/stock-concorrencia-postgresql.json index 22b48bd..8c0d821 100644 --- a/docs/stock-concorrencia-postgresql.json +++ b/docs/stock-concorrencia-postgresql.json @@ -1,6 +1,6 @@ { - "tested_at_utc": "2026-10-28T11:35:31+00:00", - "database": "compras_receipts_test_d97ad8ad1eb7", + "tested_at_utc": "2026-10-28T15:07:45+00:00", + "database": "compras_receipts_test_aa453293fa81", "separate_database": true, "transport": "Laravel HTTP kernel in independent PHP processes; real PostgreSQL connections", "scenarios": [ @@ -9,19 +9,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 201, - "id": 1, - "created": true, - "error_fields": [], - "backend_pid": 5004 - }, { "status": 422, "id": null, "created": null, "error_fields": ["quantity"], - "backend_pid": 27024 + "backend_pid": 23636 + }, + { + "status": 201, + "id": 1, + "created": true, + "error_fields": [], + "backend_pid": 15544 } ], "source_milli": 400, @@ -37,14 +37,14 @@ "id": 2, "created": true, "error_fields": [], - "backend_pid": 7640 + "backend_pid": 19896 }, { "status": 200, "id": 2, "created": false, "error_fields": [], - "backend_pid": 22852 + "backend_pid": 25896 } ], "source_milli": 400, @@ -55,19 +55,19 @@ "passed": true, "overlapping_lock_waits": 2, "responses": [ - { - "status": 201, - "id": 3, - "created": true, - "error_fields": [], - "backend_pid": 25232 - }, { "status": 200, "id": 3, "created": false, "error_fields": [], - "backend_pid": 28856 + "backend_pid": 22516 + }, + { + "status": 201, + "id": 3, + "created": true, + "error_fields": [], + "backend_pid": 24156 } ], "source_milli": 400, @@ -83,18 +83,18 @@ "id": 4, "created": true, "error_fields": [], - "backend_pid": 5268 + "backend_pid": 2604 }, { - "status": 422, - "id": null, - "created": null, - "error_fields": ["quantity"], - "backend_pid": 4288 + "status": 201, + "id": 5, + "created": true, + "error_fields": [], + "backend_pid": 22296 } ], - "source_milli": 400, - "destination_milli": 600 + "source_milli": 500, + "destination_milli": 500 }, { "name": "same_adjustment", @@ -103,17 +103,17 @@ "responses": [ { "status": 200, - "id": 6, + "id": 7, "created": false, "error_fields": [], - "backend_pid": 13608 + "backend_pid": 26392 }, { "status": 201, - "id": 6, + "id": 7, "created": true, "error_fields": [], - "backend_pid": 2320 + "backend_pid": 17308 } ], "source_milli": 800, @@ -129,14 +129,14 @@ "id": null, "created": null, "error_fields": ["count_id"], - "backend_pid": 25516 + "backend_pid": 24416 }, { "status": 422, "id": null, "created": null, "error_fields": ["count_id"], - "backend_pid": 23640 + "backend_pid": 15140 } ], "source_milli": 900, @@ -149,17 +149,17 @@ "responses": [ { "status": 201, - "id": 9, + "id": 10, "created": true, "error_fields": [], - "backend_pid": 18244 + "backend_pid": 4480 }, { "status": 422, "id": null, "created": null, "error_fields": ["quantity"], - "backend_pid": 2452 + "backend_pid": 20176 } ], "source_milli": 400, diff --git a/docs/validacao-tecnica.md b/docs/validacao-tecnica.md new file mode 100644 index 0000000..dd3ab20 --- /dev/null +++ b/docs/validacao-tecnica.md @@ -0,0 +1,83 @@ +# Validação técnica do SGC — 28 de Outubro de 2026 + +Esta revisão cobre os módulos implementados e as pendências documentadas no +repositório. Não equivale a validação operacional integral ou certificação de +todos os requisitos do sistema. Valores e políticas reais continuam a pertencer +a cada empresa; nenhum foi criado nesta revisão. + +## Correcções verificadas + +- Operações que verificavam o perfil antes de esperar pelo bloqueio da empresa + passam a recarregar e bloquear o utilizador dentro da transacção. Abrange + facturas, dados bancários, stock, recepções, requisições, adjudicação, emissão, + validação técnica e dotação inicial. Mudança de perfil ou de empresa durante + a espera não é autorizada pelo perfil antigo em memória. +- Requisição volta a verificar departamento e centro de custo ao guardar e o + departamento do solicitante ao submeter. Decisões departamentais usam o perfil + actual; revisão técnica e aprovadores finais são bloqueados durante as + verificações transaccionais. +- Dotação pendente mostra **zero disponível e zero aprovado**, preservando o + valor proposto e o histórico. O servidor já bloqueava a reserva; a interface + deixou de apresentar verba proposta como disponível. +- Teste da página de segurança com MFA desligado deixou de ser indevidamente + ignorado. Textos dessa página e confirmação de alteração de palavra-passe + traduzidos para português. Nenhuma palavra-passe real foi alterada. +- Configuração de fontes passou a declarar desactivada a optimização opcional + que já não era gerada por ausência de `fontaine`. Mantém Instrument Sans e + elimina o aviso de dependência opcional sem instalar pacotes novos. + +## Resultados + +**407 testes aprovados, 2 ignorados, 2.964 asserções** na suite completa SQLite +em memória. Os dois ignorados dependem de MFA activado, actualmente desligado; +não são apresentados como funcionalidades validadas. PHPStan, Pint, TypeScript, +compilação e formatação/lint frontend verificados no fecho. + +**32 cenários concorrentes PostgreSQL aprovados**, todos em bases exclusivas +de teste, eliminadas no final: + +| Área | Cenários | Evidência | +| ------------------------------ | -------: | ------------------------------------------------------ | +| Recepções | 4 | [Relatório](recepcao-concorrencia-postgresql.json) | +| Stock e peças | 7 | [Relatório](stock-concorrencia-postgresql.json) | +| Reservas e compromissos | 5 | [Relatório](orcamento-concorrencia-postgresql.json) | +| Facturas e consumo | 3 | [Relatório](facturas-concorrencia-postgresql.json) | +| Dados bancários | 3 | [Relatório](bancos-concorrencia-postgresql.json) | +| Pagamentos externos | 3 | [Relatório](pagamentos-concorrencia-postgresql.json) | +| Reforços | 3 | [Relatório](reforcos-concorrencia-postgresql.json) | +| Regras de investimento | 3 | [Relatório](investimento-concorrencia-postgresql.json) | +| Perfil revogado durante espera | 1 | [Relatório](autorizacao-concorrencia-postgresql.json) | + +O último ensaio bloqueia a empresa, observa duas ligações simultaneamente à +espera e revoga os dois perfis de Armazém antes de libertar o bloqueio. Os dois +pedidos pelo kernel HTTP retornam **403**; não criam recepções nem movimentos. +Os restantes ensaios verificam saldos, duplicações e integridade conforme os +respectivos relatórios. Não são testes de carga ou uma validação de todos os +possíveis cruzamentos concorrentes do sistema. + +Sem migrações, seeds, criação de contas, alteração de configuração de ambiente +ou escritas de negócio na base real nesta revisão. Acesso HTTP pode actualizar +sessões. Nenhuma autorização de compra ou transferência bancária foi emitida. + +## O que permanece por tratar + +| Pendência | Situação | +| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | +| Revisão visual pública, autenticada e impressão | Bloqueada pelo acesso ao navegador; testes HTTP não a substituem. | +| MFA obrigatório e ciclo completo de acessos | Não implementados/activados; dois testes condicionais continuam ignorados. | +| Revisão/cancelamento de adjudicações e ordens | Fluxo e política próprios ainda ausentes. Operações incompatíveis continuam bloqueadas. | +| Reversões, estornos, notas de crédito e devoluções | Funcionalidades ainda não implementadas; não se apagam lançamentos existentes. | +| Regras empresariais | Escalões provisórios, regras fiscais, validade/levantamento de conflitos e excepções exigem decisão da empresa. | +| Investimento agregado e fraccionamento | Apenas tecto por processo suportado; sem agregação/detecção automática. | +| Outras etapas do roteiro | Multimoeda, reposição, tolerâncias/investigação de inventários, manutenção/activos e requisitos de subscrição/hosting continuam no roteiro. | +| Controlos operacionais | Carga, permissões contra SQL administrativo, retenção e recuperação por empresa ainda exigem validação própria. | + +Estas pendências não foram marcadas como concluídas por compilação ou testes +funcionais. O próximo incremento de revisão/cancelamento deve definir e guardar +uma política explícita por empresa, conservar o passado e exigir novas decisões +para processos revistos; não pode autorizar por omissão a alteração de ordens +emitidas ou a libertação de compromissos já consumidos. + +Verificação HTTP local no fecho: **18 páginas públicas responderam 200** e +**13 rotas protegidas responderam 302 sem sessão**. O navegador voltou a devolver +`The browser access host is unavailable`; a revisão visual continua pendente. diff --git a/resources/js/pages/settings/security.tsx b/resources/js/pages/settings/security.tsx index c1e8ae0..8e4247d 100644 --- a/resources/js/pages/settings/security.tsx +++ b/resources/js/pages/settings/security.tsx @@ -19,15 +19,15 @@ export default function Security(props: Props) { return ( <> -
+
-
+