Skip to main content

Overview

The category management system provides a hierarchical organization structure for your products. You can create main categories and nested subcategories, each with custom colors and status settings. This enables efficient product classification and filtering across your inventory.

Key Features

  • Create unlimited categories and subcategories
  • Visual color palette with 10+ preset colors
  • Hierarchical organization (categories → subcategories)
  • Status management (ACTIVO/INACTIVO)
  • Real-time search and filtering
  • Color inheritance for subcategories
  • Duplicate name prevention

Data Structure

Categories

FieldTypeRequiredMax LengthDescription
idIntegerAuto-Unique identifier
nombreStringYes50 charsCategory name (unique)
descripcionStringNo200 charsCategory description
colorStringYes7 charsHex color code (e.g., #2e6df6)
estadoEnumYes-ACTIVO or INACTIVO
fecha_creacionDateTimeAuto-Creation timestamp
fecha_actualizacionDateTimeAuto-Last update timestamp

Subcategories

Subcategories have all category fields plus:
FieldTypeRequiredDescription
categoria_idIntegerYesParent category reference

User Workflows

Creating a Category

1

Access category mode

Ensure you’re in Categorías mode (button should be active in the top toolbar).
2

Open create dialog

Click + Crear Categoría button.
3

Enter category details

Fill in the form:
  • Nombre (required, max 50 chars): Unique category name
  • Descripción (optional, max 200 chars): Additional details
  • Color: Click a color swatch from the palette
  • Estado: Select ACTIVO or INACTIVO
4

Save category

Click Guardar. The system validates uniqueness and length constraints.

Creating a Subcategory

You must have at least one category before creating subcategories.
1

Switch to subcategory mode

Click Subcategorías button in the top toolbar.
2

Open create dialog

Click + Crear Subcategoría button.
3

Select parent category

Choose the parent category from the dropdown. The subcategory will inherit the parent’s color by default.
4

Enter subcategory details

  • Categoría (required): Parent category
  • Nombre (required, max 50 chars): Subcategory name
  • Descripción (optional, max 200 chars)
  • Color: Auto-filled from parent, but can be changed
  • Estado: ACTIVO or INACTIVO
5

Save subcategory

Click Guardar to create the subcategory.
When you select a parent category, the color picker automatically updates to match the parent’s color. You can override this if needed.

Editing Categories/Subcategories

1

Locate the item

Use the search bar or browse the card grid to find the category/subcategory.
2

Open edit mode

Click the edit icon (✏️) in the top-right corner of the card.
3

Modify fields

Update any field. For subcategories, you can change the parent category.
4

Save changes

Click Guardar. Validation rules apply as in creation.

Deleting Categories/Subcategories

Deletion is blocked if products are associated with the category/subcategory.
1

Select item

Click the delete icon (🗑️) on the card.
2

Confirm deletion

A browser confirmation dialog appears. Click OK to proceed.
3

Validation check

The backend checks for associated products:
  • If products exist, deletion fails with an error
  • If no products, the item is permanently deleted

Switching Between Categories and Subcategories

The interface has two modes accessible via top toolbar buttons:
  • Categorías: Shows all main categories
  • Subcategorías: Shows all subcategories with parent category names
Switching modes:
  • Updates the button text (”+ Crear Categoría” vs ”+ Crear Subcategoría”)
  • Changes the search placeholder
  • Reloads the appropriate data set

Color Palette

The system provides a predefined color palette for visual organization:

Blue

Default category color

Red

High priority items

Green

Active/available

Yellow

Warning/attention

Purple

Premium items

Custom

More colors available in the picker

API Reference

Categories Endpoint

GET    /database/categorias.php      # List all categories
POST   /database/categorias.php      # Create category
PUT    /database/categorias.php      # Update category
DELETE /database/categorias.php      # Delete category

Subcategories Endpoint

GET    /database/subcategorias.php   # List all subcategories
POST   /database/subcategorias.php   # Create subcategory
PUT    /database/subcategorias.php   # Update subcategory
DELETE /database/subcategorias.php   # Delete subcategory

Create Category

const response = await fetch('../database/categorias.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    nombre: 'Electronics',
    descripcion: 'Electronic devices and accessories',
    color: '#2e6df6',
    estado: 'ACTIVO'
  })
});

Create Subcategory

const response = await fetch('../database/subcategorias.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    categoria_id: 5,
    nombre: 'Smartphones',
    descripcion: 'Mobile phones and devices',
    color: '#2e6df6',
    estado: 'ACTIVO'
  })
});

Update Category

