Skip to content

OM-322: listado y eliminación de repartidores vinculados al comercio - #139

Merged
CrisNAC merged 3 commits into
devfrom
OM-322-BE-Listado-y-eliminación-de-delivery-Comercio
May 7, 2026

Hidden character warning

The head ref may contain hidden characters: "OM-322-BE-Listado-y-eliminaci\u00f3n-de-delivery-Comercio"
Merged

CrisNAC merged 3 commits into
devfrom
OM-322-BE-Listado-y-eliminación-de-delivery-Comercio

Conversation

@josediaz33

@josediaz33 josediaz33 commented May 4, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Summary by CodeRabbit

Notas de Lanzamiento

  • Nuevas Funcionalidades
    • Propietarios de tiendas pueden listar sus entregas con estadísticas detalladas (estado por entrega, conteos, tasa de éxito y calificación promedio).
    • Propietarios pueden desenlazar entregas de la tienda cuando no existan asignaciones activas pendientes o aceptadas.
  • Tests
    • Cobertura ampliada para endpoints de entregas: listado, desvinculación y validaciones de parámetros, autorizaciones y respuestas esperadas.

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

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@josediaz33 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 51 minutes and 44 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a1329d6b-ff62-4474-8749-cc9eb9050ed7

📥 Commits

Reviewing files that changed from the base of the PR and between 92b614b and 1ea8e82.

📒 Files selected for processing (2)
  • src/modules/commerce/deliveries/delivery.service.js
  • tests/unit/commerce/delivery.test.js
📝 Walkthrough

Walkthrough

Se agregan dos endpoints autenticados de tienda: GET /:id/deliveries para listar entregas con estadísticas agregadas y DELETE /:id/deliveries/:deliveryId para desvincular una entrega. Se implementan los servicios correspondientes con validaciones de propiedad y restricciones por asignaciones activas; se extienden las pruebas unitarias.

Changes

Gestión de Entregas de Tienda

Layer / File(s) Summary
Data Shape / Queries
src/modules/commerce/deliveries/delivery.service.js
Se introducen consultas a prisma.deliveries.findMany/findFirst y update para obtener entregas activas con relaciones (assignments, reviews) y para desvincular (fk_store = null).
Core Service Logic
src/modules/commerce/deliveries/delivery.service.js
Se agregan getStoreDeliveriesService(authUserId, storeId) (autoriza propietario, mapea entregas con status, completedDeliveries, successRate, avgRating, y agrega stats) y deleteStoreDeliveryService(authUserId, storeId, deliveryId) (valida propiedad, chequea asignaciones PENDING/ACCEPTED y realiza update para unlink).
Controller Wiring
src/modules/commerce/deliveries/delivery.controller.js
Se importan y exponen getStoreDeliveries y deleteStoreDelivery, que llaman a sus servicios, responden 200/204 respectivamente y normalizan errores (`error.status
Routing / API Surface
src/modules/commerce/deliveries/delivery.routes.js
Se registran rutas autenticadas SELLER: GET /:id/deliveries → getStoreDeliveries y DELETE /:id/deliveries/:deliveryId → deleteStoreDelivery (con documentación Swagger).
Tests / Mocks
tests/unit/commerce/delivery.test.js
Se extiende el mock de Prisma (deliveries.findMany, findFirst, update), se agregan fixtures (assignments, reviews) y se añaden pruebas para estadísticas, estados derivados (AVAILABLE/IN_DELIVERY/UNAVAILABLE), reglas de eliminación y respuestas (incl. 204 en DELETE).

Diagrama de Secuencia

sequenceDiagram
    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
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

  • CrisNAC/BackendMarketplace#127: Modifica controladores/servicios/rutas de deliveries; agrega búsqueda/creación/enlace de entregas — directamente relacionado a los endpoints de tienda.
  • CrisNAC/BackendMarketplace#134: Introduce cambios de esquema (Deliveries.fk_store nullable y VehicleType) que la nueva lógica de desvinculación y mapeo de vehicleType utiliza.
  • CrisNAC/BackendMarketplace#124: Añade el enum/estructura de AssignmentStatus y campos de DeliveryAssignments que los servicios consultan para validar estados PENDING/ACCEPTED.

Suggested Reviewers

  • Benjakr04
  • CrisNAC
  • leoAchu16

Poem

🐰
Entregas que vienen y van,
Cuentas y estados al compás,
Tienda desenlaza sin pesar,
Pruebas saltan a confirmar,
¡Saltito y listo para desplegar!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 las funcionalidades principales implementadas: listado y eliminación de repartidores vinculados al comercio, alineado completamente con los objetivos del PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-322-BE-Listado-y-eliminación-de-delivery-Comercio

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.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9a961f3 and 379e66f.

📒 Files selected for processing (4)
  • src/modules/commerce/deliveries/delivery.controller.js
  • src/modules/commerce/deliveries/delivery.routes.js
  • src/modules/commerce/deliveries/delivery.service.js
  • tests/unit/commerce/delivery.test.js

Comment thread src/modules/commerce/deliveries/delivery.service.js Outdated
Comment thread src/modules/commerce/deliveries/delivery.service.js Outdated
Comment thread tests/unit/commerce/delivery.test.js Outdated
@sonarqubecloud

sonarqubecloud Bot commented May 6, 2026

Copy link
Copy Markdown

@CrisNAC
CrisNAC merged commit 682edb8 into dev May 7, 2026
4 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.

2 participants