Skip to content

better database filters #167

Merged
henri318 merged 3 commits into
mainfrom
chore/create_better_user_cases
Jul 18, 2026
Merged

better database filters #167
henri318 merged 3 commits into
mainfrom
chore/create_better_user_cases

Conversation

@henri318

@henri318 henri318 commented Jul 18, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Nuevas funcionalidades

    • El carrito y el checkout muestran información enriquecida de productos, vendedores y personalizaciones.
    • Se aplica el descuento de primera compra y se agrupan los artículos por vendedor.
    • Las portadas de productos enlazan directamente con sus páginas de detalle.
    • Los formularios de productos cargan categorías y datos de forma más consistente.
  • Mejoras visuales

    • Se ajusta la cuadrícula de productos y se optimiza la visualización en dispositivos móviles.
  • Pruebas

    • Se amplía la cobertura de carrito, checkout, productos, categorías y navegación.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@henri318, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 20 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b1761f69-29d7-4a7a-a6d1-2ce55aa5e230

📥 Commits

Reviewing files that changed from the base of the PR and between 79754ef and 784022e.

📒 Files selected for processing (9)
  • composition-root/container.ts
  • modules/cart/application/get-checkout-view-use-case.ts
  • modules/cart/infrastructure/cart-product-repository-adapter.ts
  • modules/products/application/get-cart-product-views-use-case.ts
  • tests/e2e/personalization-flow.spec.ts
  • tests/unit/modules/cart/application/get-cart-view-use-case.test.ts
  • tests/unit/modules/cart/application/get-checkout-view-use-case.test.ts
  • tests/unit/modules/cart/infrastructure/cart-product-repository-adapter.test.ts
  • tests/unit/modules/products/application/get-cart-product-views-use-case.test.ts
📝 Walkthrough

Walkthrough

Las páginas delegan la obtención y transformación de datos a casos de uso resueltos por el contenedor. Se añaden modelos de carrito y checkout, carga del formulario de producto, búsquedas masivas, navegación de portadas y reglas de frontera arquitectónica.

Changes

Application boundaries and composition

Layer / File(s) Summary
Composition root y contratos de aplicación
composition-root/container.ts, modules/cart/..., modules/products/..., modules/orders/...
El contenedor expone e invalida nuevos casos de uso; se añaden modelos de carrito/checkout, búsquedas masivas de productos y carga validada del formulario de vendedor.
Modelos de carrito y checkout
app/[locale]/cart/page.tsx, app/[locale]/checkout/page.tsx, modules/cart/..., tests/unit/modules/cart/...
La construcción de ítems, personalizaciones, agrupaciones, descuentos, envíos y totales pasa a casos de uso dedicados con cobertura unitaria.
Páginas como adaptadores
app/[locale]/admin/..., app/[locale]/orders/..., app/[locale]/seller/..., app/[locale]/page.tsx, app/[locale]/products/..., docs/architecture.md
Las páginas obtienen casos de uso desde container; la documentación formaliza esta frontera de presentación.
Navegación y presentación de productos
components/products/infinite-product-list.tsx, app/[locale]/page.module.css, tests/unit/components/products/...
Las portadas enlazan al detalle localizado y se actualizan estilos de cuadrícula, enlaces y descripciones móviles.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CheckoutPage
  participant GetCheckoutViewUseCase
  participant GetCartViewUseCase
  participant PaidOrderCountPort
  CheckoutPage->>GetCheckoutViewUseCase: execute(dto)
  GetCheckoutViewUseCase->>GetCartViewUseCase: obtener CartViewData
  GetCheckoutViewUseCase->>PaidOrderCountPort: contar pedidos pagados
  GetCheckoutViewUseCase-->>CheckoutPage: devolver CheckoutViewData
Loading

Possibly related PRs

Suggested labels: type:chore

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título alude a mejoras en filtros de base de datos, pero no resume el cambio principal de la PR, que es la centralización de casos de uso en el container.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/create_better_user_cases

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (3)
app/[locale]/seller/products/[id]/edit/page.tsx (1)

20-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Considerar redirigir al inicio de sesión.

Para mejorar la experiencia del usuario y mantener la consistencia (de manera similar a cómo se maneja en app/[locale]/seller/orders/page.tsx), podrías considerar el uso de redirect para enviar a los usuarios no autenticados a la página de inicio de sesión, en lugar de mostrar un error 404.

💡 Posible mejora

Asegúrate de agregar redirect a las importaciones de next/navigation:

