diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py
index 5b5a1d0..95687c0 100644
--- a/local_backend/core/errors.py
+++ b/local_backend/core/errors.py
@@ -196,6 +196,8 @@ CODES: dict[str, tuple[int, str]] = {
"transfer.version": (400, "This export's version isn't supported."),
"contact.not_found": (404, "Contact not found."),
"expense.not_found": (404, "Expense not found."),
+ "expense.over_due": (400, "That's more than what is still due ({due})."),
+ "expense.below_paid": (400, "{paid} has been paid already: the total can't be less."),
"flag.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."),
"flag.invalid_ids": (400, "Some of these marks don't exist."),
diff --git a/local_backend/routers/expenses.py b/local_backend/routers/expenses.py
index 5c8b267..ef045db 100644
--- a/local_backend/routers/expenses.py
+++ b/local_backend/routers/expenses.py
@@ -1,5 +1,12 @@
-from core.timeutil import utcnow
-from datetime import datetime, timezone
+"""Expenses and the supplier book (module `expenses`; manager pages in plan step 6.13a).
+
+Every route needs `expenses.manage`; reading the list also works with `reports.view` (the
+expenses report). Changes send the live event `expenses.changed` so open pages refresh.
+An expense is entered once (total, category, maybe a supplier and a date it's due) and paid
+in one or more payments; it is "due", "partial" or "paid" from what was paid. A payment can't
+be more than what is still due, and the total can't drop below what was already paid.
+"""
+from datetime import date
from fastapi import APIRouter, Depends, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
@@ -12,14 +19,42 @@ from schemas.expenses import (
ExpenseCreate, ExpenseUpdate, ExpenseOut,
ExpensePaymentCreate, ExpensePaymentOut,
)
-from routers.deps import require_manager
+from core.access.deps import require, require_any
from core.errors import XeniaError
+from core.timeutil import venue_day_window
+from services.ws_bus import broadcast_sync
contacts_router = APIRouter()
expenses_router = APIRouter()
+MANAGE = Depends(require("expenses.manage"))
+CATEGORIES = ("supplier", "utilities", "rent", "maintenance", "staff", "equipment", "other")
+CONTACT_TYPES = ("supplier", "staff", "utility", "other")
+def _changed():
+ broadcast_sync("expenses.changed", {})
+
+
+def _check_contact(fields: dict):
+ if "type" in fields and fields["type"] not in CONTACT_TYPES:
+ raise XeniaError("validation.choice", field="type", value=fields["type"])
+ if "name" in fields and not (fields["name"] or "").strip():
+ raise XeniaError("validation.missing", field="name")
+
+
+def _check_expense(db: Session, fields: dict, paid: float = 0.0):
+ if "description" in fields and not (fields["description"] or "").strip():
+ raise XeniaError("validation.missing", field="description")
+ if "category" in fields and fields["category"] not in CATEGORIES:
+ raise XeniaError("validation.choice", field="category", value=fields["category"])
+ if "total_amount" in fields:
+ if fields["total_amount"] is None or fields["total_amount"] <= 0:
+ raise XeniaError("validation.positive", field="total_amount")
+ if fields["total_amount"] < paid - 0.005:
+ raise XeniaError("expense.below_paid", paid=f"{paid:.2f}")
+ if fields.get("contact_id") and not db.query(Contact).filter(Contact.id == fields["contact_id"]).first():
+ raise XeniaError("contact.not_found")
def _expense_status(total: float, paid: float) -> str:
if paid >= total:
@@ -77,7 +112,7 @@ def _expense_out(e: Expense) -> dict:
def list_contacts(
include_inactive: bool = False,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
q = db.query(Contact)
if not include_inactive:
@@ -86,33 +121,45 @@ def list_contacts(
@contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED)
-def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
- contact = Contact(**body.model_dump())
+def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = MANAGE):
+ fields = body.model_dump()
+ _check_contact(fields)
+ fields["name"] = fields["name"].strip()
+ contact = Contact(**fields)
db.add(contact)
db.commit()
db.refresh(contact)
+ _changed()
return contact
@contacts_router.put("/{contact_id}", response_model=ContactOut)
-def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def update_contact(contact_id: int, body: ContactUpdate, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact:
raise XeniaError("contact.not_found")
- for field, value in body.model_dump(exclude_none=True).items():
- setattr(contact, field, value)
+ # Fields sent as null are cleared (phone, e-mail...); name and type only change when given
+ fields = body.model_dump(exclude_unset=True)
+ for k in ("name", "type", "is_active"):
+ if fields.get(k) is None:
+ fields.pop(k, None)
+ _check_contact(fields)
+ for field, value in fields.items():
+ setattr(contact, field, value.strip() if field == "name" else value)
db.commit()
db.refresh(contact)
+ _changed()
return contact
@contacts_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
-def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User = MANAGE):
contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact:
raise XeniaError("contact.not_found")
contact.is_active = False
db.commit()
+ _changed()
# ── Expenses ──────────────────────────────────────────────────────────────────
@@ -120,7 +167,7 @@ def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User =
@expenses_router.get("/summary")
def expense_summary(
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
expenses = db.query(Expense).all()
total_due = sum(max(0.0, e.total_amount - e.paid_amount) for e in expenses if e.paid_amount < e.total_amount)
@@ -146,10 +193,18 @@ def list_expenses(
category: Optional[str] = None,
contact_id: Optional[int] = None,
business_day_id: Optional[int] = None,
+ date_from: Optional[date] = Query(default=None, alias="from"),
+ date_to: Optional[date] = Query(default=None, alias="to"),
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = Depends(require_any("expenses.manage", "reports.view")),
):
- expenses = db.query(Expense).order_by(Expense.created_at.desc()).all()
+ """Newest first. `from` / `to` are venue dates (inclusive) of the day each was entered."""
+ q = db.query(Expense)
+ if date_from:
+ q = q.filter(Expense.created_at >= venue_day_window(date_from)[0])
+ if date_to:
+ q = q.filter(Expense.created_at < venue_day_window(date_to)[1])
+ expenses = q.order_by(Expense.created_at.desc()).all()
result = [_expense_out(e) for e in expenses]
if expense_status:
result = [e for e in result if e["status"] == expense_status]
@@ -163,33 +218,45 @@ def list_expenses(
@expenses_router.post("/", response_model=ExpenseOut, status_code=status.HTTP_201_CREATED)
-def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
- expense = Expense(**body.model_dump(), created_by_id=user.id)
+def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
+ fields = body.model_dump()
+ _check_expense(db, fields)
+ fields["description"] = fields["description"].strip()
+ expense = Expense(**fields, created_by_id=user.id)
db.add(expense)
db.commit()
db.refresh(expense)
+ _changed()
return _expense_out(expense)
@expenses_router.put("/{expense_id}", response_model=ExpenseOut)
-def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def update_expense(expense_id: int, body: ExpenseUpdate, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
- for field, value in body.model_dump(exclude_none=True).items():
- setattr(expense, field, value)
+ # Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
+ fields = body.model_dump(exclude_unset=True)
+ for k in ("description", "category", "total_amount"):
+ if fields.get(k) is None:
+ fields.pop(k, None)
+ _check_expense(db, fields, paid=expense.paid_amount)
+ for field, value in fields.items():
+ setattr(expense, field, value.strip() if field == "description" else value)
db.commit()
db.refresh(expense)
+ _changed()
return _expense_out(expense)
@expenses_router.delete("/{expense_id}", status_code=status.HTTP_204_NO_CONTENT)
-def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def delete_expense(expense_id: int, db: Session = Depends(get_db), user: User = MANAGE):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
db.delete(expense)
db.commit()
+ _changed()
@expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut)
@@ -197,13 +264,16 @@ def record_payment(
expense_id: int,
body: ExpensePaymentCreate,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense:
raise XeniaError("expense.not_found")
if body.amount <= 0:
raise XeniaError("validation.positive", field='amount')
+ due = round(max(0.0, expense.total_amount - expense.paid_amount), 2)
+ if body.amount > due + 0.005:
+ raise XeniaError("expense.over_due", due=f"{due:.2f}")
payment = ExpensePayment(
expense_id=expense_id,
amount=body.amount,
@@ -217,4 +287,5 @@ def record_payment(
expense.paid_amount = round(sum(p.amount for p in all_payments), 2)
db.commit()
db.refresh(expense)
+ _changed()
return _expense_out(expense)
diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py
index b49d53a..7cec99c 100644
--- a/local_backend/routers/orders.py
+++ b/local_backend/routers/orders.py
@@ -57,6 +57,7 @@ class RevertPaymentRequest(BaseModel):
item_ids: List[int]
from routers.deps import get_current_user, require_manager
+from core.access.deps import require
from services.printer_service import route_and_print, route_and_print_sync, print_order_receipt, print_order_synopsis, print_cancellation_ticket
from models.settings import PosSettings
from services.ws_bus import broadcast_sync
@@ -2019,7 +2020,7 @@ def put_item_on_tab(
order_id: int,
item_id: int,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = Depends(require("tabs.manage")), # also needs the tabs module on (6.13a)
):
from models.tabs import Tab, TabEntry
@@ -2061,6 +2062,8 @@ def put_item_on_tab(
db.commit()
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "item_tabbed"})
+ from routers.tabs import changed as tabs_changed
+ tabs_changed()
return {"status": "tabbed", "tab_id": tab.id, "entry_amount": entry.amount}
diff --git a/local_backend/routers/tabs.py b/local_backend/routers/tabs.py
index 3cb3689..bd5b01f 100644
--- a/local_backend/routers/tabs.py
+++ b/local_backend/routers/tabs.py
@@ -1,5 +1,13 @@
+"""Customer tabs: pay later (module `tabs`; manager page in plan step 6.13a).
+
+A customer has at most one open tab. Lines of an order go on it from the order
+(POST /api/orders/{id}/items/{item}/tab: the line becomes "tabbed", the tab opens by itself);
+the customer pays it off in one or more payments (cash, card or other), and it is closed when
+nothing is owed, or forgiven (what is owed is written off, with a reason).
+Every route needs `tabs.manage`; a customer's tabs can also be read with `crm.manage` (their
+card on the customers page). Changes send the live event `tabs.changed`.
+"""
from core.timeutil import utcnow
-from datetime import datetime, timezone
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List, Optional
@@ -10,13 +18,19 @@ from models.customers import Customer
from models.order import Order, OrderItem
from models.user import User
from schemas.tabs import TabOut, TabEntryOut, TabPaymentOut, TabPayRequest, TabForgiveRequest, TabCloseRequest
-from routers.deps import require_manager
+from core.access.deps import require, require_any
from core.errors import XeniaError
+from services.ws_bus import broadcast_sync
router = APIRouter()
+MANAGE = Depends(require("tabs.manage"))
+METHODS = ("cash", "card", "other")
+def changed():
+ broadcast_sync("tabs.changed", {})
+
def _tab_out(tab: Tab) -> dict:
c = tab.customer
@@ -75,10 +89,12 @@ def list_tabs(
tab_status: Optional[str] = None,
customer_id: Optional[int] = None,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
q = db.query(Tab)
- if tab_status:
+ if tab_status == "settled":
+ q = q.filter(Tab.status.in_(("closed", "forgiven")))
+ elif tab_status:
q = q.filter(Tab.status == tab_status)
else:
q = q.filter(Tab.status == "open") # default: only open tabs
@@ -86,13 +102,13 @@ def list_tabs(
q = q.filter(Tab.customer_id == customer_id)
tabs = q.order_by(Tab.opened_at.desc()).all()
result = [_tab_out(t) for t in tabs]
- # Sort open tabs by balance descending
- result.sort(key=lambda x: x["balance"], reverse=True)
+ if tab_status in (None, "open"):
+ result.sort(key=lambda x: x["balance"], reverse=True) # who owes most first
return result
@router.get("/{tab_id}", response_model=TabOut)
-def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = MANAGE):
tab = db.query(Tab).filter(Tab.id == tab_id).first()
if not tab:
raise XeniaError("tab.not_found")
@@ -100,7 +116,7 @@ def get_tab(tab_id: int, db: Session = Depends(get_db), user: User = Depends(req
@router.post("/", response_model=TabOut, status_code=status.HTTP_201_CREATED)
-def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = MANAGE):
customer = db.query(Customer).filter(Customer.id == customer_id, Customer.is_active == True).first()
if not customer:
raise XeniaError("customer.not_found")
@@ -111,6 +127,7 @@ def open_tab(customer_id: int, db: Session = Depends(get_db), user: User = Depen
db.add(tab)
db.commit()
db.refresh(tab)
+ changed()
return _tab_out(tab)
@@ -122,7 +139,7 @@ def add_tab_entry(
amount: float = 0.0,
description: Optional[str] = None,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -136,6 +153,7 @@ def add_tab_entry(
db.add(entry)
db.commit()
db.refresh(tab)
+ changed()
return _tab_out(tab)
@@ -144,7 +162,7 @@ def pay_tab(
tab_id: int,
body: TabPayRequest,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -156,14 +174,18 @@ def pay_tab(
balance = total_charged - total_paid
if body.amount > balance + 0.005:
raise XeniaError("tab.over_balance", balance=f'{balance:.2f}')
+ method = body.payment_method or "cash"
+ if method not in METHODS:
+ raise XeniaError("validation.choice", field="payment_method", value=method)
payment = TabPayment(
tab_id=tab_id, amount=body.amount,
- payment_method=body.payment_method, notes=body.notes,
+ payment_method=method, notes=body.notes,
received_by_id=user.id,
)
db.add(payment)
db.commit()
db.refresh(tab)
+ changed()
return _tab_out(tab)
@@ -172,7 +194,7 @@ def close_tab(
tab_id: int,
body: TabCloseRequest,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -189,6 +211,7 @@ def close_tab(
tab.notes = body.notes
db.commit()
db.refresh(tab)
+ changed()
return _tab_out(tab)
@@ -197,7 +220,7 @@ def forgive_tab(
tab_id: int,
body: TabForgiveRequest,
db: Session = Depends(get_db),
- user: User = Depends(require_manager),
+ user: User = MANAGE,
):
tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab:
@@ -209,13 +232,15 @@ def forgive_tab(
tab.notes = body.reason
db.commit()
db.refresh(tab)
+ changed()
return _tab_out(tab)
# ── Customer tabs ──────────────────────────────────────────────────────────────
@router.get("/customer/{customer_id}", response_model=List[TabOut])
-def customer_tabs(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
+def customer_tabs(customer_id: int, db: Session = Depends(get_db),
+ user: User = Depends(require_any("tabs.manage", "crm.manage"))):
tabs = db.query(Tab).filter(Tab.customer_id == customer_id).order_by(
Tab.status.asc(), # open first
Tab.opened_at.desc(),
diff --git a/local_backend/schemas/expenses.py b/local_backend/schemas/expenses.py
index ae6406f..6c88d49 100644
--- a/local_backend/schemas/expenses.py
+++ b/local_backend/schemas/expenses.py
@@ -1,7 +1,9 @@
-from pydantic import BaseModel
+from pydantic import BaseModel, field_validator
from typing import Optional, List
from datetime import datetime
+from core.timeutil import parse_api_datetime
+
# ── Contacts ──────────────────────────────────────────────────────────────────
@@ -66,6 +68,12 @@ class ExpenseCreate(BaseModel):
business_day_id: Optional[int] = None
notes: Optional[str] = None
+ @field_validator("due_date", mode="before")
+ @classmethod
+ def _due_utc(cls, v):
+ # D-11: a date ("2026-11-30") or a naive time is venue-local; it was refused (500) before 6.13a
+ return parse_api_datetime(v) if isinstance(v, (str, datetime)) else v
+
class ExpenseUpdate(BaseModel):
description: Optional[str] = None
@@ -75,6 +83,12 @@ class ExpenseUpdate(BaseModel):
due_date: Optional[datetime] = None
notes: Optional[str] = None
+ @field_validator("due_date", mode="before")
+ @classmethod
+ def _due_utc(cls, v):
+ # D-11: a date ("2026-11-30") or a naive time is venue-local; it was refused (500) before 6.13a
+ return parse_api_datetime(v) if isinstance(v, (str, datetime)) else v
+
class ExpenseOut(BaseModel):
id: int
diff --git a/local_backend/tests/test_finance.py b/local_backend/tests/test_finance.py
new file mode 100644
index 0000000..8677722
--- /dev/null
+++ b/local_backend/tests/test_finance.py
@@ -0,0 +1,124 @@
+"""Expenses, the supplier book and customer tabs (plan step 6.13a): each needs its module's own
+key (expenses.manage / tabs.manage, not just the dashboard), the amounts are checked (a payment
+no larger than what is due, a total no smaller than what was paid), expenses filter by the
+venue day they were entered, and every change tells open pages (live events)."""
+from datetime import datetime, timezone
+
+import pytest
+
+
+@pytest.fixture
+def events(monkeypatch):
+ sent = []
+ import services.ws_bus as bus
+ monkeypatch.setattr(bus, "broadcast_sync", lambda t, d=None, **kw: sent.append(t))
+ import routers.expenses as ex
+ import routers.tabs as tb
+ monkeypatch.setattr(ex, "broadcast_sync", lambda t, d=None, **kw: sent.append(t))
+ monkeypatch.setattr(tb, "broadcast_sync", lambda t, d=None, **kw: sent.append(t))
+ return sent
+
+
+
+def test_expenses_need_their_own_key(client, make_user, login):
+ no = login(make_user(role="store_manager", remove=("expenses.manage",)))
+ assert client.post("/api/expenses/", headers=no, json={"description": "Milk", "category": "supplier", "total_amount": 10}).status_code == 403
+ assert client.get("/api/contacts/", headers=no).status_code == 403
+ # the expenses report reads the list with reports.view
+ rep = login(make_user(role="store_manager", keys=("core.dashboard.access", "reports.view")))
+ assert client.get("/api/expenses/", headers=rep).status_code == 200
+
+
+def test_an_expense_paid_in_two_parts(client, make_user, login, events):
+ h = login(make_user(role="owner"))
+ sup = client.post("/api/contacts/", headers=h, json={"name": " Dairy Nikos ", "type": "supplier", "phone": "2310 000000"})
+ assert sup.status_code == 201 and sup.json()["name"] == "Dairy Nikos"
+ r = client.post("/api/expenses/", headers=h, json={"description": "November milk", "category": "supplier",
+ "contact_id": sup.json()["id"], "total_amount": 120, "due_date": "2026-11-30"})
+ assert r.status_code == 201, r.text
+ e = r.json()
+ assert e["status"] == "due" and e["due_amount"] == 120 and e["contact_name"] == "Dairy Nikos"
+ r = client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 70, "notes": "cash"})
+ assert r.json()["status"] == "partial" and r.json()["due_amount"] == 50
+ r = client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 50.01})
+ assert r.status_code == 400 and "expense.over_due" in r.text # more than what is due
+ r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"total_amount": 60})
+ assert r.status_code == 400 and "expense.below_paid" in r.text # 70 paid already
+ r = client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 50})
+ assert r.json()["status"] == "paid" and r.json()["due_amount"] == 0 and len(r.json()["payments"]) == 2
+ # the supplier and the due date can be cleared
+ r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"contact_id": None, "due_date": None, "notes": "ok"})
+ assert r.json()["contact_id"] is None and r.json()["due_date"] is None and r.json()["description"] == "November milk"
+ assert events.count("expenses.changed") == 5 # the supplier, the expense, 2 payments, the edit (refused ones send nothing)
+
+
+def test_expense_rules(client, make_user, login):
+ h = login(make_user(role="owner"))
+ assert "validation.choice" in client.post("/api/expenses/", headers=h, json={"description": "X", "category": "food", "total_amount": 5}).text
+ assert "validation.positive" in client.post("/api/expenses/", headers=h, json={"description": "X", "category": "rent", "total_amount": 0}).text
+ assert "validation.missing" in client.post("/api/expenses/", headers=h, json={"description": " ", "category": "rent", "total_amount": 5}).text
+ assert "contact.not_found" in client.post("/api/expenses/", headers=h, json={"description": "X", "category": "rent", "total_amount": 5, "contact_id": 999}).text
+ assert "validation.choice" in client.post("/api/contacts/", headers=h, json={"name": "A", "type": "friend"}).text
+
+
+def test_expenses_filter_by_the_venue_day_entered(client, db, make_user, login):
+ from models.expenses import Expense
+ u = make_user(role="owner")
+ # 22:30 UTC on the 18th is 00:30 on the 19th in Athens
+ db.add_all([Expense(description="late", category="rent", total_amount=5, created_by_id=u.id, created_at=datetime(2026, 11, 18, 22, 30, tzinfo=timezone.utc)),
+ Expense(description="early", category="rent", total_amount=5, created_by_id=u.id, created_at=datetime(2026, 11, 18, 21, 30, tzinfo=timezone.utc))])
+ db.commit()
+ h = login(u)
+ names = lambda **p: [e["description"] for e in client.get("/api/expenses/", headers=h, params=p).json()]
+ assert names(**{"from": "2026-11-19", "to": "2026-11-19"}) == ["late"]
+ assert names(**{"to": "2026-11-18"}) == ["early"]
+ assert sorted(names()) == ["early", "late"]
+
+
+def _tabbed_order(db, client, h, make_user):
+ from models.customers import Customer
+ from models.order import Order, OrderItem
+ from models.product import Category, Product
+ owner = make_user(role="owner")
+ c = Customer(name="Kostas", nickname="Big K", created_by_id=owner.id)
+ cat = Category(name="Drinks")
+ db.add_all([c, cat])
+ db.flush()
+ p = Product(name="Beer", base_price=4.0, primary_category_id=cat.id)
+ db.add(p)
+ db.flush()
+ o = Order(opened_by=owner.id, order_type="takeaway", customer_id=c.id)
+ db.add(o)
+ db.flush()
+ item = OrderItem(order_id=o.id, product_id=p.id, added_by=owner.id, quantity=3, unit_price=4.0)
+ db.add(item)
+ db.commit()
+ r = client.post(f"/api/orders/{o.id}/items/{item.id}/tab", headers=h)
+ assert r.status_code == 200, r.text
+ return c, r.json()["tab_id"]
+
+
+def test_a_tab_charged_from_an_order_is_paid_and_closed(client, db, make_user, login, events):
+ h = login(make_user(role="owner"))
+ c, tab_id = _tabbed_order(db, client, h, make_user)
+ assert "tabs.changed" in events
+ tabs = client.get("/api/tabs/", headers=h).json()
+ assert [t["id"] for t in tabs] == [tab_id] and tabs[0]["balance"] == 12 and tabs[0]["customer_name"] == "Kostas «Big K»"
+ assert "tab.has_balance" in client.post(f"/api/tabs/{tab_id}/close", headers=h, json={}).text
+ assert "validation.choice" in client.post(f"/api/tabs/{tab_id}/pay", headers=h, json={"amount": 2, "payment_method": "iou"}).text
+ assert "tab.over_balance" in client.post(f"/api/tabs/{tab_id}/pay", headers=h, json={"amount": 13}).text
+ r = client.post(f"/api/tabs/{tab_id}/pay", headers=h, json={"amount": 12})
+ assert r.json()["balance"] == 0 and r.json()["payments"][0]["payment_method"] == "cash" # cash unless told
+ assert client.post(f"/api/tabs/{tab_id}/close", headers=h, json={}).json()["status"] == "closed"
+ assert client.get("/api/tabs/", headers=h).json() == []
+ assert [t["status"] for t in client.get("/api/tabs/", headers=h, params={"tab_status": "settled"}).json()] == ["closed"]
+ # the customers page reads their tabs with crm.manage
+ crm = login(make_user(role="staff_manager", keys=("core.dashboard.access", "crm.manage")))
+ assert client.get(f"/api/tabs/customer/{c.id}", headers=crm).status_code == 200
+ assert client.get("/api/tabs/", headers=crm).status_code == 403
+
+
+def test_tabs_need_their_own_key(client, db, make_user, login):
+ no = login(make_user(role="staff_manager")) # has the dashboard, not tabs.manage
+ assert client.get("/api/tabs/", headers=no).status_code == 403
+ assert client.post("/api/orders/1/items/1/tab", headers=no).status_code == 403
diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx
index 006893f..521fb29 100644
--- a/manager_dashboard/src/App.jsx
+++ b/manager_dashboard/src/App.jsx
@@ -21,12 +21,12 @@ import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage'
// CRM
-import ContactsPage from './pages/crm/ContactsPage'
+import ContactsPage from './pages/finance/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage'
// Financials
-import ExpensesPage from './pages/financials/ExpensesPage'
-import TabsPage from './pages/financials/TabsPage'
+import ExpensesPage from './pages/finance/ExpensesPage'
+import TabsPage from './pages/finance/TabsPage'
// Management
import ProductsPage from './pages/products/ProductsPage'
diff --git a/manager_dashboard/src/pages/ContactsPage.jsx b/manager_dashboard/src/pages/ContactsPage.jsx
deleted file mode 100644
index c50506f..0000000
--- a/manager_dashboard/src/pages/ContactsPage.jsx
+++ /dev/null
@@ -1,217 +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'
-
-const TYPE_LABELS = {
- supplier: 'Προμηθευτής',
- staff: 'Προσωπικό',
- utility: 'Κοινή Χρεία',
- other: 'Άλλο',
-}
-const TYPE_COLORS = {
- supplier: { bg: '#eff6ff', color: '#1d4ed8' },
- staff: { bg: '#f0fdf4', color: '#15803d' },
- utility: { bg: '#fefce8', color: '#a16207' },
- other: { bg: '#f3f4f6', color: '#374151' },
-}
-
-const EMPTY_FORM = { name: '', type: 'supplier', phone: '', email: '', address: '', notes: '' }
-
-function ContactModal({ initial, onClose, onSave, isPending }) {
- const [form, setForm] = useState(initial ?? EMPTY_FORM)
- const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
- const isNew = !initial?.id
- const canSave = form.name.trim()
-
- const inputStyle = {
- width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
- borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit',
- background: 'white',
- }
-
- return (
-
-
-
-
{isNew ? 'Νέα Επαφή' : 'Επεξεργασία Επαφής'}
-
-
-
-
-
-
- f('name', e.target.value)} autoFocus placeholder="π.χ. Νίκος Γαλακτοπωλείο" />
-
-
-
-
-
-
-
-
- f('address', e.target.value)} placeholder="Οδός, Πόλη" />
-
-
-
-
-
-
-
-
-
-
-
-
- )
-}
-
-export default function ContactsPage() {
- const qc = useQueryClient()
- const [modal, setModal] = useState(null) // null | { contact } | { contact: null } for new
-
- const { data: contacts = [], isLoading } = useQuery({
- queryKey: ['contacts'],
- queryFn: () => client.get('/api/contacts/').then(r => r.data),
- staleTime: 30_000,
- })
-
- const save = useMutation({
- mutationFn: ({ form, id }) => id
- ? client.put(`/api/contacts/${id}`, form)
- : client.post('/api/contacts/', form),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['contacts'] })
- setModal(null)
- toast.success('Αποθηκεύτηκε')
- },
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const deactivate = useMutation({
- mutationFn: (id) => client.delete(`/api/contacts/${id}`),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['contacts'] })
- toast.success('Η επαφή αποενεργοποιήθηκε')
- },
- onError: () => toast.error('Σφάλμα'),
- })
-
- return (
-
- {/* Header */}
-
-
-
{contacts.length} ενεργές επαφές
-
-
-
-
- {/* Table */}
-
- {isLoading &&
Φόρτωση…
}
- {!isLoading && contacts.length === 0 && (
-
- Δεν υπάρχουν επαφές ακόμα. Προσθέστε τον πρώτο προμηθευτή.
-
- )}
- {contacts.length > 0 && (
-
-
-
-
- {['Όνομα', 'Τύπος', 'Τηλέφωνο', 'Email', ''].map(h => (
- | {h} |
- ))}
-
-
-
- {contacts.map((c, i) => {
- const tc = TYPE_COLORS[c.type] || TYPE_COLORS.other
- return (
-
- |
- {c.name}
- {c.notes && {c.notes.slice(0, 60)}{c.notes.length > 60 ? '…' : ''} }
- |
-
-
- {TYPE_LABELS[c.type] || c.type}
-
- |
- {c.phone || '—'} |
- {c.email || '—'} |
-
-
-
-
-
- |
-
- )
- })}
-
-
-
- )}
-
-
- {modal && (
-
setModal(null)}
- isPending={save.isPending}
- onSave={(form) => save.mutate({
- form: { name: form.name, type: form.type, phone: form.phone || null, email: form.email || null, address: form.address || null, notes: form.notes || null },
- id: modal.contact?.id,
- })}
- />
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/ExpensesPage.jsx b/manager_dashboard/src/pages/ExpensesPage.jsx
deleted file mode 100644
index d4a0131..0000000
--- a/manager_dashboard/src/pages/ExpensesPage.jsx
+++ /dev/null
@@ -1,436 +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 CATEGORIES = [
- { id: 'supplier', label: 'Προμηθευτής' },
- { id: 'utilities', label: 'Κοινή Χρεία' },
- { id: 'rent', label: 'Ενοίκιο' },
- { id: 'maintenance',label: 'Συντήρηση' },
- { id: 'staff', label: 'Προσωπικό' },
- { id: 'equipment', label: 'Εξοπλισμός' },
- { id: 'other', label: 'Άλλο' },
-]
-
-const STATUS_CONFIG = {
- due: { label: 'Οφείλεται', bg: '#fee2e2', color: '#dc2626' },
- partial: { label: 'Μερική Πληρ.', bg: '#fef9c3', color: '#a16207' },
- paid: { label: 'Πληρώθηκε', bg: '#dcfce7', color: '#16a34a' },
-}
-
-// ── 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 inputStyle = {
- width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb',
- borderRadius: 8, fontSize: 13.5, outline: 'none', fontFamily: 'inherit', background: 'white',
-}
-
-// ── Expense form modal ────────────────────────────────────────────────────────
-
-const EMPTY_FORM = { description: '', category: 'supplier', contact_id: '', total_amount: '', due_date: '', notes: '' }
-
-function ExpenseModal({ initial, contacts, onClose, onSave, isPending }) {
- const [form, setForm] = useState(initial ?? EMPTY_FORM)
- const f = (k, v) => setForm(p => ({ ...p, [k]: v }))
- const isNew = !initial?.id
- const canSave = form.description.trim() && parseFloat(form.total_amount) > 0
-
- return (
-
-
-
-
{isNew ? 'Νέο Έξοδο' : 'Επεξεργασία Εξόδου'}
-
-
-
-
-
-
- f('description', e.target.value)} autoFocus placeholder="π.χ. Τιμολόγιο Νοεμβρίου — Γαλακτοκομικά" />
-
-
-
-
-
-
-
-
-
- f('total_amount', e.target.value)} placeholder="0.00" />
-
-
-
-
-
-
-
-
-
-
- f('due_date', e.target.value)} />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- )
-}
-
-// ── Pay modal ─────────────────────────────────────────────────────────────────
-
-function PayModal({ expense, onClose, onPay, isPending }) {
- const [amount, setAmount] = useState(String(Math.round((expense.due_amount) * 100) / 100))
- const [notes, setNotes] = useState('')
- const parsed = parseFloat(amount)
- const canPay = parsed > 0 && parsed <= expense.due_amount + 0.001
-
- return (
-
-
-
-
Καταγραφή Πληρωμής
-
{expense.description}
-
-
-
- Εκκρεμεί
- {fmt(expense.due_amount)}
-
-
-
- setAmount(e.target.value)} autoFocus />
-
-
-
- setNotes(e.target.value)} placeholder="π.χ. Μετρητά στο χέρι" />
-
-
-
-
-
-
-
-
- )
-}
-
-// ── Expense row (expandable) ──────────────────────────────────────────────────
-
-function ExpenseRow({ expense, isExpanded, onToggle, onPay, onEdit, onDelete }) {
- const sc = STATUS_CONFIG[expense.status] || STATUS_CONFIG.due
- const catLabel = CATEGORIES.find(c => c.id === expense.category)?.label || expense.category
-
- return (
- <>
-
- |
- {expense.description}
- {expense.contact_name && {expense.contact_name} }
- |
- {catLabel} |
- {fmt(expense.total_amount)} |
- {expense.paid_amount > 0 ? fmt(expense.paid_amount) : '—'} |
- {expense.due_amount > 0 ? fmt(expense.due_amount) : '—'} |
-
- {sc.label}
- |
- {expense.due_date ? fmtDate(expense.due_date) : '—'} |
-
-
- {expense.status !== 'paid' && (
-
- )}
-
-
-
- |
-
-
- {isExpanded && (
-
-
-
- {expense.notes && (
- 📝 {expense.notes}
- )}
-
- Καταχωρήθηκε από {expense.created_by_name} · {fmtDate(expense.created_at)}
-
- {expense.payments.length > 0 && (
-
- Ιστορικό Πληρωμών
-
- {expense.payments.map(p => (
-
-
- {p.paid_by_name} · {fmtDateTime(p.paid_at)}
- {p.notes && — {p.notes}}
-
- {fmt(p.amount)}
-
- ))}
-
-
- )}
- {expense.payments.length === 0 && expense.status === 'due' && (
- Δεν έχουν καταγραφεί πληρωμές.
- )}
-
- |
-
- )}
- >
- )
-}
-
-// ── Main page ─────────────────────────────────────────────────────────────────
-
-export default function ExpensesPage() {
- const qc = useQueryClient()
- const [statusFilter, setStatusFilter] = useState('all')
- const [categoryFilter, setCategoryFilter] = useState('all')
- const [expanded, setExpanded] = useState(null)
- const [modal, setModal] = useState(null) // null | { type: 'expense', expense? } | { type: 'pay', expense }
-
- const params = {}
- if (statusFilter !== 'all') params.status = statusFilter
- if (categoryFilter !== 'all') params.category = categoryFilter
-
- const { data: expenses = [], isLoading } = useQuery({
- queryKey: ['expenses', statusFilter, categoryFilter],
- queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data),
- staleTime: 15_000,
- })
-
- const { data: contacts = [] } = useQuery({
- queryKey: ['contacts'],
- queryFn: () => client.get('/api/contacts/').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: summary } = useQuery({
- queryKey: ['expenses-summary'],
- queryFn: () => client.get('/api/expenses/summary').then(r => r.data),
- staleTime: 15_000,
- })
-
- const saveExpense = useMutation({
- mutationFn: ({ form, id }) => id
- ? client.put(`/api/expenses/${id}`, form)
- : client.post('/api/expenses/', form),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['expenses'] })
- qc.invalidateQueries({ queryKey: ['expenses-summary'] })
- setModal(null)
- toast.success('Αποθηκεύτηκε')
- },
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- const payExpense = useMutation({
- mutationFn: ({ id, amount, notes }) => client.post(`/api/expenses/${id}/pay`, { amount, notes }),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['expenses'] })
- qc.invalidateQueries({ queryKey: ['expenses-summary'] })
- setModal(null)
- toast.success('Πληρωμή καταγράφηκε')
- },
- onError: () => toast.error('Σφάλμα καταγραφής πληρωμής'),
- })
-
- const deleteExpense = useMutation({
- mutationFn: (id) => client.delete(`/api/expenses/${id}`),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['expenses'] })
- qc.invalidateQueries({ queryKey: ['expenses-summary'] })
- toast.success('Διαγράφηκε')
- },
- onError: () => toast.error('Σφάλμα διαγραφής'),
- })
-
- const totalDue = summary?.total_due ?? 0
- const pendingCount = expenses.filter(e => e.status !== 'paid').length
-
- return (
-
- {/* Header */}
-
-
-
-
- {pendingCount} εκκρεμή · Σύνολο οφειλών: 0 ? '#dc2626' : '#16a34a' }}>{fmt(totalDue)}
-
-
-
-
-
- {/* Filters */}
-
- {/* Status filter */}
-
- {[['all', 'Όλα'], ['due', 'Οφείλεται'], ['partial', 'Μερική'], ['paid', 'Πληρώθηκε']].map(([v, l]) => (
-
- ))}
-
- {/* Category filter */}
-
-
-
-
- {/* Table */}
-
- {isLoading &&
Φόρτωση…
}
- {!isLoading && expenses.length === 0 && (
-
- Δεν βρέθηκαν έξοδα για τα επιλεγμένα φίλτρα.
-
- )}
- {expenses.length > 0 && (
-
-
-
-
- {['Περιγραφή', 'Κατηγορία', 'Σύνολο', 'Πληρωμένο', 'Εκκρεμεί', 'Κατάσταση', 'Ημ/νία', ''].map(h => (
- | {h} |
- ))}
-
-
-
- {expenses.map(e => (
- setExpanded(expanded === e.id ? null : e.id)}
- onPay={() => setModal({ type: 'pay', expense: e })}
- onEdit={() => setModal({ type: 'expense', expense: e })}
- onDelete={() => { if (window.confirm('Διαγραφή εξόδου;')) deleteExpense.mutate(e.id) }}
- />
- ))}
-
-
-
- )}
-
-
- {/* Expense create/edit modal */}
- {modal?.type === 'expense' && (
-
setModal(null)}
- isPending={saveExpense.isPending}
- onSave={(form) => saveExpense.mutate({
- form: {
- description: form.description,
- category: form.category,
- contact_id: form.contact_id ? Number(form.contact_id) : null,
- total_amount: parseFloat(form.total_amount),
- due_date: form.due_date || null,
- notes: form.notes || null,
- },
- id: modal.expense?.id,
- })}
- />
- )}
-
- {/* Pay modal */}
- {modal?.type === 'pay' && (
- setModal(null)}
- isPending={payExpense.isPending}
- onPay={(amount, notes) => payExpense.mutate({ id: modal.expense.id, amount, notes })}
- />
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/TabsPage.jsx b/manager_dashboard/src/pages/TabsPage.jsx
deleted file mode 100644
index 1219501..0000000
--- a/manager_dashboard/src/pages/TabsPage.jsx
+++ /dev/null
@@ -1,411 +0,0 @@
-import { useState, useMemo } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import { ChevronDown, Search } from 'lucide-react'
-import client from '../api/client'
-
-// ── 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' })
-}
-
-function daysSince(iso) {
- if (!iso) return null
- const days = Math.floor((Date.now() - new Date(iso).getTime()) / 86400000)
- if (days === 0) return 'Σήμερα'
- if (days === 1) return '1 μέρα'
- return `${days} μέρες`
-}
-
-const STATUS_CONFIG = {
- open: { label: 'Ανοιχτή', bg: '#fee2e2', color: '#dc2626' },
- closed: { label: 'Κλειστή', bg: '#dcfce7', color: '#16a34a' },
- forgiven: { label: 'Χαρίστηκε', bg: '#f3f4f6', color: '#6b7280' },
-}
-
-// ── Pay modal ─────────────────────────────────────────────────────────────────
-
-function PayModal({ tab, onClose, onPay, isPending }) {
- const [amount, setAmount] = useState(String(Math.round(tab.balance * 100) / 100))
- const [method, setMethod] = useState('cash')
- const [notes, setNotes] = useState('')
- const parsed = parseFloat(amount)
- const canPay = parsed > 0 && parsed <= tab.balance + 0.005
-
- return (
-
-
-
-
Πληρωμή Καρτέλας
-
{tab.customer_name}
-
-
-
- Υπόλοιπο καρτέλας
- {fmt(tab.balance)}
-
-
-
- setAmount(e.target.value)} autoFocus
- style={{ width: '100%', padding: '9px 12px', border: '1.5px solid #e5e7eb', borderRadius: 8, fontSize: 16, fontWeight: 600, outline: 'none', boxSizing: 'border-box' }} />
-
-
-
-
- {[['cash', 'Μετρητά'], ['card', 'Κάρτα'], ['other', 'Άλλο']].map(([v, l]) => (
-
- ))}
-
-
-
-
- setNotes(e.target.value)} placeholder="προαιρετικό"
- style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
-
-
-
-
-
-
-
-
- )
-}
-
-// ── Forgive confirm ───────────────────────────────────────────────────────────
-
-function ForgiveModal({ tab, onClose, onForgive, isPending }) {
- const [reason, setReason] = useState('')
- return (
-
-
-
-
Χάρισμα Καρτέλας
-
{tab.customer_name} — υπόλοιπο {fmt(tab.balance)}
-
-
-
- Το υπόλοιπο των {fmt(tab.balance)} θα διαγραφεί. Η ενέργεια δεν αναιρείται.
-
-
-
- setReason(e.target.value)} placeholder="π.χ. Καλή θέληση"
- style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
-
-
-
-
-
-
-
-
- )
-}
-
-// ── Tab detail card (collapsible) ─────────────────────────────────────────────
-
-function TabDetail({ tab, onPay, onClose, onForgive, defaultExpanded = false }) {
- const [expanded, setExpanded] = useState(defaultExpanded)
- const sc = STATUS_CONFIG[tab.status] || STATUS_CONFIG.open
- const canClose = tab.status === 'open' && tab.balance <= 0.005 && tab.entries.length > 0
-
- return (
-
- {/* Clickable header — always visible */}
-
-
- {/* Expanded body */}
- {expanded && (
- <>
- {/* Stats */}
-
- {[
- { label: 'Συνολικές χρεώσεις', value: fmt(tab.total_charged) },
- { label: 'Πληρωμένο', value: fmt(tab.total_paid), color: '#16a34a' },
- { label: 'Υπόλοιπο', value: fmt(tab.balance), color: tab.balance > 0 ? '#dc2626' : '#16a34a' },
- ].map(s => (
-
-
{s.label}
-
{s.value}
-
- ))}
-
-
- {/* Entries */}
- {tab.entries.length > 0 && (
-
-
Χρεώσεις
-
- {tab.entries.map(e => (
-
- {e.description || `Χρέωση #${e.id}`}
- {fmt(e.amount)}
-
- ))}
-
-
- )}
-
- {/* Payments */}
- {tab.payments.length > 0 && (
-
-
Πληρωμές
-
- {tab.payments.map(p => (
-
-
- {p.received_by_name} · {fmtDateTime(p.created_at)}
- {p.payment_method && ({p.payment_method})}
- {p.notes && — {p.notes}}
-
- {fmt(p.amount)}
-
- ))}
-
-
- )}
-
- {/* Actions */}
- {tab.status === 'open' && (
-
- {tab.balance > 0.005 && (
-
- )}
- {canClose && (
-
- )}
-
-
- )}
- >
- )}
-
- )
-}
-
-// ── Filter chip ───────────────────────────────────────────────────────────────
-
-function FilterChip({ label, active, onClick }) {
- return (
-
- )
-}
-
-// ── Main page ─────────────────────────────────────────────────────────────────
-
-export default function TabsPage() {
- const qc = useQueryClient()
- const [statusFilter, setStatusFilter] = useState('open') // 'open' | 'closed' | 'all'
- const [search, setSearch] = useState('')
- const [modal, setModal] = useState(null)
-
- // Fetch open and closed separately — merge for client-side filtering
- const { data: openTabs = [], isLoading: loadingOpen } = useQuery({
- queryKey: ['tabs-open'],
- queryFn: () => client.get('/api/tabs/').then(r => r.data),
- staleTime: 15_000,
- })
- const { data: closedTabs = [], isLoading: loadingClosed } = useQuery({
- queryKey: ['tabs-closed'],
- queryFn: () => client.get('/api/tabs/', { params: { tab_status: 'closed' } }).then(r => r.data),
- staleTime: 15_000,
- })
- const tabs = [...openTabs, ...closedTabs]
- const isLoading = loadingOpen || loadingClosed
-
- const payTab = useMutation({
- mutationFn: ({ id, amount, payment_method, notes }) =>
- client.post(`/api/tabs/${id}/pay`, { amount, payment_method, notes }),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
- setModal(null)
- toast.success('Πληρωμή καταγράφηκε')
- },
- onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
- })
-
- const closeTab = useMutation({
- mutationFn: (id) => client.post(`/api/tabs/${id}/close`, {}),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
- toast.success('Καρτέλα έκλεισε')
- },
- onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
- })
-
- const forgiveTab = useMutation({
- mutationFn: ({ id, reason }) => client.post(`/api/tabs/${id}/forgive`, { reason }),
- onSuccess: () => {
- qc.invalidateQueries({ queryKey: ['tabs-open'] }); qc.invalidateQueries({ queryKey: ['tabs-closed'] })
- setModal(null)
- toast.success('Το υπόλοιπο χαρίστηκε')
- },
- onError: () => toast.error('Σφάλμα'),
- })
-
- // Live client-side filtering
- const filtered = useMemo(() => {
- let result = tabs
- if (statusFilter !== 'all') {
- result = result.filter(t => {
- if (statusFilter === 'open') return t.status === 'open'
- if (statusFilter === 'closed') return t.status === 'closed' || t.status === 'forgiven'
- return true
- })
- }
- if (search.trim()) {
- const q = search.trim().toLowerCase()
- result = result.filter(t => t.customer_name?.toLowerCase().includes(q))
- }
- return result
- }, [tabs, statusFilter, search])
-
- const openCount = tabs.filter(t => t.status === 'open').length
- const closedCount = tabs.filter(t => t.status === 'closed' || t.status === 'forgiven').length
- const totalOutstanding = tabs.filter(t => t.status === 'open').reduce((s, t) => s + t.balance, 0)
-
- return (
-
- {/* Toolbar */}
-
- {/* Search */}
-
-
- setSearch(e.target.value)}
- placeholder="Αναζήτηση πελάτη…"
- className="pl-8 pr-3 py-1.5 text-[13px] bg-slate-50 border border-slate-200 rounded-lg w-48 focus:outline-none focus:ring-2 focus:ring-sky-500/30 focus:border-sky-400 transition placeholder:text-slate-400"
- />
-
-
- {/* Status filter chips */}
-
- setStatusFilter('open')} />
- setStatusFilter('closed')} />
- setStatusFilter('all')} />
-
-
- {/* Summary */}
-
- {statusFilter === 'open' && totalOutstanding > 0 && (
- Σύνολο: {fmt(totalOutstanding)}
- )}
-
-
-
- {/* Tab list */}
-
- {isLoading && (
-
Φόρτωση…
- )}
- {!isLoading && filtered.length === 0 && (
-
- {search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν καρτέλες.'}
-
- )}
- {filtered.map(tab => (
-
setModal({ type: 'pay', tab: t })}
- onClose={t => closeTab.mutate(t.id)}
- onForgive={t => setModal({ type: 'forgive', tab: t })}
- />
- ))}
-
-
- {modal?.type === 'pay' && (
-
setModal(null)}
- isPending={payTab.isPending}
- onPay={(amount, payment_method, notes) => payTab.mutate({ id: modal.tab.id, amount, payment_method, notes })}
- />
- )}
-
- {modal?.type === 'forgive' && (
- setModal(null)}
- isPending={forgiveTab.isPending}
- onForgive={(reason) => forgiveTab.mutate({ id: modal.tab.id, reason })}
- />
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/crm/ContactsPage.jsx b/manager_dashboard/src/pages/crm/ContactsPage.jsx
deleted file mode 100644
index ddfb1ef..0000000
--- a/manager_dashboard/src/pages/crm/ContactsPage.jsx
+++ /dev/null
@@ -1 +0,0 @@
-export { default } from '../ContactsPage'
diff --git a/manager_dashboard/src/pages/finance/ContactDialog.jsx b/manager_dashboard/src/pages/finance/ContactDialog.jsx
new file mode 100644
index 0000000..5324ce1
--- /dev/null
+++ b/manager_dashboard/src/pages/finance/ContactDialog.jsx
@@ -0,0 +1,59 @@
+// A supplier or other contact (plan step 6.13a): name, kind, phone, e-mail, address, notes.
+// Clearing a field clears it. `onSaved(contact)` gets the saved contact (the expense dialog picks
+// a new supplier at once).
+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, Select, Textarea } from '@xenia/ui'
+import client from '../../api/client'
+import { CONTACT_TYPES, contactBody, contactForm, contactProblems } from './financeLogic'
+
+export default function ContactDialog({ contact, onClose, onSaved }) {
+ const { t } = useTranslation('manager')
+ const isNew = !contact
+ const [form, setForm] = useState(() => contactForm(contact))
+ const [tried, setTried] = useState(false)
+ const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
+ const wrong = contactProblems(form)
+ const err = k => (tried && wrong.includes(k) ? t(`finance.contacts.wrong.${k}`) : undefined)
+ const save = useMutation({
+ mutationFn: body => (isNew ? client.post('/api/contacts/', body) : client.put(`/api/contacts/${contact.id}`, body)).then(r => r.data),
+ onSuccess: c => { toast.success(t(isNew ? 'finance.contacts.added' : 'finance.contacts.saved', { name: c.name })); onSaved(c) },
+ onError: e => toast.error(errorMessage(e, t)),
+ })
+ const submit = () => { setTried(true); if (!wrong.length) save.mutate(contactBody(form)) }
+ return (
+
+ )
+}
diff --git a/manager_dashboard/src/pages/finance/ContactsPage.jsx b/manager_dashboard/src/pages/finance/ContactsPage.jsx
new file mode 100644
index 0000000..d21a99e
--- /dev/null
+++ b/manager_dashboard/src/pages/finance/ContactsPage.jsx
@@ -0,0 +1,96 @@
+// CRM → Contacts, the supplier book (plan step 6.13a; replaces the v1 ContactsPage): suppliers,
+// utilities and other people the venue pays, with their phone (tap to call), e-mail, address and
+// notes, and what the venue still owes each one (from Finance → Expenses). New, edit, remove
+// (a removed contact stays on its old expenses). Live: `expenses.changed`.
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { BookUser, Pencil, Plus, Search, Trash2 } from 'lucide-react'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog, EmptyState, IconButton, Input, Select, Spinner } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { Pill } from '../overview/parts'
+import { Panel, Table } from '../reports/kit/parts'
+import ContactDialog from './ContactDialog'
+import { CONTACT_TYPES, filterContacts, owedByContact } from './financeLogic'
+
+const TYPE_TONE = { supplier: 'accent', staff: 'success', utility: 'warning', other: 'neutral' }
+
+export default function ContactsPage() {
+ const { t } = useTranslation('manager')
+ const fmt = useFormat()
+ const [filter, setFilter] = useState({ type: '', q: '' })
+ const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'remove', contact }
+ const { data, isPending, refetch } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
+ const { data: expenses = [] } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
+ const all = data ?? []
+ const owed = owedByContact(expenses)
+ const rows = filterContacts(all, filter)
+ const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
+ const close = () => setDialog(null)
+ const saved = () => { close(); refetch() }
+ const remove = useMutation({
+ mutationFn: c => client.delete(`/api/contacts/${c.id}`),
+ onSuccess: (_r, c) => { toast.success(t('finance.contacts.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('finance.contacts.name'), render: c => (
+
+ {c.name}
+ {c.notes && {c.notes}}
+ ) },
+ { key: 'type', label: t('finance.contacts.type'), sort: c => t(`finance.contacts.types.${c.type}`), render: c => {t(`finance.contacts.types.${c.type}`, { defaultValue: c.type })} },
+ { key: 'phone', label: t('finance.contacts.phone'), render: c => (c.phone ? ev.stopPropagation()} className="text-accent-ink hover:underline">{c.phone} : '') },
+ { key: 'email', label: t('finance.contacts.email'), render: c => (c.email ? ev.stopPropagation()} className="text-accent-ink hover:underline">{c.email} : '') },
+ { key: 'owed', label: t('finance.contacts.owed'), align: 'right', sort: c => owed[c.id]?.due ?? 0, render: c => (owed[c.id]
+ ? {fmt.formatMoney(owed[c.id].due)}{t('finance.contacts.bills', { count: owed[c.id].count })} : '') },
+ { key: 'actions', label: '', sort: false, render: c => (
+
+ setDialog({ kind: 'edit', contact: c }))}>
+ setDialog({ kind: 'remove', contact: c }))}>
+ ) },
+ ]
+
+ return (
+
+
+
+
+
+
+ set('q', e.target.value)} placeholder={t('finance.contacts.search')} aria-label={t('finance.contacts.search')} className="pl-9" />
+
+
+ {isPending ?
+ : !all.length ?
} title={t('finance.contacts.none')} description={t('finance.contacts.noneHint')} />
+ : (
+
+ setDialog({ kind: 'edit', contact: c })} rowTestId="contact-row"
+ empty={t('finance.contacts.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
+
+ )}
+
+ {(dialog?.kind === 'new' || dialog?.kind === 'edit') && }
+ {dialog?.kind === 'remove' && (
+