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:
2026-11-19 18:36:27 +02:00
co-authored by Claude Opus 5.5
parent 07c9a0aecf
commit bde125bf09
28 changed files with 1356 additions and 1244 deletions
+86 -33
View File
@@ -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}
+37 -14
View File
@@ -8,11 +8,25 @@ from database import get_db
from models.notes import SiteNote, SiteTodo
from models.user import User
from schemas.notes import NoteCreate, NoteUpdate, NoteOut, TodoCreate, TodoUpdate, TodoOut
from routers.deps import require_manager
from core.access.deps import require
from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter()
USE = Depends(require("notes.use"))
PRIORITIES = ("normal", "high")
def _changed():
broadcast_sync("notes.changed", {})
def _text(body: str | None) -> str:
if not (body or "").strip():
raise XeniaError("validation.missing", field="body")
return body.strip()
@@ -55,7 +69,7 @@ def _todo_out(t: SiteTodo) -> dict:
# ── Notes ─────────────────────────────────────────────────────────────────────
@router.get("/", response_model=List[NoteOut])
def list_notes(db: Session = Depends(get_db), user: User = Depends(require_manager)):
def list_notes(db: Session = Depends(get_db), user: User = USE):
notes = db.query(SiteNote).order_by(
SiteNote.is_pinned.desc(), SiteNote.updated_at.desc()
).all()
@@ -63,42 +77,44 @@ def list_notes(db: Session = Depends(get_db), user: User = Depends(require_manag
@router.post("/", response_model=NoteOut, status_code=status.HTTP_201_CREATED)
def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
note = SiteNote(body=body.body, is_pinned=body.is_pinned, created_by_id=user.id)
def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = USE):
note = SiteNote(body=_text(body.body), is_pinned=body.is_pinned, created_by_id=user.id)
db.add(note)
db.commit()
db.refresh(note)
_changed()
return _note_out(note)
@router.put("/{note_id}", response_model=NoteOut)
def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def update_note(note_id: int, body: NoteUpdate, db: Session = Depends(get_db), user: User = USE):
note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note:
raise XeniaError("note.not_found")
if body.body is not None:
note.body = body.body
note.body = _text(body.body)
if body.is_pinned is not None:
note.is_pinned = body.is_pinned
note.updated_at = utcnow()
db.commit()
db.refresh(note)
_changed()
return _note_out(note)
@router.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_note(note_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def delete_note(note_id: int, db: Session = Depends(get_db), user: User = USE):
note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note:
raise XeniaError("note.not_found")
db.delete(note)
db.commit()
_changed()
# ── Todos ─────────────────────────────────────────────────────────────────────
@router.get("/todos", response_model=List[TodoOut])
def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = USE):
q = db.query(SiteTodo)
if done is not None:
q = q.filter(SiteTodo.is_done == done)
@@ -112,22 +128,27 @@ def list_todos(done: bool = None, db: Session = Depends(get_db), user: User = De
@router.post("/todos", response_model=TodoOut, status_code=status.HTTP_201_CREATED)
def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
todo = SiteTodo(body=body.body, priority=body.priority, created_by_id=user.id)
def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = USE):
if body.priority not in PRIORITIES:
raise XeniaError("validation.choice", field="priority", value=body.priority)
todo = SiteTodo(body=_text(body.body), priority=body.priority, created_by_id=user.id)
db.add(todo)
db.commit()
db.refresh(todo)
_changed()
return _todo_out(todo)
@router.put("/todos/{todo_id}", response_model=TodoOut)
def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), user: User = USE):
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo:
raise XeniaError("todo.not_found")
if body.body is not None:
todo.body = body.body
todo.body = _text(body.body)
if body.priority is not None:
if body.priority not in PRIORITIES:
raise XeniaError("validation.choice", field="priority", value=body.priority)
todo.priority = body.priority
if body.is_done is not None:
todo.is_done = body.is_done
@@ -139,13 +160,15 @@ def update_todo(todo_id: int, body: TodoUpdate, db: Session = Depends(get_db), u
todo.done_by_id = None
db.commit()
db.refresh(todo)
_changed()
return _todo_out(todo)
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def delete_todo(todo_id: int, db: Session = Depends(get_db), user: User = USE):
todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo:
raise XeniaError("todo.not_found")
db.delete(todo)
db.commit()
_changed()
+41 -28
View File
@@ -1,4 +1,13 @@
from core.timeutil import parse_api_datetime
"""Throwaways (module `inventory`; manager page Inventory → Throwaways, plan step 6.13b).
What was thrown away (a product, how many, why: a kitchen mistake, dropped, expired, other)
with its cost at that moment (the product's cost, when it has one) and who logged it, in the
open business day. An entry can be deleted only during the business day it was logged in.
Everything needs `inventory.manage`; changes send `waste.changed`.
"""
from datetime import date
from core.timeutil import parse_api_datetime, venue_day_window
import json
from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session
@@ -9,12 +18,28 @@ from models.waste import WasteLog
from models.product import Product
from models.business_day import BusinessDay
from models.user import User
from schemas.waste import WasteLogCreate, WasteLogOut, VALID_REASONS, REASON_LABELS
from routers.deps import require_manager
from schemas.waste import WasteLogCreate, VALID_REASONS
from core.access.deps import require
from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter()
MANAGE = Depends(require("inventory.manage"))
def _period(q, business_day_id, from_dt, to_dt, date_from, date_to):
"""business_day_id, or `from` / `to` times, or `date_from` / `date_to` venue dates (inclusive)."""
if business_day_id:
return q.filter(WasteLog.business_day_id == business_day_id)
if from_dt and to_dt:
return q.filter(WasteLog.logged_at >= parse_api_datetime(from_dt), WasteLog.logged_at <= parse_api_datetime(to_dt))
if date_from:
q = q.filter(WasteLog.logged_at >= venue_day_window(date_from)[0])
if date_to:
q = q.filter(WasteLog.logged_at < venue_day_window(date_to)[1])
return q
def _effective_cost(product: Product) -> Optional[float]:
"""Return product's current effective cost (breakdown sum or simple), or None."""
@@ -44,7 +69,6 @@ def _waste_out(w: WasteLog) -> dict:
"unit_cost_snapshot": w.unit_cost_snapshot,
"total_cost": w.total_cost,
"reason": w.reason,
"reason_label": REASON_LABELS.get(w.reason, w.reason),
"reason_notes": w.reason_notes,
"logged_by_id": w.logged_by_id,
"logged_by_name": logger_name,
@@ -58,18 +82,12 @@ def list_waste(
business_day_id: Optional[int] = None,
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
date_from: Optional[date] = None,
date_to: Optional[date] = None,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
from datetime import datetime
q = db.query(WasteLog).order_by(WasteLog.logged_at.desc())
if business_day_id:
q = q.filter(WasteLog.business_day_id == business_day_id)
elif from_dt and to_dt:
q = q.filter(
WasteLog.logged_at >= parse_api_datetime(from_dt),
WasteLog.logged_at <= parse_api_datetime(to_dt),
)
q = _period(db.query(WasteLog).order_by(WasteLog.logged_at.desc()), business_day_id, from_dt, to_dt, date_from, date_to)
entries = q.all()
return {"entries": [_waste_out(w) for w in entries]}
@@ -78,7 +96,7 @@ def list_waste(
def log_waste(
body: WasteLogCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
if body.reason not in VALID_REASONS:
raise XeniaError("validation.choice", field='reason', value=body.reason)
@@ -109,6 +127,7 @@ def log_waste(
db.add(entry)
db.commit()
db.refresh(entry)
broadcast_sync("waste.changed", {})
return _waste_out(entry)
@@ -116,7 +135,7 @@ def log_waste(
def delete_waste(
entry_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
entry = db.query(WasteLog).filter(WasteLog.id == entry_id).first()
if not entry:
@@ -129,6 +148,7 @@ def delete_waste(
db.delete(entry)
db.commit()
broadcast_sync("waste.changed", {})
@router.get("/summary")
@@ -136,19 +156,12 @@ def waste_summary(
business_day_id: Optional[int] = None,
from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"),
date_from: Optional[date] = None,
date_to: Optional[date] = None,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = MANAGE,
):
from datetime import datetime
q = db.query(WasteLog)
if business_day_id:
q = q.filter(WasteLog.business_day_id == business_day_id)
elif from_dt and to_dt:
q = q.filter(
WasteLog.logged_at >= parse_api_datetime(from_dt),
WasteLog.logged_at <= parse_api_datetime(to_dt),
)
entries = q.all()
entries = _period(db.query(WasteLog), business_day_id, from_dt, to_dt, date_from, date_to).all()
total_items = len(entries)
total_cost = round(sum(e.total_cost for e in entries if e.total_cost is not None), 2)
@@ -159,7 +172,7 @@ def waste_summary(
for e in entries:
r = e.reason
if r not in by_reason:
by_reason[r] = {"reason": r, "label": REASON_LABELS.get(r, r), "count": 0, "total_cost": 0.0}
by_reason[r] = {"reason": r, "count": 0, "total_cost": 0.0}
by_reason[r]["count"] += 1
by_reason[r]["total_cost"] += e.total_cost or 0.0