Skip to content

Se pueden editar las categorías siendo Admin - #105

Merged
SebaKisser merged 3 commits into
devfrom
OM-348
Apr 17, 2026
Merged

SebaKisser merged 3 commits into
devfrom
OM-348

Conversation

@Andoumeda

@Andoumeda Andoumeda commented Apr 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Notas de Lanzamiento

  • Nuevas Características
    • Endpoint protegido para actualizar categorías: modificar nombre, descripción y visibilidad desde el panel de administración.
  • Documentación
    • Documentación API (OpenAPI/Swagger) añadida para el nuevo endpoint PUT.
  • Tests
    • Suites de pruebas actualizadas para cubrir validaciones, casos 200/400/404 y comportamiento de eliminación relacionado.

@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

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

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 10 minutes and 57 seconds.

⌛ 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: 12ad9dde-5c86-4796-9d14-1e42f374d547

📥 Commits

Reviewing files that changed from the base of the PR and between 897a145 and f570e71.

📒 Files selected for processing (4)
  • src/docs/schemas/admin/admin-category.schema.js
  • src/modules/admin/categories/admin-category.routes.js
  • src/modules/admin/categories/admin-category.service.js
  • tests/unit/admin/admin-category.test.js
📝 Walkthrough

Recorrido

Se añadió una operación de actualización de categorías de producto en el módulo admin: nuevo controlador y ruta PUT protegida, servicio con validación/normalización y reintento para compatibilidad de esquema Prisma, y pruebas unitarias actualizadas que cubren validación, 404 y flujo exitoso.

Cambios

Cohort / Archivo(s) Resumen
Controlador y Ruta
src/modules/admin/categories/admin-category.controller.js, src/modules/admin/categories/admin-category.routes.js
Nuevo export updateAdminProductCategory y nueva ruta PUT /api/admin/categories/:id protegida (authenticate + requireRole(ROLES.ADMIN)) con documentación OpenAPI/Swagger.
Servicio
src/modules/admin/categories/admin-category.service.js
Nuevo updateAdminProductCategoryService(id, payload) con validación/normalización de name, description, visibility; mapeo visibility→status; exige al menos un campo; verifica existencia y realiza prisma.update con fallback que reintenta sin description si el esquema lo rechaza.
Pruebas unitarias
tests/unit/admin/admin-category.test.js
Reemplazo/expansión de suites: nueva suite PUT con casos 400/401/403/404/200 (mocks de prisma.productCategories.update), re-inserción de suite DELETE con mocks de $transaction y aserciones sobre re-asignación/ocultamiento.

Diagrama de Secuencia

sequenceDiagram
    actor Cliente
    participant Router as Enrutador (Rutas)
    participant Ctrl as Controlador
    participant Service as Servicio
    participant DB as Prisma/BD

    Cliente->>Router: PUT /api/admin/categories/:id
    Router->>Router: authenticate + requireRole(ADMIN)
    Router->>Ctrl: updateAdminProductCategory(req)
    Ctrl->>Ctrl: validateId(req.params.id)
    Ctrl->>Service: updateAdminProductCategoryService(id, body)
    Service->>Service: validar y normalizar payload
    Service->>DB: findUnique(where: id_product_category)
    DB-->>Service: categoría o null
    alt no existe
        Service-->>Ctrl: lanza error 404
    else existe
        Service->>DB: update(where, data)
        alt update falla por campo `description`
            Service->>DB: update(where, data sin description)
            DB-->>Service: resultado
        else éxito
            DB-->>Service: resultado
        end
        Service-->>Ctrl: retorna entidad serializada
    end
    Ctrl-->>Cliente: 200 JSON / 4xx
Loading

Esfuerzo Estimado de Revisión

🎯 4 (Complex) | ⏱️ ~45 minutes

Revisores Sugeridos

  • Benjakr04
  • CrisNAC

Poema

🐰 Salto y remiendo, nombre y descripción,
Pinto visibilidad con cuidadosa razón.
Prisma actualiza, si falla lo intento,
Rutas protegidas me dan aliento.
¡Bravo al equipo, brinco contento!

