From bde125bf0900f011abbbb0642d511ae29e660899 Mon Sep 17 00:00:00 2001 From: bonamin Date: Thu, 19 Nov 2026 18:36:27 +0200 Subject: [PATCH] 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 --- local_backend/routers/customers.py | 119 +++-- local_backend/routers/notes.py | 51 +- local_backend/routers/waste.py | 69 ++- local_backend/schemas/customers.py | 1 + local_backend/schemas/waste.py | 8 +- .../tests/test_customers_waste_notes.py | 118 +++++ manager_dashboard/src/App.jsx | 4 +- manager_dashboard/src/pages/CustomersPage.jsx | 349 ------------ manager_dashboard/src/pages/NotesPage.jsx | 500 ------------------ manager_dashboard/src/pages/WastePage.jsx | 295 ----------- .../src/pages/crm/CustomersPage.jsx | 1 - .../src/pages/customers/CustomerCard.jsx | 83 +++ .../src/pages/customers/CustomerDialog.jsx | 53 ++ .../src/pages/customers/CustomersPage.jsx | 95 ++++ .../src/pages/customers/customersLogic.js | 29 + .../src/pages/inventory/StockPage.jsx | 11 +- .../src/pages/inventory/ThrowawaysPage.jsx | 164 +++++- .../src/pages/inventory/wasteLogic.js | 27 + .../src/pages/notes/NotesPage.jsx | 199 +++++++ .../src/pages/notes/notesLogic.js | 15 + .../src/pages/overview/NotesCard.jsx | 4 +- .../src/pages/overview/OverviewPage.jsx | 5 +- manager_dashboard/src/shell/nav.js | 8 +- manager_dashboard/tests/crm.test.mjs | 37 ++ manager_dashboard/v2.json | 4 +- packages/i18n/locales/el/manager.json | 143 +++++ packages/i18n/locales/en/manager.json | 143 +++++ tests/e2e/manager.mjs | 65 +++ 28 files changed, 1356 insertions(+), 1244 deletions(-) create mode 100644 local_backend/tests/test_customers_waste_notes.py delete mode 100644 manager_dashboard/src/pages/CustomersPage.jsx delete mode 100644 manager_dashboard/src/pages/NotesPage.jsx delete mode 100644 manager_dashboard/src/pages/WastePage.jsx delete mode 100644 manager_dashboard/src/pages/crm/CustomersPage.jsx create mode 100644 manager_dashboard/src/pages/customers/CustomerCard.jsx create mode 100644 manager_dashboard/src/pages/customers/CustomerDialog.jsx create mode 100644 manager_dashboard/src/pages/customers/CustomersPage.jsx create mode 100644 manager_dashboard/src/pages/customers/customersLogic.js create mode 100644 manager_dashboard/src/pages/inventory/wasteLogic.js create mode 100644 manager_dashboard/src/pages/notes/NotesPage.jsx create mode 100644 manager_dashboard/src/pages/notes/notesLogic.js create mode 100644 manager_dashboard/tests/crm.test.mjs 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('nickname', e.target.value)} placeholder="π.χ. Μεγάλος Γιάννης" /> -
-
- - f('phone', e.target.value)} placeholder="π.χ. 6912345678" /> -
-
-
- - f('email', e.target.value)} placeholder="email@example.com" /> -
-
- -