Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/obando1998/Proyecto_UCP/llms.txt

Use this file to discover all available pages before exploring further.

Overview

The DevolucionModel class handles all database operations related to product returns and deviations. It manages the complete lifecycle from initial registration by auxiliary users to review and approval by administrators, and provides statistical data for the dashboard. Database Table: devoluciones Key Responsibilities:
  • Register new product returns with customer and product information
  • Retrieve pending returns for administrative review
  • Process approval/rejection decisions with admin codes
  • Generate statistics by date and status
  • Provide available dates for filtering

Constructor

public function __construct()
Initializes the model and establishes database connection using Conexion::Conectar().

Methods

guardar()

public function guardar($datos)
Inserts a new product return record into the devoluciones table. This method is used by auxiliary users to register returns, shortages, or overages.
datos
array
required
Associative array containing all return information:
nit
string
required
Customer tax identification number
nombre_cliente
string
required
Customer name
direccion
string
required
Customer delivery address
item_producto
string
required
Product item code (references producto.item)
descripcion_producto
string
required
Product description
unidad
string
required
Unit of measurement (e.g., “Paquete”, “Caja”)
kg
float
required
Weight per unit in kilograms
motivo
string
required
Reason code: “Devolucion”, “Faltante”, or “Sobrante”
cantidad_und
int
required
Quantity in units
cantidad_kg
float
required
Total weight in kilograms
observacion
string
Auxiliary user observations
usuario_creador
string
required
Username of the auxiliary user creating the record
evidencia
string
Base64-encoded image or file path for evidence (optional)
Returns: bool - true on successful insertion, false on failure Automatic Fields:
  • estado is set to "Pendiente" by default
  • fecha_creacion is set to NOW() timestamp
INSERT INTO devoluciones (
    nit, nombre_cliente, direccion, item_producto, descripcion_producto, 
    unidad, kg, motivo, cantidad_und, cantidad_kg, 
    observacion, usuario_creador, estado, fecha_creacion, evidencia
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pendiente', NOW(), ?)
The evidencia field supports null values using the null coalescing operator (??). If no evidence is provided, it will be stored as NULL in the database.

obtenerPendientes()

public function obtenerPendientes()
Retrieves all product returns with estado = 'Pendiente' status, ordered by creation date (oldest first). This method is used by administrators to view returns awaiting review. Returns: array - Array of associative arrays containing all columns from the devoluciones table Returned Fields:
  • id - Primary key
  • nit, nombre_cliente, direccion - Customer information
  • item_producto, descripcion_producto, unidad, kg - Product details
  • motivo - Reason code (Devolucion/Faltante/Sobrante)
  • cantidad_und, cantidad_kg - Quantities
  • observacion - Auxiliary observations
  • usuario_creador - Creator username
  • estado - Will be “Pendiente”
  • fecha_creacion - Creation timestamp
  • evidencia - Evidence data
  • codigo_admin, observacion_admin, usuario_revisor, fecha_revision - Admin fields (will be NULL)
SELECT * FROM devoluciones 
WHERE estado = 'Pendiente' 
ORDER BY fecha_creacion ASC

procesarRevision()

public function procesarRevision($id, $accion, $codigo, $obs, $revisor)
Processes an administrator’s review decision for a pending return. Updates the record with approval or rejection status, admin code, observations, and reviewer information. Uses database transactions for data integrity.
id
int
required
Primary key of the return record to process
accion
string
required
Administrative decision: "Aprobado" or "Rechazado"
codigo
string
required
Administrative code assigned to this return (e.g., “DEV-2024-001”)
obs
string
Administrator observations or rejection reason
revisor
string
required
Username of the administrator processing the review
Returns: bool - true on successful update with commit, false on failure with rollback Transaction Behavior:
  • Begins database transaction before update
  • Commits on success
  • Rolls back on exception
Updated Fields:
  • estado - Set to $accion value
  • codigo_admin - Set to $codigo
  • observacion_admin - Set to $obs
  • usuario_revisor - Set to $revisor
  • fecha_revision - Set to NOW()
UPDATE devoluciones 
SET estado = ?, 
    codigo_admin = ?, 
    observacion_admin = ?, 
    usuario_revisor = ?, 
    fecha_revision = NOW() 
WHERE id = ?
This method uses transactions to ensure data consistency. If an exception occurs during the update, all changes are rolled back automatically. However, the exception details are not exposed - only a boolean false is returned.
The code includes a commented placeholder for creating notifications:
// $this->crearNotificacion($id, $accion);
This allows future implementation of a notification system to alert auxiliary users when their returns are reviewed.

obtenerEstadisticas()

public function obtenerEstadisticas($fecha = null)
Generates comprehensive statistics for the dashboard, aggregating return data by status and reason. Can optionally filter by a specific date.
fecha
string
Optional date filter in YYYY-MM-DD format. If null, returns statistics for all records.
Returns: array - Associative array with the following keys:
total
int
Total number of return records
total_kg
float
Sum of all cantidad_kg values (0 if no records)
total_und
int
Sum of all cantidad_und values (0 if no records)
pendientes
int
Count of records with estado = 'Pendiente'
aprobados
int
Count of records with estado = 'Aprobado'
rechazados
int
Count of records with estado = 'Rechazado'
motivo_dev
int
Count of records with motivo = 'Devolucion'
motivo_fal
int
Count of records with motivo = 'Faltante'
motivo_sob
int
Count of records with motivo = 'Sobrante'
SELECT 
    COUNT(*) as total,
    COALESCE(SUM(cantidad_kg), 0) as total_kg,
    COALESCE(SUM(cantidad_und), 0) as total_und,
    
    -- Conteo por Estados
    COUNT(CASE WHEN estado = 'Pendiente' THEN 1 END) as pendientes,
    COUNT(CASE WHEN estado = 'Aprobado' THEN 1 END) as aprobados,
    COUNT(CASE WHEN estado = 'Rechazado' THEN 1 END) as rechazados,
    
    -- Conteo por Motivos
    COUNT(CASE WHEN motivo = 'Devolucion' THEN 1 END) as motivo_dev,
    COUNT(CASE WHEN motivo = 'Faltante' THEN 1 END) as motivo_fal,
    COUNT(CASE WHEN motivo = 'Sobrante' THEN 1 END) as motivo_sob
FROM devoluciones 
WHERE DATE(fecha_creacion) = :fecha
Uses COALESCE() to ensure numeric fields return 0 instead of NULL when no records match. This prevents null pointer issues in dashboard calculations.

obtenerFechas()

public function obtenerFechas()
Retrieves a list of all unique dates when returns were created, sorted from newest to oldest. Used to populate date filter dropdowns in the dashboard. Returns: array - Indexed array of date strings in YYYY-MM-DD format
SELECT DISTINCT DATE(fecha_creacion) as fecha 
FROM devoluciones 
ORDER BY fecha DESC

Database Schema

Table: devoluciones
ColumnTypeDescription
idINT (PK, AUTO_INCREMENT)Primary key
nitVARCHARCustomer tax ID
nombre_clienteVARCHARCustomer name
direccionVARCHARDelivery address
item_productoVARCHARProduct item code
descripcion_productoVARCHARProduct description
unidadVARCHARUnit of measurement
kgDECIMALWeight per unit
motivoVARCHARDevolucion/Faltante/Sobrante
cantidad_undINTQuantity in units
cantidad_kgDECIMALTotal weight
observacionTEXTAuxiliary observations
usuario_creadorVARCHARCreating user
estadoVARCHARPendiente/Aprobado/Rechazado
fecha_creacionDATETIMECreation timestamp
evidenciaTEXTEvidence data
codigo_adminVARCHARAdmin code
observacion_adminTEXTAdmin observations
usuario_revisorVARCHARReviewing admin
fecha_revisionDATETIMEReview timestamp

State Machine


Build docs developers (and LLMs) love