Skip to content

Add delivery order history endpoint and validation schema - #133

Merged
leoAchu16 merged 6 commits into
devfrom
OM-493-get-delivery-orders
May 2, 2026
Merged

leoAchu16 merged 6 commits into
devfrom
OM-493-get-delivery-orders

Conversation

@CrisNAC

@CrisNAC CrisNAC commented May 1, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Nuevas Funcionalidades

    • Endpoint para consultar el historial de órdenes de una entrega con filtros (período, estado de asignación, ID de orden, nombre de usuario) y paginación.
  • Documentación

    • Esquema de respuesta Swagger agregado para el historial de órdenes con campos paginados y estructura de contenido.
  • Tests

    • Cobertura unitaria ampliada para el nuevo servicio y distintos escenarios de filtrado y paginación.

@coderabbitai

coderabbitai Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

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

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ 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: d7114340-2075-4e49-bc99-d5a40433a124

📥 Commits

Reviewing files that changed from the base of the PR and between 93b1749 and 39673f2.

📒 Files selected for processing (2)
  • src/docs/schemas/delivery.schema.js
  • tests/unit/delivery/delivery-assignments.test.js
📝 Walkthrough

Walkthrough

Se añade un endpoint protegido GET /api/assignments/{id}/orders con validación Zod, paginación y un servicio que consulta el historial de asignaciones de entrega, plus esquema Swagger para la respuesta paginada y tests unitarios que cubren filtros y formato de respuesta.

Changes

Historial de órdenes de entrega

Layer / File(s) Summary
Data Shape (API / Docs)
src/docs/schemas/delivery.schema.js
Se agrega DeliveryOrderHistoryResponse — objeto paginado con content[] de asignaciones y order anidado (incluye user, store, total, shipping_cost) y metadatos de paginación.
Validation (input)
src/modules/delivery/delivery-assignments/delivery-assignments.validation.js
Nuevo deliveryOrderHistoryQuerySchema (Zod) para period, assignment_status, orderId (transforma a Number) y userName.
Core Service / Data Access
src/modules/delivery/delivery-assignments/delivery-assignments.service.js
Nuevo getDeliveryOrderHistoryService(deliveryId, authenticatedUserId, filters, pagination) que valida deliveryId, autoriza por propietario, construye filtro Prisma (periodo, estado, orderId, userName), ejecuta $transaction con findMany y count, y devuelve estructura paginada (coerción numérica de montos).
Wiring: Controller & Routes
src/modules/delivery/delivery-assignments/delivery-assignments.controller.js, src/modules/delivery/delivery-assignments/delivery-assignments.routes.js
Ruta GET /api/assignments/{id}/orders añadida; middleware authenticate, requireRole(ROLES.DELIVERY), parsePagination; controlador getDeliveryOrderHistory valida query, invoca servicio y devuelve 200/400/err.status. Incluye docs OpenAPI en la ruta.
Tests
tests/unit/delivery/delivery-assignments.test.js
Se añaden tests unitarios para getDeliveryOrderHistoryService: fixtures, mocks de Prisma (deliveryAssignments.findMany, .count, $transaction array/callback), casos de validación/autorización, paginación y filtros (period, assignment_status, orderId, userName).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant Middleware
    participant Controller
    participant Service
    participant Database

    Client->>Router: GET /api/assignments/{id}/orders?page=1&period=7d
    Router->>Middleware: authenticate, requireRole, parsePagination
    Middleware-->>Router: ok
    Router->>Controller: getDeliveryOrderHistory(req)
    Controller->>Controller: validar con deliveryOrderHistoryQuerySchema
    Controller->>Service: getDeliveryOrderHistoryService(id, userId, filters, pagination)
    Service->>Database: find delivery por id
    Database-->>Service: delivery (o null)
    Service->>Database: $transaction [findMany(filters,pagination), count(filters)]
    Database-->>Service: assignments[], totalCount
    Service->>Service: mapear contenido y convertir montos a Number
    Service-->>Controller: respuesta paginada
    Controller-->>Client: 200 {content, total_elements, total_pages, page, size}
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • Benjakr04
  • Lianyang1234

Poem

🐰 Salté entre líneas y código,
traje un historial bien ordenado,
filtros, páginas y dueño comprobado,
en cada entrega un registro dorado,
¡brinca la rama, todo está documentado! 🥕

🚥 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 de manera clara y precisa los cambios principales: la adición de un endpoint para obtener el historial de órdenes de entrega y su correspondiente esquema de validación, cubriendo todos los aspectos fundamentales del cambio.
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-493-get-delivery-orders

Tip

💬 Introducing Slack Agent: 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 your free trial and get 200 agent minutes per Slack user (a $50 value).


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
Review rate limit: 0/1 reviews remaining, refill in 52 minutes and 49 seconds.

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: 2

