098_migrate_purchase_subscription_to_custom_menu.sql 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -- 096_migrate_purchase_subscription_to_custom_menu.sql
  2. --
  3. -- Migrates the legacy purchase_subscription_url setting into custom_menu_items.
  4. -- After migration, purchase_subscription_enabled is set to "false" and
  5. -- purchase_subscription_url is cleared.
  6. --
  7. -- Idempotent: skips if custom_menu_items already contains
  8. -- "migrated_purchase_subscription".
  9. DO $$
  10. DECLARE
  11. v_enabled text;
  12. v_url text;
  13. v_raw text;
  14. v_items jsonb;
  15. v_new_item jsonb;
  16. BEGIN
  17. -- Read legacy settings
  18. SELECT value INTO v_enabled
  19. FROM settings WHERE key = 'purchase_subscription_enabled';
  20. SELECT value INTO v_url
  21. FROM settings WHERE key = 'purchase_subscription_url';
  22. -- Skip if not enabled or URL is empty
  23. IF COALESCE(v_enabled, '') <> 'true' OR COALESCE(TRIM(v_url), '') = '' THEN
  24. RETURN;
  25. END IF;
  26. -- Read current custom_menu_items
  27. SELECT value INTO v_raw
  28. FROM settings WHERE key = 'custom_menu_items';
  29. IF COALESCE(v_raw, '') = '' OR v_raw = 'null' THEN
  30. v_items := '[]'::jsonb;
  31. ELSE
  32. v_items := v_raw::jsonb;
  33. END IF;
  34. -- Skip if already migrated (item with id "migrated_purchase_subscription" exists)
  35. IF EXISTS (
  36. SELECT 1 FROM jsonb_array_elements(v_items) elem
  37. WHERE elem ->> 'id' = 'migrated_purchase_subscription'
  38. ) THEN
  39. RETURN;
  40. END IF;
  41. -- Build the new menu item
  42. v_new_item := jsonb_build_object(
  43. 'id', 'migrated_purchase_subscription',
  44. 'label', 'Purchase',
  45. 'icon_svg', '',
  46. 'url', TRIM(v_url),
  47. 'visibility', 'user',
  48. 'sort_order', 100
  49. );
  50. -- Append to array
  51. v_items := v_items || jsonb_build_array(v_new_item);
  52. -- Upsert custom_menu_items
  53. INSERT INTO settings (key, value)
  54. VALUES ('custom_menu_items', v_items::text)
  55. ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
  56. -- Clear legacy settings
  57. UPDATE settings SET value = 'false' WHERE key = 'purchase_subscription_enabled';
  58. UPDATE settings SET value = '' WHERE key = 'purchase_subscription_url';
  59. RAISE NOTICE '[migration-096] Migrated purchase_subscription_url (%) to custom_menu_items', v_url;
  60. END $$;