feat(manager): customers, throwaways, stock and notes on v2 (platform-v2 step 6.13b)
- CRM -> Customers: search ignoring case and Greek accents (and part of the phone), visits / spent / last visit, the card (contact, notes, open tab, every visit with what was on a tab), new/edit/remove - Inventory -> Throwaways: log (product, quantity with a comma, reason, note) with its cost, today's list (delete today only), a period's totals by reason and product, every entry; Inventory -> Stock: an honest 'not available yet' - Notes: notes (pinned first, edit in place) and to-dos (urgent first, done folded away, who did it kept) - backend: crm.manage / inventory.manage / notes.use (the customer search also with the dashboard key, for orders); spending counted by services/sales.py (refunds off, tab lines in); null clears a field; names/notes not blank, priorities checked; waste ?date_from=&date_to= venue dates; the Greek reason labels left the API; live customers.changed / waste.changed / notes.changed - the overview's notes card needs notes.use and refreshes live - tests: test_customers_waste_notes.py (4), crm.test.mjs (3), e2e manager.mjs (customers, throwaways, notes, stock, Greek) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,12 @@
|
||||
"""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
|
||||
@@ -7,22 +16,47 @@ 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_any
|
||||
from routers.deps import require_manager, get_current_user
|
||||
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 _customer_out(c: Customer, db: Session) -> dict:
|
||||
orders = db.query(Order).filter(
|
||||
Order.customer_id == c.id,
|
||||
Order.status.in_(["closed", "paid"]),
|
||||
).all()
|
||||
total_spent = sum(
|
||||
sum(i.unit_price * i.quantity for i in o.items if i.status in ("active", "paid"))
|
||||
for o in orders
|
||||
)
|
||||
|
||||
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,
|
||||
@@ -33,8 +67,9 @@ def _customer_out(c: Customer, db: Session) -> dict:
|
||||
"is_active": c.is_active,
|
||||
"created_at": c.created_at,
|
||||
"created_by_id": c.created_by_id,
|
||||
"visit_count": len(orders),
|
||||
"total_spent": round(total_spent, 2),
|
||||
"visit_count": visits,
|
||||
"total_spent": round(spent, 2),
|
||||
"last_visit": last,
|
||||
}
|
||||
|
||||
|
||||
@@ -43,28 +78,34 @@ def list_customers(
|
||||
search: Optional[str] = None,
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(require_manager),
|
||||
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)
|
||||
if search:
|
||||
term = f"%{search}%"
|
||||
q = q.filter(
|
||||
Customer.name.ilike(term) |
|
||||
Customer.nickname.ilike(term) |
|
||||
Customer.phone.ilike(term)
|
||||
)
|
||||
customers = q.order_by(Customer.name).all()
|
||||
return [_customer_out(c, db) for c in customers]
|
||||
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 = Depends(require_manager)):
|
||||
customer = Customer(**body.model_dump(), created_by_id=user.id)
|
||||
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)
|
||||
|
||||
|
||||
@@ -79,7 +120,7 @@ def lookup_customer(phone: str = Query(..., max_length=40), db: Session = Depend
|
||||
|
||||
|
||||
@router.get("/{customer_id}", response_model=CustomerOut)
|
||||
def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
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")
|
||||
@@ -87,43 +128,55 @@ def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = D
|
||||
|
||||
|
||||
@router.put("/{customer_id}", response_model=CustomerOut)
|
||||
def update_customer(customer_id: int, body: CustomerUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
|
||||
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")
|
||||
for field, value in body.model_dump(exclude_none=True).items():
|
||||
setattr(c, field, value)
|
||||
# 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 = Depends(require_manager)):
|
||||
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 = Depends(require_manager)):
|
||||
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:
|
||||
total = sum(i.unit_price * i.quantity for i in o.items if i.status in ("active", "paid"))
|
||||
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(total, 2),
|
||||
"item_count": sum(i.quantity for i in o.items if i.status in ("active", "paid")),
|
||||
"total": round(tot.takings, 2),
|
||||
"on_tab": round(tot.on_tab, 2),
|
||||
"item_count": tot.units,
|
||||
})
|
||||
return {"orders": result}
|
||||
|
||||
Reference in New Issue
Block a user