shop management features

This commit is contained in:
2025-09-07 22:33:30 +02:00
parent 3342f1ab45
commit 9a5d70e825
3 changed files with 482 additions and 26 deletions

286
main.py
View File

@@ -18,19 +18,18 @@ import time
from functools import wraps
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import utility modules
from utils.data_processing import GTINProcessor, PriceProcessor
from utils.csv_processor import CSVProcessor
from utils.database import get_db_engine, get_session_local
from models.database_models import Base, Product, Stock, User, MarketplaceImportJob
from models.database_models import Base, Product, Stock, User, MarketplaceImportJob, Shop, ShopProduct
from models.api_models import *
from middleware.rate_limiter import RateLimiter
from middleware.auth import AuthManager
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
@@ -115,7 +114,8 @@ async def lifespan(app: FastAPI):
# FastAPI app with lifespan
app = FastAPI(
title="Ecommerce Backend API with Marketplace Support",
description="Advanced product management system with JWT authentication, marketplace-aware CSV import/export and stock management",
description="Advanced product management system with JWT authentication, marketplace-aware CSV "
"import/export and stock management",
version="2.2.0",
lifespan=lifespan
)
@@ -157,6 +157,19 @@ def get_current_admin_user(current_user: User = Depends(get_current_user)):
return auth_manager.require_admin(current_user)
def get_user_shop(shop_code: str, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""Get shop and verify user ownership (or admin)"""
shop = db.query(Shop).filter(Shop.shop_code == shop_code.upper()).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
# Admin can access any shop, owners can access their own shops
if current_user.role != "admin" and shop.owner_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied to this shop")
return shop
# Rate limiting decorator
def rate_limit(max_requests: int = 100, window_seconds: int = 3600):
def decorator(func):
@@ -282,14 +295,23 @@ async def import_products_from_marketplace(
"""Import products from marketplace CSV with background processing (Protected)"""
logger.info(
f"Starting marketplace import: {request.marketplace} -> {request.shop_name} by user {current_user.username}")
f"Starting marketplace import: {request.marketplace} -> {request.shop_code} by user {current_user.username}")
# 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")
# 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")
# Create marketplace import job record
import_job = MarketplaceImportJob(
status="pending",
source_url=request.url,
marketplace=request.marketplace,
shop_name=request.shop_name,
shop_code=request.shop_code,
user_id=current_user.id,
created_at=datetime.utcnow()
)
@@ -303,7 +325,7 @@ async def import_products_from_marketplace(
import_job.id,
request.url,
request.marketplace,
request.shop_name,
request.shop_code,
request.batch_size or 1000
)
@@ -311,12 +333,13 @@ async def import_products_from_marketplace(
job_id=import_job.id,
status="pending",
marketplace=request.marketplace,
shop_name=request.shop_name,
shop_code=request.shop_code,
message=f"Marketplace import started from {request.marketplace}. Check status with /marketplace-import-status/{import_job.id}"
)
async def process_marketplace_import(job_id: int, url: str, marketplace: str, shop_name: str, batch_size: int = 1000):
async def process_marketplace_import(job_id: int, url: str, marketplace: str, shop_name: str,
batch_size: int = 1000):
"""Background task to process marketplace CSV import with batching"""
db = SessionLocal()
@@ -352,7 +375,8 @@ async def process_marketplace_import(job_id: int, url: str, marketplace: str, sh
db.commit()
logger.info(
f"Marketplace import job {job_id} completed successfully - Imported: {result['imported']}, Updated: {result['updated']}")
f"Marketplace import job {job_id} completed successfully - Imported: {result['imported']}, "
f"Updated: {result['updated']}")
except Exception as e:
logger.error(f"Marketplace import job {job_id} failed: {e}")
@@ -899,7 +923,8 @@ def get_all_stock(
@app.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:
@@ -923,6 +948,180 @@ def delete_stock(stock_id: int, db: Session = Depends(get_db), current_user: Use
db.commit()
return {"message": "Stock entry deleted successfully"}
# Shop Management Routes
@app.post("/shops", response_model=ShopResponse)
def create_shop(
shop_data: ShopCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Create a new shop (Protected)"""
# Check if shop code already exists
existing_shop = db.query(Shop).filter(Shop.shop_code == shop_data.shop_code).first()
if existing_shop:
raise HTTPException(status_code=400, detail="Shop code already exists")
# Create shop
new_shop = Shop(
**shop_data.dict(),
owner_id=current_user.id,
is_active=True,
is_verified=(current_user.role == "admin") # Auto-verify if admin creates shop
)
db.add(new_shop)
db.commit()
db.refresh(new_shop)
logger.info(f"New shop created: {new_shop.shop_code} by {current_user.username}")
return new_shop
@app.get("/shops", response_model=ShopListResponse)
def get_shops(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
active_only: bool = Query(True),
verified_only: bool = Query(False),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get shops with filtering (Protected)"""
query = db.query(Shop)
# Non-admin users can only see active and verified shops, plus their own
if current_user.role != "admin":
query = query.filter(
(Shop.is_active == True) &
((Shop.is_verified == True) | (Shop.owner_id == current_user.id))
)
else:
# Admin can apply filters
if active_only:
query = query.filter(Shop.is_active == True)
if verified_only:
query = query.filter(Shop.is_verified == True)
total = query.count()
shops = query.offset(skip).limit(limit).all()
return ShopListResponse(
shops=shops,
total=total,
skip=skip,
limit=limit
)
@app.get("/shops/{shop_code}", response_model=ShopResponse)
def get_shop(shop_code: str, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
"""Get shop details (Protected)"""
shop = db.query(Shop).filter(Shop.shop_code == shop_code.upper()).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
# Non-admin users can only see active verified shops or their own shops
if current_user.role != "admin":
if not shop.is_active or (not shop.is_verified and shop.owner_id != current_user.id):
raise HTTPException(status_code=404, detail="Shop not found")
return shop
# Shop Product Management
@app.post("/shops/{shop_code}/products", response_model=ShopProductResponse)
def add_product_to_shop(
shop_code: str,
shop_product: ShopProductCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Add existing product to shop catalog with shop-specific settings (Protected)"""
# Get and verify shop
shop = get_user_shop(shop_code, current_user, db)
# Check if product exists
product = db.query(Product).filter(Product.product_id == shop_product.product_id).first()
if not product:
raise HTTPException(status_code=404, detail="Product not found in marketplace catalog")
# Check if product already in shop
existing_shop_product = db.query(ShopProduct).filter(
ShopProduct.shop_id == shop.id,
ShopProduct.product_id == product.id
).first()
if existing_shop_product:
raise HTTPException(status_code=400, detail="Product already in shop catalog")
# Create shop-product association
new_shop_product = ShopProduct(
shop_id=shop.id,
product_id=product.id,
**shop_product.dict(exclude={'product_id'})
)
db.add(new_shop_product)
db.commit()
db.refresh(new_shop_product)
# Return with product details
response = ShopProductResponse.model_validate(new_shop_product)
response.product = product
return response
@app.get("/shops/{shop_code}/products")
def get_shop_products(
shop_code: str,
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
active_only: bool = Query(True),
featured_only: bool = Query(False),
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
"""Get products in shop catalog (Protected)"""
# Get shop (public can view active/verified shops)
shop = db.query(Shop).filter(Shop.shop_code == shop_code.upper()).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
# Non-owners can only see active verified shops
if current_user.role != "admin" and shop.owner_id != current_user.id:
if not shop.is_active or not shop.is_verified:
raise HTTPException(status_code=404, detail="Shop not found")
# Query shop products
query = db.query(ShopProduct).filter(ShopProduct.shop_id == shop.id)
if active_only:
query = query.filter(ShopProduct.is_active == True)
if featured_only:
query = query.filter(ShopProduct.is_featured == True)
total = query.count()
shop_products = query.offset(skip).limit(limit).all()
# Format response
products = []
for sp in shop_products:
product_response = ShopProductResponse.model_validate(sp)
product_response.product = sp.product
products.append(product_response)
return {
"products": products,
"total": total,
"skip": skip,
"limit": limit,
"shop": ShopResponse.model_validate(shop)
}
# Enhanced Statistics with Marketplace Support
@app.get("/stats", response_model=StatsResponse)
def get_stats(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
@@ -1078,6 +1277,65 @@ def toggle_user_status(
return {"message": f"User {user.username} has been {status}"}
@app.get("/admin/shops", response_model=ShopListResponse)
def get_all_shops_admin(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
):
"""Get all shops with admin view (Admin only)"""
total = db.query(Shop).count()
shops = db.query(Shop).offset(skip).limit(limit).all()
return ShopListResponse(
shops=shops,
total=total,
skip=skip,
limit=limit
)
@app.put("/admin/shops/{shop_id}/verify")
def verify_shop(
shop_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
):
"""Verify/unverify shop (Admin only)"""
shop = db.query(Shop).filter(Shop.id == shop_id).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
shop.is_verified = not shop.is_verified
shop.updated_at = datetime.utcnow()
db.commit()
db.refresh(shop)
status = "verified" if shop.is_verified else "unverified"
return {"message": f"Shop {shop.shop_code} has been {status}"}
@app.put("/admin/shops/{shop_id}/status")
def toggle_shop_status(
shop_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
):
"""Toggle shop active status (Admin only)"""
shop = db.query(Shop).filter(Shop.id == shop_id).first()
if not shop:
raise HTTPException(status_code=404, detail="Shop not found")
shop.is_active = not shop.is_active
shop.updated_at = datetime.utcnow()
db.commit()
db.refresh(shop)
status = "activated" if shop.is_active else "deactivated"
return {"message": f"Shop {shop.shop_code} has been {status}"}
@app.get("/admin/marketplace-import-jobs", response_model=List[MarketplaceImportJobResponse])
def get_all_marketplace_import_jobs(
marketplace: Optional[str] = Query(None),
@@ -1130,4 +1388,4 @@ if __name__ == "__main__":
port=8000,
reload=True,
log_level="info"
)
)