Repository navigation
OM-322: listado y eliminación de repartidores vinculados al comercio - #139
Hidden character warning
Conversation
Implementa los dos endpoints del ticket OM-322 para la gestión de
repartidores desde el panel del comercio (rol SELLER).
Endpoints agregados
───────────────────
GET /api/stores/:id/deliveries
- Retorna { stats, deliveries } donde stats incluye total,
available, inDelivery y avgRating global (para el header del frontend).
- Cada delivery expone: id, user (id/name/email/phone), status derivado,
vehicleType, completedDeliveries, successRate y avgRating individual.
- El status se deriva en runtime:
· AVAILABLE → delivery_status = ACTIVE sin asignaciones activas
· IN_DELIVERY → tiene asignación PENDING o ACCEPTED
· UNAVAILABLE → delivery_status = INACTIVE o SUSPENDED
- successRate = DELIVERED / (DELIVERED + REJECTED) × 100
(null si aún no hay historial terminal).
- Solo accesible por el dueño del comercio (403 en caso contrario).
DELETE /api/stores/:id/deliveries/:deliveryId
- Desvincula el repartidor del comercio (fk_store = null).
- No elimina al usuario ni su historial de entregas.
- Bloquea la operación si el delivery tiene entregas activas
(assignment_status IN [PENDING, ACCEPTED]) → 400.
- Retorna 204 No Content al completarse.
|
Warning Rate limit exceeded
To continue reviewing without waiting, purchase usage credits in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughSe agregan dos endpoints autenticados de tienda: GET ChangesGestión de Entregas de Tienda
Diagrama de SecuenciasequenceDiagram
participant Cliente
participant Controlador as Controlador<br/>(getStoreDeliveries / deleteStoreDelivery)
participant Servicio as Servicio<br/>(getStoreDeliveriesService / deleteStoreDeliveryService)
participant BD as Prisma<br/>(Deliveries, Assignments, Reviews)
Cliente->>Controlador: GET /stores/:id/deliveries\nó DELETE /stores/:id/deliveries/:deliveryId
Controlador->>Servicio: pasar authenticatedUserId, storeId[, deliveryId]
Servicio->>BD: findMany / findFirst (entregas + asignaciones + reseñas)
BD-->>Servicio: entregas, asignaciones, reseñas
Servicio->>Servicio: calcular stats y campos derivados por entrega
alt DELETE
Servicio->>BD: findFirst (asignación PENDING/ACCEPTED)
alt hay asignación activa
Servicio-->>Controlador: lanzar error (400)
else
Servicio->>BD: update (fk_store = null)
BD-->>Servicio: entrega actualizada
Servicio-->>Controlador: éxito (204)
end
else GET
Servicio-->>Controlador: stats + lista de entregas mapeadas (200)
end
Controlador-->>Cliente: 200 JSON / 204 vacío
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly Related PRs
Suggested Reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/modules/commerce/deliveries/delivery.service.js`:
- Around line 165-186: La verificación de asignaciones activas y el update son
operaciones separadas (prisma.deliveries.findFirst y prisma.deliveries.update) y
sufren TOCTOU; reescribe esta sección para ejecutar la lectura y el posible
update dentro de una única transacción interactiva de Prisma
(prisma.$transaction) o transaction API, realizando el find/select de delivery
(incluyendo delivery_assignments filter) dentro de la transacción, comprobar ahí
mismo delivery.delivery_assignments.length y, sólo si no hay asignaciones
activas, realizar el update fk_store: null dentro de la misma transacción; lanza
NotFoundError o ValidationError desde dentro de la transacción según
corresponda.
- Around line 183-186: El registro de Deliveries se queda huérfano al solo hacer
prisma.deliveries.update({ where: { id_delivery: deliveryId }, data: { fk_store:
null }}), por lo que hay que (1) al desvincular en la función que hace el update
también resetear delivery_status a 'INACTIVE' (actualiza el data para incluir
delivery_status: 'INACTIVE') y (2) adaptar searchDeliveryCandidatesService para
que no solo busque usuarios con delivery: null sino que también incluya usuarios
cuyo Delivery existe pero tiene fk_store === null (filtrar por delivery.fk_store
=== null o añadir condición equivalente) para que esos repartidores vuelvan a
aparecer en candidatos.
In `@tests/unit/commerce/delivery.test.js`:
- Around line 421-426: The test's assertion is vacuous because prisma.users in
the vi.mock doesn't include a delete mock; update the mock in vi.mock to expose
delete: vi.fn() alongside findMany/findUnique/findFirst, and replace the current
expect(prisma.users).not.toHaveProperty("delete") check with an explicit
invocation assertion such as expect(prisma.users.delete).not.toHaveBeenCalled()
to verify the service did not attempt to delete a user (referencing
prisma.users.delete and the vi.mock block).
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 42e2c5ec-0883-44b7-b4da-7c500f084130
📒 Files selected for processing (4)
src/modules/commerce/deliveries/delivery.controller.jssrc/modules/commerce/deliveries/delivery.routes.jssrc/modules/commerce/deliveries/delivery.service.jstests/unit/commerce/delivery.test.js
|



Implementa los dos endpoints del ticket OM-322 para la gestión de repartidores desde el panel del comercio (rol SELLER).
Endpoints agregados
───────────────────
GET /api/stores/:id/deliveries
· AVAILABLE → delivery_status = ACTIVE sin asignaciones activas
· IN_DELIVERY → tiene asignación PENDING o ACCEPTED
· UNAVAILABLE → delivery_status = INACTIVE o SUSPENDED
(null si aún no hay historial terminal).
DELETE /api/stores/:id/deliveries/:deliveryId
Summary by CodeRabbit
Notas de Lanzamiento