-- scheduled_notifications.created_by is the admin actor who scheduled the job. -- Admin panel auth (POST /team/login) JWT user_id is team_members.id, not users.id. ALTER TABLE scheduled_notifications DROP CONSTRAINT IF EXISTS scheduled_notifications_created_by_fkey; -- Remap legacy rows that stored platform users.id to a valid team member when possible. UPDATE scheduled_notifications sn SET created_by = tm.id FROM users u JOIN team_members tm ON LOWER(TRIM(tm.email)) = LOWER(TRIM(u.email)) WHERE sn.created_by = u.id AND NOT EXISTS (SELECT 1 FROM team_members existing WHERE existing.id = sn.created_by); -- Fallback: assign orphaned created_by values to the earliest team member. UPDATE scheduled_notifications sn SET created_by = (SELECT id FROM team_members ORDER BY id LIMIT 1) WHERE NOT EXISTS (SELECT 1 FROM team_members tm WHERE tm.id = sn.created_by); ALTER TABLE scheduled_notifications ADD CONSTRAINT scheduled_notifications_created_by_fkey FOREIGN KEY (created_by) REFERENCES team_members(id);