86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

86 adicionar mais roles - #89

Merged
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles
Sep 3, 2025
Merged

86 adicionar mais roles#89
rbxyz merged 3 commits into
mainfrom
86-adicionar-mais-roles

Conversation

@rbxyz

@rbxyzrbxyz commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Granular view permissions for Events, Flyers, Rooms, Cars, and Forms with clear toggles, badges, and route summaries.
    • Forms management switched to Visible/Hidden controls; hidden lists drive visibility.
    • Sector options updated (Recursos Humanos, TI, Vendas) and ordering improved.
    • Super Admin (Sudo) clears/restores other permissions.
  • UI/UX Enhancements

    • Reorganized Admin > Users permissions, contextual toasts, and stricter gating: view permission required before create/locate; users without role config no longer see forms.

@vercel

vercelBot commented Sep 3, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentSep 3, 2025 9:04pm

@coderabbitai

coderabbitaiBot commented Sep 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors permissions to be view-gated across content and forms, expands RolesConfig with new can_view_* flags and hidden_forms, tightens access-control logic and hooks, adds setor support and UI changes in admin/users, and updates CompleteProfileModal setor options.

Changes

Cohort / File(s)Summary
Types & access-control core
src/types/role-config.ts, src/lib/access-control.ts, src/hooks/use-access-control.tsx
Expanded RolesConfig with content and formscan_view_* flags and hidden_forms; introduced/renamed canView* helpers (canViewEvents, canViewFlyers, canViewRooms, canViewCars, canViewShop); view permissions now gate create/locate actions and form access; stricter defaults when role_config is missing.
Admin users UI & helpers
src/app/(authenticated)/admin/users/page.tsx
Mapped route toggles to can_view_* flags, added AVAILABLE_SETORES and getSetorLabel, rewrote permissions UI (visible/hidden forms, permission badges, accessible routes text), added getRouteForPermission/handlePermissionToggle, and updated sudo behavior to clear/restore related flags with toasts.
Pages updated to use new APIs
src/app/(authenticated)/events/page.tsx, src/app/(authenticated)/flyers/page.tsx, src/app/(authenticated)/cars/page.tsx
Changed page-level permission checks to pass userData.role_config into the new canView* functions; redirect behavior preserved.
Profile modal setor options
src/components/complete-profile-modal.tsx
Reworked setor options list: removed PROMOTORES, added/renamed entries (RECURSOS_HUMANOS, TI, VENDAS), reordered LOGISTICA/INOVACAO. No public API changes.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor User
participant App
participant AccessControl
participant RoleConfig
User->>App: Navigate to Events page
App->>AccessControl: canViewEvents(RoleConfig)
AccessControl->>RoleConfig: check sudo or content.can_view_events
alt view allowed
App->>AccessControl: canCreateEvent(RoleConfig)
AccessControl->>RoleConfig: require can_view_events then can_create_event
App-->>User: Render Events (create UI gated)
else view denied
App-->>User: Redirect / show unauthorized
end
Loading
sequenceDiagram
autonumber
actor Admin
participant AdminUI as Admin Users Page
participant Helpers as Permission Helpers
participant RoleCfg as RoleConfig
Admin->>AdminUI: Toggle "Eventos" view
AdminUI->>Helpers: handlePermissionToggle('can_view_events')
Helpers->>RoleCfg: Set content.can_view_events
alt enabling
Helpers->>RoleCfg: Optionally enable related can_create_event
AdminUI-->>Admin: Toast "Eventos: visualização ativada"
else disabling
Helpers->>RoleCfg: Clear dependent flags (e.g., can_create_event)
AdminUI-->>Admin: Toast "Eventos: visualização desativada"
end
Admin->>AdminUI: Toggle Sudo
AdminUI->>RoleCfg: Set sudo = true
AdminUI->>RoleCfg: Clear admin_pages, accessible_routes, content, forms
AdminUI-->>Admin: Toast "Sudo ativado (outros campos limpos)"
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my whiskers, code in paw,
Views gated now by rules I saw.
Forms hide like carrots, tucked and neat,
Sudo sweeps the garden clean and sweet.
Setores sorted, hops of joy—approval beat. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 86-adicionar-mais-roles

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Prefer AccessDenied fallback over redirect (optional).

Guidelines suggest showing an AccessDenied fallback for unauthorized users instead of redirecting.

Apply:

