From f9558d4563f4a7e60bbc651456e261aa7e04e776 Mon Sep 17 00:00:00 2001 From: Osmane Nala Date: Mon, 30 Nov 2026 23:23:50 +0200 Subject: [PATCH] =?UTF-8?q?Delimitar=20a=20v1=20ao=20n=C3=BAcleo=20de=20co?= =?UTF-8?q?mpras=20com=20interruptores=20por=20m=C3=B3dulo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decisão de 30/11/2026: a v1 é só o núcleo (requisições, aprovações, cotações, adjudicação e ordens, fornecedores, recepções, stock básico, facturas, pagamentos externos, orçamentos, empresa, conflitos, auditoria, relatórios). - config/modules.php: pessoas, armazem_avancado e fornecimento, desligados por omissão (SGC_MODULE_*), sem apagar código. - EnsureModuleEnabled: rotas de módulos desligados respondem 404. - Menus escondem as entradas desses módulos (disabledModulePaths partilhado); contextos people.* deixam de ser oferecidos; /avaliar sem ligações mortas. - Testes: suite corre com os módulos ligados; ProductModulesTest e product-modules.test.tsx verificam núcleo disponível e módulos desligados. Co-Authored-By: Claude Opus 5.5 --- .env.example | 6 ++ app/Http/Middleware/EnsureModuleEnabled.php | 21 +++++ app/Http/Middleware/HandleInertiaRequests.php | 3 + app/Services/ProductModules.php | 81 +++++++++++++++++ app/Services/WorkContext.php | 3 + bootstrap/app.php | 2 + config/modules.php | 87 +++++++++++++++++++ phpunit.xml | 4 + .../js/components/sgc-workspace-shell.tsx | 4 + resources/js/lib/procurement-navigation.ts | 53 +++++++---- routes/evaluation.php | 4 +- tests/Feature/ProductModulesTest.php | 66 ++++++++++++++ tests/frontend/product-modules.test.tsx | 44 ++++++++++ 13 files changed, 358 insertions(+), 20 deletions(-) create mode 100644 app/Http/Middleware/EnsureModuleEnabled.php create mode 100644 app/Services/ProductModules.php create mode 100644 config/modules.php create mode 100644 tests/Feature/ProductModulesTest.php create mode 100644 tests/frontend/product-modules.test.tsx diff --git a/.env.example b/.env.example index 566e4ec..feaf436 100644 --- a/.env.example +++ b/.env.example @@ -74,3 +74,9 @@ PAYABLE_SOURCE_INSTANCE= # Adesão voluntária MFA, só depois da migração e validação da instalação. SGC_TWO_FACTOR_ENABLED=false + +# Âmbito da v1: só o núcleo de compras. Módulos laterais desligados por omissão; +# activar por instalação quando contratados (ver config/modules.php). +SGC_MODULE_PESSOAS=false +SGC_MODULE_ARMAZEM_AVANCADO=false +SGC_MODULE_FORNECIMENTO=false diff --git a/app/Http/Middleware/EnsureModuleEnabled.php b/app/Http/Middleware/EnsureModuleEnabled.php new file mode 100644 index 0000000..84d6246 --- /dev/null +++ b/app/Http/Middleware/EnsureModuleEnabled.php @@ -0,0 +1,21 @@ +route(); + abort_if($route instanceof Route && ! app(ProductModules::class)->allows($route), 404); + + return $next($request); + } +} diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index e0a5fbd..8e7a6d7 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -9,6 +9,7 @@ use App\Services\GeneralLedger; use App\Services\OperationalOrders; use App\Services\OrganizationAccess; use App\Services\PrivateAuditAccess; +use App\Services\ProductModules; use App\Services\StandaloneRuntime; use App\Services\SupplierPayables; use App\Services\WorkContext; @@ -76,6 +77,8 @@ class HandleInertiaRequests extends Middleware 'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::class)->ready(), 'capitalRegisterAvailable' => $actor !== null && app(CapitalRegister::class)->searchQuery($actor) !== null, 'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true', + 'modules' => app(ProductModules::class)->states(), + 'disabledModulePaths' => fn () => app(ProductModules::class)->disabledPaths(), ]; } diff --git a/app/Services/ProductModules.php b/app/Services/ProductModules.php new file mode 100644 index 0000000..939a8b2 --- /dev/null +++ b/app/Services/ProductModules.php @@ -0,0 +1,81 @@ +|null */ + private ?array $disabledPaths = null; + + public function __construct(private readonly Router $router) {} + + public function enabled(string $module): bool + { + return (bool) config('modules.enabled.'.$module, false); + } + + /** @return array */ + public function states(): array + { + return array_map(fn ($value) => (bool) $value, (array) config('modules.enabled', [])); + } + + /** O módulo a que a rota pertence, ou null quando é do núcleo. */ + public function moduleFor(Route $route): ?string + { + $controller = ltrim((string) $route->getControllerClass(), '\\'); + $uri = trim($route->uri(), '/'); + foreach ((array) config('modules.controllers', []) as $module => $controllers) { + if ($controller !== '' && in_array($controller, (array) $controllers, true)) { + return (string) $module; + } + } + foreach ((array) config('modules.paths', []) as $module => $prefixes) { + foreach ((array) $prefixes as $prefix) { + if ($uri === $prefix || str_starts_with($uri, $prefix.'/')) { + return (string) $module; + } + } + } + + return null; + } + + public function allows(Route $route): bool + { + $module = $this->moduleFor($route); + + return $module === null || $this->enabled($module); + } + + /** + * Caminhos (parte fixa da URL) servidos só por módulos desligados, para esconder entradas de menu. + * + * @return list + */ + public function disabledPaths(): array + { + if ($this->disabledPaths !== null) { + return $this->disabledPaths; + } + $disabled = []; + $enabled = []; + foreach ($this->router->getRoutes()->getRoutes() as $route) { + if (! in_array('GET', $route->methods(), true)) { + continue; + } + $path = '/'.trim(preg_replace('/\/?\{.*$/', '', $route->uri()) ?? '', '/'); + if ($this->allows($route)) { + $enabled[$path] = true; + } else { + $disabled[$path] = true; + } + } + + return $this->disabledPaths = array_values(array_diff(array_keys($disabled), array_keys($enabled))); + } +} diff --git a/app/Services/WorkContext.php b/app/Services/WorkContext.php index d33c8be..d9e90de 100644 --- a/app/Services/WorkContext.php +++ b/app/Services/WorkContext.php @@ -39,6 +39,9 @@ class WorkContext if (config('work_context.composition') === 'sgf' && is_array($keys)) { $keys = array_diff($keys, ['people.third_party']); } + if (! app(ProductModules::class)->enabled('pessoas') && is_array($keys)) { + $keys = array_diff($keys, ['people.internal', 'people.third_party']); + } return is_array($keys) ? array_values(array_intersect(array_keys(self::OPTIONS), $keys)) : []; } diff --git a/bootstrap/app.php b/bootstrap/app.php index 2684364..4b7b340 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ prependToPriorityList(PublicDevelopmentNavigation::class, HandleInertiaRequests::class); $middleware->web(append: [ + EnsureModuleEnabled::class, PublicDevelopmentNavigation::class, EnterLocalEvaluation::class, HandleAppearance::class, diff --git a/config/modules.php b/config/modules.php new file mode 100644 index 0000000..56cd960 --- /dev/null +++ b/config/modules.php @@ -0,0 +1,87 @@ + [ + // Recrutamento, serviços individuais, cadastro de pessoas e portal de candidaturas. + 'pessoas' => (bool) env('SGC_MODULE_PESSOAS', false), + // Requisições ao armazém, reposição automática, lotes, devoluções e disponibilidade. + 'armazem_avancado' => (bool) env('SGC_MODULE_ARMAZEM_AVANCADO', false), + // Fornecimento planeado, importações, equipamentos, projectos e ordens operacionais. + 'fornecimento' => (bool) env('SGC_MODULE_FORNECIMENTO', false), + ], + + 'controllers' => [ + 'pessoas' => [ + PeopleHiringController::class, + PeopleRegistryController::class, + PeopleReportController::class, + CandidatePortalController::class, + SubmissionFormsController::class, + ], + 'armazem_avancado' => [ + WarehouseRequestController::class, + WarehouseAvailabilityController::class, + WarehouseExchangeController::class, + WarehousePilotController::class, + WarehouseReturnController::class, + AutomaticPurchaseController::class, + InventoryLotController::class, + InventoryDispositionController::class, + InventoryReversalController::class, + ], + 'fornecimento' => [ + SupplyPlanningController::class, + SupplyCoordinationReportController::class, + AgreementFollowupController::class, + EquipmentController::class, + CapitalRegisterController::class, + OperationalOrdersController::class, + ImportBankSupportController::class, + ImportDossierController::class, + ImportEstimateController::class, + ImportLandedCostController::class, + ImportLegalController::class, + ImportReadinessController::class, + ImportTariffController::class, + ], + ], + + // Prefixos de URL do módulo servidos por controladores partilhados (ex.: caixa de tarefas de Pessoas). + 'paths' => [ + 'pessoas' => ['pessoas', 'candidaturas'], + ], +]; diff --git a/phpunit.xml b/phpunit.xml index e6a5a31..332adba 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -26,6 +26,10 @@ + + + + diff --git a/resources/js/components/sgc-workspace-shell.tsx b/resources/js/components/sgc-workspace-shell.tsx index b59e08f..6c0c495 100644 --- a/resources/js/components/sgc-workspace-shell.tsx +++ b/resources/js/components/sgc-workspace-shell.tsx @@ -58,6 +58,8 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) { const commonFinance = page.props.commonFinanceNavigation as | CommonFinanceNavigation | undefined; + const disabledModulePaths = + (page.props.disabledModulePaths as string[] | undefined) ?? []; const scopedEntries = new Set( procurementNavigation( context?.permissions ?? [], @@ -68,6 +70,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) { page.props.privateAuditAvailable === true, page.props.capitalRegisterAvailable === true, commonFinance, + disabledModulePaths, ).flatMap((group) => group.entries.map((entry) => entry.id)), ); const groups = procurementNavigation( @@ -79,6 +82,7 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) { page.props.privateAuditAvailable === true, page.props.capitalRegisterAvailable === true, commonFinance, + disabledModulePaths, ) .map((group) => ({ ...group, diff --git a/resources/js/lib/procurement-navigation.ts b/resources/js/lib/procurement-navigation.ts index 5a94696..fc42505 100644 --- a/resources/js/lib/procurement-navigation.ts +++ b/resources/js/lib/procurement-navigation.ts @@ -33,6 +33,18 @@ const readers = ['admin', 'procurement', 'finance', 'department_head']; const finance = ['admin', 'finance']; const inventory = [...readers, 'warehouse']; +/** Entradas de módulos desligados nesta instalação (ver config/modules.php no servidor). */ +export function isModulePathDisabled( + path: string, + disabledModulePaths: string[] = [], +): boolean { + const pathname = new URL(path, 'http://local').pathname.replace(/\/$/, ''); + return disabledModulePaths.some( + (disabled) => + pathname === disabled || pathname.startsWith(disabled + '/'), + ); +} + export function procurementNavigation( role: string | string[], payables: boolean, @@ -42,6 +54,7 @@ export function procurementNavigation( privateAudit = false, capitalRegister = false, commonFinance: CommonFinanceNavigation = {}, + disabledModulePaths: string[] = [], ): ProcurementGroup[] { const groups: ProcurementGroup[] = [ { @@ -654,25 +667,27 @@ export function procurementNavigation( .map((group) => ({ ...group, entries: group.entries.filter((entry) => - publicPaths - ? publicPaths.includes( - new URL(entry.path, 'http://local').pathname, - ) - : (entry.id !== 'issued_order_cancellations' || - orderCancellation) && - (entry.id !== 'audit_private' || privateAudit) && - (entry.id !== 'operational_orders' || - operationalOrders) && - (entry.id !== 'capital_register' || capitalRegister) && - (entry.id !== 'new_request' || - !Array.isArray(role) || - role.includes('requester')) && - (!entry.roles || - entry.roles.some((permission) => - (Array.isArray(role) ? role : [role]).includes( - permission, - ), - )), + isModulePathDisabled(entry.path, disabledModulePaths) + ? false + : publicPaths + ? publicPaths.includes( + new URL(entry.path, 'http://local').pathname, + ) + : (entry.id !== 'issued_order_cancellations' || + orderCancellation) && + (entry.id !== 'audit_private' || privateAudit) && + (entry.id !== 'operational_orders' || + operationalOrders) && + (entry.id !== 'capital_register' || capitalRegister) && + (entry.id !== 'new_request' || + !Array.isArray(role) || + role.includes('requester')) && + (!entry.roles || + entry.roles.some((permission) => + (Array.isArray(role) ? role : [role]).includes( + permission, + ), + )), ), })) .filter((group) => group.entries.length); diff --git a/routes/evaluation.php b/routes/evaluation.php index 17824a2..6a9d564 100644 --- a/routes/evaluation.php +++ b/routes/evaluation.php @@ -4,6 +4,7 @@ use App\Enums\PurchasingRole; use App\Models\User; use App\Services\EvaluationAccess; use App\Services\EvaluationNavigation; +use App\Services\ProductModules; use App\Services\RequisitionWorkflow; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -37,7 +38,8 @@ Route::get('/avaliar', function (Request $request) use ($evaluationScope, $evalu $html = 'Explorar SGC

