Skip to content

OM-356: modificar cantidades y eliminar productos del carrito. - #82

Merged
SebaKisser merged 5 commits into
devfrom
OM-356
Apr 7, 2026
Merged

SebaKisser merged 5 commits into
devfrom
OM-356

Conversation

@leoAchu16

@leoAchu16 leoAchu16 commented Apr 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Notas de lanzamiento

Nuevas Funcionalidades

  • Los usuarios ahora pueden eliminar artículos de sus carritos de compra de forma rápida y sencilla.
  • Los usuarios pueden actualizar la cantidad de artículos en sus carritos, con validación automática respecto al stock disponible en el catálogo.

@coderabbitai

coderabbitai Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Se agrega funcionalidad para eliminar y actualizar la cantidad de artículos del carrito mediante dos nuevos servicios, controladores y rutas autenticadas. Incluye validación de permisos, verificación de inventario y pruebas unitarias exhaustivas para servicios de carrito y órdenes.

Changes

Cohort / File(s) Summary
Cart API Layer
src/modules/users/cart/cart.controller.js, src/modules/users/cart/cart.routes.js
Dos nuevos controladores (removeCartItem, updateCartItemQuantity) con autenticación obligatoria y dos rutas correspondientes (DELETE y PUT) para gestionar items del carrito.
Cart Service Layer
src/modules/users/cart/cart.service.js
Dos nuevos servicios: removeCartItemService (elimina lógicamente items) y updatedCartItemQuantityService (valida stock y actualiza cantidades). Incluye validación de IDs, verificación de pertenencia del usuario y manejo de inventario.
Unit Tests
tests/unit/cart/cart.test.js
Suite de pruebas Vitest con 637 líneas que cubre cinco servicios de carrito: validación de autenticación, manejo de errores (ForbiddenError, ValidationError, NotFoundError), lógica de eliminación, actualización de cantidades y restricciones de stock.
Order Unit Tests
tests/unit/order/order.test.js
Suite de pruebas Vitest con 610 líneas para servicios de órdenes: creación, recuperación, filtrado por rol/estado/fechas, autorización basada en roles y transiciones de estados válidas.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • elianasmz
  • CrisNAC

Poem

🐰 Un conejito saltarín ve el carrito crecer,
Con rutas que eliminan, cantidades a vencer,
Stock validado, permisos en orden,
Las pruebas confirman: ¡nada que esconder! ✨🛒

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título describe con precisión los cambios principales: agregar funcionalidad para modificar cantidades y eliminar productos del carrito.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-356

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.

@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.

🧹 Nitpick comments (4)
src/modules/users/cart/cart.service.js (2)

295-330: LGTM - El servicio removeCartItemService está bien implementado.

La lógica de validación de pertenencia del item al carrito del usuario autenticado y el borrado lógico están correctamente implementados.

Nit menor: La variable updated en la línea 323 no se utiliza. Podés simplificar la llamada.

♻️ Eliminar variable no utilizada
   //se aplica el borrado logico del item
