"""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 def test_expense_lines_make_the_total(client, make_user, login): """2026-11-20: an expense can list what it bought (quantity, price before VAT, VAT %); the lines make its total, and editing them changes it (never below what was paid).""" h = login(make_user(role="owner")) r = client.post("/api/expenses/", headers=h, json={"description": "Market", "category": "supplier", "lines": [ {"description": "Tomatoes", "quantity": 3, "unit_price": 2.5, "vat_rate": 13}, {"description": "Bags", "quantity": 1, "unit_price": 10, "vat_rate": 24}]}) assert r.status_code == 201, r.text e = r.json() assert [ln["total"] for ln in e["lines"]] == [8.48, 12.4] assert e["net_amount"] == 17.5 and e["vat_amount"] == 3.38 and e["total_amount"] == 20.88 client.post(f"/api/expenses/{e['id']}/pay", headers=h, json={"amount": 15}) # fewer lines than what was paid: refused r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [{"description": "Bags", "quantity": 1, "unit_price": 10}]}) assert r.status_code == 400 and r.json()["error"]["code"] == "expense.below_paid" # lines cleared: the total stays as it was and is typed again r = client.put(f"/api/expenses/{e['id']}", headers=h, json={"lines": [], "total_amount": 21}) assert r.status_code == 200 and r.json()["lines"] == [] and r.json()["total_amount"] == 21 # a line needs a description and a positive quantity bad = client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other", "lines": [{"description": " ", "quantity": 1, "unit_price": 1}]}) assert bad.json()["error"]["code"] == "validation.missing" # no lines and no total: refused assert client.post("/api/expenses/", headers=h, json={"description": "X", "category": "other"}).json()["error"]["code"] == "validation.positive" def test_expense_documents(client, make_user, login, tmp_path, monkeypatch): """A PDF or a photo kept with an expense: uploaded, read back, removed; other files refused.""" import services.expense_docs as docs monkeypatch.setattr(docs, "MEDIA_DIR", str(tmp_path)) h = login(make_user(role="owner")) e = client.post("/api/expenses/", headers=h, json={"description": "Gas", "category": "utilities", "total_amount": 40}).json() pdf = b"%PDF-1.4\n%fake\n" + b"0" * 100 r = client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("bill.pdf", pdf, "application/pdf")}) assert r.status_code == 201, r.text doc = r.json()["documents"][0] assert doc["filename"] == "bill.pdf" and doc["content_type"] == "application/pdf" and doc["size"] == len(pdf) got = client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h) assert got.status_code == 200 and got.content == pdf assert client.post(f"/api/expenses/{e['id']}/documents", headers=h, files={"file": ("x.exe", b"MZ\x90\x00", "application/pdf")}).status_code == 422 r = client.delete(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h) assert r.status_code == 200 and r.json()["documents"] == [] assert client.get(f"/api/expenses/{e['id']}/documents/{doc['id']}", headers=h).status_code == 404