-- Ensure every saved billing rule can be executed by the invoice job. UPDATE sag_subscriptions SET billing_schedule_type = 'interval_anchor', updated_at = CURRENT_TIMESTAMP WHERE billing_interval IN ('daily', 'biweekly') AND billing_schedule_type IS DISTINCT FROM 'interval_anchor'; UPDATE sag_subscriptions SET billing_schedule_type = 'fixed_day', updated_at = CURRENT_TIMESTAMP WHERE billing_interval IN ('monthly', 'quarterly', 'yearly') AND billing_schedule_type = 'interval_anchor'; ALTER TABLE sag_subscriptions DROP CONSTRAINT IF EXISTS sag_subscriptions_runnable_schedule_check; ALTER TABLE sag_subscriptions ADD CONSTRAINT sag_subscriptions_runnable_schedule_check CHECK ( (billing_interval IN ('daily', 'biweekly') AND billing_schedule_type = 'interval_anchor') OR (billing_interval IN ('monthly', 'quarterly', 'yearly') AND billing_schedule_type IN ('fixed_day', 'first_business_day', 'last_business_day')) ); -- Existing legacy days 29-31 remain visible for manual review, but new/updated -- fixed-day rules must always be executable. ALTER TABLE sag_subscriptions DROP CONSTRAINT IF EXISTS sag_subscriptions_runnable_billing_day_check; ALTER TABLE sag_subscriptions ADD CONSTRAINT sag_subscriptions_runnable_billing_day_check CHECK ( billing_schedule_type <> 'fixed_day' OR billing_day BETWEEN 1 AND 28 ) NOT VALID;