🚥 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 claramente la funcionalidad principal añadida: la capacidad de editar categorías como administrador, lo que se refleja en todos los cambios del PR (nuevo controlador, ruta PUT, servicio de actualización y tests).
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-348

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/admin/categories/admin-category.routes.js`:
- Around line 45-87: Fix the mojibake in the Swagger block by replacing the
bad-encoded word "categorí­a" with the correctly encoded "categoría" in the put
operation summary for the /api/admin/categories/{id} route; update any other
occurrences in that Swagger block (e.g., summary or description fields) and
ensure the file is saved in UTF-8 encoding so the accent renders properly in
generated docs.

In `@src/modules/admin/categories/admin-category.service.js`:
- Around line 80-85: The code silently drops payload.description for
ProductCategories (per prisma model) which breaks the API contract; instead,
when payload.description is provided (payload.description !== undefined) reject
the request with a ValidationError explaining that description is not a valid
field for ProductCategories; update the handling around payload.description and
the data.description assignment in admin-category.service.js (the block using
payload.description, data.description, and ValidationError) to validate presence
against the Prisma model and throw a clear ValidationError rather than
trimming/falling back to null so clients are not misled.
- Around line 113-132: The code reads updated.description after calling
prisma.productCategories.update(select: {...}) but the Prisma model
ProductCategories doesn't define description, so either add description to the
Prisma model and include it in the update/select or remove all references to
description from the update flow; specifically, if description is needed, add a
description field to the ProductCategories model in schema.prisma, run a
migration, then include description in the select of
prisma.productCategories.update and return it in the response (reference:
prisma.productCategories.update and updated.description), otherwise remove
description from the update payload/validation and from the response mapping
(remove updated.description ?? null) and any related validators/handlers that
expect it.
🪄 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: 35e8fd40-73ff-40a0-ac70-537b84cab2fd

📥 Commits

Reviewing files that changed from the base of the PR and between b49c0eb and 8b49f61.

📒 Files selected for processing (4)
  • src/modules/admin/categories/admin-category.controller.js
  • src/modules/admin/categories/admin-category.routes.js
  • src/modules/admin/categories/admin-category.service.js
  • tests/unit/admin/admin-category.test.js

Comment thread src/modules/admin/categories/admin-category.routes.js
Comment thread src/modules/admin/categories/admin-category.service.js Outdated
Comment thread src/modules/admin/categories/admin-category.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.

♻️ Duplicate comments (1)
src/modules/admin/categories/admin-category.routes.js (1)

135-139: ⚠️ Potential issue | 🟡 Minor

Corregir mojibake en Swagger del PUT.

En Line 139 sigue apareciendo categorí­a mal codificado; en la documentación se va a renderizar con caracteres rotos.

Diff sugerido
- *     summary: Editar categorí­a de productos (Admin)
+ *     summary: Editar categoría de productos (Admin)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/admin/categories/admin-category.routes.js` around lines 135 -
139, The Swagger JSDoc block for the PUT route "/api/admin/categories/{id}" has
mojibake in the summary ("categorí­a"); update the summary string in the
admin-category.routes.js Swagger comment for the PUT operation to the correct
UTF-8 word "categoría" so the generated docs render properly (locate the JSDoc
block for the PUT under /api/admin/categories/{id} and edit the summary line).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/modules/admin/categories/admin-category.routes.js`:
- Around line 135-139: The Swagger JSDoc block for the PUT route
"/api/admin/categories/{id}" has mojibake in the summary ("categorí­a"); update
the summary string in the admin-category.routes.js Swagger comment for the PUT
operation to the correct UTF-8 word "categoría" so the generated docs render
properly (locate the JSDoc block for the PUT under /api/admin/categories/{id}
and edit the summary line).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 26f668de-fed5-415a-ac39-d2afca570252

📥 Commits

Reviewing files that changed from the base of the PR and between 8b49f61 and 897a145.

📒 Files selected for processing (4)
  • src/modules/admin/categories/admin-category.controller.js
  • src/modules/admin/categories/admin-category.routes.js
  • src/modules/admin/categories/admin-category.service.js
  • tests/unit/admin/admin-category.test.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/modules/admin/categories/admin-category.controller.js
  • tests/unit/admin/admin-category.test.js
  • src/modules/admin/categories/admin-category.service.js

@SebaKisser
SebaKisser merged commit a219dbd into dev Apr 17, 2026
2 checks passed
@Andoumeda
Andoumeda deleted the OM-348 branch April 23, 2026 17:05
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