-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsupabase_schema.sql
More file actions
2849 lines (2573 loc) · 96.1 KB
/
Copy pathsupabase_schema.sql
File metadata and controls
2849 lines (2573 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Supabase SQL Migration
-- 1. Tables
CREATE TABLE IF NOT EXISTS public.events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
slug TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
description TEXT,
public_summary TEXT,
location_text TEXT,
public_location_text TEXT,
google_maps_url TEXT,
starts_at TIMESTAMPTZ NOT NULL,
timezone TEXT NOT NULL DEFAULT 'Asia/Ho_Chi_Minh',
duration_minutes INTEGER NOT NULL DEFAULT 60 CHECK (duration_minutes >= 15 AND duration_minutes <= 360 AND duration_minutes % 15 = 0),
ends_at TIMESTAMPTZ,
capacity INTEGER NOT NULL,
host_user_id UUID REFERENCES auth.users(id),
host_name TEXT,
host_contact_text TEXT,
show_host_publicly BOOLEAN DEFAULT false,
access_code TEXT DEFAULT gen_random_uuid()::text,
visibility TEXT CHECK (visibility IN ('public', 'semi_public', 'private')) DEFAULT 'semi_public',
allow_waitlist BOOLEAN DEFAULT true,
require_host_approval_for_join BOOLEAN NOT NULL DEFAULT false,
require_guest_email_for_join BOOLEAN NOT NULL DEFAULT false,
is_public BOOLEAN DEFAULT false,
public_discovery_enabled BOOLEAN NOT NULL DEFAULT false,
moderation_status TEXT NOT NULL DEFAULT 'not_required' CHECK (moderation_status IN ('not_required', 'pending', 'approved', 'limited', 'review', 'blocked', 'error')),
moderation_risk_level TEXT CHECK (moderation_risk_level IS NULL OR moderation_risk_level IN ('low', 'medium', 'high')),
moderation_action TEXT CHECK (moderation_action IS NULL OR moderation_action IN ('allow', 'limit_visibility', 'require_review', 'block')),
moderation_confidence NUMERIC(4,3),
moderation_reasons TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
moderation_input_hash TEXT,
moderated_at TIMESTAMPTZ,
moderation_archived_at TIMESTAMPTZ,
moderation_override TEXT CHECK (moderation_override IS NULL OR moderation_override IN ('force_visible', 'force_limited', 'hide', 'mark_safe', 'mark_spam')),
status TEXT CHECK (status IN ('scheduled', 'cancelled', 'completed')) DEFAULT 'scheduled',
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.event_attendees (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID REFERENCES public.events(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
guest_name TEXT NOT NULL,
guest_email TEXT NOT NULL,
status TEXT CHECK (status IN ('confirmed', 'waitlist', 'pending_approval', 'cancelled')) NOT NULL,
joined_at TIMESTAMPTZ DEFAULT now(),
promoted_at TIMESTAMPTZ,
cancelled_at TIMESTAMPTZ,
UNIQUE(event_id, guest_email)
);
CREATE TABLE IF NOT EXISTS public.event_hosts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES public.events(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
added_by_user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(event_id, user_id)
);
CREATE TABLE IF NOT EXISTS public.event_waitlist_positions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID REFERENCES public.events(id) ON DELETE CASCADE,
attendee_id UUID REFERENCES public.event_attendees(id) ON DELETE CASCADE,
position INTEGER NOT NULL,
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE(event_id, attendee_id),
UNIQUE(event_id, position)
);
CREATE TABLE IF NOT EXISTS public.event_access_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES public.events(id) ON DELETE CASCADE,
requester_attendee_profile_id UUID REFERENCES public.attendee_profiles(id) ON DELETE SET NULL,
requester_name TEXT NOT NULL,
requester_whatsapp TEXT NOT NULL,
requester_note TEXT,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'declined', 'contacted')),
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS event_access_requests_requester_attendee_profile_id_idx
ON public.event_access_requests (requester_attendee_profile_id);
CREATE TABLE IF NOT EXISTS public.event_join_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES public.events(id) ON DELETE CASCADE,
user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
attendee_profile_id UUID REFERENCES public.attendee_profiles(id) ON DELETE SET NULL,
guest_name TEXT NOT NULL,
guest_email TEXT NOT NULL,
request_note TEXT,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'cancelled')),
reviewed_by_user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
reviewed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS event_join_requests_event_id_created_at_idx
ON public.event_join_requests (event_id, created_at DESC);
CREATE INDEX IF NOT EXISTS event_join_requests_event_id_status_idx
ON public.event_join_requests (event_id, status);
CREATE INDEX IF NOT EXISTS event_join_requests_event_id_profile_idx
ON public.event_join_requests (event_id, attendee_profile_id);
CREATE INDEX IF NOT EXISTS event_join_requests_event_id_guest_email_lower_idx
ON public.event_join_requests (event_id, lower(guest_email));
CREATE UNIQUE INDEX IF NOT EXISTS event_join_requests_pending_profile_uidx
ON public.event_join_requests (event_id, attendee_profile_id)
WHERE attendee_profile_id IS NOT NULL
AND status = 'pending';
CREATE UNIQUE INDEX IF NOT EXISTS event_join_requests_pending_guest_email_uidx
ON public.event_join_requests (event_id, lower(guest_email))
WHERE attendee_profile_id IS NULL
AND status = 'pending';
CREATE TABLE IF NOT EXISTS public.moderator_public_identities (
user_id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
public_handle TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ DEFAULT now()
);
ALTER TABLE public.moderator_public_identities ENABLE ROW LEVEL SECURITY;
CREATE TABLE IF NOT EXISTS public.public_moderation_log_entries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
target_type TEXT NOT NULL DEFAULT 'activity' CHECK (target_type IN ('activity')),
target_id UUID NOT NULL,
target_visibility_snapshot TEXT NOT NULL CHECK (target_visibility_snapshot IN ('public', 'semi_public')),
public_title_snapshot TEXT,
public_slug_snapshot TEXT,
action TEXT NOT NULL CHECK (action IN ('approved', 'denied', 'flagged', 'marked_spam', 'restored', 'removed')),
reason_code TEXT,
public_explanation TEXT,
moderator_public_handle TEXT NOT NULL,
moderator_internal_id UUID,
created_at TIMESTAMPTZ DEFAULT now()
);
ALTER TABLE public.public_moderation_log_entries ENABLE ROW LEVEL SECURITY;
CREATE SEQUENCE IF NOT EXISTS public.moderator_public_handle_seq START 1;
CREATE INDEX IF NOT EXISTS idx_public_moderation_log_entries_target_id
ON public.public_moderation_log_entries(target_id);
CREATE INDEX IF NOT EXISTS idx_public_moderation_log_entries_created_at
ON public.public_moderation_log_entries(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_public_moderation_log_entries_action
ON public.public_moderation_log_entries(action);
REVOKE ALL ON public.moderator_public_identities FROM anon, authenticated;
REVOKE ALL ON public.public_moderation_log_entries FROM anon, authenticated;
CREATE TABLE IF NOT EXISTS public.moderation_runtime_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES public.events(id) ON DELETE CASCADE,
source TEXT NOT NULL,
outcome TEXT NOT NULL CHECK (outcome IN ('succeeded', 'failed')),
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_moderation_runtime_events_event_id_created_at
ON public.moderation_runtime_events(event_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_moderation_runtime_events_created_at
ON public.moderation_runtime_events(created_at DESC);
ALTER TABLE public.moderation_runtime_events ENABLE ROW LEVEL SECURITY;
REVOKE ALL ON public.moderation_runtime_events FROM anon, authenticated;
UPDATE public.events
SET public_discovery_enabled = CASE
WHEN COALESCE(visibility, CASE WHEN is_public THEN 'public' ELSE 'private' END) IN ('public', 'semi_public')
THEN true
ELSE false
END
WHERE moderation_override IS NULL
AND moderated_at IS NULL
AND moderation_input_hash IS NULL;
UPDATE public.events
SET moderation_status = CASE
WHEN COALESCE(visibility, CASE WHEN is_public THEN 'public' ELSE 'private' END) = 'private'
THEN 'not_required'
ELSE 'approved'
END
WHERE moderation_override IS NULL
AND moderated_at IS NULL
AND moderation_input_hash IS NULL;
-- 2. RLS Policies
ALTER TABLE public.events ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_attendees ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_hosts ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_waitlist_positions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_access_requests ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_join_requests ENABLE ROW LEVEL SECURITY;
CREATE OR REPLACE FUNCTION public.is_event_host(
p_event_id UUID,
p_user_id UUID
) RETURNS BOOLEAN AS $$
SELECT EXISTS (
SELECT 1
FROM public.events e
WHERE e.id = p_event_id
AND e.host_user_id = p_user_id
)
OR EXISTS (
SELECT 1
FROM public.event_hosts eh
WHERE eh.event_id = p_event_id
AND eh.user_id = p_user_id
);
$$ LANGUAGE sql SECURITY DEFINER STABLE SET search_path = public;
GRANT EXECUTE ON FUNCTION public.is_event_host(UUID, UUID) TO anon, authenticated;
CREATE OR REPLACE FUNCTION public.event_host_count(
p_event_id UUID
) RETURNS INTEGER AS $$
SELECT count(*)::INTEGER
FROM public.event_hosts eh
WHERE eh.event_id = p_event_id;
$$ LANGUAGE sql SECURITY DEFINER STABLE SET search_path = public;
GRANT EXECUTE ON FUNCTION public.event_host_count(UUID) TO anon, authenticated;
CREATE OR REPLACE FUNCTION public.get_or_create_public_moderator_handle(
p_user_id UUID
) RETURNS TEXT AS $$
DECLARE
existing_handle TEXT;
next_number BIGINT;
new_handle TEXT;
BEGIN
SELECT mpi.public_handle
INTO existing_handle
FROM public.moderator_public_identities mpi
WHERE mpi.user_id = p_user_id;
IF existing_handle IS NOT NULL THEN
RETURN existing_handle;
END IF;
next_number := nextval('public.moderator_public_handle_seq');
new_handle := 'Moderator ' || lpad(next_number::TEXT, 2, '0');
INSERT INTO public.moderator_public_identities (user_id, public_handle)
VALUES (p_user_id, new_handle)
ON CONFLICT (user_id) DO UPDATE
SET public_handle = public.moderator_public_identities.public_handle;
RETURN (
SELECT mpi.public_handle
FROM public.moderator_public_identities mpi
WHERE mpi.user_id = p_user_id
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public;
-- -------------------------------------------------------------------
-- Event gallery feature (host photos + moderated public preview)
-- -------------------------------------------------------------------
ALTER TABLE public.events
ADD COLUMN IF NOT EXISTS gallery_visibility TEXT NOT NULL DEFAULT 'private_only'
CHECK (gallery_visibility IN ('private_only', 'public_preview'));
CREATE TABLE IF NOT EXISTS public.event_gallery_images (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES public.events(id) ON DELETE CASCADE,
storage_bucket TEXT NOT NULL DEFAULT 'event-gallery',
storage_path TEXT NOT NULL UNIQUE,
original_file_name TEXT,
content_type TEXT,
file_size_bytes INTEGER NOT NULL CHECK (file_size_bytes > 0),
width INTEGER,
height INTEGER,
sort_order INTEGER NOT NULL DEFAULT 0,
created_by_user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
public_visibility_status TEXT NOT NULL DEFAULT 'private_only'
CHECK (public_visibility_status IN ('private_only', 'pending', 'approved', 'blocked', 'error', 'report_hidden')),
public_moderation_reasons TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
public_moderation_confidence NUMERIC(4,3),
public_moderated_at TIMESTAMPTZ,
public_hidden_at TIMESTAMPTZ,
public_hidden_reason TEXT,
review_requested_at TIMESTAMPTZ,
report_count INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS public.event_gallery_image_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
image_id UUID NOT NULL REFERENCES public.event_gallery_images(id) ON DELETE CASCADE,
reporter_user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
report_reason TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (image_id, reporter_user_id)
);
ALTER TABLE public.event_gallery_images ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.event_gallery_image_reports ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS event_gallery_images_host_manage_select ON public.event_gallery_images;
CREATE POLICY event_gallery_images_host_manage_select
ON public.event_gallery_images
FOR SELECT TO authenticated
USING (public.is_event_host(event_id, auth.uid()));
DROP POLICY IF EXISTS event_gallery_images_host_manage_insert ON public.event_gallery_images;
CREATE POLICY event_gallery_images_host_manage_insert
ON public.event_gallery_images
FOR INSERT TO authenticated
WITH CHECK (
auth.uid() IS NOT NULL
AND public.is_event_host(event_id, auth.uid())
AND (
created_by_user_id IS NULL
OR created_by_user_id = auth.uid()
)
);
DROP POLICY IF EXISTS event_gallery_images_host_manage_update ON public.event_gallery_images;
CREATE POLICY event_gallery_images_host_manage_update
ON public.event_gallery_images
FOR UPDATE TO authenticated
USING (public.is_event_host(event_id, auth.uid()))
WITH CHECK (public.is_event_host(event_id, auth.uid()));
DROP POLICY IF EXISTS event_gallery_images_host_manage_delete ON public.event_gallery_images;
CREATE POLICY event_gallery_images_host_manage_delete
ON public.event_gallery_images
FOR DELETE TO authenticated
USING (public.is_event_host(event_id, auth.uid()));
DROP TRIGGER IF EXISTS event_gallery_images_touch_updated_at ON public.event_gallery_images;
CREATE TRIGGER event_gallery_images_touch_updated_at
BEFORE UPDATE ON public.event_gallery_images
FOR EACH ROW
EXECUTE FUNCTION public.touch_updated_at();
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'storage') THEN
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
'event-gallery',
'event-gallery',
false,
8388608,
ARRAY['image/png', 'image/jpeg', 'image/webp']::TEXT[]
)
ON CONFLICT (id) DO UPDATE
SET
public = false,
file_size_limit = EXCLUDED.file_size_limit,
allowed_mime_types = EXCLUDED.allowed_mime_types;
END IF;
END $$;
DROP FUNCTION IF EXISTS public.list_event_gallery_for_view(TEXT, TEXT);
CREATE FUNCTION public.list_event_gallery_for_view(
p_slug TEXT,
p_access_code TEXT DEFAULT NULL
) RETURNS TABLE (
id UUID,
event_id UUID,
storage_bucket TEXT,
storage_path TEXT,
original_file_name TEXT,
content_type TEXT,
file_size_bytes INTEGER,
width INTEGER,
height INTEGER,
sort_order INTEGER,
public_visibility_status TEXT,
public_moderation_reasons TEXT[],
public_moderation_confidence NUMERIC,
public_moderated_at TIMESTAMPTZ,
public_hidden_at TIMESTAMPTZ,
public_hidden_reason TEXT,
review_requested_at TIMESTAMPTZ,
report_count INTEGER,
is_public_preview_visible BOOLEAN,
can_report BOOLEAN,
created_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ
) AS $$
DECLARE
v_event RECORD;
v_visibility TEXT;
v_gallery_visibility TEXT;
v_can_view_full BOOLEAN := false;
v_host_viewer BOOLEAN := false;
BEGIN
SELECT *
INTO v_event
FROM public.get_event_for_view(p_slug, p_access_code)
LIMIT 1;
IF NOT FOUND OR v_event.id IS NULL THEN
RETURN;
END IF;
SELECT
COALESCE(e.visibility, CASE WHEN e.is_public THEN 'public' ELSE 'private' END),
COALESCE(e.gallery_visibility, 'private_only')
INTO
v_visibility,
v_gallery_visibility
FROM public.events e
WHERE e.id = v_event.id;
v_can_view_full := COALESCE(v_event.can_view_full_details, false);
v_host_viewer := auth.uid() IS NOT NULL AND public.is_event_host(v_event.id, auth.uid());
RETURN QUERY
SELECT
img.id,
img.event_id,
img.storage_bucket,
img.storage_path,
img.original_file_name,
img.content_type,
img.file_size_bytes,
img.width,
img.height,
img.sort_order,
img.public_visibility_status,
img.public_moderation_reasons,
img.public_moderation_confidence,
img.public_moderated_at,
img.public_hidden_at,
img.public_hidden_reason,
img.review_requested_at,
img.report_count,
(
v_visibility <> 'private'
AND v_gallery_visibility = 'public_preview'
AND img.public_visibility_status = 'approved'
AND img.public_hidden_at IS NULL
) AS is_public_preview_visible,
(
auth.uid() IS NOT NULL
AND NOT v_host_viewer
AND v_visibility <> 'private'
AND v_gallery_visibility = 'public_preview'
AND img.public_visibility_status = 'approved'
AND img.public_hidden_at IS NULL
) AS can_report,
img.created_at,
img.updated_at
FROM public.event_gallery_images img
WHERE img.event_id = v_event.id
AND (
v_can_view_full
OR (
v_gallery_visibility = 'public_preview'
AND img.public_visibility_status = 'approved'
AND img.public_hidden_at IS NULL
)
)
ORDER BY img.sort_order ASC, img.created_at ASC;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER STABLE SET search_path = public;
GRANT EXECUTE ON FUNCTION public.list_event_gallery_for_view(TEXT, TEXT) TO anon, authenticated;
DROP FUNCTION IF EXISTS public.report_event_gallery_image(UUID, TEXT);
CREATE FUNCTION public.report_event_gallery_image(
p_image_id UUID,
p_report_reason TEXT DEFAULT NULL
) RETURNS TABLE (
image_id UUID,
report_count INTEGER,
already_reported BOOLEAN,
image_hidden BOOLEAN
) AS $$
DECLARE
v_image RECORD;
v_visibility TEXT;
v_gallery_visibility TEXT;
v_is_preview_visible BOOLEAN := false;
v_already_reported BOOLEAN := false;
v_report_count INTEGER := 0;
v_image_hidden BOOLEAN := false;
v_inserted_count INTEGER := 0;
BEGIN
IF auth.uid() IS NULL THEN
RAISE EXCEPTION 'Sign-in required to report gallery images.';
END IF;
SELECT img.*, e.visibility, e.is_public, e.gallery_visibility
INTO v_image
FROM public.event_gallery_images img
JOIN public.events e
ON e.id = img.event_id
WHERE img.id = p_image_id
LIMIT 1;
IF NOT FOUND THEN
RAISE EXCEPTION 'Gallery image not found.';
END IF;
v_visibility := COALESCE(v_image.visibility, CASE WHEN v_image.is_public THEN 'public' ELSE 'private' END);
v_gallery_visibility := COALESCE(v_image.gallery_visibility, 'private_only');
v_is_preview_visible := (
v_visibility <> 'private'
AND v_gallery_visibility = 'public_preview'
AND v_image.public_visibility_status = 'approved'
AND v_image.public_hidden_at IS NULL
);
IF NOT v_is_preview_visible THEN
RAISE EXCEPTION 'This image is not currently available for public reporting.';
END IF;
INSERT INTO public.event_gallery_image_reports (image_id, reporter_user_id, report_reason)
VALUES (p_image_id, auth.uid(), nullif(trim(coalesce(p_report_reason, '')), ''))
ON CONFLICT (image_id, reporter_user_id) DO NOTHING;
GET DIAGNOSTICS v_inserted_count = ROW_COUNT;
v_already_reported := v_inserted_count = 0;
IF NOT v_already_reported THEN
UPDATE public.event_gallery_images
SET
report_count = COALESCE(report_count, 0) + 1,
review_requested_at = COALESCE(review_requested_at, now())
WHERE id = p_image_id
RETURNING report_count INTO v_report_count;
IF v_report_count >= 3 THEN
UPDATE public.event_gallery_images
SET
public_visibility_status = 'report_hidden',
public_hidden_at = COALESCE(public_hidden_at, now()),
public_hidden_reason = COALESCE(public_hidden_reason, 'reported_by_users'),
review_requested_at = COALESCE(review_requested_at, now())
WHERE id = p_image_id
AND public_hidden_at IS NULL;
END IF;
ELSE
SELECT COALESCE(report_count, 0)
INTO v_report_count
FROM public.event_gallery_images
WHERE id = p_image_id;
END IF;
SELECT (public_hidden_at IS NOT NULL OR public_visibility_status = 'report_hidden')
INTO v_image_hidden
FROM public.event_gallery_images
WHERE id = p_image_id;
RETURN QUERY
SELECT
p_image_id,
COALESCE(v_report_count, 0),
v_already_reported,
COALESCE(v_image_hidden, false);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER VOLATILE SET search_path = public;
GRANT EXECUTE ON FUNCTION public.report_event_gallery_image(UUID, TEXT) TO authenticated;
-- -------------------------------------------------------------------
-- Access model overrides (aligned with latest private/public rules)
-- -------------------------------------------------------------------
ALTER TABLE public.event_shared_with_users
ADD COLUMN IF NOT EXISTS unlock_private_slug TEXT,
ADD COLUMN IF NOT EXISTS unlock_join_code TEXT;
ALTER TABLE public.event_shared_with_users
DROP CONSTRAINT IF EXISTS event_shared_with_users_source_check;
ALTER TABLE public.event_shared_with_users
ADD CONSTRAINT event_shared_with_users_source_check
CHECK (source IN ('link', 'code', 'host_share'));
CREATE OR REPLACE FUNCTION public.is_event_shared_with_user_active(
p_event_id UUID,
p_user_id UUID
) RETURNS BOOLEAN AS $$
DECLARE
v_private_slug TEXT;
v_join_code TEXT;
BEGIN
IF p_event_id IS NULL OR p_user_id IS NULL THEN
RETURN false;
END IF;
SELECT
nullif(trim(coalesce(e.private_slug, '')), ''),
nullif(trim(coalesce(e.join_code, '')), '')
INTO
v_private_slug,
v_join_code
FROM public.events e
WHERE e.id = p_event_id;
RETURN EXISTS (
SELECT 1
FROM public.event_shared_with_users es
WHERE es.event_id = p_event_id
AND es.user_id = p_user_id
AND (
(es.unlock_private_slug IS NULL AND es.unlock_join_code IS NULL)
OR (
COALESCE(es.unlock_private_slug, '') = COALESCE(v_private_slug, '')
AND COALESCE(es.unlock_join_code, '') = COALESCE(v_join_code, '')
)
)
);
END;
$$ LANGUAGE plpgsql SECURITY DEFINER STABLE SET search_path = public;
CREATE OR REPLACE FUNCTION public.list_my_shared_activities()
RETURNS SETOF public.events AS $$
SELECT DISTINCT e.*
FROM public.event_shared_with_users es
JOIN public.events e
ON e.id = es.event_id
WHERE auth.uid() IS NOT NULL
AND es.user_id = auth.uid()
AND public.is_event_shared_with_user_active(es.event_id, es.user_id)
AND NOT public.is_event_host(e.id, auth.uid())
AND NOT EXISTS (
SELECT 1
FROM public.event_attendees ea
LEFT JOIN public.attendee_profiles ap
ON ap.id = ea.attendee_profile_id
LEFT JOIN public.attendee_profiles added_by_ap
ON added_by_ap.id = ea.added_by_attendee_profile_id
WHERE ea.event_id = e.id
AND ea.status <> 'cancelled'
AND (
ea.user_id = auth.uid()
OR ap.user_id = auth.uid()
OR lower(coalesce(ap.email, '')) = lower(coalesce(auth.jwt() ->> 'email', ''))
OR lower(coalesce(ea.guest_email, '')) = lower(coalesce(auth.jwt() ->> 'email', ''))
OR added_by_ap.user_id = auth.uid()
OR lower(coalesce(added_by_ap.email, '')) = lower(coalesce(auth.jwt() ->> 'email', ''))
)
)
AND NOT EXISTS (
SELECT 1
FROM public.event_join_requests jr
LEFT JOIN public.attendee_profiles ap
ON ap.id = jr.attendee_profile_id
WHERE jr.event_id = e.id
AND jr.status = 'pending'
AND (
jr.user_id = auth.uid()
OR ap.user_id = auth.uid()
OR lower(coalesce(ap.email, '')) = lower(coalesce(auth.jwt() ->> 'email', ''))
OR lower(coalesce(jr.guest_email, '')) = lower(coalesce(auth.jwt() ->> 'email', ''))
)
)
ORDER BY e.starts_at ASC;
$$ LANGUAGE sql SECURITY DEFINER STABLE SET search_path = public;
CREATE OR REPLACE FUNCTION public.get_event_for_view(
p_slug TEXT,
p_access_code TEXT DEFAULT NULL,
p_session_token TEXT DEFAULT NULL
) RETURNS TABLE (
id UUID,
slug TEXT,
public_slug TEXT,
private_slug TEXT,
join_code TEXT,
title TEXT,
description TEXT,
public_summary TEXT,
location_text TEXT,
public_location_text TEXT,
google_maps_url TEXT,
starts_at TIMESTAMPTZ,
timezone TEXT,
duration_minutes INTEGER,
ends_at TIMESTAMPTZ,
capacity INTEGER,
host_user_id UUID,
host_name TEXT,
host_contact_text TEXT,
show_host_publicly BOOLEAN,
access_code TEXT,
visibility TEXT,
allow_waitlist BOOLEAN,
require_host_approval_for_join BOOLEAN,
require_guest_email_for_join BOOLEAN,
is_public BOOLEAN,
public_discovery_enabled BOOLEAN,
moderation_status TEXT,
moderation_risk_level TEXT,
moderation_action TEXT,
moderation_confidence NUMERIC,
moderation_reasons TEXT[],
moderation_input_hash TEXT,
moderated_at TIMESTAMPTZ,
moderation_archived_at TIMESTAMPTZ,
moderation_override TEXT,
status TEXT,
created_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ,
can_view_full_details BOOLEAN
) AS $$
DECLARE
v_event public.events%ROWTYPE;
v_requested_slug TEXT := trim(coalesce(p_slug, ''));
v_private_slug TEXT;
v_visibility TEXT;
v_is_host BOOLEAN := false;
v_has_access_code BOOLEAN := false;
v_is_shared BOOLEAN := false;
v_is_attendee BOOLEAN := false;
v_is_private_slug BOOLEAN := false;
v_has_legacy_private_token BOOLEAN := false;
v_can_view_full BOOLEAN := false;
BEGIN
SELECT *
INTO v_event
FROM public.events e
WHERE e.slug = v_requested_slug
OR e.public_slug = v_requested_slug
OR e.private_slug = v_requested_slug
OR e.legacy_slug = v_requested_slug
LIMIT 1;
IF NOT FOUND THEN
RETURN;
END IF;
v_private_slug := COALESCE(nullif(trim(v_event.private_slug), ''), nullif(trim(v_event.join_code), ''));
v_is_private_slug := v_private_slug IS NOT NULL AND v_requested_slug = v_private_slug;
v_has_legacy_private_token := nullif(trim(coalesce(p_access_code, '')), '') IS NOT NULL
AND p_access_code = v_private_slug;
v_visibility := COALESCE(v_event.visibility, CASE WHEN v_event.is_public THEN 'public' ELSE 'private' END);
v_is_host := auth.uid() IS NOT NULL AND public.is_event_host(v_event.id, auth.uid());
v_has_access_code := nullif(trim(coalesce(p_access_code, '')), '') IS NOT NULL
AND p_access_code = v_event.access_code;
v_is_shared := auth.uid() IS NOT NULL AND public.is_event_shared_with_user_active(v_event.id, auth.uid());
v_is_attendee := EXISTS (
SELECT 1
FROM public.event_attendees ea
LEFT JOIN public.attendee_profiles ap ON ap.id = ea.attendee_profile_id
WHERE ea.event_id = v_event.id
AND ea.status IN ('confirmed', 'waitlist', 'pending_approval')
AND (
(auth.uid() IS NOT NULL AND (ea.user_id = auth.uid() OR ap.user_id = auth.uid()))
OR (v_guest_profile_id IS NOT NULL AND ea.attendee_profile_id = v_guest_profile_id)
)
);
v_can_view_full := (
v_visibility = 'public'
OR v_is_host
OR v_is_shared
OR v_is_attendee
OR v_is_private_slug
OR v_has_legacy_private_token
OR v_has_access_code
);
IF v_can_view_full
AND auth.uid() IS NOT NULL
AND NOT v_is_host
AND (v_is_private_slug OR v_has_legacy_private_token) THEN
BEGIN
PERFORM public.mark_event_shared_with_me(v_event.id, 'link');
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
BEGIN
PERFORM public.record_event_private_view(v_event.id, auth.uid());
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
END IF;
RETURN QUERY
SELECT
coalesce(v_event.id, NULL),
coalesce(v_event.public_slug, v_event.slug),
coalesce(v_event.public_slug, v_event.slug),
v_event.private_slug,
v_event.join_code,
v_event.title,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full THEN NULL
ELSE v_event.description
END,
v_event.public_summary,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full THEN NULL
ELSE v_event.location_text
END,
v_event.public_location_text,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full THEN NULL
ELSE v_event.google_maps_url
END,
v_event.starts_at,
v_event.timezone,
v_event.duration_minutes,
v_event.ends_at,
v_event.capacity,
v_event.host_user_id,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full AND NOT coalesce(v_event.show_host_publicly, false) THEN NULL
ELSE v_event.host_name
END,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full THEN NULL
ELSE v_event.host_contact_text
END,
v_event.show_host_publicly,
CASE
WHEN v_visibility = 'semi_public' AND NOT v_can_view_full THEN NULL
ELSE v_event.access_code
END,
v_event.visibility,
v_event.allow_waitlist,
coalesce(v_event.require_host_approval_for_join, false),
coalesce(v_event.require_guest_email_for_join, false),
v_event.is_public,
v_event.public_discovery_enabled,
v_event.moderation_status,
v_event.moderation_risk_level,
v_event.moderation_action,
v_event.moderation_confidence,
v_event.moderation_reasons,
v_event.moderation_input_hash,
v_event.moderated_at,
v_event.moderation_archived_at,
v_event.moderation_override,
v_event.status,
v_event.created_at,
v_event.updated_at,
v_can_view_full;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER VOLATILE SET search_path = public;
CREATE OR REPLACE FUNCTION public.list_public_calendar_events(
p_now TIMESTAMPTZ DEFAULT now()
) RETURNS TABLE (
id UUID,
slug TEXT,
title TEXT,
location_text TEXT,
public_location_text TEXT,
starts_at TIMESTAMPTZ,
timezone TEXT,
duration_minutes INTEGER,
capacity INTEGER,
visibility TEXT,
is_public BOOLEAN,
public_discovery_enabled BOOLEAN,
status TEXT,
access_code TEXT,
confirmed_count INTEGER,
thinking_count INTEGER
) AS $$
SELECT
e.id,
COALESCE(e.public_slug, e.slug) AS slug,
e.title,
CASE
WHEN COALESCE(e.visibility, CASE WHEN e.is_public THEN 'public' ELSE 'private' END) = 'semi_public' THEN NULL
ELSE e.location_text
END AS location_text,
e.public_location_text,
e.starts_at,
e.timezone,
e.duration_minutes,
e.capacity,
e.visibility,
e.is_public,
e.public_discovery_enabled,
e.status,
NULL::TEXT AS access_code,
(
SELECT count(*)::INTEGER
FROM public.event_attendees ea
WHERE ea.event_id = e.id
AND ea.status = 'confirmed'
) AS confirmed_count,
(
SELECT count(*)::INTEGER
FROM public.event_interests ei
WHERE ei.event_id = e.id
) AS thinking_count
FROM public.events e
WHERE e.status = 'scheduled'
AND e.is_public = true
AND e.public_discovery_enabled = true
AND e.starts_at >= COALESCE(p_now, now())
ORDER BY e.starts_at ASC;
$$ LANGUAGE sql SECURITY DEFINER STABLE SET search_path = public;
CREATE OR REPLACE FUNCTION public.list_event_attendees_for_view(
p_event_id UUID,
p_access_code TEXT DEFAULT NULL
) RETURNS SETOF public.event_attendees AS $$
DECLARE
v_visibility TEXT;
v_event_access_code TEXT;
v_private_slug TEXT;
v_can_view BOOLEAN := false;
v_is_shared BOOLEAN := false;
v_is_attendee BOOLEAN := false;
BEGIN
SELECT
COALESCE(e.visibility, CASE WHEN e.is_public THEN 'public' ELSE 'private' END),
e.access_code,
COALESCE(nullif(trim(e.private_slug), ''), nullif(trim(e.join_code), ''))
INTO
v_visibility,
v_event_access_code,
v_private_slug
FROM public.events e
WHERE e.id = p_event_id;
IF v_visibility IS NULL THEN
RETURN;
END IF;
v_is_shared := auth.uid() IS NOT NULL AND public.is_event_shared_with_user_active(p_event_id, auth.uid());
v_is_attendee := EXISTS (
SELECT 1
FROM public.event_attendees ea
LEFT JOIN public.attendee_profiles ap ON ap.id = ea.attendee_profile_id
WHERE ea.event_id = p_event_id
AND ea.status IN ('confirmed', 'waitlist', 'pending_approval')
AND (
(auth.uid() IS NOT NULL AND (ea.user_id = auth.uid() OR ap.user_id = auth.uid()))
OR (v_guest_profile_id IS NOT NULL AND ea.attendee_profile_id = v_guest_profile_id)
)
);
v_can_view := v_visibility = 'public'
OR (auth.uid() IS NOT NULL AND public.is_event_host(p_event_id, auth.uid()))
OR v_is_shared
OR v_is_attendee
OR (
nullif(trim(coalesce(p_access_code, '')), '') IS NOT NULL
AND (
p_access_code = v_event_access_code
OR p_access_code = coalesce(v_private_slug, '')
)
);
IF NOT v_can_view THEN
RETURN;
END IF;
RETURN QUERY
SELECT ea.*
FROM public.event_attendees ea
WHERE ea.event_id = p_event_id
AND ea.status <> 'cancelled'
ORDER BY ea.joined_at ASC;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER STABLE SET search_path = public;
CREATE OR REPLACE FUNCTION public.list_event_interests_for_view(
p_event_id UUID,
p_access_code TEXT DEFAULT NULL
) RETURNS SETOF public.event_interests AS $$
DECLARE
v_visibility TEXT;
v_event_access_code TEXT;
v_private_slug TEXT;
v_can_view_named BOOLEAN := false;
v_is_shared BOOLEAN := false;
v_is_attendee BOOLEAN := false;
BEGIN
SELECT
COALESCE(e.visibility, CASE WHEN e.is_public THEN 'public' ELSE 'private' END),