-  if (!session?.id) {
-    notFound();
-  }
+  if (!session?.id) {
+    redirect(`/${locale}/auth/signin?callbackUrl=/${locale}/seller/products/${id}/edit`);
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/`[locale]/seller/products/[id]/edit/page.tsx around lines 20 - 22,
Replace the notFound() handling in the unauthenticated branch of the edit page
with the existing login redirect pattern used by the seller orders page,
importing redirect from next/navigation as needed. Preserve the current
authenticated flow.
tests/unit/modules/products/application/get-seller-product-form-use-case.test.ts (1)

73-104: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Añade cobertura para un producto inexistente.

La suite cubre un propietario incorrecto, pero no la rama !product. Añade un caso con el repositorio vacío y verifica NotFoundError.

Propuesta de prueba
+  it('rejects a missing product', async () => {
+    const useCase = new GetSellerProductFormUseCase(
+      new MemoryProductRepository(),
+      new ListCategoriesUseCase(categoryRepository()),
+      sellerLookup('seller-1'),
+    );
+
+    await expect(
+      useCase.execute({
+        userId: 'user-1',
+        productId: 'missing-product',
+        locale: 'es',
+      }),
+    ).rejects.toBeInstanceOf(NotFoundError);
+  });

As per coding guidelines, tests must include “invalid inputs” and “error conditions”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@tests/unit/modules/products/application/get-seller-product-form-use-case.test.ts`
around lines 73 - 104, añade un caso de prueba para producto inexistente junto
al test de propiedad incorrecta, usando un MemoryProductRepository vacío y
ejecutando GetSellerProductFormUseCase con un productId que no existe; verifica
que useCase.execute rechace con NotFoundError para cubrir la rama !product.

Source: Coding guidelines

tests/unit/composition-root/container-use-case-cache.test.ts (1)

14-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verifica cada dependencia que invalida la vista del carrito.

Repite la aserción al sustituir CartProductRepository y CustomizationLookup; comprueba también que estas sustituciones reconstruyen el checkout derivado. Ahora solo queda protegida la ruta de CartRepository.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/composition-root/container-use-case-cache.test.ts` around lines 14
- 23, Amplía la prueba `rebuilds the cart view after replacing the cart
repository` para verificar que sustituir `CartProductRepository` y
`CustomizationLookup` también invalida y reconstruye `getCartViewUseCase()`.
Añade aserciones independientes tras cada reemplazo, manteniendo la comprobación
existente para `CartRepository` y cubriendo igualmente la reconstrucción del
checkout derivado.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modules/cart/application/get-checkout-view-use-case.ts`:
- Around line 95-107: Actualiza emptyCheckoutView para que un checkout sin
artículos devuelva shipping y total en cero, en lugar de usar SHIPPING_COST.
Mantén sin cambios los demás valores del estado vacío.

In `@modules/cart/infrastructure/cart-product-repository-adapter.ts`:
- Line 6: El adaptador CartProductRepositoryAdapter importa y ejecuta lógica de
dominio de Products mediante resolveDisplay, cruzando el límite modular.
Sustituye esa dependencia por un puerto/query de Products que devuelva
directamente el nombre localizado, y actualiza el adaptador para transformar
únicamente ese contrato en ProductSnapshot, eliminando la importación y uso de
resolveDisplay.

In `@tests/unit/modules/cart/application/get-cart-view-use-case.test.ts`:
- Around line 12-120: Extend the GetCartViewUseCase tests with an empty-cart
case using the existing repository fakes: save a cart whose items array is
empty, execute the use case, and assert the result is { items: [] }. Configure
or inspect the product and customization repositories to verify neither is
queried during processing.

In `@tests/unit/modules/cart/application/get-checkout-view-use-case.test.ts`:
- Around line 14-76: The GetCheckoutViewUseCase tests only cover the discounted
first-purchase path. Add tests covering an empty cart with shipping and total
equal to zero, mixed currencies that reject with ValidationError, and a repeat
buyer with no discount, reusing the existing repositories and execute setup from
the current test.

In
`@tests/unit/modules/cart/infrastructure/cart-product-repository-adapter.test.ts`:
- Around line 6-15: Amplía la prueba alrededor de
CartProductRepositoryAdapter.findByIds para que el mock findByIds devuelva un
producto de ejemplo en lugar de un arreglo vacío y verifica el resultado
transformado por el adaptador. Incluye aserciones sobre displayName, sellerName,
imageUrl e images, manteniendo también la comprobación de que la delegación usa
los IDs y la categoría esperados.

---

Nitpick comments:
In `@app/`[locale]/seller/products/[id]/edit/page.tsx:
- Around line 20-22: Replace the notFound() handling in the unauthenticated
branch of the edit page with the existing login redirect pattern used by the
seller orders page, importing redirect from next/navigation as needed. Preserve
the current authenticated flow.

In `@tests/unit/composition-root/container-use-case-cache.test.ts`:
- Around line 14-23: Amplía la prueba `rebuilds the cart view after replacing
the cart repository` para verificar que sustituir `CartProductRepository` y
`CustomizationLookup` también invalida y reconstruye `getCartViewUseCase()`.
Añade aserciones independientes tras cada reemplazo, manteniendo la comprobación
existente para `CartRepository` y cubriendo igualmente la reconstrucción del
checkout derivado.

In
`@tests/unit/modules/products/application/get-seller-product-form-use-case.test.ts`:
- Around line 73-104: añade un caso de prueba para producto inexistente junto al
test de propiedad incorrecta, usando un MemoryProductRepository vacío y
ejecutando GetSellerProductFormUseCase con un productId que no existe; verifica
que useCase.execute rechace con NotFoundError para cubrir la rama !product.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: fcc9c5a0-6795-4ccc-8371-5fe844094023

📥 Commits

Reviewing files that changed from the base of the PR and between 96495ff and 79754ef.

📒 Files selected for processing (50)
  • app/[locale]/admin/configuration/page.tsx
  • app/[locale]/admin/sellers/[sellerId]/page.tsx
  • app/[locale]/admin/sellers/[sellerId]/products/page.tsx
  • app/[locale]/admin/sellers/page.tsx
  • app/[locale]/cart/page.tsx
  • app/[locale]/checkout/page.tsx
  • app/[locale]/orders/[orderId]/page.tsx
  • app/[locale]/orders/page.tsx
  • app/[locale]/page.module.css
  • app/[locale]/page.tsx
  • app/[locale]/products/[id]/page.tsx
  • app/[locale]/seller/orders/[orderId]/page.tsx
  • app/[locale]/seller/orders/page.tsx
  • app/[locale]/seller/products/[id]/edit/page.tsx
  • app/[locale]/seller/products/new/page.tsx
  • app/[locale]/seller/products/page.tsx
  • components/products/infinite-product-list.tsx
  • composition-root/container.ts
  • docs/architecture.md
  • modules/cart/application/get-cart-view-use-case.ts
  • modules/cart/application/get-checkout-view-use-case.ts
  • modules/cart/domain/product-snapshot.ts
  • modules/cart/infrastructure/cart-product-repository-adapter.ts
  • modules/orders/infrastructure/product-repository-adapter.ts
  • modules/products/application/get-seller-product-form-use-case.ts
  • modules/products/application/list-categories-use-case.ts
  • modules/products/domain/product-repository.ts
  • modules/products/domain/seller-ownership-lookup-port.ts
  • modules/products/infrastructure/prisma-product-repository.ts
  • modules/products/infrastructure/seller-ownership-lookup-adapter.ts
  • tests/doubles/memory-cart-product-repository.ts
  • tests/doubles/memory-product-repository.ts
  • tests/unit/app/[locale]/admin/configuration/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/[sellerId]/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/[sellerId]/products/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/page.test.tsx
  • tests/unit/app/[locale]/checkout/page.test.tsx
  • tests/unit/app/[locale]/orders/page.test.tsx
  • tests/unit/app/[locale]/page.test.tsx
  • tests/unit/app/[locale]/products/[id]/page.test.tsx
  • tests/unit/app/[locale]/seller/orders/page.test.tsx
  • tests/unit/app/[locale]/seller/products/page.test.tsx
  • tests/unit/components/products/infinite-product-list.test.tsx
  • tests/unit/composition-root/container-use-case-cache.test.ts
  • tests/unit/modules/cart/application/get-cart-view-use-case.test.ts
  • tests/unit/modules/cart/application/get-checkout-view-use-case.test.ts
  • tests/unit/modules/cart/infrastructure/cart-product-repository-adapter.test.ts
  • tests/unit/modules/products/application/get-seller-product-form-use-case.test.ts
  • tests/unit/modules/products/application/list-categories-use-case.test.ts
  • tests/unit/modules/products/infrastructure/prisma-product-repository.test.ts
💤 Files with no reviewable changes (10)
  • tests/unit/app/[locale]/checkout/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/[sellerId]/products/page.test.tsx
  • tests/unit/app/[locale]/admin/configuration/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/[sellerId]/page.test.tsx
  • tests/unit/app/[locale]/orders/page.test.tsx
  • tests/unit/app/[locale]/admin/sellers/page.test.tsx
  • tests/unit/app/[locale]/page.test.tsx
  • tests/unit/app/[locale]/products/[id]/page.test.tsx
  • tests/unit/app/[locale]/seller/products/page.test.tsx
  • tests/unit/app/[locale]/seller/orders/page.test.tsx

Comment thread modules/cart/application/get-checkout-view-use-case.ts
Comment thread modules/cart/infrastructure/cart-product-repository-adapter.ts Outdated
Comment thread tests/unit/modules/cart/application/get-cart-view-use-case.test.ts
@henri318
henri318 merged commit 8b80f0f into main Jul 18, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant