InventoryService class handles transactional operations for physical item instances, including reservations and releases with proper concurrency control.
Methods
reserve_instances
Atomically reserves a specified quantity of available item instances.The ID of the catalog item to reserve instances from
Number of instances to reserve
Returns a tuple containing:
bool: Success statuslist[int]: List of reserved instance IDsstr: Result message
- Uses
with_for_update(skip_locked=True)for pessimistic locking - Prevents race conditions when multiple users request same items
- Automatically rolls back on
OperationalError(concurrency conflicts)
- Validates catalog exists
- Locks and retrieves available instances up to requested quantity
- Changes status from ‘disponible’ to ‘prestado’
- Returns list of reserved instance IDs for loan creation
"Catálogo no encontrado."- Invalid catalog_id"Stock físico insuficiente o temporalmente bloqueado por otra transacción."- Not enough available instances"El sistema está procesando otra solicitud para este ítem. Intente nuevamente."- Concurrency conflict detected"Error interno al procesar el inventario."- Unexpected database error"Instancias reservadas exitosamente."- Success
app/services/inventory_service.py:9
release_instance
Releases a single instance back to available inventory.The ID of the instance to release
Returns a tuple containing:
bool: Success statusstr: Result message
- Validates instance exists
- Sets status to ‘disponible’
- Does NOT commit - caller must handle transaction
"Instancia física no encontrada."- Invalid instance_id"Instancia liberada y devuelta al inventario."- Success
app/services/inventory_service.py:39
CatalogService
TheCatalogService class provides optimized queries for catalog items with availability counts, solving N+1 query problems.
get_catalog_with_counts
Returns catalog items with dynamically injected availability counts (no pagination).Filter by specific category (e.g., ‘computo’, ‘libro’)
Exclude specific category from results
List of Catalog objects with
available_count attribute dynamically injected- Uses single JOIN query instead of N+1 queries
- Groups by catalog ID and counts available instances
- Dynamically injects
available_countattribute to maintain frontend compatibility
app/services/inventory_service.py:49
get_paginated_catalog
Returns paginated catalog items with availability counts.Current page number
Number of items per page
Filter by specific category
Exclude specific category from results
Flask-SQLAlchemy Pagination object with:
items: List of Catalog objects withavailable_countinjectedpage: Current page numberpages: Total number of pagestotal: Total number of itemshas_prev,has_next: Boolean navigation flags
- Single optimized query with JOIN and GROUP BY
- Prevents N+1 queries when displaying catalog lists
- Maintains pagination metadata
app/services/inventory_service.py:75