-  const updated = await prisma.cartItems.update({
+  await prisma.cartItems.update({
     where: { id_cart_item: resolvedCartItemId },
     data: { status: false }
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/cart/cart.service.js` around lines 295 - 330, The variable
`updated` in removeCartItemService is unused; remove the unnecessary assignment
by calling prisma.cartItems.update(...) without assigning its result (or await
it inline if needed) — keep the await to ensure the logical delete completes
before calling getCartWithItems(cartItem.fk_cart); update the
removeCartItemService function to drop the `updated` identifier and simply await
prisma.cartItems.update({ where: { id_cart_item: resolvedCartItemId }, data: {
status: false } }); before calling getCartWithItems and mapCartResponse.

337-376: El nombre de la función debería usar el verbo en presente.

La función updatedCartItemQuantityService usa el participio pasado "updated". Para mantener consistencia con los demás servicios (addCartItemService, removeCartItemService, getCartItemsByIdService), debería llamarse updateCartItemQuantityService.

♻️ Renombrar función para consistencia
-export const updatedCartItemQuantityService = async (authenticatedUserId, cartItemId, newQuantity) => {
+export const updateCartItemQuantityService = async (authenticatedUserId, cartItemId, newQuantity) => {

Nota: Recordá actualizar también el import y la llamada en cart.controller.js.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/cart/cart.service.js` around lines 337 - 376, The function
name uses past participle; rename exported function
updatedCartItemQuantityService to updateCartItemQuantityService and update all
references: change the exported identifier in
src/modules/users/cart/cart.service.js, update any imports and calls (e.g., in
cart.controller.js) to the new name, and keep the internal logic, signature
(authenticatedUserId, cartItemId, newQuantity) and related helpers
(parsePositiveInteger, getCartWithItems, mapCartResponse) unchanged so existing
behavior and tests remain intact.
src/modules/users/cart/cart.controller.js (1)

1-6: Nota: Actualizar el nombre del import si se renombra el servicio.

El import de updatedCartItemQuantityService deberá actualizarse si se aplica el refactor de nombre sugerido en el servicio.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/cart/cart.controller.js` around lines 1 - 6, El import en
cart.controller.js aún referencia updatedCartItemQuantityService; si en
cart.service.js renombraste la función (por ejemplo a
updateCartItemQuantityService), actualiza la importación en la lista de imports
(la declaración que incluye addCartItemService, getActiveCartsForUserService,
getCartItemsByIdService, removeCartItemService, updatedCartItemQuantityService)
para usar el nuevo identificador exacto que exporta cart.service.js, y verifica
que todas las referencias en este archivo usen ese mismo nombre.
tests/unit/order/order.test.js (1)

364-394: Los tests de filtros podrían ser más específicos.

Los tests para filtros por order_status y rango de fechas solo verifican que $transaction fue llamado, pero no validan que los filtros se aplicaron correctamente en el query. Esto es aceptable para tests unitarios básicos, pero podrías considerar agregar assertions más específicas en el futuro.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/order/order.test.js` around lines 364 - 394, The tests currently
only assert prisma.$transaction was called; improve them by inspecting the
actual query arguments passed into the mocked prisma.$transaction to verify the
filters are built correctly: after calling getStoreOrdersService, read
prisma.$transaction.mock.calls[0][0] (the transaction array) and locate the
orders findMany call (e.g., the first element used as findManyCall), then assert
that its 'where' contains the expected order_status conditions (single value or
array for comma-separated statuses) and that the date range produces a
created_at (or appropriate field) filter with gte/lte for date_from/date_to;
update the three tests to include these specific expect checks referencing
getStoreOrdersService and prisma.$transaction.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/modules/users/cart/cart.controller.js`:
- Around line 1-6: El import en cart.controller.js aún referencia
updatedCartItemQuantityService; si en cart.service.js renombraste la función
(por ejemplo a updateCartItemQuantityService), actualiza la importación en la
lista de imports (la declaración que incluye addCartItemService,
getActiveCartsForUserService, getCartItemsByIdService, removeCartItemService,
updatedCartItemQuantityService) para usar el nuevo identificador exacto que
exporta cart.service.js, y verifica que todas las referencias en este archivo
usen ese mismo nombre.

In `@src/modules/users/cart/cart.service.js`:
- Around line 295-330: The variable `updated` in removeCartItemService is
unused; remove the unnecessary assignment by calling
prisma.cartItems.update(...) without assigning its result (or await it inline if
needed) — keep the await to ensure the logical delete completes before calling
getCartWithItems(cartItem.fk_cart); update the removeCartItemService function to
drop the `updated` identifier and simply await prisma.cartItems.update({ where:
{ id_cart_item: resolvedCartItemId }, data: { status: false } }); before calling
getCartWithItems and mapCartResponse.
- Around line 337-376: The function name uses past participle; rename exported
function updatedCartItemQuantityService to updateCartItemQuantityService and
update all references: change the exported identifier in
src/modules/users/cart/cart.service.js, update any imports and calls (e.g., in
cart.controller.js) to the new name, and keep the internal logic, signature
(authenticatedUserId, cartItemId, newQuantity) and related helpers
(parsePositiveInteger, getCartWithItems, mapCartResponse) unchanged so existing
behavior and tests remain intact.

In `@tests/unit/order/order.test.js`:
- Around line 364-394: The tests currently only assert prisma.$transaction was
called; improve them by inspecting the actual query arguments passed into the
mocked prisma.$transaction to verify the filters are built correctly: after
calling getStoreOrdersService, read prisma.$transaction.mock.calls[0][0] (the
transaction array) and locate the orders findMany call (e.g., the first element
used as findManyCall), then assert that its 'where' contains the expected
order_status conditions (single value or array for comma-separated statuses) and
that the date range produces a created_at (or appropriate field) filter with
gte/lte for date_from/date_to; update the three tests to include these specific
expect checks referencing getStoreOrdersService and prisma.$transaction.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 37e7867e-264d-4143-8e92-bcf6a51c6eb3

📥 Commits

Reviewing files that changed from the base of the PR and between 09d1743 and 69cf143.

📒 Files selected for processing (5)
  • src/modules/users/cart/cart.controller.js
  • src/modules/users/cart/cart.routes.js
  • src/modules/users/cart/cart.service.js
  • tests/unit/cart/cart.test.js
  • tests/unit/order/order.test.js

@SebaKisser
SebaKisser merged commit f229dac into dev Apr 7, 2026
2 checks passed
@Andoumeda
Andoumeda deleted the OM-356 branch April 11, 2026 17:12
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
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.

2 participants