🤖 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/delivery/delivery-assignments/delivery-assignments.routes.js`:
- Around line 158-163: El 400 response en este endpoint está apuntando al schema
DeliveryStatusErrorResponse (orientado a delivery_status) y debe usar un schema
de validación de query; update the OpenAPI response $ref in
delivery-assignments.routes.js to point to a proper query-validation schema
(e.g., QueryValidationErrorResponse or InvalidQueryErrorResponse), and if that
schema does not exist add it to components/schemas describing invalid query
params (message, invalidFields, etc.); ensure the 400 entry replaces $ref
'#/components/schemas/DeliveryStatusErrorResponse' with the new schema name and
keep response content/application/json structure unchanged.

In `@src/modules/delivery/delivery-assignments/delivery-assignments.service.js`:
- Line 380: The spread uses a truthy check "(...orderId && { fk_order: orderId
})" which skips valid falsy ids (e.g., 0); update the spread to only omit the
filter when orderId is strictly undefined by replacing that truthy check with an
explicit undefined check or a conditional that returns an empty object when
orderId is undefined, so fk_order is included for values like 0; target the
expression using orderId and fk_order in delivery-assignments.service.js.
🪄 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: 84015711-d0df-4190-b32e-96bc4fd724c7

📥 Commits

Reviewing files that changed from the base of the PR and between 85637d0 and 1cf238b.

📒 Files selected for processing (5)
  • src/docs/schemas/delivery.schema.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.controller.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.routes.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.service.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.validation.js

Comment thread src/modules/delivery/delivery-assignments/delivery-assignments.routes.js Outdated
Comment thread src/modules/delivery/delivery-assignments/delivery-assignments.service.js Outdated

@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: 1

🧹 Nitpick comments (1)
tests/unit/delivery/delivery-assignments.test.js (1)

390-503: ⚡ Quick win

Falta validar que count reciba los mismos filtros que findMany.

Las pruebas de filtros hoy sólo chequean el where de findMany. Si count se desalinea, la paginación (total_elements, total_pages) puede romperse sin que el suite lo detecte.

🧪 Cobertura sugerida (ejemplo)
   it("filtra correctamente por orderId", async () => {
     prisma.deliveries.findUnique.mockResolvedValue(mockDeliveryForHistory);
     prisma.deliveryAssignments.findMany.mockResolvedValue([mockAssignmentHistory]);
     prisma.deliveryAssignments.count.mockResolvedValue(1);

     await getDeliveryOrderHistoryService(1, 5, { orderId: 100 }, mockPagination);

     expect(prisma.deliveryAssignments.findMany).toHaveBeenCalledWith(
       expect.objectContaining({
         where: expect.objectContaining({ fk_order: 100 })
       })
     );
+    expect(prisma.deliveryAssignments.count).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: expect.objectContaining({ fk_order: 100 })
+      })
+    );
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/delivery/delivery-assignments.test.js` around lines 390 - 503, The
tests only assert that prisma.deliveryAssignments.findMany is called with the
expected where filters but do not verify prisma.deliveryAssignments.count is
invoked with the same filters, which can hide pagination bugs; update each
filter-related test (e.g., the cases calling getDeliveryOrderHistoryService with
period, assignment_status, orderId, userName, and the no-filters case) to also
expect prisma.deliveryAssignments.count toHaveBeenCalledWith an objectContaining
the same where clause (matching the same created_at, assignment_status,
fk_order, or nested order.user.name filters or absence thereof) so count and
findMany remain aligned for pagination calculations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/unit/delivery/delivery-assignments.test.js`:
- Line 325: Reemplaza la llamada en beforeEach que usa vi.clearAllMocks() por
vi.resetAllMocks() para asegurar que también se reinicien las implementaciones
(o, como alternativa, reinstala explícitamente cada mock antes de cada test),
especialmente los mocks configurados con mockResolvedValue(...) y la
implementación de $transaction usada en estos tests; busca la beforeEach que
contiene vi.clearAllMocks(), y cambia a vi.resetAllMocks() o añade reinstalación
explícita de mockImplementation/mockResolvedValue para $transaction y otros
mocks reutilizados.

---

Nitpick comments:
In `@tests/unit/delivery/delivery-assignments.test.js`:
- Around line 390-503: The tests only assert that
prisma.deliveryAssignments.findMany is called with the expected where filters
but do not verify prisma.deliveryAssignments.count is invoked with the same
filters, which can hide pagination bugs; update each filter-related test (e.g.,
the cases calling getDeliveryOrderHistoryService with period, assignment_status,
orderId, userName, and the no-filters case) to also expect
prisma.deliveryAssignments.count toHaveBeenCalledWith an objectContaining the
same where clause (matching the same created_at, assignment_status, fk_order, or
nested order.user.name filters or absence thereof) so count and findMany remain
aligned for pagination calculations.
🪄 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: d1ae53cf-c8a9-4665-abc3-a7061b659945

📥 Commits

Reviewing files that changed from the base of the PR and between 1cf238b and 93b1749.

📒 Files selected for processing (4)
  • src/docs/schemas/delivery.schema.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.routes.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.service.js
  • tests/unit/delivery/delivery-assignments.test.js
✅ Files skipped from review due to trivial changes (3)
  • src/docs/schemas/delivery.schema.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.routes.js
  • src/modules/delivery/delivery-assignments/delivery-assignments.service.js

Comment thread tests/unit/delivery/delivery-assignments.test.js Outdated
@sonarqubecloud

sonarqubecloud Bot commented May 2, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
10.7% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@leoAchu16
leoAchu16 merged commit 5dcbf39 into dev May 2, 2026
3 of 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