Files
orion/app/modules/loyalty/routes/pages/merchant.py
Samir Boulahtit 6276e9e3ac
Some checks failed
CI / ruff (push) Successful in 47s
CI / validate (push) Has been cancelled
CI / dependency-scanning (push) Has been cancelled
CI / docs (push) Has been cancelled
CI / deploy (push) Has been cancelled
CI / pytest (push) Has been cancelled
feat(loyalty): pair POS terminal devices with one-time setup QR
Adds the backend half of the Android tablet rollout. Merchants can
pair tablets to specific stores from /merchants/loyalty/devices (or
admins can pair on behalf from the merchant detail page). Each
pairing issues a long-lived JWT shown ONCE in the response with a
server-rendered QR PNG containing {api_url, store_code, auth_token} —
the tablet scans it on first boot and persists the three fields.

The store API (/api/v1/store/loyalty/*) now accepts these device JWTs
alongside user JWTs. Revoking a device row immediately rejects its
token (401 TERMINAL_DEVICE_REVOKED). Tokens expire after 1 year;
re-pair to renew.

- Migration loyalty_010 + TerminalDevice model
- create_device_token / verify_device_token JWT helpers
- 5 endpoints x 2 portals (merchant + admin on-behalf)
- Bearer-auth wiring in app/api/deps.py
- Pages, shared list partial with one-time pairing-QR modal,
  Alpine.js factories
- Locale strings (en authoritative; fr/de/lb seeded with EN copy
  for translation)
- 6 integration tests covering pair, list, revoke, idempotency,
  cross-merchant rejection, store-API auth via device JWT

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:18:57 +02:00

307 lines
9.1 KiB
Python

# app/modules/loyalty/routes/pages/merchant.py
"""
Loyalty Merchant Page Routes (HTML rendering).
Merchant portal pages for:
- Loyalty program (read-only view)
- Loyalty program edit
- Loyalty analytics (aggregate stats across all stores)
Authentication: merchant_token cookie or Authorization header.
Auto-discovered by the route system (merchant.py in routes/pages/ triggers
registration under /merchants/loyalty/*).
"""
import logging
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session
from app.api.deps import (
get_current_merchant_from_cookie_or_header,
get_merchant_for_current_user_page,
)
from app.core.database import get_db
from app.modules.core.utils.page_context import get_context_for_frontend
from app.modules.enums import FrontendType
from app.modules.loyalty.services import program_service
from app.modules.tenancy.models import Merchant
from app.modules.tenancy.schemas.auth import UserContext
from app.templates_config import templates
logger = logging.getLogger(__name__)
ROUTE_CONFIG = {
"prefix": "/loyalty",
}
router = APIRouter()
# ============================================================================
# Helper
# ============================================================================
def _get_merchant_context(
request: Request,
db: Session,
current_user: UserContext,
**extra_context,
) -> dict:
"""Build template context for merchant loyalty pages."""
return get_context_for_frontend(
FrontendType.MERCHANT,
request,
db,
user=current_user,
**extra_context,
)
# ============================================================================
# LOYALTY PROGRAM (Read-only view)
# ============================================================================
@router.get("/program", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_program(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""
Render merchant loyalty program view page.
Shows read-only program configuration with link to edit.
"""
merchant_id = merchant.id
stats = {}
try:
stats = program_service.get_merchant_stats(db, merchant_id)
except Exception:
logger.warning(
f"Failed to load loyalty stats for merchant {merchant_id}",
exc_info=True,
)
context = _get_merchant_context(
request,
db,
current_user,
loyalty_stats=stats,
merchant_id=merchant_id,
)
return templates.TemplateResponse(
"loyalty/merchant/program.html",
context,
)
# ============================================================================
# LOYALTY PROGRAM EDIT
# ============================================================================
@router.get("/program/edit", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_program_edit(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""
Render merchant loyalty program edit page.
Allows merchant to create, configure, and manage their loyalty program.
"""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/program-edit.html",
context,
)
# ============================================================================
# LOYALTY ANALYTICS
# ============================================================================
@router.get("/analytics", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_analytics(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""
Render merchant loyalty analytics page.
Stats are loaded client-side via JS fetch.
"""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/analytics.html",
context,
)
# ============================================================================
# LOYALTY CARDS
# ============================================================================
@router.get("/cards", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_cards(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""Render merchant loyalty cards list page."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/cards.html",
context,
)
@router.get("/cards/{card_id}", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_card_detail(
request: Request,
card_id: int,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""Render merchant loyalty card detail page."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
card_id=card_id,
)
return templates.TemplateResponse(
"loyalty/merchant/card-detail.html",
context,
)
# ============================================================================
# LOYALTY TRANSACTIONS
# ============================================================================
@router.get("/transactions", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_transactions(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""Render merchant loyalty transactions page."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/transactions.html",
context,
)
# ============================================================================
# LOYALTY STAFF PINS
# ============================================================================
@router.get("/pins", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_pins(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""Render merchant loyalty staff PINs page."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/pins.html",
context,
)
# ============================================================================
# LOYALTY SETTINGS
# ============================================================================
@router.get("/settings", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_settings(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""Render merchant loyalty settings page (read-only)."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/settings.html",
context,
)
# ============================================================================
# TERMINAL DEVICES (POS tablet pairing)
# ============================================================================
@router.get("/devices", response_class=HTMLResponse, include_in_schema=False)
async def merchant_loyalty_devices(
request: Request,
current_user: UserContext = Depends(get_current_merchant_from_cookie_or_header),
merchant: Merchant = Depends(get_merchant_for_current_user_page),
db: Session = Depends(get_db),
):
"""List + pair POS terminal devices for the merchant."""
context = _get_merchant_context(
request,
db,
current_user,
merchant_id=merchant.id,
)
return templates.TemplateResponse(
"loyalty/merchant/devices.html",
context,
)