- if (!canViewEvents(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewEvents(userData.role_config)) {+ return <AccessDenied />+ }

And ensure the import exists:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/flyers/page.tsx (1)

26-28: Optional: render AccessDenied instead of redirect.

Keeps UX consistent with unauthorized fallbacks.

- if (!canViewFlyers(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewFlyers(userData.role_config)) {+ return <AccessDenied />+ }

Import if needed:

import{AccessDenied}from"@/components/access-denied"
src/app/(authenticated)/cars/page.tsx (1)

35-37: Optional UX: show AccessDenied instead of redirect.

Consistent unauthorized handling across authenticated routes.

- if (!canViewCars(userData.role_config)) {- redirect("/dashboard")- }+ if (!canViewCars(userData.role_config)) {+ return <AccessDenied />+ }

Add import if missing:

import{AccessDenied}from"@/components/access-denied"
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6163d31 and f4a52a1.

📒 Files selected for processing (3)
  • src/app/(authenticated)/cars/page.tsx (1 hunks)
  • src/app/(authenticated)/events/page.tsx (1 hunks)
  • src/app/(authenticated)/flyers/page.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

**/*.{ts,tsx}: Use path aliases (e.g., @/components/ui/button, @/trpc/react, @/lib/utils, and type-only imports) instead of long relative paths
Avoid long multi-level relative imports like ../../../components/ui/button
Document functions with JSDoc for clarity on params and return values
Do not use any unnecessarily; prefer precise types

**/*.{ts,tsx}: Evitar usar any; preferir tipos específicos ou unknown
Usar interface para objetos e type para uniões/tipos utilitários
Definir tipos de retorno explícitos para funções
Usar import type para importar somente tipos; evitar import de valores quando apenas tipos são necessários

**/*.{ts,tsx}: In component props interfaces, list required props first, then optional props; include className as an optional prop at the end
Group imports in the order: React, external libraries, internal components, types, then utils

**/*.{ts,tsx}: Prefer select to avoid fetching all fields in Prisma queries
Use transactions (db.$transaction) for related operations and use the transactional client (tx) inside the callback
Fetch related data in a single optimized query using nested selects/filters/order/limit instead of multiple sequential queries

**/*.{ts,tsx}: Validate all API inputs with Zod schemas and pass them to procedures (e.g., protectedProcedure.input(schema))
Use separate schemas for create and update; derive update schemas with schema.partial().extend({ id: z.string().cuid() })
Enforce authorization inside mutations (e.g., deny user updates unless sudo or self) and return FORBIDDEN on violations
Validate file uploads with Zod: enforce max size (≤5MB) and whitelist MIME types (image/jpeg, image/png, image/webp)
Do not expose sensitive data in API responses; select only required fields from the database
Log internal errors for monitoring, but return generic, non-sensitive messages to clients (e.g., TRPCError with INTERNAL_SERVER_ERROR)
Implement rate limiting on sensitive routes (e.g., /api/auth) using express-rate-limit ...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/00-quick-reference.mdc)

src/**/*.tsx: Define React component props with a TypeScript interface and include optional className to merge via cn
Use the design system components (e.g., Card, Button) and compose classes with cn for consistent UI
Build forms with React Hook Form and Zod (zodResolver), show field errors, and disable submit while isSubmitting
Memoize expensive computations with useMemo and event handlers with useCallback; use React.memo where beneficial

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/02-react-components.mdc)

**/*.tsx: Only add the "use client" directive at the top of a file when a component truly needs to run on the client
When destructuring props in a React component, keep the order: required props, then optional props, then className
Place state hooks (useState) at the top of the component before any effects or functions
Place effects (useEffect) after state declarations
Define component functions/handlers after hooks (state/effects)
Use the cn utility to merge class names when applying className to elements
Use React.forwardRef for components that need to receive a ref
Always set displayName on components created with React.forwardRef
Wrap functions passed as props with useCallback
Memoize expensive computations with useMemo

Sanitize any user-provided HTML before rendering with DOMPurify.sanitize, allowing only safe tags/attributes

**/*.tsx: Use React Hook Form with Zod (zodResolver) for validation in React forms
Implement accessibility on form fields: associate Label htmlFor with input id, set aria-invalid when errors exist, and link error text via aria-describedby
Provide clear visual feedback for field errors by rendering error messages near inputs and linking them with matching ids
Use formState.isSubmitting to show a loading state and disable the submit button during submission
Reset the form and trigger onSuccess after a successful submit; wrap submit logic in try/catch to handle errors
When editing entities, initialize form defaultValues from the provided data
Use Controller to integrate custom or controlled components (e.g., Select) with React Hook Form and surface validation errors
Validate file uploads on the client: enforce accept and maxSize, preview images using Object URLs when applicable, and allow removing the selected file

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

src/**/*.{ts,tsx}: Use TypeScript path aliases (e.g., @/components, @/lib, @/types) instead of long relative import paths
Order imports with the following groups: 1) React imports, 2) external libraries (alphabetically), 3) internal alias-based imports (ordered by alias), 4) type-only imports, 5) asset imports
Use kebab-case for file names (e.g., user-profile.tsx)
Use camelCase for functions and hooks (e.g., useUserProfile)
Use PascalCase for type and interface names (e.g., UserProfileData)
Use SCREAMING_SNAKE_CASE for constants (e.g., DEFAULT_PAGE_SIZE)
Place type-only imports after value imports within the imports block
Place asset imports after code and type imports within the imports block
Alphabetize external library imports within their group
Order internal alias-based imports by alias name within their group

