diff --git a/docs/README.md b/docs/README.md index 2b80f7a..813eab1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -53,9 +53,11 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r ## Pack-specific rules -**CS-1. Schema changes go through `_run_migrations()`.** -A new table: `create_all` handles it. A new column on an existing table: append an `ALTER TABLE ADD COLUMN ...` to the `migrations` list in `local_backend/main.py`, with a SQLite-safe default for `NOT NULL`. -Add the column to the SQLAlchemy model **and** the Pydantic schema in the same commit. Never drop or rename columns. +**CS-1. Schema changes are Alembic revisions** (branch `platform-v2`, APPS_PLATFORM D-13). +Change the model, then from `local_backend/`: `alembic revision --autogenerate --rev-id NNNN_short_name -m "what changed"`. **Review the generated file by hand** (SQLite needs batch ops; data moves are written by hand), then run `python -m pytest tests -q`. The drift guard (`tests/guards/test_migrations.py`) fails if models and revisions disagree. +Update the Pydantic schema in the same commit. Revisions may drop or rename columns. Never use `create_all`: startup, seed/wipe scripts and tests all call `core/schema.py::upgrade_to_head()`. New model modules must be added to `models/all.py`. +A v1 database (tables, no `alembic_version`) is refused at startup; v1 data comes over only through `tools/migrate_v1.py`. Old dev databases (`%LOCALAPPDATA%\pos\pos.db`, `tests/e2e/out/seed.db`) must be deleted once. +*(On `main`, the v1 rule still applies: `_run_migrations()` ALTER list, additive only.)* **CS-2. New real-time events need both ends.** If the backend emits a new event type, handle it in `waiter_pwa/src/context/SSEContext.jsx` (and in the manager, if relevant), or state explicitly that it's ignored. diff --git a/local_backend/alembic.ini b/local_backend/alembic.ini new file mode 100644 index 0000000..3a93c75 --- /dev/null +++ b/local_backend/alembic.ini @@ -0,0 +1,11 @@ +# Alembic CLI config for local_backend (APPS_PLATFORM D-13). +# The app never reads this file: startup calls core/schema.py::upgrade_to_head(). +# The DB URL comes from config.settings (DATABASE_URL), not from here. +# +# cd local_backend +# alembic revision --autogenerate --rev-id 0002_short_name -m "short description" +# (rev ids are NNNN_slug, numbered in order; then REVIEW the generated file by hand) +# alembic upgrade head +[alembic] +script_location = migrations +file_template = %%(rev)s diff --git a/local_backend/core/schema.py b/local_backend/core/schema.py new file mode 100644 index 0000000..ad76081 --- /dev/null +++ b/local_backend/core/schema.py @@ -0,0 +1,63 @@ +"""The one way the local database schema is created and upgraded: Alembic (APPS_PLATFORM D-13). + +v1 used SQLAlchemy create_all + a list of ALTER TABLE statements in +main.py::_run_migrations(). That list is gone on platform-v2. Every schema +change is now an Alembic revision in local_backend/migrations/versions/, and the +guard test tests/guards/test_migrations.py fails if models and revisions drift. + +Agent notes: +- Call upgrade_to_head() at startup (main.py lifespan), in seed/wipe scripts and + in tests. Never use SQLAlchemy create_all (a guard test fails on it). +- A v1 database (tables but no alembic_version) is refused with a clear error: + v2 never reads v1 databases; history comes over via tools/migrate_v1.py (D-21). +""" +from __future__ import annotations + +import logging +from pathlib import Path + +from alembic import command +from alembic.config import Config +from sqlalchemy import inspect + +logger = logging.getLogger("xenia.schema") + +MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" + + +class V1DatabaseError(RuntimeError): + pass + + +def alembic_config(connection=None) -> Config: + cfg = Config() + cfg.set_main_option("script_location", str(MIGRATIONS_DIR)) + if connection is not None: + cfg.attributes["connection"] = connection + return cfg + + +def _refuse_v1(connection) -> None: + tables = set(inspect(connection).get_table_names()) + if tables and "alembic_version" not in tables: + raise V1DatabaseError( + "This database was created by Xenia v1 (it has tables but no alembic_version). " + "Platform v2 does not open v1 databases. Start with an empty data folder and " + "import the history with tools/migrate_v1.py (APPS_PLATFORM D-21, section 11)." + ) + + +def upgrade_to_head(engine=None) -> None: + """Create or upgrade the schema to the newest revision.""" + if engine is None: + from database import engine as app_engine + engine = app_engine + with engine.begin() as conn: + _refuse_v1(conn) + command.upgrade(alembic_config(conn), "head") + logger.info("schema.upgraded head=%s", current_head()) + + +def current_head() -> str: + from alembic.script import ScriptDirectory + return ScriptDirectory.from_config(alembic_config()).get_current_head() diff --git a/local_backend/demo_seed.py b/local_backend/demo_seed.py index 722c952..36e6974 100644 --- a/local_backend/demo_seed.py +++ b/local_backend/demo_seed.py @@ -66,7 +66,8 @@ from models.customers import Customer from models.tabs import Tab, TabEntry, TabPayment from models.schedule import ScheduledShift -Base.metadata.create_all(bind=engine) +from core.schema import upgrade_to_head # noqa: E402 +upgrade_to_head() # ── Config ──────────────────────────────────────────────────────────────────── diff --git a/local_backend/main.py b/local_backend/main.py index 5fa7a04..45ecbf3 100644 --- a/local_backend/main.py +++ b/local_backend/main.py @@ -1,3 +1,8 @@ +"""Local backend entry point: logging, app, middleware, routers, startup. + +Schema is created/upgraded only by Alembic (core/schema.py::upgrade_to_head, D-13). +The v1 create_all + _run_migrations() ALTER list was deleted in platform-v2 step 1.0. +""" import os import logging from contextlib import asynccontextmanager @@ -12,32 +17,12 @@ setup_logging() logger = logging.getLogger("xenia.main") from config import settings -from database import engine, Base, SessionLocal +from database import SessionLocal from middleware.license_check import LicenseCheckMiddleware from services.cloud_sync import start_cloud_sync -# Import all models so SQLAlchemy can create their tables -import models.user # noqa: F401 — also registers WaiterZone -import models.table # noqa: F401 -import models.printer # noqa: F401 -import models.product # noqa: F401 -import models.order # noqa: F401 — also registers OrderAuditLog, OrderDiscount, PrintJob -import models.business_day # noqa: F401 -import models.shift # noqa: F401 — registers WaiterShift, ShiftBreak -import models.settings # noqa: F401 -import models.flag # noqa: F401 — registers TableFlagDef, TableFlagAssignment -import models.message # noqa: F401 — registers StaffMessage, StaffMessageAck, QuickMessageTemplate -import models.reservation # noqa: F401 -import models.notes # noqa: F401 — registers SiteNote, SiteTodo -import models.expenses # noqa: F401 — registers Contact, Expense, ExpensePayment -import models.customers # noqa: F401 — registers Customer -import models.tabs # noqa: F401 — registers Tab, TabEntry, TabPayment -import models.waste # noqa: F401 — registers WasteLog -import models.schedule # noqa: F401 — registers ScheduledShift -import models.chat # noqa: F401 — registers Conversation, ConversationParticipant, ChatMessage -import models.prep_zone # noqa: F401 — registers PrepZone, prep_zone_printers, product_prep_zones -import models.pricing # noqa: F401 — registers PriceGroup, PriceModifier, Deal, PriceEventLog, WaiterDiscountSettings -import models.recovery_code # noqa: F401 — registers RecoveryCode +# Every model must be registered before the routers import them (see models/all.py). +import models.all # noqa: F401 from routers import auth, tables, products, orders, waiters, reports, system, setup as setup_router from routers import business_day as business_day_router @@ -65,693 +50,6 @@ from routers import phone as phone_router from routers import recovery as recovery_router -def _run_migrations(): - """Apply additive schema changes that create_all won't handle. - Each migration gets its own connection so a no-op (column already exists) - doesn't leave a dirty transaction that blocks subsequent migrations.""" - from sqlalchemy import text - - migrations = [ - "ALTER TABLE product_ingredients ADD COLUMN extra_cost REAL NOT NULL DEFAULT 0.0", - "ALTER TABLE products ADD COLUMN image_url VARCHAR", - "ALTER TABLE tables ADD COLUMN group_id INTEGER REFERENCES table_groups(id)", - "ALTER TABLE table_groups ADD COLUMN prefix VARCHAR", - "ALTER TABLE table_groups ADD COLUMN color VARCHAR", - "ALTER TABLE products ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_preference_sets ADD COLUMN default_choice_id INTEGER", - "ALTER TABLE product_preference_choices ADD COLUMN sub_choices TEXT", - "ALTER TABLE product_preference_choices ADD COLUMN disables_subset INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_preference_sets ADD COLUMN shared_subset TEXT", - "ALTER TABLE product_options ADD COLUMN sub_choices TEXT", - # Zone-based access control - """CREATE TABLE IF NOT EXISTS waiter_zones ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - waiter_id INTEGER NOT NULL REFERENCES users(id), - group_id INTEGER REFERENCES table_groups(id), - assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Payment tracking on items - "ALTER TABLE order_items ADD COLUMN paid_by INTEGER REFERENCES users(id)", - "ALTER TABLE order_items ADD COLUMN paid_at DATETIME", - "ALTER TABLE order_items ADD COLUMN payment_method VARCHAR", - # Full audit log - """CREATE TABLE IF NOT EXISTS order_audit_log ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - order_id INTEGER NOT NULL REFERENCES orders(id), - event_type VARCHAR NOT NULL, - waiter_id INTEGER REFERENCES users(id), - item_ids TEXT, - amount REAL, - payment_method VARCHAR, - note TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Waiter profile fields - "ALTER TABLE users ADD COLUMN full_name VARCHAR", - "ALTER TABLE users ADD COLUMN nickname VARCHAR", - "ALTER TABLE users ADD COLUMN mobile_phone VARCHAR", - "ALTER TABLE users ADD COLUMN avatar_url VARCHAR", - # Quick options (flat, allow_multiple) - """CREATE TABLE IF NOT EXISTS product_quick_options ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - product_id INTEGER NOT NULL REFERENCES products(id), - name VARCHAR NOT NULL, - price REAL NOT NULL DEFAULT 0.0, - allow_multiple INTEGER NOT NULL DEFAULT 0, - sort_order INTEGER NOT NULL DEFAULT 0 - )""", - # allow_multiple flag on extras (product_options) - "ALTER TABLE product_options ADD COLUMN allow_multiple INTEGER NOT NULL DEFAULT 0", - # Discounts table (future-proofed, schema ready now) - """CREATE TABLE IF NOT EXISTS order_discounts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - order_id INTEGER NOT NULL REFERENCES orders(id), - item_id INTEGER REFERENCES order_items(id), - discount_type VARCHAR NOT NULL, - discount_value REAL NOT NULL, - applied_by INTEGER NOT NULL REFERENCES users(id), - applied_at DATETIME DEFAULT CURRENT_TIMESTAMP, - reason TEXT - )""", - # Business day scoping on orders - "ALTER TABLE orders ADD COLUMN business_day_id INTEGER REFERENCES business_days(id)", - # Shift attribution on paid items - "ALTER TABLE order_items ADD COLUMN paid_in_shift_id INTEGER REFERENCES waiter_shifts(id)", - # Seed default POS settings (INSERT OR IGNORE = no-op if already exists) - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_start', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_end', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('business_day.force_close_allowed', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('flags.display_mode', 'both', CURRENT_TIMESTAMP)", - # Table flags - """CREATE TABLE IF NOT EXISTS table_flag_defs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - emoji VARCHAR, - color VARCHAR DEFAULT '#6b7280', - text_color VARCHAR DEFAULT NULL, - sort_order INTEGER NOT NULL DEFAULT 0, - is_active INTEGER NOT NULL DEFAULT 1, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Migration: add text_color if upgrading from older schema - "ALTER TABLE table_flag_defs ADD COLUMN text_color VARCHAR DEFAULT NULL", - """CREATE TABLE IF NOT EXISTS table_flag_assignments ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - table_id INTEGER NOT NULL REFERENCES tables(id), - flag_id INTEGER NOT NULL REFERENCES table_flag_defs(id), - assigned_at DATETIME DEFAULT CURRENT_TIMESTAMP, - assigned_by INTEGER REFERENCES users(id) - )""", - # Staff messaging - """CREATE TABLE IF NOT EXISTS quick_message_templates ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - body VARCHAR NOT NULL, - sort_order INTEGER NOT NULL DEFAULT 0, - is_active INTEGER NOT NULL DEFAULT 1, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - """CREATE TABLE IF NOT EXISTS staff_messages ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - sender_id INTEGER NOT NULL REFERENCES users(id), - body TEXT NOT NULL, - target_waiter_ids TEXT NOT NULL DEFAULT '[]', - table_ids TEXT NOT NULL DEFAULT '[]', - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - """CREATE TABLE IF NOT EXISTS staff_message_acks ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - message_id INTEGER NOT NULL REFERENCES staff_messages(id), - waiter_id INTEGER NOT NULL REFERENCES users(id), - acked_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Seed default flag definitions - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (1, 'Χρειάζεται καθάρισμα', '🧹', '#ef4444', 1)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (2, 'Χρειάζεται Βοήθεια', '🆘', '#f97316', 2)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (3, 'Χρειάζεται Σερβιτόρο', '🔔', '#eab308', 3)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (4, 'Περιμένει να πληρώσει', '💳', '#3b82f6', 4)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (5, 'VIP', '⭐', '#8b5cf6', 5)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (6, 'Ευγενικός Πελάτης', '😊', '#22c55e', 6)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (7, 'Αγενής Πελάτης', '😤', '#dc2626', 7)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (8, 'Αλλεργίες', '⚠️', '#f59e0b', 8)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (9, 'Παιδιά στο τραπέζι', '👶', '#06b6d4', 9)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (10, 'Επέτειος / Γενέθλια', '🎂', '#ec4899', 10)", - # Seed default quick message templates - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (1, 'Σε χρειάζομαι τώρα', 1)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (2, 'Πάρε διάλειμμα', 2)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (3, 'Ετοιμάσου για κλείσιμο', 3)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (4, 'Ήρθε νέος πελάτης', 4)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (5, 'Ο πελάτης περιμένει να πληρώσει', 5)", - # Product lifecycle status (active / archived) - "ALTER TABLE products ADD COLUMN lifecycle_status VARCHAR NOT NULL DEFAULT 'active'", - # Favorite flags + ordering on all product sub-item types - "ALTER TABLE product_quick_options ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_quick_options ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_options ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_options ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_ingredients ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_ingredients ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_preference_sets ADD COLUMN is_favorite INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_preference_sets ADD COLUMN favorite_sort_order INTEGER NOT NULL DEFAULT 0", - # Sub-category support - "ALTER TABLE categories ADD COLUMN parent_id INTEGER REFERENCES categories(id)", - "ALTER TABLE categories ADD COLUMN general_sort_order INTEGER NOT NULL DEFAULT 0", - # Auto-expand flag for sub-categories on the PWA accordion - "ALTER TABLE categories ADD COLUMN auto_expanded INTEGER NOT NULL DEFAULT 0", - # Printer protocol field - "ALTER TABLE printers ADD COLUMN protocol VARCHAR NOT NULL DEFAULT 'escpos_tcp'", - # Compact (half-width) display flag for quick options - "ALTER TABLE product_quick_options ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0", - # Print layout + per-type font settings - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.ticket_mode', 'detailed', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_number', '48:1:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_meta', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_name', '16:1:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_quick', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_pref', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_extra', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_ingredient', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_note', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_note', '0:1:0', CURRENT_TIMESTAMP)", - # Offline/emergency payment tracking - "ALTER TABLE order_audit_log ADD COLUMN offline_uuid VARCHAR", - "ALTER TABLE order_audit_log ADD COLUMN offline_at VARCHAR", - "ALTER TABLE order_audit_log ADD COLUMN is_duplicate INTEGER NOT NULL DEFAULT 0", - # Cancellation tracking on order items (for reports) - "ALTER TABLE order_items ADD COLUMN cancelled_by INTEGER REFERENCES users(id)", - "ALTER TABLE order_items ADD COLUMN cancel_reason TEXT", - "ALTER TABLE order_items ADD COLUMN cancelled_at DATETIME", - # Manager account fields (added for setup wizard / future password login) - "ALTER TABLE users ADD COLUMN password_hash VARCHAR", - "ALTER TABLE users ADD COLUMN email VARCHAR", - # Venue identity settings - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.name', '', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.type', '', CURRENT_TIMESTAMP)", - # Security settings - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.login_method', 'password', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.autofill_username', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock', 'false', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock_seconds', '300', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout', 'false', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout_seconds', '1800', CURRENT_TIMESTAMP)", - # Xenia Connect — online order fields on orders table - "ALTER TABLE orders ADD COLUMN source VARCHAR NOT NULL DEFAULT 'pos'", - "ALTER TABLE orders ADD COLUMN online_order_ref VARCHAR", - "ALTER TABLE orders ADD COLUMN online_order_cloud_id INTEGER", - "ALTER TABLE orders ADD COLUMN online_status VARCHAR", - "ALTER TABLE orders ADD COLUMN online_customer_name VARCHAR", - "ALTER TABLE orders ADD COLUMN online_customer_phone VARCHAR", - "ALTER TABLE orders ADD COLUMN online_customer_address TEXT", - "ALTER TABLE orders ADD COLUMN online_customer_notes TEXT", - "ALTER TABLE orders ADD COLUMN online_order_type VARCHAR", - # Xenia Connect — digital menu fields on products - "ALTER TABLE products ADD COLUMN digital_visible INTEGER NOT NULL DEFAULT 1", - "ALTER TABLE products ADD COLUMN digital_available INTEGER NOT NULL DEFAULT 1", - "ALTER TABLE products ADD COLUMN digital_name VARCHAR", - "ALTER TABLE products ADD COLUMN digital_description VARCHAR", - "ALTER TABLE products ADD COLUMN digital_price REAL", - "ALTER TABLE products ADD COLUMN digital_discount REAL NOT NULL DEFAULT 0.0", - "ALTER TABLE products ADD COLUMN digital_image_url VARCHAR", - # Per-printer line width (chars per line) — default 48 for 80mm Jolimark - "ALTER TABLE printers ADD COLUMN line_width INTEGER NOT NULL DEFAULT 48", - # Product description (plain-text, for menu display) - "ALTER TABLE products ADD COLUMN description TEXT", - # Staff note (internal memo on a waiter's profile) - "ALTER TABLE users ADD COLUMN note VARCHAR", - # Reservations table - """CREATE TABLE IF NOT EXISTS reservations ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - guest_name VARCHAR NOT NULL, - party_size INTEGER NOT NULL, - phone VARCHAR, - email VARCHAR, - note TEXT, - reserved_for DATETIME NOT NULL, - table_id INTEGER REFERENCES tables(id), - status VARCHAR NOT NULL DEFAULT 'pending', - source VARCHAR NOT NULL DEFAULT 'manager_app', - created_by_user_id INTEGER REFERENCES users(id), - online_customer_id VARCHAR, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Product unit of measure (piece / portion / kg / liter / gram / ml) - "ALTER TABLE products ADD COLUMN unit_type VARCHAR NOT NULL DEFAULT 'piece'", - # Phase 2A — product cost tracking - "ALTER TABLE products ADD COLUMN cost_simple REAL", - "ALTER TABLE products ADD COLUMN cost_breakdown TEXT", - "ALTER TABLE order_items ADD COLUMN unit_cost REAL", - # Phase 2B — staff payroll - "ALTER TABLE users ADD COLUMN hourly_rate REAL", - "ALTER TABLE waiter_shifts ADD COLUMN hourly_rate_snapshot REAL", - # Phase 2J — staff shift scheduling - """CREATE TABLE IF NOT EXISTS scheduled_shifts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL REFERENCES users(id), - scheduled_date DATE NOT NULL, - start_time VARCHAR NOT NULL, - end_time VARCHAR NOT NULL, - notes TEXT, - created_by_id INTEGER NOT NULL REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Phase 2H — void/waste log - """CREATE TABLE IF NOT EXISTS waste_log ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - product_id INTEGER NOT NULL REFERENCES products(id), - quantity REAL NOT NULL, - unit_cost_snapshot REAL, - total_cost REAL, - reason VARCHAR NOT NULL, - reason_notes TEXT, - logged_by_id INTEGER NOT NULL REFERENCES users(id), - business_day_id INTEGER REFERENCES business_days(id), - logged_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Phase 2G — pay-later tab system - """CREATE TABLE IF NOT EXISTS tabs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - customer_id INTEGER NOT NULL REFERENCES customers(id), - status VARCHAR NOT NULL DEFAULT 'open', - opened_at DATETIME DEFAULT CURRENT_TIMESTAMP, - closed_at DATETIME, - closed_by_id INTEGER REFERENCES users(id), - notes TEXT - )""", - """CREATE TABLE IF NOT EXISTS tab_entries ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - tab_id INTEGER NOT NULL REFERENCES tabs(id), - order_id INTEGER REFERENCES orders(id), - order_item_id INTEGER REFERENCES order_items(id), - amount REAL NOT NULL, - description TEXT, - created_by_id INTEGER NOT NULL REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - """CREATE TABLE IF NOT EXISTS tab_payments ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - tab_id INTEGER NOT NULL REFERENCES tabs(id), - amount REAL NOT NULL, - payment_method VARCHAR, - received_by_id INTEGER NOT NULL REFERENCES users(id), - notes TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - # Phase 2F — customer CRM - """CREATE TABLE IF NOT EXISTS customers ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - nickname VARCHAR, - phone VARCHAR, - email VARCHAR, - notes TEXT, - is_active INTEGER NOT NULL DEFAULT 1, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - created_by_id INTEGER NOT NULL REFERENCES users(id) - )""", - "ALTER TABLE orders ADD COLUMN customer_id INTEGER REFERENCES customers(id)", - # Phase 2E — cash drawer reconciliation - "ALTER TABLE waiter_shifts ADD COLUMN counted_cash_end REAL", - "ALTER TABLE waiter_shifts ADD COLUMN cash_discrepancy REAL", - "ALTER TABLE business_days ADD COLUMN store_opening_cash REAL", - "ALTER TABLE business_days ADD COLUMN store_closing_cash REAL", - "ALTER TABLE business_days ADD COLUMN store_cash_discrepancy REAL", - # Phase 2D — expense tracking + supplier contacts - """CREATE TABLE IF NOT EXISTS contacts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - type VARCHAR NOT NULL DEFAULT 'supplier', - phone VARCHAR, - email VARCHAR, - address TEXT, - notes TEXT, - is_active INTEGER NOT NULL DEFAULT 1, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - """CREATE TABLE IF NOT EXISTS expenses ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - description VARCHAR NOT NULL, - category VARCHAR NOT NULL, - contact_id INTEGER REFERENCES contacts(id), - total_amount REAL NOT NULL, - paid_amount REAL NOT NULL DEFAULT 0.0, - due_date DATETIME, - business_day_id INTEGER REFERENCES business_days(id), - created_by_id INTEGER NOT NULL REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - notes TEXT - )""", - """CREATE TABLE IF NOT EXISTS expense_payments ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - expense_id INTEGER NOT NULL REFERENCES expenses(id), - amount REAL NOT NULL, - paid_at DATETIME DEFAULT CURRENT_TIMESTAMP, - paid_by_id INTEGER NOT NULL REFERENCES users(id), - notes TEXT - )""", - # Phase 2C — notes & todos - """CREATE TABLE IF NOT EXISTS site_notes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - body TEXT NOT NULL, - created_by_id INTEGER NOT NULL REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, - is_pinned INTEGER NOT NULL DEFAULT 0 - )""", - """CREATE TABLE IF NOT EXISTS site_todos ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - body TEXT NOT NULL, - is_done INTEGER NOT NULL DEFAULT 0, - done_at DATETIME, - done_by_id INTEGER REFERENCES users(id), - created_by_id INTEGER NOT NULL REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - priority VARCHAR NOT NULL DEFAULT 'normal' - )""", - # Printer duplicate copies (0 = print once, 1 = print twice, etc.) - "ALTER TABLE printers ADD COLUMN duplicates INTEGER NOT NULL DEFAULT 0", - # Waiter cancellation permissions - "ALTER TABLE users ADD COLUMN can_cancel_orders INTEGER NOT NULL DEFAULT 0", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.waiter_cancellations_allowed', 'false', CURRENT_TIMESTAMP)", - # KDS — kitchen display system status tracking - "ALTER TABLE orders ADD COLUMN kds_status VARCHAR NOT NULL DEFAULT 'pending'", - "ALTER TABLE orders ADD COLUMN order_type VARCHAR NOT NULL DEFAULT 'here'", - "ALTER TABLE order_items ADD COLUMN kds_status VARCHAR NOT NULL DEFAULT 'pending'", - # KDS notifications — message type + zone tagging on staff messages - "ALTER TABLE staff_messages ADD COLUMN message_type VARCHAR NOT NULL DEFAULT 'manager'", - "ALTER TABLE staff_messages ADD COLUMN kds_zone VARCHAR", - # Chat system - """CREATE TABLE IF NOT EXISTS conversations ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - type VARCHAR NOT NULL DEFAULT 'direct', - name VARCHAR, - is_system INTEGER NOT NULL DEFAULT 0, - created_by INTEGER REFERENCES users(id), - created_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - """CREATE TABLE IF NOT EXISTS conversation_participants ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - conversation_id INTEGER NOT NULL REFERENCES conversations(id), - user_id INTEGER NOT NULL REFERENCES users(id), - joined_at DATETIME DEFAULT CURRENT_TIMESTAMP, - last_read_at DATETIME - )""", - """CREATE TABLE IF NOT EXISTS chat_messages ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - conversation_id INTEGER NOT NULL REFERENCES conversations(id), - sender_id INTEGER NOT NULL REFERENCES users(id), - body TEXT NOT NULL, - sent_at DATETIME DEFAULT CURRENT_TIMESTAMP, - deleted_at DATETIME - )""", - # Prep Zones — replaces per-product printer assignment - """CREATE TABLE IF NOT EXISTS prep_zones ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - description VARCHAR - )""", - """CREATE TABLE IF NOT EXISTS prep_zone_printers ( - prep_zone_id INTEGER NOT NULL REFERENCES prep_zones(id), - printer_id INTEGER NOT NULL REFERENCES printers(id), - PRIMARY KEY (prep_zone_id, printer_id) - )""", - """CREATE TABLE IF NOT EXISTS product_prep_zones ( - product_id INTEGER NOT NULL REFERENCES products(id), - prep_zone_id INTEGER NOT NULL REFERENCES prep_zones(id), - PRIMARY KEY (product_id, prep_zone_id) - )""", - # KDS decline tracking on items - "ALTER TABLE order_items ADD COLUMN decline_note TEXT", - # Prep zone notification name - "ALTER TABLE prep_zones ADD COLUMN notification_name VARCHAR", - # KDS status change timestamp on orders (for "latest change" sorting in PWA) - "ALTER TABLE orders ADD COLUMN kds_status_changed_at DATETIME", - # Auto-close table after full payment setting - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.auto_close_on_full_payment', 'false', CURRENT_TIMESTAMP)", - # Quick Add: allow direct 1-unit add from product list without opening config modal - "ALTER TABLE products ADD COLUMN quick_add_enabled INTEGER NOT NULL DEFAULT 1", - # Per-waiter settings + favorites sync (JSON blob) - "ALTER TABLE users ADD COLUMN waiter_settings TEXT", - # Prep zone print settings — synced with KDS auto-print controls - "ALTER TABLE prep_zones ADD COLUMN auto_print VARCHAR NOT NULL DEFAULT 'none'", - "ALTER TABLE prep_zones ADD COLUMN print_copies INTEGER NOT NULL DEFAULT 1", - # Bypass KDS/serve flow: new orders immediately start as served - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.bypass_kds_serve', 'false', CURRENT_TIMESTAMP)", - # Prep zone: rename auto_print value 'primary' → 'master' for existing rows - "UPDATE prep_zones SET auto_print = 'master' WHERE auto_print = 'primary'", - # Prep zone: master printer (single FK) + per-role copy counts - "ALTER TABLE prep_zones ADD COLUMN master_printer_id INTEGER REFERENCES printers(id)", - "ALTER TABLE prep_zones ADD COLUMN master_copies INTEGER NOT NULL DEFAULT 1", - "ALTER TABLE prep_zones ADD COLUMN secondary_copies INTEGER NOT NULL DEFAULT 1", - # Prep zone: item sort / category grouping options - "ALTER TABLE prep_zones ADD COLUMN sort_items_by VARCHAR NOT NULL DEFAULT 'order_time'", - "ALTER TABLE prep_zones ADD COLUMN group_by_category INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE prep_zones ADD COLUMN category_order TEXT NOT NULL DEFAULT '[]'", - # Prep zone: ticket formatting option - "ALTER TABLE prep_zones ADD COLUMN print_checkboxes INTEGER NOT NULL DEFAULT 0", - # Prep zone: KDS bypass options - "ALTER TABLE prep_zones ADD COLUMN bypass_pending INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE prep_zones ADD COLUMN bypass_kds INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE prep_zones ADD COLUMN auto_ready_to_served INTEGER NOT NULL DEFAULT 0", - # Prep zone: migrate existing master_printer_id from first printer in zone (best-effort) - # (handled in Python at runtime, not SQL — no-op SQL here) - # Product tags (JSON array of strings) - "ALTER TABLE products ADD COLUMN tags TEXT", - # Hide revenue from waiters on shift overview - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.hide_revenue_from_waiters', 'false', CURRENT_TIMESTAMP)", - # WebSocket event log — append-only, pruned to 24h on startup - """CREATE TABLE IF NOT EXISTS sync_events ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - event_type VARCHAR NOT NULL, - payload TEXT NOT NULL, - target_user_ids TEXT, - created_at VARCHAR NOT NULL - )""", - "CREATE INDEX IF NOT EXISTS ix_sync_events_created_at ON sync_events (created_at)", - # Migrate from legacy per-product printer to prep zones: clear old printer_zone_id - "UPDATE products SET printer_zone_id = NULL WHERE printer_zone_id IS NOT NULL", - # Per-printer ESC/POS code page index (n in ESC t n) — default 29 = CP737 on Jolimark - "ALTER TABLE printers ADD COLUMN codepage_n INTEGER NOT NULL DEFAULT 29", - # Price adjustment: per-item on-the-fly price delta (positive or negative) - "ALTER TABLE order_items ADD COLUMN price_adjustment REAL NOT NULL DEFAULT 0.0", - # Customer count: how many people are at the table for this order - "ALTER TABLE orders ADD COLUMN customer_count INTEGER", - # Service items: flag on products, these are non-inventoried table-service items - "ALTER TABLE products ADD COLUMN is_service_item INTEGER NOT NULL DEFAULT 0", - # Table seat count — physical seats at each table (foundation for per-seat dish assignment) - "ALTER TABLE tables ADD COLUMN seat_count INTEGER", - # Courses — optional course assignment for sequenced firing - "ALTER TABLE order_items ADD COLUMN course_id INTEGER", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.courses_enabled', 'false', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.courses', '[]', CURRENT_TIMESTAMP)", - # Print job lifecycle tracking — auto-retry system - """CREATE TABLE IF NOT EXISTS print_jobs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - order_id INTEGER NOT NULL REFERENCES orders(id), - printer_id INTEGER NOT NULL REFERENCES printers(id), - zone_id INTEGER, - item_ids TEXT NOT NULL, - copies INTEGER NOT NULL DEFAULT 1, - status VARCHAR NOT NULL DEFAULT 'pending', - retry_count INTEGER NOT NULL DEFAULT 0, - first_attempted_at DATETIME DEFAULT CURRENT_TIMESTAMP, - last_attempted_at DATETIME, - succeeded_at DATETIME, - cancelled_at DATETIME, - cancel_reason VARCHAR - )""", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('orders.waiter_price_adjust_allowed', 'false', CURRENT_TIMESTAMP)", - # Pricing system — Phase 2 pricing overhaul - """CREATE TABLE IF NOT EXISTS price_groups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - description TEXT, - color VARCHAR, - is_active INTEGER NOT NULL DEFAULT 0, - auto_enable_time VARCHAR, - auto_disable_time VARCHAR, - auto_days TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - created_by INTEGER REFERENCES users(id) - )""", - """CREATE TABLE IF NOT EXISTS price_modifiers ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - description TEXT, - color VARCHAR, - is_active INTEGER NOT NULL DEFAULT 1, - is_favorite INTEGER NOT NULL DEFAULT 0, - allow_stack INTEGER NOT NULL DEFAULT 0, - sort_order INTEGER NOT NULL DEFAULT 0, - scope VARCHAR NOT NULL DEFAULT 'global', - item_id INTEGER REFERENCES products(id), - action_type VARCHAR NOT NULL, - action_value REAL NOT NULL, - round_to VARCHAR, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - created_by INTEGER REFERENCES users(id), - updated_at DATETIME, - updated_by INTEGER REFERENCES users(id) - )""", - """CREATE TABLE IF NOT EXISTS price_modifier_conditions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - modifier_id INTEGER NOT NULL REFERENCES price_modifiers(id) ON DELETE CASCADE, - condition_type VARCHAR NOT NULL, - params TEXT NOT NULL DEFAULT '{}' - )""", - """CREATE TABLE IF NOT EXISTS price_modifier_targets ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - modifier_id INTEGER NOT NULL REFERENCES price_modifiers(id) ON DELETE CASCADE, - target_type VARCHAR NOT NULL, - target_id INTEGER, - target_tag VARCHAR - )""", - """CREATE TABLE IF NOT EXISTS deals ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name VARCHAR NOT NULL, - description TEXT, - color VARCHAR, - is_active INTEGER NOT NULL DEFAULT 1, - sort_order INTEGER NOT NULL DEFAULT 0, - action_type VARCHAR NOT NULL, - action_modifier_id INTEGER REFERENCES price_modifiers(id), - action_value REAL, - action_free_item_id INTEGER REFERENCES products(id), - action_free_target_type VARCHAR, - action_free_target_ids TEXT, - action_free_quantity INTEGER NOT NULL DEFAULT 1, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - created_by INTEGER REFERENCES users(id) - )""", - """CREATE TABLE IF NOT EXISTS deal_conditions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE, - condition_type VARCHAR NOT NULL, - params TEXT NOT NULL DEFAULT '{}' - )""", - """CREATE TABLE IF NOT EXISTS deal_targets ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - deal_id INTEGER NOT NULL REFERENCES deals(id) ON DELETE CASCADE, - target_type VARCHAR NOT NULL, - target_id INTEGER, - target_tag VARCHAR - )""", - """CREATE TABLE IF NOT EXISTS price_event_log ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - order_id INTEGER NOT NULL REFERENCES orders(id), - order_item_id INTEGER REFERENCES order_items(id), - event_type VARCHAR NOT NULL, - modifier_id INTEGER REFERENCES price_modifiers(id), - deal_id INTEGER REFERENCES deals(id), - price_before REAL, - price_after REAL, - delta_amount REAL, - applied_by_user_id INTEGER REFERENCES users(id), - waiter_note TEXT, - conditions_snapshot TEXT, - selected_item_ids TEXT, - applied_at DATETIME DEFAULT CURRENT_TIMESTAMP - )""", - "CREATE INDEX IF NOT EXISTS ix_price_event_log_order_id ON price_event_log (order_id)", - "CREATE INDEX IF NOT EXISTS ix_price_event_log_order_item_id ON price_event_log (order_item_id)", - """CREATE TABLE IF NOT EXISTS waiter_discount_settings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, - can_apply_discounts INTEGER NOT NULL DEFAULT 0, - max_discount_percent REAL, - max_discount_amount REAL, - max_total_value_shift REAL, - max_total_value_workday REAL, - max_items_per_shift INTEGER, - max_items_per_workday INTEGER, - max_items_per_order INTEGER - )""", - # Extend order_discounts with price snapshot columns for clean audit trail - "ALTER TABLE order_discounts ADD COLUMN price_before REAL", - "ALTER TABLE order_discounts ADD COLUMN price_after REAL", - # Global discount settings in pos_settings - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.enabled', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_total_value_workday', '', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_total_value_shift', '', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('discounts.max_items_per_shift', '', CURRENT_TIMESTAMP)", - # Deal item binding — which deal created this item, and which item it's linked to - "ALTER TABLE order_items ADD COLUMN deal_id INTEGER REFERENCES deals(id)", - "ALTER TABLE order_items ADD COLUMN linked_item_id INTEGER REFERENCES order_items(id)", - # Multi-select targets: JSON arrays of IDs/tags per target row - "ALTER TABLE price_modifier_targets ADD COLUMN target_ids TEXT", - "ALTER TABLE price_modifier_targets ADD COLUMN target_tags TEXT", - "ALTER TABLE deal_targets ADD COLUMN target_ids TEXT", - "ALTER TABLE deal_targets ADD COLUMN target_tags TEXT", - # Role & permissions overhaul — granular per-user permission flags - # Access permissions - "ALTER TABLE users ADD COLUMN perm_access_dashboard INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_access_waiter_app INTEGER NOT NULL DEFAULT 1", - "ALTER TABLE users ADD COLUMN perm_access_kds INTEGER NOT NULL DEFAULT 0", - # Order action permissions - "ALTER TABLE users ADD COLUMN perm_cancel_orders INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_apply_discounts INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_modify_prices INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_open_orders INTEGER NOT NULL DEFAULT 1", - "ALTER TABLE users ADD COLUMN perm_close_orders INTEGER NOT NULL DEFAULT 1", - # Management permissions - "ALTER TABLE users ADD COLUMN perm_view_reports INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_manage_staff INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_manage_tables INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_manage_menu INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE users ADD COLUMN perm_manage_settings INTEGER NOT NULL DEFAULT 0", - # Migrate existing managers/sysadmins to have dashboard access + all management perms - "UPDATE users SET perm_access_dashboard=1, perm_access_waiter_app=1, perm_access_kds=1, perm_cancel_orders=1, perm_apply_discounts=1, perm_modify_prices=1, perm_open_orders=1, perm_close_orders=1, perm_view_reports=1, perm_manage_staff=1, perm_manage_tables=1, perm_manage_menu=1, perm_manage_settings=1 WHERE role IN ('manager', 'sysadmin')", - # Migrate existing waiters: update can_cancel_orders → perm_cancel_orders - "UPDATE users SET perm_cancel_orders = can_cancel_orders WHERE role = 'waiter'", - # Rename legacy roles: manager → store_manager, sysadmin → superadmin - "UPDATE users SET role = 'superadmin' WHERE role = 'sysadmin'", - "UPDATE users SET role = 'store_manager' WHERE role = 'manager'", - # Feature: modifier groups (folders), multi-select extras, compact mode - """CREATE TABLE IF NOT EXISTS product_modifier_groups ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - product_id INTEGER NOT NULL REFERENCES products(id), - modifier_type VARCHAR NOT NULL, - name VARCHAR NOT NULL, - sort_order INTEGER NOT NULL DEFAULT 0 - )""", - "ALTER TABLE product_options ADD COLUMN multi_select INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_options ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_options ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)", - "ALTER TABLE product_ingredients ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_ingredients ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)", - "ALTER TABLE product_preference_choices ADD COLUMN is_compact INTEGER NOT NULL DEFAULT 0", - "ALTER TABLE product_preference_sets ADD COLUMN group_id INTEGER REFERENCES product_modifier_groups(id)", - # Fiscal printer (ΦΗΜ) — product fields - "ALTER TABLE products ADD COLUMN fiscal_name VARCHAR", - "ALTER TABLE products ADD COLUMN fiscal_vat_group_id INTEGER", - # Fiscal status on orders (NULL=fiscal off, pending/success/failed) - "ALTER TABLE orders ADD COLUMN fiscal_status VARCHAR", - # Drop legacy can_cancel_orders column — data already migrated to perm_cancel_orders - "ALTER TABLE users DROP COLUMN can_cancel_orders", - # Recovery codes for account self-recovery - """CREATE TABLE IF NOT EXISTS recovery_codes ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, - code_hash VARCHAR NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - used_at DATETIME - )""", - "CREATE INDEX IF NOT EXISTS ix_recovery_codes_user_id ON recovery_codes (user_id)", - # Multi-select preference sets - "ALTER TABLE product_preference_sets ADD COLUMN allow_multi_select INTEGER NOT NULL DEFAULT 0", - # Per-choice quantity on multi-select preference sets (x2, x3, …) - "ALTER TABLE product_preference_sets ADD COLUMN allow_choice_quantity INTEGER NOT NULL DEFAULT 0", - # Tracks the hash of the product image last pushed to the cloud (Xenia Connect) - "ALTER TABLE products ADD COLUMN cloud_image_hash VARCHAR", - ] - for sql in migrations: - try: - with engine.connect() as conn: - conn.execute(text(sql)) - conn.commit() - except Exception: - pass - - def _init_chat(): """Bootstrap the system group chat and sync all active users into it.""" from services.chat_service import ensure_system_group, add_user_to_system_group @@ -777,8 +75,9 @@ async def lifespan(app: FastAPI): loop = asyncio.get_running_loop() sse_init_loop(loop) ws_init_loop(loop) - Base.metadata.create_all(bind=engine) - _run_migrations() + # Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases. + from core.schema import upgrade_to_head + upgrade_to_head() _db = SessionLocal() try: apply_retention_setting(_db) diff --git a/local_backend/migrations/env.py b/local_backend/migrations/env.py new file mode 100644 index 0000000..c69947b --- /dev/null +++ b/local_backend/migrations/env.py @@ -0,0 +1,53 @@ +"""Alembic environment for local_backend. + +Agent notes: +- Target metadata = every model (models/all.py). Add new model modules there. +- render_as_batch=True: SQLite can't ALTER most things, so Alembic rebuilds the + table (copy → drop → rename) for column changes. Review batch ops carefully. +- No logging.fileConfig() here on purpose: it would replace core/logging.py's + handlers when migrations run at app startup. +- A caller may pass an open connection in config.attributes["connection"] + (core/schema.py, tests); otherwise we connect to config.settings.DATABASE_URL. +- Only "online" mode is supported; offline SQL generation is not needed for SQLite. +""" +import sys +from pathlib import Path + +from alembic import context +from sqlalchemy import create_engine + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from database import Base # noqa: E402 +import models.all # noqa: E402,F401 + +target_metadata = Base.metadata + + +def _configure_and_run(connection): + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=True, + compare_type=True, + compare_server_default=True, + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + connection = context.config.attributes.get("connection") + if connection is not None: + _configure_and_run(connection) + return + from config import settings + engine = create_engine(settings.DATABASE_URL) + with engine.connect() as conn: + _configure_and_run(conn) + engine.dispose() + + +if context.is_offline_mode(): + raise SystemExit("Offline (--sql) mode is not supported for local_backend.") +run_migrations_online() diff --git a/local_backend/migrations/script.py.mako b/local_backend/migrations/script.py.mako new file mode 100644 index 0000000..36cd8ef --- /dev/null +++ b/local_backend/migrations/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/local_backend/migrations/versions/0001_v2_baseline.py b/local_backend/migrations/versions/0001_v2_baseline.py new file mode 100644 index 0000000..e6ed708 --- /dev/null +++ b/local_backend/migrations/versions/0001_v2_baseline.py @@ -0,0 +1,1305 @@ +"""v2 baseline: the whole local schema as of platform-v2 step 1.0, plus install defaults. + +Revision ID: 0001_v2_baseline +Revises: +Create Date: 2026-11-12 + +Autogenerated from the models on an empty database, then reviewed by hand. +Differences from what a v1 install had (create_all + main.py::_run_migrations): +- sync_events is now a model (models/sync_event.py) instead of raw DDL. +- price_event_log.order_id / order_item_id indexes are declared on the model. +- order_discounts.price_before / price_after are gone: no model or code used them. +- The default table flags and quick-message templates that _run_migrations tried + to insert are NOT seeded: those INSERTs always failed on fresh v1 installs + (NOT NULL columns without defaults), so no install ever had them. + +INSTALL_SETTINGS below are the pos_settings rows a fresh v1 install got. Several +readers treat a missing row differently from the default (e.g. the global +discount settings endpoint), so they are kept as install data. +>>> Step 1.3 (module registry: settings declared in manifests with defaults) +>>> should make every reader fall back to declared defaults; then these rows +>>> can stop being seeded. +""" +from datetime import datetime, timezone + +from alembic import op +import sqlalchemy as sa + +INSTALL_SETTINGS = { + 'business_day.force_close_allowed': 'true', + 'discounts.enabled': 'true', + 'discounts.max_items_per_shift': '', + 'discounts.max_total_value_shift': '', + 'discounts.max_total_value_workday': '', + 'flags.display_mode': 'both', + 'orders.auto_close_on_full_payment': 'false', + 'orders.bypass_kds_serve': 'false', + 'orders.courses': '[]', + 'orders.courses_enabled': 'false', + 'orders.waiter_cancellations_allowed': 'false', + 'orders.waiter_price_adjust_allowed': 'false', + 'print.font_extra': '0:0:0', + 'print.font_ingredient': '0:0:0', + 'print.font_item_name': '16:1:0', + 'print.font_item_note': '0:0:0', + 'print.font_meta': '0:0:0', + 'print.font_order_note': '0:1:0', + 'print.font_order_number': '48:1:0', + 'print.font_pref': '0:0:0', + 'print.font_quick': '0:0:0', + 'print.ticket_mode': 'detailed', + 'security.auto_lock': 'false', + 'security.auto_lock_seconds': '300', + 'security.auto_logout': 'false', + 'security.auto_logout_seconds': '1800', + 'security.autofill_username': 'true', + 'security.login_method': 'password', + 'shifts.hide_revenue_from_waiters': 'false', + 'shifts.waiter_self_end': 'true', + 'shifts.waiter_self_start': 'true', + 'venue.name': '', + 'venue.type': '', +} + + +revision = '0001_v2_baseline' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('categories', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('color', sa.String(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=True), + sa.Column('parent_id', sa.Integer(), nullable=True), + sa.Column('general_sort_order', sa.Integer(), nullable=False), + sa.Column('auto_expanded', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['parent_id'], ['categories.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('categories', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_categories_id'), ['id'], unique=False) + + op.create_table('contacts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('type', sa.String(), nullable=False), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('email', sa.String(), nullable=True), + sa.Column('address', sa.Text(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('contacts', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_contacts_id'), ['id'], unique=False) + + op.create_table('printers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('ip_address', sa.String(), nullable=False), + sa.Column('port', sa.Integer(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('protocol', sa.String(), nullable=False), + sa.Column('line_width', sa.Integer(), nullable=False), + sa.Column('duplicates', sa.Integer(), nullable=False), + sa.Column('codepage_n', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('printers', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_printers_id'), ['id'], unique=False) + + op.create_table('quick_message_templates', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('body', sa.String(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('quick_message_templates', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_quick_message_templates_id'), ['id'], unique=False) + + op.create_table('sync_events', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('event_type', sa.String(), nullable=False), + sa.Column('payload', sa.Text(), nullable=False), + sa.Column('target_user_ids', sa.Text(), nullable=True), + sa.Column('created_at', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sqlite_autoincrement=True + ) + with op.batch_alter_table('sync_events', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_sync_events_created_at'), ['created_at'], unique=False) + + op.create_table('table_flag_defs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('emoji', sa.String(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.Column('text_color', sa.String(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('table_flag_defs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_table_flag_defs_id'), ['id'], unique=False) + + op.create_table('table_groups', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('prefix', sa.String(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('name') + ) + with op.batch_alter_table('table_groups', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_table_groups_id'), ['id'], unique=False) + + op.create_table('users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('username', sa.String(), nullable=False), + sa.Column('pin_hash', sa.String(), nullable=False), + sa.Column('password_hash', sa.String(), nullable=True), + sa.Column('email', sa.String(), nullable=True), + sa.Column('role', sa.String(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('full_name', sa.String(), nullable=True), + sa.Column('nickname', sa.String(), nullable=True), + sa.Column('mobile_phone', sa.String(), nullable=True), + sa.Column('note', sa.String(), nullable=True), + sa.Column('avatar_url', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('hourly_rate', sa.Float(), nullable=True), + sa.Column('perm_access_dashboard', sa.Boolean(), nullable=False), + sa.Column('perm_access_waiter_app', sa.Boolean(), nullable=False), + sa.Column('perm_access_kds', sa.Boolean(), nullable=False), + sa.Column('perm_cancel_orders', sa.Boolean(), nullable=False), + sa.Column('perm_apply_discounts', sa.Boolean(), nullable=False), + sa.Column('perm_modify_prices', sa.Boolean(), nullable=False), + sa.Column('perm_open_orders', sa.Boolean(), nullable=False), + sa.Column('perm_close_orders', sa.Boolean(), nullable=False), + sa.Column('perm_view_reports', sa.Boolean(), nullable=False), + sa.Column('perm_manage_staff', sa.Boolean(), nullable=False), + sa.Column('perm_manage_tables', sa.Boolean(), nullable=False), + sa.Column('perm_manage_menu', sa.Boolean(), nullable=False), + sa.Column('perm_manage_settings', sa.Boolean(), nullable=False), + sa.Column('waiter_settings', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_users_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True) + + op.create_table('assistant_assignments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('primary_waiter_id', sa.Integer(), nullable=False), + sa.Column('assistant_waiter_id', sa.Integer(), nullable=False), + sa.Column('assigned_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['assistant_waiter_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['primary_waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('assistant_assignments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_assistant_assignments_id'), ['id'], unique=False) + + op.create_table('business_days', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('status', sa.String(), nullable=False), + sa.Column('opened_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('opened_by_id', sa.Integer(), nullable=False), + sa.Column('closed_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('closed_by_id', sa.Integer(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('store_opening_cash', sa.Float(), nullable=True), + sa.Column('store_closing_cash', sa.Float(), nullable=True), + sa.Column('store_cash_discrepancy', sa.Float(), nullable=True), + sa.ForeignKeyConstraint(['closed_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['opened_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('business_days', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_business_days_id'), ['id'], unique=False) + + op.create_table('conversations', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('type', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('is_system', sa.Boolean(), nullable=False), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('conversations', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_conversations_id'), ['id'], unique=False) + + op.create_table('customers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('nickname', sa.String(), nullable=True), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('email', sa.String(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('customers', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_customers_id'), ['id'], unique=False) + + op.create_table('pos_settings', + sa.Column('key', sa.String(), nullable=False), + sa.Column('value', sa.String(), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_by_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['updated_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('key') + ) + op.create_table('prep_zones', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=True), + sa.Column('notification_name', sa.String(), nullable=True), + sa.Column('auto_print', sa.String(), nullable=False), + sa.Column('master_printer_id', sa.Integer(), nullable=True), + sa.Column('master_copies', sa.Integer(), nullable=False), + sa.Column('secondary_copies', sa.Integer(), nullable=False), + sa.Column('print_copies', sa.Integer(), nullable=False), + sa.Column('sort_items_by', sa.String(), nullable=False), + sa.Column('group_by_category', sa.Integer(), nullable=False), + sa.Column('category_order', sa.String(), nullable=False), + sa.Column('print_checkboxes', sa.Integer(), nullable=False), + sa.Column('bypass_pending', sa.Integer(), nullable=False), + sa.Column('bypass_kds', sa.Integer(), nullable=False), + sa.Column('auto_ready_to_served', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['master_printer_id'], ['printers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('prep_zones', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_prep_zones_id'), ['id'], unique=False) + + op.create_table('price_groups', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.Column('is_active', sa.Integer(), nullable=False), + sa.Column('auto_enable_time', sa.String(), nullable=True), + sa.Column('auto_disable_time', sa.String(), nullable=True), + sa.Column('auto_days', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('price_groups', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_price_groups_id'), ['id'], unique=False) + + op.create_table('products', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('category_id', sa.Integer(), nullable=True), + sa.Column('base_price', sa.Float(), nullable=False), + sa.Column('is_available', sa.Boolean(), nullable=False), + sa.Column('lifecycle_status', sa.String(), nullable=False), + sa.Column('printer_zone_id', sa.Integer(), nullable=True), + sa.Column('image_url', sa.String(), nullable=True), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('digital_visible', sa.Integer(), nullable=False), + sa.Column('digital_available', sa.Integer(), nullable=False), + sa.Column('digital_name', sa.String(), nullable=True), + sa.Column('digital_description', sa.String(), nullable=True), + sa.Column('digital_price', sa.Float(), nullable=True), + sa.Column('digital_discount', sa.Float(), nullable=False), + sa.Column('digital_image_url', sa.String(), nullable=True), + sa.Column('cloud_image_hash', sa.String(), nullable=True), + sa.Column('unit_type', sa.String(), nullable=False), + sa.Column('cost_simple', sa.Float(), nullable=True), + sa.Column('cost_breakdown', sa.Text(), nullable=True), + sa.Column('quick_add_enabled', sa.Boolean(), nullable=False), + sa.Column('is_service_item', sa.Boolean(), nullable=False), + sa.Column('tags', sa.Text(), nullable=True), + sa.Column('fiscal_name', sa.String(), nullable=True), + sa.Column('fiscal_vat_group_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ), + sa.ForeignKeyConstraint(['printer_zone_id'], ['printers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_products_id'), ['id'], unique=False) + + op.create_table('recovery_codes', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('code_hash', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('used_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('recovery_codes', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_recovery_codes_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_recovery_codes_user_id'), ['user_id'], unique=False) + + op.create_table('scheduled_shifts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('scheduled_date', sa.Date(), nullable=False), + sa.Column('start_time', sa.String(), nullable=False), + sa.Column('end_time', sa.String(), nullable=False), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('scheduled_shifts', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_scheduled_shifts_id'), ['id'], unique=False) + + op.create_table('site_notes', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('body', sa.Text(), nullable=False), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('is_pinned', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('site_notes', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_site_notes_id'), ['id'], unique=False) + + op.create_table('site_todos', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('body', sa.Text(), nullable=False), + sa.Column('is_done', sa.Boolean(), nullable=False), + sa.Column('done_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('done_by_id', sa.Integer(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('priority', sa.String(), nullable=False), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['done_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('site_todos', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_site_todos_id'), ['id'], unique=False) + + op.create_table('staff_messages', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('sender_id', sa.Integer(), nullable=False), + sa.Column('body', sa.Text(), nullable=False), + sa.Column('target_waiter_ids', sa.Text(), nullable=False), + sa.Column('table_ids', sa.Text(), nullable=False), + sa.Column('message_type', sa.String(), nullable=False), + sa.Column('kds_zone', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('staff_messages', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_staff_messages_id'), ['id'], unique=False) + + op.create_table('tables', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('number', sa.Integer(), nullable=False), + sa.Column('label', sa.String(), nullable=True), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('seat_count', sa.Integer(), nullable=True), + sa.Column('floor_x', sa.Float(), nullable=True), + sa.Column('floor_y', sa.Float(), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['table_groups.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('tables', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_tables_id'), ['id'], unique=False) + + op.create_table('waiter_discount_settings', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('can_apply_discounts', sa.Integer(), nullable=False), + sa.Column('max_discount_percent', sa.Float(), nullable=True), + sa.Column('max_discount_amount', sa.Float(), nullable=True), + sa.Column('max_total_value_shift', sa.Float(), nullable=True), + sa.Column('max_total_value_workday', sa.Float(), nullable=True), + sa.Column('max_items_per_shift', sa.Integer(), nullable=True), + sa.Column('max_items_per_workday', sa.Integer(), nullable=True), + sa.Column('max_items_per_order', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id') + ) + with op.batch_alter_table('waiter_discount_settings', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_waiter_discount_settings_id'), ['id'], unique=False) + + op.create_table('waiter_zones', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('waiter_id', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.Column('assigned_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['table_groups.id'], ), + sa.ForeignKeyConstraint(['waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('waiter_zones', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_waiter_zones_id'), ['id'], unique=False) + + op.create_table('chat_messages', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('conversation_id', sa.Integer(), nullable=False), + sa.Column('sender_id', sa.Integer(), nullable=False), + sa.Column('body', sa.Text(), nullable=False), + sa.Column('sent_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['conversation_id'], ['conversations.id'], ), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_chat_messages_id'), ['id'], unique=False) + + op.create_table('conversation_participants', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('conversation_id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('joined_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('last_read_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['conversation_id'], ['conversations.id'], ), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('conversation_participants', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_conversation_participants_id'), ['id'], unique=False) + + op.create_table('expenses', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('category', sa.String(), nullable=False), + sa.Column('contact_id', sa.Integer(), nullable=True), + sa.Column('total_amount', sa.Float(), nullable=False), + sa.Column('paid_amount', sa.Float(), nullable=False), + sa.Column('due_date', sa.DateTime(timezone=True), nullable=True), + sa.Column('business_day_id', sa.Integer(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['business_day_id'], ['business_days.id'], ), + sa.ForeignKeyConstraint(['contact_id'], ['contacts.id'], ), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('expenses', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_expenses_id'), ['id'], unique=False) + + op.create_table('orders', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('table_id', sa.Integer(), nullable=True), + sa.Column('opened_by', sa.Integer(), nullable=False), + sa.Column('opened_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.Column('closed_at', sa.DateTime(), nullable=True), + sa.Column('closed_by', sa.Integer(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('business_day_id', sa.Integer(), nullable=True), + sa.Column('kds_status', sa.String(), nullable=False), + sa.Column('kds_status_changed_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('order_type', sa.String(), nullable=False), + sa.Column('source', sa.String(), nullable=False), + sa.Column('online_order_ref', sa.String(), nullable=True), + sa.Column('online_order_cloud_id', sa.Integer(), nullable=True), + sa.Column('online_status', sa.String(), nullable=True), + sa.Column('online_customer_name', sa.String(), nullable=True), + sa.Column('online_customer_phone', sa.String(), nullable=True), + sa.Column('online_customer_address', sa.Text(), nullable=True), + sa.Column('online_customer_notes', sa.Text(), nullable=True), + sa.Column('online_order_type', sa.String(), nullable=True), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('customer_count', sa.Integer(), nullable=True), + sa.Column('fiscal_status', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['business_day_id'], ['business_days.id'], ), + sa.ForeignKeyConstraint(['closed_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ), + sa.ForeignKeyConstraint(['opened_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('orders', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_orders_id'), ['id'], unique=False) + + op.create_table('prep_zone_printers', + sa.Column('prep_zone_id', sa.Integer(), nullable=False), + sa.Column('printer_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['prep_zone_id'], ['prep_zones.id'], ), + sa.ForeignKeyConstraint(['printer_id'], ['printers.id'], ), + sa.PrimaryKeyConstraint('prep_zone_id', 'printer_id') + ) + op.create_table('price_modifiers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.Column('is_active', sa.Integer(), nullable=False), + sa.Column('is_favorite', sa.Integer(), nullable=False), + sa.Column('allow_stack', sa.Integer(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('scope', sa.String(), nullable=False), + sa.Column('item_id', sa.Integer(), nullable=True), + sa.Column('action_type', sa.String(), nullable=False), + sa.Column('action_value', sa.Float(), nullable=False), + sa.Column('round_to', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('updated_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['item_id'], ['products.id'], ), + sa.ForeignKeyConstraint(['updated_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('price_modifiers', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_price_modifiers_id'), ['id'], unique=False) + + op.create_table('product_modifier_groups', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('modifier_type', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_modifier_groups', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_modifier_groups_id'), ['id'], unique=False) + + op.create_table('product_prep_zones', + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('prep_zone_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['prep_zone_id'], ['prep_zones.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('product_id', 'prep_zone_id') + ) + op.create_table('product_quick_options', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('price', sa.Float(), nullable=False), + sa.Column('allow_multiple', sa.Boolean(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('is_favorite', sa.Boolean(), nullable=False), + sa.Column('favorite_sort_order', sa.Integer(), nullable=False), + sa.Column('is_compact', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_quick_options', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_quick_options_id'), ['id'], unique=False) + + op.create_table('reservations', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('guest_name', sa.String(), nullable=False), + sa.Column('party_size', sa.Integer(), nullable=False), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('email', sa.String(), nullable=True), + sa.Column('note', sa.Text(), nullable=True), + sa.Column('reserved_for', sa.DateTime(), nullable=False), + sa.Column('table_id', sa.Integer(), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.Column('source', sa.String(), nullable=False), + sa.Column('created_by_user_id', sa.Integer(), nullable=True), + sa.Column('online_customer_id', sa.String(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['created_by_user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('reservations', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_reservations_id'), ['id'], unique=False) + + op.create_table('staff_message_acks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('message_id', sa.Integer(), nullable=False), + sa.Column('waiter_id', sa.Integer(), nullable=False), + sa.Column('acked_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['message_id'], ['staff_messages.id'], ), + sa.ForeignKeyConstraint(['waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('staff_message_acks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_staff_message_acks_id'), ['id'], unique=False) + + op.create_table('table_flag_assignments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('table_id', sa.Integer(), nullable=False), + sa.Column('flag_id', sa.Integer(), nullable=False), + sa.Column('assigned_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('assigned_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['assigned_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['flag_id'], ['table_flag_defs.id'], ), + sa.ForeignKeyConstraint(['table_id'], ['tables.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('table_flag_assignments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_table_flag_assignments_id'), ['id'], unique=False) + + op.create_table('tabs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('status', sa.String(), nullable=False), + sa.Column('opened_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('closed_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('closed_by_id', sa.Integer(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['closed_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('tabs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_tabs_id'), ['id'], unique=False) + + op.create_table('waiter_shifts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('waiter_id', sa.Integer(), nullable=False), + sa.Column('business_day_id', sa.Integer(), nullable=False), + sa.Column('started_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('ended_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('starting_cash', sa.Float(), nullable=True), + sa.Column('total_collected', sa.Float(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('hourly_rate_snapshot', sa.Float(), nullable=True), + sa.Column('counted_cash_end', sa.Float(), nullable=True), + sa.Column('cash_discrepancy', sa.Float(), nullable=True), + sa.ForeignKeyConstraint(['business_day_id'], ['business_days.id'], ), + sa.ForeignKeyConstraint(['waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('waiter_shifts', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_waiter_shifts_id'), ['id'], unique=False) + + op.create_table('waste_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('quantity', sa.Float(), nullable=False), + sa.Column('unit_cost_snapshot', sa.Float(), nullable=True), + sa.Column('total_cost', sa.Float(), nullable=True), + sa.Column('reason', sa.String(), nullable=False), + sa.Column('reason_notes', sa.Text(), nullable=True), + sa.Column('logged_by_id', sa.Integer(), nullable=False), + sa.Column('business_day_id', sa.Integer(), nullable=True), + sa.Column('logged_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['business_day_id'], ['business_days.id'], ), + sa.ForeignKeyConstraint(['logged_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('waste_log', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_waste_log_id'), ['id'], unique=False) + + op.create_table('deals', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('color', sa.String(), nullable=True), + sa.Column('is_active', sa.Integer(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('action_type', sa.String(), nullable=False), + sa.Column('action_modifier_id', sa.Integer(), nullable=True), + sa.Column('action_value', sa.Float(), nullable=True), + sa.Column('action_free_item_id', sa.Integer(), nullable=True), + sa.Column('action_free_target_type', sa.String(), nullable=True), + sa.Column('action_free_target_ids', sa.Text(), nullable=True), + sa.Column('action_free_quantity', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['action_free_item_id'], ['products.id'], ), + sa.ForeignKeyConstraint(['action_modifier_id'], ['price_modifiers.id'], ), + sa.ForeignKeyConstraint(['created_by'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('deals', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_deals_id'), ['id'], unique=False) + + op.create_table('expense_payments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('expense_id', sa.Integer(), nullable=False), + sa.Column('amount', sa.Float(), nullable=False), + sa.Column('paid_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('paid_by_id', sa.Integer(), nullable=False), + sa.Column('notes', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['expense_id'], ['expenses.id'], ), + sa.ForeignKeyConstraint(['paid_by_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('expense_payments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_expense_payments_id'), ['id'], unique=False) + + op.create_table('order_audit_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('event_type', sa.String(), nullable=False), + sa.Column('waiter_id', sa.Integer(), nullable=True), + sa.Column('item_ids', sa.Text(), nullable=True), + sa.Column('amount', sa.Float(), nullable=True), + sa.Column('payment_method', sa.String(), nullable=True), + sa.Column('note', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('offline_uuid', sa.String(), nullable=True), + sa.Column('offline_at', sa.String(), nullable=True), + sa.Column('is_duplicate', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('order_audit_log', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_order_audit_log_id'), ['id'], unique=False) + + op.create_table('order_waiters', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('waiter_id', sa.Integer(), nullable=False), + sa.Column('assigned_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['waiter_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('order_waiters', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_order_waiters_id'), ['id'], unique=False) + + op.create_table('price_modifier_conditions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('modifier_id', sa.Integer(), nullable=False), + sa.Column('condition_type', sa.String(), nullable=False), + sa.Column('params', sa.Text(), nullable=False), + sa.ForeignKeyConstraint(['modifier_id'], ['price_modifiers.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('price_modifier_conditions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_price_modifier_conditions_id'), ['id'], unique=False) + + op.create_table('price_modifier_targets', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('modifier_id', sa.Integer(), nullable=False), + sa.Column('target_type', sa.String(), nullable=False), + sa.Column('target_id', sa.Integer(), nullable=True), + sa.Column('target_tag', sa.String(), nullable=True), + sa.Column('target_ids', sa.Text(), nullable=True), + sa.Column('target_tags', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['modifier_id'], ['price_modifiers.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('price_modifier_targets', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_price_modifier_targets_id'), ['id'], unique=False) + + op.create_table('print_jobs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('printer_id', sa.Integer(), nullable=False), + sa.Column('zone_id', sa.Integer(), nullable=True), + sa.Column('item_ids', sa.Text(), nullable=False), + sa.Column('copies', sa.Integer(), nullable=False), + sa.Column('status', sa.String(), nullable=False), + sa.Column('retry_count', sa.Integer(), nullable=False), + sa.Column('first_attempted_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('last_attempted_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('succeeded_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('cancelled_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('cancel_reason', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['printer_id'], ['printers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('print_jobs', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_print_jobs_id'), ['id'], unique=False) + + op.create_table('print_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('printer_id', sa.Integer(), nullable=False), + sa.Column('printed_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('item_ids', sa.Text(), nullable=False), + sa.Column('success', sa.Boolean(), nullable=False), + sa.Column('error_message', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['printer_id'], ['printers.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('print_log', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_print_log_id'), ['id'], unique=False) + + op.create_table('product_ingredients', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('extra_cost', sa.Float(), nullable=True), + sa.Column('is_favorite', sa.Boolean(), nullable=False), + sa.Column('favorite_sort_order', sa.Integer(), nullable=False), + sa.Column('is_compact', sa.Boolean(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['product_modifier_groups.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_ingredients', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_ingredients_id'), ['id'], unique=False) + + op.create_table('product_options', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('extra_cost', sa.Float(), nullable=True), + sa.Column('allow_multiple', sa.Boolean(), nullable=False), + sa.Column('multi_select', sa.Boolean(), nullable=False), + sa.Column('sub_choices', sa.Text(), nullable=True), + sa.Column('is_favorite', sa.Boolean(), nullable=False), + sa.Column('favorite_sort_order', sa.Integer(), nullable=False), + sa.Column('is_compact', sa.Boolean(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['group_id'], ['product_modifier_groups.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_options', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_options_id'), ['id'], unique=False) + + op.create_table('product_preference_sets', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('default_choice_id', sa.Integer(), nullable=True), + sa.Column('shared_subset', sa.Text(), nullable=True), + sa.Column('is_favorite', sa.Boolean(), nullable=False), + sa.Column('favorite_sort_order', sa.Integer(), nullable=False), + sa.Column('group_id', sa.Integer(), nullable=True), + sa.Column('allow_multi_select', sa.Boolean(), nullable=False), + sa.Column('allow_choice_quantity', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['group_id'], ['product_modifier_groups.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_preference_sets', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_preference_sets_id'), ['id'], unique=False) + + op.create_table('shift_breaks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('shift_id', sa.Integer(), nullable=False), + sa.Column('started_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('ended_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['shift_id'], ['waiter_shifts.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('shift_breaks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_shift_breaks_id'), ['id'], unique=False) + + op.create_table('tab_payments', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('tab_id', sa.Integer(), nullable=False), + sa.Column('amount', sa.Float(), nullable=False), + sa.Column('payment_method', sa.String(), nullable=True), + sa.Column('received_by_id', sa.Integer(), nullable=False), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['received_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['tab_id'], ['tabs.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('tab_payments', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_tab_payments_id'), ['id'], unique=False) + + op.create_table('deal_conditions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('deal_id', sa.Integer(), nullable=False), + sa.Column('condition_type', sa.String(), nullable=False), + sa.Column('params', sa.Text(), nullable=False), + sa.ForeignKeyConstraint(['deal_id'], ['deals.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('deal_conditions', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_deal_conditions_id'), ['id'], unique=False) + + op.create_table('deal_targets', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('deal_id', sa.Integer(), nullable=False), + sa.Column('target_type', sa.String(), nullable=False), + sa.Column('target_id', sa.Integer(), nullable=True), + sa.Column('target_tag', sa.String(), nullable=True), + sa.Column('target_ids', sa.Text(), nullable=True), + sa.Column('target_tags', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['deal_id'], ['deals.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('deal_targets', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_deal_targets_id'), ['id'], unique=False) + + op.create_table('order_items', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('product_id', sa.Integer(), nullable=False), + sa.Column('added_by', sa.Integer(), nullable=False), + sa.Column('quantity', sa.Float(), nullable=False), + sa.Column('unit_price', sa.Float(), nullable=False), + sa.Column('selected_options', sa.Text(), nullable=True), + sa.Column('removed_ingredients', sa.Text(), nullable=True), + sa.Column('notes', sa.Text(), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.Column('kds_status', sa.String(), nullable=False), + sa.Column('added_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('printed', sa.Boolean(), nullable=False), + sa.Column('paid_by', sa.Integer(), nullable=True), + sa.Column('paid_at', sa.DateTime(), nullable=True), + sa.Column('payment_method', sa.String(), nullable=True), + sa.Column('paid_in_shift_id', sa.Integer(), nullable=True), + sa.Column('unit_cost', sa.Float(), nullable=True), + sa.Column('price_adjustment', sa.Float(), nullable=False), + sa.Column('cancelled_by', sa.Integer(), nullable=True), + sa.Column('cancelled_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('cancel_reason', sa.Text(), nullable=True), + sa.Column('decline_note', sa.Text(), nullable=True), + sa.Column('course_id', sa.Integer(), nullable=True), + sa.Column('deal_id', sa.Integer(), nullable=True), + sa.Column('linked_item_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['added_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['cancelled_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['deal_id'], ['deals.id'], ), + sa.ForeignKeyConstraint(['linked_item_id'], ['order_items.id'], ), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['paid_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['paid_in_shift_id'], ['waiter_shifts.id'], ), + sa.ForeignKeyConstraint(['product_id'], ['products.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_order_items_id'), ['id'], unique=False) + + op.create_table('product_preference_choices', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('set_id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('extra_cost', sa.Float(), nullable=True), + sa.Column('sub_choices', sa.Text(), nullable=True), + sa.Column('disables_subset', sa.Boolean(), nullable=False), + sa.Column('is_compact', sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(['set_id'], ['product_preference_sets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('product_preference_choices', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_product_preference_choices_id'), ['id'], unique=False) + + op.create_table('order_discounts', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('item_id', sa.Integer(), nullable=True), + sa.Column('discount_type', sa.String(), nullable=False), + sa.Column('discount_value', sa.Float(), nullable=False), + sa.Column('applied_by', sa.Integer(), nullable=False), + sa.Column('applied_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('reason', sa.Text(), nullable=True), + sa.ForeignKeyConstraint(['applied_by'], ['users.id'], ), + sa.ForeignKeyConstraint(['item_id'], ['order_items.id'], ), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('order_discounts', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_order_discounts_id'), ['id'], unique=False) + + op.create_table('price_event_log', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=False), + sa.Column('order_item_id', sa.Integer(), nullable=True), + sa.Column('event_type', sa.String(), nullable=False), + sa.Column('modifier_id', sa.Integer(), nullable=True), + sa.Column('deal_id', sa.Integer(), nullable=True), + sa.Column('price_before', sa.Float(), nullable=True), + sa.Column('price_after', sa.Float(), nullable=True), + sa.Column('delta_amount', sa.Float(), nullable=True), + sa.Column('applied_by_user_id', sa.Integer(), nullable=True), + sa.Column('waiter_note', sa.Text(), nullable=True), + sa.Column('conditions_snapshot', sa.Text(), nullable=True), + sa.Column('selected_item_ids', sa.Text(), nullable=True), + sa.Column('applied_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['applied_by_user_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['deal_id'], ['deals.id'], ), + sa.ForeignKeyConstraint(['modifier_id'], ['price_modifiers.id'], ), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['order_item_id'], ['order_items.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('price_event_log', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_price_event_log_id'), ['id'], unique=False) + batch_op.create_index(batch_op.f('ix_price_event_log_order_id'), ['order_id'], unique=False) + batch_op.create_index(batch_op.f('ix_price_event_log_order_item_id'), ['order_item_id'], unique=False) + + op.create_table('tab_entries', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('tab_id', sa.Integer(), nullable=False), + sa.Column('order_id', sa.Integer(), nullable=True), + sa.Column('order_item_id', sa.Integer(), nullable=True), + sa.Column('amount', sa.Float(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('created_by_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ), + sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ), + sa.ForeignKeyConstraint(['order_item_id'], ['order_items.id'], ), + sa.ForeignKeyConstraint(['tab_id'], ['tabs.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('tab_entries', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_tab_entries_id'), ['id'], unique=False) + + # ### end Alembic commands ### + + settings_table = sa.table( + "pos_settings", + sa.column("key", sa.String), sa.column("value", sa.String), sa.column("updated_at", sa.DateTime(timezone=True)), + ) + now = datetime.now(timezone.utc) + op.bulk_insert(settings_table, [{"key": k, "value": v, "updated_at": now} for k, v in INSTALL_SETTINGS.items()]) + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('tab_entries', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_tab_entries_id')) + + op.drop_table('tab_entries') + with op.batch_alter_table('price_event_log', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_price_event_log_order_item_id')) + batch_op.drop_index(batch_op.f('ix_price_event_log_order_id')) + batch_op.drop_index(batch_op.f('ix_price_event_log_id')) + + op.drop_table('price_event_log') + with op.batch_alter_table('order_discounts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_order_discounts_id')) + + op.drop_table('order_discounts') + with op.batch_alter_table('product_preference_choices', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_preference_choices_id')) + + op.drop_table('product_preference_choices') + with op.batch_alter_table('order_items', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_order_items_id')) + + op.drop_table('order_items') + with op.batch_alter_table('deal_targets', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_deal_targets_id')) + + op.drop_table('deal_targets') + with op.batch_alter_table('deal_conditions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_deal_conditions_id')) + + op.drop_table('deal_conditions') + with op.batch_alter_table('tab_payments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_tab_payments_id')) + + op.drop_table('tab_payments') + with op.batch_alter_table('shift_breaks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_shift_breaks_id')) + + op.drop_table('shift_breaks') + with op.batch_alter_table('product_preference_sets', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_preference_sets_id')) + + op.drop_table('product_preference_sets') + with op.batch_alter_table('product_options', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_options_id')) + + op.drop_table('product_options') + with op.batch_alter_table('product_ingredients', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_ingredients_id')) + + op.drop_table('product_ingredients') + with op.batch_alter_table('print_log', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_print_log_id')) + + op.drop_table('print_log') + with op.batch_alter_table('print_jobs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_print_jobs_id')) + + op.drop_table('print_jobs') + with op.batch_alter_table('price_modifier_targets', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_price_modifier_targets_id')) + + op.drop_table('price_modifier_targets') + with op.batch_alter_table('price_modifier_conditions', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_price_modifier_conditions_id')) + + op.drop_table('price_modifier_conditions') + with op.batch_alter_table('order_waiters', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_order_waiters_id')) + + op.drop_table('order_waiters') + with op.batch_alter_table('order_audit_log', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_order_audit_log_id')) + + op.drop_table('order_audit_log') + with op.batch_alter_table('expense_payments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_expense_payments_id')) + + op.drop_table('expense_payments') + with op.batch_alter_table('deals', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_deals_id')) + + op.drop_table('deals') + with op.batch_alter_table('waste_log', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_waste_log_id')) + + op.drop_table('waste_log') + with op.batch_alter_table('waiter_shifts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_waiter_shifts_id')) + + op.drop_table('waiter_shifts') + with op.batch_alter_table('tabs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_tabs_id')) + + op.drop_table('tabs') + with op.batch_alter_table('table_flag_assignments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_table_flag_assignments_id')) + + op.drop_table('table_flag_assignments') + with op.batch_alter_table('staff_message_acks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_staff_message_acks_id')) + + op.drop_table('staff_message_acks') + with op.batch_alter_table('reservations', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_reservations_id')) + + op.drop_table('reservations') + with op.batch_alter_table('product_quick_options', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_quick_options_id')) + + op.drop_table('product_quick_options') + op.drop_table('product_prep_zones') + with op.batch_alter_table('product_modifier_groups', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_product_modifier_groups_id')) + + op.drop_table('product_modifier_groups') + with op.batch_alter_table('price_modifiers', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_price_modifiers_id')) + + op.drop_table('price_modifiers') + op.drop_table('prep_zone_printers') + with op.batch_alter_table('orders', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_orders_id')) + + op.drop_table('orders') + with op.batch_alter_table('expenses', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_expenses_id')) + + op.drop_table('expenses') + with op.batch_alter_table('conversation_participants', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_conversation_participants_id')) + + op.drop_table('conversation_participants') + with op.batch_alter_table('chat_messages', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_chat_messages_id')) + + op.drop_table('chat_messages') + with op.batch_alter_table('waiter_zones', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_waiter_zones_id')) + + op.drop_table('waiter_zones') + with op.batch_alter_table('waiter_discount_settings', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_waiter_discount_settings_id')) + + op.drop_table('waiter_discount_settings') + with op.batch_alter_table('tables', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_tables_id')) + + op.drop_table('tables') + with op.batch_alter_table('staff_messages', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_staff_messages_id')) + + op.drop_table('staff_messages') + with op.batch_alter_table('site_todos', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_site_todos_id')) + + op.drop_table('site_todos') + with op.batch_alter_table('site_notes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_site_notes_id')) + + op.drop_table('site_notes') + with op.batch_alter_table('scheduled_shifts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_scheduled_shifts_id')) + + op.drop_table('scheduled_shifts') + with op.batch_alter_table('recovery_codes', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_recovery_codes_user_id')) + batch_op.drop_index(batch_op.f('ix_recovery_codes_id')) + + op.drop_table('recovery_codes') + with op.batch_alter_table('products', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_products_id')) + + op.drop_table('products') + with op.batch_alter_table('price_groups', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_price_groups_id')) + + op.drop_table('price_groups') + with op.batch_alter_table('prep_zones', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_prep_zones_id')) + + op.drop_table('prep_zones') + op.drop_table('pos_settings') + with op.batch_alter_table('customers', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_customers_id')) + + op.drop_table('customers') + with op.batch_alter_table('conversations', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_conversations_id')) + + op.drop_table('conversations') + with op.batch_alter_table('business_days', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_business_days_id')) + + op.drop_table('business_days') + with op.batch_alter_table('assistant_assignments', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_assistant_assignments_id')) + + op.drop_table('assistant_assignments') + with op.batch_alter_table('users', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_users_username')) + batch_op.drop_index(batch_op.f('ix_users_id')) + + op.drop_table('users') + with op.batch_alter_table('table_groups', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_table_groups_id')) + + op.drop_table('table_groups') + with op.batch_alter_table('table_flag_defs', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_table_flag_defs_id')) + + op.drop_table('table_flag_defs') + with op.batch_alter_table('sync_events', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_sync_events_created_at')) + + op.drop_table('sync_events') + with op.batch_alter_table('quick_message_templates', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_quick_message_templates_id')) + + op.drop_table('quick_message_templates') + with op.batch_alter_table('printers', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_printers_id')) + + op.drop_table('printers') + with op.batch_alter_table('contacts', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_contacts_id')) + + op.drop_table('contacts') + with op.batch_alter_table('categories', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_categories_id')) + + op.drop_table('categories') + # ### end Alembic commands ### diff --git a/local_backend/models/all.py b/local_backend/models/all.py new file mode 100644 index 0000000..50ea612 --- /dev/null +++ b/local_backend/models/all.py @@ -0,0 +1,29 @@ +"""Import every model module so Base.metadata knows the whole schema. + +Used by main.py (app startup), migrations/env.py (Alembic autogenerate) and +the tests. Agent note: a new model module MUST be added here, or Alembic +autogenerate will not see it and the drift guard (tests/guards) will not +catch it either. +""" +import models.user # noqa: F401 also registers WaiterZone +import models.table # noqa: F401 +import models.printer # noqa: F401 +import models.product # noqa: F401 +import models.customers # noqa: F401 +import models.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob +import models.business_day # noqa: F401 +import models.shift # noqa: F401 WaiterShift, ShiftBreak +import models.settings # noqa: F401 +import models.flag # noqa: F401 TableFlagDef, TableFlagAssignment +import models.message # noqa: F401 StaffMessage, StaffMessageAck, QuickMessageTemplate +import models.reservation # noqa: F401 +import models.notes # noqa: F401 SiteNote, SiteTodo +import models.expenses # noqa: F401 Contact, Expense, ExpensePayment +import models.tabs # noqa: F401 Tab, TabEntry, TabPayment +import models.waste # noqa: F401 WasteLog +import models.schedule # noqa: F401 ScheduledShift +import models.chat # noqa: F401 Conversation, ConversationParticipant, ChatMessage +import models.prep_zone # noqa: F401 PrepZone, prep_zone_printers, product_prep_zones +import models.pricing # noqa: F401 PriceGroup, PriceModifier, Deal, PriceEventLog, WaiterDiscountSettings +import models.recovery_code # noqa: F401 +import models.sync_event # noqa: F401 diff --git a/local_backend/models/pricing.py b/local_backend/models/pricing.py index 7450a36..4504689 100644 --- a/local_backend/models/pricing.py +++ b/local_backend/models/pricing.py @@ -216,8 +216,8 @@ class PriceEventLog(Base): __tablename__ = "price_event_log" id = Column(Integer, primary_key=True, index=True) - order_id = Column(Integer, ForeignKey("orders.id"), nullable=False) - order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True) # NULL for order-level events + order_id = Column(Integer, ForeignKey("orders.id"), nullable=False, index=True) + order_item_id = Column(Integer, ForeignKey("order_items.id"), nullable=True, index=True) # NULL for order-level events # Event classification event_type = Column(String, nullable=False) diff --git a/local_backend/models/sync_event.py b/local_backend/models/sync_event.py new file mode 100644 index 0000000..4e2bf5d --- /dev/null +++ b/local_backend/models/sync_event.py @@ -0,0 +1,22 @@ +"""WebSocket replay buffer (F-014): every broadcast event gets a seq id the clients resume from. + +Written and read with raw SQL in services/ws_bus.py (hot path, no ORM). The model +exists so the table is part of the Alembic-managed schema. +- sqlite_autoincrement: ids must never be reused after old rows are pruned, or a + client's cursor could skip events. +- created_at is an ISO string with offset (v1 audit, APPS_PLATFORM §7.4). + >>> Step 1.1 converts it to the UTC datetime type. +""" +from sqlalchemy import Column, Integer, String, Text +from database import Base + + +class SyncEvent(Base): + __tablename__ = "sync_events" + __table_args__ = {"sqlite_autoincrement": True} + + id = Column(Integer, primary_key=True) + event_type = Column(String, nullable=False) + payload = Column(Text, nullable=False) + target_user_ids = Column(Text, nullable=True) + created_at = Column(String, nullable=False, index=True) diff --git a/local_backend/requirements.txt b/local_backend/requirements.txt index eccd31c..4e3ec77 100644 --- a/local_backend/requirements.txt +++ b/local_backend/requirements.txt @@ -10,3 +10,4 @@ pyjwt==2.9.0 httpx==0.27.2 python-multipart==0.0.9 cryptography==46.0.4 +alembic==1.14.0 diff --git a/local_backend/seed.py b/local_backend/seed.py index 406b6e9..8be42e3 100644 --- a/local_backend/seed.py +++ b/local_backend/seed.py @@ -3,14 +3,11 @@ Run once to bootstrap the database with initial data. Usage: python seed.py """ import bcrypt -from database import engine, Base, SessionLocal -import models.user -import models.table -import models.printer -import models.product -import models.order +from database import SessionLocal +import models.all # noqa: F401 +from core.schema import upgrade_to_head -Base.metadata.create_all(bind=engine) +upgrade_to_head() db = SessionLocal() diff --git a/local_backend/tests/conftest.py b/local_backend/tests/conftest.py index 990e2c4..79ad85e 100644 --- a/local_backend/tests/conftest.py +++ b/local_backend/tests/conftest.py @@ -13,9 +13,8 @@ How the DB tests are isolated (agent notes): * Before anything imports config/database, this file points DATABASE_URL, LOG_DIR and TLS_DIR at a fresh temp folder. Tests can never touch a dev or venue database. - * The schema is built once per test session (fixture `_schema`). - >>> Step 1.0 (Alembic) must replace the body of `_build_schema` with - >>> `alembic upgrade head`, so tests run on exactly the migrated schema. + * The schema is built once per test session (fixture `_engine`) with the same + Alembic upgrade the app runs at startup, so tests see the migrated schema. * Each test gets one connection with an outer transaction that is rolled back at the end. App code may call db.commit() freely: the session uses join_transaction_mode="create_savepoint", so its commits only release @@ -68,10 +67,9 @@ def pytest_collection_modifyitems(config, items): # ── schema + per-test transaction ─────────────────────────────────────────── def _build_schema(engine): - import main # registers every model; also runs setup_logging() into LOG_DIR - from database import Base - Base.metadata.create_all(bind=engine) - main._run_migrations() + import main # noqa: F401 registers every model; also runs setup_logging() into LOG_DIR + from core.schema import upgrade_to_head + upgrade_to_head(engine) @pytest.fixture(scope="session") diff --git a/local_backend/tests/guards/README.md b/local_backend/tests/guards/README.md new file mode 100644 index 0000000..bb10c74 --- /dev/null +++ b/local_backend/tests/guards/README.md @@ -0,0 +1,10 @@ +# Guard tests (APPS_PLATFORM D-17) + +Tests that protect platform-wide rules rather than one feature. They must stay green; if one fails, fix the code, not the guard. +Changing a guard's rule is a design decision: record it in APPS_PLATFORM §2 first. + +| File | Rule | Filled in | +|---|---|---| +| `test_migrations.py` | Models and Alembic revisions don't drift; the schema is built only by Alembic; v1 databases are refused | step 1.0 | +| `test_no_naive_datetimes.py` | No `datetime.utcnow`, argument-less `now()` / `.astimezone()`, or `Column(DateTime` in backend code | step 1.1 (placeholder until then) | +| `test_route_access.py` | Every route declares `require(...)`, `require_device(...)` or `public()` | step 1.5 (placeholder until then) | diff --git a/local_backend/tests/guards/__init__.py b/local_backend/tests/guards/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/local_backend/tests/guards/test_migrations.py b/local_backend/tests/guards/test_migrations.py new file mode 100644 index 0000000..28f996d --- /dev/null +++ b/local_backend/tests/guards/test_migrations.py @@ -0,0 +1,74 @@ +"""Schema guard (D-13, D-17): Alembic is the only source of the schema, and it matches the models. + +If test_no_drift fails, you changed a model without a revision (or the reverse): + cd local_backend + alembic revision --autogenerate --rev-id NNNN_short_name -m "what changed" +then REVIEW the generated file (SQLite batch ops, data moves) and run the tests again. +""" +import re +from pathlib import Path + +import pytest +from alembic.autogenerate import compare_metadata +from alembic.migration import MigrationContext +from sqlalchemy import create_engine, inspect, text + +from core.schema import V1DatabaseError, current_head, upgrade_to_head + +BACKEND = Path(__file__).resolve().parents[2] + + +def _fresh_engine(tmp_path): + return create_engine(f"sqlite:///{(tmp_path / 'g.db').as_posix()}") + + +def test_upgrade_empty_db_then_no_drift(tmp_path): + from database import Base + import models.all # noqa: F401 + + eng = _fresh_engine(tmp_path) + upgrade_to_head(eng) + with eng.connect() as conn: + ctx = MigrationContext.configure(conn, opts={"compare_type": True, "render_as_batch": True}) + diff = compare_metadata(ctx, Base.metadata) + version = conn.execute(text("select version_num from alembic_version")).scalar() + eng.dispose() + assert diff == [], "models and migrations drifted:\n" + "\n".join(map(str, diff)) + assert version == current_head() + + +def test_upgrade_is_idempotent(tmp_path): + eng = _fresh_engine(tmp_path) + upgrade_to_head(eng) + upgrade_to_head(eng) # second start of the app: nothing to do, no error + eng.dispose() + + +def test_install_defaults_seeded(tmp_path): + eng = _fresh_engine(tmp_path) + upgrade_to_head(eng) + with eng.connect() as conn: + method = conn.execute(text("select value from pos_settings where key='security.login_method'")).scalar() + eng.dispose() + assert method == "password" + + +def test_v1_database_is_refused(tmp_path): + eng = _fresh_engine(tmp_path) + with eng.begin() as conn: + conn.execute(text("create table orders (id integer primary key)")) + with pytest.raises(V1DatabaseError): + upgrade_to_head(eng) + assert "alembic_version" not in inspect(eng).get_table_names() + eng.dispose() + + +def test_nothing_calls_create_all(): + offenders = [] + for f in BACKEND.rglob("*.py"): + rel = f.relative_to(BACKEND).as_posix() + if rel.startswith(("tests/", "migrations/")) or "/__pycache__/" in rel: + continue + if re.search(r"\.create_all\(", f.read_text(encoding="utf-8", errors="ignore")): + offenders.append(rel) + assert offenders == [], f"use core.schema.upgrade_to_head() instead of create_all: {offenders}" diff --git a/local_backend/tests/guards/test_no_naive_datetimes.py b/local_backend/tests/guards/test_no_naive_datetimes.py new file mode 100644 index 0000000..72bf98f --- /dev/null +++ b/local_backend/tests/guards/test_no_naive_datetimes.py @@ -0,0 +1,8 @@ +"""Time guard (D-11, D-17). Filled in by plan step 1.1 (time model).""" +import pytest + +pytestmark = pytest.mark.skip(reason="placeholder: implemented in platform-v2 step 1.1") + + +def test_no_naive_datetimes(): + raise NotImplementedError diff --git a/local_backend/tests/guards/test_route_access.py b/local_backend/tests/guards/test_route_access.py new file mode 100644 index 0000000..81a7d93 --- /dev/null +++ b/local_backend/tests/guards/test_route_access.py @@ -0,0 +1,8 @@ +"""Access guard (D-7, D-17): every route declares require()/require_device()/public(). Filled in by plan step 1.5.""" +import pytest + +pytestmark = pytest.mark.skip(reason="placeholder: implemented in platform-v2 step 1.5") + + +def test_every_route_declares_access(): + raise NotImplementedError diff --git a/local_backend/wipe_database.py b/local_backend/wipe_database.py index b8c5ab5..2c5423a 100644 --- a/local_backend/wipe_database.py +++ b/local_backend/wipe_database.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- """ -Wipes the POS database completely and re-applies the schema + default seed data. +Wipes the POS database completely and re-creates it through Alembic +(schema + install defaults, migrations/versions/0001_v2_baseline.py). Usage: python wipe_database.py @@ -23,27 +24,9 @@ if answer != "YES": # ── Imports (after confirmation, so we don't waste time if user bails) ──────── from sqlalchemy import text, inspect -from database import engine, Base, SessionLocal +from database import engine -# Import all models so Base.metadata knows about every table. -# Order matters: tables with no FK dependencies first, then dependents. -import models.user # noqa: F401 -import models.table # noqa: F401 -import models.printer # noqa: F401 -import models.product # noqa: F401 -import models.customers # noqa: F401 must be before models.order (orders.customer_id FK) -import models.order # noqa: F401 -import models.business_day # noqa: F401 -import models.shift # noqa: F401 -import models.settings # noqa: F401 -import models.flag # noqa: F401 -import models.message # noqa: F401 -import models.notes # noqa: F401 -import models.expenses # noqa: F401 -import models.tabs # noqa: F401 -import models.schedule # noqa: F401 -import models.waste # noqa: F401 -import models.reservation # noqa: F401 +from core.schema import upgrade_to_head print("\nDropping all tables...") @@ -65,63 +48,8 @@ with engine.connect() as conn: conn.execute(text("PRAGMA foreign_keys = ON")) conn.commit() -print("\nRecreating schema...") -Base.metadata.create_all(bind=engine) - -# Re-run the same migration/seed SQL from main.py so default settings, -# flags, and quick message templates are present after the wipe. -print("Applying seed migrations...") - -seed_migrations = [ - # pos_settings defaults - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_start', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('shifts.waiter_self_end', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('business_day.force_close_allowed', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('flags.display_mode', 'both', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.ticket_mode', 'detailed', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_number', '48:1:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_meta', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_name', '16:1:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_quick', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_pref', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_extra', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_ingredient', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_item_note', '0:0:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('print.font_order_note', '0:1:0', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.name', '', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('venue.type', '', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.login_method', 'password', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.autofill_username', 'true', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock', 'false', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_lock_seconds', '300', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout', 'false', CURRENT_TIMESTAMP)", - "INSERT OR IGNORE INTO pos_settings (key, value, updated_at) VALUES ('security.auto_logout_seconds', '1800', CURRENT_TIMESTAMP)", - # Default table flag definitions - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (1, 'Χρειάζεται καθάρισμα', '🧹', '#ef4444', 1)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (2, 'Χρειάζεται Βοήθεια', '🆘', '#f97316', 2)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (3, 'Χρειάζεται Σερβιτόρο', '🔔', '#eab308', 3)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (4, 'Περιμένει να πληρώσει', '💳', '#3b82f6', 4)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (5, 'VIP', '⭐', '#8b5cf6', 5)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (6, 'Ευγενικός Πελάτης', '😊', '#22c55e', 6)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (7, 'Αγενής Πελάτης', '😤', '#dc2626', 7)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (8, 'Αλλεργίες', '⚠️', '#f59e0b', 8)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (9, 'Παιδιά στο τραπέζι', '👶', '#06b6d4', 9)", - "INSERT OR IGNORE INTO table_flag_defs (id, name, emoji, color, sort_order) VALUES (10, 'Επέτειος / Γενέθλια', '🎂', '#ec4899', 10)", - # Default quick message templates - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (1, 'Σε χρειάζομαι τώρα', 1)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (2, 'Πάρε διάλειμμα', 2)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (3, 'Ετοιμάσου για κλείσιμο', 3)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (4, 'Ήρθε νέος πελάτης', 4)", - "INSERT OR IGNORE INTO quick_message_templates (id, body, sort_order) VALUES (5, 'Ο πελάτης περιμένει να πληρώσει', 5)", -] - -for sql in seed_migrations: - try: - with engine.connect() as conn: - conn.execute(text(sql)) - conn.commit() - except Exception as e: - print(f" [skip] {e}") +print("\nRecreating schema (Alembic, incl. install defaults)...") +upgrade_to_head() print("\nDone. Database is clean and ready.") print("Run python demo_seed.py to populate with demo data.")