feat: add admin inventory management (Phase 1)

- Add admin API endpoints for inventory management
- Add inventory page with vendor selector and filtering
- Add admin schemas for cross-vendor inventory operations
- Support digital products with unlimited inventory
- Add integration tests for admin inventory API
- Add inventory management guide documentation

Mirrors vendor inventory functionality with admin-level access.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-18 21:05:12 +01:00
parent 0ab10128ae
commit 8d8d41808b
12 changed files with 2880 additions and 3 deletions

View File

@@ -32,11 +32,13 @@ from . import (
companies,
content_pages,
dashboard,
inventory,
letzshop,
logs,
marketplace,
monitoring,
notifications,
orders,
products,
settings,
tests,
@@ -98,7 +100,7 @@ router.include_router(dashboard.router, tags=["admin-dashboard"])
# ============================================================================
# Product Catalog
# Vendor Operations (Product Catalog, Inventory & Orders)
# ============================================================================
# Include marketplace product catalog management endpoints
@@ -107,6 +109,12 @@ router.include_router(products.router, tags=["admin-marketplace-products"])
# Include vendor product catalog management endpoints
router.include_router(vendor_products.router, tags=["admin-vendor-products"])
# Include inventory management endpoints
router.include_router(inventory.router, tags=["admin-inventory"])
# Include order management endpoints
router.include_router(orders.router, tags=["admin-orders"])
# ============================================================================
# Marketplace & Imports

View File

@@ -0,0 +1,286 @@
# app/api/v1/admin/inventory.py
"""
Admin inventory management endpoints.
Provides inventory management capabilities for administrators:
- View inventory across all vendors
- View vendor-specific inventory
- Set/adjust inventory on behalf of vendors
- Low stock alerts and reporting
Admin Context: Uses admin JWT authentication.
Vendor selection is passed as a request parameter.
"""
import logging
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.inventory_service import inventory_service
from models.database.user import User
from models.schema.inventory import (
AdminInventoryAdjust,
AdminInventoryCreate,
AdminInventoryListResponse,
AdminInventoryLocationsResponse,
AdminInventoryStats,
AdminLowStockItem,
AdminVendorsWithInventoryResponse,
InventoryAdjust,
InventoryCreate,
InventoryMessageResponse,
InventoryResponse,
InventoryUpdate,
ProductInventorySummary,
)
router = APIRouter(prefix="/inventory")
logger = logging.getLogger(__name__)
# ============================================================================
# List & Statistics Endpoints
# ============================================================================
@router.get("", response_model=AdminInventoryListResponse)
def get_all_inventory(
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=500),
vendor_id: int | None = Query(None, description="Filter by vendor"),
location: str | None = Query(None, description="Filter by location"),
low_stock: int | None = Query(None, ge=0, description="Filter items below threshold"),
search: str | None = Query(None, description="Search by product title or SKU"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get inventory across all vendors with filtering.
Allows admins to view and filter inventory across the platform.
"""
return inventory_service.get_all_inventory_admin(
db=db,
skip=skip,
limit=limit,
vendor_id=vendor_id,
location=location,
low_stock=low_stock,
search=search,
)
@router.get("/stats", response_model=AdminInventoryStats)
def get_inventory_stats(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get platform-wide inventory statistics."""
return inventory_service.get_inventory_stats_admin(db)
@router.get("/low-stock", response_model=list[AdminLowStockItem])
def get_low_stock_items(
threshold: int = Query(10, ge=0, description="Stock threshold"),
vendor_id: int | None = Query(None, description="Filter by vendor"),
limit: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get items with low stock levels."""
return inventory_service.get_low_stock_items_admin(
db=db,
threshold=threshold,
vendor_id=vendor_id,
limit=limit,
)
@router.get("/vendors", response_model=AdminVendorsWithInventoryResponse)
def get_vendors_with_inventory(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get list of vendors that have inventory entries."""
return inventory_service.get_vendors_with_inventory_admin(db)
@router.get("/locations", response_model=AdminInventoryLocationsResponse)
def get_inventory_locations(
vendor_id: int | None = Query(None, description="Filter by vendor"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get list of unique inventory locations."""
return inventory_service.get_inventory_locations_admin(db, vendor_id)
# ============================================================================
# Vendor-Specific Endpoints
# ============================================================================
@router.get("/vendors/{vendor_id}", response_model=AdminInventoryListResponse)
def get_vendor_inventory(
vendor_id: int,
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=500),
location: str | None = Query(None, description="Filter by location"),
low_stock: int | None = Query(None, ge=0, description="Filter items below threshold"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get inventory for a specific vendor."""
return inventory_service.get_vendor_inventory_admin(
db=db,
vendor_id=vendor_id,
skip=skip,
limit=limit,
location=location,
low_stock=low_stock,
)
@router.get("/products/{product_id}", response_model=ProductInventorySummary)
def get_product_inventory(
product_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Get inventory summary for a specific product across all locations."""
return inventory_service.get_product_inventory_admin(db, product_id)
# ============================================================================
# Inventory Modification Endpoints
# ============================================================================
@router.post("/set", response_model=InventoryResponse)
def set_inventory(
inventory_data: AdminInventoryCreate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""
Set exact inventory quantity for a product at a location.
Admin version - requires explicit vendor_id in request body.
"""
# Verify vendor exists
inventory_service.verify_vendor_exists(db, inventory_data.vendor_id)
# Convert to standard schema for service
service_data = InventoryCreate(
product_id=inventory_data.product_id,
location=inventory_data.location,
quantity=inventory_data.quantity,
)
result = inventory_service.set_inventory(
db=db,
vendor_id=inventory_data.vendor_id,
inventory_data=service_data,
)
logger.info(
f"Admin {current_admin.email} set inventory for product {inventory_data.product_id} "
f"at {inventory_data.location}: {inventory_data.quantity} units"
)
db.commit()
return result
@router.post("/adjust", response_model=InventoryResponse)
def adjust_inventory(
adjustment: AdminInventoryAdjust,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""
Adjust inventory by adding or removing quantity.
Positive quantity = add stock, negative = remove stock.
Admin version - requires explicit vendor_id in request body.
"""
# Verify vendor exists
inventory_service.verify_vendor_exists(db, adjustment.vendor_id)
# Convert to standard schema for service
service_data = InventoryAdjust(
product_id=adjustment.product_id,
location=adjustment.location,
quantity=adjustment.quantity,
)
result = inventory_service.adjust_inventory(
db=db,
vendor_id=adjustment.vendor_id,
inventory_data=service_data,
)
sign = "+" if adjustment.quantity >= 0 else ""
logger.info(
f"Admin {current_admin.email} adjusted inventory for product {adjustment.product_id} "
f"at {adjustment.location}: {sign}{adjustment.quantity} units"
f"{f' (reason: {adjustment.reason})' if adjustment.reason else ''}"
)
db.commit()
return result
@router.put("/{inventory_id}", response_model=InventoryResponse)
def update_inventory(
inventory_id: int,
inventory_update: InventoryUpdate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Update inventory entry fields."""
# Get inventory to find vendor_id
inventory = inventory_service.get_inventory_by_id_admin(db, inventory_id)
result = inventory_service.update_inventory(
db=db,
vendor_id=inventory.vendor_id,
inventory_id=inventory_id,
inventory_update=inventory_update,
)
logger.info(f"Admin {current_admin.email} updated inventory {inventory_id}")
db.commit()
return result
@router.delete("/{inventory_id}", response_model=InventoryMessageResponse)
def delete_inventory(
inventory_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_api),
):
"""Delete inventory entry."""
# Get inventory to find vendor_id and log details
inventory = inventory_service.get_inventory_by_id_admin(db, inventory_id)
vendor_id = inventory.vendor_id
product_id = inventory.product_id
location = inventory.location
inventory_service.delete_inventory(
db=db,
vendor_id=vendor_id,
inventory_id=inventory_id,
)
logger.info(
f"Admin {current_admin.email} deleted inventory {inventory_id} "
f"(product {product_id} at {location})"
)
db.commit()
return InventoryMessageResponse(message="Inventory deleted successfully")

View File

@@ -24,6 +24,8 @@ Routes:
- GET /vendors/{vendor_code}/theme → Vendor theme editor (auth required)
- GET /users → User management page (auth required)
- GET /customers → Customer management page (auth required)
- GET /inventory → Inventory management page (auth required)
- GET /orders → Orders management page (auth required)
- GET /imports → Import history page (auth required)
- GET /marketplace-products → Marketplace products catalog (auth required)
- GET /vendor-products → Vendor products catalog (auth required)
@@ -474,6 +476,54 @@ async def admin_customers_page(
)
# ============================================================================
# INVENTORY MANAGEMENT ROUTES
# ============================================================================
@router.get("/inventory", response_class=HTMLResponse, include_in_schema=False)
async def admin_inventory_page(
request: Request,
current_user: User = Depends(get_current_admin_from_cookie_or_header),
db: Session = Depends(get_db),
):
"""
Render inventory management page.
Shows stock levels across all vendors with filtering and adjustment capabilities.
"""
return templates.TemplateResponse(
"admin/inventory.html",
{
"request": request,
"user": current_user,
},
)
# ============================================================================
# ORDER MANAGEMENT ROUTES
# ============================================================================
@router.get("/orders", response_class=HTMLResponse, include_in_schema=False)
async def admin_orders_page(
request: Request,
current_user: User = Depends(get_current_admin_from_cookie_or_header),
db: Session = Depends(get_db),
):
"""
Render orders management page.
Shows orders across all vendors with filtering and status management.
"""
return templates.TemplateResponse(
"admin/orders.html",
{
"request": request,
"user": current_user,
},
)
# ============================================================================
# IMPORT MANAGEMENT ROUTES
# ============================================================================

View File

@@ -2,6 +2,7 @@
import logging
from datetime import UTC, datetime
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.exceptions import (
@@ -11,10 +12,19 @@ from app.exceptions import (
InventoryValidationException,
ProductNotFoundException,
ValidationException,
VendorNotFoundException,
)
from models.database.inventory import Inventory
from models.database.product import Product
from models.database.vendor import Vendor
from models.schema.inventory import (
AdminInventoryItem,
AdminInventoryListResponse,
AdminInventoryLocationsResponse,
AdminInventoryStats,
AdminLowStockItem,
AdminVendorsWithInventoryResponse,
AdminVendorWithInventory,
InventoryAdjust,
InventoryCreate,
InventoryLocationResponse,
@@ -547,7 +557,325 @@ class InventoryService:
logger.error(f"Error deleting inventory: {str(e)}")
raise ValidationException("Failed to delete inventory")
# =========================================================================
# Admin Methods (cross-vendor operations)
# =========================================================================
def get_all_inventory_admin(
self,
db: Session,
skip: int = 0,
limit: int = 50,
vendor_id: int | None = None,
location: str | None = None,
low_stock: int | None = None,
search: str | None = None,
) -> AdminInventoryListResponse:
"""
Get inventory across all vendors with filtering (admin only).
Args:
db: Database session
skip: Pagination offset
limit: Pagination limit
vendor_id: Filter by vendor
location: Filter by location
low_stock: Filter items below threshold
search: Search by product title or SKU
Returns:
AdminInventoryListResponse
"""
query = db.query(Inventory).join(Product).join(Vendor)
# Apply filters
if vendor_id is not None:
query = query.filter(Inventory.vendor_id == vendor_id)
if location:
query = query.filter(Inventory.location.ilike(f"%{location}%"))
if low_stock is not None:
query = query.filter(Inventory.quantity <= low_stock)
if search:
from models.database.marketplace_product import MarketplaceProduct
from models.database.marketplace_product_translation import (
MarketplaceProductTranslation,
)
query = (
query.join(MarketplaceProduct)
.outerjoin(MarketplaceProductTranslation)
.filter(
(MarketplaceProductTranslation.title.ilike(f"%{search}%"))
| (Product.vendor_sku.ilike(f"%{search}%"))
)
)
# Get total count before pagination
total = query.count()
# Apply pagination
inventories = query.offset(skip).limit(limit).all()
# Build response with vendor/product info
items = []
for inv in inventories:
product = inv.product
vendor = inv.vendor
title = None
if product and product.marketplace_product:
title = product.marketplace_product.get_title()
items.append(
AdminInventoryItem(
id=inv.id,
product_id=inv.product_id,
vendor_id=inv.vendor_id,
vendor_name=vendor.name if vendor else None,
vendor_code=vendor.vendor_code if vendor else None,
product_title=title,
product_sku=product.vendor_sku if product else None,
location=inv.location,
quantity=inv.quantity,
reserved_quantity=inv.reserved_quantity,
available_quantity=inv.available_quantity,
gtin=inv.gtin,
created_at=inv.created_at,
updated_at=inv.updated_at,
)
)
return AdminInventoryListResponse(
inventories=items,
total=total,
skip=skip,
limit=limit,
vendor_filter=vendor_id,
location_filter=location,
)
def get_inventory_stats_admin(self, db: Session) -> AdminInventoryStats:
"""Get platform-wide inventory statistics (admin only)."""
# Total entries
total_entries = db.query(func.count(Inventory.id)).scalar() or 0
# Aggregate quantities
totals = db.query(
func.sum(Inventory.quantity).label("total_qty"),
func.sum(Inventory.reserved_quantity).label("total_reserved"),
).first()
total_quantity = totals.total_qty or 0
total_reserved = totals.total_reserved or 0
total_available = total_quantity - total_reserved
# Low stock count (default threshold: 10)
low_stock_count = (
db.query(func.count(Inventory.id))
.filter(Inventory.quantity <= 10)
.scalar()
or 0
)
# Vendors with inventory
vendors_with_inventory = (
db.query(func.count(func.distinct(Inventory.vendor_id))).scalar() or 0
)
# Unique locations
unique_locations = (
db.query(func.count(func.distinct(Inventory.location))).scalar() or 0
)
return AdminInventoryStats(
total_entries=total_entries,
total_quantity=total_quantity,
total_reserved=total_reserved,
total_available=total_available,
low_stock_count=low_stock_count,
vendors_with_inventory=vendors_with_inventory,
unique_locations=unique_locations,
)
def get_low_stock_items_admin(
self,
db: Session,
threshold: int = 10,
vendor_id: int | None = None,
limit: int = 50,
) -> list[AdminLowStockItem]:
"""Get items with low stock levels (admin only)."""
query = (
db.query(Inventory)
.join(Product)
.join(Vendor)
.filter(Inventory.quantity <= threshold)
)
if vendor_id is not None:
query = query.filter(Inventory.vendor_id == vendor_id)
# Order by quantity ascending (most critical first)
query = query.order_by(Inventory.quantity.asc())
inventories = query.limit(limit).all()
items = []
for inv in inventories:
product = inv.product
vendor = inv.vendor
title = None
if product and product.marketplace_product:
title = product.marketplace_product.get_title()
items.append(
AdminLowStockItem(
id=inv.id,
product_id=inv.product_id,
vendor_id=inv.vendor_id,
vendor_name=vendor.name if vendor else None,
product_title=title,
location=inv.location,
quantity=inv.quantity,
reserved_quantity=inv.reserved_quantity,
available_quantity=inv.available_quantity,
)
)
return items
def get_vendors_with_inventory_admin(
self, db: Session
) -> AdminVendorsWithInventoryResponse:
"""Get list of vendors that have inventory entries (admin only)."""
vendors = (
db.query(Vendor).join(Inventory).distinct().order_by(Vendor.name).all()
)
return AdminVendorsWithInventoryResponse(
vendors=[
AdminVendorWithInventory(
id=v.id, name=v.name, vendor_code=v.vendor_code
)
for v in vendors
]
)
def get_inventory_locations_admin(
self, db: Session, vendor_id: int | None = None
) -> AdminInventoryLocationsResponse:
"""Get list of unique inventory locations (admin only)."""
query = db.query(func.distinct(Inventory.location))
if vendor_id is not None:
query = query.filter(Inventory.vendor_id == vendor_id)
locations = [loc[0] for loc in query.all()]
return AdminInventoryLocationsResponse(locations=sorted(locations))
def get_vendor_inventory_admin(
self,
db: Session,
vendor_id: int,
skip: int = 0,
limit: int = 50,
location: str | None = None,
low_stock: int | None = None,
) -> AdminInventoryListResponse:
"""Get inventory for a specific vendor (admin only)."""
# Verify vendor exists
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
if not vendor:
raise VendorNotFoundException(f"Vendor {vendor_id} not found")
# Use the existing method
inventories = self.get_vendor_inventory(
db=db,
vendor_id=vendor_id,
skip=skip,
limit=limit,
location=location,
low_stock_threshold=low_stock,
)
# Build response with product info
items = []
for inv in inventories:
product = inv.product
title = None
if product and product.marketplace_product:
title = product.marketplace_product.get_title()
items.append(
AdminInventoryItem(
id=inv.id,
product_id=inv.product_id,
vendor_id=inv.vendor_id,
vendor_name=vendor.name,
vendor_code=vendor.vendor_code,
product_title=title,
product_sku=product.vendor_sku if product else None,
location=inv.location,
quantity=inv.quantity,
reserved_quantity=inv.reserved_quantity,
available_quantity=inv.available_quantity,
gtin=inv.gtin,
created_at=inv.created_at,
updated_at=inv.updated_at,
)
)
# Get total count for pagination
total_query = db.query(func.count(Inventory.id)).filter(
Inventory.vendor_id == vendor_id
)
if location:
total_query = total_query.filter(Inventory.location.ilike(f"%{location}%"))
if low_stock is not None:
total_query = total_query.filter(Inventory.quantity <= low_stock)
total = total_query.scalar() or 0
return AdminInventoryListResponse(
inventories=items,
total=total,
skip=skip,
limit=limit,
vendor_filter=vendor_id,
location_filter=location,
)
def get_product_inventory_admin(
self, db: Session, product_id: int
) -> ProductInventorySummary:
"""Get inventory summary for a product (admin only - no vendor check)."""
product = db.query(Product).filter(Product.id == product_id).first()
if not product:
raise ProductNotFoundException(f"Product {product_id} not found")
# Use existing method with the product's vendor_id
return self.get_product_inventory(db, product.vendor_id, product_id)
def verify_vendor_exists(self, db: Session, vendor_id: int) -> Vendor:
"""Verify vendor exists and return it."""
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
if not vendor:
raise VendorNotFoundException(f"Vendor {vendor_id} not found")
return vendor
def get_inventory_by_id_admin(self, db: Session, inventory_id: int) -> Inventory:
"""Get inventory by ID (admin only - returns inventory with vendor_id)."""
inventory = db.query(Inventory).filter(Inventory.id == inventory_id).first()
if not inventory:
raise InventoryNotFoundException(f"Inventory {inventory_id} not found")
return inventory
# =========================================================================
# Private helper methods
# =========================================================================
def _get_vendor_product(
self, db: Session, vendor_id: int, product_id: int
) -> Product:

View File

@@ -0,0 +1,440 @@
{# app/templates/admin/inventory.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/headers.html' import page_header %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper %}
{% from 'shared/macros/modals.html' import modal_simple %}
{% from 'shared/macros/inputs.html' import vendor_selector %}
{% block title %}Inventory{% endblock %}
{% block alpine_data %}adminInventory(){% endblock %}
{% block content %}
{{ page_header('Inventory', subtitle='Manage stock levels across all vendors') }}
{{ loading_state('Loading inventory...') }}
{{ error_state('Error loading inventory') }}
<!-- Stats Cards -->
<div x-show="!loading" class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-4">
<!-- Card: Total Entries -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
<span x-html="$icon('archive', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Total Entries
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total_entries || 0">
0
</p>
</div>
</div>
<!-- Card: Total Quantity -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
<span x-html="$icon('cube', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Total Stock
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_quantity || 0)">
0
</p>
</div>
</div>
<!-- Card: Available Stock -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
<span x-html="$icon('check-circle', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Available
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="formatNumber(stats.total_available || 0)">
0
</p>
</div>
</div>
<!-- Card: Low Stock Items -->
<div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="p-3 mr-4 text-red-500 bg-red-100 rounded-full dark:text-red-100 dark:bg-red-500">
<span x-html="$icon('exclamation', 'w-5 h-5')"></span>
</div>
<div>
<p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
Low Stock
</p>
<p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.low_stock_count || 0">
0
</p>
</div>
</div>
</div>
<!-- Search and Filters Bar -->
<div x-show="!loading" class="mb-6 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
<!-- Search Input -->
<div class="flex-1 max-w-xl">
<div class="relative">
<span class="absolute inset-y-0 left-0 flex items-center pl-3">
<span x-html="$icon('search', 'w-5 h-5 text-gray-400')"></span>
</span>
<input
type="text"
x-model="filters.search"
@input="debouncedSearch()"
placeholder="Search by product title or SKU..."
class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
>
</div>
</div>
<!-- Filters -->
<div class="flex flex-wrap gap-3">
<!-- Vendor Filter (Tom Select) -->
{{ vendor_selector(
ref_name='vendorSelect',
id='inventory-vendor-select',
placeholder='Filter by vendor...',
width='w-64'
) }}
<!-- Location Filter -->
<select
x-model="filters.location"
@change="pagination.page = 1; loadInventory()"
class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none"
>
<option value="">All Locations</option>
<template x-for="loc in locations" :key="loc">
<option :value="loc" x-text="loc"></option>
</template>
</select>
<!-- Low Stock Filter -->
<select
x-model="filters.low_stock"
@change="pagination.page = 1; loadInventory()"
class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none"
>
<option value="">All Stock Levels</option>
<option value="5">Low Stock (< 5)</option>
<option value="10">Low Stock (< 10)</option>
<option value="25">Low Stock (< 25)</option>
<option value="50">Low Stock (< 50)</option>
</select>
<!-- Refresh Button -->
<button
@click="refresh()"
class="flex items-center px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none transition-colors"
title="Refresh inventory"
>
<span x-html="$icon('refresh', 'w-4 h-4 mr-2')"></span>
Refresh
</button>
</div>
</div>
</div>
<!-- Inventory Table with Pagination -->
<div x-show="!loading">
{% call table_wrapper() %}
<thead>
<tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
<th class="px-4 py-3">Product</th>
<th class="px-4 py-3">Vendor</th>
<th class="px-4 py-3">Location</th>
<th class="px-4 py-3 text-right">Quantity</th>
<th class="px-4 py-3 text-right">Reserved</th>
<th class="px-4 py-3 text-right">Available</th>
<th class="px-4 py-3">Status</th>
<th class="px-4 py-3">Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
<!-- Empty State -->
<template x-if="inventory.length === 0">
<tr>
<td colspan="8" class="px-4 py-8 text-center text-gray-600 dark:text-gray-400">
<div class="flex flex-col items-center">
<span x-html="$icon('archive', 'w-12 h-12 mb-2 text-gray-300')"></span>
<p class="font-medium">No inventory entries found</p>
<p class="text-xs mt-1" x-text="filters.search || filters.vendor_id || filters.location || filters.low_stock ? 'Try adjusting your filters' : 'Inventory will appear here when products have stock entries'"></p>
</div>
</td>
</tr>
</template>
<!-- Inventory Rows -->
<template x-for="item in inventory" :key="item.id">
<tr class="text-gray-700 dark:text-gray-400">
<!-- Product Info -->
<td class="px-4 py-3">
<div class="flex items-center">
<!-- Product Image -->
<div class="w-10 h-10 mr-3 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0">
<template x-if="item.product_image">
<img :src="item.product_image" :alt="item.product_title" class="w-full h-full object-cover" loading="lazy" />
</template>
<template x-if="!item.product_image">
<div class="w-full h-full flex items-center justify-center">
<span x-html="$icon('photograph', 'w-5 h-5 text-gray-400')"></span>
</div>
</template>
</div>
<!-- Product Details -->
<div class="min-w-0">
<p class="font-semibold text-sm truncate max-w-[200px]" x-text="item.product_title || 'Untitled'"></p>
<template x-if="item.product_sku">
<p class="text-xs text-gray-400 font-mono">SKU: <span x-text="item.product_sku"></span></p>
</template>
<template x-if="item.gtin">
<p class="text-xs text-gray-400 font-mono">GTIN: <span x-text="item.gtin"></span></p>
</template>
</div>
</div>
</td>
<!-- Vendor Info -->
<td class="px-4 py-3 text-sm">
<p class="font-medium" x-text="item.vendor_name || 'Unknown'"></p>
</td>
<!-- Location -->
<td class="px-4 py-3 text-sm">
<span class="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300" x-text="item.location"></span>
</td>
<!-- Quantity -->
<td class="px-4 py-3 text-sm text-right font-mono">
<span x-text="formatNumber(item.quantity)"></span>
</td>
<!-- Reserved -->
<td class="px-4 py-3 text-sm text-right font-mono">
<span :class="item.reserved_quantity > 0 ? 'text-orange-600 dark:text-orange-400' : ''" x-text="formatNumber(item.reserved_quantity)"></span>
</td>
<!-- Available -->
<td class="px-4 py-3 text-sm text-right font-mono font-semibold">
<span :class="item.available_quantity <= 0 ? 'text-red-600 dark:text-red-400' : item.available_quantity < 10 ? 'text-orange-600 dark:text-orange-400' : 'text-green-600 dark:text-green-400'" x-text="formatNumber(item.available_quantity)"></span>
</td>
<!-- Status -->
<td class="px-4 py-3 text-sm">
<template x-if="item.available_quantity <= 0">
<span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100">
Out of Stock
</span>
</template>
<template x-if="item.available_quantity > 0 && item.available_quantity < 10">
<span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100">
Low Stock
</span>
</template>
<template x-if="item.available_quantity >= 10">
<span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100">
In Stock
</span>
</template>
</td>
<!-- Actions -->
<td class="px-4 py-3 text-sm">
<div class="flex items-center space-x-2">
<button
@click="openAdjustModal(item)"
class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-purple-600 rounded-lg dark:text-purple-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
title="Adjust Stock"
>
<span x-html="$icon('adjustments', 'w-4 h-4')"></span>
</button>
<button
@click="openSetModal(item)"
class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-blue-600 rounded-lg dark:text-blue-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
title="Set Quantity"
>
<span x-html="$icon('pencil', 'w-4 h-4')"></span>
</button>
<button
@click="confirmDelete(item)"
class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-red-600 rounded-lg dark:text-red-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
title="Delete Entry"
>
<span x-html="$icon('delete', 'w-4 h-4')"></span>
</button>
</div>
</td>
</tr>
</template>
</tbody>
{% endcall %}
{{ pagination(show_condition="!loading && pagination.total > 0") }}
</div>
<!-- Adjust Stock Modal -->
{% call modal_simple('adjustStockModal', 'Adjust Stock', show_var='showAdjustModal', size='sm') %}
<div class="space-y-4">
<div class="text-sm text-gray-600 dark:text-gray-400">
<p class="font-medium text-gray-700 dark:text-gray-300" x-text="selectedItem?.product_title || 'Product'"></p>
<p class="text-xs">Location: <span x-text="selectedItem?.location || '-'"></span></p>
<p class="text-xs">Current Stock: <span x-text="formatNumber(selectedItem?.quantity || 0)"></span></p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Adjustment Quantity
</label>
<div class="flex items-center gap-2">
<button
@click="adjustForm.quantity = Math.max(-999999, adjustForm.quantity - 1)"
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 border border-gray-300 dark:border-gray-600 rounded"
>
<span x-html="$icon('minus', 'w-4 h-4')"></span>
</button>
{# noqa: FE-008 - Custom stepper with negative values for stock adjustments #}
<input
type="number"
x-model.number="adjustForm.quantity"
class="flex-1 px-3 py-2 text-sm text-center border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
placeholder="0"
>
<button
@click="adjustForm.quantity = Math.min(999999, adjustForm.quantity + 1)"
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 border border-gray-300 dark:border-gray-600 rounded"
>
<span x-html="$icon('plus', 'w-4 h-4')"></span>
</button>
</div>
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
Positive = add stock, Negative = remove stock
</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Reason (optional)
</label>
<input
type="text"
x-model="adjustForm.reason"
class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
placeholder="e.g., Restocking from supplier"
>
</div>
<div class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
<p class="text-sm text-gray-600 dark:text-gray-400">
New quantity will be:
<span class="font-semibold" :class="(selectedItem?.quantity || 0) + adjustForm.quantity < 0 ? 'text-red-600' : 'text-green-600'" x-text="formatNumber(Math.max(0, (selectedItem?.quantity || 0) + adjustForm.quantity))"></span>
</p>
</div>
<div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
<button
@click="showAdjustModal = false"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
>
Cancel
</button>
<button
@click="executeAdjust()"
:disabled="saving || adjustForm.quantity === 0"
class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50"
>
<span x-text="saving ? 'Saving...' : 'Adjust Stock'"></span>
</button>
</div>
</div>
{% endcall %}
<!-- Set Quantity Modal -->
{% call modal_simple('setQuantityModal', 'Set Quantity', show_var='showSetModal', size='sm') %}
<div class="space-y-4">
<div class="text-sm text-gray-600 dark:text-gray-400">
<p class="font-medium text-gray-700 dark:text-gray-300" x-text="selectedItem?.product_title || 'Product'"></p>
<p class="text-xs">Location: <span x-text="selectedItem?.location || '-'"></span></p>
<p class="text-xs">Current Stock: <span x-text="formatNumber(selectedItem?.quantity || 0)"></span></p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
New Quantity
</label>
<input
type="number"
x-model.number="setForm.quantity"
min="0"
class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
placeholder="Enter new quantity"
>
</div>
<div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
<button
@click="showSetModal = false"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
>
Cancel
</button>
<button
@click="executeSet()"
:disabled="saving || setForm.quantity < 0"
class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
>
<span x-text="saving ? 'Saving...' : 'Set Quantity'"></span>
</button>
</div>
</div>
{% endcall %}
<!-- Delete Confirmation Modal -->
{% call modal_simple('deleteModal', 'Delete Inventory Entry', show_var='showDeleteModal', size='sm') %}
<div class="space-y-4">
<p class="text-sm text-gray-600 dark:text-gray-400">
Are you sure you want to delete this inventory entry?
</p>
<div class="text-sm">
<p class="font-medium text-gray-700 dark:text-gray-300" x-text="selectedItem?.product_title || 'Product'"></p>
<p class="text-xs text-gray-500">Location: <span x-text="selectedItem?.location || '-'"></span></p>
<p class="text-xs text-gray-500">Current Stock: <span x-text="formatNumber(selectedItem?.quantity || 0)"></span></p>
</div>
<p class="text-xs text-red-600 dark:text-red-400">
This action cannot be undone.
</p>
<div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
<button
@click="showDeleteModal = false"
class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
>
Cancel
</button>
<button
@click="executeDelete()"
:disabled="saving"
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
>
<span x-text="saving ? 'Deleting...' : 'Delete'"></span>
</button>
</div>
</div>
{% endcall %}
{% endblock %}
{% block extra_scripts %}
<script src="{{ url_for('static', path='admin/js/inventory.js') }}"></script>
{% endblock %}

View File

@@ -80,9 +80,9 @@
{{ menu_item('marketplace-products', '/admin/marketplace-products', 'database', 'Marketplace Products') }}
{{ menu_item('vendor-products', '/admin/vendor-products', 'cube', 'Vendor Products') }}
{{ menu_item('customers', '/admin/customers', 'user-group', 'Customers') }}
{# Future items - uncomment when implemented:
{{ menu_item('inventory', '/admin/inventory', 'archive', 'Inventory') }}
{{ menu_item('orders', '/admin/orders', 'clipboard-list', 'Orders') }}
{# Future items - uncomment when implemented:
{{ menu_item('shipping', '/admin/shipping', 'truck', 'Shipping') }}
#}
{% endcall %}