@nextblock-cms/db 0.15.5 → 0.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -109,6 +109,7 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
109
109
  content: string;
110
110
  created_at: string;
111
111
  id: string;
112
+ parent_id: string | null;
112
113
  post_id: number | null;
113
114
  product_id: string | null;
114
115
  rating: number | null;
@@ -122,6 +123,7 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
122
123
  content: string;
123
124
  created_at?: string;
124
125
  id?: string;
126
+ parent_id?: string | null;
125
127
  post_id?: number | null;
126
128
  product_id?: string | null;
127
129
  rating?: number | null;
@@ -135,6 +137,7 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
135
137
  content?: string;
136
138
  created_at?: string;
137
139
  id?: string;
140
+ parent_id?: string | null;
138
141
  post_id?: number | null;
139
142
  product_id?: string | null;
140
143
  rating?: number | null;
@@ -145,6 +148,12 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
145
148
  user_id?: string;
146
149
  };
147
150
  Relationships: [{
151
+ foreignKeyName: "cms_interactions_parent_id_fkey";
152
+ columns: ["parent_id"];
153
+ isOneToOne: false;
154
+ referencedRelation: "cms_interactions";
155
+ referencedColumns: ["id"];
156
+ }, {
148
157
  foreignKeyName: "cms_interactions_post_id_fkey";
149
158
  columns: ["post_id"];
150
159
  isOneToOne: false;
@@ -563,6 +572,33 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
563
572
  };
564
573
  Relationships: [];
565
574
  };
575
+ form_endpoints: {
576
+ Row: {
577
+ created_at: string;
578
+ fields: import('./types').Json;
579
+ form_key: string;
580
+ label: string;
581
+ recipient_email: string | null;
582
+ updated_at: string;
583
+ };
584
+ Insert: {
585
+ created_at?: string;
586
+ fields?: import('./types').Json;
587
+ form_key: string;
588
+ label?: string;
589
+ recipient_email?: string | null;
590
+ updated_at?: string;
591
+ };
592
+ Update: {
593
+ created_at?: string;
594
+ fields?: import('./types').Json;
595
+ form_key?: string;
596
+ label?: string;
597
+ recipient_email?: string | null;
598
+ updated_at?: string;
599
+ };
600
+ Relationships: [];
601
+ };
566
602
  freemius_plans: {
567
603
  Row: {
568
604
  created_at: string;
@@ -824,6 +860,78 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
824
860
  referencedColumns: ["id"];
825
861
  }];
826
862
  };
863
+ message_threads: {
864
+ Row: {
865
+ created_at: string;
866
+ fields: import('./types').Json;
867
+ form_key: string | null;
868
+ id: string;
869
+ ip_masked: string | null;
870
+ last_message_at: string;
871
+ locale: string | null;
872
+ sender_email: string | null;
873
+ sender_name: string | null;
874
+ source: string;
875
+ status: string;
876
+ subject_id: string | null;
877
+ subject_label: string;
878
+ token_expires_at: string | null;
879
+ token_hash: string | null;
880
+ token_last_used_at: string | null;
881
+ token_revoked_at: string | null;
882
+ unread_for_admin: boolean;
883
+ unread_for_visitor: boolean;
884
+ updated_at: string;
885
+ user_agent: string | null;
886
+ };
887
+ Insert: {
888
+ created_at?: string;
889
+ fields?: import('./types').Json;
890
+ form_key?: string | null;
891
+ id?: string;
892
+ ip_masked?: string | null;
893
+ last_message_at?: string;
894
+ locale?: string | null;
895
+ sender_email?: string | null;
896
+ sender_name?: string | null;
897
+ source: string;
898
+ status?: string;
899
+ subject_id?: string | null;
900
+ subject_label?: string;
901
+ token_expires_at?: string | null;
902
+ token_hash?: string | null;
903
+ token_last_used_at?: string | null;
904
+ token_revoked_at?: string | null;
905
+ unread_for_admin?: boolean;
906
+ unread_for_visitor?: boolean;
907
+ updated_at?: string;
908
+ user_agent?: string | null;
909
+ };
910
+ Update: {
911
+ created_at?: string;
912
+ fields?: import('./types').Json;
913
+ form_key?: string | null;
914
+ id?: string;
915
+ ip_masked?: string | null;
916
+ last_message_at?: string;
917
+ locale?: string | null;
918
+ sender_email?: string | null;
919
+ sender_name?: string | null;
920
+ source?: string;
921
+ status?: string;
922
+ subject_id?: string | null;
923
+ subject_label?: string;
924
+ token_expires_at?: string | null;
925
+ token_hash?: string | null;
926
+ token_last_used_at?: string | null;
927
+ token_revoked_at?: string | null;
928
+ unread_for_admin?: boolean;
929
+ unread_for_visitor?: boolean;
930
+ updated_at?: string;
931
+ user_agent?: string | null;
932
+ };
933
+ Relationships: [];
934
+ };
827
935
  navigation_items: {
828
936
  Row: {
829
937
  created_at: string;
@@ -1532,6 +1640,54 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
1532
1640
  referencedColumns: ["id"];
1533
1641
  }];
1534
1642
  };
1643
+ product_inquiries: {
1644
+ Row: {
1645
+ created_at: string;
1646
+ email_delivered: boolean;
1647
+ id: string;
1648
+ ip_masked: string | null;
1649
+ is_resolved: boolean;
1650
+ locale: string | null;
1651
+ message: string;
1652
+ product_id: string | null;
1653
+ product_slug: string | null;
1654
+ product_title: string | null;
1655
+ sender_email: string;
1656
+ sender_name: string;
1657
+ user_agent: string | null;
1658
+ };
1659
+ Insert: {
1660
+ created_at?: string;
1661
+ email_delivered?: boolean;
1662
+ id?: string;
1663
+ ip_masked?: string | null;
1664
+ is_resolved?: boolean;
1665
+ locale?: string | null;
1666
+ message: string;
1667
+ product_id?: string | null;
1668
+ product_slug?: string | null;
1669
+ product_title?: string | null;
1670
+ sender_email: string;
1671
+ sender_name: string;
1672
+ user_agent?: string | null;
1673
+ };
1674
+ Update: {
1675
+ created_at?: string;
1676
+ email_delivered?: boolean;
1677
+ id?: string;
1678
+ ip_masked?: string | null;
1679
+ is_resolved?: boolean;
1680
+ locale?: string | null;
1681
+ message?: string;
1682
+ product_id?: string | null;
1683
+ product_slug?: string | null;
1684
+ product_title?: string | null;
1685
+ sender_email?: string;
1686
+ sender_name?: string;
1687
+ user_agent?: string | null;
1688
+ };
1689
+ Relationships: [];
1690
+ };
1535
1691
  product_media: {
1536
1692
  Row: {
1537
1693
  media_id: string;
@@ -2177,6 +2333,51 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
2177
2333
  };
2178
2334
  Relationships: [];
2179
2335
  };
