feat(manager): expenses, the supplier book and tabs on v2 (platform-v2 step 6.13a)

- Finance -> Expenses: still owed, late, filters, new/edit (supplier picked or added there), pay in parts, details with payments, delete
- CRM -> Contacts: the supplier book with what each one is owed
- Finance -> Tabs: open (who owes most first) / settled, charges and payments, pay (cash/card/other), close, forgive
- backend: expenses.manage / tabs.manage (the list also reports.view, a customer's tabs also crm.manage, put-on-tab needs tabs.manage);
  payment <= due (expense.over_due), total >= paid (expense.below_paid), categories/kinds/methods checked, null clears a field;
  live events expenses.changed / tabs.changed; GET /api/expenses ?from=&to= venue dates (the report uses it); tab_status=settled
- fix: an expense with a due date failed to save (naive date refused by D-11)
- @xenia/i18n/number subpath; tests: test_finance.py (6), finance.test.mjs (5), e2e manager.mjs finance flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 12:54:21 +02:00
co-authored by Claude Opus 5.5
parent 6bdf0bdd79
commit 93c0dd7d9c
32 changed files with 1667 additions and 1153 deletions
+2
View File
@@ -196,6 +196,8 @@ CODES: dict[str, tuple[int, str]] = {
"transfer.version": (400, "This export's version isn't supported."), "transfer.version": (400, "This export's version isn't supported."),
"contact.not_found": (404, "Contact not found."), "contact.not_found": (404, "Contact not found."),
"expense.not_found": (404, "Expense 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.not_found": (404, "Mark not found."),
"flag.in_use": (409, "This mark is on {count} table(s). Remove it there first."), "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."), "flag.invalid_ids": (400, "Some of these marks don't exist."),
+91 -20
View File
@@ -1,5 +1,12 @@
from core.timeutil import utcnow """Expenses and the supplier book (module `expenses`; manager pages in plan step 6.13a).
from datetime import datetime, timezone
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 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
@@ -12,14 +19,42 @@ from schemas.expenses import (
ExpenseCreate, ExpenseUpdate, ExpenseOut, ExpenseCreate, ExpenseUpdate, ExpenseOut,
ExpensePaymentCreate, ExpensePaymentOut, ExpensePaymentCreate, ExpensePaymentOut,
) )
from routers.deps import require_manager from core.access.deps import require, require_any
from core.errors import XeniaError from core.errors import XeniaError
from core.timeutil import venue_day_window
from services.ws_bus import broadcast_sync
contacts_router = APIRouter() contacts_router = APIRouter()
expenses_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: def _expense_status(total: float, paid: float) -> str:
if paid >= total: if paid >= total:
@@ -77,7 +112,7 @@ def _expense_out(e: Expense) -> dict:
def list_contacts( def list_contacts(
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 = MANAGE,
): ):
q = db.query(Contact) q = db.query(Contact)
if not include_inactive: if not include_inactive:
@@ -86,33 +121,45 @@ def list_contacts(
@contacts_router.post("/", response_model=ContactOut, status_code=status.HTTP_201_CREATED) @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)): def create_contact(body: ContactCreate, db: Session = Depends(get_db), user: User = MANAGE):
contact = Contact(**body.model_dump()) fields = body.model_dump()
_check_contact(fields)
fields["name"] = fields["name"].strip()
contact = Contact(**fields)
db.add(contact) db.add(contact)
db.commit() db.commit()
db.refresh(contact) db.refresh(contact)
_changed()
return contact return contact
@contacts_router.put("/{contact_id}", response_model=ContactOut) @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() contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact: if not contact:
raise XeniaError("contact.not_found") raise XeniaError("contact.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (phone, e-mail...); name and type only change when given
setattr(contact, field, value) 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.commit()
db.refresh(contact) db.refresh(contact)
_changed()
return contact return contact
@contacts_router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT) @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() contact = db.query(Contact).filter(Contact.id == contact_id).first()
if not contact: if not contact:
raise XeniaError("contact.not_found") raise XeniaError("contact.not_found")
contact.is_active = False contact.is_active = False
db.commit() db.commit()
_changed()
# ── Expenses ────────────────────────────────────────────────────────────────── # ── Expenses ──────────────────────────────────────────────────────────────────
@@ -120,7 +167,7 @@ def delete_contact(contact_id: int, db: Session = Depends(get_db), user: User =
@expenses_router.get("/summary") @expenses_router.get("/summary")
def expense_summary( def expense_summary(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
expenses = db.query(Expense).all() 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) 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, category: Optional[str] = None,
contact_id: Optional[int] = None, contact_id: Optional[int] = None,
business_day_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), 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] result = [_expense_out(e) for e in expenses]
if expense_status: if expense_status:
result = [e for e in result if e["status"] == 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) @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)): def create_expense(body: ExpenseCreate, db: Session = Depends(get_db), user: User = MANAGE):
expense = Expense(**body.model_dump(), created_by_id=user.id) 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.add(expense)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
@expenses_router.put("/{expense_id}", response_model=ExpenseOut) @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() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise XeniaError("expense.not_found") raise XeniaError("expense.not_found")
for field, value in body.model_dump(exclude_none=True).items(): # Fields sent as null are cleared (supplier, due date, notes); the rest only change when given
setattr(expense, field, value) 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.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
@expenses_router.delete("/{expense_id}", status_code=status.HTTP_204_NO_CONTENT) @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() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise XeniaError("expense.not_found") raise XeniaError("expense.not_found")
db.delete(expense) db.delete(expense)
db.commit() db.commit()
_changed()
@expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut) @expenses_router.post("/{expense_id}/pay", response_model=ExpenseOut)
@@ -197,13 +264,16 @@ def record_payment(
expense_id: int, expense_id: int,
body: ExpensePaymentCreate, body: ExpensePaymentCreate,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
expense = db.query(Expense).filter(Expense.id == expense_id).first() expense = db.query(Expense).filter(Expense.id == expense_id).first()
if not expense: if not expense:
raise XeniaError("expense.not_found") raise XeniaError("expense.not_found")
if body.amount <= 0: if body.amount <= 0:
raise XeniaError("validation.positive", field='amount') 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( payment = ExpensePayment(
expense_id=expense_id, expense_id=expense_id,
amount=body.amount, amount=body.amount,
@@ -217,4 +287,5 @@ def record_payment(
expense.paid_amount = round(sum(p.amount for p in all_payments), 2) expense.paid_amount = round(sum(p.amount for p in all_payments), 2)
db.commit() db.commit()
db.refresh(expense) db.refresh(expense)
_changed()
return _expense_out(expense) return _expense_out(expense)
+4 -1
View File
@@ -57,6 +57,7 @@ class RevertPaymentRequest(BaseModel):
item_ids: List[int] item_ids: List[int]
from routers.deps import get_current_user, require_manager 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 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 models.settings import PosSettings
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
@@ -2019,7 +2020,7 @@ def put_item_on_tab(
order_id: int, order_id: int,
item_id: int, item_id: int,
db: Session = Depends(get_db), 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 from models.tabs import Tab, TabEntry
@@ -2061,6 +2062,8 @@ def put_item_on_tab(
db.commit() db.commit()
broadcast_sync("order_updated", {"order_id": order.id, "table_id": order.table_id, "status": order.status, "action": "item_tabbed"}) 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} return {"status": "tabbed", "tab_id": tab.id, "entry_amount": entry.amount}
+39 -14
View File
@@ -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 core.timeutil import utcnow
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, status from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import List, Optional from typing import List, Optional
@@ -10,13 +18,19 @@ 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.tabs import TabOut, TabEntryOut, TabPaymentOut, TabPayRequest, TabForgiveRequest, TabCloseRequest 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 core.errors import XeniaError
from services.ws_bus import broadcast_sync
router = APIRouter() router = APIRouter()
MANAGE = Depends(require("tabs.manage"))
METHODS = ("cash", "card", "other")
def changed():
broadcast_sync("tabs.changed", {})
def _tab_out(tab: Tab) -> dict: def _tab_out(tab: Tab) -> dict:
c = tab.customer c = tab.customer
@@ -75,10 +89,12 @@ def list_tabs(
tab_status: Optional[str] = None, tab_status: Optional[str] = None,
customer_id: Optional[int] = None, customer_id: Optional[int] = None,
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: User = Depends(require_manager), user: User = MANAGE,
): ):
q = db.query(Tab) 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) q = q.filter(Tab.status == tab_status)
else: else:
q = q.filter(Tab.status == "open") # default: only open tabs 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) q = q.filter(Tab.customer_id == customer_id)
tabs = q.order_by(Tab.opened_at.desc()).all() tabs = q.order_by(Tab.opened_at.desc()).all()
result = [_tab_out(t) for t in tabs] result = [_tab_out(t) for t in tabs]
# Sort open tabs by balance descending if tab_status in (None, "open"):
result.sort(key=lambda x: x["balance"], reverse=True) result.sort(key=lambda x: x["balance"], reverse=True) # who owes most first
return result return result
@router.get("/{tab_id}", response_model=TabOut) @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() tab = db.query(Tab).filter(Tab.id == tab_id).first()
if not tab: if not tab:
raise XeniaError("tab.not_found") 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) @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() customer = db.query(Customer).filter(Customer.id == customer_id, Customer.is_active == True).first()
if not customer: if not customer:
raise XeniaError("customer.not_found") 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.add(tab)
db.commit() db.commit()
db.refresh(tab) db.refresh(tab)
changed()
return _tab_out(tab) return _tab_out(tab)
@@ -122,7 +139,7 @@ def add_tab_entry(
amount: float = 0.0, amount: float = 0.0,
description: Optional[str] = None, description: Optional[str] = None,
db: Session = Depends(get_db), 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() tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab: if not tab:
@@ -136,6 +153,7 @@ def add_tab_entry(
db.add(entry) db.add(entry)
db.commit() db.commit()
db.refresh(tab) db.refresh(tab)
changed()
return _tab_out(tab) return _tab_out(tab)
@@ -144,7 +162,7 @@ def pay_tab(
tab_id: int, tab_id: int,
body: TabPayRequest, body: TabPayRequest,
db: Session = Depends(get_db), 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() tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab: if not tab:
@@ -156,14 +174,18 @@ def pay_tab(
balance = total_charged - total_paid balance = total_charged - total_paid
if body.amount > balance + 0.005: if body.amount > balance + 0.005:
raise XeniaError("tab.over_balance", balance=f'{balance:.2f}') 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( payment = TabPayment(
tab_id=tab_id, amount=body.amount, 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, received_by_id=user.id,
) )
db.add(payment) db.add(payment)
db.commit() db.commit()
db.refresh(tab) db.refresh(tab)
changed()
return _tab_out(tab) return _tab_out(tab)
@@ -172,7 +194,7 @@ def close_tab(
tab_id: int, tab_id: int,
body: TabCloseRequest, body: TabCloseRequest,
db: Session = Depends(get_db), 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() tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab: if not tab:
@@ -189,6 +211,7 @@ def close_tab(
tab.notes = body.notes tab.notes = body.notes
db.commit() db.commit()
db.refresh(tab) db.refresh(tab)
changed()
return _tab_out(tab) return _tab_out(tab)
@@ -197,7 +220,7 @@ def forgive_tab(
tab_id: int, tab_id: int,
body: TabForgiveRequest, body: TabForgiveRequest,
db: Session = Depends(get_db), 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() tab = db.query(Tab).filter(Tab.id == tab_id, Tab.status == "open").first()
if not tab: if not tab:
@@ -209,13 +232,15 @@ def forgive_tab(
tab.notes = body.reason tab.notes = body.reason
db.commit() db.commit()
db.refresh(tab) db.refresh(tab)
changed()
return _tab_out(tab) return _tab_out(tab)
# ── Customer tabs ────────────────────────────────────────────────────────────── # ── Customer tabs ──────────────────────────────────────────────────────────────
@router.get("/customer/{customer_id}", response_model=List[TabOut]) @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( tabs = db.query(Tab).filter(Tab.customer_id == customer_id).order_by(
Tab.status.asc(), # open first Tab.status.asc(), # open first
Tab.opened_at.desc(), Tab.opened_at.desc(),
+15 -1
View File
@@ -1,7 +1,9 @@
from pydantic import BaseModel from pydantic import BaseModel, field_validator
from typing import Optional, List from typing import Optional, List
from datetime import datetime from datetime import datetime
from core.timeutil import parse_api_datetime
# ── Contacts ────────────────────────────────────────────────────────────────── # ── Contacts ──────────────────────────────────────────────────────────────────
@@ -66,6 +68,12 @@ class ExpenseCreate(BaseModel):
business_day_id: Optional[int] = None business_day_id: Optional[int] = None
notes: Optional[str] = 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): class ExpenseUpdate(BaseModel):
description: Optional[str] = None description: Optional[str] = None
@@ -75,6 +83,12 @@ class ExpenseUpdate(BaseModel):
due_date: Optional[datetime] = None due_date: Optional[datetime] = None
notes: Optional[str] = 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): class ExpenseOut(BaseModel):
id: int id: int
+124
View File
@@ -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
+3 -3
View File
@@ -21,12 +21,12 @@ import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage' import QrCodesPage from './pages/online/QrCodesPage'
// CRM // CRM
import ContactsPage from './pages/crm/ContactsPage' import ContactsPage from './pages/finance/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage' import CustomersPage from './pages/crm/CustomersPage'
// Financials // Financials
import ExpensesPage from './pages/financials/ExpensesPage' import ExpensesPage from './pages/finance/ExpensesPage'
import TabsPage from './pages/financials/TabsPage' import TabsPage from './pages/finance/TabsPage'
// Management // Management
import ProductsPage from './pages/products/ProductsPage' import ProductsPage from './pages/products/ProductsPage'
@@ -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 (
<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: 520,
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: 14 }}>
<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>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τύπος</label>
<select style={inputStyle} value={form.type} onChange={e => f('type', e.target.value)}>
{Object.entries(TYPE_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
</select>
</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.phone} onChange={e => f('phone', e.target.value)} placeholder="π.χ. 6912345678" />
</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="info@example.com" />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Διεύθυνση</label>
<input style={inputStyle} value={form.address} onChange={e => f('address', e.target.value)} placeholder="Οδός, Πόλη" />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις</label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={3} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Εσωτερικές σημειώσεις…" />
</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={!canSave || isPending}
style={{
padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600,
cursor: canSave && !isPending ? 'pointer' : 'default',
background: canSave ? '#111827' : '#e5e7eb',
color: canSave ? 'white' : '#9ca3af',
}}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Header */}
<div style={{ padding: '18px 28px 14px', borderBottom: '1px solid #f0f0ef', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0, background: 'white' }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>{contacts.length} ενεργές επαφές</p>
</div>
<button
onClick={() => setModal({ contact: null })}
style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέα Επαφή
</button>
</div>
{/* Table */}
<div style={{ flex: 1, overflowY: 'auto', padding: '20px 28px' }}>
{isLoading && <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0' }}>Φόρτωση…</div>}
{!isLoading && contacts.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0', fontSize: 14 }}>
Δεν υπάρχουν επαφές ακόμα. Προσθέστε τον πρώτο προμηθευτή.
</div>
)}
{contacts.length > 0 && (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13.5 }}>
<thead>
<tr style={{ background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
{['Όνομα', 'Τύπος', 'Τηλέφωνο', 'Email', ''].map(h => (
<th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{contacts.map((c, i) => {
const tc = TYPE_COLORS[c.type] || TYPE_COLORS.other
return (
<tr key={c.id} style={{ borderBottom: i < contacts.length - 1 ? '1px solid #f3f4f6' : 'none', background: 'white' }}>
<td style={{ padding: '12px 16px', fontWeight: 600, color: '#111315' }}>
{c.name}
{c.notes && <div style={{ fontSize: 11.5, color: '#9ca3af', fontWeight: 400, marginTop: 1 }}>{c.notes.slice(0, 60)}{c.notes.length > 60 ? '…' : ''}</div>}
</td>
<td style={{ padding: '12px 16px' }}>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: tc.bg, color: tc.color }}>
{TYPE_LABELS[c.type] || c.type}
</span>
</td>
<td style={{ padding: '12px 16px', color: c.phone ? '#374151' : '#d1d5db' }}>{c.phone || '—'}</td>
<td style={{ padding: '12px 16px', color: c.email ? '#374151' : '#d1d5db' }}>{c.email || '—'}</td>
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
<button
onClick={() => setModal({ contact: c })}
style={{ padding: '4px 12px', borderRadius: 6, border: '1px solid #e5e7eb', background: 'white', fontSize: 12, fontWeight: 500, cursor: 'pointer', color: '#374151' }}
>
Επεξεργασία
</button>
<button
onClick={() => { if (window.confirm(`Αποενεργοποίηση "${c.name}";`)) deactivate.mutate(c.id) }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', fontSize: 12, cursor: 'pointer', color: '#ef4444' }}
>
Απενεργ.
</button>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
{modal && (
<ContactModal
initial={modal.contact ? { ...modal.contact, phone: modal.contact.phone || '', email: modal.contact.email || '', address: modal.contact.address || '', notes: modal.contact.notes || '' } : null}
onClose={() => 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,
})}
/>
)}
</div>
)
}
@@ -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 (
<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: 540, 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: 14 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Περιγραφή *</label>
<input style={inputStyle} value={form.description} onChange={e => f('description', 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>
<select style={inputStyle} value={form.category} onChange={e => f('category', e.target.value)}>
{CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
</select>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό (€) *</label>
<input style={inputStyle} type="number" step="0.01" min="0" value={form.total_amount} onChange={e => f('total_amount', e.target.value)} placeholder="0.00" />
</div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Επαφή / Προμηθευτής</label>
<select style={inputStyle} value={form.contact_id} onChange={e => f('contact_id', e.target.value)}>
<option value="">— Χωρίς επαφή —</option>
{contacts.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ημ/νία πληρωμής</label>
<input style={inputStyle} type="date" value={form.due_date ? form.due_date.slice(0, 10) : ''} onChange={e => f('due_date', e.target.value)} />
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημειώσεις</label>
<textarea style={{ ...inputStyle, resize: 'none' }} rows={2} value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Προαιρετικές σημειώσεις…" />
</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={!canSave || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canSave && !isPending ? 'pointer' : 'default', background: canSave ? '#111827' : '#e5e7eb', color: canSave ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : isNew ? 'Δημιουργία' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
// ── 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 (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<h2 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Καταγραφή Πληρωμής</h2>
<p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{expense.description}</p>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ background: '#f9fafb', borderRadius: 10, padding: '12px 14px', display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 13, color: '#6b7280' }}>Εκκρεμεί</span>
<span style={{ fontSize: 15, fontWeight: 700, color: '#dc2626' }}>{fmt(expense.due_amount)}</span>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό πληρωμής (€)</label>
<input style={inputStyle} type="number" step="0.01" min="0.01" max={expense.due_amount} value={amount} onChange={e => setAmount(e.target.value)} autoFocus />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημείωση</label>
<input style={inputStyle} value={notes} onChange={e => setNotes(e.target.value)} placeholder="π.χ. Μετρητά στο χέρι" />
</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={() => onPay(parsed, notes || null)}
disabled={!canPay || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canPay && !isPending ? 'pointer' : 'default', background: canPay ? '#16a34a' : '#e5e7eb', color: canPay ? 'white' : '#9ca3af' }}
>
{isPending ? 'Αποθήκευση…' : 'Καταγραφή Πληρωμής'}
</button>
</div>
</div>
</div>
)
}
// ── 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 (
<>
<tr
onClick={onToggle}
style={{ borderBottom: '1px solid #f3f4f6', cursor: 'pointer', background: isExpanded ? '#f9fafb' : 'white' }}
>
<td style={{ padding: '12px 16px' }}>
<div style={{ fontWeight: 600, color: '#111315', fontSize: 13.5 }}>{expense.description}</div>
{expense.contact_name && <div style={{ fontSize: 11.5, color: '#9ca3af', marginTop: 1 }}>{expense.contact_name}</div>}
</td>
<td style={{ padding: '12px 16px', fontSize: 12, color: '#6b7280' }}>{catLabel}</td>
<td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 600, color: '#111315', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{fmt(expense.total_amount)}</td>
<td style={{ padding: '12px 16px', fontSize: 13, color: '#16a34a', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.paid_amount > 0 ? fmt(expense.paid_amount) : '—'}</td>
<td style={{ padding: '12px 16px', fontSize: 13, fontWeight: 700, color: '#dc2626', fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>{expense.due_amount > 0 ? fmt(expense.due_amount) : '—'}</td>
<td style={{ padding: '12px 16px' }}>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: sc.bg, color: sc.color }}>{sc.label}</span>
</td>
<td style={{ padding: '12px 16px', fontSize: 12, color: '#9ca3af' }}>{expense.due_date ? fmtDate(expense.due_date) : '—'}</td>
<td style={{ padding: '12px 16px', textAlign: 'right' }}>
<div style={{ display: 'flex', gap: 5, justifyContent: 'flex-end' }}>
{expense.status !== 'paid' && (
<button
onClick={e => { e.stopPropagation(); onPay() }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #bbf7d0', background: '#f0fdf4', fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#16a34a' }}
>
Πληρωμή
</button>
)}
<button
onClick={e => { e.stopPropagation(); onEdit() }}
style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid #e5e7eb', background: 'white', fontSize: 12, cursor: 'pointer', color: '#374151' }}
>
Επεξ.
</button>
<button
onClick={e => { e.stopPropagation(); onDelete() }}
style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid #fecaca', background: 'white', fontSize: 12, cursor: 'pointer', color: '#ef4444' }}
>
✕
</button>
</div>
</td>
</tr>
{isExpanded && (
<tr style={{ background: '#f9fafb' }}>
<td colSpan={8} style={{ padding: '12px 16px 16px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{expense.notes && (
<p style={{ margin: 0, fontSize: 12.5, color: '#6b7280', fontStyle: 'italic' }}>📝 {expense.notes}</p>
)}
<div style={{ fontSize: 11.5, color: '#9ca3af' }}>
Καταχωρήθηκε από {expense.created_by_name} · {fmtDate(expense.created_at)}
</div>
{expense.payments.length > 0 && (
<div>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Ιστορικό Πληρωμών</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{expense.payments.map(p => (
<div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 12px', background: 'white', borderRadius: 8, border: '1px solid #e5e7eb' }}>
<span style={{ fontSize: 12.5, color: '#374151' }}>
{p.paid_by_name} · {fmtDateTime(p.paid_at)}
{p.notes && <span style={{ color: '#9ca3af' }}> — {p.notes}</span>}
</span>
<span style={{ fontSize: 13, fontWeight: 700, color: '#16a34a' }}>{fmt(p.amount)}</span>
</div>
))}
</div>
</div>
)}
{expense.payments.length === 0 && expense.status === 'due' && (
<div style={{ fontSize: 12.5, color: '#d1d5db' }}>Δεν έχουν καταγραφεί πληρωμές.</div>
)}
</div>
</td>
</tr>
)}
</>
)
}
// ── 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 (
<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' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<div>
<p style={{ margin: 0, fontSize: 13, color: '#9ca3af' }}>
{pendingCount} εκκρεμή · Σύνολο οφειλών: <strong style={{ color: totalDue > 0 ? '#dc2626' : '#16a34a' }}>{fmt(totalDue)}</strong>
</p>
</div>
<button
onClick={() => setModal({ type: 'expense', expense: null })}
style={{ padding: '9px 18px', borderRadius: 9, border: 'none', background: '#111827', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
>
+ Νέο Έξοδο
</button>
</div>
{/* Filters */}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{/* Status filter */}
<div style={{ display: 'flex', gap: 4 }}>
{[['all', 'Όλα'], ['due', 'Οφείλεται'], ['partial', 'Μερική'], ['paid', 'Πληρώθηκε']].map(([v, l]) => (
<button key={v} onClick={() => setStatusFilter(v)}
style={{
padding: '5px 12px', borderRadius: 20, fontSize: 12, fontWeight: 600, cursor: 'pointer', border: '1.5px solid',
borderColor: statusFilter === v ? '#111827' : '#e5e7eb',
background: statusFilter === v ? '#111827' : 'white',
color: statusFilter === v ? 'white' : '#6b7280',
}}>
{l}
</button>
))}
</div>
{/* Category filter */}
<select
value={categoryFilter}
onChange={e => setCategoryFilter(e.target.value)}
style={{ padding: '5px 10px', borderRadius: 8, border: '1px solid #e5e7eb', fontSize: 12, outline: 'none', background: 'white', color: '#374151' }}
>
<option value="all">Όλες οι κατηγορίες</option>
{CATEGORIES.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
</select>
</div>
</div>
{/* Table */}
<div style={{ flex: 1, overflowY: 'auto', padding: '16px 28px' }}>
{isLoading && <div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0' }}>Φόρτωση…</div>}
{!isLoading && expenses.length === 0 && (
<div style={{ textAlign: 'center', color: '#9ca3af', padding: '48px 0', fontSize: 14 }}>
Δεν βρέθηκαν έξοδα για τα επιλεγμένα φίλτρα.
</div>
)}
{expenses.length > 0 && (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden' }}>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: '#f9fafb', borderBottom: '1px solid #e5e7eb' }}>
{['Περιγραφή', 'Κατηγορία', 'Σύνολο', 'Πληρωμένο', 'Εκκρεμεί', 'Κατάσταση', 'Ημ/νία', ''].map(h => (
<th key={h} style={{ padding: '10px 16px', textAlign: h === 'Σύνολο' || h === 'Πληρωμένο' || h === 'Εκκρεμεί' ? 'right' : 'left', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }}>{h}</th>
))}
</tr>
</thead>
<tbody>
{expenses.map(e => (
<ExpenseRow
key={e.id}
expense={e}
isExpanded={expanded === e.id}
onToggle={() => 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) }}
/>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Expense create/edit modal */}
{modal?.type === 'expense' && (
<ExpenseModal
initial={modal.expense ? {
...modal.expense,
contact_id: modal.expense.contact_id ? String(modal.expense.contact_id) : '',
due_date: modal.expense.due_date || '',
notes: modal.expense.notes || '',
} : null}
contacts={contacts}
onClose={() => 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' && (
<PayModal
expense={modal.expense}
onClose={() => setModal(null)}
isPending={payExpense.isPending}
onPay={(amount, notes) => payExpense.mutate({ id: modal.expense.id, amount, notes })}
/>
)}
</div>
)
}
-411
View File
@@ -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 (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 16, fontWeight: 700 }}>Πληρωμή Καρτέλας</div>
<div style={{ fontSize: 13, color: '#6b7280', marginTop: 2 }}>{tab.customer_name}</div>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ background: '#f9fafb', borderRadius: 10, padding: '12px 14px', display: 'flex', justifyContent: 'space-between' }}>
<span style={{ fontSize: 13, color: '#6b7280' }}>Υπόλοιπο καρτέλας</span>
<span style={{ fontSize: 15, fontWeight: 700, color: '#dc2626' }}>{fmt(tab.balance)}</span>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Ποσό πληρωμής (€)</label>
<input type="number" step="0.01" min="0.01"
value={amount} onChange={e => 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' }} />
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Τρόπος πληρωμής</label>
<div style={{ display: 'flex', gap: 6 }}>
{[['cash', 'Μετρητά'], ['card', 'Κάρτα'], ['other', 'Άλλο']].map(([v, l]) => (
<button key={v} onClick={() => setMethod(v)}
style={{
flex: 1, padding: '7px', borderRadius: 7, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
border: `1.5px solid ${method === v ? '#111827' : '#e5e7eb'}`,
background: method === v ? '#111827' : 'white',
color: method === v ? 'white' : '#6b7280',
}}>{l}</button>
))}
</div>
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Σημείωση</label>
<input value={notes} onChange={e => setNotes(e.target.value)} placeholder="προαιρετικό"
style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button onClick={() => onPay(parsed, method, notes || null)} disabled={!canPay || isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: canPay ? 'pointer' : 'default', background: canPay ? '#16a34a' : '#e5e7eb', color: canPay ? 'white' : '#9ca3af' }}>
{isPending ? 'Αποθήκευση…' : 'Καταγραφή Πληρωμής'}
</button>
</div>
</div>
</div>
)
}
// ── Forgive confirm ───────────────────────────────────────────────────────────
function ForgiveModal({ tab, onClose, onForgive, isPending }) {
const [reason, setReason] = useState('')
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 60, padding: 20 }}>
<div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 400, boxShadow: '0 20px 60px rgba(0,0,0,0.18)' }}>
<div style={{ padding: '18px 22px 14px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 16, fontWeight: 700, color: '#dc2626' }}>Χάρισμα Καρτέλας</div>
<div style={{ fontSize: 13, color: '#6b7280', marginTop: 2 }}>{tab.customer_name} — υπόλοιπο {fmt(tab.balance)}</div>
</div>
<div style={{ padding: '18px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ padding: '12px 14px', background: '#fef2f2', borderRadius: 10, border: '1px solid #fecaca', fontSize: 13, color: '#7f1d1d', lineHeight: 1.5 }}>
Το υπόλοιπο των {fmt(tab.balance)} θα διαγραφεί. Η ενέργεια δεν αναιρείται.
</div>
<div>
<label style={{ fontSize: 12, fontWeight: 600, color: '#374151', display: 'block', marginBottom: 5 }}>Αιτιολογία</label>
<input value={reason} onChange={e => setReason(e.target.value)} placeholder="π.χ. Καλή θέληση"
style={{ width: '100%', padding: '8px 11px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }} />
</div>
</div>
<div style={{ padding: '14px 22px', borderTop: '1px solid #f0f0ef', display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button onClick={onClose} style={{ padding: '8px 18px', border: '1px solid #e5e7eb', background: 'white', borderRadius: 8, fontSize: 13, cursor: 'pointer' }}>Ακύρωση</button>
<button onClick={() => onForgive(reason || null)} disabled={isPending}
style={{ padding: '8px 20px', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', background: '#dc2626', color: 'white' }}>
{isPending ? 'Αποθήκευση…' : 'Χάρισμα Υπολοίπου'}
</button>
</div>
</div>
</div>
)
}
// ── 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 (
<div style={{ border: '1px solid #e5e7eb', borderRadius: 12, overflow: 'hidden', background: 'white' }}>
{/* Clickable header — always visible */}
<button
onClick={() => setExpanded(e => !e)}
style={{
width: '100%', textAlign: 'left',
padding: '14px 18px', background: '#f9fafb',
borderBottom: expanded ? '1px solid #e5e7eb' : 'none',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
flexWrap: 'wrap', gap: 8, cursor: 'pointer',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
<ChevronDown
size={16}
style={{
flexShrink: 0, color: '#9ca3af',
transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
transition: 'transform 0.18s',
}}
/>
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>{tab.customer_name}</div>
<div style={{ fontSize: 12, color: '#9ca3af', marginTop: 1 }}>
Άνοιγμα: {fmtDateTime(tab.opened_at)} · {daysSince(tab.opened_at)} ανοιχτή
</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
<span style={{ fontSize: 22, fontWeight: 800, color: tab.balance > 0 ? '#dc2626' : '#16a34a' }}>
{fmt(tab.balance)}
</span>
<span style={{ fontSize: 11.5, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: sc.bg, color: sc.color }}>
{sc.label}
</span>
</div>
</button>
{/* Expanded body */}
{expanded && (
<>
{/* Stats */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 1, background: '#f0f0ef' }}>
{[
{ 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 => (
<div key={s.label} style={{ background: 'white', padding: '10px 14px', textAlign: 'center' }}>
<div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
<div style={{ fontSize: 15, fontWeight: 800, color: s.color || '#111315', marginTop: 2 }}>{s.value}</div>
</div>
))}
</div>
{/* Entries */}
{tab.entries.length > 0 && (
<div style={{ padding: '12px 18px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Χρεώσεις</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{tab.entries.map(e => (
<div key={e.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
<span style={{ color: '#374151' }}>{e.description || `Χρέωση #${e.id}`}</span>
<span style={{ fontWeight: 600, color: '#dc2626', whiteSpace: 'nowrap', marginLeft: 12 }}>{fmt(e.amount)}</span>
</div>
))}
</div>
</div>
)}
{/* Payments */}
{tab.payments.length > 0 && (
<div style={{ padding: '12px 18px', borderBottom: '1px solid #f0f0ef' }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Πληρωμές</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{tab.payments.map(p => (
<div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }}>
<span style={{ color: '#374151' }}>
{p.received_by_name} · {fmtDateTime(p.created_at)}
{p.payment_method && <span style={{ color: '#9ca3af', marginLeft: 6 }}>({p.payment_method})</span>}
{p.notes && <span style={{ color: '#9ca3af', marginLeft: 6 }}>— {p.notes}</span>}
</span>
<span style={{ fontWeight: 600, color: '#16a34a', whiteSpace: 'nowrap', marginLeft: 12 }}>{fmt(p.amount)}</span>
</div>
))}
</div>
</div>
)}
{/* Actions */}
{tab.status === 'open' && (
<div style={{ padding: '12px 18px', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{tab.balance > 0.005 && (
<button onClick={() => onPay(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: 'none', background: '#16a34a', color: 'white', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
Πληρωμή
</button>
)}
{canClose && (
<button onClick={() => onClose(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid #d1d5db', background: 'white', color: '#374151', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
Κλείσιμο Καρτέλας
</button>
)}
<button onClick={() => onForgive(tab)}
style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid #fecaca', background: 'white', color: '#dc2626', fontSize: 13, fontWeight: 500, cursor: 'pointer', marginLeft: 'auto' }}>
Χάρισμα Υπολοίπου
</button>
</div>
)}
</>
)}
</div>
)
}
// ── Filter chip ───────────────────────────────────────────────────────────────
function FilterChip({ label, active, onClick }) {
return (
<button
onClick={onClick}
className={`px-3 py-1 rounded-full text-[12px] font-semibold border transition-colors ${
active
? 'bg-slate-800 text-white border-slate-800'
: 'bg-white text-slate-500 border-slate-200 hover:border-slate-400 hover:text-slate-700'
}`}
>
{label}
</button>
)
}
// ── 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 (
<div className="flex flex-col h-full overflow-hidden">
{/* Toolbar */}
<div className="px-6 py-3 border-b border-slate-200 bg-white shrink-0 flex items-center gap-3 flex-wrap">
{/* Search */}
<div className="relative flex items-center">
<Search className="absolute left-2.5 h-3.5 w-3.5 text-slate-400 pointer-events-none" />
<input
type="text"
value={search}
onChange={e => 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"
/>
</div>
{/* Status filter chips */}
<div className="flex items-center gap-2">
<FilterChip label={`Ανοιχτές (${openCount})`} active={statusFilter === 'open'} onClick={() => setStatusFilter('open')} />
<FilterChip label={`Κλειστές (${closedCount})`} active={statusFilter === 'closed'} onClick={() => setStatusFilter('closed')} />
<FilterChip label="Όλες" active={statusFilter === 'all'} onClick={() => setStatusFilter('all')} />
</div>
{/* Summary */}
<div className="ml-auto text-[12px] text-slate-400">
{statusFilter === 'open' && totalOutstanding > 0 && (
<span>Σύνολο: <strong className="text-red-600">{fmt(totalOutstanding)}</strong></span>
)}
</div>
</div>
{/* Tab list */}
<div className="flex-1 overflow-y-auto px-6 py-4 flex flex-col gap-3">
{isLoading && (
<div className="text-center text-slate-400 text-[13px] py-12">Φόρτωση…</div>
)}
{!isLoading && filtered.length === 0 && (
<div className="text-center text-slate-400 text-[14px] py-12">
{search ? 'Δεν βρέθηκαν αποτελέσματα.' : 'Δεν υπάρχουν καρτέλες.'}
</div>
)}
{filtered.map(tab => (
<TabDetail
key={tab.id}
tab={tab}
defaultExpanded={false}
onPay={t => setModal({ type: 'pay', tab: t })}
onClose={t => closeTab.mutate(t.id)}
onForgive={t => setModal({ type: 'forgive', tab: t })}
/>
))}
</div>
{modal?.type === 'pay' && (
<PayModal
tab={modal.tab}
onClose={() => setModal(null)}
isPending={payTab.isPending}
onPay={(amount, payment_method, notes) => payTab.mutate({ id: modal.tab.id, amount, payment_method, notes })}
/>
)}
{modal?.type === 'forgive' && (
<ForgiveModal
tab={modal.tab}
onClose={() => setModal(null)}
isPending={forgiveTab.isPending}
onForgive={(reason) => forgiveTab.mutate({ id: modal.tab.id, reason })}
/>
)}
</div>
)
}
@@ -1 +0,0 @@
export { default } from '../ContactsPage'
@@ -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 (
<Dialog open size="md" onClose={onClose} title={isNew ? t('finance.contacts.newTitle') : contact.name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="contact-save">{isNew ? t('finance.contacts.add') : t('finance.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="contact-dialog">
<div className="grid gap-3 sm:grid-cols-[2fr_1fr]">
<Field label={t('finance.contacts.name')} required error={err('name')}>
<Input value={form.name} autoFocus onChange={e => set('name', e.target.value)} data-testid="contact-name" />
</Field>
<Field label={t('finance.contacts.type')}>
<Select value={form.type} onChange={e => set('type', e.target.value)} options={CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))} />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('finance.contacts.phone')}>
<Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} data-testid="contact-phone" />
</Field>
<Field label={t('finance.contacts.email')} error={err('email')}>
<Input type="email" value={form.email} onChange={e => set('email', e.target.value)} />
</Field>
</div>
<Field label={t('finance.contacts.address')}>
<Input value={form.address} onChange={e => set('address', e.target.value)} />
</Field>
<Field label={t('finance.notes')} hint={t('finance.contacts.notesHint')}>
<Textarea rows={3} value={form.notes} onChange={e => set('notes', e.target.value)} />
</Field>
</div>
</Dialog>
)
}
@@ -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 => (
<span className="grid">
<span className="font-semibold text-ink">{c.name}</span>
{c.notes && <span className="text-caption text-ink-2 line-clamp-1">{c.notes}</span>}
</span>) },
{ key: 'type', label: t('finance.contacts.type'), sort: c => t(`finance.contacts.types.${c.type}`), render: c => <Pill tone={TYPE_TONE[c.type] ?? 'neutral'}>{t(`finance.contacts.types.${c.type}`, { defaultValue: c.type })}</Pill> },
{ key: 'phone', label: t('finance.contacts.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: 'email', label: t('finance.contacts.email'), render: c => (c.email ? <a href={`mailto:${c.email}`} onClick={ev => ev.stopPropagation()} className="text-accent-ink hover:underline">{c.email}</a> : '') },
{ key: 'owed', label: t('finance.contacts.owed'), align: 'right', sort: c => owed[c.id]?.due ?? 0, render: c => (owed[c.id]
? <span className="grid"><b className="text-danger-ink">{fmt.formatMoney(owed[c.id].due)}</b><span className="text-caption text-ink-3">{t('finance.contacts.bills', { count: owed[c.id].count })}</span></span> : '') },
{ key: 'actions', label: '', sort: false, render: c => (
<span className="flex justify-end gap-0.5">
<IconButton size="sm" variant="ghost" label={t('finance.contacts.editOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'edit', contact: c }))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('finance.contacts.removeOf', { name: c.name })} onClick={stop(() => setDialog({ kind: 'remove', contact: c }))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="contacts-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('finance.contacts.title')}</h1>
<p className="text-label text-ink-2">{t('finance.contacts.subtitle', { count: all.length })}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'new' })} data-testid="contact-new">{t('finance.contacts.new')}</Button>
</header>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.contacts.search')} aria-label={t('finance.contacts.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.type} onChange={e => set('type', e.target.value)} aria-label={t('finance.contacts.type')}
options={[{ value: '', label: t('finance.contacts.allTypes') }, ...CONTACT_TYPES.map(k => ({ value: k, label: t(`finance.contacts.types.${k}`) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<BookUser size={28} />} title={t('finance.contacts.none')} description={t('finance.contacts.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={c => setDialog({ kind: 'edit', contact: c })} rowTestId="contact-row"
empty={t('finance.contacts.noMatch')} initialSort={{ key: 'name', dir: 'asc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ContactDialog contact={dialog.contact} onClose={close} onSaved={saved} />}
{dialog?.kind === 'remove' && (
<Dialog open size="sm" onClose={close} title={t('finance.contacts.removeTitle', { name: dialog.contact.name })} description={t('finance.contacts.removeBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('finance.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.contact)}>{t('finance.contacts.removeYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,75 @@
// A new expense or an existing one (plan step 6.13a): what it is, its category, the supplier
// (from the supplier book; a new one can be added from here), the amount (comma or dot), the date
// it is due by and notes. The total can't be less than what was paid already.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input, Select, Textarea } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import ContactDialog from './ContactDialog'
import { CATEGORIES, expenseBody, expenseForm, expenseProblems } from './financeLogic'
export default function ExpenseDialog({ expense, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const qc = useQueryClient()
const isNew = !expense
const [form, setForm] = useState(() => expenseForm(expense, fmt.venueDateKey))
const [tried, setTried] = useState(false)
const [addContact, setAddContact] = useState(false)
const { data: contacts = [] } = useLiveQuery({ queryKey: ['contacts'], queryFn: () => client.get('/api/contacts/').then(r => r.data), events: ['expenses.changed'] })
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const paid = expense?.paid_amount ?? 0
const wrong = expenseProblems(form, paid)
const err = k => (tried && wrong.includes(k) ? t(`finance.exp.wrong.${k}`, { paid: fmt.formatMoney(paid) }) : undefined)
const save = useMutation({
mutationFn: body => (isNew ? client.post('/api/expenses/', body) : client.put(`/api/expenses/${expense.id}`, body)),
onSuccess: () => { toast.success(t(isNew ? 'finance.exp.added' : 'finance.exp.saved', { what: form.description.trim() })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(expenseBody(form)) }
// A supplier no longer in the book still shows on its expense
const options = [{ value: '', label: t('finance.exp.noSupplier') },
...contacts.map(c => ({ value: String(c.id), label: c.name })),
...(expense?.contact_id && !contacts.some(c => c.id === expense.contact_id) ? [{ value: String(expense.contact_id), label: expense.contact_name ?? '' }] : [])]
return (
<Dialog open size="lg" onClose={onClose} title={isNew ? t('finance.exp.newTitle') : expense.description}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="expense-save">{isNew ? t('finance.exp.add') : t('finance.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="expense-dialog">
<Field label={t('finance.exp.what')} required error={err('description')}>
<Input value={form.description} autoFocus onChange={e => set('description', e.target.value)} placeholder={t('finance.exp.whatHint')} data-testid="expense-description" />
</Field>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('finance.exp.category')}>
<Select value={form.category} onChange={e => set('category', e.target.value)} data-testid="expense-category"
options={CATEGORIES.map(c => ({ value: c, label: t(`finance.categories.${c}`) }))} />
</Field>
<Field label={t('finance.exp.amount')} required error={err('total_amount') ?? err('below_paid')}>
<Input inputMode="decimal" value={form.total_amount} onChange={e => set('total_amount', e.target.value)} placeholder="0,00" data-testid="expense-amount" />
</Field>
<Field label={t('finance.exp.supplier')} hint={<button type="button" className="text-accent-ink hover:underline" onClick={() => setAddContact(true)}>{t('finance.exp.newSupplier')}</button>}>
<Select value={form.contact_id} onChange={e => set('contact_id', e.target.value)} data-testid="expense-supplier" options={options} />
</Field>
<Field label={t('finance.exp.dueBy')} hint={t('finance.exp.dueByHint')}>
<Input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} data-testid="expense-due-date" />
</Field>
</div>
<Field label={t('finance.notes')}>
<Textarea rows={2} value={form.notes} onChange={e => set('notes', e.target.value)} />
</Field>
</div>
{addContact && (
<ContactDialog onClose={() => setAddContact(false)}
onSaved={c => { setAddContact(false); qc.invalidateQueries({ queryKey: ['contacts'] }); if (c?.id) set('contact_id', String(c.id)) }} />
)}
</Dialog>
)
}
@@ -0,0 +1,47 @@
// A payment towards an expense (plan step 6.13a): all of what is due (the default) or part of
// it, with a note (how, which receipt). No more than what is due.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../../api/client'
import { paymentAmount } from './financeLogic'
export default function ExpensePayDialog({ expense, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const due = expense.due_amount
// In the venue's own way of writing numbers; parseNumber reads it back (1.234,50 or 1,234.50)
const [amount, setAmount] = useState(() => fmt.formatNumber(due, { decimals: 2 }))
const [notes, setNotes] = useState('')
const [tried, setTried] = useState(false)
const value = paymentAmount(amount, due)
const pay = useMutation({
mutationFn: () => client.post(`/api/expenses/${expense.id}/pay`, { amount: value, notes: notes.trim() || null }).then(r => r.data),
onSuccess: e => { toast.success(t(e.status === 'paid' ? 'finance.exp.paidAll' : 'finance.exp.paidPart', { amount: fmt.formatMoney(value), due: fmt.formatMoney(e.due_amount) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (value != null) pay.mutate() }
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.exp.payTitle')} description={expense.description}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={pay.isPending} onClick={submit} data-testid="expense-pay-save">{t('finance.exp.payYes')}</Button>
</>}>
<div className="grid gap-3" data-testid="expense-pay-dialog">
<p className="flex justify-between rounded-card bg-surface-2 p-3 text-body">
<span className="text-ink-2">{t('finance.exp.due')}</span><b className="tabular-nums text-danger-ink">{fmt.formatMoney(due)}</b>
</p>
<Field label={t('finance.exp.payAmount')} required hint={t('finance.exp.payAmountHint')}
error={tried && value == null ? t('finance.exp.wrong.payment', { due: fmt.formatMoney(due) }) : undefined}>
<Input inputMode="decimal" autoFocus value={amount} onChange={e => setAmount(e.target.value)} data-testid="expense-pay-amount" />
</Field>
<Field label={t('finance.notes')}>
<Input value={notes} onChange={e => setNotes(e.target.value)} placeholder={t('finance.exp.payNoteHint')} />
</Field>
</div>
</Dialog>
)
}
@@ -0,0 +1,170 @@
// Finance → Expenses (plan step 6.13a; replaces the v1 ExpensesPage): what the venue owes and has
// paid. New expense (what, category, supplier, amount, due by), a payment (in parts until it's
// paid), edit, delete; filters (unpaid / status, category, text); what is due and what is late.
// The analysis of a period is Reports → Expenses. Live: `expenses.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Banknote, Pencil, Plus, Receipt, 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, Stat, Table } from '../reports/kit/parts'
import ExpenseDialog from './ExpenseDialog'
import ExpensePayDialog from './ExpensePayDialog'
import { CATEGORIES, STATUS_TONE, expenseTotals, filterExpenses, isLate } from './financeLogic'
export default function ExpensesPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [filter, setFilter] = useState({ status: 'unpaid', category: '', q: '' })
const [dialog, setDialog] = useState(null) // { kind: 'new' | 'edit' | 'pay' | 'view' | 'delete', expense }
const { data, isPending, refetch } = useLiveQuery({ queryKey: ['expenses'], queryFn: () => client.get('/api/expenses/').then(r => r.data), events: ['expenses.changed'] })
const all = data ?? []
const today = fmt.venueToday()
const rows = filterExpenses(all, filter)
const owed = expenseTotals(all, today, fmt.venueDateKey)
const shown = expenseTotals(rows, today, fmt.venueDateKey)
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const open = (kind, expense = null) => setDialog({ kind, expense })
const close = () => setDialog(null)
const saved = () => { close(); refetch() }
const remove = useMutation({
mutationFn: e => client.delete(`/api/expenses/${e.id}`),
onSuccess: (_r, e) => { toast.success(t('finance.exp.deleted', { what: e.description })); saved() },
onError: err => toast.error(errorMessage(err, t)),
})
const cat = c => t(`finance.categories.${c}`, { defaultValue: c })
const stop = fn => ev => { ev.stopPropagation(); fn() }
const columns = [
{ key: 'description', label: t('finance.exp.what'), render: e => (
<span className="grid">
<span className="font-semibold text-ink">{e.description}</span>
{e.contact_name && <span className="text-caption text-ink-2">{e.contact_name}</span>}
</span>) },
{ key: 'category', label: t('finance.exp.category'), sort: e => cat(e.category), render: e => cat(e.category) },
{ key: 'created_at', label: t('finance.exp.entered'), render: e => fmt.formatDate(e.created_at) },
{ key: 'due_date', label: t('finance.exp.dueBy'), sort: e => e.due_date ?? '', render: e => (e.due_date
? <span className={isLate(e, today, fmt.venueDateKey) ? 'text-danger-ink font-semibold' : ''}>{fmt.formatDate(e.due_date)}</span> : '') },
{ key: 'total_amount', label: t('finance.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('finance.exp.due'), align: 'right', render: e => (e.due_amount > 0 ? <span className="text-danger-ink font-semibold">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('finance.exp.status'), render: e => (
<span className="flex flex-wrap gap-1">
<Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill>
{isLate(e, today, fmt.venueDateKey) && <Pill tone="danger">{t('finance.exp.late')}</Pill>}
</span>) },
{ key: 'actions', label: '', sort: false, render: e => (
<span className="flex justify-end gap-0.5">
{e.status !== 'paid' && <IconButton size="sm" variant="ghost" label={t('finance.exp.payOf', { what: e.description })} onClick={stop(() => open('pay', e))} data-testid="expense-pay"><Banknote size={15} /></IconButton>}
<IconButton size="sm" variant="ghost" label={t('finance.exp.editOf', { what: e.description })} onClick={stop(() => open('edit', e))}><Pencil size={15} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('finance.exp.deleteOf', { what: e.description })} onClick={stop(() => open('delete', e))}><Trash2 size={15} /></IconButton>
</span>) },
]
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="expenses-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('finance.exp.title')}</h1>
<p className="text-label text-ink-2">{t('finance.exp.subtitle')}</p>
</div>
<Button icon={<Plus size={16} />} onClick={() => open('new')} data-testid="expense-new">{t('finance.exp.new')}</Button>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.exp.owed')} tone={owed.due ? 'danger' : 'success'} value={fmt.formatMoney(owed.due)}
sub={t('finance.exp.unpaid', { count: owed.unpaid })} testId="expenses-owed" />
<Stat label={t('finance.exp.lateTitle')} tone={owed.late ? 'danger' : undefined} value={fmt.formatNumber(owed.late)} sub={t('finance.exp.lateSub')} />
<Stat label={t('finance.exp.shown')} value={fmt.formatMoney(shown.total)}
sub={t('finance.exp.shownSub', { paid: fmt.formatMoney(shown.paid), count: rows.length })} />
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="relative flex-1 min-w-56">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={filter.q} onChange={e => set('q', e.target.value)} placeholder={t('finance.exp.search')} aria-label={t('finance.exp.search')} className="pl-9" />
</div>
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('finance.exp.status')} data-testid="expenses-status"
options={[{ value: '', label: t('finance.exp.all') }, { value: 'unpaid', label: t('finance.exp.unpaidOnly') },
...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={filter.category} onChange={e => set('category', e.target.value)} aria-label={t('finance.exp.category')}
options={[{ value: '', label: t('finance.exp.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: cat(c) }))]} />
</div>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !all.length ? <EmptyState icon={<Receipt size={28} />} title={t('finance.exp.none')} description={t('finance.exp.noneHint')} />
: (
<Panel padded={false}>
<Table columns={columns} rows={rows} onRow={e => open('view', e)} rowTestId="expense-row" empty={t('finance.exp.noMatch')}
initialSort={{ key: 'created_at', dir: 'desc' }} />
</Panel>
)}
</div>
{(dialog?.kind === 'new' || dialog?.kind === 'edit') && <ExpenseDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'pay' && <ExpensePayDialog expense={dialog.expense} onClose={close} onSaved={saved} />}
{dialog?.kind === 'view' && (
<ExpenseView expense={dialog.expense} cat={cat} onClose={close}
onPay={() => open('pay', dialog.expense)} onEdit={() => open('edit', dialog.expense)} />
)}
{dialog?.kind === 'delete' && (
<Dialog open size="sm" onClose={close} title={t('finance.exp.deleteTitle', { what: dialog.expense.description })}
description={dialog.expense.payments?.length ? t('finance.exp.deleteBodyPaid', { count: dialog.expense.payments.length }) : t('finance.exp.deleteBody')}
footer={<>
<Button variant="secondary" onClick={close}>{t('finance.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(dialog.expense)} data-testid="expense-delete-confirm">{t('finance.exp.deleteYes')}</Button>
</>} />
)}
</div>
)
}
/** One expense: amounts, who entered it, notes and every payment. */
function ExpenseView({ expense: e, cat, onClose, onPay, onEdit }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
return (
<Dialog open size="md" onClose={onClose} title={e.description}
description={[cat(e.category), e.contact_name, t('finance.exp.enteredBy', { date: fmt.formatDate(e.created_at), name: e.created_by_name ?? '' })].filter(Boolean).join(' · ')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button variant="secondary" icon={<Pencil size={14} />} onClick={onEdit}>{t('finance.exp.edit')}</Button>
{e.status !== 'paid' && <Button icon={<Banknote size={14} />} onClick={onPay}>{t('finance.exp.pay')}</Button>}
</>}>
<div className="grid gap-3 text-body" data-testid="expense-view">
<div className="grid grid-cols-3 gap-2">
<Figure label={t('finance.exp.total')} value={fmt.formatMoney(e.total_amount)} />
<Figure label={t('finance.exp.paid')} value={fmt.formatMoney(e.paid_amount)} tone="text-success-ink" />
<Figure label={t('finance.exp.due')} value={fmt.formatMoney(e.due_amount)} tone={e.due_amount > 0 ? 'text-danger-ink' : undefined} />
</div>
{e.due_date && <p className="text-label text-ink-2">{t('finance.exp.dueOn', { date: fmt.formatDate(e.due_date) })}</p>}
{e.notes && <p className="text-label text-ink-2 whitespace-pre-wrap">{e.notes}</p>}
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('finance.exp.payments')}</h3>
{e.payments?.length ? (
<ul className="divide-y divide-line">
{e.payments.map(p => (
<li key={p.id} className="py-1.5 flex justify-between gap-3 text-label">
<span>{fmt.formatDateTime(p.paid_at, 'datetimeShort')}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}{p.notes ? ` · ${p.notes}` : ''}</span>
<b className="tabular-nums text-success-ink">{fmt.formatMoney(p.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.exp.noPayments')}</p>}
</div>
</Dialog>
)
}
function Figure({ label, value, tone }) {
return (
<div 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">{label}</span>
<span className={`text-body font-semibold tabular-nums ${tone ?? 'text-ink'}`}>{value}</span>
</div>
)
}
@@ -0,0 +1,85 @@
// A tab's payment and forgiving it (plan step 6.13a). A payment: all of what is owed (the
// default) or part, cash / card / other, a note; no more than what is owed. Forgiving writes off
// what is owed, with a reason, and can't be undone.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Input } from '@xenia/ui'
import client from '../../api/client'
import { PAY_METHODS, paymentAmount } from './financeLogic'
export default function TabDialogs({ dialog, onClose, onSaved }) {
if (dialog?.kind === 'pay') return <PayDialog tab={dialog.tab} onClose={onClose} onSaved={onSaved} />
if (dialog?.kind === 'forgive') return <ForgiveDialog tab={dialog.tab} onClose={onClose} onSaved={onSaved} />
return null
}
function PayDialog({ tab, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [amount, setAmount] = useState(() => fmt.formatNumber(tab.balance, { decimals: 2 }))
const [method, setMethod] = useState('cash')
const [notes, setNotes] = useState('')
const [tried, setTried] = useState(false)
const value = paymentAmount(amount, tab.balance)
const pay = useMutation({
mutationFn: () => client.post(`/api/tabs/${tab.id}/pay`, { amount: value, payment_method: method, notes: notes.trim() || null }).then(r => r.data),
onSuccess: r => { toast.success(t(r.balance > 0.005 ? 'finance.tabs.paidPart' : 'finance.tabs.paidAll', { amount: fmt.formatMoney(value), balance: fmt.formatMoney(r.balance) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (value != null) pay.mutate() }
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.tabs.payTitle')} description={tab.customer_name}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button loading={pay.isPending} onClick={submit} data-testid="tab-pay-save">{t('finance.tabs.payYes')}</Button>
</>}>
<div className="grid gap-3" data-testid="tab-pay-dialog">
<p className="flex justify-between rounded-card bg-surface-2 p-3 text-body">
<span className="text-ink-2">{t('finance.tabs.balance')}</span><b className="tabular-nums text-danger-ink">{fmt.formatMoney(tab.balance)}</b>
</p>
<Field label={t('finance.tabs.payAmount')} required
error={tried && value == null ? t('finance.tabs.wrongPayment', { balance: fmt.formatMoney(tab.balance) }) : undefined}>
<Input inputMode="decimal" autoFocus value={amount} onChange={e => setAmount(e.target.value)} data-testid="tab-pay-amount" />
</Field>
<Field label={t('finance.tabs.method')}>
<span className="grid grid-cols-3 gap-1" role="radiogroup" aria-label={t('finance.tabs.method')}>
{PAY_METHODS.map(m => (
<Button key={m} size="sm" variant={method === m ? 'primary' : 'secondary'} role="radio" aria-checked={method === m} onClick={() => setMethod(m)}>
{t(`finance.tabs.methods.${m}`)}
</Button>
))}
</span>
</Field>
<Field label={t('finance.notes')}>
<Input value={notes} onChange={e => setNotes(e.target.value)} />
</Field>
</div>
</Dialog>
)
}
function ForgiveDialog({ tab, onClose, onSaved }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [reason, setReason] = useState('')
const forgive = useMutation({
mutationFn: () => client.post(`/api/tabs/${tab.id}/forgive`, { reason: reason.trim() || null }),
onSuccess: () => { toast.success(t('finance.tabs.forgiven', { name: tab.customer_name, amount: fmt.formatMoney(tab.balance) })); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
return (
<Dialog open size="sm" onClose={onClose} title={t('finance.tabs.forgiveTitle', { name: tab.customer_name })}
description={t('finance.tabs.forgiveBody', { amount: fmt.formatMoney(tab.balance) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('finance.back')}</Button>
<Button variant="danger" loading={forgive.isPending} onClick={() => forgive.mutate()} data-testid="tab-forgive-confirm">{t('finance.tabs.forgiveYes')}</Button>
</>}>
<Field label={t('finance.tabs.reason')}>
<Input value={reason} autoFocus onChange={e => setReason(e.target.value)} placeholder={t('finance.tabs.reasonHint')} />
</Field>
</Dialog>
)
}
@@ -0,0 +1,164 @@
// Finance → Tabs, pay later (plan step 6.13a; replaces the v1 TabsPage): what each regular
// customer owes. Lines go on a customer's tab from an order (the order's "Put on tab": the tab
// opens by itself). Here: open tabs (who owes most first) or settled ones, search, each tab's
// charges and payments; a payment (cash, card or other; part or all), close one that owes
// nothing, forgive what is owed (with a reason; it can't be undone). Live: `tabs.changed`.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Banknote, CheckCircle2, ChevronDown, CreditCard, HandHeart, Search } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Input, Spinner, cx } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { Stat } from '../reports/kit/parts'
import TabDialogs from './TabDialogs'
import { TAB_TONE, daysBetween, filterTabs, tabActions, tabTotals } from './financeLogic'
export default function TabsPage() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [view, setView] = useState('open') // 'open' | 'settled'
const [q, setQ] = useState('')
const [expanded, setExpanded] = useState(null)
const [dialog, setDialog] = useState(null) // { kind: 'pay' | 'forgive', id }
const live = { events: ['tabs.changed'] }
const openQ = useLiveQuery({ queryKey: ['tabs', 'open'], queryFn: () => client.get('/api/tabs/').then(r => r.data), ...live })
const settledQ = useLiveQuery({ queryKey: ['tabs', 'settled'], queryFn: () => client.get('/api/tabs/', { params: { tab_status: 'settled' } }).then(r => r.data), ...live, enabled: view === 'settled' })
const current = view === 'open' ? openQ : settledQ
const rows = filterTabs(current.data ?? [], q)
const totals = tabTotals(openQ.data ?? [])
// The dialogs read the tab from the current list (a payment just made may not be in the row clicked)
const tabNow = dialog && (openQ.data ?? []).find(x => x.id === dialog.id)
const refresh = () => { openQ.refetch(); if (view === 'settled') settledQ.refetch() }
const closeTab = useMutation({
mutationFn: tab => client.post(`/api/tabs/${tab.id}/close`, {}),
onSuccess: (_r, tab) => { toast.success(t('finance.tabs.closed', { name: tab.customer_name })); refresh() },
onError: err => toast.error(errorMessage(err, t)),
})
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="tabs-page">
<div className="max-w-4xl mx-auto grid gap-4">
<header>
<h1 className="text-title font-semibold text-ink">{t('finance.tabs.title')}</h1>
<p className="text-label text-ink-2">{t('finance.tabs.subtitle')}</p>
</header>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('finance.tabs.owed')} tone={totals.owed ? 'danger' : 'success'} value={fmt.formatMoney(totals.owed)}
sub={t('finance.tabs.openCount', { count: totals.count })} testId="tabs-owed" />
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{['open', 'settled'].map(k => (
<Button key={k} size="sm" variant={view === k ? 'primary' : 'ghost'} role="tab" aria-selected={view === k}
onClick={() => { setView(k); setExpanded(null) }} data-testid={`tabs-view-${k}`}>{t(`finance.tabs.views.${k}`)}</Button>
))}
</span>
<div className="relative flex-1 min-w-56">
<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('finance.tabs.search')} aria-label={t('finance.tabs.search')} className="pl-9" />
</div>
</div>
{current.isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !rows.length ? (
<EmptyState icon={<CreditCard size={28} />} title={q ? t('finance.tabs.noMatch') : t(`finance.tabs.none.${view}`)}
description={!q && view === 'open' ? t('finance.tabs.noneHint') : undefined} />
) : (
<ul className="grid gap-2">
{rows.map(tab => (
<TabCard key={tab.id} tab={tab} open={expanded === tab.id} onToggle={() => setExpanded(e => (e === tab.id ? null : tab.id))}
onPay={() => setDialog({ kind: 'pay', id: tab.id })} onForgive={() => setDialog({ kind: 'forgive', id: tab.id })}
onClose={() => closeTab.mutate(tab)} closing={closeTab.isPending && closeTab.variables?.id === tab.id} />
))}
</ul>
)}
</div>
<TabDialogs dialog={tabNow && !openQ.isFetching ? { kind: dialog.kind, tab: tabNow } : null} onClose={() => setDialog(null)} onSaved={() => { setDialog(null); refresh() }} />
</div>
)
}
function TabCard({ tab, open, onToggle, onPay, onForgive, onClose, closing }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const can = tabActions(tab)
const days = daysBetween(fmt.venueDateKey(tab.opened_at), fmt.venueToday())
const method = m => (m ? t(`finance.tabs.methods.${m}`, { defaultValue: m }) : '')
return (
<li className="rounded-card border border-line bg-surface shadow-raised overflow-hidden" data-testid="tab-card">
<button type="button" onClick={onToggle} aria-expanded={open} className="w-full px-4 py-3 flex flex-wrap items-center gap-3 text-left hover:bg-surface-2">
<ChevronDown size={16} className={cx('text-ink-3 transition-transform', open && 'rotate-180')} aria-hidden="true" />
<span className="grid flex-1 min-w-48">
<span className="text-body font-semibold text-ink">{tab.customer_name}</span>
<span className="text-caption text-ink-2">
{tab.status === 'open'
? t('finance.tabs.openSince', { date: fmt.formatDate(tab.opened_at), count: days })
: t(`finance.tabs.settledOn.${tab.status}`, { date: fmt.formatDate(tab.closed_at) })}
{tab.customer_phone ? ` · ${tab.customer_phone}` : ''}
</span>
</span>
<span className="flex items-center gap-2">
<span className={cx('text-title font-semibold tabular-nums', tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink-2')} data-testid="tab-balance">{fmt.formatMoney(tab.balance)}</span>
<Pill tone={TAB_TONE[tab.status] ?? 'neutral'}>{t(`finance.tabs.status.${tab.status}`, { defaultValue: tab.status })}</Pill>
</span>
</button>
{open && (
<div className="border-t border-line">
<div className="grid grid-cols-3 divide-x divide-line bg-surface-2 text-center">
{[['charged', tab.total_charged, 'text-ink'], ['paid', tab.total_paid, 'text-success-ink'], ['balance', tab.balance, tab.balance > 0.005 ? 'text-danger-ink' : 'text-ink']].map(([k, v, tone]) => (
<span key={k} className="p-2 grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`finance.tabs.${k}`)}</span>
<span className={cx('text-body font-semibold tabular-nums', tone)}>{fmt.formatMoney(v)}</span>
</span>
))}
</div>
<div className="grid gap-3 p-4 sm:grid-cols-2">
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.charges')}</h3>
{tab.entries.length ? (
<ul className="divide-y divide-line text-label">
{tab.entries.map(e => (
<li key={e.id} className="py-1.5 flex justify-between gap-3">
<span className="grid">
<span className="text-ink">{e.description || t('finance.tabs.charge', { id: e.id })}</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(e.created_at, 'datetimeShort')}{e.created_by_name ? ` · ${e.created_by_name}` : ''}{e.order_id ? ` · ${t('finance.tabs.order', { id: e.order_id })}` : ''}</span>
</span>
<b className="tabular-nums">{fmt.formatMoney(e.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.tabs.noCharges')}</p>}
</section>
<section>
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3 mb-1">{t('finance.tabs.payments')}</h3>
{tab.payments.length ? (
<ul className="divide-y divide-line text-label">
{tab.payments.map(p => (
<li key={p.id} className="py-1.5 flex justify-between gap-3">
<span className="grid">
<span className="text-ink">{[method(p.payment_method), p.notes].filter(Boolean).join(' · ')}</span>
<span className="text-caption text-ink-3">{fmt.formatDateTime(p.created_at, 'datetimeShort')}{p.received_by_name ? ` · ${p.received_by_name}` : ''}</span>
</span>
<b className="tabular-nums text-success-ink">{fmt.formatMoney(p.amount)}</b>
</li>
))}
</ul>
) : <p className="text-label text-ink-3">{t('finance.tabs.noPayments')}</p>}
</section>
</div>
{tab.status !== 'open' && tab.notes && <p className="px-4 pb-3 text-label text-ink-2">{tab.notes}</p>}
{(can.pay || can.close || can.forgive) && (
<div className="flex flex-wrap gap-2 px-4 pb-4">
{can.pay && <Button icon={<Banknote size={15} />} onClick={onPay} data-testid="tab-pay">{t('finance.tabs.pay')}</Button>}
{can.close && <Button icon={<CheckCircle2 size={15} />} loading={closing} onClick={onClose} data-testid="tab-close">{t('finance.tabs.close')}</Button>}
{can.forgive && <Button variant="ghost" icon={<HandHeart size={15} />} onClick={onForgive} className="ml-auto" data-testid="tab-forgive">{t('finance.tabs.forgive')}</Button>}
</div>
)}
</div>
)}
</li>
)
}
@@ -0,0 +1,138 @@
// The rules of Finance → Expenses, the supplier book and Finance → Tabs (plan step 6.13a), kept
// out of the components so they are unit-tested (tests/finance.test.mjs). The backend checks the
// same things (routers/expenses.py, routers/tabs.py); these give the message before saving.
import { parseNumber } from '@xenia/i18n/number' // plain JS: Node tests import this file
// As routers/expenses.py CATEGORIES / CONTACT_TYPES and routers/tabs.py METHODS
export const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other']
export const CONTACT_TYPES = ['supplier', 'staff', 'utility', 'other']
export const PAY_METHODS = ['cash', 'card', 'other']
export const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' }
export const TAB_TONE = { open: 'danger', closed: 'success', forgiven: 'neutral' }
const money = text => parseNumber(String(text ?? ''), { decimals: 2, allowNegative: false })
const cents = v => Math.round(v * 100)
// ── Expenses ─────────────────────────────────────────────────────────────────
/** The dialog's fields for a new expense or an existing one (amounts as typed text; the due
* date as the venue date 'YYYY-MM-DD' through `dateKey`, useFormat().venueDateKey). */
export function expenseForm(e, dateKey = d => d) {
return {
description: e?.description ?? '', category: e?.category ?? 'supplier',
contact_id: e?.contact_id ? String(e.contact_id) : '', total_amount: e ? String(e.total_amount) : '',
due_date: e?.due_date ? dateKey(e.due_date) : '', notes: e?.notes ?? '',
}
}
/** Which fields are wrong: description, total_amount (none, zero, or less than what was paid). */
export function expenseProblems(form, paid = 0) {
const out = []
if (!form.description.trim()) out.push('description')
const total = money(form.total_amount)
if (!(total > 0)) out.push('total_amount')
else if (cents(total) < cents(paid)) out.push('below_paid')
return out
}
/** What the API takes. `due_date` is the venue date picked ('' clears it). */
export function expenseBody(form) {
return {
description: form.description.trim(), category: form.category,
contact_id: form.contact_id ? Number(form.contact_id) : null,
total_amount: money(form.total_amount),
due_date: form.due_date || null, notes: form.notes.trim() || null,
}
}
/** A payment's amount: a number above zero and no more than what is due, or null. */
export function paymentAmount(text, due) {
const v = money(text)
return v > 0 && cents(v) <= cents(due) ? v : null
}
/** Is it late? Due before today (venue dates, 'YYYY-MM-DD') and not paid. */
export function isLate(expense, today, dateKey) {
return expense.status !== 'paid' && !!expense.due_date && dateKey(expense.due_date) < today
}
/** The page's list after its filters: status ('' | 'unpaid' | due | partial | paid), category, text. */
export function filterExpenses(list, { status = '', category = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(e => (!status || (status === 'unpaid' ? e.status !== 'paid' : e.status === status))
&& (!category || e.category === category)
&& words.every(w => `${e.description} ${e.contact_name ?? ''} ${e.notes ?? ''}`.toLowerCase().includes(w)))
}
/** Totals of a list: spent, paid, due, how many unpaid, how many late. */
export function expenseTotals(list, today, dateKey) {
const sum = k => Math.round(list.reduce((s, e) => s + (e[k] ?? 0), 0) * 100) / 100
return {
total: sum('total_amount'), paid: sum('paid_amount'), due: sum('due_amount'),
unpaid: list.filter(e => e.status !== 'paid').length,
late: list.filter(e => isLate(e, today, dateKey)).length,
}
}
/** What is owed to each supplier: { [contact_id]: { due, count } } from the expenses. */
export function owedByContact(expenses) {
const out = {}
for (const e of expenses) {
if (!e.contact_id || !(e.due_amount > 0)) continue
const o = (out[e.contact_id] ??= { due: 0, count: 0 })
o.due = Math.round((o.due + e.due_amount) * 100) / 100
o.count += 1
}
return out
}
// ── Suppliers and contacts ───────────────────────────────────────────────────
export function contactForm(c) {
return { name: c?.name ?? '', type: c?.type ?? 'supplier', phone: c?.phone ?? '', email: c?.email ?? '', address: c?.address ?? '', notes: c?.notes ?? '' }
}
export function contactProblems(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 contactBody(form) {
const v = k => form[k].trim() || null
return { name: form.name.trim(), type: form.type, phone: v('phone'), email: v('email'), address: v('address'), notes: v('notes') }
}
export function filterContacts(list, { type = '', q = '' } = {}) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(c => (!type || c.type === type)
&& words.every(w => `${c.name} ${c.phone ?? ''} ${c.email ?? ''} ${c.notes ?? ''}`.toLowerCase().includes(w)))
}
// ── Tabs ─────────────────────────────────────────────────────────────────────
/** Whole venue days a tab has been open ('YYYY-MM-DD' keys). */
export function daysBetween(fromKey, toKey) {
return Math.max(0, Math.round((Date.parse(`${toKey}T00:00:00Z`) - Date.parse(`${fromKey}T00:00:00Z`)) / 86_400_000))
}
/** What can be done with a tab now. */
export function tabActions(tab) {
const open = tab.status === 'open'
return {
pay: open && tab.balance > 0.005,
close: open && tab.balance <= 0.005 && tab.entries.length > 0,
forgive: open && tab.balance > 0.005,
}
}
export function filterTabs(list, q = '') {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean)
return list.filter(tab => words.every(w => `${tab.customer_name ?? ''} ${tab.customer_phone ?? ''}`.toLowerCase().includes(w)))
}
export function tabTotals(open) {
return { owed: Math.round(open.reduce((s, tab) => s + tab.balance, 0) * 100) / 100, count: open.length }
}
@@ -1 +0,0 @@
export { default } from '../ExpensesPage'
@@ -1 +0,0 @@
export { default } from '../TabsPage'
@@ -6,7 +6,7 @@ import { useState } from 'react'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react' import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
import { useCan } from '@xenia/access' import { useCan, useModule } from '@xenia/access'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui' import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
@@ -21,6 +21,8 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatMoney, formatTime } = useFormat() const { formatMoney, formatTime } = useFormat()
const canDiscount = useCan('pricing.discounts.apply') const canDiscount = useCan('pricing.discounts.apply')
const tabsOn = useModule('tabs')
const canTab = useCan('tabs.manage') && tabsOn // what the tab route checks (6.13a)
const [selected, setSelected] = useState([]) const [selected, setSelected] = useState([])
const [cancelling, setCancelling] = useState(false) const [cancelling, setCancelling] = useState(false)
const [discounting, setDiscounting] = useState(false) const [discounting, setDiscounting] = useState(false)
@@ -94,7 +96,7 @@ export default function OrderLines({ order, open, priceEvents, onPay, onChanged
<div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions"> <div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions">
<span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span> <span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span>
<Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button> <Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button>
{order.customer_id && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>} {order.customer_id && canTab && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
{canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>} {canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>}
<Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button> <Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button>
<Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button> <Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button>
@@ -1,6 +1,7 @@
// Reports → Expenses (plan step 6.12c; replaces the v1 expenses report): what the venue spent in // Reports → Expenses (plan step 6.12c; replaces the v1 expenses report): what the venue spent in
// a period (by the day each expense was entered), paid and still due; split by category or by // a period (by the day each expense was entered), paid and still due; split by category or by
// supplier; every expense, a tap shows its payments. Entering expenses is Finance → Expenses. // supplier; every expense, a tap shows its payments. Entering expenses is Finance → Expenses.
// The period is filtered by the server (venue dates, 6.13a); categories / statuses are `finance.*` texts.
import { useState } from 'react' import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Select } from '@xenia/ui' import { Button, Dialog, Select } from '@xenia/ui'
@@ -11,9 +12,8 @@ import { BarList } from '../kit/charts'
import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts' import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period' import { PeriodPicker } from '../kit/Period'
import { defaultPeriod } from '../kit/reportLogic' import { defaultPeriod } from '../kit/reportLogic'
import { CATEGORIES, STATUS_TONE } from '../../finance/financeLogic'
const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' }
const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other'] // as Finance → Expenses saves them (models/expenses.py)
export default function ExpensesReport() { export default function ExpensesReport() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -28,11 +28,10 @@ function Expenses() {
const [category, setCategory] = useState('') const [category, setCategory] = useState('')
const [split, setSplit] = useState('category') const [split, setSplit] = useState('category')
const [open, setOpen] = useState(null) const [open, setOpen] = useState(null)
const params = { ...(status ? { status } : {}), ...(category ? { category } : {}) } const params = { ...(period.from ? { from: period.from } : {}), ...(period.to ? { to: period.to } : {}), ...(status ? { status } : {}), ...(category ? { category } : {}) }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data) }) const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data), events: ['expenses.changed'] })
const catName = c => t(`reports.exp.categories.${c}`, { defaultValue: c }) const catName = c => t(`finance.categories.${c}`, { defaultValue: c })
const inPeriod = e => { const d = fmt.venueDateKey(e.created_at); return (!period.from || d >= period.from) && (!period.to || d <= period.to) } const rows = data ?? []
const rows = (data ?? []).filter(inPeriod)
const sum = k => rows.reduce((s, e) => s + (e[k] ?? 0), 0) const sum = k => rows.reduce((s, e) => s + (e[k] ?? 0), 0)
const groups = Object.values(rows.reduce((m, e) => { const groups = Object.values(rows.reduce((m, e) => {
const k = split === 'category' ? e.category : (e.contact_name || t('reports.exp.noSupplier')) const k = split === 'category' ? e.category : (e.contact_name || t('reports.exp.noSupplier'))
@@ -48,13 +47,13 @@ function Expenses() {
{ key: 'contact_name', label: t('reports.exp.supplier'), render: e => e.contact_name || '' }, { key: 'contact_name', label: t('reports.exp.supplier'), render: e => e.contact_name || '' },
{ key: 'total_amount', label: t('reports.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) }, { key: 'total_amount', label: t('reports.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) },
{ key: 'due_amount', label: t('reports.exp.due'), align: 'right', render: e => (e.due_amount ? <span className="text-danger-ink">{fmt.formatMoney(e.due_amount)}</span> : '') }, { key: 'due_amount', label: t('reports.exp.due'), align: 'right', render: e => (e.due_amount ? <span className="text-danger-ink">{fmt.formatMoney(e.due_amount)}</span> : '') },
{ key: 'status', label: t('reports.status'), render: e => <Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`reports.exp.status.${e.status}`, { defaultValue: e.status })}</Pill> }, { key: 'status', label: t('reports.status'), render: e => <Pill tone={STATUS_TONE[e.status] ?? 'neutral'}>{t(`finance.status.${e.status}`, { defaultValue: e.status })}</Pill> },
] ]
return ( return (
<div className="grid gap-4"> <div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} allowDay={false} right={<span className="flex gap-2 items-end"> <PeriodPicker value={period} onChange={setPeriod} allowDay={false} right={<span className="flex gap-2 items-end">
<Select size="sm" value={status} onChange={e => setStatus(e.target.value)} aria-label={t('reports.status')} <Select size="sm" value={status} onChange={e => setStatus(e.target.value)} aria-label={t('reports.status')}
options={[{ value: '', label: t('reports.store.anyStatus') }, ...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`reports.exp.status.${s}`) }))]} /> options={[{ value: '', label: t('reports.store.anyStatus') }, ...['due', 'partial', 'paid'].map(s => ({ value: s, label: t(`finance.status.${s}`) }))]} />
<Select size="sm" value={category} onChange={e => setCategory(e.target.value)} aria-label={t('reports.prod.category')} <Select size="sm" value={category} onChange={e => setCategory(e.target.value)} aria-label={t('reports.prod.category')}
options={[{ value: '', label: t('reports.prod.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: catName(c) }))]} /> options={[{ value: '', label: t('reports.prod.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: catName(c) }))]} />
</span>} /> </span>} />
+3 -3
View File
@@ -41,15 +41,15 @@ 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: DASH }, { 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: DASH },
], ],
}, },
{ {
group: 'financials', icon: Receipt, label: 'nav.finance', group: 'financials', icon: Receipt, label: 'nav.finance',
children: [ children: [
{ to: '/financials/expenses', icon: Receipt, label: 'nav.expenses', module: 'expenses', perm: DASH }, { to: '/financials/expenses', icon: Receipt, label: 'nav.expenses', module: 'expenses', perm: 'expenses.manage' },
{ to: '/financials/tabs', icon: CreditCard, label: 'nav.tabs', module: 'tabs', perm: DASH }, { to: '/financials/tabs', icon: CreditCard, label: 'nav.tabs', module: 'tabs', perm: 'tabs.manage' },
], ],
}, },
], ],
+67
View File
@@ -0,0 +1,67 @@
// Expenses, the supplier book and tabs as plain data (plan step 6.13a).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
contactBody, contactForm, contactProblems, daysBetween, expenseBody, expenseForm, expenseProblems, expenseTotals,
filterContacts, filterExpenses, filterTabs, isLate, owedByContact, paymentAmount, tabActions, tabTotals,
} from '../src/pages/finance/financeLogic.js'
const key = iso => iso.slice(0, 10)
const expenses = [
{ id: 1, description: 'Γάλα Νοεμβρίου', category: 'supplier', contact_id: 7, contact_name: 'Dairy Nikos', total_amount: 120, paid_amount: 70, due_amount: 50, status: 'partial', due_date: '2026-11-18T22:00:00Z' },
{ id: 2, description: 'Rent', category: 'rent', contact_id: null, total_amount: 800, paid_amount: 800, due_amount: 0, status: 'paid', due_date: '2026-11-01T00:00:00Z' },
{ id: 3, description: 'Feta', category: 'supplier', contact_id: 7, contact_name: 'Dairy Nikos', total_amount: 40, paid_amount: 0, due_amount: 40, status: 'due', due_date: null, notes: 'two tins' },
]
test('an expense form: typed amounts with a comma, the due date as a venue date, cleared fields as null', () => {
const f = expenseForm(expenses[0], key)
assert.equal(f.due_date, '2026-11-18')
assert.equal(f.contact_id, '7')
assert.deepEqual(expenseProblems({ ...f, total_amount: '120,50' }, 70), [])
assert.deepEqual(expenseProblems({ ...f, description: ' ', total_amount: '0' }), ['description', 'total_amount'])
assert.deepEqual(expenseProblems({ ...f, total_amount: '60' }, 70), ['below_paid'])
assert.deepEqual(expenseBody({ ...f, total_amount: '120,50', contact_id: '', due_date: '', notes: ' ' }),
{ description: 'Γάλα Νοεμβρίου', category: 'supplier', contact_id: null, total_amount: 120.5, due_date: null, notes: null })
assert.equal(expenseForm(null).category, 'supplier')
})
test('a payment is above zero and no more than what is due', () => {
assert.equal(paymentAmount('50', 50), 50)
assert.equal(paymentAmount('20,25', 50), 20.25)
assert.equal(paymentAmount('50,01', 50), null)
assert.equal(paymentAmount('0', 50), null)
assert.equal(paymentAmount('abc', 50), null)
})
test('filters, totals, late ones and what each supplier is owed', () => {
assert.deepEqual(filterExpenses(expenses, { status: 'unpaid' }).map(e => e.id), [1, 3])
assert.deepEqual(filterExpenses(expenses, { category: 'rent' }).map(e => e.id), [2])
assert.deepEqual(filterExpenses(expenses, { q: 'nikos tins' }).map(e => e.id), [3])
assert.deepEqual(filterExpenses(expenses, { q: 'γάλα' }).map(e => e.id), [1])
assert.equal(isLate(expenses[0], '2026-11-19', key), true)
assert.equal(isLate(expenses[1], '2026-11-19', key), false) // paid
assert.deepEqual(expenseTotals(expenses, '2026-11-19', key), { total: 960, paid: 870, due: 90, unpaid: 2, late: 1 })
assert.deepEqual(owedByContact(expenses), { 7: { due: 90, count: 2 } })
})
test('a contact: name needed, a wrong e-mail caught, empty fields cleared', () => {
const f = contactForm(null)
assert.deepEqual(contactProblems(f), ['name'])
assert.deepEqual(contactProblems({ ...f, name: 'A', email: 'nope' }), ['email'])
assert.deepEqual(contactBody({ ...f, name: ' Dairy ', phone: ' ' }), { name: 'Dairy', type: 'supplier', phone: null, email: null, address: null, notes: null })
const list = [{ id: 1, name: 'Dairy Nikos', type: 'supplier', phone: '2310' }, { id: 2, name: 'DEH', type: 'utility' }]
assert.deepEqual(filterContacts(list, { type: 'utility' }).map(c => c.id), [2])
assert.deepEqual(filterContacts(list, { q: '2310' }).map(c => c.id), [1])
})
test('tabs: what can be done, days open, search and what is owed', () => {
const owing = { status: 'open', balance: 12, entries: [{}] }
assert.deepEqual(tabActions(owing), { pay: true, close: false, forgive: true })
assert.deepEqual(tabActions({ ...owing, balance: 0 }), { pay: false, close: true, forgive: false })
assert.deepEqual(tabActions({ ...owing, status: 'closed', balance: 0 }), { pay: false, close: false, forgive: false })
assert.equal(daysBetween('2026-11-01', '2026-11-19'), 18)
assert.equal(daysBetween('2026-11-19', '2026-11-19'), 0)
const tabs = [{ customer_name: 'Kostas «Big K»', customer_phone: '697', balance: 12 }, { customer_name: 'Anna', balance: 3.5 }]
assert.equal(filterTabs(tabs, 'big').length, 1)
assert.deepEqual(tabTotals(tabs), { owed: 15.5, count: 2 })
})
+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/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"
], ],
"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/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"
] ]
} }
+3 -1
View File
@@ -238,7 +238,9 @@
"not_found": "Η επαφή δεν βρέθηκε." "not_found": "Η επαφή δεν βρέθηκε."
}, },
"expense": { "expense": {
"not_found": "Το έξοδο δεν βρέθηκε." "not_found": "Το έξοδο δεν βρέθηκε.",
"over_due": "Είναι περισσότερα από όσα οφείλονται ακόμα ({{due}}).",
"below_paid": "Έχουν ήδη πληρωθεί {{paid}}: το σύνολο δεν μπορεί να είναι λιγότερο."
}, },
"flag": { "flag": {
"not_found": "Η σήμανση δεν βρέθηκε.", "not_found": "Η σήμανση δεν βρέθηκε.",
+186 -14
View File
@@ -3045,23 +3045,195 @@
"what": "Τι", "what": "Τι",
"supplier": "Προμηθευτής", "supplier": "Προμηθευτής",
"total": "Σύνολο", "total": "Σύνολο",
"status": {
"due": "Οφείλεται",
"partial": "Μερικώς",
"paid": "Πληρώθηκε"
},
"categories": {
"supplier": "Προμηθευτές",
"utilities": "Κοινή χρεία",
"rent": "Ενοίκιο",
"maintenance": "Συντήρηση",
"staff": "Προσωπικό",
"equipment": "Εξοπλισμός",
"other": "Άλλο"
},
"dueDate": "Λήξη {{date}}", "dueDate": "Λήξη {{date}}",
"payments": "Πληρωμές", "payments": "Πληρωμές",
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα." "noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα."
} }
},
"finance": {
"back": "Πίσω",
"save": "Αποθήκευση",
"notes": "Σημειώσεις",
"categories": {
"supplier": "Προμηθευτές",
"utilities": "Κοινή χρεία",
"rent": "Ενοίκιο",
"maintenance": "Συντήρηση",
"staff": "Προσωπικό",
"equipment": "Εξοπλισμός",
"other": "Άλλο"
},
"status": {
"due": "Οφείλεται",
"partial": "Μερικώς",
"paid": "Πληρώθηκε"
},
"exp": {
"title": "Δαπάνες",
"subtitle": "Τι οφείλει και τι έχει πληρώσει το κατάστημα. Η ανάλυση μιας περιόδου είναι στις Αναφορές → Δαπάνες.",
"new": "Νέα δαπάνη",
"newTitle": "Νέα δαπάνη",
"add": "Προσθήκη δαπάνης",
"owed": "Οφείλονται",
"unpaid_one": "{{count}} δεν έχει εξοφληθεί",
"unpaid_other": "{{count}} δεν έχουν εξοφληθεί",
"lateTitle": "Εκπρόθεσμες",
"lateSub": "πέρασε η ημερομηνία λήξης, δεν πληρώθηκαν",
"late": "Εκπρόθεσμη",
"shown": "Σε αυτή τη λίστα",
"shownSub_one": "{{count}} δαπάνη · πληρώθηκαν {{paid}}",
"shownSub_other": "{{count}} δαπάνες · πληρώθηκαν {{paid}}",
"search": "Αναζήτηση: τι, προμηθευτής ή σημειώσεις",
"all": "Όλες",
"unpaidOnly": "Ανεξόφλητες",
"allCategories": "Όλες οι κατηγορίες",
"what": "Τι",
"whatHint": "π.χ. Τιμολόγιο Νοεμβρίου: γαλακτοκομικά",
"category": "Κατηγορία",
"entered": "Καταχωρήθηκε",
"dueBy": "Λήξη",
"dueByHint": "Προαιρετικά: έως πότε πρέπει να πληρωθεί.",
"dueOn": "Λήξη {{date}}",
"total": "Σύνολο",
"paid": "Πληρώθηκαν",
"due": "Οφείλονται",
"status": "Κατάσταση",
"amount": "Ποσό",
"supplier": "Προμηθευτής",
"noSupplier": "Χωρίς προμηθευτή",
"newSupplier": "Νέος προμηθευτής…",
"none": "Δεν υπάρχουν δαπάνες ακόμα.",
"noneHint": "Καταχωρήστε ό,τι αγοράζει ή πληρώνει το κατάστημα (προμήθειες, λογαριασμοί, ενοίκιο) και τις πληρωμές καθώς γίνονται.",
"noMatch": "Καμία δαπάνη δεν ταιριάζει.",
"payOf": "Πληρωμή: {{what}}",
"editOf": "Επεξεργασία: {{what}}",
"deleteOf": "Διαγραφή: {{what}}",
"edit": "Επεξεργασία",
"pay": "Καταγραφή πληρωμής",
"payments": "Πληρωμές",
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα.",
"enteredBy": "καταχωρήθηκε {{date}} από {{name}}",
"added": "Προστέθηκε: {{what}}",
"saved": "Αποθηκεύτηκε: {{what}}",
"deleted": "Διαγράφηκε: {{what}}",
"deleteTitle": "Διαγραφή: {{what}};",
"deleteBody": "Η δαπάνη φεύγει από τη λίστα και τις αναφορές.",
"deleteBodyPaid_one": "Η δαπάνη και η πληρωμή της φεύγουν από τη λίστα και τις αναφορές.",
"deleteBodyPaid_other": "Η δαπάνη και οι {{count}} πληρωμές της φεύγουν από τη λίστα και τις αναφορές.",
"deleteYes": "Διαγραφή",
"payTitle": "Καταγραφή πληρωμής",
"payAmount": "Ποσό που πληρώθηκε",
"payAmountHint": "Όλο το υπόλοιπο ή μέρος του.",
"payNoteHint": "π.χ. μετρητά, τραπεζική μεταφορά, αριθμός απόδειξης",
"payYes": "Καταγραφή πληρωμής",
"paidAll": "Πληρώθηκαν {{amount}}: δεν οφείλεται τίποτα άλλο",
"paidPart": "Πληρώθηκαν {{amount}}: οφείλονται ακόμα {{due}}",
"wrong": {
"description": "Γράψτε τι είναι.",
"total_amount": "Βάλτε ποσό πάνω από μηδέν.",
"below_paid": "Έχουν ήδη πληρωθεί {{paid}}: το σύνολο δεν μπορεί να είναι λιγότερο.",
"payment": "Βάλτε ποσό πάνω από μηδέν και έως {{due}}."
}
},
"contacts": {
"title": "Προμηθευτές και επαφές",
"subtitle_one": "{{count}} επαφή: όσοι πληρώνει το κατάστημα.",
"subtitle_other": "{{count}} επαφές: όσοι πληρώνει το κατάστημα.",
"new": "Νέα επαφή",
"newTitle": "Νέα επαφή",
"add": "Προσθήκη επαφής",
"name": "Όνομα",
"type": "Είδος",
"phone": "Τηλέφωνο",
"email": "Email",
"address": "Διεύθυνση",
"notesHint": "Μόνο για τους υπευθύνους: π.χ. φέρνει Τρίτη, ζητήστε τον Νίκο.",
"types": {
"supplier": "Προμηθευτής",
"staff": "Προσωπικό",
"utility": "Κοινή χρεία",
"other": "Άλλο"
},
"allTypes": "Όλα τα είδη",
"search": "Αναζήτηση: όνομα, τηλέφωνο, email ή σημειώσεις",
"owed": "Τους οφείλονται",
"bills_one": "{{count}} δαπάνη",
"bills_other": "{{count}} δαπάνες",
"none": "Δεν υπάρχουν επαφές ακόμα.",
"noneHint": "Προσθέστε εδώ τους προμηθευτές σας, ή από μια νέα δαπάνη.",
"noMatch": "Καμία επαφή δεν ταιριάζει.",
"editOf": "Επεξεργασία: {{name}}",
"removeOf": "Αφαίρεση: {{name}}",
"added": "Προστέθηκε: {{name}}",
"saved": "Αποθηκεύτηκε: {{name}}",
"removed": "Αφαιρέθηκε: {{name}}",
"removeTitle": "Αφαίρεση: {{name}};",
"removeBody": "Φεύγει από τις επαφές και τις λίστες προμηθευτών. Οι παλιές δαπάνες κρατούν το όνομά του.",
"removeYes": "Αφαίρεση",
"wrong": {
"name": "Γράψτε ένα όνομα.",
"email": "Δεν μοιάζει με διεύθυνση email."
}
},
"tabs": {
"title": "Καρτέλες",
"subtitle": "Τι χρωστούν οι τακτικοί πελάτες. Οι γραμμές μπαίνουν στην καρτέλα ενός πελάτη από την παραγγελία του (Στην καρτέλα).",
"owed": "Οφειλές σε καρτέλες",
"openCount_one": "{{count}} ανοιχτή καρτέλα",
"openCount_other": "{{count}} ανοιχτές καρτέλες",
"views": {
"open": "Ανοιχτές",
"settled": "Εξοφλημένες"
},
"search": "Αναζήτηση πελάτη ή τηλεφώνου",
"none": {
"open": "Δεν υπάρχουν ανοιχτές καρτέλες.",
"settled": "Δεν υπάρχουν εξοφλημένες καρτέλες ακόμα."
},
"noneHint": "Μια καρτέλα ανοίγει μόνη της όταν μια γραμμή της παραγγελίας ενός πελάτη μπαίνει σε αυτήν.",
"noMatch": "Καμία καρτέλα δεν ταιριάζει.",
"openSince_one": "ανοιχτή από {{date}} · {{count}} μέρα",
"openSince_other": "ανοιχτή από {{date}} · {{count}} μέρες",
"settledOn": {
"closed": "εξοφλήθηκε και έκλεισε {{date}}",
"forgiven": "χαρίστηκε {{date}}"
},
"status": {
"open": "Ανοιχτή",
"closed": "Κλειστή",
"forgiven": "Χαρίστηκε"
},
"charged": "Χρεώσεις",
"paid": "Πληρώθηκαν",
"balance": "Οφείλει",
"charges": "Χρεώσεις",
"charge": "Χρέωση #{{id}}",
"order": "παραγγελία #{{id}}",
"noCharges": "Καμία χρέωση.",
"payments": "Πληρωμές",
"noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα.",
"methods": {
"cash": "Μετρητά",
"card": "Κάρτα",
"other": "Άλλο"
},
"pay": "Καταγραφή πληρωμής",
"close": "Κλείσιμο καρτέλας",
"forgive": "Χάρισμα οφειλής",
"closed": "Η καρτέλα του/της {{name}} έκλεισε",
"payTitle": "Πληρωμή στην καρτέλα",
"payAmount": "Ποσό που πληρώθηκε",
"method": "Τρόπος",
"payYes": "Καταγραφή πληρωμής",
"wrongPayment": "Βάλτε ποσό πάνω από μηδέν και έως {{balance}}.",
"paidAll": "Πληρώθηκαν {{amount}}: δεν οφείλεται τίποτα. Κλείστε την καρτέλα όταν θέλετε.",
"paidPart": "Πληρώθηκαν {{amount}}: οφείλονται ακόμα {{balance}}",
"forgiveTitle": "Χάρισμα της καρτέλας: {{name}};",
"forgiveBody": "Τα {{amount}} διαγράφονται και η καρτέλα κλείνει. Δεν αναιρείται.",
"reason": "Γιατί",
"reasonHint": "π.χ. καλός πελάτης, έφυγε από την περιοχή",
"forgiveYes": "Χάρισμα",
"forgiven": "{{name}}: χαρίστηκαν {{amount}}"
}
} }
} }
+3 -1
View File
@@ -238,7 +238,9 @@
"not_found": "Contact not found." "not_found": "Contact not found."
}, },
"expense": { "expense": {
"not_found": "Expense not found." "not_found": "Expense not found.",
"over_due": "That's more than what is still due ({{due}}).",
"below_paid": "{{paid}} has been paid already: the total can't be less."
}, },
"flag": { "flag": {
"not_found": "Mark not found.", "not_found": "Mark not found.",
+186 -14
View File
@@ -3045,23 +3045,195 @@
"what": "What", "what": "What",
"supplier": "Supplier", "supplier": "Supplier",
"total": "Total", "total": "Total",
"status": {
"due": "Due",
"partial": "Partly paid",
"paid": "Paid"
},
"categories": {
"supplier": "Supplies",
"utilities": "Utilities",
"rent": "Rent",
"maintenance": "Maintenance",
"staff": "Staff",
"equipment": "Equipment",
"other": "Other"
},
"dueDate": "Due by {{date}}", "dueDate": "Due by {{date}}",
"payments": "Payments", "payments": "Payments",
"noPayments": "Nothing paid yet." "noPayments": "Nothing paid yet."
} }
},
"finance": {
"back": "Back",
"save": "Save",
"notes": "Notes",
"categories": {
"supplier": "Supplies",
"utilities": "Utilities",
"rent": "Rent",
"maintenance": "Maintenance",
"staff": "Staff",
"equipment": "Equipment",
"other": "Other"
},
"status": {
"due": "Due",
"partial": "Partly paid",
"paid": "Paid"
},
"exp": {
"title": "Expenses",
"subtitle": "What the venue owes and has paid. The analysis of a period is in Reports → Expenses.",
"new": "New expense",
"newTitle": "New expense",
"add": "Add the expense",
"owed": "Still owed",
"unpaid_one": "{{count}} not fully paid",
"unpaid_other": "{{count}} not fully paid",
"lateTitle": "Late",
"lateSub": "past their due date, not paid",
"late": "Late",
"shown": "In this list",
"shownSub_one": "{{count}} expense · {{paid}} paid",
"shownSub_other": "{{count}} expenses · {{paid}} paid",
"search": "Search what, supplier or notes",
"all": "All",
"unpaidOnly": "Not fully paid",
"allCategories": "All categories",
"what": "What",
"whatHint": "e.g. November invoice: dairy",
"category": "Category",
"entered": "Entered",
"dueBy": "Due by",
"dueByHint": "Optional: when it must be paid.",
"dueOn": "Due by {{date}}",
"total": "Total",
"paid": "Paid",
"due": "Still due",
"status": "Status",
"amount": "Amount",
"supplier": "Supplier",
"noSupplier": "No supplier",
"newSupplier": "New supplier…",
"none": "No expenses yet.",
"noneHint": "Enter what the venue buys or pays (supplies, bills, rent) and record payments as they are made.",
"noMatch": "No expense matches.",
"payOf": "Pay {{what}}",
"editOf": "Edit {{what}}",
"deleteOf": "Delete {{what}}",
"edit": "Edit",
"pay": "Record a payment",
"payments": "Payments",
"noPayments": "Nothing paid yet.",
"enteredBy": "entered {{date}} by {{name}}",
"added": "{{what}} added",
"saved": "{{what}} saved",
"deleted": "{{what}} deleted",
"deleteTitle": "Delete {{what}}?",
"deleteBody": "The expense goes from the list and the reports.",
"deleteBodyPaid_one": "The expense and its payment go from the list and the reports.",
"deleteBodyPaid_other": "The expense and its {{count}} payments go from the list and the reports.",
"deleteYes": "Delete",
"payTitle": "Record a payment",
"payAmount": "Amount paid",
"payAmountHint": "All of what is due, or part of it.",
"payNoteHint": "e.g. cash, bank transfer, receipt number",
"payYes": "Record the payment",
"paidAll": "{{amount}} paid: nothing more is due",
"paidPart": "{{amount}} paid: {{due}} still due",
"wrong": {
"description": "Say what it is.",
"total_amount": "Enter an amount above zero.",
"below_paid": "{{paid}} has been paid already: the total can't be less.",
"payment": "Enter an amount above zero and no more than {{due}}."
}
},
"contacts": {
"title": "Suppliers and contacts",
"subtitle_one": "{{count}} contact: the people and companies the venue pays.",
"subtitle_other": "{{count}} contacts: the people and companies the venue pays.",
"new": "New contact",
"newTitle": "New contact",
"add": "Add the contact",
"name": "Name",
"type": "Kind",
"phone": "Phone",
"email": "E-mail",
"address": "Address",
"notesHint": "Only for the managers: e.g. delivers on Tuesdays, ask for Nikos.",
"types": {
"supplier": "Supplier",
"staff": "Staff",
"utility": "Utility",
"other": "Other"
},
"allTypes": "All kinds",
"search": "Search name, phone, e-mail or notes",
"owed": "Owed to them",
"bills_one": "{{count}} expense",
"bills_other": "{{count}} expenses",
"none": "No contacts yet.",
"noneHint": "Add your suppliers here, or from a new expense.",
"noMatch": "No contact matches.",
"editOf": "Edit {{name}}",
"removeOf": "Remove {{name}}",
"added": "{{name}} added",
"saved": "{{name}} saved",
"removed": "{{name}} removed",
"removeTitle": "Remove {{name}}?",
"removeBody": "They leave the book and the supplier lists. Their past expenses keep their name.",
"removeYes": "Remove",
"wrong": {
"name": "Enter a name.",
"email": "This doesn't look like an e-mail address."
}
},
"tabs": {
"title": "Tabs",
"subtitle": "What regular customers owe. Lines go on a customer's tab from their order (On the tab).",
"owed": "Owed on tabs",
"openCount_one": "{{count}} open tab",
"openCount_other": "{{count}} open tabs",
"views": {
"open": "Open",
"settled": "Settled"
},
"search": "Search a customer or phone",
"none": {
"open": "No open tabs.",
"settled": "No settled tabs yet."
},
"noneHint": "A tab opens by itself when a line of a customer's order is put on it.",
"noMatch": "No tab matches.",
"openSince_one": "open since {{date}} · {{count}} day",
"openSince_other": "open since {{date}} · {{count}} days",
"settledOn": {
"closed": "paid and closed {{date}}",
"forgiven": "forgiven {{date}}"
},
"status": {
"open": "Open",
"closed": "Closed",
"forgiven": "Forgiven"
},
"charged": "Charged",
"paid": "Paid",
"balance": "Owed",
"charges": "Charges",
"charge": "Charge #{{id}}",
"order": "order #{{id}}",
"noCharges": "Nothing charged.",
"payments": "Payments",
"noPayments": "Nothing paid yet.",
"methods": {
"cash": "Cash",
"card": "Card",
"other": "Other"
},
"pay": "Record a payment",
"close": "Close the tab",
"forgive": "Forgive what is owed",
"closed": "{{name}}'s tab closed",
"payTitle": "Payment on the tab",
"payAmount": "Amount paid",
"method": "Paid with",
"payYes": "Record the payment",
"wrongPayment": "Enter an amount above zero and no more than {{balance}}.",
"paidAll": "{{amount}} paid: nothing more is owed. Close the tab when you're ready.",
"paidPart": "{{amount}} paid: {{balance}} still owed",
"forgiveTitle": "Forgive {{name}}'s tab?",
"forgiveBody": "{{amount}} is written off and the tab closes. This can't be undone.",
"reason": "Why",
"reasonHint": "e.g. a good customer, moved away",
"forgiveYes": "Forgive it",
"forgiven": "{{name}}: {{amount}} forgiven"
}
} }
} }
+2 -1
View File
@@ -8,7 +8,8 @@
"exports": { "exports": {
".": "./src/index.js", ".": "./src/index.js",
"./sample": "./sample/Sample.jsx", "./sample": "./sample/Sample.jsx",
"./latin": "./src/latin.js" "./latin": "./src/latin.js",
"./number": "./src/number.js"
}, },
"scripts": { "scripts": {
"test": "node --test \"tests/*.test.mjs\"", "test": "node --test \"tests/*.test.mjs\"",
+91
View File
@@ -1238,6 +1238,97 @@ try {
await opens('/reports/expenses', 'expenses-total', 'Expenses') await opens('/reports/expenses', 'expenses-total', 'Expenses')
await page.screenshot({ path: path.join(OUT, 'manager-report-expenses.png'), fullPage: true }) await page.screenshot({ path: path.join(OUT, 'manager-report-expenses.png'), fullPage: true })
// ── 6.13a: a supplier, an expense paid in two parts, a tab paid and closed ──────
const fi = 'finance:'
for (const m of ['expenses', 'crm', 'tabs']) await api('PUT', `/api/platform/modules/${m}`, { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${APP}/crm/contacts`)
await page.getByTestId('contact-new').click()
await page.getByTestId('contact-save').click()
r.check(`${fi} a contact needs a name`, (await page.getByTestId('contact-dialog').textContent()).includes('Enter a name'))
await page.getByTestId('contact-name').fill('E2E Dairy')
await page.getByTestId('contact-phone').fill('2310 555 000')
await page.getByTestId('contact-save').click()
const dairyRow = page.locator('[data-testid="contact-row"]', { hasText: 'E2E Dairy' })
r.check(`${fi} the supplier is in the book`, await dairyRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
const dairy = (await api('GET', '/api/contacts/', { token: boss })).find(c => c.name === 'E2E Dairy')
await page.goto(`${APP}/financials/expenses`)
await page.getByTestId('expense-new').click()
await page.getByTestId('expense-save').click()
r.check(`${fi} an expense needs what it is and an amount`, (await page.getByTestId('expense-dialog').textContent()).includes('Say what it is'))
await page.getByTestId('expense-description').fill('E2E milk November')
await page.getByTestId('expense-amount').fill('120,50')
await page.getByTestId('expense-supplier').selectOption(String(dairy?.id))
await page.getByTestId('expense-due-date').fill(addDaysIso(venueDay, -1))
await page.getByTestId('expense-save').click()
const milkRow = page.locator('[data-testid="expense-row"]', { hasText: 'E2E milk November' })
await milkRow.waitFor({ timeout: 8000 }).catch(() => {})
let milk = (await api('GET', '/api/expenses/', { token: boss })).find(e => e.description === 'E2E milk November')
r.check(`${fi} entered from the page: 120.50 to the supplier, due yesterday, shown as late`, milk?.total_amount === 120.5 && milk.contact_id === dairy?.id && milk.status === 'due'
&& (await milkRow.textContent()).includes('Late'), JSON.stringify(milk))
await milkRow.getByTestId('expense-pay').click()
await page.getByTestId('expense-pay-amount').fill('70')
await page.getByTestId('expense-pay-save').click()
await page.getByTestId('expense-pay-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
for (let i = 0; i < 20 && milk?.status !== 'partial'; i++) { await sleep(250); milk = (await api('GET', '/api/expenses/', { token: boss })).find(e => e.id === milk.id) }
r.check(`${fi} a payment of 70: partly paid, 50.50 still due`, milk.status === 'partial' && milk.due_amount === 50.5, JSON.stringify(milk))
await milkRow.getByTestId('expense-pay').click()
await page.getByTestId('expense-pay-amount').fill('60')
await page.getByTestId('expense-pay-save').click()
r.check(`${fi} paying more than what is due is refused before saving`, (await page.getByTestId('expense-pay-dialog').textContent()).includes('no more than'))
await page.getByTestId('expense-pay-amount').fill('50,50')
await page.getByTestId('expense-pay-save').click()
const gone = await milkRow.waitFor({ state: 'detached', timeout: 8000 }).then(() => true).catch(() => false)
milk = (await api('GET', '/api/expenses/', { token: boss })).find(e => e.id === milk.id)
r.check(`${fi} the rest paid: it shows paid and leaves the "not fully paid" list`, gone && milk.status === 'paid' && milk.payments.length === 2, JSON.stringify(milk))
await page.getByTestId('expenses-status').selectOption('paid')
await page.locator('[data-testid="expense-row"]', { hasText: 'E2E milk November' }).click()
r.check(`${fi} the expense opens with its two payments`, await page.getByTestId('expense-view').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& await page.locator('[data-testid="expense-view"] li').count() === 2)
await page.screenshot({ path: path.join(OUT, 'manager-expenses.png'), fullPage: true })
await page.keyboard.press('Escape')
// a tab: a line of a customer's order goes on the tab, paid in two parts on the page, then closed
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
const tabCustomer = await api('POST', '/api/customers/', { token: boss, body: { name: 'Tab E2E', phone: '6900000013' } })
const tabMenu = await api('GET', '/api/orders/menu', { token: boss })
const tabProduct = tabMenu.products.find(x => x.available && !x.service && !x.prefs.length && x.price > 0)
const tabOrder = await api('POST', '/api/orders/', { token: boss, body: { order_type: 'takeaway' } })
await api('PUT', `/api/orders/${tabOrder.id}/customer`, { token: boss, body: { customer_id: tabCustomer.id } })
await api('POST', `/api/orders/${tabOrder.id}/items`, { token: boss, body: { lines: [{ product_id: tabProduct.id, quantity: 2 }] } })
const tabLine = (await api('GET', `/api/orders/${tabOrder.id}`, { token: boss })).items.find(x => x.product_id === tabProduct.id)
await api('POST', `/api/orders/${tabOrder.id}/items/${tabLine.id}/tab`, { token: boss })
const owes = Math.round(tabLine.unit_price * 2 * 100) / 100
await page.goto(`${APP}/financials/tabs`)
const tabCard = page.locator('[data-testid="tab-card"]', { hasText: 'Tab E2E' })
await tabCard.waitFor({ timeout: 10_000 }).catch(() => {})
r.check(`${fi} the customer's tab is open with what the line cost`, (await tabCard.getByTestId('tab-balance').textContent()).replace(/[\s,]/g, '').includes(owes.toFixed(2)), `${owes} vs ${await tabCard.textContent()}`)
await tabCard.locator('button[aria-expanded]').click()
await tabCard.getByTestId('tab-pay').click()
await page.getByTestId('tab-pay-amount').fill('1')
await page.getByRole('radio', { name: 'Card' }).click()
await page.getByTestId('tab-pay-save').click()
await page.getByTestId('tab-pay-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
for (let i = 0; i < 30 && (await tabCard.getByTestId('tab-balance').textContent()).replace(/[\s,]/g, '').includes(owes.toFixed(2)); i++) await sleep(250) // the first payment shows
await tabCard.getByTestId('tab-pay').click()
await page.getByTestId('tab-pay-save').click() // the rest (the default)
await page.getByTestId('tab-pay-dialog').waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
const closeBtn = tabCard.getByTestId('tab-close')
r.check(`${fi} paid in two parts (card, then the rest): nothing owed, it can be closed`, await closeBtn.waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.screenshot({ path: path.join(OUT, 'manager-tabs.png'), fullPage: true })
await closeBtn.click()
await tabCard.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
const settled = (await api('GET', '/api/tabs/?tab_status=settled', { token: boss })).find(x => x.customer_id === tabCustomer.id)
r.check(`${fi} closed: it leaves the open tabs; payments card + cash`, settled?.status === 'closed' && settled.payments.map(x => x.payment_method).join(',') === 'card,cash', JSON.stringify(settled?.payments))
await page.getByTestId('tabs-view-settled').click()
r.check(`${fi} it is listed with the settled tabs`, await page.locator('[data-testid="tab-card"]', { hasText: 'Tab E2E' }).waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.getByTestId('user-menu').click()
await page.getByRole('menuitemradio', { name: 'Ελληνικά' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid="tabs-page"] h1')?.textContent === 'Καρτέλες', null, { timeout: 5000 }).catch(() => {})
r.check(`${fi} Tabs in Greek`, (await page.locator('[data-testid="tabs-page"] h1').textContent()) === 'Καρτέλες')
await page.goto(`${APP}/financials/expenses`)
r.check(`${fi} Expenses in Greek`, await page.locator('[data-testid="expenses-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(() => {})