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 fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
@@ -7,22 +16,47 @@ from models.customers import Customer
from models.order import Order, OrderItem from models.order import Order, OrderItem
from models.user import User from models.user import User
from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest
from core.access.deps import require_any from core.access.deps import require, require_any
from routers.deps import require_manager, get_current_user
from core.errors import XeniaError from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
MANAGE = Depends(require("crm.manage"))
def _customer_out(c: Customer, db: Session) -> dict:
orders = db.query(Order).filter( def _changed():
Order.customer_id == c.id, broadcast_sync("customers.changed", {})
Order.status.in_(["closed", "paid"]),
).all()
total_spent = sum( def _fold(text: str | None) -> str:
sum(i.unit_price * i.quantity for i in o.items if i.status in ("active", "paid")) """Lower case without accents: "Γιώργος" and "γιωργος" match."""
for o in orders 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 { return {
"id": c.id, "id": c.id,
"name": c.name, "name": c.name,
@@ -33,8 +67,9 @@ def _customer_out(c: Customer, db: Session) -> dict:
"is_active": c.is_active, "is_active": c.is_active,
"created_at": c.created_at, "created_at": c.created_at,
"created_by_id": c.created_by_id, "created_by_id": c.created_by_id,
"visit_count": len(orders), "visit_count": visits,
"total_spent": round(total_spent, 2), "total_spent": round(spent, 2),
"last_visit": last,
} }
@@ -43,28 +78,34 @@ def list_customers(
search: Optional[str] = None, search: Optional[str] = None,
include_inactive: bool = False, include_inactive: bool = False,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = Depends(require_any("crm.manage", "core.dashboard.access")),
): ):
q = db.query(Customer) q = db.query(Customer)
if not include_inactive: if not include_inactive:
q = q.filter(Customer.is_active == True) 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() 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) @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)): def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: User = MANAGE):
customer = Customer(**body.model_dump(), created_by_id=user.id) fields = body.model_dump()
_check(fields)
fields["name"] = fields["name"].strip()
customer = Customer(**fields, created_by_id=user.id)
db.add(customer) db.add(customer)
db.commit() db.commit()
db.refresh(customer) db.refresh(customer)
_changed()
return _customer_out(customer, db) 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) @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() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise XeniaError("customer.not_found") 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) @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() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise XeniaError("customer.not_found") raise XeniaError("customer.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (nickname, phone…); name and is_active only change when given
setattr(c, field, value) 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.commit()
db.refresh(c) db.refresh(c)
_changed()
return _customer_out(c, db) return _customer_out(c, db)
@router.delete("/{customer_id}", status_code=status.HTTP_204_NO_CONTENT) @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() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise XeniaError("customer.not_found") raise XeniaError("customer.not_found")
c.is_active = False c.is_active = False
db.commit() db.commit()
_changed()
@router.get("/{customer_id}/orders") @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() c = db.query(Customer).filter(Customer.id == customer_id).first()
if not c: if not c:
raise XeniaError("customer.not_found") raise XeniaError("customer.not_found")
from models.table import Table 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() 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()} 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 = [] result = []
for o in orders: 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({ result.append({
"id": o.id, "id": o.id,
"table_name": tables_map.get(o.table_id) if o.table_id else None, "table_name": tables_map.get(o.table_id) if o.table_id else None,
"order_type": o.order_type,
"opened_at": o.opened_at, "opened_at": o.opened_at,
"status": o.status, "status": o.status,
"total": round(total, 2), "total": round(tot.takings, 2),
"item_count": sum(i.quantity for i in o.items if i.status in ("active", "paid")), "on_tab": round(tot.on_tab, 2),
"item_count": tot.units,
}) })
return {"orders": result} return {"orders": result}
+37 -14
View File
@@ -8,11 +8,25 @@ from database import get_db
from models.notes import SiteNote, SiteTodo from models.notes import SiteNote, SiteTodo
from models.user import User from models.user import User
from schemas.notes import NoteCreate, NoteUpdate, NoteOut, TodoCreate, TodoUpdate, TodoOut 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 core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() 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 ───────────────────────────────────────────────────────────────────── # ── Notes ─────────────────────────────────────────────────────────────────────
@router.get("/", response_model=List[NoteOut]) @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( notes = db.query(SiteNote).order_by(
SiteNote.is_pinned.desc(), SiteNote.updated_at.desc() SiteNote.is_pinned.desc(), SiteNote.updated_at.desc()
).all() ).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) @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)): def create_note(body: NoteCreate, db: Session = Depends(get_db), user: User = USE):
note = SiteNote(body=body.body, is_pinned=body.is_pinned, created_by_id=user.id) note = SiteNote(body=_text(body.body), is_pinned=body.is_pinned, created_by_id=user.id)
db.add(note) db.add(note)
db.commit() db.commit()
db.refresh(note) db.refresh(note)
_changed()
return _note_out(note) return _note_out(note)
@router.put("/{note_id}", response_model=NoteOut) @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() note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note: if not note:
raise XeniaError("note.not_found") raise XeniaError("note.not_found")
if body.body is not None: if body.body is not None:
note.body = body.body note.body = _text(body.body)
if body.is_pinned is not None: if body.is_pinned is not None:
note.is_pinned = body.is_pinned note.is_pinned = body.is_pinned
note.updated_at = utcnow()
db.commit() db.commit()
db.refresh(note) db.refresh(note)
_changed()
return _note_out(note) return _note_out(note)
@router.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT) @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() note = db.query(SiteNote).filter(SiteNote.id == note_id).first()
if not note: if not note:
raise XeniaError("note.not_found") raise XeniaError("note.not_found")
db.delete(note) db.delete(note)
db.commit() db.commit()
_changed()
# ── Todos ───────────────────────────────────────────────────────────────────── # ── Todos ─────────────────────────────────────────────────────────────────────
@router.get("/todos", response_model=List[TodoOut]) @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) q = db.query(SiteTodo)
if done is not None: if done is not None:
q = q.filter(SiteTodo.is_done == done) 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) @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)): def create_todo(body: TodoCreate, db: Session = Depends(get_db), user: User = USE):
todo = SiteTodo(body=body.body, priority=body.priority, created_by_id=user.id) 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.add(todo)
db.commit() db.commit()
db.refresh(todo) db.refresh(todo)
_changed()
return _todo_out(todo) return _todo_out(todo)
@router.put("/todos/{todo_id}", response_model=TodoOut) @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() todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo: if not todo:
raise XeniaError("todo.not_found") raise XeniaError("todo.not_found")
if body.body is not None: if body.body is not None:
todo.body = body.body todo.body = _text(body.body)
if body.priority is not None: 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 todo.priority = body.priority
if body.is_done is not None: if body.is_done is not None:
todo.is_done = body.is_done 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 todo.done_by_id = None
db.commit() db.commit()
db.refresh(todo) db.refresh(todo)
_changed()
return _todo_out(todo) return _todo_out(todo)
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT) @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() todo = db.query(SiteTodo).filter(SiteTodo.id == todo_id).first()
if not todo: if not todo:
raise XeniaError("todo.not_found") raise XeniaError("todo.not_found")
db.delete(todo) db.delete(todo)
db.commit() 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 import json
from fastapi import APIRouter, Depends, status, Query from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -9,12 +18,28 @@ from models.waste import WasteLog
from models.product import Product from models.product import Product
from models.business_day import BusinessDay from models.business_day import BusinessDay
from models.user import User from models.user import User
from schemas.waste import WasteLogCreate, WasteLogOut, VALID_REASONS, REASON_LABELS from schemas.waste import WasteLogCreate, VALID_REASONS
from routers.deps import require_manager from core.access.deps import require
from core.errors import XeniaError from core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() 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]: def _effective_cost(product: Product) -> Optional[float]:
"""Return product's current effective cost (breakdown sum or simple), or None.""" """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, "unit_cost_snapshot": w.unit_cost_snapshot,
"total_cost": w.total_cost, "total_cost": w.total_cost,
"reason": w.reason, "reason": w.reason,
"reason_label": REASON_LABELS.get(w.reason, w.reason),
"reason_notes": w.reason_notes, "reason_notes": w.reason_notes,
"logged_by_id": w.logged_by_id, "logged_by_id": w.logged_by_id,
"logged_by_name": logger_name, "logged_by_name": logger_name,
@@ -58,18 +82,12 @@ def list_waste(
business_day_id: Optional[int] = None, business_day_id: Optional[int] = None,
from_dt: Optional[str] = Query(default=None, alias="from"), from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"), to_dt: Optional[str] = Query(default=None, alias="to"),
date_from: Optional[date] = None,
date_to: Optional[date] = None,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
from datetime import datetime q = _period(db.query(WasteLog).order_by(WasteLog.logged_at.desc()), business_day_id, from_dt, to_dt, date_from, date_to)
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),
)
entries = q.all() entries = q.all()
return {"entries": [_waste_out(w) for w in entries]} return {"entries": [_waste_out(w) for w in entries]}
@@ -78,7 +96,7 @@ def list_waste(
def log_waste( def log_waste(
body: WasteLogCreate, body: WasteLogCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
if body.reason not in VALID_REASONS: if body.reason not in VALID_REASONS:
raise XeniaError("validation.choice", field='reason', value=body.reason) raise XeniaError("validation.choice", field='reason', value=body.reason)
@@ -109,6 +127,7 @@ def log_waste(
db.add(entry) db.add(entry)
db.commit() db.commit()
db.refresh(entry) db.refresh(entry)
broadcast_sync("waste.changed", {})
return _waste_out(entry) return _waste_out(entry)
@@ -116,7 +135,7 @@ def log_waste(
def delete_waste( def delete_waste(
entry_id: int, entry_id: int,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
entry = db.query(WasteLog).filter(WasteLog.id == entry_id).first() entry = db.query(WasteLog).filter(WasteLog.id == entry_id).first()
if not entry: if not entry:
@@ -129,6 +148,7 @@ def delete_waste(
db.delete(entry) db.delete(entry)
db.commit() db.commit()
broadcast_sync("waste.changed", {})
@router.get("/summary") @router.get("/summary")
@@ -136,19 +156,12 @@ def waste_summary(
business_day_id: Optional[int] = None, business_day_id: Optional[int] = None,
from_dt: Optional[str] = Query(default=None, alias="from"), from_dt: Optional[str] = Query(default=None, alias="from"),
to_dt: Optional[str] = Query(default=None, alias="to"), to_dt: Optional[str] = Query(default=None, alias="to"),
date_from: Optional[date] = None,
date_to: Optional[date] = None,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
from datetime import datetime entries = _period(db.query(WasteLog), business_day_id, from_dt, to_dt, date_from, date_to).all()
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()
total_items = len(entries) total_items = len(entries)
total_cost = round(sum(e.total_cost for e in entries if e.total_cost is not None), 2) 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: for e in entries:
r = e.reason r = e.reason
if r not in by_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]["count"] += 1
by_reason[r]["total_cost"] += e.total_cost or 0.0 by_reason[r]["total_cost"] += e.total_cost or 0.0
+1
View File
@@ -33,6 +33,7 @@ class CustomerOut(BaseModel):
# computed stats (set by router) # computed stats (set by router)
visit_count: int = 0 visit_count: int = 0
total_spent: float = 0.0 total_spent: float = 0.0
last_visit: Optional[datetime] = None
model_config = {"from_attributes": True} model_config = {"from_attributes": True}
+1 -7
View File
@@ -4,12 +4,7 @@ from datetime import datetime
VALID_REASONS = {"kitchen_error", "dropped", "expired", "other"} VALID_REASONS = {"kitchen_error", "dropped", "expired", "other"}
REASON_LABELS = { # Texts: manager `waste.reasons.*` (6.13b; the Greek labels that were here are gone)
"kitchen_error": "Λάθος κουζίνας",
"dropped": "Έπεσε",
"expired": "Έληξε",
"other": "Άλλο",
}
class WasteLogCreate(BaseModel): class WasteLogCreate(BaseModel):
@@ -27,7 +22,6 @@ class WasteLogOut(BaseModel):
unit_cost_snapshot: Optional[float] = None unit_cost_snapshot: Optional[float] = None
total_cost: Optional[float] = None total_cost: Optional[float] = None
reason: str reason: str
reason_label: Optional[str] = None
reason_notes: Optional[str] = None reason_notes: Optional[str] = None
logged_by_id: int logged_by_id: int
logged_by_name: Optional[str] = None logged_by_name: Optional[str] = None
@@ -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
+2 -2
View File
@@ -22,7 +22,7 @@ import QrCodesPage from './pages/online/QrCodesPage'
// CRM // CRM
import ContactsPage from './pages/finance/ContactsPage' import ContactsPage from './pages/finance/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage' import CustomersPage from './pages/customers/CustomersPage'
// Financials // Financials
import ExpensesPage from './pages/finance/ExpensesPage' import ExpensesPage from './pages/finance/ExpensesPage'
@@ -60,7 +60,7 @@ import LicensePage from './pages/platform/LicensePage'
import DevicesPage from './pages/platform/DevicesPage' import DevicesPage from './pages/platform/DevicesPage'
import PhonePage from './pages/PhonePage' import PhonePage from './pages/PhonePage'
import SettingsPage from './pages/Settings/SettingsPage' 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). // 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). // The language follows bootstrap (user -> venue); the current pages are still Greek (phase 6).
@@ -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 (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 480, boxShadow: '0 20px 60px rgba(0,0,0,0.18)', display: 'flex', flexDirection: 'column' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>{isNew ? 'Νέος Πελάτης' : 'Επεξεργασία Πελάτη'}</h2>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Όνομα *</label>
<input style={inputStyle} value={form.name} onChange={e => f('name', e.target.value)} autoFocus placeholder="π.χ. Γιώργος Παπαδόπουλος" />
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Παρατσούκλι</label>
<input style={inputStyle} value={form.nickname} onChange={e => f('nickname', e.target.value)} placeholder="π.χ. Μεγάλος Γιάννης" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τηλέφωνο</label>
<input style={inputStyle} value={form.phone} onChange={e => f('phone', e.target.value)} placeholder="π.χ. 6912345678" />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Email</label>
<input style={inputStyle} type="email" value={form.email} onChange={e => f('email', e.target.value)} placeholder="email@example.com" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις <span style={{ fontWeight: 400, color: '#9ca3af' }}>(αλλεργίες, προτιμήσεις…)</span></label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={3} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="π.χ. Αλλεργία στους ξηρούς καρπούς, VIP πελάτης…" />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button
onClick={() => onSave(form)}
disabled={!form.name.trim() || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: form.name.trim() ? 'pointer' : 'default', background: form.name.trim() ? '#111827' : '#e5e7eb', color: form.name.trim() ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'white', borderLeft: '1px solid #f0f0ef' }}>
{/* Header */}
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', flexShrink: 0 }}>
<div>
<div style={{ fontSize: 18, fontWeight: 800, color: '#111315' }}>{customer.name}</div>
{customer.nickname && <div style={{ fontSize: 13, color: '#9ca3af', marginTop: 2 }}>«{customer.nickname}»</div>}
</div>
<div style={{ display: 'flex', gap: 6 }}>
<button onClick={onEdit} style={{ padding: '5px 12px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 7, fontSize: 12, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>Επεξεργασία</button>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#9ca3af', padding: '0 4px' }}>✕</button>
</div>
</div>
{/* Stats row */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, padding: '14px 22px', flexShrink: 0, borderBottom: '1px solid #f0f0ef' }}>
{[
{ 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 => (
<div key={s.label} style={{ background: '#f9fafb', borderRadius: 10, padding: '10px 12px', textAlign: 'center' }}>
<div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
<div style={{ fontSize: 16, fontWeight: 800, color: '#111315', marginTop: 3 }}>{s.value}</div>
</div>
))}
</div>
{/* Open tab banner */}
{openTab && (
<div style={{ padding: '10px 22px', borderBottom: '1px solid #f0f0ef', flexShrink: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 10 }}>
<div>
<div style={{ fontSize: 12.5, fontWeight: 700, color: '#dc2626' }}>Ανοιχτή Καρτέλα</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
{openTab.entries.length} χρεώσεις · πληρωμένο {fmt(openTab.total_paid)}
</div>
</div>
<div style={{ fontSize: 18, fontWeight: 800, color: '#dc2626' }}>{fmt(openTab.balance)}</div>
</div>
</div>
)}
{/* Contact info */}
<div style={{ padding: '12px 22px', borderBottom: '1px solid #f0f0ef', flexShrink: 0 }}>
{(customer.phone || customer.email || customer.notes) ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13 }}>
{customer.phone && <div><span style={{ color: '#9ca3af', marginRight: 6 }}>📞</span>{customer.phone}</div>}
{customer.email && <div><span style={{ color: '#9ca3af', marginRight: 6 }}>✉</span>{customer.email}</div>}
{customer.notes && (
<div style={{ marginTop: 4, padding: '8px 12px', background: '#fffbeb', borderRadius: 8, border: '1px solid #fef3c7', fontSize: 12.5, color: '#92400e', lineHeight: 1.5 }}>
📝 {customer.notes}
</div>
)}
</div>
) : (
<div style={{ fontSize: 12.5, color: '#d1d5db' }}>Δεν υπάρχουν στοιχεία επικοινωνίας.</div>
)}
</div>
{/* Visit history */}
<div style={{ flex: 1, overflowY: 'auto', padding: '14px 22px' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>Ιστορικό Επισκέψεων</div>
{isLoading && <div style={{ color: '#9ca3af', fontSize: 13 }}>Φόρτωση…</div>}
{!isLoading && orders.length === 0 && (
<div style={{ color: '#d1d5db', fontSize: 13 }}>Δεν υπάρχουν επισκέψεις ακόμα.</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{orders.map(o => (
<div key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', border: '1px solid #f0f0ef', borderRadius: 10, background: 'white' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#111315' }}>
{o.table_name ? `Τραπέζι ${o.table_name}` : 'Χωρίς τραπέζι'}
{' '}
<span style={{ fontSize: 11, fontWeight: 700, padding: '1px 6px', borderRadius: 99, background: '#f3f4f6', color: ORDER_STATUS_COLORS[o.status] || '#6b7280' }}>
{ORDER_STATUS_LABELS[o.status] || o.status}
</span>
</div>
<div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>
{fmtDateTime(o.opened_at)} · {o.item_count} αντικ.
</div>
</div>
<div style={{ fontSize: 14, fontWeight: 700, color: '#111315', whiteSpace: 'nowrap' }}>{fmt(o.total)}</div>
</div>
))}
</div>
</div>
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
{/* Left: list */}
<div style={{ display: 'flex', flexDirection: 'column', width: selected ? 360 : '100%', flexShrink: 0, borderRight: selected ? '1px solid #f0f0ef' : 'none', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 24px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>{activeCount} ενεργοί πελάτες</p>
</div>
<button
onClick={() => setModal({ customer: null })}
style={{ padding: '8px 16px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέος
</button>
</div>
<input
value={search}
onChange={e => setSearch(e.target.value)}
placeholder="Αναζήτηση με όνομα, παρατσούκλι ή τηλέφωνο…"
style={{ ...inputStyle, fontSize: 13 }}
/>
</div>
{/* List */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 4 }}>
{isLoading && <div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>Φόρτωση…</div>}
{!isLoading && customers.length === 0 && (
<div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: '32px 0' }}>
{search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν πελάτες ακόμα.'}
</div>
)}
{customers.map(c => (
<button
key={c.id}
onClick={() => setSelected(selected?.id === c.id ? null : c)}
style={{
display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
border: `1px solid ${selected?.id === c.id ? '#3b82f6' : '#f0f0ef'}`,
borderRadius: 10, background: selected?.id === c.id ? '#eff6ff' : 'white',
cursor: 'pointer', textAlign: 'left', width: '100%',
}}
>
{/* Avatar */}
<div style={{
width: 38, height: 38, borderRadius: '50%', flexShrink: 0,
background: `hsl(${[...c.name].reduce((a, ch) => a + ch.charCodeAt(0), 0) % 360},55%,62%)`,
color: 'white', fontSize: 15, fontWeight: 700,
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{c.name.trim()[0].toUpperCase()}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: '#111315', display: 'flex', alignItems: 'center', gap: 6 }}>
{c.name}
{c.nickname && <span style={{ fontSize: 11, fontWeight: 500, color: '#9ca3af' }}>«{c.nickname}»</span>}
</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
{c.phone || c.email || 'Χωρίς στοιχεία'}
{c.visit_count > 0 && <span style={{ marginLeft: 8, color: '#6b7280' }}>· {c.visit_count} επισκέψεις</span>}
</div>
</div>
<div style={{ fontSize: 13, fontWeight: 700, color: '#111315', whiteSpace: 'nowrap', flexShrink: 0 }}>
{c.total_spent > 0 ? fmt(c.total_spent) : ''}
</div>
</button>
))}
</div>
</div>
{/* Right: detail panel */}
{selected && (
<div style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
<CustomerDetail
customer={selected}
onEdit={() => setModal({ customer: selected })}
onClose={() => setSelected(null)}
/>
</div>
)}
{modal && (
<CustomerModal
initial={modal.customer ? {
...modal.customer,
nickname: modal.customer.nickname || '',
phone: modal.customer.phone || '',
email: modal.customer.email || '',
notes: modal.customer.notes || '',
} : null}
onClose={() => 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,
})}
/>
)}
</div>
)
}
-500
View File
@@ -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 (
<div style={{
border: note.is_pinned ? '1.5px solid #fbbf24' : '1px solid #e5e7eb',
borderRadius: 12,
background: note.is_pinned ? '#fffbeb' : 'white',
padding: '14px 16px',
display: 'flex',
flexDirection: 'column',
gap: 8,
}}>
{editing ? (
<textarea
ref={taRef}
value={draft}
onChange={e => setDraft(e.target.value)}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
style={{
width: '100%', minHeight: 80, border: '1.5px solid #3b82f6',
borderRadius: 8, padding: '8px 10px', fontSize: 13.5, lineHeight: 1.55,
resize: 'vertical', outline: 'none', fontFamily: 'inherit',
background: 'white',
}}
/>
) : (
<p
onClick={() => { setEditing(true); setDraft(note.body) }}
style={{
fontSize: 13.5, color: '#111827', lineHeight: 1.6, cursor: 'text',
whiteSpace: 'pre-wrap', margin: 0, wordBreak: 'break-word',
}}
>
{note.body}
</p>
)}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ fontSize: 11, color: '#9ca3af' }}>
{note.created_by_name} · {fmtDate(note.updated_at)}
</span>
<div style={{ display: 'flex', gap: 4 }}>
<button
onClick={() => onTogglePin(note.id, !note.is_pinned)}
title={note.is_pinned ? 'Αποσύνδεση' : 'Καρφίτσωμα'}
style={{
fontSize: 13, padding: '2px 7px', borderRadius: 6, border: '1px solid #e5e7eb',
background: note.is_pinned ? '#fef3c7' : 'white', cursor: 'pointer',
color: note.is_pinned ? '#d97706' : '#6b7280',
}}
>
{note.is_pinned ? '📌' : '📍'}
</button>
<button
onClick={() => { if (window.confirm('Διαγραφή σημείωσης;')) onDelete(note.id) }}
style={{
fontSize: 12, padding: '2px 7px', borderRadius: 6,
border: '1px solid #fecaca', background: 'white',
color: '#ef4444', cursor: 'pointer',
}}
>✕</button>
</div>
</div>
</div>
)
}
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
{/* New note form */}
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 12, padding: '12px 14px', background: '#fafafa' }}>
<textarea
value={newBody}
onChange={e => setNewBody(e.target.value)}
onKeyDown={onKeyDown}
placeholder="Νέα σημείωση… (Ctrl+Enter για αποθήκευση)"
style={{
width: '100%', minHeight: 72, border: 'none', outline: 'none',
background: 'transparent', fontSize: 13.5, lineHeight: 1.55,
resize: 'none', fontFamily: 'inherit', color: '#374151',
}}
/>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#6b7280', cursor: 'pointer' }}>
<input type="checkbox" checked={newPinned} onChange={e => setNewPinned(e.target.checked)} />
Καρφίτσωμα
</label>
<button
onClick={submit}
disabled={!newBody.trim()}
style={{
padding: '5px 14px', borderRadius: 7, border: 'none',
background: newBody.trim() ? '#111827' : '#e5e7eb',
color: newBody.trim() ? 'white' : '#9ca3af',
fontSize: 12.5, fontWeight: 600, cursor: newBody.trim() ? 'pointer' : 'default',
}}
>
Αποθήκευση
</button>
</div>
</div>
{/* Notes list */}
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
{pinned.length > 0 && (
<>
<div style={{ fontSize: 10, fontWeight: 700, color: '#d97706', textTransform: 'uppercase', letterSpacing: '0.06em' }}>📌 Καρφιτσωμένες</div>
{pinned.map(n => (
<NoteCard key={n.id} note={n} onSave={onSave} onDelete={onDelete} onTogglePin={onTogglePin} />
))}
</>
)}
{rest.length > 0 && (
<>
{pinned.length > 0 && <div style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 4 }}>Πρόσφατες</div>}
{rest.map(n => (
<NoteCard key={n.id} note={n} onSave={onSave} onDelete={onDelete} onTogglePin={onTogglePin} />
))}
</>
)}
{notes.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>
Δεν υπάρχουν σημειώσεις ακόμα.
</div>
)}
</div>
</div>
)
}
// ── 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 (
<div style={{
display: 'flex', alignItems: 'flex-start', gap: 10,
padding: '10px 12px', borderRadius: 10,
border: `1px solid ${todo.is_done ? '#e5e7eb' : todo.priority === 'high' ? '#fca5a5' : '#e5e7eb'}`,
background: todo.is_done ? '#fafafa' : todo.priority === 'high' ? '#fff5f5' : 'white',
opacity: todo.is_done ? 0.65 : 1,
}}>
{/* Checkbox */}
<button
onClick={() => onToggle(todo.id, !todo.is_done)}
style={{
width: 20, height: 20, borderRadius: 5, flexShrink: 0, marginTop: 1,
border: `2px solid ${todo.is_done ? '#22c55e' : todo.priority === 'high' ? '#ef4444' : '#d1d5db'}`,
background: todo.is_done ? '#22c55e' : 'white',
cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
>
{todo.is_done && <span style={{ color: 'white', fontSize: 11, lineHeight: 1 }}>✓</span>}
</button>
{/* Body */}
<div style={{ flex: 1, minWidth: 0 }}>
{editing ? (
<input
ref={inputRef}
value={draft}
onChange={e => 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',
}}
/>
) : (
<p
onClick={() => { 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 && (
<span style={{ fontSize: 11, fontWeight: 700, color: '#ef4444', marginRight: 5 }}>● ΕΠΕΙΓΟΝ</span>
)}
{todo.body}
</p>
)}
<div style={{ fontSize: 11, color: '#9ca3af', marginTop: 3 }}>
{todo.created_by_name} · {fmtDate(todo.created_at)}
{todo.is_done && todo.done_by_name && (
<span style={{ color: '#22c55e' }}> · ✓ {todo.done_by_name}</span>
)}
</div>
</div>
{/* Delete */}
<button
onClick={() => { if (window.confirm('Διαγραφή εργασίας;')) onDelete(todo.id) }}
style={{
fontSize: 11, padding: '2px 6px', borderRadius: 5, flexShrink: 0,
border: '1px solid #fecaca', background: 'white', color: '#ef4444', cursor: 'pointer',
}}
>✕</button>
</div>
)
}
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '100%' }}>
{/* New todo form */}
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 12, padding: '12px 14px', background: '#fafafa' }}>
<input
value={newBody}
onChange={e => 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',
}}
/>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
<div style={{ display: 'flex', gap: 6 }}>
{['normal', 'high'].map(p => (
<button
key={p}
onClick={() => setNewPriority(p)}
style={{
padding: '3px 10px', borderRadius: 6, fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${newPriority === p ? (p === 'high' ? '#ef4444' : '#6b7280') : '#e5e7eb'}`,
background: newPriority === p ? (p === 'high' ? '#fee2e2' : '#f3f4f6') : 'white',
color: newPriority === p ? (p === 'high' ? '#ef4444' : '#374151') : '#9ca3af',
}}
>
{p === 'high' ? '● Επείγον' : 'Κανονικό'}
</button>
))}
</div>
<button
onClick={submit}
disabled={!newBody.trim()}
style={{
padding: '5px 14px', borderRadius: 7, border: 'none',
background: newBody.trim() ? '#111827' : '#e5e7eb',
color: newBody.trim() ? 'white' : '#9ca3af',
fontSize: 12.5, fontWeight: 600, cursor: newBody.trim() ? 'pointer' : 'default',
}}
>
Προσθήκη
</button>
</div>
</div>
{/* Todo list */}
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
{undone.length === 0 && done.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', fontSize: 13, padding: '32px 0' }}>
Δεν υπάρχουν εργασίες ακόμα.
</div>
)}
{undone.map(t => (
<TodoItem key={t.id} todo={t} onToggle={onToggle} onDelete={onDelete} onEdit={onEdit} />
))}
{done.length > 0 && (
<button
onClick={() => setShowDone(s => !s)}
style={{
marginTop: 4, fontSize: 12, color: '#9ca3af', fontWeight: 600,
background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', padding: '4px 0',
}}
>
{showDone ? '▾' : '▸'} Ολοκληρωμένες ({done.length})
</button>
)}
{showDone && done.map(t => (
<TodoItem key={t.id} todo={t} onToggle={onToggle} onDelete={onDelete} onEdit={onEdit} />
))}
</div>
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Page header */}
<div style={{
padding: '18px 28px 14px',
borderBottom: '1px solid #f0f0ef',
display: 'flex', alignItems: 'baseline', gap: 16, flexShrink: 0,
background: 'white',
}}>
<span style={{ fontSize: 13, color: '#9ca3af' }}>
{notes.length} σημειώσεις · {todos.filter(t => !t.is_done).length} εκκρεμείς εργασίες
</span>
</div>
{/* Two-column body */}
<div style={{
display: 'grid', gridTemplateColumns: '1fr 1fr',
gap: 0, flex: 1, overflow: 'hidden',
}}>
{/* Left: Notes */}
<div style={{
borderRight: '1px solid #f0f0ef',
padding: '20px 24px',
display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
Σημειώσεις
</div>
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
<NotesColumn
notes={notes}
onAdd={(body, is_pinned) => 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 })}
/>
</div>
</div>
{/* Right: Todos */}
<div style={{
padding: '20px 24px',
display: 'flex', flexDirection: 'column', overflow: 'hidden',
}}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
Εργασίες
</div>
<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
<TodosColumn
todos={todos}
onAdd={(body, priority) => 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)}
/>
</div>
</div>
</div>
</div>
)
}
-295
View File
@@ -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 (
<div style={{ border: '1.5px dashed #d1d5db', borderRadius: 14, padding: '16px 20px', background: '#fafafa' }}>
<div style={{ fontSize: 12, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 14 }}>
Καταγραφή Απόβλητου
</div>
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 10, marginBottom: 10 }}>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Προϊόν *</label>
<select style={inputStyle} value={productId} onChange={e => setProductId(e.target.value)} autoFocus>
<option value="">— Επιλέξτε προϊόν —</option>
{products.map(p => (
<option key={p.id} value={p.id}>{p.name}{p.category_name ? ` (${p.category_name})` : ''}</option>
))}
</select>
</div>
<div>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>Ποσότητα *</label>
<input type="number" step="0.5" min="0.1"
style={inputStyle} value={qty} onChange={e => setQty(e.target.value)} />
</div>
</div>
<div style={{ marginBottom: 10 }}>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 6 }}>Αιτία</label>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{REASONS.map(r => (
<button key={r.id} type="button" onClick={() => setReason(r.id)}
style={{
padding: '5px 12px', borderRadius: 20, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${reason === r.id ? r.color : '#e5e7eb'}`,
background: reason === r.id ? r.color : 'white',
color: reason === r.id ? 'white' : '#6b7280',
}}>
{r.label}
</button>
))}
</div>
</div>
<div style={{ marginBottom: 14 }}>
<label style={{ fontSize: 11.5, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 4 }}>
Σημείωση <span style={{ fontWeight: 400, color: '#9ca3af' }}>(προαιρετική)</span>
</label>
<input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)}
placeholder="π.χ. Ο πελάτης επέστρεψε ελαττωματικό…" />
</div>
<button onClick={submit} disabled={!canLog || isPending}
style={{
padding: '9px 22px', borderRadius: 9, border: 'none', fontSize: 13.5, fontWeight: 700, cursor: canLog ? 'pointer' : 'default',
background: canLog ? '#111827' : '#e5e7eb', color: canLog ? 'white' : '#9ca3af',
}}>
{isPending ? 'Καταγραφή…' : '+ Καταγραφή Απόβλητου'}
</button>
</div>
)
}
// ── Waste entry row ───────────────────────────────────────────────────────────
function WasteRow({ entry, canDelete, onDelete }) {
const reasonCfg = REASONS.find(r => r.id === entry.reason) || { label: entry.reason, color: '#6b7280' }
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', border: '1px solid #f0f0ef', borderRadius: 10, background: 'white' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: '#111315', display: 'flex', alignItems: 'center', gap: 8 }}>
{entry.product_name}
<span style={{ fontSize: 13, fontWeight: 700, color: '#374151' }}>×{entry.quantity}</span>
<span style={{ fontSize: 11, fontWeight: 700, padding: '1px 7px', borderRadius: 99, background: `${reasonCfg.color}18`, color: reasonCfg.color }}>
{reasonCfg.label}
</span>
</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 2 }}>
{fmtDateTime(entry.logged_at)} · {entry.logged_by_name}
{entry.reason_notes && <span style={{ color: '#6b7280', marginLeft: 8 }}>— {entry.reason_notes}</span>}
</div>
</div>
<div style={{ textAlign: 'right', flexShrink: 0 }}>
{entry.total_cost != null ? (
<div style={{ fontSize: 13.5, fontWeight: 700, color: '#dc2626' }}>{fmt(entry.total_cost)}</div>
) : (
<div style={{ fontSize: 12, color: '#d1d5db' }}>χωρίς κόστος</div>
)}
{entry.unit_cost_snapshot != null && (
<div style={{ fontSize: 11, color: '#9ca3af' }}>{fmt(entry.unit_cost_snapshot)}/τεμ.</div>
)}
</div>
{canDelete && (
<button onClick={() => { if (window.confirm('Διαγραφή καταχώρησης;')) onDelete(entry.id) }}
style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', color: '#ef4444', fontSize: 12, cursor: 'pointer', flexShrink: 0 }}>
✕
</button>
)}
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', flexShrink: 0, background: 'white', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>
Σήμερα: {todayCount} καταχωρήσεις
{todayCost > 0 && <span style={{ color: '#dc2626', fontWeight: 600 }}> · εκτιμώμενο κόστος {todayCost.toLocaleString('el-GR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €</span>}
</p>
</div>
</div>
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px', display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* Log form */}
<LogForm products={productsData} onLog={body => logWaste.mutate(body)} isPending={logWaste.isPending} />
{/* Today's entries */}
<div>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
{activeDayId ? 'Σήμερα' : 'Τελευταίες καταχωρήσεις'}
</div>
{todayEntries.length === 0 ? (
<div style={{ textAlign: 'center', color: '#d1d5db', fontSize: 13, padding: '20px 0' }}>Καμία καταχώρηση ακόμα.</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{todayEntries.map(e => (
<WasteRow key={e.id} entry={e} canDelete={!!activeDayId} onDelete={id => deleteWaste.mutate(id)} />
))}
</div>
)}
</div>
{/* History toggle */}
<div style={{ borderTop: '1px solid #f0f0ef', paddingTop: 12 }}>
<button onClick={() => setShowHistory(s => !s)}
style={{ fontSize: 13, fontWeight: 600, color: '#6b7280', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
{showHistory ? '▾ Απόκρυψη ιστορικού' : '▸ Εμφάνιση ιστορικού'}
</button>
{showHistory && (
<div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
<div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<label style={{ fontSize: 12, color: '#6b7280', fontWeight: 600 }}>Από</label>
<input type="date" value={histFrom} onChange={e => setHistFrom(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<label style={{ fontSize: 12, color: '#6b7280', fontWeight: 600 }}>Έως</label>
<input type="date" value={histTo} onChange={e => setHistTo(e.target.value)}
style={{ padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 13, outline: 'none' }} />
</div>
<button onClick={() => refetchHist()}
style={{ padding: '5px 14px', borderRadius: 7, border: '1px solid #e5e7eb', background: 'white', fontSize: 12.5, cursor: 'pointer', color: '#374151', fontWeight: 500 }}>
Αναζήτηση
</button>
</div>
{histEntries.length === 0 ? (
<div style={{ color: '#d1d5db', fontSize: 13, padding: '12px 0' }}>Δεν βρέθηκαν καταχωρήσεις.</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{histEntries.map(e => (
<WasteRow key={e.id} entry={e} canDelete={false} onDelete={() => {}} />
))}
<div style={{ fontSize: 12.5, color: '#6b7280', fontWeight: 600, paddingLeft: 4 }}>
{histEntries.length} καταχωρήσεις · εκτιμώμενο κόστος{' '}
<span style={{ color: '#dc2626' }}>
{histEntries.reduce((s, e) => s + (e.total_cost || 0), 0).toLocaleString('el-GR', { minimumFractionDigits: 2 })} €
</span>
</div>
</div>
)}
</div>
)}
</div>
</div>
</div>
)
}
@@ -1 +0,0 @@
export { default } from '../CustomersPage'
@@ -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 (
<Dialog open size="lg" onClose={onClose} title={c.nickname ? `${c.name} «${c.nickname}»` : c.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('customers.back')}</Button>
<Button icon={<Pencil size={14} />} onClick={onEdit}>{t('customers.edit')}</Button>
</>}>
<div className="grid gap-4" data-testid="customer-card">
<div className="grid grid-cols-3 gap-2">
{[['visits', fmt.formatNumber(c.visit_count)], ['spent', fmt.formatMoney(c.total_spent)], ['perVisit', avg != null ? fmt.formatMoney(avg) : '—']].map(([k, v]) => (
<div key={k} className="rounded-card bg-surface-2 p-3 grid gap-0.5 text-center">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`customers.${k}`)}</span>
<span className="text-body font-semibold tabular-nums text-ink">{v}</span>
</div>
))}
</div>
{openTab && (
<div className="rounded-card border border-danger bg-danger-soft p-3 flex flex-wrap items-center justify-between gap-2" data-testid="customer-tab">
<span className="grid">
<span className="font-semibold text-danger-ink">{t('customers.owes')}</span>
<span className="text-caption text-ink-2">{t('customers.owesSub', { date: fmt.formatDate(openTab.opened_at), paid: fmt.formatMoney(openTab.total_paid) })}</span>
</span>
<span className="text-title font-semibold tabular-nums text-danger-ink">{fmt.formatMoney(openTab.balance)}</span>
</div>
)}
{(c.phone || c.email) && (
<div className="flex flex-wrap gap-4 text-body">
{c.phone && <a href={`tel:${c.phone.replace(/\s/g, '')}`} className="inline-flex items-center gap-1.5 text-accent-ink hover:underline"><Phone size={15} aria-hidden="true" />{c.phone}</a>}
{c.email && <a href={`mailto:${c.email}`} className="inline-flex items-center gap-1.5 text-accent-ink hover:underline"><Mail size={15} aria-hidden="true" />{c.email}</a>}
</div>
)}
{c.notes && <p className="rounded-card bg-warning-soft text-warning-ink p-3 text-label whitespace-pre-wrap">{c.notes}</p>}
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('customers.history')}</h3>
{isPending ? <Spinner /> : !data?.length ? <p className="text-label text-ink-3">{t('customers.noVisits')}</p> : (
<ul className="divide-y divide-line">
{data.map(o => (
<li key={o.id} className="py-2 flex flex-wrap items-center gap-2 text-label">
<span className="grid flex-1 min-w-40">
<span className="text-ink font-semibold">
{o.table_name ? t('customers.atTable', { table: o.table_name }) : t(`customers.orderType.${o.order_type}`, { defaultValue: t('customers.noTable') })}
</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(o.opened_at, 'datetimeShort')} · {t('customers.items', { count: o.item_count })}</span>
</span>
{o.on_tab > 0 && <Pill tone="warning">{t('customers.onTab', { amount: fmt.formatMoney(o.on_tab) })}</Pill>}
<Pill tone={ORDER_TONE[o.status] ?? 'neutral'}>{t(`customers.orderStatus.${o.status}`, { defaultValue: o.status })}</Pill>
<b className="tabular-nums w-20 text-right">{fmt.formatMoney(o.total)}</b>
</li>
))}
</ul>
)}
</section>
</div>
</Dialog>
)
}
@@ -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 (
<Dialog open size="md" onClose={onClose} title={isNew ? t('customers.newTitle') : customer.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('customers.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="customer-save">{isNew ? t('customers.add') : t('customers.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="customer-dialog">
<Field label={t('customers.name')} required error={err('name')}>
<Input value={form.name} autoFocus onChange={e => set('name', e.target.value)} data-testid="customer-name" />
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('customers.nickname')} hint={t('customers.nicknameHint')}>
<Input value={form.nickname} onChange={e => set('nickname', e.target.value)} />
</Field>
<Field label={t('customers.phone')} hint={t('customers.phoneHint')}>
<Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} data-testid="customer-phone" />
</Field>
</div>
<Field label={t('customers.email')} error={err('email')}>
<Input type="email" value={form.email} onChange={e => set('email', e.target.value)} />
</Field>
<Field label={t('customers.notes')} hint={t('customers.notesHint')}>
<Textarea rows={3} value={form.notes} onChange={e => set('notes', e.target.value)} data-testid="customer-notes" />
</Field>
</div>
</Dialog>
)
}
@@ -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 => (
<span className="flex items-center gap-2">
<Avatar name={c.name} size="sm" />
<span className="grid">
<span className="font-semibold text-ink">{c.name}{c.nickname && <span className="font-normal text-ink-2"> «{c.nickname}»</span>}</span>
{c.notes && <span className="text-caption text-ink-2 line-clamp-1">{c.notes}</span>}
</span>
</span>) },
{ key: 'phone', label: t('customers.phone'), render: c => (c.phone ? <a href={`tel:${c.phone.replace(/\s/g, '')}`} onClick={ev => ev.stopPropagation()} className="text-accent-ink hover:underline">{c.phone}</a> : '') },
{ 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 => (
<span className="flex justify-end gap-0.5">
<IconButton size="sm" variant="ghost" label={t('customers.editOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'edit', customer: c }))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('customers.removeOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'remove', customer: c }))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="customers-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('customers.title')}</h1>
<p className="text-label text-ink-2">{t('customers.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="customer-new">{t('customers.new')}</Button>
</header>
<div className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('customers.search')} aria-label={t('customers.search')} className="pl-9" data-testid="customer-search" />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length && !search ? <EmptyState icon={<Users size={28} />} title={t('customers.none')} description={t('customers.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={c => setDialog({ kind: 'card', customer: c })} rowTestId="customer-row"
empty={t('customers.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <CustomerDialog customer={dialog.customer} onClose={close} onSaved={saved} />}
{dialog?.kind === 'card' && <CustomerCard customer={dialog.customer} onClose={close} onEdit={() => setDialog({ kind: 'edit', customer: dialog.customer })} />}
{dialog?.kind === 'remove' && (
<Dialog open size="sm" onClose={close} title={t('customers.removeTitle', { name: dialog.customer.name })} description={t('customers.removeBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('customers.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.customer)}>{t('customers.removeYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,29 @@
// The rules of CRM → Customers (plan step 6.13b), unit-tested in tests/crm.test.mjs. The backend
// checks the same (routers/customers.py) and does the search (case and Greek accents ignored).
export function customerForm(c) {
return { name: c?.name ?? '', nickname: c?.nickname ?? '', phone: c?.phone ?? '', email: c?.email ?? '', notes: c?.notes ?? '' }
}
export function customerProblems(form) {
const out = []
if (!form.name.trim()) out.push('name')
if (form.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) out.push('email')
return out
}
/** Empty fields are sent as null, so clearing a phone number clears it. */
export function customerBody(form) {
const v = k => form[k].trim() || null
return { name: form.name.trim(), nickname: v('nickname'), phone: v('phone'), email: v('email'), notes: v('notes') }
}
/** Their average per visit, or null. */
export function perVisit(c) {
return c.visit_count > 0 ? Math.round((c.total_spent / c.visit_count) * 100) / 100 : null
}
/** The name with the nickname, as the lists show it. */
export function customerLabel(c) {
return c.nickname ? `${c.name} «${c.nickname}»` : c.name
}
@@ -1,11 +1,14 @@
// Inventory → Stock (plan step 6.13b): not built yet. The page says so, and where the costs and
// throwaways are kept meanwhile. Stock levels need the owner's decisions first (units, counting).
import { Boxes } from 'lucide-react' import { Boxes } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { EmptyState } from '@xenia/ui'
export default function StockPage() { export default function StockPage() {
const { t } = useTranslation('manager')
return ( return (
<div className="flex flex-col items-center justify-center h-full text-center gap-3 text-slate-400"> <div className="h-full grid place-items-center p-6" data-testid="stock-page">
<Boxes size={36} className="opacity-40" /> <EmptyState icon={<Boxes size={32} />} title={t('stock.title')} description={t('stock.soon')} />
<p className="text-[15px] font-semibold text-slate-500">Stock Management</p>
<p className="text-[13px]">Coming soon — manage item stock volumes here.</p>
</div> </div>
) )
} }
@@ -1 +1,163 @@
export { default } from '../WastePage' // Inventory → Throwaways (plan step 6.13b; replaces the v1 WastePage): log what was thrown away
// (a product, how many, why, a note), with its cost at that moment when the product has a cost,
// in the open business day. Today's entries (deletable today only) and the history of a period:
// totals, by reason, by product, every entry. Live: `waste.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { BarList } from '../reports/kit/charts'
import { PeriodPicker } from '../reports/kit/Period'
import { Panel, Stat, Table } from '../reports/kit/parts'
import { defaultPeriod } from '../reports/kit/reportLogic'
import { REASONS, REASON_TONE, wasteProducts, wasteQuantity, wasteTotals } from './wasteLogic'
const LIVE = ['waste.changed']
export default function ThrowawaysPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [removing, setRemoving] = useState(null)
const { data: day } = useLiveQuery({ queryKey: ['business-day'], queryFn: () => client.get('/api/business-day/current').then(r => r.data), refetchInterval: 60_000 })
const dayId = day?.id ?? null
const today = useLiveQuery({
queryKey: ['waste', 'day', dayId], enabled: !!dayId, events: LIVE,
queryFn: () => client.get('/api/waste/', { params: { business_day_id: dayId } }).then(r => r.data.entries),
})
const params = { ...(period.from ? { date_from: period.from } : {}), ...(period.to ? { date_to: period.to } : {}) }
const history = useLiveQuery({ queryKey: ['waste', 'period', params], events: LIVE, queryFn: () => client.get('/api/waste/', { params }).then(r => r.data.entries) })
const todayRows = today.data ?? []
const rows = history.data ?? []
const totals = wasteTotals(todayRows)
const periodTotals = wasteTotals(rows)
const remove = useMutation({
mutationFn: e => client.delete(`/api/waste/${e.id}`),
onSuccess: () => { toast.success(t('waste.deleted')); setRemoving(null); today.refetch(); history.refetch() },
onError: err => toast.error(errorMessage(err, t)),
})
const reason = r => t(`waste.reasons.${r}`, { defaultValue: r })
const group = (key, label) => Object.values(rows.reduce((m, e) => {
const k = e[key]
m[k] = m[k] ?? { key: k, label: label(e), value: 0, count: 0 }
m[k].value += e.total_cost ?? 0
m[k].count += key === 'reason' ? 1 : e.quantity
return m
}, {})).sort((a, b) => b.value - a.value || b.count - a.count)
const columns = (deletable) => [
{ key: 'logged_at', label: t('waste.when'), render: e => fmt.formatDateTime(e.logged_at, 'datetimeShort') },
{ key: 'product_name', label: t('waste.product'), render: e => <span className="font-semibold text-ink">{e.product_name}</span> },
{ key: 'quantity', label: t('waste.quantity'), align: 'right', render: e => fmt.formatNumber(e.quantity, { maxDecimals: 3 }) },
{ key: 'reason', label: t('waste.reason'), sort: e => reason(e.reason), render: e => (
<span className="grid gap-0.5"><Pill tone={REASON_TONE[e.reason] ?? 'neutral'} className="justify-self-start">{reason(e.reason)}</Pill>
{e.reason_notes && <span className="text-caption text-ink-2">{e.reason_notes}</span>}</span>) },
{ key: 'logged_by_name', label: t('waste.by') },
{ key: 'total_cost', label: t('waste.cost'), align: 'right', render: e => (e.total_cost != null ? fmt.formatMoney(e.total_cost) : <span className="text-ink-3">{t('waste.noCost')}</span>) },
...(deletable ? [{ key: 'del', label: '', sort: false, render: e => (
<IconButton size="sm" variant="ghost" label={t('waste.deleteOf', { name: e.product_name })} onClick={() => setRemoving(e)}><Trash2 size={15} /></IconButton>) }] : []),
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="waste-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('waste.title')}</h1>
<p className="text-label text-ink-2">{t('waste.subtitle')}</p>
</header>
<LogForm onLogged={() => { today.refetch(); history.refetch() }} dayOpen={!!dayId} />
<Panel padded={false} title={t('waste.today')} testId="waste-today"
actions={<span className="text-label text-ink-2">{t('waste.todaySum', { count: totals.count, cost: fmt.formatMoney(totals.cost) })}</span>}>
{!dayId ? <p className="p-4 text-label text-ink-3">{t('waste.noDay')}</p>
: today.isPending ? <div className="p-4"><Spinner /></div>
: <Table columns={columns(true)} rows={todayRows} rowTestId="waste-today-row" empty={t('waste.noneToday')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
</Panel>
<h2 className="text-body font-semibold text-ink mt-2">{t('waste.history')}</h2>
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} />
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('waste.cost')} tone={periodTotals.cost ? 'danger' : undefined} value={fmt.formatMoney(periodTotals.cost)}
sub={periodTotals.uncosted ? t('waste.uncosted', { count: periodTotals.uncosted }) : undefined} testId="waste-period-cost" />
<Stat label={t('waste.entries')} value={fmt.formatNumber(periodTotals.count)} />
</div>
{rows.length > 0 && (
<div className="grid gap-4 lg:grid-cols-2">
<Panel title={t('waste.byReason')}>
<BarList format={v => fmt.formatMoney(v)} rows={group('reason', e => reason(e.reason)).map(g => ({ ...g, sub: t('waste.times', { count: g.count }) }))} />
</Panel>
<Panel title={t('waste.byProduct')}>
<BarList format={v => fmt.formatMoney(v)} rows={group('product_id', e => e.product_name).slice(0, 10).map(g => ({ ...g, sub: t('waste.units', { qty: fmt.formatNumber(g.count, { maxDecimals: 3 }) }) }))} />
</Panel>
</div>
)}
<Panel padded={false} title={t('waste.every')}>
{history.isPending ? <div className="p-4"><Spinner /></div>
: <Table columns={columns(false)} rows={rows} rowTestId="waste-row" empty={t('waste.noneInPeriod')} initialSort={{ key: 'logged_at', dir: 'desc' }} />}
</Panel>
</div>
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('waste.deleteTitle', { name: removing.product_name })}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('waste.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing)}>{t('waste.deleteYes')}</Button>
</>} />
)}
</div>
)
}
function LogForm({ onLogged, dayOpen }) {
const { t, i18n } = useTranslation('manager')
const fmt = useFormat()
const [form, setForm] = useState({ product_id: '', qty: '1', reason: 'kitchen_error', notes: '' })
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const { data: products = [] } = useLiveQuery({ queryKey: ['products', 'all'], queryFn: () => client.get('/api/products/').then(r => r.data), staleTime: 300_000 })
const qty = wasteQuantity(form.qty)
const log = useMutation({
mutationFn: () => client.post('/api/waste/', { product_id: Number(form.product_id), quantity: qty, reason: form.reason, reason_notes: form.notes.trim() || null }).then(r => r.data),
onSuccess: e => {
toast.success(e.total_cost != null ? t('waste.loggedCost', { name: e.product_name, cost: fmt.formatMoney(e.total_cost) }) : t('waste.logged', { name: e.product_name }))
setForm(f => ({ ...f, product_id: '', qty: '1', notes: '' })); setTried(false); onLogged()
},
onError: err => toast.error(errorMessage(err, t)),
})
const submit = () => { setTried(true); if (form.product_id && qty != null) log.mutate() }
return (
<Panel title={t('waste.log')} testId="waste-form">
<div className="grid gap-3">
<div className="grid gap-3 sm:grid-cols-[2fr_1fr]">
<Field label={t('waste.product')} required error={tried && !form.product_id ? t('waste.pickProduct') : undefined}>
<Select value={form.product_id} onChange={e => set('product_id', e.target.value)} data-testid="waste-product"
options={[{ value: '', label: t('waste.choose') }, ...wasteProducts(products, i18n.language).map(p => ({ value: String(p.id), label: p.name }))]} />
</Field>
<Field label={t('waste.quantity')} required error={tried && qty == null ? t('waste.wrongQty') : undefined}>
<Input inputMode="decimal" value={form.qty} onChange={e => set('qty', e.target.value)} data-testid="waste-qty" />
</Field>
</div>
<Field label={t('waste.reason')}>
<span className="flex flex-wrap gap-1" role="radiogroup" aria-label={t('waste.reason')}>
{REASONS.map(r => (
<Button key={r} size="sm" variant={form.reason === r ? 'primary' : 'secondary'} role="radio" aria-checked={form.reason === r} onClick={() => set('reason', r)}>
{t(`waste.reasons.${r}`)}
</Button>
))}
</span>
</Field>
<Field label={t('waste.note')}>
<Input value={form.notes} onChange={e => set('notes', e.target.value)} placeholder={t('waste.noteHint')} />
</Field>
<div className="flex flex-wrap items-center gap-3">
<Button icon={<Plus size={16} />} loading={log.isPending} onClick={submit} data-testid="waste-log">{t('waste.logIt')}</Button>
{!dayOpen && <span className="text-caption text-ink-3">{t('waste.noDayHint')}</span>}
</div>
</div>
</Panel>
)
}
@@ -0,0 +1,27 @@
// The rules of Inventory → Throwaways (plan step 6.13b), unit-tested in tests/crm.test.mjs.
// As routers/waste.py VALID_REASONS; texts are manager `waste.reasons.*`.
import { parseNumber } from '@xenia/i18n/number' // plain JS: Node tests import this file
export const REASONS = ['kitchen_error', 'dropped', 'expired', 'other']
export const REASON_TONE = { kitchen_error: 'danger', dropped: 'warning', expired: 'accent', other: 'neutral' }
/** A typed quantity (comma or dot) above zero, or null. */
export function wasteQuantity(text) {
const v = parseNumber(String(text ?? ''), { decimals: 3, allowNegative: false })
return v > 0 ? v : null
}
/** Totals of a list of entries: how many, their known cost, how many have no cost. */
export function wasteTotals(entries) {
return {
count: entries.length,
cost: Math.round(entries.reduce((s, e) => s + (e.total_cost ?? 0), 0) * 100) / 100,
uncosted: entries.filter(e => e.total_cost == null).length,
}
}
/** Products for the form: available ones, by name in the language's order. */
export function wasteProducts(products, lang = 'en') {
return products.filter(p => p.is_available !== false && !p.system_key)
.sort((a, b) => a.name.localeCompare(b.name, lang))
}
@@ -0,0 +1,199 @@
// Notes and to-dos (plan step 6.13b; replaces the v1 NotesPage): the managers' shared notes
// (pinned ones first; tap to edit, Ctrl+Enter saves, Esc cancels) and to-dos (urgent first; tick
// when done, who did it is kept; the done ones folded away). The overview's notes card shows the
// same. Live: `notes.changed`.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Check, ChevronDown, Pin, PinOff, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Input, Switch, Textarea, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Panel } from '../reports/kit/parts'
import { splitNotes, splitTodos } from './notesLogic'
const LIVE = ['notes.changed']
function useChange() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
return (fn, done) => ({
mutationFn: fn,
onSuccess: () => { qc.invalidateQueries({ queryKey: ['notes'] }); qc.invalidateQueries({ queryKey: ['todos'] }); if (done) toast.success(done) },
onError: err => toast.error(errorMessage(err, t)),
})
}
export default function NotesPage() {
const { t } = useTranslation('manager')
const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), events: LIVE })
const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), events: LIVE })
const [removing, setRemoving] = useState(null) // { kind: 'note' | 'todo', item }
const change = useChange()
const remove = useMutation(change(({ kind, item }) => client.delete(kind === 'note' ? `/api/notes/${item.id}` : `/api/notes/todos/${item.id}`), t('notes.deleted')))
const { pinned, rest } = splitNotes(notes)
const { open, done } = splitTodos(todos)
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="notes-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('notes.title')}</h1>
<p className="text-label text-ink-2">{t('notes.subtitle', { notes: notes.length, todos: open.length })}</p>
</header>
<div className="grid gap-4 lg:grid-cols-2 items-start">
<Panel title={t('notes.notes')} testId="notes-column">
<div className="grid gap-3">
<NewNote />
{pinned.length > 0 && <Label>{t('notes.pinned')}</Label>}
{pinned.map(n => <NoteCard key={n.id} note={n} onDelete={() => setRemoving({ kind: 'note', item: n })} />)}
{pinned.length > 0 && rest.length > 0 && <Label>{t('notes.others')}</Label>}
{rest.map(n => <NoteCard key={n.id} note={n} onDelete={() => setRemoving({ kind: 'note', item: n })} />)}
{!notes.length && <p className="text-label text-ink-3">{t('notes.noNotes')}</p>}
</div>
</Panel>
<Panel title={t('notes.todos')} testId="todos-column">
<div className="grid gap-2">
<NewTodo />
{open.map(x => <TodoRow key={x.id} todo={x} onDelete={() => setRemoving({ kind: 'todo', item: x })} />)}
{!todos.length && <p className="text-label text-ink-3">{t('notes.noTodos')}</p>}
{done.length > 0 && <DoneTodos done={done} onDelete={x => setRemoving({ kind: 'todo', item: x })} />}
</div>
</Panel>
</div>
</div>
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t(removing.kind === 'note' ? 'notes.deleteNote' : 'notes.deleteTodo')}
description={removing.item.body.length > 120 ? `${removing.item.body.slice(0, 120)}…` : removing.item.body}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('notes.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing, { onSuccess: () => setRemoving(null) })} data-testid="notes-delete-confirm">{t('notes.deleteYes')}</Button>
</>} />
)}
</div>
)
}
function Label({ children }) {
return <span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{children}</span>
}
function NewNote() {
const { t } = useTranslation('manager')
const [body, setBody] = useState('')
const [pin, setPin] = useState(false)
const change = useChange()
const add = useMutation(change(() => client.post('/api/notes/', { body: body.trim(), is_pinned: pin })))
const submit = () => { if (body.trim()) add.mutate(undefined, { onSuccess: () => { setBody(''); setPin(false) } }) }
return (
<div className="grid gap-2 rounded-card border border-dashed border-line p-3">
<Textarea rows={3} value={body} onChange={e => setBody(e.target.value)} placeholder={t('notes.newNote')} aria-label={t('notes.newNote')}
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }} data-testid="note-new" />
<div className="flex items-center gap-3">
<Switch checked={pin} onChange={setPin} label={t('notes.pinIt')} />
<span className="flex-1" />
<Button size="sm" icon={<Plus size={14} />} disabled={!body.trim()} loading={add.isPending} onClick={submit} data-testid="note-add">{t('notes.addNote')}</Button>
</div>
</div>
)
}
function NoteCard({ note, onDelete }) {
const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const [draft, setDraft] = useState(null)
const change = useChange()
const save = useMutation(change(body => client.put(`/api/notes/${note.id}`, body)))
const finish = () => {
const text = draft?.trim()
if (text && text !== note.body) save.mutate({ body: text })
setDraft(null)
}
return (
<div className={cx('rounded-card border p-3 grid gap-2', note.is_pinned ? 'border-warning bg-warning-soft' : 'border-line bg-surface')} data-testid="note-card">
{draft != null ? (
<Textarea rows={4} autoFocus value={draft} onChange={e => setDraft(e.target.value)} onBlur={finish} aria-label={t('notes.edit')}
onKeyDown={e => { if (e.key === 'Escape') setDraft(null); if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) finish() }} />
) : (
<button type="button" className="text-left text-body text-ink whitespace-pre-wrap break-words" onClick={() => setDraft(note.body)} title={t('notes.tapToEdit')}>{note.body}</button>
)}
<div className="flex items-center gap-2">
<span className="flex-1 text-caption text-ink-3">{note.created_by_name} · {formatDateTime(note.updated_at ?? note.created_at, 'datetimeShort')}</span>
<IconButton size="sm" variant="ghost" label={t(note.is_pinned ? 'notes.unpin' : 'notes.pin')} onClick={() => save.mutate({ is_pinned: !note.is_pinned })}>
{note.is_pinned ? <PinOff size={15} /> : <Pin size={15} />}
</IconButton>
<IconButton size="sm" variant="ghost" label={t('notes.deleteNote')} onClick={onDelete}><Trash2 size={15} /></IconButton>
</div>
</div>
)
}
function NewTodo() {
const { t } = useTranslation('manager')
const [body, setBody] = useState('')
const [urgent, setUrgent] = useState(false)
const change = useChange()
const add = useMutation(change(() => client.post('/api/notes/todos', { body: body.trim(), priority: urgent ? 'high' : 'normal' })))
const submit = () => { if (body.trim()) add.mutate(undefined, { onSuccess: () => { setBody(''); setUrgent(false) } }) }
return (
<div className="grid gap-2 rounded-card border border-dashed border-line p-3">
<Input value={body} onChange={e => setBody(e.target.value)} placeholder={t('notes.newTodo')} aria-label={t('notes.newTodo')}
onKeyDown={e => { if (e.key === 'Enter') submit() }} data-testid="todo-new" />
<div className="flex items-center gap-3">
<Switch checked={urgent} onChange={setUrgent} label={t('notes.urgent')} />
<span className="flex-1" />
<Button size="sm" icon={<Plus size={14} />} disabled={!body.trim()} loading={add.isPending} onClick={submit} data-testid="todo-add">{t('notes.addTodo')}</Button>
</div>
</div>
)
}
function TodoRow({ todo, onDelete }) {
const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const [draft, setDraft] = useState(null)
const change = useChange()
const save = useMutation(change(body => client.put(`/api/notes/todos/${todo.id}`, body)))
const finish = () => {
const text = draft?.trim()
if (text && text !== todo.body) save.mutate({ body: text })
setDraft(null)
}
const urgent = todo.priority === 'high' && !todo.is_done
return (
<div className={cx('flex items-start gap-3 rounded-card border p-2.5', urgent ? 'border-danger bg-danger-soft' : 'border-line bg-surface', todo.is_done && 'opacity-70')} data-testid="todo-row">
<button type="button" role="checkbox" aria-checked={todo.is_done} aria-label={t(todo.is_done ? 'notes.undo' : 'notes.markDone', { what: todo.body })}
onClick={() => save.mutate({ is_done: !todo.is_done })} data-testid="todo-done"
className={cx('mt-0.5 w-5 h-5 shrink-0 rounded border-2 grid place-items-center', todo.is_done ? 'bg-success border-success text-success-fg' : urgent ? 'border-danger' : 'border-line')}>
{todo.is_done && <Check size={13} aria-hidden="true" />}
</button>
<span className="flex-1 min-w-0 grid gap-0.5">
{draft != null ? (
<Input autoFocus value={draft} onChange={e => setDraft(e.target.value)} onBlur={finish} aria-label={t('notes.edit')}
onKeyDown={e => { if (e.key === 'Enter') finish(); if (e.key === 'Escape') setDraft(null) }} />
) : (
<button type="button" disabled={todo.is_done} onClick={() => setDraft(todo.body)} className={cx('text-left text-body break-words', todo.is_done ? 'line-through text-ink-3' : 'text-ink')}>
{urgent && <span className="text-caption font-semibold text-danger-ink mr-1.5">{t('notes.urgentTag')}</span>}{todo.body}
</button>
)}
<span className="text-caption text-ink-3">
{todo.created_by_name} · {formatDateTime(todo.created_at, 'datetimeShort')}
{todo.is_done && todo.done_by_name && <span className="text-success-ink"> · {t('notes.doneBy', { name: todo.done_by_name, time: formatDateTime(todo.done_at, 'datetimeShort') })}</span>}
</span>
</span>
<IconButton size="sm" variant="ghost" label={t('notes.deleteTodo')} onClick={onDelete}><Trash2 size={15} /></IconButton>
</div>
)
}
function DoneTodos({ done, onDelete }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
return (<>
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} className="flex items-center gap-1 text-label font-semibold text-ink-2 hover:text-ink mt-1" data-testid="todos-done-toggle">
<ChevronDown size={15} className={cx('transition-transform', open && 'rotate-180')} aria-hidden="true" />{t('notes.doneCount', { count: done.length })}
</button>
{open && done.map(x => <TodoRow key={x.id} todo={x} onDelete={() => onDelete(x)} />)}
</>)
}
@@ -0,0 +1,15 @@
// The order of the Notes page (plan step 6.13b), unit-tested in tests/crm.test.mjs.
/** Pinned notes first, then the rest; each newest-edited first. */
export function splitNotes(notes) {
const newest = (a, b) => String(b.updated_at ?? b.created_at).localeCompare(String(a.updated_at ?? a.created_at))
return { pinned: notes.filter(n => n.is_pinned).sort(newest), rest: notes.filter(n => !n.is_pinned).sort(newest) }
}
/** To-dos not done (urgent first, then newest) and done ones (most recently done first). */
export function splitTodos(todos) {
const open = todos.filter(t => !t.is_done).sort((a, b) => (a.priority === 'high' ? 0 : 1) - (b.priority === 'high' ? 0 : 1)
|| String(b.created_at).localeCompare(String(a.created_at)))
const done = todos.filter(t => t.is_done).sort((a, b) => String(b.done_at ?? '').localeCompare(String(a.done_at ?? '')))
return { open, done }
}
@@ -16,8 +16,8 @@ export default function NotesCard() {
const navigate = useNavigate() const navigate = useNavigate()
const timer = useRef(null) const timer = useRef(null)
const [preview, setPreview] = useState(false) const [preview, setPreview] = useState(false)
const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), refetchInterval: 60_000 }) const { data: notes = [] } = useLiveQuery({ queryKey: ['notes'], queryFn: () => client.get('/api/notes/').then(r => r.data), events: ['notes.changed'] })
const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), refetchInterval: 60_000 }) const { data: todos = [] } = useLiveQuery({ queryKey: ['todos'], queryFn: () => client.get('/api/notes/todos').then(r => r.data), events: ['notes.changed'] })
const items = notesPreview(notes, todos) const items = notesPreview(notes, todos)
const pinned = notes.filter(n => n.is_pinned).length const pinned = notes.filter(n => n.is_pinned).length
@@ -11,7 +11,7 @@ import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { BarChart3, Eye, EyeOff, Lock, Play, Power } from 'lucide-react' import { BarChart3, Eye, EyeOff, Lock, Play, Power } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useModule } from '@xenia/access' import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui' import { Button, Dialog, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
@@ -44,7 +44,8 @@ export default function OverviewPage() {
const navigate = useNavigate() const navigate = useNavigate()
const qc = useQueryClient() const qc = useQueryClient()
const license = useContext(LicenseContext) const license = useContext(LicenseContext)
const notesOn = useModule('notes') const notesModule = useModule('notes')
const notesOn = useCan('notes.use') && notesModule // what /api/notes checks (6.13b)
const bookingsOn = useModule('reservations') const bookingsOn = useModule('reservations')
const chatOn = useModule('chat') const chatOn = useModule('chat')
+4 -4
View File
@@ -42,7 +42,7 @@ export const NAV = [
group: 'crm', icon: BookUser, label: 'nav.crm', group: 'crm', icon: BookUser, label: 'nav.crm',
children: [ children: [
{ to: '/crm/contacts', icon: BookUser, label: 'nav.contacts', module: 'expenses', perm: 'expenses.manage' }, { to: '/crm/contacts', icon: BookUser, label: 'nav.contacts', module: 'expenses', perm: 'expenses.manage' },
{ to: '/crm/customers', icon: Users, label: 'nav.customers', module: 'crm', perm: DASH }, { to: '/crm/customers', icon: Users, label: 'nav.customers', module: 'crm', perm: 'crm.manage' },
], ],
}, },
{ {
@@ -70,14 +70,14 @@ export const NAV = [
{ to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' }, { to: '/management/schedule', icon: CalendarDays, label: 'nav.schedule', module: 'staff_planning', perm: 'core.staff.manage' },
{ to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' }, { to: '/management/prep-zones', icon: CookingPot, label: 'nav.prepZones', module: 'catalog', perm: 'catalog.menu.manage' },
{ to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'pricing.manage' }, { to: '/management/pricing', icon: Percent, label: 'nav.pricing', module: 'pricing', perm: 'pricing.manage' },
{ to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: DASH }, { to: '/notes', icon: StickyNote, label: 'nav.notes', module: 'notes', perm: 'notes.use' },
], ],
}, },
{ {
group: 'inventory', icon: Boxes, label: 'nav.inventory', group: 'inventory', icon: Boxes, label: 'nav.inventory',
children: [ children: [
{ to: '/inventory/throwaways', icon: Trash2, label: 'nav.waste', module: 'inventory', perm: DASH }, { to: '/inventory/throwaways', icon: Trash2, label: 'nav.waste', module: 'inventory', perm: 'inventory.manage' },
{ to: '/inventory/stock', icon: Boxes, label: 'nav.stock', module: 'inventory', perm: DASH, placeholder: true }, { to: '/inventory/stock', icon: Boxes, label: 'nav.stock', module: 'inventory', perm: 'inventory.manage', placeholder: true },
], ],
}, },
], ],
+37
View File
@@ -0,0 +1,37 @@
// Customers, throwaways and notes as plain data (plan step 6.13b).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { customerBody, customerForm, customerLabel, customerProblems, perVisit } from '../src/pages/customers/customersLogic.js'
import { wasteProducts, wasteQuantity, wasteTotals } from '../src/pages/inventory/wasteLogic.js'
import { splitNotes, splitTodos } from '../src/pages/notes/notesLogic.js'
test('a customer: a name needed, a wrong e-mail caught, empty fields cleared', () => {
const f = customerForm(null)
assert.deepEqual(customerProblems(f), ['name'])
assert.deepEqual(customerProblems({ ...f, name: 'Γιώργος', email: 'x@' }), ['email'])
assert.deepEqual(customerBody({ ...f, name: ' Γιώργος ', nickname: ' ', phone: '697' }), { name: 'Γιώργος', nickname: null, phone: '697', email: null, notes: null })
assert.equal(customerLabel({ name: 'Kostas', nickname: 'Big K' }), 'Kostas «Big K»')
assert.equal(perVisit({ visit_count: 3, total_spent: 50 }), 16.67)
assert.equal(perVisit({ visit_count: 0, total_spent: 0 }), null)
})
test('throwaways: quantities with a comma, totals, the products offered', () => {
assert.equal(wasteQuantity('1,5'), 1.5)
assert.equal(wasteQuantity('0'), null)
assert.equal(wasteQuantity('x'), null)
assert.deepEqual(wasteTotals([{ total_cost: 2.5 }, { total_cost: null }, { total_cost: 1.25 }]), { count: 3, cost: 3.75, uncosted: 1 })
const products = [{ name: 'Σουβλάκι' }, { name: 'Απλή πίτα' }, { name: 'Off', is_available: false }, { name: 'Delivery', system_key: 'delivery_fee' }]
assert.deepEqual(wasteProducts(products, 'el').map(p => p.name), ['Απλή πίτα', 'Σουβλάκι'])
})
test('notes: pinned first; to-dos: urgent first, done apart', () => {
const { pinned, rest } = splitNotes([
{ id: 1, is_pinned: false, updated_at: '2026-11-19T10:00:00Z' }, { id: 2, is_pinned: true, updated_at: '2026-11-18T10:00:00Z' },
{ id: 3, is_pinned: false, updated_at: '2026-11-19T11:00:00Z' }])
assert.deepEqual([pinned.map(n => n.id), rest.map(n => n.id)], [[2], [3, 1]])
const { open, done } = splitTodos([
{ id: 1, is_done: false, priority: 'normal', created_at: '2026-11-19T12:00:00Z' },
{ id: 2, is_done: false, priority: 'high', created_at: '2026-11-18T12:00:00Z' },
{ id: 3, is_done: true, priority: 'high', done_at: '2026-11-19T09:00:00Z' }])
assert.deepEqual([open.map(t => t.id), done.map(t => t.id)], [[2, 1], [3]])
})
+2 -2
View File
@@ -1,9 +1,9 @@
{ {
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [ "paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports", "src/pages/finance" "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes"
], ],
"strict": [ "strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses", "src/pages/finance" "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses", "src/pages/finance", "src/pages/customers", "src/pages/inventory", "src/pages/notes"
] ]
} }
+143
View File
@@ -3261,5 +3261,148 @@
"forgiveYes": "Χάρισμα", "forgiveYes": "Χάρισμα",
"forgiven": "{{name}}: χαρίστηκαν {{amount}}" "forgiven": "{{name}}: χαρίστηκαν {{amount}}"
} }
},
"customers": {
"title": "Πελάτες",
"subtitle": "Οι τακτικοί πελάτες του καταστήματος: τι τους αρέσει, πόσο συχνά έρχονται, πόσα ξοδεύουν.",
"new": "Νέος πελάτης",
"newTitle": "Νέος πελάτης",
"add": "Προσθήκη πελάτη",
"save": "Αποθήκευση",
"back": "Πίσω",
"edit": "Επεξεργασία",
"search": "Αναζήτηση: όνομα, παρατσούκλι, τηλέφωνο, email ή σημειώσεις",
"name": "Όνομα",
"nickname": "Παρατσούκλι",
"nicknameHint": "Πώς τον ξέρει το προσωπικό.",
"phone": "Τηλέφωνο",
"phoneHint": "Η αναγνώριση κλήσης τον βρίσκει από αυτό.",
"email": "Email",
"notes": "Σημειώσεις",
"notesHint": "Αλλεργίες, τι του αρέσει, ό,τι πρέπει να ξέρει το προσωπικό.",
"visits": "Επισκέψεις",
"spent": "Ξόδεψε",
"spentTip": "Οι ολοκληρωμένες παραγγελίες του, όπως τις μετρούν οι αναφορές: μείον επιστροφές, μαζί με όσα μπήκαν σε καρτέλα.",
"perVisit": "Ανά επίσκεψη",
"lastVisit": "Τελευταία επίσκεψη",
"none": "Δεν υπάρχουν πελάτες ακόμα.",
"noneHint": "Προσθέστε εδώ τους τακτικούς, ή από μια παραγγελία (ο πελάτης της) ή μια κλήση.",
"noMatch": "Κανένας πελάτης δεν ταιριάζει.",
"editOf": "Επεξεργασία: {{name}}",
"removeOf": "Αφαίρεση: {{name}}",
"added": "Προστέθηκε: {{name}}",
"saved": "Αποθηκεύτηκε: {{name}}",
"removed": "Αφαιρέθηκε: {{name}}",
"removeTitle": "Αφαίρεση: {{name}};",
"removeBody": "Φεύγει από τη λίστα και την αναζήτηση. Οι παλιές παραγγελίες κρατούν το όνομά του.",
"removeYes": "Αφαίρεση",
"owes": "Χρωστάει στην καρτέλα",
"owesSub": "ανοιχτή από {{date}} · έχει πληρώσει {{paid}}: εξόφληση στα Οικονομικά → Καρτέλες",
"history": "Επισκέψεις",
"noVisits": "Καμία παραγγελία ακόμα.",
"atTable": "Τραπέζι {{table}}",
"noTable": "Χωρίς τραπέζι",
"orderType": {
"takeaway": "Πακέτο",
"delivery": "Διανομή",
"here": "Στο κατάστημα"
},
"items_one": "{{count}} είδος",
"items_other": "{{count}} είδη",
"onTab": "{{amount}} στην καρτέλα",
"orderStatus": {
"open": "Ανοιχτή",
"partially_paid": "Μερικώς πληρωμένη",
"paid": "Πληρωμένη",
"closed": "Κλειστή",
"cancelled": "Ακυρωμένη"
},
"wrong": {
"name": "Γράψτε ένα όνομα.",
"email": "Δεν μοιάζει με διεύθυνση email."
}
},
"waste": {
"title": "Απορρίμματα",
"subtitle": "Τι πετάχτηκε και πόσο κόστισε. Κάθε καταχώρηση κρατά το κόστος του προϊόντος εκείνη τη στιγμή.",
"log": "Καταγραφή απόρριψης",
"product": "Προϊόν",
"choose": "Επιλέξτε προϊόν…",
"pickProduct": "Επιλέξτε τι πετάχτηκε.",
"quantity": "Πόσα",
"wrongQty": "Βάλτε ποσότητα πάνω από μηδέν.",
"reason": "Γιατί",
"reasons": {
"kitchen_error": "Λάθος κουζίνας",
"dropped": "Έπεσε",
"expired": "Έληξε",
"other": "Άλλο"
},
"note": "Σημείωση",
"noteHint": "Προαιρετικά: π.χ. το επέστρεψε πελάτης",
"logIt": "Καταγραφή",
"logged": "Καταγράφηκε: {{name}} (δεν έχει ορισμένο κόστος)",
"loggedCost": "Καταγράφηκε: {{name}}, {{cost}}",
"noDayHint": "Δεν είναι ανοιχτή εργάσιμη μέρα: καταγράφεται χωρίς μέρα.",
"today": "Σήμερα",
"todaySum_one": "{{count}} καταχώρηση · {{cost}}",
"todaySum_other": "{{count}} καταχωρήσεις · {{cost}}",
"noDay": "Δεν είναι ανοιχτή εργάσιμη μέρα.",
"noneToday": "Τίποτα δεν πετάχτηκε σήμερα.",
"when": "Πότε",
"by": "Από",
"cost": "Κόστος",
"noCost": "χωρίς κόστος",
"deleteOf": "Διαγραφή: {{name}}",
"deleteTitle": "Διαγραφή αυτής της απόρριψης ({{name}});",
"deleteYes": "Διαγραφή",
"deleted": "Η απόρριψη διαγράφηκε",
"back": "Πίσω",
"history": "Παλιότερα",
"entries": "Καταχωρήσεις",
"uncosted_one": "{{count}} χωρίς κόστος",
"uncosted_other": "{{count}} χωρίς κόστος",
"byReason": "Ανά αιτία",
"byProduct": "Ανά προϊόν (κόστος)",
"times_one": "{{count}} φορά",
"times_other": "{{count}} φορές",
"units": "πετάχτηκαν {{qty}}",
"every": "Όλα τα απορρίμματα",
"noneInPeriod": "Τίποτα δεν πετάχτηκε σε αυτή την περίοδο."
},
"stock": {
"title": "Απόθεμα",
"soon": "Η καταμέτρηση αποθέματος δεν είναι διαθέσιμη ακόμα. Τα κόστη ορίζονται σε κάθε προϊόν (Προϊόντα) και οι απορρίψεις καταγράφονται στην Αποθήκη → Απορρίμματα."
},
"notes": {
"title": "Σημειώσεις",
"subtitle": "{{notes}} σημειώσεις · {{todos}} εκκρεμείς εργασίες. Κοινές για τους υπευθύνους.",
"notes": "Σημειώσεις",
"todos": "Εργασίες",
"pinned": "Καρφιτσωμένες",
"others": "Υπόλοιπες",
"newNote": "Νέα σημείωση… (Ctrl+Enter για αποθήκευση)",
"pinIt": "Καρφίτσωμα",
"addNote": "Προσθήκη σημείωσης",
"newTodo": "Κάτι να γίνει… (Enter για προσθήκη)",
"urgent": "Επείγον",
"urgentTag": "ΕΠΕΙΓΟΝ",
"addTodo": "Προσθήκη",
"noNotes": "Δεν υπάρχουν σημειώσεις ακόμα.",
"noTodos": "Δεν υπάρχουν εργασίες ακόμα.",
"edit": "Επεξεργασία",
"tapToEdit": "Πατήστε για επεξεργασία",
"pin": "Καρφίτσωμα",
"unpin": "Ξεκαρφίτσωμα",
"markDone": "Έγινε: {{what}}",
"undo": "Δεν έγινε: {{what}}",
"doneBy": "το έκανε {{name}}, {{time}}",
"doneCount_one": "{{count}} ολοκληρωμένη",
"doneCount_other": "{{count}} ολοκληρωμένες",
"deleteNote": "Διαγραφή σημείωσης",
"deleteTodo": "Διαγραφή εργασίας",
"deleteYes": "Διαγραφή",
"deleted": "Διαγράφηκε",
"back": "Πίσω"
} }
} }
+143
View File
@@ -3261,5 +3261,148 @@
"forgiveYes": "Forgive it", "forgiveYes": "Forgive it",
"forgiven": "{{name}}: {{amount}} forgiven" "forgiven": "{{name}}: {{amount}} forgiven"
} }
},
"customers": {
"title": "Customers",
"subtitle": "The venue's regular customers: what they like, how often they come, what they spend.",
"new": "New customer",
"newTitle": "New customer",
"add": "Add the customer",
"save": "Save",
"back": "Back",
"edit": "Edit",
"search": "Search name, nickname, phone, e-mail or notes",
"name": "Name",
"nickname": "Nickname",
"nicknameHint": "How the staff know them.",
"phone": "Phone",
"phoneHint": "Caller ID finds them by it.",
"email": "E-mail",
"notes": "Notes",
"notesHint": "Allergies, what they like, anything the staff should know.",
"visits": "Visits",
"spent": "Spent",
"spentTip": "Their finished orders, as the reports count them: refunds off, lines on a tab included.",
"perVisit": "Per visit",
"lastVisit": "Last visit",
"none": "No customers yet.",
"noneHint": "Add regulars here, or from an order (its customer) or a phone call.",
"noMatch": "No customer matches.",
"editOf": "Edit {{name}}",
"removeOf": "Remove {{name}}",
"added": "{{name}} added",
"saved": "{{name}} saved",
"removed": "{{name}} removed",
"removeTitle": "Remove {{name}}?",
"removeBody": "They leave the list and the search. Their past orders keep their name.",
"removeYes": "Remove",
"owes": "Owes on their tab",
"owesSub": "open since {{date}} · {{paid}} paid so far: settle it in Finance → Tabs",
"history": "Visits",
"noVisits": "No orders yet.",
"atTable": "Table {{table}}",
"noTable": "Without a table",
"orderType": {
"takeaway": "Takeaway",
"delivery": "Delivery",
"here": "In the shop"
},
"items_one": "{{count}} item",
"items_other": "{{count}} items",
"onTab": "{{amount}} on the tab",
"orderStatus": {
"open": "Open",
"partially_paid": "Partly paid",
"paid": "Paid",
"closed": "Closed",
"cancelled": "Cancelled"
},
"wrong": {
"name": "Enter a name.",
"email": "This doesn't look like an e-mail address."
}
},
"waste": {
"title": "Throwaways",
"subtitle": "What was thrown away and what it cost. Each entry keeps the product's cost at that moment.",
"log": "Log a throwaway",
"product": "Product",
"choose": "Choose a product…",
"pickProduct": "Choose what was thrown away.",
"quantity": "How many",
"wrongQty": "Enter a quantity above zero.",
"reason": "Why",
"reasons": {
"kitchen_error": "Kitchen mistake",
"dropped": "Dropped",
"expired": "Expired",
"other": "Other"
},
"note": "Note",
"noteHint": "Optional: e.g. a customer sent it back",
"logIt": "Log it",
"logged": "{{name}} logged (it has no cost set)",
"loggedCost": "{{name}} logged: {{cost}}",
"noDayHint": "No business day is open: the entry is logged without one.",
"today": "Today",
"todaySum_one": "{{count}} entry · {{cost}}",
"todaySum_other": "{{count}} entries · {{cost}}",
"noDay": "No business day is open.",
"noneToday": "Nothing thrown away today.",
"when": "When",
"by": "Logged by",
"cost": "Cost",
"noCost": "no cost",
"deleteOf": "Delete {{name}}",
"deleteTitle": "Delete this throwaway ({{name}})?",
"deleteYes": "Delete",
"deleted": "Throwaway deleted",
"back": "Back",
"history": "Earlier",
"entries": "Entries",
"uncosted_one": "{{count}} without a cost",
"uncosted_other": "{{count}} without a cost",
"byReason": "By reason",
"byProduct": "By product (cost)",
"times_one": "{{count}} time",
"times_other": "{{count}} times",
"units": "{{qty}} thrown away",
"every": "Every throwaway",
"noneInPeriod": "Nothing thrown away in this period."
},
"stock": {
"title": "Stock",
"soon": "Counting stock isn't available yet. Costs are set on each product (Products) and throwaways are logged in Inventory → Throwaways."
},
"notes": {
"title": "Notes",
"subtitle": "{{notes}} notes · {{todos}} to-dos open. Shared by the managers.",
"notes": "Notes",
"todos": "To-dos",
"pinned": "Pinned",
"others": "Others",
"newNote": "A new note… (Ctrl+Enter saves)",
"pinIt": "Pin it",
"addNote": "Add the note",
"newTodo": "Something to do… (Enter adds it)",
"urgent": "Urgent",
"urgentTag": "URGENT",
"addTodo": "Add",
"noNotes": "No notes yet.",
"noTodos": "Nothing to do yet.",
"edit": "Edit",
"tapToEdit": "Tap to edit",
"pin": "Pin",
"unpin": "Unpin",
"markDone": "Mark done: {{what}}",
"undo": "Not done: {{what}}",
"doneBy": "done by {{name}}, {{time}}",
"doneCount_one": "{{count}} done",
"doneCount_other": "{{count}} done",
"deleteNote": "Delete the note",
"deleteTodo": "Delete the to-do",
"deleteYes": "Delete",
"deleted": "Deleted",
"back": "Back"
} }
} }
+65
View File
@@ -1339,6 +1339,71 @@ try {
await page.getByTestId('user-menu').click() await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'English' }).click() await page.getByRole('menuitemradio', { name: 'English' }).click()
// ── 6.13b: a customer found without accents, a throwaway with its cost, a note and a to-do done ──
const cr = 'customers, waste, notes:'
for (const m of ['crm', 'inventory', 'notes']) await api('PUT', `/api/platform/modules/${m}`, { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${APP}/crm/customers`)
await page.getByTestId('customer-new').click()
await page.getByTestId('customer-save').click()
r.check(`${cr} a customer needs a name`, (await page.getByTestId('customer-dialog').textContent()).includes('Enter a name'))
await page.getByTestId('customer-name').fill('Γιώργος Ε2Ε')
await page.getByTestId('customer-phone').fill('697 700 1122')
await page.getByTestId('customer-notes').fill('Nut allergy')
await page.getByTestId('customer-save').click()
await page.getByTestId('customer-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
await page.getByTestId('customer-search').fill('γιωργος ε2ε')
const georgeRow = page.locator('[data-testid="customer-row"]', { hasText: 'Γιώργος Ε2Ε' })
r.check(`${cr} found by typing the name without accents, in lower case`, await georgeRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& await page.getByTestId('customer-row').count() === 1)
await page.getByTestId('customer-search').fill('7001122')
r.check(`${cr} found by part of the phone number`, await georgeRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await georgeRow.click()
r.check(`${cr} the card shows the allergy`, await page.getByTestId('customer-card').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& (await page.getByTestId('customer-card').textContent()).includes('Nut allergy'))
await page.screenshot({ path: path.join(OUT, 'manager-customer-card.png'), fullPage: true })
await page.keyboard.press('Escape')
await page.goto(`${APP}/inventory/throwaways`)
const wasteProduct = page.getByTestId('waste-product')
await wasteProduct.waitFor({ timeout: 10_000 }).catch(() => {})
await page.getByTestId('waste-log').click()
r.check(`${cr} a throwaway needs a product`, (await page.getByTestId('waste-form').textContent()).includes('Choose what was thrown away'))
const wasteOption = await wasteProduct.locator('option:not([value=""])').first().getAttribute('value')
await wasteProduct.selectOption(wasteOption)
await page.getByTestId('waste-qty').fill('1,5')
await page.getByRole('radio', { name: 'Dropped' }).click()
await page.getByTestId('waste-log').click()
const wasteRow = page.getByTestId('waste-today-row').first()
await wasteRow.waitFor({ timeout: 8000 }).catch(() => {})
const dayNow = await api('GET', '/api/business-day/current', { token: boss })
const logged = (await api('GET', `/api/waste/?business_day_id=${dayNow?.id}`, { token: boss })).entries.find(e => String(e.product_id) === wasteOption)
r.check(`${cr} logged from the page: 1.5, dropped, in today's list`, logged?.quantity === 1.5 && logged.reason === 'dropped' && (await wasteRow.textContent()).includes('Dropped'), JSON.stringify(logged))
await page.screenshot({ path: path.join(OUT, 'manager-throwaways.png'), fullPage: true })
await page.goto(`${APP}/notes`)
await page.getByTestId('note-new').fill('E2E: the fridge door sticks')
await page.getByTestId('note-add').click()
await page.getByTestId('todo-new').fill('E2E: call the plumber')
await page.getByRole('switch', { name: 'Urgent' }).click()
await page.getByTestId('todo-add').click()
const todoRow = page.locator('[data-testid="todo-row"]', { hasText: 'E2E: call the plumber' })
await todoRow.waitFor({ timeout: 8000 }).catch(() => {})
r.check(`${cr} the note and the urgent to-do are listed`, await page.locator('[data-testid="note-card"]', { hasText: 'the fridge door sticks' }).count() === 1
&& (await todoRow.textContent()).includes('URGENT'))
await todoRow.getByTestId('todo-done').click()
let plumber = null
for (let i = 0; i < 20 && !plumber?.is_done; i++) { await sleep(250); plumber = (await api('GET', '/api/notes/todos', { token: boss })).find(x => x.body === 'E2E: call the plumber') }
r.check(`${cr} the to-do ticked: done, and who did it is kept`, plumber?.is_done === true && !!plumber.done_by_name, JSON.stringify(plumber))
await page.screenshot({ path: path.join(OUT, 'manager-notes.png'), fullPage: true })
await page.goto(`${APP}/inventory/stock`)
r.check(`${cr} Stock says it isn't available yet`, await page.getByTestId('stock-page').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'Ελληνικά' }).click()
await page.goto(`${APP}/crm/customers`)
r.check(`${cr} Customers in Greek`, await page.locator('[data-testid="customers-page"] h1', { hasText: 'Πελάτες' }).waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.goto(`${APP}/notes`)
r.check(`${cr} Notes in Greek`, await page.locator('[data-testid="notes-page"] h1', { hasText: 'Σημειώσεις' }).waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'English' }).click()
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`) await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {}) await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})