diff --git a/local_backend/routers/customers.py b/local_backend/routers/customers.py
index 6226e10..76d20ac 100644
--- a/local_backend/routers/customers.py
+++ b/local_backend/routers/customers.py
@@ -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}
diff --git a/local_backend/routers/notes.py b/local_backend/routers/notes.py
index dd83da3..7c2bb9a 100644
--- a/local_backend/routers/notes.py
+++ b/local_backend/routers/notes.py
@@ -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()
diff --git a/local_backend/routers/waste.py b/local_backend/routers/waste.py
index 47e5821..8c5a7e8 100644
--- a/local_backend/routers/waste.py
+++ b/local_backend/routers/waste.py
@@ -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
diff --git a/local_backend/schemas/customers.py b/local_backend/schemas/customers.py
index 2ec6bb3..95ef386 100644
--- a/local_backend/schemas/customers.py
+++ b/local_backend/schemas/customers.py
@@ -33,6 +33,7 @@ class CustomerOut(BaseModel):
# computed stats (set by router)
visit_count: int = 0
total_spent: float = 0.0
+ last_visit: Optional[datetime] = None
model_config = {"from_attributes": True}
diff --git a/local_backend/schemas/waste.py b/local_backend/schemas/waste.py
index a290406..754a88c 100644
--- a/local_backend/schemas/waste.py
+++ b/local_backend/schemas/waste.py
@@ -4,12 +4,7 @@ from datetime import datetime
VALID_REASONS = {"kitchen_error", "dropped", "expired", "other"}
-REASON_LABELS = {
- "kitchen_error": "Λάθος κουζίνας",
- "dropped": "Έπεσε",
- "expired": "Έληξε",
- "other": "Άλλο",
-}
+# Texts: manager `waste.reasons.*` (6.13b; the Greek labels that were here are gone)
class WasteLogCreate(BaseModel):
@@ -27,7 +22,6 @@ class WasteLogOut(BaseModel):
unit_cost_snapshot: Optional[float] = None
total_cost: Optional[float] = None
reason: str
- reason_label: Optional[str] = None
reason_notes: Optional[str] = None
logged_by_id: int
logged_by_name: Optional[str] = None
diff --git a/local_backend/tests/test_customers_waste_notes.py b/local_backend/tests/test_customers_waste_notes.py
new file mode 100644
index 0000000..01fe993
--- /dev/null
+++ b/local_backend/tests/test_customers_waste_notes.py
@@ -0,0 +1,118 @@
+"""Customers, throwaways and notes (plan step 6.13b): each needs its module's own key (crm.manage,
+inventory.manage, notes.use; the customer search also with the dashboard key, for orders), a
+customer's spending is counted by services/sales.py, search ignores case and Greek accents, and
+every change tells open pages (live events)."""
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+
+@pytest.fixture
+def events(monkeypatch):
+ sent = []
+ import routers.customers as c
+ import routers.notes as n
+ import routers.waste as w
+ for mod in (c, n, w):
+ monkeypatch.setattr(mod, "broadcast_sync", lambda t, d=None, **kw: sent.append(t))
+ return sent
+
+
+def test_each_needs_its_own_key(client, make_user, login):
+ dash = login(make_user(role="store_manager", keys=("core.dashboard.access",)))
+ assert client.get("/api/customers/", headers=dash).status_code == 200 # attaching a customer to an order
+ assert client.post("/api/customers/", headers=dash, json={"name": "X"}).status_code == 403
+ assert client.get("/api/waste/", headers=dash).status_code == 403
+ assert client.get("/api/notes/", headers=dash).status_code == 403
+ assert client.get("/api/notes/todos", headers=dash).status_code == 403
+
+
+def test_a_customer_found_without_accents_and_their_spending(client, db, make_user, login, events):
+ from models.order import Order, OrderItem
+ from models.product import Category, Product
+ from models.refund import Refund, RefundItem
+ h = login(make_user(role="owner"))
+ r = client.post("/api/customers/", headers=h, json={"name": " Γιώργος Παπαδόπουλος ", "nickname": "Ο μεγάλος", "phone": "+30 697 111 2222"})
+ assert r.status_code == 201 and r.json()["name"] == "Γιώργος Παπαδόπουλος"
+ cid = r.json()["id"]
+ client.post("/api/customers/", headers=h, json={"name": "Anna"})
+ find = lambda q: [c["name"] for c in client.get("/api/customers/", headers=h, params={"search": q}).json()] # noqa: E731
+ assert find("γιωργος") == ["Γιώργος Παπαδόπουλος"]
+ assert find("ΜΕΓΑΛΟΣ") == ["Γιώργος Παπαδόπουλος"]
+ assert find("6971112222") == ["Γιώργος Παπαδόπουλος"] and find("111 2222") == ["Γιώργος Παπαδόπουλος"]
+ assert find("nobody") == []
+ assert "validation.missing" in client.post("/api/customers/", headers=h, json={"name": " "}).text
+ # a finished order: 2 × 5 paid, 1 refunded; a line of 4 on a tab (sold, 6.13c); a cancelled line
+ u = make_user(role="waiter")
+ cat = Category(name="Food")
+ db.add(cat)
+ db.flush()
+ p = Product(name="Pita", base_price=5.0, primary_category_id=cat.id)
+ db.add(p)
+ db.flush()
+ o = Order(opened_by=u.id, order_type="takeaway", customer_id=cid, status="closed", opened_at=datetime(2026, 11, 18, 19, tzinfo=timezone.utc))
+ db.add(o)
+ db.flush()
+ paid = OrderItem(order_id=o.id, product_id=p.id, added_by=u.id, quantity=2, unit_price=5.0, status="paid", payment_method="cash")
+ db.add_all([paid, OrderItem(order_id=o.id, product_id=p.id, added_by=u.id, quantity=1, unit_price=4.0, status="tabbed"),
+ OrderItem(order_id=o.id, product_id=p.id, added_by=u.id, quantity=1, unit_price=5.0, status="cancelled")])
+ db.flush()
+ ref = Refund(order_id=o.id, refunded_by=u.id, method="cash", amount=5.0)
+ db.add(ref)
+ db.flush()
+ db.add(RefundItem(refund_id=ref.id, order_item_id=paid.id, quantity=1, amount=5.0))
+ db.commit()
+ c = client.get(f"/api/customers/{cid}", headers=h).json()
+ assert (c["visit_count"], c["total_spent"]) == (1, 9.0) and c["last_visit"] # 10 − 5 refunded + 4 on the tab
+ visits = client.get(f"/api/customers/{cid}/orders", headers=h).json()["orders"]
+ assert (visits[0]["total"], visits[0]["on_tab"], visits[0]["item_count"]) == (9.0, 4.0, 2)
+ # a field sent empty is cleared; the name stays
+ r = client.put(f"/api/customers/{cid}", headers=h, json={"nickname": None, "notes": "nut allergy"})
+ assert r.json()["nickname"] is None and r.json()["notes"] == "nut allergy" and r.json()["name"] == "Γιώργος Παπαδόπουλος"
+ assert client.delete(f"/api/customers/{cid}", headers=h).status_code == 204
+ assert events.count("customers.changed") == 4 # 2 added, 1 edited, 1 removed
+
+
+def test_throwaways_cost_period_and_deleting(client, db, make_user, login, events):
+ from core.timeutil import business_date_of, utcnow
+ from models.business_day import BusinessDay
+ from models.product import Category, Product
+ from models.waste import WasteLog
+ owner = make_user(role="owner")
+ h = login(owner)
+ cat = Category(name="Food")
+ db.add(cat)
+ db.flush()
+ p = Product(name="Souvlaki", base_price=3.0, primary_category_id=cat.id, cost_simple=1.25)
+ db.add(p)
+ day = BusinessDay(status="open", opened_by_id=owner.id, opened_at=utcnow() - timedelta(hours=1), business_date=business_date_of(utcnow()))
+ db.add(day)
+ db.commit()
+ r = client.post("/api/waste/", headers=h, json={"product_id": p.id, "quantity": 2, "reason": "dropped", "reason_notes": "tray"})
+ assert r.status_code == 201, r.text
+ w = r.json()
+ assert (w["unit_cost_snapshot"], w["total_cost"], w["business_day_id"]) == (1.25, 2.5, day.id) and "reason_label" not in w
+ assert "validation.choice" in client.post("/api/waste/", headers=h, json={"product_id": p.id, "quantity": 1, "reason": "stolen"}).text
+ # an old entry (another day): listed by venue date, can't be deleted
+ old = WasteLog(product_id=p.id, quantity=1, reason="expired", logged_by_id=owner.id, logged_at=datetime(2026, 11, 1, 22, 30, tzinfo=timezone.utc))
+ db.add(old)
+ db.commit()
+ assert [e["id"] for e in client.get("/api/waste/", headers=h, params={"date_from": "2026-11-02", "date_to": "2026-11-02"}).json()["entries"]] == [old.id] # 00:30 in Athens
+ assert "waste.not_today" in client.delete(f"/api/waste/{old.id}", headers=h).text
+ s = client.get("/api/waste/summary", headers=h, params={"business_day_id": day.id}).json()
+ assert (s["total_items"], s["total_cost"], s["by_reason"][0]) == (1, 2.5, {"reason": "dropped", "count": 1, "total_cost": 2.5})
+ assert client.delete(f"/api/waste/{w['id']}", headers=h).status_code == 204
+ assert events.count("waste.changed") == 2
+
+
+def test_notes_and_todos(client, make_user, login, events):
+ h = login(make_user(role="owner"))
+ n = client.post("/api/notes/", headers=h, json={"body": " Fridge 2 is noisy ", "is_pinned": False}).json()
+ assert n["body"] == "Fridge 2 is noisy"
+ assert "validation.missing" in client.post("/api/notes/", headers=h, json={"body": " "}).text
+ assert client.put(f"/api/notes/{n['id']}", headers=h, json={"is_pinned": True}).json()["is_pinned"] is True
+ t = client.post("/api/notes/todos", headers=h, json={"body": "Call the plumber", "priority": "high"}).json()
+ assert "validation.choice" in client.post("/api/notes/todos", headers=h, json={"body": "x", "priority": "urgent"}).text
+ done = client.put(f"/api/notes/todos/{t['id']}", headers=h, json={"is_done": True}).json()
+ assert done["is_done"] and done["done_by_name"]
+ assert events.count("notes.changed") == 4 # the note, its pin, the to-do, done
diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx
index 521fb29..75dd35a 100644
--- a/manager_dashboard/src/App.jsx
+++ b/manager_dashboard/src/App.jsx
@@ -22,7 +22,7 @@ import QrCodesPage from './pages/online/QrCodesPage'
// CRM
import ContactsPage from './pages/finance/ContactsPage'
-import CustomersPage from './pages/crm/CustomersPage'
+import CustomersPage from './pages/customers/CustomersPage'
// Financials
import ExpensesPage from './pages/finance/ExpensesPage'
@@ -60,7 +60,7 @@ import LicensePage from './pages/platform/LicensePage'
import DevicesPage from './pages/platform/DevicesPage'
import PhonePage from './pages/PhonePage'
import SettingsPage from './pages/Settings/SettingsPage'
-import NotesPage from './pages/NotesPage'
+import NotesPage from './pages/notes/NotesPage'
// Texts for the shared parts (approval dialog, "feature off" screens, component labels).
// The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6).
diff --git a/manager_dashboard/src/pages/CustomersPage.jsx b/manager_dashboard/src/pages/CustomersPage.jsx
deleted file mode 100644
index 2ed4c85..0000000
--- a/manager_dashboard/src/pages/CustomersPage.jsx
+++ /dev/null
@@ -1,349 +0,0 @@
-import { useState } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-function fmt(n) {
- if (n == null) return '—'
- return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
-}
-
-function fmtDate(iso) {
- if (!iso) return '—'
- return new Date(iso).toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit', year: 'numeric' })
-}
-
-function fmtDateTime(iso) {
- if (!iso) return '—'
- return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
-}
-
-const ORDER_STATUS_LABELS = {
- closed: 'Κλειστή', paid: 'Πληρωμένη', open: 'Ανοιχτή',
- partially_paid: 'Μερική πλ.', cancelled: 'Ακυρωμένη',
-}
-const ORDER_STATUS_COLORS = {
- closed: '#6b7280', paid: '#16a34a', open: '#3b82f6',
- partially_paid: '#d97706', cancelled: '#ef4444',
-}
-
-const inputStyle = {
- width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
- borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
-}
-
-// ── Customer modal (create / edit) ───────────────────────────────────────────
-
-const EMPTY_FORM = { name: '', nickname: '', phone: '', email: '', notes: '' }
-
-function CustomerModal({ initial, onClose, onSave, isPending }) {
- const [form, setForm] = useState(initial ?? EMPTY_FORM)
- const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
- const isNew = !initial?.id
-
- return (
-
-
-
-
{isNew ? 'Νέος Πελάτης' : 'Επεξεργασία Πελάτη'}
-
-
-
-
-
- f('name', e.target.value)} autoFocus placeholder="π.χ. Γιώργος Παπαδόπουλος" />
-
-
-
-
- f('email', e.target.value)} placeholder="email@example.com" />
-
-
-
-
-
-
-
-
-
-
-
- )
-}
-
-// ── Customer detail panel ─────────────────────────────────────────────────────
-
-function CustomerDetail({ customer, onEdit, onClose }) {
- const { data, isLoading } = useQuery({
- queryKey: ['customer-orders', customer.id],
- queryFn: () => client.get(`/api/customers/${customer.id}/orders`).then(r => r.data),
- staleTime: 30_000,
- })
-
- const { data: tabsData = [] } = useQuery({
- queryKey: ['customer-tabs', customer.id],
- queryFn: () => client.get(`/api/tabs/customer/${customer.id}`).then(r => r.data),
- staleTime: 30_000,
- })
-
- const openTab = tabsData.find(t => t.status === 'open')
- const orders = data?.orders || []
-
- return (
-
- {/* Header */}
-
-
-
{customer.name}
- {customer.nickname &&
«{customer.nickname}»
}
-
-
-
-
-
-
-
- {/* Stats row */}
-
- {[
- { label: 'Επισκέψεις', value: customer.visit_count },
- { label: 'Σύνολο εξόδων', value: fmt(customer.total_spent) },
- { label: 'Μέσος λογ.', value: customer.visit_count > 0 ? fmt(customer.total_spent / customer.visit_count) : '—' },
- ].map(s => (
-
-
{s.label}
-
{s.value}
-
- ))}
-
-
- {/* Open tab banner */}
- {openTab && (
-
-
-
-
Ανοιχτή Καρτέλα
-
- {openTab.entries.length} χρεώσεις · πληρωμένο {fmt(openTab.total_paid)}
-
-
-
{fmt(openTab.balance)}
-
-
- )}
-
- {/* Contact info */}
-
- {(customer.phone || customer.email || customer.notes) ? (
-
- {customer.phone &&
📞{customer.phone}
}
- {customer.email &&
✉{customer.email}
}
- {customer.notes && (
-
- 📝 {customer.notes}
-
- )}
-
- ) : (
-
Δεν υπάρχουν στοιχεία επικοινωνίας.
- )}
-
-
- {/* Visit history */}
-
-
Ιστορικό Επισκέψεων
- {isLoading &&
Φόρτωση…
}
- {!isLoading && orders.length === 0 && (
-
Δεν υπάρχουν επισκέψεις ακόμα.
- )}
-
- {orders.map(o => (
-
-
-
- {o.table_name ? `Τραπέζι ${o.table_name}` : 'Χωρίς τραπέζι'}
- {' '}
-
- {ORDER_STATUS_LABELS[o.status] || o.status}
-
-
-
- {fmtDateTime(o.opened_at)} · {o.item_count} αντικ.
-
-
-
{fmt(o.total)}
-
- ))}
-
-
-
- )
-}
-
-// ── Main page ─────────────────────────────────────────────────────────────────
-
-export default function CustomersPage() {
- const qc = useQueryClient()
- const [search, setSearch] = useState('')
- const [selected, setSelected] = useState(null) // customer being viewed
- const [modal, setModal] = useState(null) // null | { customer } | { customer: null }
-
- const { data: customers = [], isLoading } = useQuery({
- queryKey: ['customers', search],
- queryFn: () => client.get('/api/customers/', { params: search ? { search } : {} }).then(r => r.data),
- staleTime: 30_000,
- })
-
- const save = useMutation({
- mutationFn: ({ form, id }) => id
- ? client.put(`/api/customers/${id}`, form)
- : client.post('/api/customers/', form),
- onSuccess: (res) => {
- qc.invalidateQueries({ queryKey: ['customers'] })
- if (selected && res.data?.id === selected.id) {
- setSelected(res.data)
- }
- setModal(null)
- toast.success('Αποθηκεύτηκε')
- },
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const deactivate = useMutation({
- mutationFn: (id) => client.delete(`/api/customers/${id}`),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['customers'] })
- if (selected?.id) setSelected(null)
- toast.success('Αποενεργοποιήθηκε')
- },
- onError: () => toast.error('Σφάλμα'),
- })
-
- const activeCount = customers.length
-
- return (
-
- {/* Left: list */}
-
- {/* Header */}
-
-
-
-
{activeCount} ενεργοί πελάτες
-
-
-
-
setSearch(e.target.value)}
- placeholder="Αναζήτηση με όνομα, παρατσούκλι ή τηλέφωνο…"
- style={{ ...inputStyle, fontSize: 13 }}
- />
-
-
- {/* List */}
-
- {isLoading &&
Φόρτωση…
}
- {!isLoading && customers.length === 0 && (
-
- {search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν πελάτες ακόμα.'}
-
- )}
- {customers.map(c => (
-
- ))}
-
-
-
- {/* Right: detail panel */}
- {selected && (
-
- setModal({ customer: selected })}
- onClose={() => setSelected(null)}
- />
-
- )}
-
- {modal && (
-
setModal(null)}
- isPending={save.isPending}
- onSave={(form) => save.mutate({
- form: {
- name: form.name,
- nickname: form.nickname || null,
- phone: form.phone || null,
- email: form.email || null,
- notes: form.notes || null,
- },
- id: modal.customer?.id,
- })}
- />
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/NotesPage.jsx b/manager_dashboard/src/pages/NotesPage.jsx
deleted file mode 100644
index 4cadfd7..0000000
--- a/manager_dashboard/src/pages/NotesPage.jsx
+++ /dev/null
@@ -1,500 +0,0 @@
-import { useState, useRef, useEffect } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-
-// ── helpers ───────────────────────────────────────────────────────────────────
-
-function fmtDate(iso) {
- if (!iso) return ''
- const d = new Date(iso)
- const now = new Date()
- const diffMs = now - d
- const diffMins = Math.floor(diffMs / 60000)
- if (diffMins < 1) return 'μόλις τώρα'
- if (diffMins < 60) return `${diffMins}λ πριν`
- const diffH = Math.floor(diffMins / 60)
- if (diffH < 24) return `${diffH}ω πριν`
- return d.toLocaleDateString('el-GR', { day: '2-digit', month: '2-digit' })
-}
-
-// ── Notes column ──────────────────────────────────────────────────────────────
-
-function NoteCard({ note, onSave, onDelete, onTogglePin }) {
- const [editing, setEditing] = useState(false)
- const [draft, setDraft] = useState(note.body)
- const taRef = useRef(null)
-
- useEffect(() => {
- if (editing && taRef.current) {
- taRef.current.focus()
- taRef.current.selectionStart = taRef.current.value.length
- }
- }, [editing])
-
- function handleBlur() {
- if (draft.trim() === note.body) { setEditing(false); return }
- if (!draft.trim()) { setEditing(false); setDraft(note.body); return }
- onSave(note.id, draft.trim())
- setEditing(false)
- }
-
- function handleKeyDown(e) {
- if (e.key === 'Escape') { setEditing(false); setDraft(note.body) }
- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleBlur()
- }
-
- return (
-
- )
-}
-
-function NotesColumn({ notes, onAdd, onSave, onDelete, onTogglePin }) {
- const [newBody, setNewBody] = useState('')
- const [newPinned, setNewPinned] = useState(false)
-
- function submit() {
- if (!newBody.trim()) return
- onAdd(newBody.trim(), newPinned)
- setNewBody('')
- setNewPinned(false)
- }
-
- function onKeyDown(e) {
- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit()
- }
-
- const pinned = notes.filter(n => n.is_pinned)
- const rest = notes.filter(n => !n.is_pinned)
-
- return (
-
- {/* New note form */}
-
-
- {/* Notes list */}
-
- {pinned.length > 0 && (
- <>
-
📌 Καρφιτσωμένες
- {pinned.map(n => (
-
- ))}
- >
- )}
- {rest.length > 0 && (
- <>
- {pinned.length > 0 &&
Πρόσφατες
}
- {rest.map(n => (
-
- ))}
- >
- )}
- {notes.length === 0 && (
-
- Δεν υπάρχουν σημειώσεις ακόμα.
-
- )}
-
-
- )
-}
-
-// ── Todos column ──────────────────────────────────────────────────────────────
-
-function TodoItem({ todo, onToggle, onDelete, onEdit }) {
- const [editing, setEditing] = useState(false)
- const [draft, setDraft] = useState(todo.body)
- const inputRef = useRef(null)
-
- useEffect(() => {
- if (editing && inputRef.current) inputRef.current.focus()
- }, [editing])
-
- function saveEdit() {
- if (!draft.trim() || draft.trim() === todo.body) { setEditing(false); setDraft(todo.body); return }
- onEdit(todo.id, draft.trim())
- setEditing(false)
- }
-
- return (
-
- {/* Checkbox */}
-
-
- {/* Body */}
-
- {editing ? (
-
setDraft(e.target.value)}
- onBlur={saveEdit}
- onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') { setEditing(false); setDraft(todo.body) } }}
- style={{
- width: '100%', border: '1.5px solid #3b82f6', borderRadius: 6,
- padding: '3px 7px', fontSize: 13.5, outline: 'none', fontFamily: 'inherit',
- }}
- />
- ) : (
-
{ if (!todo.is_done) { setEditing(true); setDraft(todo.body) } }}
- style={{
- margin: 0, fontSize: 13.5, lineHeight: 1.5, wordBreak: 'break-word',
- color: todo.is_done ? '#9ca3af' : '#111827',
- textDecoration: todo.is_done ? 'line-through' : 'none',
- cursor: todo.is_done ? 'default' : 'text',
- }}
- >
- {todo.priority === 'high' && !todo.is_done && (
- ● ΕΠΕΙΓΟΝ
- )}
- {todo.body}
-
- )}
-
- {todo.created_by_name} · {fmtDate(todo.created_at)}
- {todo.is_done && todo.done_by_name && (
- · ✓ {todo.done_by_name}
- )}
-
-
-
- {/* Delete */}
-
-
- )
-}
-
-function TodosColumn({ todos, onAdd, onToggle, onDelete, onEdit }) {
- const [newBody, setNewBody] = useState('')
- const [newPriority, setNewPriority] = useState('normal')
- const [showDone, setShowDone] = useState(false)
-
- function submit() {
- if (!newBody.trim()) return
- onAdd(newBody.trim(), newPriority)
- setNewBody('')
- setNewPriority('normal')
- }
-
- const undone = todos.filter(t => !t.is_done)
- const done = todos.filter(t => t.is_done)
-
- return (
-
- {/* New todo form */}
-
-
setNewBody(e.target.value)}
- onKeyDown={e => { if (e.key === 'Enter') submit() }}
- placeholder="Νέα εργασία… (Enter)"
- style={{
- width: '100%', border: 'none', outline: 'none', background: 'transparent',
- fontSize: 13.5, fontFamily: 'inherit', color: '#374151',
- }}
- />
-
-
- {['normal', 'high'].map(p => (
-
- ))}
-
-
-
-
-
- {/* Todo list */}
-
- {undone.length === 0 && done.length === 0 && (
-
- Δεν υπάρχουν εργασίες ακόμα.
-
- )}
- {undone.map(t => (
-
- ))}
-
- {done.length > 0 && (
-
- )}
- {showDone && done.map(t => (
-
- ))}
-
-
- )
-}
-
-// ── Main page ─────────────────────────────────────────────────────────────────
-
-export default function NotesPage() {
- const qc = useQueryClient()
-
- const { data: notes = [] } = useQuery({
- queryKey: ['site-notes'],
- queryFn: () => client.get('/api/notes/').then(r => r.data),
- staleTime: 30_000,
- })
-
- const { data: todos = [] } = useQuery({
- queryKey: ['site-todos'],
- queryFn: () => client.get('/api/notes/todos').then(r => r.data),
- staleTime: 30_000,
- })
-
- // ── Note mutations ──────────────────────────────────────────────────────────
-
- const addNote = useMutation({
- mutationFn: ({ body, is_pinned }) => client.post('/api/notes/', { body, is_pinned }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const saveNote = useMutation({
- mutationFn: ({ id, body }) => client.put(`/api/notes/${id}`, { body }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const pinNote = useMutation({
- mutationFn: ({ id, is_pinned }) => client.put(`/api/notes/${id}`, { is_pinned }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
- })
-
- const deleteNote = useMutation({
- mutationFn: (id) => client.delete(`/api/notes/${id}`),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-notes'] }),
- onError: () => toast.error('Σφάλμα διαγραφής'),
- })
-
- // ── Todo mutations ──────────────────────────────────────────────────────────
-
- const addTodo = useMutation({
- mutationFn: ({ body, priority }) => client.post('/api/notes/todos', { body, priority }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const toggleTodo = useMutation({
- mutationFn: ({ id, is_done }) => client.put(`/api/notes/todos/${id}`, { is_done }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
- })
-
- const editTodo = useMutation({
- mutationFn: ({ id, body }) => client.put(`/api/notes/todos/${id}`, { body }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const deleteTodo = useMutation({
- mutationFn: (id) => client.delete(`/api/notes/todos/${id}`),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['site-todos'] }),
- onError: () => toast.error('Σφάλμα διαγραφής'),
- })
-
- return (
-
- {/* Page header */}
-
-
- {notes.length} σημειώσεις · {todos.filter(t => !t.is_done).length} εκκρεμείς εργασίες
-
-
-
- {/* Two-column body */}
-
- {/* Left: Notes */}
-
-
- Σημειώσεις
-
-
- addNote.mutate({ body, is_pinned })}
- onSave={(id, body) => saveNote.mutate({ id, body })}
- onDelete={(id) => deleteNote.mutate(id)}
- onTogglePin={(id, is_pinned) => pinNote.mutate({ id, is_pinned })}
- />
-
-
-
- {/* Right: Todos */}
-
-
- Εργασίες
-
-
- addTodo.mutate({ body, priority })}
- onToggle={(id, is_done) => toggleTodo.mutate({ id, is_done })}
- onEdit={(id, body) => editTodo.mutate({ id, body })}
- onDelete={(id) => deleteTodo.mutate(id)}
- />
-
-
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/WastePage.jsx b/manager_dashboard/src/pages/WastePage.jsx
deleted file mode 100644
index 0b009de..0000000
--- a/manager_dashboard/src/pages/WastePage.jsx
+++ /dev/null
@@ -1,295 +0,0 @@
-import { useState } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-
-// ── Constants ─────────────────────────────────────────────────────────────────
-
-const REASONS = [
- { id: 'kitchen_error', label: 'Λάθος κουζίνας', color: '#dc2626' },
- { id: 'dropped', label: 'Έπεσε', color: '#d97706' },
- { id: 'expired', label: 'Έληξε', color: '#7c3aed' },
- { id: 'other', label: 'Άλλο', color: '#6b7280' },
-]
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-function fmt(n) {
- if (n == null) return '—'
- return n.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €'
-}
-
-function fmtDateTime(iso) {
- if (!iso) return '—'
- return new Date(iso).toLocaleString('el-GR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })
-}
-
-// ── Log form ──────────────────────────────────────────────────────────────────
-
-function LogForm({ products, onLog, isPending }) {
- const [productId, setProductId] = useState('')
- const [qty, setQty] = useState('1')
- const [reason, setReason] = useState('kitchen_error')
- const [notes, setNotes] = useState('')
-
- const canLog = productId && parseFloat(qty) > 0
-
- function submit() {
- if (!canLog) return
- onLog({
- product_id: Number(productId),
- quantity: parseFloat(qty),
- reason,
- reason_notes: notes.trim() || null,
- })
- setProductId('')
- setQty('1')
- setReason('kitchen_error')
- setNotes('')
- }
-
- const inputStyle = {
- width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
- borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
- boxSizing: 'border-box',
- }
-
- return (
-
-
- Καταγραφή Απόβλητου
-
-
-
-
-
-
-
-
- setQty(e.target.value)} />
-
-
-
-
-
-
- {REASONS.map(r => (
-
- ))}
-
-
-
-
-
- setNotes(e.target.value)}
- placeholder="π.χ. Ο πελάτης επέστρεψε ελαττωματικό…" />
-
-
-
-
- )
-}
-
-// ── Waste entry row ───────────────────────────────────────────────────────────
-
-function WasteRow({ entry, canDelete, onDelete }) {
- const reasonCfg = REASONS.find(r => r.id === entry.reason) || { label: entry.reason, color: '#6b7280' }
- return (
-
-
-
- {entry.product_name}
- ×{entry.quantity}
-
- {reasonCfg.label}
-
-
-
- {fmtDateTime(entry.logged_at)} · {entry.logged_by_name}
- {entry.reason_notes && — {entry.reason_notes}}
-
-
-
- {entry.total_cost != null ? (
-
{fmt(entry.total_cost)}
- ) : (
-
χωρίς κόστος
- )}
- {entry.unit_cost_snapshot != null && (
-
{fmt(entry.unit_cost_snapshot)}/τεμ.
- )}
-
- {canDelete && (
-
- )}
-
- )
-}
-
-// ── Main page ─────────────────────────────────────────────────────────────────
-
-export default function WastePage() {
- const qc = useQueryClient()
- const [showHistory, setShowHistory] = useState(false)
- const [histFrom, setHistFrom] = useState(() => new Date().toISOString().slice(0, 10))
- const [histTo, setHistTo] = useState(() => new Date().toISOString().slice(0, 10))
-
- const { data: productsData = [] } = useQuery({
- queryKey: ['meta-products'],
- queryFn: () => client.get('/api/reports/meta/products').then(r => r.data.products),
- staleTime: 5 * 60_000,
- })
-
- const { data: bdData } = useQuery({
- queryKey: ['business-day'],
- queryFn: () => client.get('/api/business-day/current').then(r => r.data),
- staleTime: 30_000,
- })
- const activeDayId = bdData?.id ?? null
-
- // Today's entries — scoped to active business day (or all if no active day)
- const { data: todayData } = useQuery({
- queryKey: ['waste-today', activeDayId],
- queryFn: () => client.get('/api/waste/', { params: activeDayId ? { business_day_id: activeDayId } : {} }).then(r => r.data),
- staleTime: 15_000,
- })
-
- // Historical entries
- const { data: histData, refetch: refetchHist } = useQuery({
- queryKey: ['waste-history', histFrom, histTo],
- queryFn: () => client.get('/api/waste/', { params: { from: histFrom + 'T00:00:00', to: histTo + 'T23:59:59' } }).then(r => r.data),
- staleTime: 30_000,
- enabled: showHistory,
- })
-
- const todayEntries = todayData?.entries || []
- const histEntries = histData?.entries || []
-
- const todayCost = todayEntries.reduce((s, e) => s + (e.total_cost || 0), 0)
- const todayCount = todayEntries.length
-
- const logWaste = useMutation({
- mutationFn: (body) => client.post('/api/waste/', body),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['waste-today'] })
- qc.invalidateQueries({ queryKey: ['waste-history'] })
- toast.success('Καταγράφηκε')
- },
- onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
- })
-
- const deleteWaste = useMutation({
- mutationFn: (id) => client.delete(`/api/waste/${id}`),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['waste-today'] })
- qc.invalidateQueries({ queryKey: ['waste-history'] })
- toast.success('Διαγράφηκε')
- },
- onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
- })
-
- return (
-
- {/* Header */}
-
-
-
- Σήμερα: {todayCount} καταχωρήσεις
- {todayCost > 0 && · εκτιμώμενο κόστος {todayCost.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €}
-
-
-
-
-
- {/* Log form */}
-
logWaste.mutate(body)} isPending={logWaste.isPending} />
-
- {/* Today's entries */}
-
-
- {activeDayId ? 'Σήμερα' : 'Τελευταίες καταχωρήσεις'}
-
- {todayEntries.length === 0 ? (
-
Καμία καταχώρηση ακόμα.
- ) : (
-
- {todayEntries.map(e => (
- deleteWaste.mutate(id)} />
- ))}
-
- )}
-
-
- {/* History toggle */}
-
-
-
- {showHistory && (
-
-
-
-
- setHistFrom(e.target.value)}
- style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
-
-
-
- setHistTo(e.target.value)}
- style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
-
-
-
-
- {histEntries.length === 0 ? (
-
Δεν βρέθηκαν καταχωρήσεις.
- ) : (
-
- {histEntries.map(e => (
-
{}} />
- ))}
-
- {histEntries.length} καταχωρήσεις · εκτιμώμενο κόστος{' '}
-
- {histEntries.reduce((s, e) => s + (e.total_cost || 0), 0).toLocaleString('el-GR', { minimumFractionDigits: 2 })} €
-
-
-
- )}
-
- )}
-
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/crm/CustomersPage.jsx b/manager_dashboard/src/pages/crm/CustomersPage.jsx
deleted file mode 100644
index c402c98..0000000
--- a/manager_dashboard/src/pages/crm/CustomersPage.jsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from '../CustomersPage'
diff --git a/manager_dashboard/src/pages/customers/CustomerCard.jsx b/manager_dashboard/src/pages/customers/CustomerCard.jsx
new file mode 100644
index 0000000..673770b
--- /dev/null
+++ b/manager_dashboard/src/pages/customers/CustomerCard.jsx
@@ -0,0 +1,83 @@
+// A customer's card (plan step 6.13b): visits, spent, per visit; phone and e-mail; their notes;
+// what they owe on an open tab (with the Tabs app on: Finance → Tabs settles it); every visit
+// (when, where, what it came to, the part on a tab, its state).
+import { Mail, Pencil, Phone } from 'lucide-react'
+import { useModule } from '@xenia/access'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog, Spinner } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { Pill } from '../overview/parts'
+import { perVisit } from './customersLogic'
+
+const ORDER_TONE = { open: 'info', partially_paid: 'warning', paid: 'success', closed: 'neutral', cancelled: 'danger' }
+
+export default function CustomerCard({ customer: c, onClose, onEdit }) {
+ const { t } = useTranslation('manager')
+ const fmt = useFormat()
+ const tabsOn = useModule('tabs')
+ const { data, isPending } = useLiveQuery({
+ queryKey: ['customer-orders', c.id], queryFn: () => client.get(`/api/customers/${c.id}/orders`).then(r => r.data.orders),
+ events: ['customers.changed', 'order_closed', 'order_paid'],
+ })
+ const { data: tabs = [] } = useLiveQuery({
+ queryKey: ['customer-tabs', c.id], enabled: tabsOn, queryFn: () => client.get(`/api/tabs/customer/${c.id}`).then(r => r.data),
+ events: ['tabs.changed'],
+ })
+ const openTab = tabs.find(x => x.status === 'open')
+ const avg = perVisit(c)
+ return (
+
+ )
+}
diff --git a/manager_dashboard/src/pages/customers/CustomerDialog.jsx b/manager_dashboard/src/pages/customers/CustomerDialog.jsx
new file mode 100644
index 0000000..18a3f94
--- /dev/null
+++ b/manager_dashboard/src/pages/customers/CustomerDialog.jsx
@@ -0,0 +1,53 @@
+// A new customer or an existing one (plan step 6.13b): name, nickname (how the staff know them),
+// phone (caller ID finds them by it), e-mail, notes (allergies, likes). Clearing a field clears it.
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { errorMessage } from '@xenia/api'
+import { useTranslation } from '@xenia/i18n'
+import { Button, Dialog, Field, Input, Textarea } from '@xenia/ui'
+import client from '../../api/client'
+import { customerBody, customerForm, customerProblems } from './customersLogic'
+
+export default function CustomerDialog({ customer, onClose, onSaved }) {
+ const { t } = useTranslation('manager')
+ const isNew = !customer
+ const [form, setForm] = useState(() => customerForm(customer))
+ const [tried, setTried] = useState(false)
+ const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
+ const wrong = customerProblems(form)
+ const err = k => (tried && wrong.includes(k) ? t(`customers.wrong.${k}`) : undefined)
+ const save = useMutation({
+ mutationFn: body => (isNew ? client.post('/api/customers/', body) : client.put(`/api/customers/${customer.id}`, body)).then(r => r.data),
+ onSuccess: c => { toast.success(t(isNew ? 'customers.added' : 'customers.saved', { name: c.name })); onSaved(c) },
+ onError: e => toast.error(errorMessage(e, t)),
+ })
+ const submit = () => { setTried(true); if (!wrong.length) save.mutate(customerBody(form)) }
+ return (
+
+ )
+}
diff --git a/manager_dashboard/src/pages/customers/CustomersPage.jsx b/manager_dashboard/src/pages/customers/CustomersPage.jsx
new file mode 100644
index 0000000..d88e2fe
--- /dev/null
+++ b/manager_dashboard/src/pages/customers/CustomersPage.jsx
@@ -0,0 +1,95 @@
+// CRM → Customers (plan step 6.13b; replaces the v1 CustomersPage): the venue's regular
+// customers. Search by name, nickname, phone, e-mail or notes (case and Greek accents ignored);
+// each with visits, what they spent (counted as in the reports: refunds off, tab lines in) and
+// their last visit. A tap opens their card: contact, notes (allergies, likes), their open tab,
+// every visit. New, edit, remove (a removed customer stays on old orders). Live: `customers.changed`.
+import { useDeferredValue, useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { Pencil, Plus, Search, Trash2, Users } from 'lucide-react'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog, EmptyState, IconButton, Input, Spinner } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { Avatar } from '../overview/parts'
+import { Panel, Table } from '../reports/kit/parts'
+import CustomerCard from './CustomerCard'
+import CustomerDialog from './CustomerDialog'
+
+export default function CustomersPage() {
+ const { t } = useTranslation('manager')
+ const fmt = useFormat()
+ const [q, setQ] = useState('')
+ const search = useDeferredValue(q.trim())
+ const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'card' | 'remove', customer }
+ const { data, isPending, refetch } = useLiveQuery({
+ queryKey: ['customers', search], placeholderData: prev => prev,
+ queryFn: () => client.get('/api/customers/', { params: search ? { search } : {} }).then(r => r.data),
+ events: ['customers.changed', 'order_closed', 'order_paid'],
+ })
+ const rows = data ?? []
+ const close = () => setDialog(null)
+ const saved = () => { close(); refetch() }
+ const remove = useMutation({
+ mutationFn: c => client.delete(`/api/customers/${c.id}`),
+ onSuccess: (_r, c) => { toast.success(t('customers.removed', { name: c.name })); saved() },
+ onError: err => toast.error(errorMessage(err, t)),
+ })
+ const stop = fn => ev => { ev.stopPropagation(); fn() }
+
+ const columns = [
+ { key: 'name', label: t('customers.name'), render: c => (
+
+
+
+ {c.name}{c.nickname && «{c.nickname}»}
+ {c.notes && {c.notes}}
+
+ ) },
+ { key: 'phone', label: t('customers.phone'), render: c => (c.phone ? ev.stopPropagation()} className="text-accent-ink hover:underline">{c.phone} : '') },
+ { key: 'visit_count', label: t('customers.visits'), align: 'right' },
+ { key: 'total_spent', label: t('customers.spent'), align: 'right', tip: t('customers.spentTip'), render: c => (c.total_spent ? fmt.formatMoney(c.total_spent) : '') },
+ { key: 'last_visit', label: t('customers.lastVisit'), sort: c => c.last_visit ?? '', render: c => (c.last_visit ? fmt.formatDate(c.last_visit) : '') },
+ { key: 'actions', label: '', sort: false, render: c => (
+
+ setDialog({ kind: 'edit', customer: c }))}>
+ setDialog({ kind: 'remove', customer: c }))}>
+ ) },
+ ]
+
+ return (
+
+
+
+
+
+ setQ(e.target.value)} placeholder={t('customers.search')} aria-label={t('customers.search')} className="pl-9" data-testid="customer-search" />
+
+ {isPending ?
+ : !rows.length && !search ?
} title={t('customers.none')} description={t('customers.noneHint')} />
+ : (
+
+ setDialog({ kind: 'card', customer: c })} rowTestId="customer-row"
+ empty={t('customers.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
+
+ )}
+
+ {(dialog?.kind === 'new' || dialog?.kind === 'edit') && }
+ {dialog?.kind === 'card' && setDialog({ kind: 'edit', customer: dialog.customer })} />}
+ {dialog?.kind === 'remove' && (
+