Explorar SGC

Entrada local sem palavra-passe. Os exemplos e alterações ficam guardados nesta instalação de testes.

Acesso de proprietário

Abre a administração e as páginas dos módulos abaixo. As regras dos processos e as funções operacionais continuam visíveis.

'; if ($request->user()) { $html .= '

Áreas da aplicação

    '; - foreach ($evaluationPages as $path => $label) { + $disabledPaths = app(ProductModules::class)->disabledPaths(); + foreach (array_filter($evaluationPages, fn ($path) => ! in_array($path, $disabledPaths, true), ARRAY_FILTER_USE_KEY) as $path => $label) { $html .= '
  • '.$label.'
  • '; } $html .= '
'; diff --git a/tests/Feature/ProductModulesTest.php b/tests/Feature/ProductModulesTest.php new file mode 100644 index 0000000..a47b102 --- /dev/null +++ b/tests/Feature/ProductModulesTest.php @@ -0,0 +1,66 @@ + ['pessoas' => false, 'armazem_avancado' => false, 'fornecimento' => false]]); + $tenant = Tenant::query()->create(['name' => 'Empresa do núcleo']); + $department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']); + $this->admin = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Admin]); +}); + +test('core purchasing pages stay available with every lateral module off', function (string $path) { + $this->actingAs($this->admin)->get($path)->assertOk(); +})->with([ + '/dashboard', '/requisicoes', '/fornecedores', '/cotacoes', '/ordens', '/recepcoes', + '/stock', '/stock/operacoes', '/facturas', '/pagamentos', '/orcamentos', '/regras-investimento', + '/empresa', '/conflitos', '/relatorios', +]); + +test('lateral module routes answer as missing when their module is off', function (string $path) { + $this->actingAs($this->admin)->get($path)->assertNotFound(); +})->with([ + 'pessoas' => '/pessoas', + 'pessoas: relatórios' => '/pessoas/relatorios', + 'pessoas: portal público' => '/candidaturas/1', + 'armazém: requisições internas' => '/stock/requisicoes', + 'armazém: reposição automática' => '/stock/reposicao', + 'armazém: lotes' => '/stock/lotes', + 'fornecimento: planeado' => '/compras/fornecimento', + 'fornecimento: equipamentos' => '/equipamentos', + 'fornecimento: projectos e imobilizado' => '/projectos-imobilizado', +]); + +test('a module switched on serves its routes again', function () { + config(['modules.enabled.fornecimento' => true]); + expect(app(ProductModules::class)->enabled('fornecimento'))->toBeTrue(); + $this->actingAs($this->admin)->get('/equipamentos')->assertStatus(200); +}); + +test('menus receive the paths of disabled modules and keep the core ones', function () { + $this->actingAs($this->admin)->get('/dashboard')->assertOk()->assertInertia(fn (Assert $page) => $page + ->where('modules', ['pessoas' => false, 'armazem_avancado' => false, 'fornecimento' => false]) + ->where('disabledModulePaths', fn ($paths) => collect($paths)->contains('/pessoas') + && collect($paths)->contains('/stock/requisicoes') + && collect($paths)->contains('/equipamentos') + && ! collect($paths)->contains('/stock') + && ! collect($paths)->contains('/requisicoes') + && ! collect($paths)->contains('/compras'))); +}); + +test('people work contexts are not offered while the people module is off', function () { + config(['work_context.composition' => 'sgc', 'work_context.entitlements' => [$this->admin->tenant_id => array_keys(WorkContext::OPTIONS)]]); + expect(app(WorkContext::class)->purchased($this->admin))->not->toContain('people.internal')->not->toContain('people.third_party') + ->toContain('procurement.internal'); + + config(['modules.enabled.pessoas' => true]); + expect(app(WorkContext::class)->purchased($this->admin))->toContain('people.internal'); +}); diff --git a/tests/frontend/product-modules.test.tsx b/tests/frontend/product-modules.test.tsx new file mode 100644 index 0000000..d10ab15 --- /dev/null +++ b/tests/frontend/product-modules.test.tsx @@ -0,0 +1,44 @@ +import { expect, test } from 'vitest'; +import { + isModulePathDisabled, + procurementNavigation, +} from '@/lib/procurement-navigation'; + +const disabled = ['/pessoas', '/stock/requisicoes', '/compras/fornecimento']; + +test('only paths served by disabled modules are hidden', () => { + expect(isModulePathDisabled('/pessoas', disabled)).toBe(true); + expect(isModulePathDisabled('/pessoas/relatorios', disabled)).toBe(true); + expect( + isModulePathDisabled('/compras/fornecimento?view=imports', disabled), + ).toBe(true); + expect(isModulePathDisabled('/stock', disabled)).toBe(false); + expect(isModulePathDisabled('/stock/operacoes', disabled)).toBe(false); + expect(isModulePathDisabled('/pessoasx', disabled)).toBe(false); + expect(isModulePathDisabled('/requisicoes', [])).toBe(false); +}); + +test('navigation drops entries of disabled modules and keeps the core', () => { + const paths = (hidden: string[]) => + procurementNavigation( + ['admin'], + false, + undefined, + false, + false, + false, + false, + {}, + hidden, + ) + .flatMap((group) => group.entries) + .map((entry) => entry.path.split('?')[0]); + + const all = paths([]); + const core = paths(disabled); + expect(all).toContain('/compras/fornecimento'); + expect(core).not.toContain('/compras/fornecimento'); + expect(core.some((path) => path.startsWith('/pessoas'))).toBe(false); + expect(core).toContain('/requisicoes'); + expect(core).toContain('/stock'); +});