create-nextblock 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.
Files changed (79) hide show
  1. package/package.json +50 -26
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/route.ts +14 -0
  12. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  13. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  14. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  15. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  16. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  17. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  18. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  19. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  20. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  21. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  22. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  23. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  24. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  25. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  26. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  27. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  28. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  29. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  30. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  31. package/templates/nextblock-template/app/layout.tsx +671 -667
  32. package/templates/nextblock-template/app/lib/seo.ts +319 -311
  33. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  34. package/templates/nextblock-template/app/providers.tsx +96 -96
  35. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  36. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  37. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  38. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  39. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  40. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  41. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  42. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  43. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  44. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  45. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  46. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  47. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  48. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  49. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  50. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  51. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  52. package/templates/nextblock-template/docs/05-DEVELOPER-GUIDE.md +25 -19
  53. package/templates/nextblock-template/docs/06-CLI-AND-SCAFFOLDING.md +1 -1
  54. package/templates/nextblock-template/docs/08-NEXTBLOCK-CORTEX-AI-ARCHITECTURE.md +2 -2
  55. package/templates/nextblock-template/docs/12-VERCEL-DEPLOYMENT.md +32 -9
  56. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  57. package/templates/nextblock-template/docs/README.md +42 -41
  58. package/templates/nextblock-template/docs/TECHNICAL_SPECIFICATION.md +540 -542
  59. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  60. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  61. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  62. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  63. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  64. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  65. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  66. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  67. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  68. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  69. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  70. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  71. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  72. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  73. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  74. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  75. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  76. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  77. package/templates/nextblock-template/lib/site-url.ts +102 -48
  78. package/templates/nextblock-template/package.json +14 -1
  79. package/templates/nextblock-template/public/assets/nextblock-banner.jpg +0 -0
@@ -7369,6 +7369,665 @@ END
7369
7369
  $body$;
7370
7370
 
7371
7371
 