const response = await fetch('../database/categorias.php', {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id: 5,
    nombre: 'Electronics & Tech',
    descripcion: 'Updated description',
    color: '#8b5cf6',
    estado: 'ACTIVO'
  })
});

Delete Category

const response = await fetch('../database/categorias.php', {
  method: 'DELETE',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ id: 5 })
});

Validation Rules

  • Required: Cannot be empty
  • Max Length: 50 characters
  • Uniqueness: Must be unique across all categories (or subcategories)
  • Trimming: Whitespace is automatically removed
  • Validation Location: Both frontend (line 499-508) and backend (line 56-62)
  • Optional: Can be left empty
  • Max Length: 200 characters
  • Trimming: Whitespace is automatically removed
  • Validation Location: Frontend (line 510-513)
  • Format: Must be hex color code (e.g., #2e6df6)
  • Default: #2e6df6 (blue) if not specified
  • Inheritance: Subcategories inherit parent color by default
  • Change Detection: Color picker updates when parent category changes
  • Values: ACTIVO or INACTIVO only
  • Default: ACTIVO for new items
  • Required: Must be specified
  • Required: Must select a parent category
  • Frontend Check: Validates selection before submission (line 532-536)
  • Prerequisite: At least one category must exist (line 299-302)

UI Components

Category Card

Each category/subcategory displays as a card with:
  • Actions: Edit and delete buttons (top-right)
  • Icon: Colored circle with folder icon
  • Parent Name: (Subcategories only) Shows parent category
  • Title: Category/subcategory name
  • Description: Truncated description text
  • Footer: Product count and status badge

Status Badges

Status is displayed with color coding:
  • ACTIVO: Green badge
  • INACTIVO: Red/gray badge
CSS classes: status-activo and status-inactivo

Empty States

No Categories:
┌─────────────────────────────┐
│      📁 Folder Icon         │
│                             │
│ No hay categorías disponibles│
└─────────────────────────────┘
No Subcategories:
┌─────────────────────────────┐
│      📁 Folder Icon         │
│                             │
│No hay subcategorías disponibles│
└─────────────────────────────┘

Technical Implementation

Frontend (categorias.js)

Key Functions:
  • cargarCategorias(filtro) - Fetches categories with optional filter (line 104)
  • mostrarCategorias(filtro) - Renders category cards (line 122)
  • cargarSubcategorias(filtro) - Fetches subcategories (line 220)
  • mostrarSubcategorias(filtro) - Renders subcategory cards with parent names (line 238)
  • abrirModalNuevaSubcategoria() - Dynamically creates category select (line 298)
  • updateColorSwatch() - Highlights selected color (line 81)
Mode Switching: The currentMode variable (line 7) toggles between ‘categorias’ and ‘subcategorias’, affecting:
  • Button text
  • Search placeholder
  • Modal content
  • Data loading function

Backend (categorias.php)

Database Tables:
  • categorias - Main category table
  • subcategorias - Subcategory table with FK to categorias
Key Operations:
  • Line 21: SELECT with DESC ordering
  • Line 87: Unique name check before INSERT
  • Line 99: INSERT with automatic timestamps
  • Line 187: Unique name check excluding current ID
  • Line 256: Product association check before DELETE
  • Line 264-273: Dynamic column detection for FK relationship
The backend uses intelligent FK column detection to support various naming conventions: categoria_id, id_categoria, categoria, or categoriaId.

Best Practices

Logical Grouping

Create categories that match your business organization (e.g., Electronics → Smartphones, Laptops)

Consistent Colors

Use color coding consistently (e.g., all food items green, electronics blue)

Descriptive Names

Keep names clear and concise within the 50-character limit

Status Management

Use INACTIVO status to hide categories without deleting historical data

Plan Hierarchy

Design your category structure before creating products for better organization

Regular Reviews

Periodically audit categories and merge duplicates or similar items

Common Error Messages

Error MessageCauseSolution
”El nombre es obligatorio”Empty name fieldEnter a category name
”El nombre no puede superar 50 caracteres”Name too longShorten the name
”La descripción no puede superar 200 caracteres”Description too longReduce description length
”Ya existe una categoría con este nombre”Duplicate nameChoose a unique name
”Debe seleccionar una categoría”No parent selected (subcategory)Select a parent category
”Debe crear al menos una categoría primero”Creating subcategory without categoriesCreate a category first
”Categoría no encontrada”Invalid IDRefresh and try again
”No se puede eliminar. Tiene X producto(s) asociado(s)“Products linkedReassign products first

Build docs developers (and LLMs) love