refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

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

refactor: update food order validation logic and schema to allow opti… - #180

Merged
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos
Oct 15, 2025
Merged

refactor: update food order validation logic and schema to allow opti…#180
rbxyz merged 1 commit into
mainfrom
179-ajuste-nos-pedidos

Conversation

@rbxyz

@rbxyzrbxyz commented Oct 15, 2025

Copy link
Copy Markdown
Collaborator

…onal choices

Summary by CodeRabbit

  • Bug Fixes
    • You can now place orders for items that have no available options; the app no longer errors in this scenario.
    • Validation correctly treats option selections as optional, so you don’t need to choose options when none exist.
    • Order creation omits option selections when none are chosen, preventing false validation failures.
    • Removed redundant checks that previously blocked valid orders without options.

@rbxyzrbxyz linked an issue Oct 15, 2025 that may be closed by this pull request
@vercel

vercelBot commented Oct 15, 2025

Copy link
Copy Markdown

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

ProjectDeploymentPreviewCommentsUpdated (UTC)
eloReadyReadyPreviewCommentOct 15, 2025 0:19am

@coderabbitai

coderabbitaiBot commented Oct 15, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes relax option selection requirements when creating food orders: UI components allow orders without selected options, schema makes optionChoices optional, and server-side validation of required options is removed. Control flow now proceeds to order creation without enforcing option selection, sending optionChoices as undefined when not provided.

Changes

Cohort / File(s)Summary
UI: Food ordering page and option handling
src/app/(authenticated)/food/page.tsx
Allows order creation when no options are selected; sends optionChoices as undefined if empty; triggers automatic validation true when an item has no optional choices; formatting cleanups.
Validation schema
src/schemas/food-order.schema.ts
optionChoices changed from required z.array(z.string()).min(1, ...) to z.array(z.string()).optional().
API: Order creation router
src/server/api/routers/food-order.ts
Removed server-side validation enforcing required menu item options; flow now directly checks existing orders and creates order without option validation.

Sequence Diagram(s)

sequenceDiagram
autonumber
actor U as User
participant FP as FoodPage (UI)
participant API as food-order router
participant DB as Database
U->>FP: Select menu item (no options selected)
Note over FP: Auto-validate true if no optional items
FP->>API: createOrder({ optionChoices: undefined })
API->>DB: Check existing open order
alt Order exists
API-->>FP: Return existing order
else No order
API->>DB: Create order (no option validation)
API-->>FP: Return new order
end
Loading
sequenceDiagram
autonumber
participant API as food-order router
%% Previous (removed) behavior
rect rgba(255, 228, 225, 0.5)
note right of API: Previous flow (removed)
API->>API: Fetch menu item options
API->>API: Filter required options
API->>API: Validate input contains required choices
API-->>API: Throw BAD_REQUEST on missing required
end
%% Current behavior
rect rgba(225, 255, 228, 0.5)
note right of API: Current flow
API->>API: Skip option validation
end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • jdalmeida

Poem

I hop through forms where choices fade,
A basket of orders neatly made.
No toppings? Fine—I won’t complain,
The schema nods, the servers refrain.
With optional whispers, carts take flight—
Thump-thump, approved, on moonlit night. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check nameStatusExplanationResolution
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title Check✅ PassedThe title succinctly conveys the primary refactoring of food order validation logic and schema. It accurately highlights the shift to allowing optional choices, which reflects the core functional changes. The phrasing is clear and follows conventional commit style without unnecessary details or noise.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 179-ajuste-nos-pedidos

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c073d9d and 8a2a4a7.

📒 Files selected for processing (3)
  • src/app/(authenticated)/food/page.tsx (4 hunks)
  • src/schemas/food-order.schema.ts (1 hunks)
  • src/server/api/routers/food-order.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/server/api/routers/food-order.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/page.tsx
src/schemas/**

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

Place Zod schemas and validations under src/schemas

Files:

  • src/schemas/food-order.schema.ts
**/*.{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/schemas/food-order.schema.ts
  • src/app/(authenticated)/food/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)/food/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)/food/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)/food/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)/food/page.tsx
🔇 Additional comments (3)
src/app/(authenticated)/food/page.tsx (2)

41-45: LGTM! Auto-validation for items without options.

The logic correctly handles the case where a menu item has no selectable options by automatically marking the form as valid. This prevents users from being blocked when ordering items that don't require option selection.


191-198: LGTM! Correct handling of optional choices.

The implementation correctly:

  1. Flattens the selected choices into an array
  2. Sends undefined instead of an empty array when no options are selected, which properly aligns with the schema change making optionChoices optional

This approach follows best practices for optional Zod schema fields.

src/schemas/food-order.schema.ts (1)

8-8: Backend handling of optional optionChoices verified. Router skips creating selections when optionChoices is undefined or empty, and the Prisma model uses a one-to-many relation (OrderOptionSelection[]) so no nullability issues.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@rbxyz
rbxyz merged commit 9a414cc into mainOct 15, 2025
7 of 9 checks passed
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.

Ajuste nos pedidos

1 participant

@rbxyz