2336
+ thread_messages: {
2337
+ Row: {
2338
+ author_id: string | null;
2339
+ author_name: string | null;
2340
+ body: string;
2341
+ created_at: string;
2342
+ direction: string;
2343
+ email_delivered: boolean;
2344
+ email_error: string | null;
2345
+ id: string;
2346
+ ip_masked: string | null;
2347
+ thread_id: string;
2348
+ };
2349
+ Insert: {
2350
+ author_id?: string | null;
2351
+ author_name?: string | null;
2352
+ body: string;
2353
+ created_at?: string;
2354
+ direction: string;
2355
+ email_delivered?: boolean;
2356
+ email_error?: string | null;
2357
+ id?: string;
2358
+ ip_masked?: string | null;
2359
+ thread_id: string;
2360
+ };
2361
+ Update: {
2362
+ author_id?: string | null;
2363
+ author_name?: string | null;
2364
+ body?: string;
2365
+ created_at?: string;
2366
+ direction?: string;
2367
+ email_delivered?: boolean;
2368
+ email_error?: string | null;
2369
+ id?: string;
2370
+ ip_masked?: string | null;
2371
+ thread_id?: string;
2372
+ };
2373
+ Relationships: [{
2374
+ foreignKeyName: "thread_messages_thread_id_fkey";
2375
+ columns: ["thread_id"];
2376
+ isOneToOne: false;
2377
+ referencedRelation: "message_threads";
2378
+ referencedColumns: ["id"];
2379
+ }];
2380
+ };
2180
2381
  translations: {
2181
2382
  Row: {
2182
2383
  created_at: string;
@@ -2521,6 +2722,6 @@ export declare const getServiceRoleSupabaseClient: () => import('@supabase/supab
2521
2722
  };
2522
2723
  CompositeTypes: { [_ in never]: never; };
2523
2724
  }, {
2524
- PostgrestVersion: "14.15";
2725
+ PostgrestVersion: "14.17";
2525
2726
  }>;
2526
2727
  export {};
@@ -3,7 +3,7 @@ export type Json = string | number | boolean | null | {
3
3
  } | Json[];
4
4
  export type Database = {
5
5
  __InternalSupabase: {
6
- PostgrestVersion: "14.15";
6
+ PostgrestVersion: "14.17";
7
7
  };
8
8
  public: {
9
9
  Tables: {
@@ -110,6 +110,7 @@ export type Database = {
110
110
  content: string;
111
111
  created_at: string;
112
112
  id: string;
113
+ parent_id: string | null;
113
114
  post_id: number | null;
114
115
  product_id: string | null;
115
116
  rating: number | null;
@@ -123,6 +124,7 @@ export type Database = {
123
124
  content: string;
124
125
  created_at?: string;
125
126
  id?: string;
127
+ parent_id?: string | null;
126
128
  post_id?: number | null;
127
129
  product_id?: string | null;
128
130
  rating?: number | null;
@@ -136,6 +138,7 @@ export type Database = {
136
138
  content?: string;
137
139
  created_at?: string;
138
140
  id?: string;
141
+ parent_id?: string | null;
139
142
  post_id?: number | null;
140
143
  product_id?: string | null;
141
144
  rating?: number | null;
@@ -146,6 +149,13 @@ export type Database = {
146
149
  user_id?: string;
147
150
  };
148
151
  Relationships: [
152
+ {
153
+ foreignKeyName: "cms_interactions_parent_id_fkey";
154
+ columns: ["parent_id"];
155
+ isOneToOne: false;
156
+ referencedRelation: "cms_interactions";
157
+ referencedColumns: ["id"];
158
+ },
149
159
  {
150
160
  foreignKeyName: "cms_interactions_post_id_fkey";
151
161
  columns: ["post_id"];
@@ -581,6 +591,33 @@ export type Database = {
581
591
  };
582
592
  Relationships: [];
583
593
  };
594
+ form_endpoints: {
595
+ Row: {
596
+ created_at: string;
597
+ fields: Json;
598
+ form_key: string;
599
+ label: string;
600
+ recipient_email: string | null;
601
+ updated_at: string;
602
+ };
603
+ Insert: {
604
+ created_at?: string;
605
+ fields?: Json;
606
+ form_key: string;
607
+ label?: string;
608
+ recipient_email?: string | null;
609
+ updated_at?: string;
610
+ };
611
+ Update: {
612
+ created_at?: string;
613
+ fields?: Json;
614
+ form_key?: string;
615
+ label?: string;
616
+ recipient_email?: string | null;
617
+ updated_at?: string;
618
+ };
619
+ Relationships: [];
620
+ };
584
621
  freemius_plans: {
585
622
  Row: {
586
623
  created_at: string;
@@ -850,6 +887,78 @@ export type Database = {
850
887
  }
851
888
  ];
852
889
  };
890
+ message_threads: {
891
+ Row: {
892
+ created_at: string;
893
+ fields: Json;
894
+ form_key: string | null;
895
+ id: string;
896
+ ip_masked: string | null;
897
+ last_message_at: string;
898
+ locale: string | null;
899
+ sender_email: string | null;
900
+ sender_name: string | null;
901
+ source: string;
902
+ status: string;
903
+ subject_id: string | null;
904
+ subject_label: string;
905
+ token_expires_at: string | null;
906
+ token_hash: string | null;
907
+ token_last_used_at: string | null;
908
+ token_revoked_at: string | null;
909
+ unread_for_admin: boolean;
910
+ unread_for_visitor: boolean;
911
+ updated_at: string;
912
+ user_agent: string | null;
913
+ };
914
+ Insert: {
915
+ created_at?: string;
916
+ fields?: Json;
917
+ form_key?: string | null;
918
+ id?: string;
919
+ ip_masked?: string | null;
920
+ last_message_at?: string;
921
+ locale?: string | null;
922
+ sender_email?: string | null;
923
+ sender_name?: string | null;
924
+ source: string;
925
+ status?: string;
926
+ subject_id?: string | null;
927
+ subject_label?: string;
928
+ token_expires_at?: string | null;
929
+ token_hash?: string | null;
930
+ token_last_used_at?: string | null;
931
+ token_revoked_at?: string | null;
932
+ unread_for_admin?: boolean;
933
+ unread_for_visitor?: boolean;
934
+ updated_at?: string;
935
+ user_agent?: string | null;
936
+ };
937
+ Update: {
938
+ created_at?: string;
939
+ fields?: Json;
940
+ form_key?: string | null;
941
+ id?: string;
942
+ ip_masked?: string | null;
943
+ last_message_at?: string;
944
+ locale?: string | null;
945
+ sender_email?: string | null;
946
+ sender_name?: string | null;
947
+ source?: string;
948
+ status?: string;
949
+ subject_id?: string | null;
950
+ subject_label?: string;
951
+ token_expires_at?: string | null;
952
+ token_hash?: string | null;
953
+ token_last_used_at?: string | null;
954
+ token_revoked_at?: string | null;
955
+ unread_for_admin?: boolean;
956
+ unread_for_visitor?: boolean;
957
+ updated_at?: string;
958
+ user_agent?: string | null;
959
+ };
960
+ Relationships: [];
961
+ };
853
962
  navigation_items: {
854
963
  Row: {
855
964
  created_at: string;
@@ -1592,6 +1701,54 @@ export type Database = {
1592
1701
  }
1593
1702
  ];
1594
1703
  };
1704
+ product_inquiries: {
1705
+ Row: {
1706
+ created_at: string;
1707
+ email_delivered: boolean;
1708
+ id: string;
1709
+ ip_masked: string | null;
1710
+ is_resolved: boolean;
1711
+ locale: string | null;
1712
+ message: string;
1713
+ product_id: string | null;
1714
+ product_slug: string | null;
1715
+ product_title: string | null;
1716
+ sender_email: string;
1717
+ sender_name: string;
1718
+ user_agent: string | null;
1719
+ };
1720
+ Insert: {
1721
+ created_at?: string;
1722
+ email_delivered?: boolean;
1723
+ id?: string;
1724
+ ip_masked?: string | null;
1725
+ is_resolved?: boolean;
1726
+ locale?: string | null;
1727
+ message: string;
1728
+ product_id?: string | null;
1729
+ product_slug?: string | null;
1730
+ product_title?: string | null;
1731
+ sender_email: string;
1732
+ sender_name: string;
1733
+ user_agent?: string | null;
1734
+ };
1735
+ Update: {
1736
+ created_at?: string;
1737
+ email_delivered?: boolean;
1738
+ id?: string;
1739
+ ip_masked?: string | null;
1740
+ is_resolved?: boolean;
1741
+ locale?: string | null;
1742
+ message?: string;
1743
+ product_id?: string | null;
1744
+ product_slug?: string | null;
1745
+ product_title?: string | null;
1746
+ sender_email?: string;
1747
+ sender_name?: string;
1748
+ user_agent?: string | null;
1749
+ };
1750
+ Relationships: [];
1751
+ };
1595
1752
  product_media: {
1596
1753
  Row: {
1597
1754
  media_id: string;
@@ -2252,6 +2409,53 @@ export type Database = {
2252
2409
  };
2253
2410
  Relationships: [];
2254
2411
  };
2412
+ thread_messages: {
2413
+ Row: {
2414
+ author_id: string | null;
2415
+ author_name: string | null;
2416
+ body: string;
2417
+ created_at: string;
2418
+ direction: string;
2419
+ email_delivered: boolean;
2420
+ email_error: string | null;
2421
+ id: string;
2422
+ ip_masked: string | null;
2423
+ thread_id: string;
2424
+ };
2425
+ Insert: {
2426
+ author_id?: string | null;
2427
+ author_name?: string | null;
2428
+ body: string;
2429
+ created_at?: string;
2430
+ direction: string;
2431
+ email_delivered?: boolean;
2432
+ email_error?: string | null;
2433
+ id?: string;
2434
+ ip_masked?: string | null;
2435
+ thread_id: string;
2436
+ };
2437
+ Update: {
2438
+ author_id?: string | null;
2439
+ author_name?: string | null;
2440
+ body?: string;
2441
+ created_at?: string;
2442
+ direction?: string;
2443
+ email_delivered?: boolean;
2444
+ email_error?: string | null;
2445
+ id?: string;
2446
+ ip_masked?: string | null;
2447
+ thread_id?: string;
2448
+ };
2449
+ Relationships: [
2450
+ {
2451
+ foreignKeyName: "thread_messages_thread_id_fkey";
2452
+ columns: ["thread_id"];
2453
+ isOneToOne: false;
2454
+ referencedRelation: "message_threads";
2455
+ referencedColumns: ["id"];
2456
+ }
2457
+ ];
2458
+ };
2255
2459
  translations: {
2256
2460
  Row: {
2257
2461
  created_at: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextblock-cms/db",
3
- "version": "0.15.5",
3
+ "version": "0.15.9",
4
4
  "main": "index.cjs.js",
5
5
  "module": "index.es.js",
6
6
  "types": "index.d.ts",
@@ -0,0 +1,118 @@
1
+ -- Purchase enquiries raised when the store cannot take payment.
2
+ --
3
+ -- A NextBlock store can be fully built — products, prices, images, pages — while its
4
+ -- Stripe or Freemius credentials are still missing. Until this migration the only
5
+ -- symptom was a shopper reaching checkout and receiving the payment provider's raw
6
+ -- rejection ("Invalid API Key provided: sk_test_*ummy"), which tells them nothing and
7
+ -- loses the sale outright.
8
+ --
9
+ -- The storefront now offers those shoppers an enquiry form in place of Add-to-Cart,
10
+ -- and every submission lands here. The row is the product, not the email: SMTP is a
11
+ -- separate piece of setup that the same half-configured store has usually also not
12
+ -- done, so a notification that cannot be sent must never be the only record. The
13
+ -- `email_delivered` flag records whether the owner was successfully notified; false
14
+ -- means "read this in the CMS, nobody got a mail about it".
15
+ --
16
+ -- SECURITY POSTURE. Rows hold visitor-supplied PII (name, email, free text) plus a
17
+ -- masked IP. There is deliberately NO anon policy of any kind: anonymous visitors
18
+ -- neither read nor write this table directly. The public server action inserts with
19
+ -- the service-role client after bot-protection and throttle checks, exactly as
20
+ -- `privacy_consent_logs` does — that keeps the insert shape server-controlled and
21
+ -- means a leaked anon key cannot enumerate or seed enquiries. ADMINs read; nobody
22
+ -- else does, because these are sales leads and personal data.
23
+ --
24
+ -- `product_id` is a PLAIN uuid with NO foreign key, following site_script_revisions:
25
+ -- an enquiry is evidence that someone wanted a product, and deleting the product
26
+ -- should not delete or rewrite that evidence. `product_slug` and `product_title` are
27
+ -- denormalised so a deleted product is still identifiable in the list.
28
+ --
29
+ -- Forward-only and idempotent.
30
+
31
+ CREATE TABLE IF NOT EXISTS public.product_inquiries (
32
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
33
+ -- No FK by design (see header). Null when the product was deleted after the fact.
34
+ product_id uuid,
35
+ product_slug text,
36
+ product_title text,
37
+ sender_name text NOT NULL,
38
+ sender_email text NOT NULL,
39
+ message text NOT NULL,
40
+ -- Which language the visitor was browsing in, so the owner can reply in kind.
41
+ locale text,
42
+ ip_masked text,
43
+ user_agent text,
44
+ -- False when SMTP was unconfigured or the send failed: the CMS list is then the
45
+ -- only place this enquiry exists.
46
+ email_delivered boolean DEFAULT false NOT NULL,
47
+ is_resolved boolean DEFAULT false NOT NULL,
48
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
49
+ CONSTRAINT product_inquiries_pkey PRIMARY KEY (id),
50
+ CONSTRAINT product_inquiries_sender_name_not_blank CHECK ((char_length(btrim(sender_name)) > 0)),
51
+ CONSTRAINT product_inquiries_sender_email_not_blank CHECK ((char_length(btrim(sender_email)) > 0)),
52
+ CONSTRAINT product_inquiries_message_not_blank CHECK ((char_length(btrim(message)) > 0))
53
+ );
54
+
55
+ COMMENT ON TABLE public.product_inquiries IS 'Visitor purchase enquiries raised when the store cannot take payment. Written by the service role from a public server action; read by ADMINs only.';
56
+
57
+ COMMENT ON COLUMN public.product_inquiries.product_id IS 'Plain uuid, no FK: an enquiry outlives the product it was about.';
58
+
59
+ COMMENT ON COLUMN public.product_inquiries.ip_masked IS 'Partially masked IP (e.g. 203.0.113.x) - never store a full address. Also backs the per-IP submission throttle.';
60
+
61
+ COMMENT ON COLUMN public.product_inquiries.email_delivered IS 'False when the owner notification could not be sent (e.g. SMTP unconfigured); the stored row is then the only record.';
62
+
63
+ -- Newest-first is the only listing order the CMS needs.
64
+ CREATE INDEX IF NOT EXISTS product_inquiries_created_idx
65
+ ON public.product_inquiries USING btree (created_at DESC);
66
+
67
+ -- Backs the throttle lookup in the public server action: count recent rows per IP.
68
+ CREATE INDEX IF NOT EXISTS product_inquiries_ip_created_idx
69
+ ON public.product_inquiries USING btree (ip_masked, created_at DESC);
70
+
71
+ -- Lets the CMS count outstanding enquiries without scanning resolved history.
72
+ CREATE INDEX IF NOT EXISTS product_inquiries_unresolved_idx
73
+ ON public.product_inquiries USING btree (created_at DESC)
74
+ WHERE (is_resolved = false);
75
+
76
+ ALTER TABLE public.product_inquiries ENABLE ROW LEVEL SECURITY;
77
+
78
+ -- anon is deliberately absent: the public path goes through the service role.
79
+ GRANT SELECT, UPDATE ON TABLE public.product_inquiries TO authenticated;
80
+ GRANT ALL ON TABLE public.product_inquiries TO service_role;
81
+
82
+ DROP POLICY IF EXISTS product_inquiries_admin_read_policy ON public.product_inquiries;
83
+ CREATE POLICY product_inquiries_admin_read_policy ON public.product_inquiries FOR SELECT TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
84
+
85
+ -- ADMINs may only flip the resolved flag; the enquiry content itself is a record.
86
+ DROP POLICY IF EXISTS product_inquiries_admin_update_policy ON public.product_inquiries;
87
+ CREATE POLICY product_inquiries_admin_update_policy ON public.product_inquiries FOR UPDATE TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role)) WITH CHECK ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
88
+
89
+ DROP POLICY IF EXISTS product_inquiries_service_role_policy ON public.product_inquiries;
90
+ CREATE POLICY product_inquiries_service_role_policy ON public.product_inquiries TO service_role USING (true) WITH CHECK (true);
91
+
92
+ -- Where enquiry notifications are sent. Kept in the PUBLIC settings row rather than the
93
+ -- secret one because it is an address, not a credential — but it is never rendered to
94
+ -- the storefront: the public form posts a product id and the server resolves the
95
+ -- recipient. Empty string means "fall back", see resolveSellerContactEmail().
96
+ INSERT INTO public.site_settings (key, value)
97
+ VALUES ('store_contact', '{"contactEmail": ""}'::jsonb)
98
+ ON CONFLICT (key) DO NOTHING;
99
+
100
+ -- Storefront copy for the enquiry flow. Public-facing, so it must be translatable;
101
+ -- the components pass an English literal as the fallback, so an install that never
102
+ -- runs this seed still renders correctly.
103
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
104
+ ('ecommerce.contact_seller', '{"en": "Contact the seller", "fr": "Contacter le vendeur"}', now(), now()),
105
+ ('ecommerce.contact_seller_heading', '{"en": "Interested in this product?", "fr": "Ce produit vous intéresse ?"}', now(), now()),
106
+ ('ecommerce.contact_seller_intro', '{"en": "Online ordering isn''t available for this item yet. Send the seller a message and they''ll get back to you about buying it.", "fr": "La commande en ligne n''est pas encore disponible pour cet article. Envoyez un message au vendeur et il vous répondra au sujet de son achat."}', now(), now()),
107
+ ('ecommerce.contact_seller_name', '{"en": "Your name", "fr": "Votre nom"}', now(), now()),
108
+ ('ecommerce.contact_seller_email', '{"en": "Your email", "fr": "Votre courriel"}', now(), now()),
109
+ ('ecommerce.contact_seller_message', '{"en": "Message", "fr": "Message"}', now(), now()),
110
+ ('ecommerce.contact_seller_send', '{"en": "Send message", "fr": "Envoyer le message"}', now(), now()),
111
+ ('ecommerce.contact_seller_sending', '{"en": "Sending...", "fr": "Envoi..."}', now(), now()),
112
+ ('ecommerce.contact_seller_sent', '{"en": "Thanks - your message has been sent to the seller. They''ll reply to the email address you gave.", "fr": "Merci - votre message a été envoyé au vendeur. Il répondra à l''adresse courriel que vous avez indiquée."}', now(), now()),
113
+ ('ecommerce.contact_seller_error', '{"en": "Sorry, your message couldn''t be sent. Please try again in a moment.", "fr": "Désolé, votre message n''a pas pu être envoyé. Veuillez réessayer dans un instant."}', now(), now()),
114
+ ('ecommerce.contact_seller_invalid', '{"en": "Please check your name, email address and message, then try again.", "fr": "Veuillez vérifier votre nom, votre adresse courriel et votre message, puis réessayer."}', now(), now()),
115
+ ('ecommerce.contact_seller_throttled', '{"en": "You''ve sent several messages already. Please wait a few minutes before sending another.", "fr": "Vous avez déjà envoyé plusieurs messages. Veuillez patienter quelques minutes avant d''en envoyer un autre."}', now(), now()),
116
+ ('ecommerce.not_available_for_purchase', '{"en": "Not available for online purchase", "fr": "Non disponible à l''achat en ligne"}', now(), now()),
117
+ ('ecommerce.checkout_payments_unavailable', '{"en": "This store is not able to take payments right now. Please contact the seller to complete your purchase.", "fr": "Cette boutique ne peut pas accepter de paiements pour le moment. Veuillez contacter le vendeur pour finaliser votre achat."}', now(), now())
118
+ ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,391 @@
1
+ -- Private conversations with anonymous visitors, and the end of the exposed form address.
2
+ --
3
+ -- Two problems, one shape.
4
+ --
5
+ -- FIRST: a contact-form block stores its destination address in the block's own
6
+ -- content, and `FormBlockRenderer` is a "use client" component that receives that
7
+ -- content wholesale. Everything crossing that boundary is serialized into the RSC
8
+ -- payload, so the shop owner's inbox is published in the markup of every page
9
+ -- carrying a form. `form_endpoints` moves the address server-side and leaves behind a
10
+ -- `form_key` — an opaque handle that grants nothing and is safe to serialize.
11
+ --
12
+ -- SECOND: a visitor who sends a message has nowhere to receive an answer. They are
13
+ -- anonymous — `cms_interactions` cannot hold them, because its `user_id` is NOT NULL
14
+ -- with a foreign key to `profiles`. So this is a separate lane: `message_threads` plus
15
+ -- `thread_messages`, reached by a tokenised link rather than an account.
16
+ --
17
+ -- WHY REVIEWS AND COMMENTS ARE NOT HERE. They are already public, already tied to a
18
+ -- registered account, and a staff answer to them is published content, not a private
19
+ -- reply. That lane stays in `cms_interactions` and is handled by migration 28. One
20
+ -- inbox reads both; the storage stays honest about the difference.
21
+ --
22
+ -- SECURITY POSTURE. Rows hold visitor PII (name, email, free text) and a masked IP.
23
+ -- There is NO anon grant and NO anon policy: the tokenised visitor page verifies the
24
+ -- token in application code and then reads with the service role, the same posture the
25
+ -- MCP token route takes against `mcp_access_tokens`. ADMINs read; nobody else does.
26
+ --
27
+ -- `token_hash` stores only a SHA-256 of the visitor's token. The plaintext exists long
28
+ -- enough to be placed in one outbound email and is never written down. A token is
29
+ -- minted on the FIRST ADMIN REPLY, never at submission — a store that receives a
30
+ -- hundred enquiries and answers three has three live credentials, not a hundred.
31
+ --
32
+ -- `source` is a text column with a CHECK rather than an enum, deliberately.
33
+ -- `interaction_type` in this same schema is the cautionary tale: a two-value enum
34
+ -- guarded by an exhaustive CHECK, where adding a third value needs ALTER TYPE ... ADD
35
+ -- VALUE — and PostgreSQL forbids using a value added in the transaction that added it,
36
+ -- which is exactly one migration file. A CHECK is replaceable in one statement.
37
+ --
38
+ -- Forward-only and idempotent.
39
+
40
+ -- ---------------------------------------------------------------------------
41
+ -- 1. form_endpoints — where a contact-form block's mail goes, and what its fields
42
+ -- are called. `fields` is a SERVER-SIDE snapshot of the field manifest so the
43
+ -- notification email renders labels the browser did not supply; the same rule
44
+ -- the product-enquiry action follows when it looks the product title up itself.
45
+ -- ---------------------------------------------------------------------------
46
+ CREATE TABLE IF NOT EXISTS public.form_endpoints (
47
+ form_key uuid NOT NULL,
48
+ label text DEFAULT 'Contact form' NOT NULL,
49
+ -- NULL/empty means "fall back to the resolver ladder", like store_contact.
50
+ recipient_email text,
51
+ fields jsonb DEFAULT '[]'::jsonb NOT NULL,
52
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
53
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
54
+ CONSTRAINT form_endpoints_pkey PRIMARY KEY (form_key),
55
+ CONSTRAINT form_endpoints_label_not_blank CHECK ((char_length(btrim(label)) > 0)),
56
+ CONSTRAINT form_endpoints_fields_array CHECK ((jsonb_typeof(fields) = 'array'))
57
+ );
58
+
59
+ COMMENT ON TABLE public.form_endpoints IS 'Server-side destination and field manifest for a contact-form block, keyed by the non-secret form_key carried in block content. The address never reaches the browser.';
60
+
61
+ COMMENT ON COLUMN public.form_endpoints.form_key IS 'Non-secret opaque handle. Safe in the RSC payload: it grants nothing, it is only a lookup key.';
62
+
63
+ COMMENT ON COLUMN public.form_endpoints.fields IS 'Snapshot of [{temp_id,label,field_type}] written by the CMS editor, so labels in emails and the inbox are server-trusted.';
64
+
65
+ DROP TRIGGER IF EXISTS set_form_endpoints_updated_at ON public.form_endpoints;
66
+ CREATE TRIGGER set_form_endpoints_updated_at BEFORE UPDATE ON public.form_endpoints
67
+ FOR EACH ROW EXECUTE FUNCTION public.set_current_timestamp_updated_at();
68
+
69
+ ALTER TABLE public.form_endpoints ENABLE ROW LEVEL SECURITY;
70
+
71
+ -- anon deliberately absent: the public submit path goes through the service role.
72
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.form_endpoints TO authenticated;
73
+ GRANT ALL ON TABLE public.form_endpoints TO service_role;
74
+
75
+ DROP POLICY IF EXISTS form_endpoints_editor_read_policy ON public.form_endpoints;
76
+ CREATE POLICY form_endpoints_editor_read_policy ON public.form_endpoints FOR SELECT TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = ANY (ARRAY['ADMIN'::public.user_role, 'WRITER'::public.user_role])));
77
+
78
+ DROP POLICY IF EXISTS form_endpoints_admin_write_policy ON public.form_endpoints;
79
+ CREATE POLICY form_endpoints_admin_write_policy ON public.form_endpoints FOR ALL TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role)) WITH CHECK ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
80
+
81
+ DROP POLICY IF EXISTS form_endpoints_service_role_policy ON public.form_endpoints;
82
+ CREATE POLICY form_endpoints_service_role_policy ON public.form_endpoints TO service_role USING (true) WITH CHECK (true);
83
+
84
+ -- ---------------------------------------------------------------------------
85
+ -- 2. message_threads — the private-lane spine and the only home of a thread token.
86
+ -- `subject_id` and `form_key` are PLAIN uuids with NO foreign key: a conversation
87
+ -- outlives the product or the form block it started from.
88
+ -- ---------------------------------------------------------------------------
89
+ CREATE TABLE IF NOT EXISTS public.message_threads (
90
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
91
+ source text NOT NULL,
92
+ -- product_inquiries.id when source = 'product_inquiry'.
93
+ subject_id uuid,
94
+ -- form_endpoints.form_key when source = 'contact_form'.
95
+ form_key uuid,
96
+ -- Denormalised so a deleted product or removed form block stays identifiable.
97
+ subject_label text DEFAULT 'Message' NOT NULL,
98
+ sender_name text,
99
+ -- NULL when a contact form collected no email field. Such a thread can never be
100
+ -- answered, and the CMS says so rather than failing silently at reply time.
101
+ sender_email text,
102
+ locale text,
103
+ -- Submitted field map for a contact form: {temp_id: value}.
104
+ fields jsonb DEFAULT '{}'::jsonb NOT NULL,
105
+ status text DEFAULT 'open' NOT NULL,
106
+ unread_for_admin boolean DEFAULT true NOT NULL,
107
+ unread_for_visitor boolean DEFAULT false NOT NULL,
108
+ -- SHA-256 hex of the visitor's token; NULL until the first admin reply.
109
+ token_hash text,
110
+ token_expires_at timestamp with time zone,
111
+ token_revoked_at timestamp with time zone,
112
+ token_last_used_at timestamp with time zone,
113
+ last_message_at timestamp with time zone DEFAULT now() NOT NULL,
114
+ ip_masked text,
115
+ user_agent text,
116
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
117
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
118
+ CONSTRAINT message_threads_pkey PRIMARY KEY (id),
119
+ CONSTRAINT message_threads_token_hash_key UNIQUE (token_hash),
120
+ CONSTRAINT message_threads_source_check
121
+ CHECK ((source = ANY (ARRAY['product_inquiry'::text, 'contact_form'::text]))),
122
+ CONSTRAINT message_threads_status_check
123
+ CHECK ((status = ANY (ARRAY['open'::text, 'closed'::text]))),
124
+ CONSTRAINT message_threads_subject_check CHECK (
125
+ (((source = 'product_inquiry'::text) AND (subject_id IS NOT NULL)) OR
126
+ ((source = 'contact_form'::text) AND (form_key IS NOT NULL)))),
127
+ CONSTRAINT message_threads_fields_object CHECK ((jsonb_typeof(fields) = 'object'))
128
+ );
129
+
130
+ COMMENT ON TABLE public.message_threads IS 'Private conversations with anonymous visitors (product enquiries and contact-form submissions). Written by the service role from public server actions; read by ADMINs only. Public reviews and comments are NOT here - they live in cms_interactions.';
131
+
132
+ COMMENT ON COLUMN public.message_threads.token_hash IS 'SHA-256 hex of the visitor thread token. The raw token is never stored; it is minted on the first admin reply and mailed once.';
133
+
134
+ COMMENT ON COLUMN public.message_threads.subject_id IS 'product_inquiries.id. Plain uuid, no FK: a conversation outlives the enquiry record it grew from.';
135
+
136
+ CREATE INDEX IF NOT EXISTS message_threads_last_message_idx
137
+ ON public.message_threads USING btree (last_message_at DESC);
138
+
139
+ CREATE INDEX IF NOT EXISTS message_threads_source_last_idx
140
+ ON public.message_threads USING btree (source, last_message_at DESC);
141
+
142
+ -- Backs the CMS nav unread badge without scanning read history.
143
+ CREATE INDEX IF NOT EXISTS message_threads_unread_idx
144
+ ON public.message_threads USING btree (last_message_at DESC)
145
+ WHERE (unread_for_admin = true);
146
+
147
+ -- Idempotent backfill / dedupe of enquiry threads.
148
+ CREATE INDEX IF NOT EXISTS message_threads_subject_idx
149
+ ON public.message_threads USING btree (subject_id) WHERE (subject_id IS NOT NULL);
150
+
151
+ -- No separate token index: message_threads_token_hash_key is already the unique
152
+ -- btree the /thread lookup probes.
153
+
154
+ DROP TRIGGER IF EXISTS set_message_threads_updated_at ON public.message_threads;
155
+ CREATE TRIGGER set_message_threads_updated_at BEFORE UPDATE ON public.message_threads
156
+ FOR EACH ROW EXECUTE FUNCTION public.set_current_timestamp_updated_at();
157
+
158
+ ALTER TABLE public.message_threads ENABLE ROW LEVEL SECURITY;
159
+
160
+ GRANT SELECT, UPDATE ON TABLE public.message_threads TO authenticated;
161
+ GRANT ALL ON TABLE public.message_threads TO service_role;
162
+
163
+ DROP POLICY IF EXISTS message_threads_admin_read_policy ON public.message_threads;
164
+ CREATE POLICY message_threads_admin_read_policy ON public.message_threads FOR SELECT TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
165
+
166
+ DROP POLICY IF EXISTS message_threads_admin_update_policy ON public.message_threads;
167
+ CREATE POLICY message_threads_admin_update_policy ON public.message_threads FOR UPDATE TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role)) WITH CHECK ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
168
+
169
+ DROP POLICY IF EXISTS message_threads_service_role_policy ON public.message_threads;
170
+ CREATE POLICY message_threads_service_role_policy ON public.message_threads TO service_role USING (true) WITH CHECK (true);
171
+
172
+ -- ---------------------------------------------------------------------------
173
+ -- 3. thread_messages — one turn of a private conversation.
174
+ -- ---------------------------------------------------------------------------
175
+ CREATE TABLE IF NOT EXISTS public.thread_messages (
176
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
177
+ thread_id uuid NOT NULL,
178
+ direction text NOT NULL,
179
+ body text NOT NULL,
180
+ -- profiles.id for an outbound reply. No FK: a departing admin must not take the
181
+ -- conversation with them.
182
+ author_id uuid,
183
+ author_name text,
184
+ -- False when SMTP was unconfigured or the send failed. sendEmail() throws when
185
+ -- unconfigured, so this row - not the mail - is the record.
186
+ email_delivered boolean DEFAULT false NOT NULL,
187
+ email_error text,
188
+ ip_masked text,
189
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
190
+ CONSTRAINT thread_messages_pkey PRIMARY KEY (id),
191
+ CONSTRAINT thread_messages_direction_check
192
+ CHECK ((direction = ANY (ARRAY['inbound'::text, 'outbound'::text]))),
193
+ CONSTRAINT thread_messages_body_not_blank CHECK ((char_length(btrim(body)) > 0))
194
+ );
195
+
196
+ COMMENT ON TABLE public.thread_messages IS 'Turns of a private conversation. Content is append-only; only the delivery flags may change after insert.';
197
+
198
+ -- A real foreign key here, unlike the outward pointers above: a message has no
199
+ -- meaning without its thread.
200
+ DO $rb$ BEGIN
201
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
202
+ WHERE conname = 'thread_messages_thread_id_fkey'
203
+ AND conrelid = 'public.thread_messages'::regclass) THEN
204
+ ALTER TABLE ONLY public.thread_messages
205
+ ADD CONSTRAINT thread_messages_thread_id_fkey FOREIGN KEY (thread_id)
206
+ REFERENCES public.message_threads(id) ON DELETE CASCADE;
207
+ END IF;
208
+ END $rb$;
209
+
210
+ CREATE INDEX IF NOT EXISTS thread_messages_thread_created_idx
211
+ ON public.thread_messages USING btree (thread_id, created_at);
212
+
213
+ -- Backs the per-IP reply throttle on the public thread page.
214
+ CREATE INDEX IF NOT EXISTS thread_messages_ip_created_idx
215
+ ON public.thread_messages USING btree (ip_masked, created_at DESC);
216
+
217
+ -- Message TEXT is append-only — not the whole row, because email_delivered has to be
218
+ -- settable after the send completes. The trigger blocks rewrites of the load-bearing
219
+ -- columns only, and it binds the service role too, which otherwise bypasses RLS.
220
+ CREATE OR REPLACE FUNCTION public.prevent_thread_message_rewrite() RETURNS trigger
221
+ LANGUAGE plpgsql SET search_path = '' AS $$
222
+ BEGIN
223
+ IF TG_OP = 'DELETE' THEN
224
+ RAISE EXCEPTION 'thread_messages is append-only; DELETE is not permitted'
225
+ USING ERRCODE = 'restrict_violation';
226
+ END IF;
227
+ IF NEW.body IS DISTINCT FROM OLD.body
228
+ OR NEW.direction IS DISTINCT FROM OLD.direction
229
+ OR NEW.thread_id IS DISTINCT FROM OLD.thread_id
230
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN
231
+ RAISE EXCEPTION 'thread_messages content is append-only; only delivery flags may change'
232
+ USING ERRCODE = 'restrict_violation';
233
+ END IF;
234
+ RETURN NEW;
235
+ END;
236
+ $$;
237
+
238
+ DROP TRIGGER IF EXISTS trg_thread_messages_append_only ON public.thread_messages;
239
+ CREATE TRIGGER trg_thread_messages_append_only BEFORE UPDATE OR DELETE ON public.thread_messages
240
+ FOR EACH ROW EXECUTE FUNCTION public.prevent_thread_message_rewrite();
241
+
242
+ -- NB: the ON DELETE CASCADE above fires this trigger, so deleting a thread is
243
+ -- impossible by design. "Delete" in the CMS means status='closed' plus a revoked
244
+ -- token, and the UI says so.
245
+
246
+ ALTER TABLE public.thread_messages ENABLE ROW LEVEL SECURITY;
247
+
248
+ GRANT SELECT ON TABLE public.thread_messages TO authenticated;
249
+ GRANT ALL ON TABLE public.thread_messages TO service_role;
250
+
251
+ DROP POLICY IF EXISTS thread_messages_admin_read_policy ON public.thread_messages;
252
+ CREATE POLICY thread_messages_admin_read_policy ON public.thread_messages FOR SELECT TO authenticated USING ((( SELECT public.get_current_user_role() AS get_current_user_role) = 'ADMIN'::public.user_role));
253
+
254
+ DROP POLICY IF EXISTS thread_messages_service_role_policy ON public.thread_messages;
255
+ CREATE POLICY thread_messages_service_role_policy ON public.thread_messages TO service_role USING (true) WITH CHECK (true);
256
+
257
+ -- ---------------------------------------------------------------------------
258
+ -- 4. Backfill: every existing enquiry becomes a thread whose first inbound turn is
259
+ -- the original message. product_inquiries is KEPT and kept written — it is the
260
+ -- enquiry's own record and owns the ip_masked the submission throttle counts.
261
+ -- The thread is a conversation ABOUT the enquiry, not a replacement for it.
262
+ -- ---------------------------------------------------------------------------
263
+ INSERT INTO public.message_threads
264
+ (source, subject_id, subject_label, sender_name, sender_email, locale,
265
+ ip_masked, user_agent, unread_for_admin, status, last_message_at, created_at)
266
+ SELECT 'product_inquiry', i.id, COALESCE(i.product_title, 'Product enquiry'),
267
+ i.sender_name, i.sender_email, i.locale, i.ip_masked, i.user_agent,
268
+ NOT i.is_resolved, CASE WHEN i.is_resolved THEN 'closed' ELSE 'open' END,
269
+ i.created_at, i.created_at
270
+ FROM public.product_inquiries i
271
+ WHERE NOT EXISTS (SELECT 1 FROM public.message_threads t WHERE t.subject_id = i.id);
272
+
273
+ INSERT INTO public.thread_messages (thread_id, direction, body, email_delivered, ip_masked, created_at)
274
+ SELECT t.id, 'inbound', i.message, i.email_delivered, i.ip_masked, i.created_at
275
+ FROM public.product_inquiries i
276
+ JOIN public.message_threads t ON t.subject_id = i.id
277
+ WHERE NOT EXISTS (SELECT 1 FROM public.thread_messages m WHERE m.thread_id = t.id);
278
+
279
+ -- ---------------------------------------------------------------------------
280
+ -- 5. The form-block data migration.
281
+ -- Rewrites every stored form block: mints a form_key, moves recipient_email into
282
+ -- form_endpoints, snapshots the field manifest, and DELETES recipient_email from
283
+ -- the jsonb. Three shapes have to be handled, because a form nested inside a
284
+ -- section has no blocks row of its own — it lives in the section's content:
285
+ -- a) blocks.content where block_type = 'form'
286
+ -- b) blocks.content where block_type = 'section' (column_blocks, slides)
287
+ -- c) content_drafts.blocks / product_drafts.blocks (jsonb arrays of snapshots)
288
+ -- ---------------------------------------------------------------------------
289
+ CREATE OR REPLACE FUNCTION public.nb_migrate_form_columns(p_cols jsonb)
290
+ RETURNS jsonb LANGUAGE plpgsql VOLATILE SET search_path = '' AS $fn$
291
+ DECLARE v_col jsonb; v_blk jsonb; v_new_cols jsonb := '[]'::jsonb; v_new_col jsonb;
292
+ BEGIN
293
+ FOR v_col IN SELECT * FROM jsonb_array_elements(p_cols) LOOP
294
+ v_new_col := '[]'::jsonb;
295
+ FOR v_blk IN SELECT * FROM jsonb_array_elements(coalesce(v_col, '[]'::jsonb)) LOOP
296
+ v_new_col := v_new_col || jsonb_build_array(
297
+ v_blk || jsonb_build_object('content', public.nb_migrate_form_content(v_blk->'content')));
298
+ END LOOP;
299
+ v_new_cols := v_new_cols || jsonb_build_array(v_new_col);
300
+ END LOOP;
301
+ RETURN v_new_cols;
302
+ END;
303
+ $fn$;
304
+
305
+ CREATE OR REPLACE FUNCTION public.nb_migrate_form_content(p_content jsonb)
306
+ RETURNS jsonb LANGUAGE plpgsql VOLATILE SET search_path = '' AS $fn$
307
+ DECLARE
308
+ v_key uuid; v_email text; v_fields jsonb; v_slide jsonb; v_new_slides jsonb;
309
+ BEGIN
310
+ IF p_content IS NULL OR jsonb_typeof(p_content) <> 'object' THEN
311
+ RETURN p_content;
312
+ END IF;
313
+
314
+ -- Leaf: this object IS a form block's content.
315
+ IF (p_content ? 'recipient_email') AND (p_content ? 'fields') THEN
316
+ v_key := gen_random_uuid();
317
+ v_email := nullif(btrim(coalesce(p_content->>'recipient_email','')), '');
318
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
319
+ 'temp_id', f->>'temp_id', 'label', f->>'label', 'field_type', f->>'field_type')), '[]'::jsonb)
320
+ INTO v_fields
321
+ FROM jsonb_array_elements(coalesce(p_content->'fields', '[]'::jsonb)) f;
322
+ INSERT INTO public.form_endpoints (form_key, label, recipient_email, fields)
323
+ VALUES (v_key, 'Contact form', v_email, v_fields)
324
+ ON CONFLICT (form_key) DO NOTHING;
325
+ RETURN (p_content - 'recipient_email') || jsonb_build_object('form_key', v_key::text);
326
+ END IF;
327
+
328
+ -- Container: a section's slides, each with column_blocks.
329
+ IF (p_content ? 'slides') AND jsonb_typeof(p_content->'slides') = 'array' THEN
330
+ v_new_slides := '[]'::jsonb;
331
+ FOR v_slide IN SELECT * FROM jsonb_array_elements(p_content->'slides') LOOP
332
+ v_new_slides := v_new_slides || jsonb_build_array(
333
+ v_slide || jsonb_build_object('column_blocks',
334
+ public.nb_migrate_form_columns(coalesce(v_slide->'column_blocks','[]'::jsonb))));
335
+ END LOOP;
336
+ p_content := p_content || jsonb_build_object('slides', v_new_slides);
337
+ END IF;
338
+
339
+ -- Container: a standard section's column_blocks.
340
+ IF (p_content ? 'column_blocks') AND jsonb_typeof(p_content->'column_blocks') = 'array' THEN
341
+ p_content := p_content || jsonb_build_object('column_blocks',
342
+ public.nb_migrate_form_columns(p_content->'column_blocks'));
343
+ END IF;
344
+
345
+ RETURN p_content;
346
+ END;
347
+ $fn$;
348
+
349
+ -- The LIKE guard keeps this from rewriting (and bumping updated_at on) every block.
350
+ UPDATE public.blocks
351
+ SET content = public.nb_migrate_form_content(content)
352
+ WHERE content::text LIKE '%recipient_email%';
353
+
354
+ UPDATE public.content_drafts d
355
+ SET blocks = (SELECT coalesce(jsonb_agg(b || jsonb_build_object(
356
+ 'content', public.nb_migrate_form_content(b->'content'))), '[]'::jsonb)
357
+ FROM jsonb_array_elements(d.blocks) b)
358
+ WHERE d.blocks::text LIKE '%recipient_email%';
359
+
360
+ UPDATE public.product_drafts d
361
+ SET blocks = (SELECT coalesce(jsonb_agg(b || jsonb_build_object(
362
+ 'content', public.nb_migrate_form_content(b->'content'))), '[]'::jsonb)
363
+ FROM jsonb_array_elements(d.blocks) b)
364
+ WHERE d.blocks::text LIKE '%recipient_email%';
365
+
366
+ -- One-shot helpers. Dropping them keeps the public schema (and db:types) clean.
367
+ DROP FUNCTION IF EXISTS public.nb_migrate_form_content(jsonb);
368
+ DROP FUNCTION IF EXISTS public.nb_migrate_form_columns(jsonb);
369
+
370
+ -- ---------------------------------------------------------------------------
371
+ -- 6. Seeds. Thread-page copy is public-facing so it must be translatable; the
372
+ -- components pass an English literal as the fallback, so an install that never
373
+ -- runs this seed still renders correctly.
374
+ -- ---------------------------------------------------------------------------
375
+ INSERT INTO public.site_settings (key, value)
376
+ VALUES ('forms_contact', '{"contactEmail": ""}'::jsonb)
377
+ ON CONFLICT (key) DO NOTHING;
378
+
379
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
380
+ ('thread.heading', '{"en": "Your conversation", "fr": "Votre conversation"}', now(), now()),
381
+ ('thread.reply_label', '{"en": "Write a reply", "fr": "Écrire une réponse"}', now(), now()),
382
+ ('thread.send', '{"en": "Send reply", "fr": "Envoyer la réponse"}', now(), now()),
383
+ ('thread.sending', '{"en": "Sending...", "fr": "Envoi..."}', now(), now()),
384
+ ('thread.sent', '{"en": "Thanks - your reply has been sent.", "fr": "Merci - votre réponse a été envoyée."}', now(), now()),
385
+ ('thread.error', '{"en": "Sorry, your reply couldn''t be sent. Please try again in a moment.", "fr": "Désolé, votre réponse n''a pas pu être envoyée. Veuillez réessayer dans un instant."}', now(), now()),
386
+ ('thread.throttled', '{"en": "You''ve sent several replies already. Please wait a few minutes.", "fr": "Vous avez déjà envoyé plusieurs réponses. Veuillez patienter quelques minutes."}', now(), now()),
387
+ ('thread.closed', '{"en": "This conversation has been closed.", "fr": "Cette conversation est fermée."}', now(), now()),
388
+ ('thread.invalid', '{"en": "This link has expired or is no longer valid. If you still need help, please contact us again from our website.", "fr": "Ce lien a expiré ou n''est plus valide. Si vous avez encore besoin d''aide, contactez-nous de nouveau depuis notre site."}', now(), now()),
389
+ ('thread.you', '{"en": "You", "fr": "Vous"}', now(), now()),
390
+ ('forms.submission_stored', '{"en": "Thanks - your message has been received.", "fr": "Merci - votre message a bien été reçu."}', now(), now())
391
+ ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,86 @@
1
+ -- Staff replies on reviews and post comments, and the indexes cms_interactions never had.
2
+ --
3
+ -- WHY THIS IS A DIFFERENT SHAPE FROM MIGRATION 27, AND WHY IT NEEDS NO TOKEN.
4
+ -- `cms_interactions.user_id` is NOT NULL with a foreign key to `profiles`: every review
5
+ -- and comment already comes from a signed-in account with a reachable address, and the
6
+ -- content already renders publicly on /product/{slug} and /article/{slug}. A staff
7
+ -- answer there is PUBLISHED CONTENT plus moderation, not a private conversation.
8
+ -- Routing it through the tokenised thread page would hide a public reply behind a
9
+ -- secret link. So: one inbox in the CMS, two storage models underneath.
10
+ --
11
+ -- THE ONE CONSTRAINT THAT DICTATES THE MODELLING.
12
+ -- `check_rating_only_for_review` is an exhaustive OR over ('review','comment'):
13
+ -- (type='review' AND rating IS NOT NULL AND rating BETWEEN 1 AND 5)
14
+ -- OR (type='comment' AND rating IS NULL)
15
+ -- A type='review' row with a NULL rating is rejected, so a reply to a review cannot be
16
+ -- a 'review' row. Adding a 'reply' value to interaction_type would ALSO violate it —
17
+ -- the OR covers no third value — and PostgreSQL forbids using an enum value in the
18
+ -- transaction that added it, which is exactly one migration file.
19
+ --
20
+ -- THEREFORE a reply is a `type='comment'` row carrying the PARENT's target and a NULL
21
+ -- rating: a combination the existing constraints already accept, unchanged. The bonus
22
+ -- is decisive — `update_product_ratings()` aggregates only
23
+ -- WHERE product_id = ? AND type='review' AND status='approved'
24
+ -- so a reply can never move products.average_rating or products.total_reviews. The new
25
+ -- CHECK below pins that invariant in the schema instead of trusting the action to
26
+ -- remember it.
27
+ --
28
+ -- No new policies are needed. `cms_interactions_insert_policy` already admits an
29
+ -- ADMIN/WRITER self-insert with status='approved'
30
+ -- (auth.uid() = user_id AND (status='pending' OR role IN ('ADMIN','WRITER')))
31
+ -- which is precisely a published staff reply.
32
+ --
33
+ -- Forward-only and idempotent.
34
+
35
+ ALTER TABLE public.cms_interactions ADD COLUMN IF NOT EXISTS parent_id uuid;
36
+
37
+ COMMENT ON COLUMN public.cms_interactions.parent_id IS 'Set on a staff reply: points at the review or comment being answered. Replies are always type=comment with a NULL rating, and carry the parent''s product_id/post_id so check_product_or_post still holds.';
38
+
39
+ DO $rb$ BEGIN
40
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
41
+ WHERE conname = 'cms_interactions_parent_id_fkey'
42
+ AND conrelid = 'public.cms_interactions'::regclass) THEN
43
+ ALTER TABLE ONLY public.cms_interactions
44
+ ADD CONSTRAINT cms_interactions_parent_id_fkey FOREIGN KEY (parent_id)
45
+ REFERENCES public.cms_interactions(id) ON DELETE CASCADE;
46
+ END IF;
47
+ END $rb$;
48
+
49
+ -- One level only, never itself, no rating, always a comment. Keeps the reply
50
+ -- invisible to the ratings trigger and to the existing storefront review query.
51
+ DO $rb$ BEGIN
52
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
53
+ WHERE conname = 'cms_interactions_reply_check'
54
+ AND conrelid = 'public.cms_interactions'::regclass) THEN
55
+ ALTER TABLE public.cms_interactions
56
+ ADD CONSTRAINT cms_interactions_reply_check CHECK (
57
+ ((parent_id IS NULL) OR
58
+ ((parent_id <> id) AND (rating IS NULL) AND (type = 'comment'::public.interaction_type))));
59
+ END IF;
60
+ END $rb$;
61
+
62
+ -- Fetch every reply for a page of parents in one probe.
63
+ CREATE INDEX IF NOT EXISTS cms_interactions_parent_idx
64
+ ON public.cms_interactions USING btree (parent_id, created_at)
65
+ WHERE (parent_id IS NOT NULL);
66
+
67
+ -- cms_interactions has had ZERO secondary indexes since the baseline, while both
68
+ -- public renderers filter on exactly these predicates on every product and article
69
+ -- page. The inbox multiplies read volume on this table, so they go in now.
70
+ CREATE INDEX IF NOT EXISTS cms_interactions_product_type_status_idx
71
+ ON public.cms_interactions USING btree (product_id, type, status, created_at DESC)
72
+ WHERE (product_id IS NOT NULL);
73
+
74
+ CREATE INDEX IF NOT EXISTS cms_interactions_post_type_status_idx
75
+ ON public.cms_interactions USING btree (post_id, type, status, created_at DESC)
76
+ WHERE (post_id IS NOT NULL);
77
+
78
+ -- Inbox listing: newest top-level items, replies excluded.
79
+ CREATE INDEX IF NOT EXISTS cms_interactions_inbox_idx
80
+ ON public.cms_interactions USING btree (created_at DESC)
81
+ WHERE (parent_id IS NULL);
82
+
83
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
84
+ ('interactions.staff_reply', '{"en": "Reply from the team", "fr": "Réponse de l''équipe"}', now(), now()),
85
+ ('interactions.staff_badge', '{"en": "Staff", "fr": "Équipe"}', now(), now())
86
+ ON CONFLICT (key) DO NOTHING;
@@ -0,0 +1,52 @@
1
+ -- A contact form has no address of its own by default.
2
+ --
3
+ -- The starter content ships a contact page addressed to `contact@example.com`, and
4
+ -- migration 27 faithfully carried that placeholder into `form_endpoints`. Faithful was
5
+ -- the wrong call. `example.com` is reserved by RFC 2606 precisely so it can never be
6
+ -- registered, so the address is not merely unhelpful — it is guaranteed undeliverable,
7
+ -- while looking like a real setting to every layer downstream. The visitor is thanked,
8
+ -- the relay accepts the message, and nobody is ever notified. Nothing errors, so an
9
+ -- install can run that way indefinitely.
10
+ --
11
+ -- Since the messaging system arrived, a per-form address is not something an operator
12
+ -- needs to think about at all. Submissions are stored as threads and answered in
13
+ -- CMS → Messages; the notification address is a single site-wide setting, and a form
14
+ -- only carries its own address when someone deliberately wants that form routed
15
+ -- elsewhere (a careers form to HR, say).
16
+ --
17
+ -- So the default becomes NULL, meaning "use the site contact address", which resolves
18
+ -- to the address set in CMS → Messages and finally to the first admin's own login. An
19
+ -- install therefore reaches a real human out of the box without configuring anything.
20
+ --
21
+ -- The sandbox is unaffected: `resolveFormRecipient` overrides everything with
22
+ -- SANDBOX_CONTACT_EMAIL when NEXT_PUBLIC_IS_SANDBOX is set, so the hosted demo keeps
23
+ -- routing to the operator's own inbox without storing an address here.
24
+ --
25
+ -- Forward-only and idempotent.
26
+
27
+ -- Reserved domains from RFC 2606 / RFC 6761. Matching on the domain rather than the
28
+ -- exact seeded string also catches an operator who typed their own placeholder.
29
+ UPDATE public.form_endpoints
30
+ SET recipient_email = NULL
31
+ WHERE recipient_email IS NOT NULL
32
+ AND (
33
+ lower(recipient_email) LIKE '%@example.com'
34
+ OR lower(recipient_email) LIKE '%@example.org'
35
+ OR lower(recipient_email) LIKE '%@example.net'
36
+ OR lower(recipient_email) LIKE '%@example.edu'
37
+ OR lower(recipient_email) LIKE '%.example'
38
+ OR lower(recipient_email) LIKE '%.invalid'
39
+ OR lower(recipient_email) LIKE '%.test'
40
+ OR lower(recipient_email) LIKE '%.localhost'
41
+ OR lower(recipient_email) LIKE '%.local'
42
+ );
43
+
44
+ COMMENT ON COLUMN public.form_endpoints.recipient_email IS 'Per-form override. NULL means "use the site contact address" (CMS -> Messages, falling back to the first admin), which is the default and the usual case.';
45
+
46
+ -- Same reasoning for the site-wide rows: a placeholder there is worse than an empty
47
+ -- value, because an empty one falls through to the first admin and actually arrives.
48
+ UPDATE public.site_settings
49
+ SET value = jsonb_set(value, '{contactEmail}', '""'::jsonb)
50
+ WHERE key IN ('forms_contact', 'store_contact')
51
+ AND value ? 'contactEmail'
52
+ AND lower(value->>'contactEmail') LIKE '%@example.%';