7372
+ -- >>> FROM: 00000000000026_product_inquiries.sql <<<
7373
+ -- Purchase enquiries raised when the store cannot take payment.
7374
+ --
7375
+ -- A NextBlock store can be fully built — products, prices, images, pages — while its
7376
+ -- Stripe or Freemius credentials are still missing. Until this migration the only
7377
+ -- symptom was a shopper reaching checkout and receiving the payment provider's raw
7378
+ -- rejection ("Invalid API Key provided: sk_test_*ummy"), which tells them nothing and
7379
+ -- loses the sale outright.
7380
+ --
7381
+ -- The storefront now offers those shoppers an enquiry form in place of Add-to-Cart,
7382
+ -- and every submission lands here. The row is the product, not the email: SMTP is a
7383
+ -- separate piece of setup that the same half-configured store has usually also not
7384
+ -- done, so a notification that cannot be sent must never be the only record. The
7385
+ -- \`email_delivered\` flag records whether the owner was successfully notified; false
7386
+ -- means "read this in the CMS, nobody got a mail about it".
7387
+ --
7388
+ -- SECURITY POSTURE. Rows hold visitor-supplied PII (name, email, free text) plus a
7389
+ -- masked IP. There is deliberately NO anon policy of any kind: anonymous visitors
7390
+ -- neither read nor write this table directly. The public server action inserts with
7391
+ -- the service-role client after bot-protection and throttle checks, exactly as
7392
+ -- \`privacy_consent_logs\` does — that keeps the insert shape server-controlled and
7393
+ -- means a leaked anon key cannot enumerate or seed enquiries. ADMINs read; nobody
7394
+ -- else does, because these are sales leads and personal data.
7395
+ --
7396
+ -- \`product_id\` is a PLAIN uuid with NO foreign key, following site_script_revisions:
7397
+ -- an enquiry is evidence that someone wanted a product, and deleting the product
7398
+ -- should not delete or rewrite that evidence. \`product_slug\` and \`product_title\` are
7399
+ -- denormalised so a deleted product is still identifiable in the list.
7400
+ --
7401
+ -- Forward-only and idempotent.
7402
+
7403
+ CREATE TABLE IF NOT EXISTS public.product_inquiries (
7404
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
7405
+ -- No FK by design (see header). Null when the product was deleted after the fact.
7406
+ product_id uuid,
7407
+ product_slug text,
7408
+ product_title text,
7409
+ sender_name text NOT NULL,
7410
+ sender_email text NOT NULL,
7411
+ message text NOT NULL,
7412
+ -- Which language the visitor was browsing in, so the owner can reply in kind.
7413
+ locale text,
7414
+ ip_masked text,
7415
+ user_agent text,
7416
+ -- False when SMTP was unconfigured or the send failed: the CMS list is then the
7417
+ -- only place this enquiry exists.
7418
+ email_delivered boolean DEFAULT false NOT NULL,
7419
+ is_resolved boolean DEFAULT false NOT NULL,
7420
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
7421
+ CONSTRAINT product_inquiries_pkey PRIMARY KEY (id),
7422
+ CONSTRAINT product_inquiries_sender_name_not_blank CHECK ((char_length(btrim(sender_name)) > 0)),
7423
+ CONSTRAINT product_inquiries_sender_email_not_blank CHECK ((char_length(btrim(sender_email)) > 0)),
7424
+ CONSTRAINT product_inquiries_message_not_blank CHECK ((char_length(btrim(message)) > 0))
7425
+ );
7426
+
7427
+ 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.';
7428
+
7429
+ COMMENT ON COLUMN public.product_inquiries.product_id IS 'Plain uuid, no FK: an enquiry outlives the product it was about.';
7430
+
7431
+ 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.';
7432
+
7433
+ 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.';
7434
+
7435
+ -- Newest-first is the only listing order the CMS needs.
7436
+ CREATE INDEX IF NOT EXISTS product_inquiries_created_idx
7437
+ ON public.product_inquiries USING btree (created_at DESC);
7438
+
7439
+ -- Backs the throttle lookup in the public server action: count recent rows per IP.
7440
+ CREATE INDEX IF NOT EXISTS product_inquiries_ip_created_idx
7441
+ ON public.product_inquiries USING btree (ip_masked, created_at DESC);
7442
+
7443
+ -- Lets the CMS count outstanding enquiries without scanning resolved history.
7444
+ CREATE INDEX IF NOT EXISTS product_inquiries_unresolved_idx
7445
+ ON public.product_inquiries USING btree (created_at DESC)
7446
+ WHERE (is_resolved = false);
7447
+
7448
+ ALTER TABLE public.product_inquiries ENABLE ROW LEVEL SECURITY;
7449
+
7450
+ -- anon is deliberately absent: the public path goes through the service role.
7451
+ GRANT SELECT, UPDATE ON TABLE public.product_inquiries TO authenticated;
7452
+ GRANT ALL ON TABLE public.product_inquiries TO service_role;
7453
+
7454
+ DROP POLICY IF EXISTS product_inquiries_admin_read_policy ON public.product_inquiries;
7455
+ 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));
7456
+
7457
+ -- ADMINs may only flip the resolved flag; the enquiry content itself is a record.
7458
+ DROP POLICY IF EXISTS product_inquiries_admin_update_policy ON public.product_inquiries;
7459
+ 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));
7460
+
7461
+ DROP POLICY IF EXISTS product_inquiries_service_role_policy ON public.product_inquiries;
7462
+ CREATE POLICY product_inquiries_service_role_policy ON public.product_inquiries TO service_role USING (true) WITH CHECK (true);
7463
+
7464
+ -- Where enquiry notifications are sent. Kept in the PUBLIC settings row rather than the
7465
+ -- secret one because it is an address, not a credential — but it is never rendered to
7466
+ -- the storefront: the public form posts a product id and the server resolves the
7467
+ -- recipient. Empty string means "fall back", see resolveSellerContactEmail().
7468
+ INSERT INTO public.site_settings (key, value)
7469
+ VALUES ('store_contact', '{"contactEmail": ""}'::jsonb)
7470
+ ON CONFLICT (key) DO NOTHING;
7471
+
7472
+ -- Storefront copy for the enquiry flow. Public-facing, so it must be translatable;
7473
+ -- the components pass an English literal as the fallback, so an install that never
7474
+ -- runs this seed still renders correctly.
7475
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
7476
+ ('ecommerce.contact_seller', '{"en": "Contact the seller", "fr": "Contacter le vendeur"}', now(), now()),
7477
+ ('ecommerce.contact_seller_heading', '{"en": "Interested in this product?", "fr": "Ce produit vous intéresse ?"}', now(), now()),
7478
+ ('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()),
7479
+ ('ecommerce.contact_seller_name', '{"en": "Your name", "fr": "Votre nom"}', now(), now()),
7480
+ ('ecommerce.contact_seller_email', '{"en": "Your email", "fr": "Votre courriel"}', now(), now()),
7481
+ ('ecommerce.contact_seller_message', '{"en": "Message", "fr": "Message"}', now(), now()),
7482
+ ('ecommerce.contact_seller_send', '{"en": "Send message", "fr": "Envoyer le message"}', now(), now()),
7483
+ ('ecommerce.contact_seller_sending', '{"en": "Sending...", "fr": "Envoi..."}', now(), now()),
7484
+ ('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()),
7485
+ ('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()),
7486
+ ('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()),
7487
+ ('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()),
7488
+ ('ecommerce.not_available_for_purchase', '{"en": "Not available for online purchase", "fr": "Non disponible à l''achat en ligne"}', now(), now()),
7489
+ ('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())
7490
+ ON CONFLICT (key) DO NOTHING;
7491
+
7492
+
7493
+ -- >>> FROM: 00000000000027_message_threads.sql <<<
7494
+ -- Private conversations with anonymous visitors, and the end of the exposed form address.
7495
+ --
7496
+ -- Two problems, one shape.
7497
+ --
7498
+ -- FIRST: a contact-form block stores its destination address in the block's own
7499
+ -- content, and \`FormBlockRenderer\` is a "use client" component that receives that
7500
+ -- content wholesale. Everything crossing that boundary is serialized into the RSC
7501
+ -- payload, so the shop owner's inbox is published in the markup of every page
7502
+ -- carrying a form. \`form_endpoints\` moves the address server-side and leaves behind a
7503
+ -- \`form_key\` — an opaque handle that grants nothing and is safe to serialize.
7504
+ --
7505
+ -- SECOND: a visitor who sends a message has nowhere to receive an answer. They are
7506
+ -- anonymous — \`cms_interactions\` cannot hold them, because its \`user_id\` is NOT NULL
7507
+ -- with a foreign key to \`profiles\`. So this is a separate lane: \`message_threads\` plus
7508
+ -- \`thread_messages\`, reached by a tokenised link rather than an account.
7509
+ --
7510
+ -- WHY REVIEWS AND COMMENTS ARE NOT HERE. They are already public, already tied to a
7511
+ -- registered account, and a staff answer to them is published content, not a private
7512
+ -- reply. That lane stays in \`cms_interactions\` and is handled by migration 28. One
7513
+ -- inbox reads both; the storage stays honest about the difference.
7514
+ --
7515
+ -- SECURITY POSTURE. Rows hold visitor PII (name, email, free text) and a masked IP.
7516
+ -- There is NO anon grant and NO anon policy: the tokenised visitor page verifies the
7517
+ -- token in application code and then reads with the service role, the same posture the
7518
+ -- MCP token route takes against \`mcp_access_tokens\`. ADMINs read; nobody else does.
7519
+ --
7520
+ -- \`token_hash\` stores only a SHA-256 of the visitor's token. The plaintext exists long
7521
+ -- enough to be placed in one outbound email and is never written down. A token is
7522
+ -- minted on the FIRST ADMIN REPLY, never at submission — a store that receives a
7523
+ -- hundred enquiries and answers three has three live credentials, not a hundred.
7524
+ --
7525
+ -- \`source\` is a text column with a CHECK rather than an enum, deliberately.
7526
+ -- \`interaction_type\` in this same schema is the cautionary tale: a two-value enum
7527
+ -- guarded by an exhaustive CHECK, where adding a third value needs ALTER TYPE ... ADD
7528
+ -- VALUE — and PostgreSQL forbids using a value added in the transaction that added it,
7529
+ -- which is exactly one migration file. A CHECK is replaceable in one statement.
7530
+ --
7531
+ -- Forward-only and idempotent.
7532
+
7533
+ -- ---------------------------------------------------------------------------
7534
+ -- 1. form_endpoints — where a contact-form block's mail goes, and what its fields
7535
+ -- are called. \`fields\` is a SERVER-SIDE snapshot of the field manifest so the
7536
+ -- notification email renders labels the browser did not supply; the same rule
7537
+ -- the product-enquiry action follows when it looks the product title up itself.
7538
+ -- ---------------------------------------------------------------------------
7539
+ CREATE TABLE IF NOT EXISTS public.form_endpoints (
7540
+ form_key uuid NOT NULL,
7541
+ label text DEFAULT 'Contact form' NOT NULL,
7542
+ -- NULL/empty means "fall back to the resolver ladder", like store_contact.
7543
+ recipient_email text,
7544
+ fields jsonb DEFAULT '[]'::jsonb NOT NULL,
7545
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
7546
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
7547
+ CONSTRAINT form_endpoints_pkey PRIMARY KEY (form_key),
7548
+ CONSTRAINT form_endpoints_label_not_blank CHECK ((char_length(btrim(label)) > 0)),
7549
+ CONSTRAINT form_endpoints_fields_array CHECK ((jsonb_typeof(fields) = 'array'))
7550
+ );
7551
+
7552
+ 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.';
7553
+
7554
+ 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.';
7555
+
7556
+ 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.';
7557
+
7558
+ DROP TRIGGER IF EXISTS set_form_endpoints_updated_at ON public.form_endpoints;
7559
+ CREATE TRIGGER set_form_endpoints_updated_at BEFORE UPDATE ON public.form_endpoints
7560
+ FOR EACH ROW EXECUTE FUNCTION public.set_current_timestamp_updated_at();
7561
+
7562
+ ALTER TABLE public.form_endpoints ENABLE ROW LEVEL SECURITY;
7563
+
7564
+ -- anon deliberately absent: the public submit path goes through the service role.
7565
+ GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE public.form_endpoints TO authenticated;
7566
+ GRANT ALL ON TABLE public.form_endpoints TO service_role;
7567
+
7568
+ DROP POLICY IF EXISTS form_endpoints_editor_read_policy ON public.form_endpoints;
7569
+ 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])));
7570
+
7571
+ DROP POLICY IF EXISTS form_endpoints_admin_write_policy ON public.form_endpoints;
7572
+ 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));
7573
+
7574
+ DROP POLICY IF EXISTS form_endpoints_service_role_policy ON public.form_endpoints;
7575
+ CREATE POLICY form_endpoints_service_role_policy ON public.form_endpoints TO service_role USING (true) WITH CHECK (true);
7576
+
7577
+ -- ---------------------------------------------------------------------------
7578
+ -- 2. message_threads — the private-lane spine and the only home of a thread token.
7579
+ -- \`subject_id\` and \`form_key\` are PLAIN uuids with NO foreign key: a conversation
7580
+ -- outlives the product or the form block it started from.
7581
+ -- ---------------------------------------------------------------------------
7582
+ CREATE TABLE IF NOT EXISTS public.message_threads (
7583
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
7584
+ source text NOT NULL,
7585
+ -- product_inquiries.id when source = 'product_inquiry'.
7586
+ subject_id uuid,
7587
+ -- form_endpoints.form_key when source = 'contact_form'.
7588
+ form_key uuid,
7589
+ -- Denormalised so a deleted product or removed form block stays identifiable.
7590
+ subject_label text DEFAULT 'Message' NOT NULL,
7591
+ sender_name text,
7592
+ -- NULL when a contact form collected no email field. Such a thread can never be
7593
+ -- answered, and the CMS says so rather than failing silently at reply time.
7594
+ sender_email text,
7595
+ locale text,
7596
+ -- Submitted field map for a contact form: {temp_id: value}.
7597
+ fields jsonb DEFAULT '{}'::jsonb NOT NULL,
7598
+ status text DEFAULT 'open' NOT NULL,
7599
+ unread_for_admin boolean DEFAULT true NOT NULL,
7600
+ unread_for_visitor boolean DEFAULT false NOT NULL,
7601
+ -- SHA-256 hex of the visitor's token; NULL until the first admin reply.
7602
+ token_hash text,
7603
+ token_expires_at timestamp with time zone,
7604
+ token_revoked_at timestamp with time zone,
7605
+ token_last_used_at timestamp with time zone,
7606
+ last_message_at timestamp with time zone DEFAULT now() NOT NULL,
7607
+ ip_masked text,
7608
+ user_agent text,
7609
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
7610
+ updated_at timestamp with time zone DEFAULT now() NOT NULL,
7611
+ CONSTRAINT message_threads_pkey PRIMARY KEY (id),
7612
+ CONSTRAINT message_threads_token_hash_key UNIQUE (token_hash),
7613
+ CONSTRAINT message_threads_source_check
7614
+ CHECK ((source = ANY (ARRAY['product_inquiry'::text, 'contact_form'::text]))),
7615
+ CONSTRAINT message_threads_status_check
7616
+ CHECK ((status = ANY (ARRAY['open'::text, 'closed'::text]))),
7617
+ CONSTRAINT message_threads_subject_check CHECK (
7618
+ (((source = 'product_inquiry'::text) AND (subject_id IS NOT NULL)) OR
7619
+ ((source = 'contact_form'::text) AND (form_key IS NOT NULL)))),
7620
+ CONSTRAINT message_threads_fields_object CHECK ((jsonb_typeof(fields) = 'object'))
7621
+ );
7622
+
7623
+ 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.';
7624
+
7625
+ 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.';
7626
+
7627
+ 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.';
7628
+
7629
+ CREATE INDEX IF NOT EXISTS message_threads_last_message_idx
7630
+ ON public.message_threads USING btree (last_message_at DESC);
7631
+
7632
+ CREATE INDEX IF NOT EXISTS message_threads_source_last_idx
7633
+ ON public.message_threads USING btree (source, last_message_at DESC);
7634
+
7635
+ -- Backs the CMS nav unread badge without scanning read history.
7636
+ CREATE INDEX IF NOT EXISTS message_threads_unread_idx
7637
+ ON public.message_threads USING btree (last_message_at DESC)
7638
+ WHERE (unread_for_admin = true);
7639
+
7640
+ -- Idempotent backfill / dedupe of enquiry threads.
7641
+ CREATE INDEX IF NOT EXISTS message_threads_subject_idx
7642
+ ON public.message_threads USING btree (subject_id) WHERE (subject_id IS NOT NULL);
7643
+
7644
+ -- No separate token index: message_threads_token_hash_key is already the unique
7645
+ -- btree the /thread lookup probes.
7646
+
7647
+ DROP TRIGGER IF EXISTS set_message_threads_updated_at ON public.message_threads;
7648
+ CREATE TRIGGER set_message_threads_updated_at BEFORE UPDATE ON public.message_threads
7649
+ FOR EACH ROW EXECUTE FUNCTION public.set_current_timestamp_updated_at();
7650
+
7651
+ ALTER TABLE public.message_threads ENABLE ROW LEVEL SECURITY;
7652
+
7653
+ GRANT SELECT, UPDATE ON TABLE public.message_threads TO authenticated;
7654
+ GRANT ALL ON TABLE public.message_threads TO service_role;
7655
+
7656
+ DROP POLICY IF EXISTS message_threads_admin_read_policy ON public.message_threads;
7657
+ 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));
7658
+
7659
+ DROP POLICY IF EXISTS message_threads_admin_update_policy ON public.message_threads;
7660
+ 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));
7661
+
7662
+ DROP POLICY IF EXISTS message_threads_service_role_policy ON public.message_threads;
7663
+ CREATE POLICY message_threads_service_role_policy ON public.message_threads TO service_role USING (true) WITH CHECK (true);
7664
+
7665
+ -- ---------------------------------------------------------------------------
7666
+ -- 3. thread_messages — one turn of a private conversation.
7667
+ -- ---------------------------------------------------------------------------
7668
+ CREATE TABLE IF NOT EXISTS public.thread_messages (
7669
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
7670
+ thread_id uuid NOT NULL,
7671
+ direction text NOT NULL,
7672
+ body text NOT NULL,
7673
+ -- profiles.id for an outbound reply. No FK: a departing admin must not take the
7674
+ -- conversation with them.
7675
+ author_id uuid,
7676
+ author_name text,
7677
+ -- False when SMTP was unconfigured or the send failed. sendEmail() throws when
7678
+ -- unconfigured, so this row - not the mail - is the record.
7679
+ email_delivered boolean DEFAULT false NOT NULL,
7680
+ email_error text,
7681
+ ip_masked text,
7682
+ created_at timestamp with time zone DEFAULT now() NOT NULL,
7683
+ CONSTRAINT thread_messages_pkey PRIMARY KEY (id),
7684
+ CONSTRAINT thread_messages_direction_check
7685
+ CHECK ((direction = ANY (ARRAY['inbound'::text, 'outbound'::text]))),
7686
+ CONSTRAINT thread_messages_body_not_blank CHECK ((char_length(btrim(body)) > 0))
7687
+ );
7688
+
7689
+ COMMENT ON TABLE public.thread_messages IS 'Turns of a private conversation. Content is append-only; only the delivery flags may change after insert.';
7690
+
7691
+ -- A real foreign key here, unlike the outward pointers above: a message has no
7692
+ -- meaning without its thread.
7693
+ DO $rb$ BEGIN
7694
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
7695
+ WHERE conname = 'thread_messages_thread_id_fkey'
7696
+ AND conrelid = 'public.thread_messages'::regclass) THEN
7697
+ ALTER TABLE ONLY public.thread_messages
7698
+ ADD CONSTRAINT thread_messages_thread_id_fkey FOREIGN KEY (thread_id)
7699
+ REFERENCES public.message_threads(id) ON DELETE CASCADE;
7700
+ END IF;
7701
+ END $rb$;
7702
+
7703
+ CREATE INDEX IF NOT EXISTS thread_messages_thread_created_idx
7704
+ ON public.thread_messages USING btree (thread_id, created_at);
7705
+
7706
+ -- Backs the per-IP reply throttle on the public thread page.
7707
+ CREATE INDEX IF NOT EXISTS thread_messages_ip_created_idx
7708
+ ON public.thread_messages USING btree (ip_masked, created_at DESC);
7709
+
7710
+ -- Message TEXT is append-only — not the whole row, because email_delivered has to be
7711
+ -- settable after the send completes. The trigger blocks rewrites of the load-bearing
7712
+ -- columns only, and it binds the service role too, which otherwise bypasses RLS.
7713
+ CREATE OR REPLACE FUNCTION public.prevent_thread_message_rewrite() RETURNS trigger
7714
+ LANGUAGE plpgsql SET search_path = '' AS $$
7715
+ BEGIN
7716
+ IF TG_OP = 'DELETE' THEN
7717
+ RAISE EXCEPTION 'thread_messages is append-only; DELETE is not permitted'
7718
+ USING ERRCODE = 'restrict_violation';
7719
+ END IF;
7720
+ IF NEW.body IS DISTINCT FROM OLD.body
7721
+ OR NEW.direction IS DISTINCT FROM OLD.direction
7722
+ OR NEW.thread_id IS DISTINCT FROM OLD.thread_id
7723
+ OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN
7724
+ RAISE EXCEPTION 'thread_messages content is append-only; only delivery flags may change'
7725
+ USING ERRCODE = 'restrict_violation';
7726
+ END IF;
7727
+ RETURN NEW;
7728
+ END;
7729
+ $$;
7730
+
7731
+ DROP TRIGGER IF EXISTS trg_thread_messages_append_only ON public.thread_messages;
7732
+ CREATE TRIGGER trg_thread_messages_append_only BEFORE UPDATE OR DELETE ON public.thread_messages
7733
+ FOR EACH ROW EXECUTE FUNCTION public.prevent_thread_message_rewrite();
7734
+
7735
+ -- NB: the ON DELETE CASCADE above fires this trigger, so deleting a thread is
7736
+ -- impossible by design. "Delete" in the CMS means status='closed' plus a revoked
7737
+ -- token, and the UI says so.
7738
+
7739
+ ALTER TABLE public.thread_messages ENABLE ROW LEVEL SECURITY;
7740
+
7741
+ GRANT SELECT ON TABLE public.thread_messages TO authenticated;
7742
+ GRANT ALL ON TABLE public.thread_messages TO service_role;
7743
+
7744
+ DROP POLICY IF EXISTS thread_messages_admin_read_policy ON public.thread_messages;
7745
+ 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));
7746
+
7747
+ DROP POLICY IF EXISTS thread_messages_service_role_policy ON public.thread_messages;
7748
+ CREATE POLICY thread_messages_service_role_policy ON public.thread_messages TO service_role USING (true) WITH CHECK (true);
7749
+
7750
+ -- ---------------------------------------------------------------------------
7751
+ -- 4. Backfill: every existing enquiry becomes a thread whose first inbound turn is
7752
+ -- the original message. product_inquiries is KEPT and kept written — it is the
7753
+ -- enquiry's own record and owns the ip_masked the submission throttle counts.
7754
+ -- The thread is a conversation ABOUT the enquiry, not a replacement for it.
7755
+ -- ---------------------------------------------------------------------------
7756
+ INSERT INTO public.message_threads
7757
+ (source, subject_id, subject_label, sender_name, sender_email, locale,
7758
+ ip_masked, user_agent, unread_for_admin, status, last_message_at, created_at)
7759
+ SELECT 'product_inquiry', i.id, COALESCE(i.product_title, 'Product enquiry'),
7760
+ i.sender_name, i.sender_email, i.locale, i.ip_masked, i.user_agent,
7761
+ NOT i.is_resolved, CASE WHEN i.is_resolved THEN 'closed' ELSE 'open' END,
7762
+ i.created_at, i.created_at
7763
+ FROM public.product_inquiries i
7764
+ WHERE NOT EXISTS (SELECT 1 FROM public.message_threads t WHERE t.subject_id = i.id);
7765
+
7766
+ INSERT INTO public.thread_messages (thread_id, direction, body, email_delivered, ip_masked, created_at)
7767
+ SELECT t.id, 'inbound', i.message, i.email_delivered, i.ip_masked, i.created_at
7768
+ FROM public.product_inquiries i
7769
+ JOIN public.message_threads t ON t.subject_id = i.id
7770
+ WHERE NOT EXISTS (SELECT 1 FROM public.thread_messages m WHERE m.thread_id = t.id);
7771
+
7772
+ -- ---------------------------------------------------------------------------
7773
+ -- 5. The form-block data migration.
7774
+ -- Rewrites every stored form block: mints a form_key, moves recipient_email into
7775
+ -- form_endpoints, snapshots the field manifest, and DELETES recipient_email from
7776
+ -- the jsonb. Three shapes have to be handled, because a form nested inside a
7777
+ -- section has no blocks row of its own — it lives in the section's content:
7778
+ -- a) blocks.content where block_type = 'form'
7779
+ -- b) blocks.content where block_type = 'section' (column_blocks, slides)
7780
+ -- c) content_drafts.blocks / product_drafts.blocks (jsonb arrays of snapshots)
7781
+ -- ---------------------------------------------------------------------------
7782
+ CREATE OR REPLACE FUNCTION public.nb_migrate_form_columns(p_cols jsonb)
7783
+ RETURNS jsonb LANGUAGE plpgsql VOLATILE SET search_path = '' AS $fn$
7784
+ DECLARE v_col jsonb; v_blk jsonb; v_new_cols jsonb := '[]'::jsonb; v_new_col jsonb;
7785
+ BEGIN
7786
+ FOR v_col IN SELECT * FROM jsonb_array_elements(p_cols) LOOP
7787
+ v_new_col := '[]'::jsonb;
7788
+ FOR v_blk IN SELECT * FROM jsonb_array_elements(coalesce(v_col, '[]'::jsonb)) LOOP
7789
+ v_new_col := v_new_col || jsonb_build_array(
7790
+ v_blk || jsonb_build_object('content', public.nb_migrate_form_content(v_blk->'content')));
7791
+ END LOOP;
7792
+ v_new_cols := v_new_cols || jsonb_build_array(v_new_col);
7793
+ END LOOP;
7794
+ RETURN v_new_cols;
7795
+ END;
7796
+ $fn$;
7797
+
7798
+ CREATE OR REPLACE FUNCTION public.nb_migrate_form_content(p_content jsonb)
7799
+ RETURNS jsonb LANGUAGE plpgsql VOLATILE SET search_path = '' AS $fn$
7800
+ DECLARE
7801
+ v_key uuid; v_email text; v_fields jsonb; v_slide jsonb; v_new_slides jsonb;
7802
+ BEGIN
7803
+ IF p_content IS NULL OR jsonb_typeof(p_content) <> 'object' THEN
7804
+ RETURN p_content;
7805
+ END IF;
7806
+
7807
+ -- Leaf: this object IS a form block's content.
7808
+ IF (p_content ? 'recipient_email') AND (p_content ? 'fields') THEN
7809
+ v_key := gen_random_uuid();
7810
+ v_email := nullif(btrim(coalesce(p_content->>'recipient_email','')), '');
7811
+ SELECT coalesce(jsonb_agg(jsonb_build_object(
7812
+ 'temp_id', f->>'temp_id', 'label', f->>'label', 'field_type', f->>'field_type')), '[]'::jsonb)
7813
+ INTO v_fields
7814
+ FROM jsonb_array_elements(coalesce(p_content->'fields', '[]'::jsonb)) f;
7815
+ INSERT INTO public.form_endpoints (form_key, label, recipient_email, fields)
7816
+ VALUES (v_key, 'Contact form', v_email, v_fields)
7817
+ ON CONFLICT (form_key) DO NOTHING;
7818
+ RETURN (p_content - 'recipient_email') || jsonb_build_object('form_key', v_key::text);
7819
+ END IF;
7820
+
7821
+ -- Container: a section's slides, each with column_blocks.
7822
+ IF (p_content ? 'slides') AND jsonb_typeof(p_content->'slides') = 'array' THEN
7823
+ v_new_slides := '[]'::jsonb;
7824
+ FOR v_slide IN SELECT * FROM jsonb_array_elements(p_content->'slides') LOOP
7825
+ v_new_slides := v_new_slides || jsonb_build_array(
7826
+ v_slide || jsonb_build_object('column_blocks',
7827
+ public.nb_migrate_form_columns(coalesce(v_slide->'column_blocks','[]'::jsonb))));
7828
+ END LOOP;
7829
+ p_content := p_content || jsonb_build_object('slides', v_new_slides);
7830
+ END IF;
7831
+
7832
+ -- Container: a standard section's column_blocks.
7833
+ IF (p_content ? 'column_blocks') AND jsonb_typeof(p_content->'column_blocks') = 'array' THEN
7834
+ p_content := p_content || jsonb_build_object('column_blocks',
7835
+ public.nb_migrate_form_columns(p_content->'column_blocks'));
7836
+ END IF;
7837
+
7838
+ RETURN p_content;
7839
+ END;
7840
+ $fn$;
7841
+
7842
+ -- The LIKE guard keeps this from rewriting (and bumping updated_at on) every block.
7843
+ UPDATE public.blocks
7844
+ SET content = public.nb_migrate_form_content(content)
7845
+ WHERE content::text LIKE '%recipient_email%';
7846
+
7847
+ UPDATE public.content_drafts d
7848
+ SET blocks = (SELECT coalesce(jsonb_agg(b || jsonb_build_object(
7849
+ 'content', public.nb_migrate_form_content(b->'content'))), '[]'::jsonb)
7850
+ FROM jsonb_array_elements(d.blocks) b)
7851
+ WHERE d.blocks::text LIKE '%recipient_email%';
7852
+
7853
+ UPDATE public.product_drafts d
7854
+ SET blocks = (SELECT coalesce(jsonb_agg(b || jsonb_build_object(
7855
+ 'content', public.nb_migrate_form_content(b->'content'))), '[]'::jsonb)
7856
+ FROM jsonb_array_elements(d.blocks) b)
7857
+ WHERE d.blocks::text LIKE '%recipient_email%';
7858
+
7859
+ -- One-shot helpers. Dropping them keeps the public schema (and db:types) clean.
7860
+ DROP FUNCTION IF EXISTS public.nb_migrate_form_content(jsonb);
7861
+ DROP FUNCTION IF EXISTS public.nb_migrate_form_columns(jsonb);
7862
+
7863
+ -- ---------------------------------------------------------------------------
7864
+ -- 6. Seeds. Thread-page copy is public-facing so it must be translatable; the
7865
+ -- components pass an English literal as the fallback, so an install that never
7866
+ -- runs this seed still renders correctly.
7867
+ -- ---------------------------------------------------------------------------
7868
+ INSERT INTO public.site_settings (key, value)
7869
+ VALUES ('forms_contact', '{"contactEmail": ""}'::jsonb)
7870
+ ON CONFLICT (key) DO NOTHING;
7871
+
7872
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
7873
+ ('thread.heading', '{"en": "Your conversation", "fr": "Votre conversation"}', now(), now()),
7874
+ ('thread.reply_label', '{"en": "Write a reply", "fr": "Écrire une réponse"}', now(), now()),
7875
+ ('thread.send', '{"en": "Send reply", "fr": "Envoyer la réponse"}', now(), now()),
7876
+ ('thread.sending', '{"en": "Sending...", "fr": "Envoi..."}', now(), now()),
7877
+ ('thread.sent', '{"en": "Thanks - your reply has been sent.", "fr": "Merci - votre réponse a été envoyée."}', now(), now()),
7878
+ ('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()),
7879
+ ('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()),
7880
+ ('thread.closed', '{"en": "This conversation has been closed.", "fr": "Cette conversation est fermée."}', now(), now()),
7881
+ ('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()),
7882
+ ('thread.you', '{"en": "You", "fr": "Vous"}', now(), now()),
7883
+ ('forms.submission_stored', '{"en": "Thanks - your message has been received.", "fr": "Merci - votre message a bien été reçu."}', now(), now())
7884
+ ON CONFLICT (key) DO NOTHING;
7885
+
7886
+
7887
+ -- >>> FROM: 00000000000028_interaction_replies.sql <<<
7888
+ -- Staff replies on reviews and post comments, and the indexes cms_interactions never had.
7889
+ --
7890
+ -- WHY THIS IS A DIFFERENT SHAPE FROM MIGRATION 27, AND WHY IT NEEDS NO TOKEN.
7891
+ -- \`cms_interactions.user_id\` is NOT NULL with a foreign key to \`profiles\`: every review
7892
+ -- and comment already comes from a signed-in account with a reachable address, and the
7893
+ -- content already renders publicly on /product/{slug} and /article/{slug}. A staff
7894
+ -- answer there is PUBLISHED CONTENT plus moderation, not a private conversation.
7895
+ -- Routing it through the tokenised thread page would hide a public reply behind a
7896
+ -- secret link. So: one inbox in the CMS, two storage models underneath.
7897
+ --
7898
+ -- THE ONE CONSTRAINT THAT DICTATES THE MODELLING.
7899
+ -- \`check_rating_only_for_review\` is an exhaustive OR over ('review','comment'):
7900
+ -- (type='review' AND rating IS NOT NULL AND rating BETWEEN 1 AND 5)
7901
+ -- OR (type='comment' AND rating IS NULL)
7902
+ -- A type='review' row with a NULL rating is rejected, so a reply to a review cannot be
7903
+ -- a 'review' row. Adding a 'reply' value to interaction_type would ALSO violate it —
7904
+ -- the OR covers no third value — and PostgreSQL forbids using an enum value in the
7905
+ -- transaction that added it, which is exactly one migration file.
7906
+ --
7907
+ -- THEREFORE a reply is a \`type='comment'\` row carrying the PARENT's target and a NULL
7908
+ -- rating: a combination the existing constraints already accept, unchanged. The bonus
7909
+ -- is decisive — \`update_product_ratings()\` aggregates only
7910
+ -- WHERE product_id = ? AND type='review' AND status='approved'
7911
+ -- so a reply can never move products.average_rating or products.total_reviews. The new
7912
+ -- CHECK below pins that invariant in the schema instead of trusting the action to
7913
+ -- remember it.
7914
+ --
7915
+ -- No new policies are needed. \`cms_interactions_insert_policy\` already admits an
7916
+ -- ADMIN/WRITER self-insert with status='approved'
7917
+ -- (auth.uid() = user_id AND (status='pending' OR role IN ('ADMIN','WRITER')))
7918
+ -- which is precisely a published staff reply.
7919
+ --
7920
+ -- Forward-only and idempotent.
7921
+
7922
+ ALTER TABLE public.cms_interactions ADD COLUMN IF NOT EXISTS parent_id uuid;
7923
+
7924
+ 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.';
7925
+
7926
+ DO $rb$ BEGIN
7927
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
7928
+ WHERE conname = 'cms_interactions_parent_id_fkey'
7929
+ AND conrelid = 'public.cms_interactions'::regclass) THEN
7930
+ ALTER TABLE ONLY public.cms_interactions
7931
+ ADD CONSTRAINT cms_interactions_parent_id_fkey FOREIGN KEY (parent_id)
7932
+ REFERENCES public.cms_interactions(id) ON DELETE CASCADE;
7933
+ END IF;
7934
+ END $rb$;
7935
+
7936
+ -- One level only, never itself, no rating, always a comment. Keeps the reply
7937
+ -- invisible to the ratings trigger and to the existing storefront review query.
7938
+ DO $rb$ BEGIN
7939
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint
7940
+ WHERE conname = 'cms_interactions_reply_check'
7941
+ AND conrelid = 'public.cms_interactions'::regclass) THEN
7942
+ ALTER TABLE public.cms_interactions
7943
+ ADD CONSTRAINT cms_interactions_reply_check CHECK (
7944
+ ((parent_id IS NULL) OR
7945
+ ((parent_id <> id) AND (rating IS NULL) AND (type = 'comment'::public.interaction_type))));
7946
+ END IF;
7947
+ END $rb$;
7948
+
7949
+ -- Fetch every reply for a page of parents in one probe.
7950
+ CREATE INDEX IF NOT EXISTS cms_interactions_parent_idx
7951
+ ON public.cms_interactions USING btree (parent_id, created_at)
7952
+ WHERE (parent_id IS NOT NULL);
7953
+
7954
+ -- cms_interactions has had ZERO secondary indexes since the baseline, while both
7955
+ -- public renderers filter on exactly these predicates on every product and article
7956
+ -- page. The inbox multiplies read volume on this table, so they go in now.
7957
+ CREATE INDEX IF NOT EXISTS cms_interactions_product_type_status_idx
7958
+ ON public.cms_interactions USING btree (product_id, type, status, created_at DESC)
7959
+ WHERE (product_id IS NOT NULL);
7960
+
7961
+ CREATE INDEX IF NOT EXISTS cms_interactions_post_type_status_idx
7962
+ ON public.cms_interactions USING btree (post_id, type, status, created_at DESC)
7963
+ WHERE (post_id IS NOT NULL);
7964
+
7965
+ -- Inbox listing: newest top-level items, replies excluded.
7966
+ CREATE INDEX IF NOT EXISTS cms_interactions_inbox_idx
7967
+ ON public.cms_interactions USING btree (created_at DESC)
7968
+ WHERE (parent_id IS NULL);
7969
+
7970
+ INSERT INTO public.translations (key, translations, created_at, updated_at) VALUES
7971
+ ('interactions.staff_reply', '{"en": "Reply from the team", "fr": "Réponse de l''équipe"}', now(), now()),
7972
+ ('interactions.staff_badge', '{"en": "Staff", "fr": "Équipe"}', now(), now())
7973
+ ON CONFLICT (key) DO NOTHING;
7974
+
7975
+
7976
+ -- >>> FROM: 00000000000029_form_endpoints_default_empty.sql <<<
7977
+ -- A contact form has no address of its own by default.
7978
+ --
7979
+ -- The starter content ships a contact page addressed to \`contact@example.com\`, and
7980
+ -- migration 27 faithfully carried that placeholder into \`form_endpoints\`. Faithful was
7981
+ -- the wrong call. \`example.com\` is reserved by RFC 2606 precisely so it can never be
7982
+ -- registered, so the address is not merely unhelpful — it is guaranteed undeliverable,
7983
+ -- while looking like a real setting to every layer downstream. The visitor is thanked,
7984
+ -- the relay accepts the message, and nobody is ever notified. Nothing errors, so an
7985
+ -- install can run that way indefinitely.
7986
+ --
7987
+ -- Since the messaging system arrived, a per-form address is not something an operator
7988
+ -- needs to think about at all. Submissions are stored as threads and answered in
7989
+ -- CMS → Messages; the notification address is a single site-wide setting, and a form
7990
+ -- only carries its own address when someone deliberately wants that form routed
7991
+ -- elsewhere (a careers form to HR, say).
7992
+ --
7993
+ -- So the default becomes NULL, meaning "use the site contact address", which resolves
7994
+ -- to the address set in CMS → Messages and finally to the first admin's own login. An
7995
+ -- install therefore reaches a real human out of the box without configuring anything.
7996
+ --
7997
+ -- The sandbox is unaffected: \`resolveFormRecipient\` overrides everything with
7998
+ -- SANDBOX_CONTACT_EMAIL when NEXT_PUBLIC_IS_SANDBOX is set, so the hosted demo keeps
7999
+ -- routing to the operator's own inbox without storing an address here.
8000
+ --
8001
+ -- Forward-only and idempotent.
8002
+
8003
+ -- Reserved domains from RFC 2606 / RFC 6761. Matching on the domain rather than the
8004
+ -- exact seeded string also catches an operator who typed their own placeholder.
8005
+ UPDATE public.form_endpoints
8006
+ SET recipient_email = NULL
8007
+ WHERE recipient_email IS NOT NULL
8008
+ AND (
8009
+ lower(recipient_email) LIKE '%@example.com'
8010
+ OR lower(recipient_email) LIKE '%@example.org'
8011
+ OR lower(recipient_email) LIKE '%@example.net'
8012
+ OR lower(recipient_email) LIKE '%@example.edu'
8013
+ OR lower(recipient_email) LIKE '%.example'
8014
+ OR lower(recipient_email) LIKE '%.invalid'
8015
+ OR lower(recipient_email) LIKE '%.test'
8016
+ OR lower(recipient_email) LIKE '%.localhost'
8017
+ OR lower(recipient_email) LIKE '%.local'
8018
+ );
8019
+
8020
+ 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.';
8021
+
8022
+ -- Same reasoning for the site-wide rows: a placeholder there is worse than an empty
8023
+ -- value, because an empty one falls through to the first admin and actually arrives.
8024
+ UPDATE public.site_settings
8025
+ SET value = jsonb_set(value, '{contactEmail}', '""'::jsonb)
8026
+ WHERE key IN ('forms_contact', 'store_contact')
8027
+ AND value ? 'contactEmail'
8028
+ AND lower(value->>'contactEmail') LIKE '%@example.%';
8029
+
8030
+
7372
8031
  -- Step D: Record the applied migrations in history (truncated in Step B) so
7373
8032
  -- \`npm run db:migrate:check\` reports up to date instead of listing every file as pending.
7374
8033
  INSERT INTO supabase_migrations.schema_migrations (version, name) VALUES
@@ -7397,7 +8056,11 @@ $body$;
7397
8056
  ('00000000000022', 'updating_article_accuracy'),
7398
8057
  ('00000000000023', 'updating_article_layout_not_host'),
7399
8058
  ('00000000000024', 'updating_article_newline_fix'),
7400
- ('00000000000025', 'rebrand_nextblock_dev')
8059
+ ('00000000000025', 'rebrand_nextblock_dev'),
8060
+ ('00000000000026', 'product_inquiries'),
8061
+ ('00000000000027', 'message_threads'),
8062
+ ('00000000000028', 'interaction_replies'),
8063
+ ('00000000000029', 'form_endpoints_default_empty')
7401
8064
  ON CONFLICT (version) DO NOTHING;
7402
8065
 
7403
8066
  -- Step E: Anchor preserved profiles