Skip to content

OM-508: agregar campo icon a Categories con migración y soporte en ad… - #157

Merged
leoAchu16 merged 2 commits into
devfrom
OM-508
May 18, 2026
Merged

leoAchu16 merged 2 commits into
devfrom
OM-508

Conversation

@J-Kanami-PS

@J-Kanami-PS J-Kanami-PS commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

Este PR agrega el campo icon a Categories. Después de hacer pull corran npx prisma generate.

Summary by CodeRabbit

Notas de Lanzamiento

  • New Features
    • Se agregó la capacidad de asociar íconos a las categorías de productos. Los administradores ahora pueden asignar, visualizar y modificar íconos en las categorías existentes.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@J-Kanami-PS has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 52 minutes and 8 seconds before requesting another review.

You’ve run out of usage credits. Purchase more 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: 424ac621-0399-4dff-af4f-894ae231ddc2

📥 Commits

Reviewing files that changed from the base of the PR and between 02fb15c and 2ce045e.

📒 Files selected for processing (1)
  • src/modules/admin/categories/admin-category.service.js
📝 Walkthrough

Resumen

Se agrega un nuevo campo icon al dominio de categorías mediante migración de BD, actualización del esquema Prisma, y modificación de la lógica del controlador y servicios de administración para crear, consultar y actualizar categorías incluyendo el icono.

Cambios

Soporte de icono en categorías

Capa / Archivo(s) Resumen
Migración de esquema y definición de modelo
prisma/migrations/20260517230841_add_icon_to_categories/migration.sql, prisma/schema.prisma
Se agrega la columna icon VARCHAR(500) a la tabla Categories en la migración SQL y se define el campo opcional icon: String? en el modelo Prisma.
Creación de categoría con icono
src/modules/admin/categories/admin-category.controller.js, src/modules/admin/categories/admin-category.service.js
El endpoint POST ahora extrae req.body?.icon y lo envía a createAdminProductCategoryService, que expande su firma para aceptar icon como parámetro, lo valida, lo persiste en BD e incluye el campo en la respuesta.
Exposición de icono en lectura y actualización
src/modules/admin/categories/admin-category.service.js
Los servicios getAdminProductCategoryService y getAllCategories incluyen icon en sus consultas SELECT y lo exponen en los objetos retornados; normalizeUpdatePayload valida y acepta icon en requests de actualización.

Esfuerzo estimado de revisión de código

🎯 2 (Simple) | ⏱️ ~12 minutos

PRs posiblemente relacionadas

  • CrisNAC/BackendMarketplace#103: Ambos PRs modifican getAllCategories en src/modules/admin/categories/admin-category.service.js extendiendo los campos devueltos en el listado de categorías.
  • CrisNAC/BackendMarketplace#105: Ambos PRs tocan la lógica de actualización de categorías en updateAdminProductCategoryService, agregando validación y persistencia del campo icon en el payload normalizado.

Revisores sugeridos

  • Andoumeda

Poema

🐰 Un icono por cada categoría,
Colores que adornan la mercancía,
Migración sin tropiezo, BD lista,
GET, POST, UPDATE... ¡la fiesta se vuelve artística!

🚥 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 claramente el cambio principal: agregar el campo icon a Categories con migración y soporte en admin, lo cual es exactamente lo que el changeset implementa.
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-508

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/modules/admin/categories/admin-category.service.js (1)

31-70: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validá y normalizá icon de forma consistente antes de persistir.

Hoy en create no se valida icon, y en update solo tipo/null. Un valor largo (>500) o sin normalizar puede terminar en error de BD en vez de ValidationError controlado.

Propuesta de ajuste
 const normalizeAdminCategoryName = (name) => {
   ...
 };

+const normalizeCategoryIcon = (icon) => {
+  if (icon === undefined || icon === null) return null;
+  if (typeof icon !== "string") {
+    throw new ValidationError("icon debe ser texto o null");
+  }
+  const normalizedIcon = icon.trim();
+  if (normalizedIcon.length > 500) {
+    throw new ValidationError("icon no puede superar 500 caracteres");
+  }
+  return normalizedIcon || null;
+};

 export const createAdminProductCategoryService = async (name, icon = null) => {
   const normalizedName = normalizeAdminCategoryName(name);
+  const normalizedIcon = normalizeCategoryIcon(icon);
   ...
   const createdCategory = await prisma.categories.create({
     data: {
       name: normalizedName,
-      icon: icon ?? null,
+      icon: normalizedIcon,
       visible: true,
       status: true
     },
     ...
   });
 };

 const normalizeUpdatePayload = (payload) => {
   ...
   if (payload.icon !== undefined) {
-    if (payload.icon !== null && typeof payload.icon !== "string") {
-      throw new ValidationError("icon debe ser texto o null");
-    }
-    data.icon = payload.icon ?? null;
+    data.icon = normalizeCategoryIcon(payload.icon);
   }
   ...
 };

Also applies to: 350-355

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/admin/categories/admin-category.service.js` around lines 31 - 70,
The createAdminProductCategoryService currently does not validate or normalize
the icon value before saving; update logic only checks type/null. Update
createAdminProductCategoryService to validate that icon is either null or a
string, normalize it (e.g., trim, collapse whitespace), enforce a maximum length
(e.g., 500 chars) and convert empty/whitespace-only to null, and throw a
ValidationError on invalid input instead of letting the DB error; apply the same
validation/normalization logic to the corresponding update function (e.g.,
updateAdminProductCategoryService) so both create and update use the same icon
rules.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/modules/admin/categories/admin-category.service.js`:
- Around line 350-355: El servicio updateAdminProductCategoryService no está
incluyendo el campo icon en la respuesta tras actualizar (aunque ya valida y
setea data.icon), por lo que la API queda inconsistente con create/get/list;
updateAdminProductCategoryService debe devolver el icon en el objeto resultante:
ensure the updated response payload (the object returned by
updateAdminProductCategoryService or the value returned from the DB update call)
includes data.icon (or the entity.icon field) so the client receives the updated
icon field consistently; update the return/selection logic in
updateAdminProductCategoryService to include icon alongside the other returned
properties.

---

Outside diff comments:
In `@src/modules/admin/categories/admin-category.service.js`:
- Around line 31-70: The createAdminProductCategoryService currently does not
validate or normalize the icon value before saving; update logic only checks
type/null. Update createAdminProductCategoryService to validate that icon is
either null or a string, normalize it (e.g., trim, collapse whitespace), enforce
a maximum length (e.g., 500 chars) and convert empty/whitespace-only to null,
and throw a ValidationError on invalid input instead of letting the DB error;
apply the same validation/normalization logic to the corresponding update
function (e.g., updateAdminProductCategoryService) so both create and update use
the same icon rules.
🪄 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: 0569ddcc-e474-4bee-ac10-7807ddaecbee

📥 Commits

Reviewing files that changed from the base of the PR and between af30237 and 02fb15c.

📒 Files selected for processing (4)
  • prisma/migrations/20260517230841_add_icon_to_categories/migration.sql
  • prisma/schema.prisma
  • src/modules/admin/categories/admin-category.controller.js
  • src/modules/admin/categories/admin-category.service.js

Comment thread src/modules/admin/categories/admin-category.service.js
@sonarqubecloud

Copy link
Copy Markdown

@leoAchu16
leoAchu16 merged commit 3f2fb4e into dev May 18, 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