feat: add customer profile, VAT alignment, and fix shop auth
Customer Profile: - Add profile API (GET/PUT /api/v1/shop/profile) - Add password change endpoint (PUT /api/v1/shop/profile/password) - Implement full profile page with preferences and password sections - Add CustomerPasswordChange schema Shop Authentication Fixes: - Add Authorization header to all shop account API calls - Fix orders, order-detail, messages pages authentication - Add proper redirect to login on 401 responses - Fix toast message showing noqa comment in shop-layout.js VAT Calculation: - Add shared VAT utility (app/utils/vat.py) - Add VAT fields to Order model (vat_regime, vat_rate, etc.) - Align order VAT calculation with invoice settings - Add migration for VAT fields on orders Validation Framework: - Fix base_validator.py with missing methods - Add validate_file, output_results, get_exit_code methods - Fix validate_all.py import issues Documentation: - Add launch-readiness.md tracking OMS status - Update to 95% feature complete 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,7 +21,7 @@ Authentication:
|
||||
from fastapi import APIRouter
|
||||
|
||||
# Import shop routers
|
||||
from . import addresses, auth, carts, content_pages, messages, orders, products
|
||||
from . import addresses, auth, carts, content_pages, messages, orders, products, profile
|
||||
|
||||
# Create shop router
|
||||
router = APIRouter()
|
||||
@@ -48,6 +48,9 @@ router.include_router(orders.router, tags=["shop-orders"])
|
||||
# Messages (authenticated)
|
||||
router.include_router(messages.router, tags=["shop-messages"])
|
||||
|
||||
# Profile (authenticated)
|
||||
router.include_router(profile.router, tags=["shop-profile"])
|
||||
|
||||
# Content pages (public)
|
||||
router.include_router(
|
||||
content_pages.router, prefix="/content-pages", tags=["shop-content-pages"]
|
||||
|
||||
@@ -13,15 +13,19 @@ Customer Context: get_current_customer_api returns Customer directly
|
||||
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path as FilePath
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query, Request
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_customer_api
|
||||
from app.core.database import get_db
|
||||
from app.exceptions import VendorNotFoundException
|
||||
from app.exceptions.invoice import InvoicePDFNotFoundException
|
||||
from app.services.cart_service import cart_service
|
||||
from app.services.email_service import EmailService
|
||||
from app.services.invoice_service import invoice_service
|
||||
from app.services.order_service import order_service
|
||||
from app.utils.money import cents_to_euros
|
||||
from models.database.customer import Customer
|
||||
@@ -226,3 +230,101 @@ def get_order_details(
|
||||
raise OrderNotFoundException(str(order_id))
|
||||
|
||||
return OrderDetailResponse.model_validate(order)
|
||||
|
||||
|
||||
@router.get("/orders/{order_id}/invoice")
|
||||
def download_order_invoice(
|
||||
request: Request,
|
||||
order_id: int = Path(..., description="Order ID", gt=0),
|
||||
customer: Customer = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Download invoice PDF for a customer's order.
|
||||
|
||||
Vendor is automatically determined from request context.
|
||||
Customer can only download invoices for their own orders.
|
||||
Invoice is auto-generated if it doesn't exist.
|
||||
|
||||
Path Parameters:
|
||||
- order_id: ID of the order to get invoice for
|
||||
"""
|
||||
from app.exceptions import OrderNotFoundException
|
||||
|
||||
# Get vendor from middleware
|
||||
vendor = getattr(request.state, "vendor", None)
|
||||
|
||||
if not vendor:
|
||||
raise VendorNotFoundException("context", identifier_type="subdomain")
|
||||
|
||||
logger.debug(
|
||||
f"[SHOP_API] download_order_invoice: order {order_id}",
|
||||
extra={
|
||||
"vendor_id": vendor.id,
|
||||
"vendor_code": vendor.subdomain,
|
||||
"customer_id": customer.id,
|
||||
"order_id": order_id,
|
||||
},
|
||||
)
|
||||
|
||||
# Get order
|
||||
order = order_service.get_order(db=db, vendor_id=vendor.id, order_id=order_id)
|
||||
|
||||
# Verify order belongs to customer
|
||||
if order.customer_id != customer.id:
|
||||
raise OrderNotFoundException(str(order_id))
|
||||
|
||||
# Only allow invoice download for orders that are at least processing
|
||||
allowed_statuses = ["processing", "partially_shipped", "shipped", "delivered", "completed"]
|
||||
if order.status not in allowed_statuses:
|
||||
from app.exceptions import ValidationException
|
||||
raise ValidationException("Invoice not available for pending orders")
|
||||
|
||||
# Check if invoice exists for this order (via service layer)
|
||||
invoice = invoice_service.get_invoice_by_order_id(
|
||||
db=db, vendor_id=vendor.id, order_id=order_id
|
||||
)
|
||||
|
||||
# Create invoice if it doesn't exist
|
||||
if not invoice:
|
||||
logger.info(f"Creating invoice for order {order_id} (customer download)")
|
||||
invoice = invoice_service.create_invoice_from_order(
|
||||
db=db,
|
||||
vendor_id=vendor.id,
|
||||
order_id=order_id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Get or generate PDF
|
||||
pdf_path = invoice_service.get_pdf_path(
|
||||
db=db,
|
||||
vendor_id=vendor.id,
|
||||
invoice_id=invoice.id,
|
||||
)
|
||||
|
||||
if not pdf_path:
|
||||
# Generate PDF
|
||||
pdf_path = invoice_service.generate_pdf(
|
||||
db=db,
|
||||
vendor_id=vendor.id,
|
||||
invoice_id=invoice.id,
|
||||
)
|
||||
|
||||
# Verify file exists
|
||||
if not FilePath(pdf_path).exists():
|
||||
raise InvoicePDFNotFoundException(invoice.id)
|
||||
|
||||
filename = f"invoice-{invoice.invoice_number}.pdf"
|
||||
|
||||
logger.info(
|
||||
f"Customer {customer.id} downloading invoice {invoice.invoice_number} for order {order.order_number}"
|
||||
)
|
||||
|
||||
return FileResponse(
|
||||
path=pdf_path,
|
||||
media_type="application/pdf",
|
||||
filename=filename,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename}"'
|
||||
},
|
||||
)
|
||||
|
||||
161
app/api/v1/shop/profile.py
Normal file
161
app/api/v1/shop/profile.py
Normal file
@@ -0,0 +1,161 @@
|
||||
# app/api/v1/shop/profile.py
|
||||
"""
|
||||
Shop Profile API (Customer authenticated)
|
||||
|
||||
Endpoints for managing customer profile in shop frontend.
|
||||
Requires customer authentication.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_customer_api
|
||||
from app.core.database import get_db
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
from app.exceptions import ValidationException
|
||||
from models.database.customer import Customer
|
||||
from models.schema.customer import (
|
||||
CustomerPasswordChange,
|
||||
CustomerResponse,
|
||||
CustomerUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/profile", response_model=CustomerResponse)
|
||||
def get_profile(
|
||||
customer: Customer = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get current customer profile.
|
||||
|
||||
Returns the authenticated customer's profile information.
|
||||
"""
|
||||
logger.debug(
|
||||
f"[SHOP_API] get_profile for customer {customer.id}",
|
||||
extra={
|
||||
"customer_id": customer.id,
|
||||
"email": customer.email,
|
||||
},
|
||||
)
|
||||
|
||||
return CustomerResponse.model_validate(customer)
|
||||
|
||||
|
||||
@router.put("/profile", response_model=CustomerResponse)
|
||||
def update_profile(
|
||||
update_data: CustomerUpdate,
|
||||
customer: Customer = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Update current customer profile.
|
||||
|
||||
Allows updating profile fields like name, phone, marketing consent, etc.
|
||||
Email changes require the new email to be unique within the vendor.
|
||||
|
||||
Request Body:
|
||||
- email: New email address (optional)
|
||||
- first_name: First name (optional)
|
||||
- last_name: Last name (optional)
|
||||
- phone: Phone number (optional)
|
||||
- marketing_consent: Marketing consent (optional)
|
||||
- preferred_language: Preferred language (optional)
|
||||
"""
|
||||
logger.debug(
|
||||
f"[SHOP_API] update_profile for customer {customer.id}",
|
||||
extra={
|
||||
"customer_id": customer.id,
|
||||
"email": customer.email,
|
||||
"update_fields": [k for k, v in update_data.model_dump().items() if v is not None],
|
||||
},
|
||||
)
|
||||
|
||||
# If email is being changed, check uniqueness within vendor
|
||||
if update_data.email and update_data.email != customer.email:
|
||||
existing = (
|
||||
db.query(Customer)
|
||||
.filter(
|
||||
Customer.vendor_id == customer.vendor_id,
|
||||
Customer.email == update_data.email,
|
||||
Customer.id != customer.id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise ValidationException("Email already in use")
|
||||
|
||||
# Update only provided fields
|
||||
update_dict = update_data.model_dump(exclude_unset=True)
|
||||
for field, value in update_dict.items():
|
||||
if value is not None:
|
||||
setattr(customer, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(customer)
|
||||
|
||||
logger.info(
|
||||
f"Customer {customer.id} updated profile",
|
||||
extra={
|
||||
"customer_id": customer.id,
|
||||
"updated_fields": list(update_dict.keys()),
|
||||
},
|
||||
)
|
||||
|
||||
return CustomerResponse.model_validate(customer)
|
||||
|
||||
|
||||
@router.put("/profile/password", response_model=dict)
|
||||
def change_password(
|
||||
password_data: CustomerPasswordChange,
|
||||
customer: Customer = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Change customer password.
|
||||
|
||||
Requires current password verification and matching new password confirmation.
|
||||
|
||||
Request Body:
|
||||
- current_password: Current password
|
||||
- new_password: New password (min 8 chars, must contain letter and digit)
|
||||
- confirm_password: Confirmation of new password
|
||||
"""
|
||||
logger.debug(
|
||||
f"[SHOP_API] change_password for customer {customer.id}",
|
||||
extra={
|
||||
"customer_id": customer.id,
|
||||
"email": customer.email,
|
||||
},
|
||||
)
|
||||
|
||||
# Verify current password
|
||||
if not verify_password(password_data.current_password, customer.hashed_password):
|
||||
raise ValidationException("Current password is incorrect")
|
||||
|
||||
# Verify passwords match
|
||||
if password_data.new_password != password_data.confirm_password:
|
||||
raise ValidationException("New passwords do not match")
|
||||
|
||||
# Check new password is different
|
||||
if password_data.new_password == password_data.current_password:
|
||||
raise ValidationException("New password must be different from current password")
|
||||
|
||||
# Update password
|
||||
customer.hashed_password = get_password_hash(password_data.new_password)
|
||||
db.commit()
|
||||
|
||||
logger.info(
|
||||
f"Customer {customer.id} changed password",
|
||||
extra={
|
||||
"customer_id": customer.id,
|
||||
"email": customer.email,
|
||||
},
|
||||
)
|
||||
|
||||
return {"message": "Password changed successfully"}
|
||||
Reference in New Issue
Block a user