Refactoring code for modular approach

This commit is contained in:
2025-09-09 22:07:21 +02:00
parent b865235f8a
commit 8fbe64687a
9 changed files with 1517 additions and 520 deletions

View File

@@ -7,8 +7,8 @@ from app.api.deps import get_current_user
from app.tasks.background_tasks import process_marketplace_import
from middleware.decorators import rate_limit
from models.api_models import MarketplaceImportJobResponse, MarketplaceImportRequest
from models.database_models import User, MarketplaceImportJob, Shop
from datetime import datetime
from models.database_models import User
from marketplace_service import marketplace_service
import logging
router = APIRouter()
@@ -25,50 +25,39 @@ async def import_products_from_marketplace(
current_user: User = Depends(get_current_user)
):
"""Import products from marketplace CSV with background processing (Protected)"""
try:
logger.info(
f"Starting marketplace import: {request.marketplace} -> {request.shop_code} by user {current_user.username}")
logger.info(
f"Starting marketplace import: {request.marketplace} -> {request.shop_code} by user {current_user.username}")
# Create import job through service
import_job = marketplace_service.create_import_job(db, request, current_user)
# Verify shop exists and user has access
shop = db.query(Shop).filter(Shop.shop_code == request.shop_code).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
# Process in background
background_tasks.add_task(
process_marketplace_import,
import_job.id,
request.url,
request.marketplace,
request.shop_code,
request.batch_size or 1000
)
# Check permissions: admin can import for any shop, others only for their own
if current_user.role != "admin" and shop.owner_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied to this shop")
return MarketplaceImportJobResponse(
job_id=import_job.id,
status="pending",
marketplace=request.marketplace,
shop_code=request.shop_code,
message=f"Marketplace import started from {request.marketplace}. Check status with "
f"/marketplace-import-status/{import_job.id}"
)
# Create marketplace import job record
import_job = MarketplaceImportJob(
status="pending",
source_url=request.url,
marketplace=request.marketplace,
shop_code=request.shop_code,
user_id=current_user.id,
created_at=datetime.utcnow()
)
db.add(import_job)
db.commit()
db.refresh(import_job)
# Process in background
background_tasks.add_task(
process_marketplace_import,
import_job.id,
request.url,
request.marketplace,
request.shop_code,
request.batch_size or 1000
)
return MarketplaceImportJobResponse(
job_id=import_job.id,
status="pending",
marketplace=request.marketplace,
shop_code=request.shop_code,
message=f"Marketplace import started from {request.marketplace}. Check status with "
f"/marketplace-import-status/{import_job.id}"
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e))
except Exception as e:
logger.error(f"Error starting marketplace import: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/marketplace-import-status/{job_id}", response_model=MarketplaceImportJobResponse)
@@ -78,28 +67,17 @@ def get_marketplace_import_status(
current_user: User = Depends(get_current_user)
):
"""Get status of marketplace import job (Protected)"""
job = db.query(MarketplaceImportJob).filter(MarketplaceImportJob.id == job_id).first()
if not job:
raise HTTPException(status_code=404, detail="Marketplace import job not found")
try:
job = marketplace_service.get_import_job_by_id(db, job_id, current_user)
return marketplace_service.convert_to_response_model(job)
# Users can only see their own jobs, admins can see all
if current_user.role != "admin" and job.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied to this import job")
return MarketplaceImportJobResponse(
job_id=job.id,
status=job.status,
marketplace=job.marketplace,
shop_name=job.shop_name,
imported=job.imported_count or 0,
updated=job.updated_count or 0,
total_processed=job.total_processed or 0,
error_count=job.error_count or 0,
error_message=job.error_message,
created_at=job.created_at,
started_at=job.started_at,
completed_at=job.completed_at
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e))
except Exception as e:
logger.error(f"Error getting import job status {job_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/marketplace-import-jobs", response_model=List[MarketplaceImportJobResponse])
@@ -112,35 +90,73 @@ def get_marketplace_import_jobs(
current_user: User = Depends(get_current_user)
):
"""Get marketplace import jobs with filtering (Protected)"""
try:
jobs = marketplace_service.get_import_jobs(
db=db,
user=current_user,
marketplace=marketplace,
shop_name=shop_name,
skip=skip,
limit=limit
)
query = db.query(MarketplaceImportJob)
return [marketplace_service.convert_to_response_model(job) for job in jobs]
# Users can only see their own jobs, admins can see all
if current_user.role != "admin":
query = query.filter(MarketplaceImportJob.user_id == current_user.id)
except Exception as e:
logger.error(f"Error getting import jobs: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
# Apply filters
if marketplace:
query = query.filter(MarketplaceImportJob.marketplace.ilike(f"%{marketplace}%"))
if shop_name:
query = query.filter(MarketplaceImportJob.shop_name.ilike(f"%{shop_name}%"))
# Order by creation date (newest first) and apply pagination
jobs = query.order_by(MarketplaceImportJob.created_at.desc()).offset(skip).limit(limit).all()
@router.get("/marketplace-import-stats")
def get_marketplace_import_stats(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get statistics about marketplace import jobs (Protected)"""
try:
stats = marketplace_service.get_job_stats(db, current_user)
return stats
return [
MarketplaceImportJobResponse(
job_id=job.id,
status=job.status,
marketplace=job.marketplace,
shop_name=job.shop_name,
imported=job.imported_count or 0,
updated=job.updated_count or 0,
total_processed=job.total_processed or 0,
error_count=job.error_count or 0,
error_message=job.error_message,
created_at=job.created_at,
started_at=job.started_at,
completed_at=job.completed_at
) for job in jobs
]
except Exception as e:
logger.error(f"Error getting import stats: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.put("/marketplace-import-jobs/{job_id}/cancel", response_model=MarketplaceImportJobResponse)
def cancel_marketplace_import_job(
job_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Cancel a pending or running marketplace import job (Protected)"""
try:
job = marketplace_service.cancel_import_job(db, job_id, current_user)
return marketplace_service.convert_to_response_model(job)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e))
except Exception as e:
logger.error(f"Error cancelling import job {job_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.delete("/marketplace-import-jobs/{job_id}")
def delete_marketplace_import_job(
job_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Delete a completed marketplace import job (Protected)"""
try:
marketplace_service.delete_import_job(db, job_id, current_user)
return {"message": "Marketplace import job deleted successfully"}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except PermissionError as e:
raise HTTPException(status_code=403, detail=str(e))
except Exception as e:
logger.error(f"Error deleting import job {job_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")

View File

@@ -11,15 +11,12 @@ from models.database_models import User, Product, Stock
from datetime import datetime
import logging
from utils.data_processing import GTINProcessor, PriceProcessor
from app.services.product_service import product_service
router = APIRouter()
logger = logging.getLogger(__name__)
# Initialize processors
gtin_processor = GTINProcessor()
price_processor = PriceProcessor()
# Enhanced Product Routes with Marketplace Support
@router.get("/products", response_model=ProductListResponse)
@@ -37,41 +34,28 @@ def get_products(
):
"""Get products with advanced filtering including marketplace and shop (Protected)"""
query = db.query(Product)
# Apply filters
if brand:
query = query.filter(Product.brand.ilike(f"%{brand}%"))
if category:
query = query.filter(Product.google_product_category.ilike(f"%{category}%"))
if availability:
query = query.filter(Product.availability == availability)
if marketplace:
query = query.filter(Product.marketplace.ilike(f"%{marketplace}%"))
if shop_name:
query = query.filter(Product.shop_name.ilike(f"%{shop_name}%"))
if search:
# Search in title, description, and marketplace
search_term = f"%{search}%"
query = query.filter(
(Product.title.ilike(search_term)) |
(Product.description.ilike(search_term)) |
(Product.marketplace.ilike(search_term)) |
(Product.shop_name.ilike(search_term))
try:
products, total = product_service.get_products_with_filters(
db=db,
skip=skip,
limit=limit,
brand=brand,
category=category,
availability=availability,
marketplace=marketplace,
shop_name=shop_name,
search=search
)
# Get total count for pagination
total = query.count()
# Apply pagination
products = query.offset(skip).limit(limit).all()
return ProductListResponse(
products=products,
total=total,
skip=skip,
limit=limit
)
return ProductListResponse(
products=products,
total=total,
skip=skip,
limit=limit
)
except Exception as e:
logger.error(f"Error getting products: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.post("/products", response_model=ProductResponse)
@@ -82,68 +66,54 @@ def create_product(
):
"""Create a new product with validation and marketplace support (Protected)"""
# Check if product_id already exists
existing = db.query(Product).filter(Product.product_id == product.product_id).first()
if existing:
raise HTTPException(status_code=400, detail="Product with this ID already exists")
try:
# Check if product_id already exists
existing = product_service.get_product_by_id(db, product.product_id)
if existing:
raise HTTPException(status_code=400, detail="Product with this ID already exists")
# Process and validate GTIN if provided
if product.gtin:
normalized_gtin = gtin_processor.normalize(product.gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
product.gtin = normalized_gtin
db_product = product_service.create_product(db, product)
# Process price if provided
if product.price:
parsed_price, currency = price_processor.parse_price_currency(product.price)
if parsed_price:
product.price = parsed_price
product.currency = currency
logger.info(
f"Created product {db_product.product_id} for marketplace {db_product.marketplace}, "
f"shop {db_product.shop_name}")
return db_product
# Set default marketplace if not provided
if not product.marketplace:
product.marketplace = "Letzshop"
db_product = Product(**product.dict())
db.add(db_product)
db.commit()
db.refresh(db_product)
logger.info(
f"Created product {db_product.product_id} for marketplace {db_product.marketplace}, "
f"shop {db_product.shop_name}")
return db_product
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error creating product: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/products/{product_id}", response_model=ProductDetailResponse)
def get_product(product_id: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def get_product(
product_id: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get product with stock information (Protected)"""
product = db.query(Product).filter(Product.product_id == product_id).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found")
try:
product = product_service.get_product_by_id(db, product_id)
if not product:
raise HTTPException(status_code=404, detail="Product not found")
# Get stock information if GTIN exists
stock_info = None
if product.gtin:
stock_entries = db.query(Stock).filter(Stock.gtin == product.gtin).all()
if stock_entries:
total_quantity = sum(entry.quantity for entry in stock_entries)
locations = [
StockLocationResponse(location=entry.location, quantity=entry.quantity)
for entry in stock_entries
]
stock_info = StockSummaryResponse(
gtin=product.gtin,
total_quantity=total_quantity,
locations=locations
)
# Get stock information if GTIN exists
stock_info = None
if product.gtin:
stock_info = product_service.get_stock_info(db, product.gtin)
return ProductDetailResponse(
product=product,
stock_info=stock_info
)
return ProductDetailResponse(
product=product,
stock_info=stock_info
)
except HTTPException:
raise
except Exception as e:
logger.error(f"Error getting product {product_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.put("/products/{product_id}", response_model=ProductResponse)
@@ -155,35 +125,21 @@ def update_product(
):
"""Update product with validation and marketplace support (Protected)"""
product = db.query(Product).filter(Product.product_id == product_id).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found")
try:
product = product_service.get_product_by_id(db, product_id)
if not product:
raise HTTPException(status_code=404, detail="Product not found")
# Update fields
update_data = product_update.dict(exclude_unset=True)
updated_product = product_service.update_product(db, product_id, product_update)
return updated_product
# Validate GTIN if being updated
if "gtin" in update_data and update_data["gtin"]:
normalized_gtin = gtin_processor.normalize(update_data["gtin"])
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
update_data["gtin"] = normalized_gtin
# Process price if being updated
if "price" in update_data and update_data["price"]:
parsed_price, currency = price_processor.parse_price_currency(update_data["price"])
if parsed_price:
update_data["price"] = parsed_price
update_data["currency"] = currency
for key, value in update_data.items():
setattr(product, key, value)
product.updated_at = datetime.utcnow()
db.commit()
db.refresh(product)
return product
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error updating product {product_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.delete("/products/{product_id}")
@@ -194,18 +150,21 @@ def delete_product(
):
"""Delete product and associated stock (Protected)"""
product = db.query(Product).filter(Product.product_id == product_id).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found")
try:
product = product_service.get_product_by_id(db, product_id)
if not product:
raise HTTPException(status_code=404, detail="Product not found")
# Delete associated stock entries if GTIN exists
if product.gtin:
db.query(Stock).filter(Stock.gtin == product.gtin).delete()
product_service.delete_product(db, product_id)
db.delete(product)
db.commit()
return {"message": "Product and associated stock deleted successfully"}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error deleting product {product_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
return {"message": "Product and associated stock deleted successfully"}
# Export with streaming for large datasets (Protected)
@router.get("/export-csv")
@@ -217,45 +176,27 @@ async def export_csv(
):
"""Export products as CSV with streaming and marketplace filtering (Protected)"""
def generate_csv():
# Stream CSV generation for memory efficiency
yield "product_id,title,description,link,image_link,availability,price,currency,brand,gtin,marketplace,shop_name\n"
try:
def generate_csv():
return product_service.generate_csv_export(
db=db,
marketplace=marketplace,
shop_name=shop_name
)
batch_size = 1000
offset = 0
filename = "products_export"
if marketplace:
filename += f"_{marketplace}"
if shop_name:
filename += f"_{shop_name}"
filename += ".csv"
while True:
query = db.query(Product)
return StreamingResponse(
generate_csv(),
media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
# Apply marketplace filters
if marketplace:
query = query.filter(Product.marketplace.ilike(f"%{marketplace}%"))
if shop_name:
query = query.filter(Product.shop_name.ilike(f"%{shop_name}%"))
products = query.offset(offset).limit(batch_size).all()
if not products:
break
for product in products:
# Create CSV row with marketplace fields
row = (f'"{product.product_id}","{product.title or ""}","{product.description or ""}",'
f'"{product.link or ""}","{product.image_link or ""}","{product.availability or ""}",'
f'"{product.price or ""}","{product.currency or ""}","{product.brand or ""}",'
f'"{product.gtin or ""}","{product.marketplace or ""}","{product.shop_name or ""}"\n')
yield row
offset += batch_size
filename = "products_export"
if marketplace:
filename += f"_{marketplace}"
if shop_name:
filename += f"_{shop_name}"
filename += ".csv"
return StreamingResponse(
generate_csv(),
media_type="text/csv",
headers={"Content-Disposition": f"attachment; filename={filename}"}
)
except Exception as e:
logger.error(f"Error exporting CSV: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")

View File

@@ -6,10 +6,10 @@ from app.core.database import get_db
from app.api.deps import get_current_user
from app.tasks.background_tasks import process_marketplace_import
from middleware.decorators import rate_limit
from models.api_models import MarketplaceImportJobResponse, MarketplaceImportRequest, StockResponse, \
StockSummaryResponse
from models.api_models import (MarketplaceImportJobResponse, MarketplaceImportRequest, StockResponse,
StockSummaryResponse, StockCreate, StockAdd, StockUpdate)
from models.database_models import User, MarketplaceImportJob, Shop
from datetime import datetime
from stock_service import stock_service
import logging
router = APIRouter()
@@ -19,236 +19,88 @@ logger = logging.getLogger(__name__)
# Stock Management Routes (Protected)
@router.post("/stock", response_model=StockResponse)
def set_stock(stock: StockCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def set_stock(
stock: StockCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Set exact stock quantity for a GTIN at a specific location (replaces existing quantity)"""
# Normalize GTIN
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(stock.gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
# Check if stock entry already exists for this GTIN and location
existing_stock = db.query(Stock).filter(
Stock.gtin == normalized_gtin,
Stock.location == stock.location.strip().upper()
).first()
if existing_stock:
# Update existing stock (SET to exact quantity)
old_quantity = existing_stock.quantity
existing_stock.quantity = stock.quantity
existing_stock.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing_stock)
logger.info(f"Updated stock for GTIN {normalized_gtin} at {stock.location}: {old_quantity}{stock.quantity}")
return existing_stock
else:
# Create new stock entry
new_stock = Stock(
gtin=normalized_gtin,
location=stock.location.strip().upper(),
quantity=stock.quantity
)
db.add(new_stock)
db.commit()
db.refresh(new_stock)
logger.info(f"Created new stock for GTIN {normalized_gtin} at {stock.location}: {stock.quantity}")
return new_stock
try:
result = stock_service.set_stock(db, stock)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error setting stock: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.post("/stock/add", response_model=StockResponse)
def add_stock(stock: StockAdd, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def add_stock(
stock: StockAdd,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Add quantity to existing stock for a GTIN at a specific location (adds to existing quantity)"""
# Normalize GTIN
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(stock.gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
# Check if stock entry already exists for this GTIN and location
existing_stock = db.query(Stock).filter(
Stock.gtin == normalized_gtin,
Stock.location == stock.location.strip().upper()
).first()
if existing_stock:
# Add to existing stock
old_quantity = existing_stock.quantity
existing_stock.quantity += stock.quantity
existing_stock.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing_stock)
logger.info(
f"Added stock for GTIN {normalized_gtin} at {stock.location}: {old_quantity} + {stock.quantity} = {existing_stock.quantity}")
return existing_stock
else:
# Create new stock entry with the quantity
new_stock = Stock(
gtin=normalized_gtin,
location=stock.location.strip().upper(),
quantity=stock.quantity
)
db.add(new_stock)
db.commit()
db.refresh(new_stock)
logger.info(f"Created new stock for GTIN {normalized_gtin} at {stock.location}: {stock.quantity}")
return new_stock
try:
result = stock_service.add_stock(db, stock)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error adding stock: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.post("/stock/remove", response_model=StockResponse)
def remove_stock(stock: StockAdd, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def remove_stock(
stock: StockAdd,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Remove quantity from existing stock for a GTIN at a specific location"""
# Normalize GTIN
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(stock.gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
# Find existing stock entry
existing_stock = db.query(Stock).filter(
Stock.gtin == normalized_gtin,
Stock.location == stock.location.strip().upper()
).first()
if not existing_stock:
raise HTTPException(
status_code=404,
detail=f"No stock found for GTIN {normalized_gtin} at location {stock.location}"
)
# Check if we have enough stock to remove
if existing_stock.quantity < stock.quantity:
raise HTTPException(
status_code=400,
detail=f"Insufficient stock. Available: {existing_stock.quantity}, Requested to remove: {stock.quantity}"
)
# Remove from existing stock
old_quantity = existing_stock.quantity
existing_stock.quantity -= stock.quantity
existing_stock.updated_at = datetime.utcnow()
db.commit()
db.refresh(existing_stock)
logger.info(
f"Removed stock for GTIN {normalized_gtin} at {stock.location}: {old_quantity} - {stock.quantity} = {existing_stock.quantity}")
return existing_stock
try:
result = stock_service.remove_stock(db, stock)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error removing stock: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/stock/{gtin}", response_model=StockSummaryResponse)
def get_stock_by_gtin(gtin: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def get_stock_by_gtin(
gtin: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get all stock locations and total quantity for a specific GTIN"""
# Normalize GTIN
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
# Get all stock entries for this GTIN
stock_entries = db.query(Stock).filter(Stock.gtin == normalized_gtin).all()
if not stock_entries:
raise HTTPException(status_code=404, detail=f"No stock found for GTIN: {gtin}")
# Calculate total quantity and build locations list
total_quantity = 0
locations = []
for entry in stock_entries:
total_quantity += entry.quantity
locations.append(StockLocationResponse(
location=entry.location,
quantity=entry.quantity
))
# Try to get product title for reference
product = db.query(Product).filter(Product.gtin == normalized_gtin).first()
product_title = product.title if product else None
return StockSummaryResponse(
gtin=normalized_gtin,
total_quantity=total_quantity,
locations=locations,
product_title=product_title
)
try:
result = stock_service.get_stock_by_gtin(db, gtin)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"Error getting stock for GTIN {gtin}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/stock/{gtin}/total")
def get_total_stock(gtin: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def get_total_stock(
gtin: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get total quantity in stock for a specific GTIN"""
# Normalize GTIN
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(gtin)
if not normalized_gtin:
raise HTTPException(status_code=400, detail="Invalid GTIN format")
# Calculate total stock
total_stock = db.query(Stock).filter(Stock.gtin == normalized_gtin).all()
total_quantity = sum(entry.quantity for entry in total_stock)
# Get product info for context
product = db.query(Product).filter(Product.gtin == normalized_gtin).first()
return {
"gtin": normalized_gtin,
"total_quantity": total_quantity,
"product_title": product.title if product else None,
"locations_count": len(total_stock)
}
try:
result = stock_service.get_total_stock(db, gtin)
return result
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error getting total stock for GTIN {gtin}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.get("/stock", response_model=List[StockResponse])
@@ -261,55 +113,50 @@ def get_all_stock(
current_user: User = Depends(get_current_user)
):
"""Get all stock entries with optional filtering"""
query = db.query(Stock)
if location:
query = query.filter(Stock.location.ilike(f"%{location}%"))
if gtin:
# Normalize GTIN for search
def normalize_gtin(gtin_value):
if not gtin_value:
return None
gtin_str = str(gtin_value).strip()
if '.' in gtin_str:
gtin_str = gtin_str.split('.')[0]
gtin_clean = ''.join(filter(str.isdigit, gtin_str))
if len(gtin_clean) in [8, 12, 13, 14]:
return gtin_clean.zfill(13) if len(gtin_clean) == 13 else gtin_clean.zfill(12)
return gtin_clean if gtin_clean else None
normalized_gtin = normalize_gtin(gtin)
if normalized_gtin:
query = query.filter(Stock.gtin == normalized_gtin)
stock_entries = query.offset(skip).limit(limit).all()
return stock_entries
try:
result = stock_service.get_all_stock(
db=db,
skip=skip,
limit=limit,
location=location,
gtin=gtin
)
return result
except Exception as e:
logger.error(f"Error getting all stock: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.put("/stock/{stock_id}", response_model=StockResponse)
def update_stock(stock_id: int, stock_update: StockUpdate, db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)):
def update_stock(
stock_id: int,
stock_update: StockUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Update stock quantity for a specific stock entry"""
stock_entry = db.query(Stock).filter(Stock.id == stock_id).first()
if not stock_entry:
raise HTTPException(status_code=404, detail="Stock entry not found")
stock_entry.quantity = stock_update.quantity
stock_entry.updated_at = datetime.utcnow()
db.commit()
db.refresh(stock_entry)
return stock_entry
try:
result = stock_service.update_stock(db, stock_id, stock_update)
return result
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"Error updating stock {stock_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@router.delete("/stock/{stock_id}")
def delete_stock(stock_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
def delete_stock(
stock_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Delete a stock entry"""
stock_entry = db.query(Stock).filter(Stock.id == stock_id).first()
if not stock_entry:
raise HTTPException(status_code=404, detail="Stock entry not found")
db.delete(stock_entry)
db.commit()
return {"message": "Stock entry deleted successfully"}
try:
stock_service.delete_stock(db, stock_id)
return {"message": "Stock entry deleted successfully"}
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
logger.error(f"Error deleting stock {stock_id}: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")