"""Tabs in the books (plan step 6.13c, KI-018): a line put on a tab and a payment on a tab record the business day and the shift they happened in (the shift of whoever did it, if they were on one), so a shift shows what it put on tabs and the tab money it received, and the day shows both. Existing rows get their business day from when they happened. Revision ID: 0037_tab_books Revises: 0036_print_job_resolution Create Date: 2026-11-19 12:00:00 """ from alembic import op import sqlalchemy as sa revision = '0037_tab_books' down_revision = '0036_print_job_resolution' branch_labels = None depends_on = None TABLES = ('tab_entries', 'tab_payments') def upgrade() -> None: for t in TABLES: with op.batch_alter_table(t, schema=None) as batch_op: batch_op.add_column(sa.Column('business_day_id', sa.Integer(), nullable=True)) batch_op.add_column(sa.Column('shift_id', sa.Integer(), nullable=True)) batch_op.create_index(f'ix_{t}_business_day_id', ['business_day_id']) batch_op.create_index(f'ix_{t}_shift_id', ['shift_id']) batch_op.create_foreign_key(f'fk_{t}_business_day_id_business_days', 'business_days', ['business_day_id'], ['id']) batch_op.create_foreign_key(f'fk_{t}_shift_id_waiter_shifts', 'waiter_shifts', ['shift_id'], ['id']) # the day each existing row happened in (a closed day's window, or the open one) op.execute(f""" UPDATE {t} SET business_day_id = ( SELECT d.id FROM business_days d WHERE d.opened_at <= {t}.created_at AND (d.closed_at IS NULL OR d.closed_at >= {t}.created_at) ORDER BY d.opened_at DESC LIMIT 1) """) def downgrade() -> None: for t in TABLES: with op.batch_alter_table(t, schema=None) as batch_op: batch_op.drop_constraint(f'fk_{t}_shift_id_waiter_shifts', type_='foreignkey') batch_op.drop_constraint(f'fk_{t}_business_day_id_business_days', type_='foreignkey') batch_op.drop_index(f'ix_{t}_shift_id') batch_op.drop_index(f'ix_{t}_business_day_id') batch_op.drop_column('shift_id') batch_op.drop_column('business_day_id')