"""Customers (module `crm`; manager page in plan step 6.13b). Writing and a customer's details need `crm.manage`. The list / search also works with the dashboard key (attaching a customer to an order, 6.9). Spending and visits are counted by services/sales.py (refunds off, lines on a tab are sold: 6.13c). Search ignores case and Greek accents. Changes send `customers.changed`. """ import unicodedata from fastapi import APIRouter, Depends, status, Query from sqlalchemy.orm import Session from typing import List, Optional from database import get_db from models.customers import Customer from models.order import Order, OrderItem from models.user import User from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest from core.access.deps import require, require_any from core.errors import XeniaError from services.ws_bus import broadcast_sync router = APIRouter() MANAGE = Depends(require("crm.manage")) def _changed(): broadcast_sync("customers.changed", {}) def _fold(text: str | None) -> str: """Lower case without accents: "Γιώργος" and "γιωργος" match.""" t = unicodedata.normalize("NFD", (text or "").casefold()) return "".join(c for c in t if not unicodedata.combining(c)) def _check(fields: dict): if "name" in fields and not (fields["name"] or "").strip(): raise XeniaError("validation.missing", field="name") def _stats(db: Session, customer_ids) -> dict: """{customer_id: (visits, spent, last_visit)} from their finished orders, counted by services/sales.py.""" from services import sales ids = list(customer_ids) if not ids: return {} orders = db.query(Order).filter(Order.customer_id.in_(ids), Order.status.in_(["closed", "paid"])).all() totals = sales.order_totals(db, orders) out: dict = {} for o in orders: v, s, last = out.get(o.customer_id, (0, 0.0, None)) out[o.customer_id] = (v + 1, s + totals[o.id].takings, max(filter(None, (last, o.opened_at)), default=None)) return out def _customer_out(c: Customer, db: Session, stats: dict | None = None) -> dict: visits, spent, last = (stats if stats is not None else _stats(db, [c.id])).get(c.id, (0, 0.0, None)) return { "id": c.id, "name": c.name, "nickname": c.nickname, "phone": c.phone, "email": c.email, "notes": c.notes, "is_active": c.is_active, "created_at": c.created_at, "created_by_id": c.created_by_id, "visit_count": visits, "total_spent": round(spent, 2), "last_visit": last, } @router.get("/", response_model=List[CustomerOut]) def list_customers( search: Optional[str] = None, include_inactive: bool = False, db: Session = Depends(get_db), user: User = Depends(require_any("crm.manage", "core.dashboard.access")), ): q = db.query(Customer) if not include_inactive: q = q.filter(Customer.is_active == True) customers = q.order_by(Customer.name).all() if search: words = _fold(search).split() digits = "".join(ch for ch in search if ch.isdigit()) def hit(c): text = _fold(f"{c.name} {c.nickname or ''} {c.email or ''} {c.notes or ''}") phone = "".join(ch for ch in (c.phone or "") if ch.isdigit()) return all(w in text for w in words) or (len(digits) >= 3 and digits in phone) customers = [c for c in customers if hit(c)] stats = _stats(db, [c.id for c in customers]) return [_customer_out(c, db, stats) for c in customers] @router.post("/", response_model=CustomerOut, status_code=status.HTTP_201_CREATED) def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: User = MANAGE): fields = body.model_dump() _check(fields) fields["name"] = fields["name"].strip() customer = Customer(**fields, created_by_id=user.id) db.add(customer) db.commit() db.refresh(customer) _changed() return _customer_out(customer, db) @router.get("/lookup") def lookup_customer(phone: str = Query(..., max_length=40), db: Session = Depends(get_db), user: User = Depends(require_any("caller_id.use", "core.dashboard.access"))): """Who has this phone number (caller ID, plan step 3.5): matched on the server with the Greek number rules (services/caller_id.py) → {customer: card | null}.""" from services import caller_id c = caller_id.match(db, phone) return {"customer": caller_id.card(db, c) if c else None} @router.get("/{customer_id}", response_model=CustomerOut) def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE): c = db.query(Customer).filter(Customer.id == customer_id).first() if not c: raise XeniaError("customer.not_found") return _customer_out(c, db) @router.put("/{customer_id}", response_model=CustomerOut) def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depends(get_db), user: User = MANAGE): c = db.query(Customer).filter(Customer.id == customer_id).first() if not c: raise XeniaError("customer.not_found") # Fields sent as null are cleared (nickname, phone…); name and is_active only change when given fields = body.model_dump(exclude_unset=True) for k in ("name", "is_active"): if fields.get(k) is None: fields.pop(k, None) _check(fields) for field, value in fields.items(): setattr(c, field, value.strip() if field == "name" else value) db.commit() db.refresh(c) _changed() return _customer_out(c, db) @router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT) def delete_customer(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE): c = db.query(Customer).filter(Customer.id == customer_id).first() if not c: raise XeniaError("customer.not_found") c.is_active = False db.commit() _changed() @router.get("/{customer_id}/orders") def customer_orders(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE): c = db.query(Customer).filter(Customer.id == customer_id).first() if not c: raise XeniaError("customer.not_found") from models.table import Table from services import sales orders = db.query(Order).filter(Order.customer_id == customer_id).order_by(Order.opened_at.desc()).all() tables_map = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} totals = sales.order_totals(db, orders) result = [] for o in orders: tot = totals[o.id] result.append({ "id": o.id, "table_name": tables_map.get(o.table_id) if o.table_id else None, "order_type": o.order_type, "opened_at": o.opened_at, "status": o.status, "total": round(tot.takings, 2), "on_tab": round(tot.on_tab, 2), "item_count": tot.units, }) return {"orders": result}