src/**/*.{ts,tsx}: Arquivos de código TypeScript devem ser nomeados em kebab-case (ex.: user-profile.tsx)
Funções e hooks devem usar camelCase (ex.: useUserProfile)
Constantes devem usar SCREAMING_SNAKE_CASE
Sempre usar o alias @/ para imports internos
Agrupar imports por categoria (externos, internos, locais, etc.)
Ordenar imports alfabeticamente dentro de cada grupo

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
src/app/**

📄 CodeRabbit inference engine (.cursor/rules/03-imports-file-structure.mdc)

Place Next.js App Router pages under src/app

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/06-ui-ux-patterns.mdc)

**/*.{tsx,jsx}: Preferir componentes do shadcn/ui (ex.: Button, Card, Input) importados de "@/components/ui/*" em vez de estilos customizados
Usar consistentemente componentes do design system (ex.: Button, Card, Input) nas UIs ao invés de HTML ad‑hoc
Usar a função cn() de "@/lib/utils" para compor className em vez de concatenação manual de strings
Preferir classes/tokens semânticos do design system (ex.: text-muted-foreground, btn-primary e seus estados hover/focus) em vez de estilos arbitrários
Construir layouts responsivos com Tailwind (ex.: grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3, gap controlado)
Usar padrões de Flexbox com utilitários Tailwind (ex.: flex, flex-col, items-center, justify-between, space-y-4) em vez de CSS customizado
Fornecer estados de loading e erro em componentes de dados usando Skeleton e Alert (variant="destructive")
Marcar ícones puramente decorativos com aria-hidden="true" e fornecer rótulos acessíveis (aria-label) para botões
Desabilitar interações conforme estado (ex.: disabled durante loading) em elementos interativos
Formulários acessíveis: associar Label htmlFor ao Input id, usar aria-describedby para mensagens de erro e aria-invalid quando aplicável
Usar tokens/variáveis de tema do Tailwind para cores (ex.: text-primary, bg-secondary) em vez de cores hardcoded
Suportar modo escuro usando o prefixo dark: nas classes Tailwind quando pertinente

**/*.{tsx,jsx}: Use React.memo for components that re-render frequently
Memoize expensive computations with useMemo
Use useCallback for functions passed as props to child components
Virtualize large lists (e.g., react-window) instead of rendering all items
Use lazy loading/code splitting (React.lazy/Suspense or dynamic import) for heavy components and pages
Optimize images using Next.js Image with proper sizes, priority, and blur placeholders
Use debounce for search and similar high-frequency inputs to reduce request frequency
Use throttle for scroll/resize or other frequent events to...

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/07-security-access-control.mdc)

Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧠 Learnings (2)
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/*.{tsx,ts} : Guard privileged UI and route-entry points with permission checks (e.g., hasPermission('admin_pages.view_dashboard')) and show an AccessDenied fallback when unauthorized

Applied to files:

  • src/app/(authenticated)/cars/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
📚 Learning: 2025-09-03T14:06:35.724Z
Learnt from: CR
PR: GRHInvDev/elo#0
File: .cursor/rules/07-security-access-control.mdc:0-0
Timestamp: 2025-09-03T14:06:35.724Z
Learning: Applies to **/use-access-control.{ts,tsx} : Provide a centralized access-control hook (useAccessControl) that exposes hasPermission and hasRole, checks sudo via user.role_config.sudo, and delegates specific checks to checkPermission

Applied to files:

  • src/app/(authenticated)/events/page.tsx
  • src/app/(authenticated)/flyers/page.tsx
🧬 Code graph analysis (3)
src/app/(authenticated)/cars/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewCars (178-186)
src/app/(authenticated)/events/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewEvents (148-156)
src/app/(authenticated)/flyers/page.tsx (1)
src/lib/access-control.ts (1)
  • canViewFlyers (158-166)
🔇 Additional comments (3)
src/app/(authenticated)/events/page.tsx (1)

27-29: Switched to role-based view check — correct and consistent.

Passing userData.role_config matches canViewEvents(roleConfig) and safely blocks when null/absent.

src/app/(authenticated)/flyers/page.tsx (1)

26-28: Role-config-based gate looks good.

Using canViewFlyers(userData.role_config) aligns with the updated access-control API.

src/app/(authenticated)/cars/page.tsx (1)

35-37: Updated permission check is correct.

canViewCars(userData.role_config) matches the new signature and prevents access when role_config is null.

Comment on lines +27 to 29
if (!canViewEvents(userData.role_config)) {
redirect("/dashboard")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify all view checks now pass role_config.

Scan for any leftover zero-arg calls to canViewEvents/canViewFlyers/canViewCars.


🏁 Script executed:

#!/bin/bash# Find zero-argument calls that should be passing role_configset -euo pipefail
echo"Calls missing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanView(?:Events|Flyers|Cars)\s*\(\s*\)' -S ||trueechoecho"Optionally, confirm create helpers are also passing role_config:"
rg -nP --glob 'src/**/*.{ts,tsx}''\bcanCreate(?:Event|Flyer)\s*\(\s*\)' -S ||true

Length of output: 536


Pass role_config to creation permission checks

  • Update calls to canCreateEvent() and canCreateFlyer() to canCreateEvent(userData.role_config) / canCreateFlyer(userData.role_config) in:
    src/components/create-event-button.tsx:63
    src/components/create-flyer-button.tsx:173

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@rbxyz