-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommunity-patch-v4.sql
More file actions
2424 lines (2174 loc) Β· 119 KB
/
Copy pathcommunity-patch-v4.sql
File metadata and controls
2424 lines (2174 loc) Β· 119 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
-- ============================================================================
-- IsotopeAI β Community Patch v4
-- ============================================================================
-- Run this in Supabase SQL Editor (Project > SQL Editor > New query > Run).
-- Fully idempotent: safe to run multiple times on the same database.
-- Fixes EVERY mismatch between the compiled frontend JS and the DB schema.
--
-- What this fixes:
-- 1. users β username, coins, gems, plan columns, everyone β ranker
-- 2. groups β is_public, deleted_at, fts, max_members, slug, cover_url β¦
-- 3. group_members β role, joined_at, unique constraint
-- 4. group_chat_messages β user_id (JS inserts/reads this, not sender_id)
-- 5. group_invites β token as plain writable column (not invite_code)
-- 6. group_announcements β author_id, content, pinned columns
-- 7. group_milestones β milestone_type, earned_at columns
-- 8. group_challenges β full table (CREATE IF NOT EXISTS + column adds)
-- 9. group_challenge_participants β full table
-- 10. user_stats_summary β adds the 7 columns JS reads (total_hours etc.)
-- 11. user_points β points, lifetime_points
-- 12. user_profiles β profile_data jsonb
-- 13. daily_user_stats β CREATE IF NOT EXISTS
-- 14. study_sessions_log β CREATE IF NOT EXISTS
-- 15. store_items β CREATE IF NOT EXISTS
-- 16. user_inventory β CREATE IF NOT EXISTS
-- 17. notifications β CREATE IF NOT EXISTS
-- 18. user_presence β CREATE IF NOT EXISTS
-- 19. RPC get_invite_details β search by token (not invite_code)
-- 20. RPC accept_invite β search by token; returns {success:} not {ok:}
-- 21. RPC get_membership_snapshot β param is p_user_id (not p_group_id)
-- 22. RPC get_group_analytics_from_snapshots β correct
-- 23. RPC get_leaderboard β SQL-based (edge function not deployed)
-- 24. RPC get_group_leaderboard β SQL-based
-- 25. RPC is_premium_user β always true
-- 26. GRANT EXECUTE on all RPCs to anon/authenticated/service_role
-- 27. RLS policies β fix group_chat_messages INSERT (user_id not sender_id)
-- 28. handle_new_user trigger β updated for all new tables
-- 29. Performance indexes
-- 30. Backfill all existing users
-- ============================================================================
-- ββ 0. Drop RPCs with return-type drift before any CREATE OR REPLACE βββββββββ
-- PostgreSQL cannot change a function's return type with CREATE OR REPLACE.
-- These exact drops make the full migration rerunnable on databases that have
-- older Isotope function definitions.
DROP FUNCTION IF EXISTS public.get_invite_details(text);
DROP FUNCTION IF EXISTS public.accept_invite(text);
DROP FUNCTION IF EXISTS public.get_membership_snapshot();
DROP FUNCTION IF EXISTS public.get_membership_snapshot(uuid);
DROP FUNCTION IF EXISTS public.get_membership_snapshot(uuid, uuid);
DROP FUNCTION IF EXISTS public.get_group_analytics_from_snapshots(uuid);
DROP FUNCTION IF EXISTS public.get_group_analytics_from_snapshots(uuid, integer);
DROP FUNCTION IF EXISTS public.get_leaderboard();
DROP FUNCTION IF EXISTS public.get_leaderboard(text);
DROP FUNCTION IF EXISTS public.get_leaderboard(text, integer);
DROP FUNCTION IF EXISTS public.get_leaderboard(text, integer, integer);
DROP FUNCTION IF EXISTS public.get_group_leaderboard(uuid);
DROP FUNCTION IF EXISTS public.get_group_leaderboard(uuid, integer);
DROP FUNCTION IF EXISTS public.finish_session_sync(uuid, text, integer, uuid, text, text, timestamptz);
DROP FUNCTION IF EXISTS public.finish_session_sync(uuid, text, integer, text, text, uuid);
DROP FUNCTION IF EXISTS public.finish_session_sync(uuid, text, integer, uuid, text, text, text);
DROP FUNCTION IF EXISTS public.get_event_attendees(uuid);
-- ββ 1. users βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS username text;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS coins integer NOT NULL DEFAULT 0;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS gems integer NOT NULL DEFAULT 0;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS avatar_url text;
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS plan_expires_at timestamptz DEFAULT '2099-12-31 23:59:59+00';
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS access_ends_at timestamptz DEFAULT '2099-12-31 23:59:59+00';
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
DO $$ BEGIN
ALTER TABLE public.users ALTER COLUMN plan_type SET DEFAULT 'ranker';
EXCEPTION WHEN OTHERS THEN NULL; END $$;
DO $$ BEGIN
ALTER TABLE public.users ALTER COLUMN billing_status SET DEFAULT 'active';
EXCEPTION WHEN OTHERS THEN NULL; END $$;
-- ββ 2. groups βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads: id, name, description, cover_url, logo_url, category, slug,
-- member_count, owner_id, is_public, max_members, created_at
-- JS filters: .eq("is_public", true) .is("deleted_at", null)
-- JS search: .textSearch("fts", ...)
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS cover_url text;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS logo_url text;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS category text;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS slug text;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS member_count integer NOT NULL DEFAULT 0;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS owner_id uuid;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS max_members integer NOT NULL DEFAULT 100;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS is_active boolean NOT NULL DEFAULT true;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS deleted_at timestamptz;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS settings jsonb NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS visibility text NOT NULL DEFAULT 'public';
-- is_public: add as plain column if missing, then backfill
ALTER TABLE public.groups ADD COLUMN IF NOT EXISTS is_public boolean;
DO $$
BEGIN
-- Backfill from visibility column
UPDATE public.groups
SET is_public = (visibility NOT IN ('private', 'invite_only'))
WHERE is_public IS NULL;
-- Default any remaining NULLs
UPDATE public.groups SET is_public = true WHERE is_public IS NULL;
-- Harden
ALTER TABLE public.groups ALTER COLUMN is_public SET NOT NULL;
ALTER TABLE public.groups ALTER COLUMN is_public SET DEFAULT true;
EXCEPTION WHEN OTHERS THEN NULL;
END $$;
-- Full-text search generated column (for .textSearch("fts", ...))
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'groups' AND column_name = 'fts'
) THEN
ALTER TABLE public.groups
ADD COLUMN fts tsvector GENERATED ALWAYS AS (
to_tsvector('english',
coalesce(name,'') || ' ' ||
coalesce(description,'') || ' ' ||
coalesce(category,'')
)
) STORED;
END IF;
END $$;
CREATE INDEX IF NOT EXISTS idx_groups_fts ON public.groups USING GIN (fts);
CREATE INDEX IF NOT EXISTS idx_groups_public ON public.groups (is_public) WHERE is_public = true;
CREATE INDEX IF NOT EXISTS idx_groups_slug ON public.groups (slug) WHERE slug IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_groups_owner ON public.groups (owner_id);
CREATE INDEX IF NOT EXISTS idx_groups_active ON public.groups (is_active) WHERE is_active = true;
CREATE INDEX IF NOT EXISTS idx_groups_del ON public.groups (deleted_at) WHERE deleted_at IS NULL;
-- ββ 3. group_members ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads/inserts: id, group_id, user_id, role, joined_at
ALTER TABLE public.group_members ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'member';
ALTER TABLE public.group_members ADD COLUMN IF NOT EXISTS joined_at timestamptz NOT NULL DEFAULT now();
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'public.group_members'::regclass
AND conname = 'group_members_group_id_user_id_key'
) THEN
ALTER TABLE public.group_members
ADD CONSTRAINT group_members_group_id_user_id_key UNIQUE (group_id, user_id);
END IF;
END $$;
CREATE INDEX IF NOT EXISTS idx_gm_group ON public.group_members (group_id);
CREATE INDEX IF NOT EXISTS idx_gm_user ON public.group_members (user_id);
-- ββ 4. group_chat_messages ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS selects: id, content, created_at, user_id
-- JS inserts: { id, group_id, user_id, content }
-- CRITICAL: JS uses user_id β NOT sender_id
ALTER TABLE public.group_chat_messages ADD COLUMN IF NOT EXISTS user_id uuid;
ALTER TABLE public.group_chat_messages ADD COLUMN IF NOT EXISTS message_type text NOT NULL DEFAULT 'text';
ALTER TABLE public.group_chat_messages ADD COLUMN IF NOT EXISTS reply_to_id uuid;
ALTER TABLE public.group_chat_messages ADD COLUMN IF NOT EXISTS deleted_at timestamptz;
-- Backfill user_id from sender_id (if sender_id exists)
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'group_chat_messages'
AND column_name = 'sender_id'
) THEN
UPDATE public.group_chat_messages
SET user_id = sender_id
WHERE user_id IS NULL AND sender_id IS NOT NULL;
END IF;
END $$;
CREATE INDEX IF NOT EXISTS idx_gchat_group_time ON public.group_chat_messages (group_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_gchat_user ON public.group_chat_messages (user_id);
-- ββ 5. group_invites ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads/inserts: id, group_id, token, created_by, max_uses, uses_count,
-- expires_at, created_at
-- CRITICAL: JS column name is 'token'. Must be a plain writable TEXT column.
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS created_by uuid;
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS max_uses integer;
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS uses_count integer NOT NULL DEFAULT 0;
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS expires_at timestamptz;
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS created_at timestamptz NOT NULL DEFAULT now();
-- Ensure 'token' is a plain writable column (drop it if it's a GENERATED column)
DO $$
DECLARE
v_is_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_is_gen
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'group_invites'
AND column_name = 'token';
IF v_is_gen IS TRUE THEN
-- Drop the generated column and replace with plain
ALTER TABLE public.group_invites DROP COLUMN token;
ALTER TABLE public.group_invites ADD COLUMN token text;
-- Backfill from invite_code if it exists
BEGIN
UPDATE public.group_invites
SET token = invite_code
WHERE token IS NULL AND invite_code IS NOT NULL;
EXCEPTION WHEN OTHERS THEN NULL;
END;
ELSIF v_is_gen IS NULL THEN
-- Column does not exist at all β add it
ALTER TABLE public.group_invites ADD COLUMN token text;
END IF;
-- If v_is_gen = FALSE the column already exists as a plain column β nothing to do
END $$;
-- Keep invite_code in sync so legacy lookups still work
ALTER TABLE public.group_invites ADD COLUMN IF NOT EXISTS invite_code text;
UPDATE public.group_invites SET invite_code = token WHERE invite_code IS NULL AND token IS NOT NULL;
UPDATE public.group_invites SET token = invite_code WHERE token IS NULL AND invite_code IS NOT NULL;
-- Unique constraints
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'public.group_invites'::regclass
AND conname = 'group_invites_token_key'
) THEN
ALTER TABLE public.group_invites ADD CONSTRAINT group_invites_token_key UNIQUE (token);
END IF;
END $$;
CREATE INDEX IF NOT EXISTS idx_ginv_token ON public.group_invites (token);
CREATE INDEX IF NOT EXISTS idx_ginv_group ON public.group_invites (group_id);
-- ββ 6. group_announcements ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS selects: id, content, pinned, author_id, created_at
-- JS inserts: { group_id, author_id, content, pinned }
ALTER TABLE public.group_announcements ADD COLUMN IF NOT EXISTS author_id uuid;
ALTER TABLE public.group_announcements ADD COLUMN IF NOT EXISTS content text NOT NULL DEFAULT '';
ALTER TABLE public.group_announcements ADD COLUMN IF NOT EXISTS pinned boolean NOT NULL DEFAULT false;
ALTER TABLE public.group_announcements ADD COLUMN IF NOT EXISTS created_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_gann_group ON public.group_announcements (group_id);
CREATE INDEX IF NOT EXISTS idx_gann_pinned ON public.group_announcements (group_id, pinned DESC, created_at DESC);
-- ββ 7. group_milestones βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS selects: milestone_type, earned_at
ALTER TABLE public.group_milestones ADD COLUMN IF NOT EXISTS group_id uuid;
ALTER TABLE public.group_milestones ADD COLUMN IF NOT EXISTS milestone_type text NOT NULL DEFAULT '';
ALTER TABLE public.group_milestones ADD COLUMN IF NOT EXISTS earned_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_gmile_group ON public.group_milestones (group_id);
-- ββ 8. group_challenges βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads/inserts: id, group_id, title, description, goal_type, goal_value,
-- start_time, end_time, created_by, is_active, created_at
CREATE TABLE IF NOT EXISTS public.group_challenges (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
group_id uuid NOT NULL,
title text NOT NULL DEFAULT '',
description text,
goal_type text NOT NULL DEFAULT 'hours',
goal_value numeric NOT NULL DEFAULT 0,
start_time timestamptz NOT NULL DEFAULT now(),
end_time timestamptz,
created_by uuid,
is_active boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS title text NOT NULL DEFAULT '';
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS description text;
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS goal_type text NOT NULL DEFAULT 'hours';
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS goal_value numeric NOT NULL DEFAULT 0;
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS start_time timestamptz NOT NULL DEFAULT now();
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS end_time timestamptz;
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS created_by uuid;
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS is_active boolean NOT NULL DEFAULT true;
ALTER TABLE public.group_challenges ADD COLUMN IF NOT EXISTS created_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_gchall_group ON public.group_challenges (group_id);
-- ββ 9. group_challenge_participants βββββββββββββββββββββββββββββββββββββββββββ
-- JS reads/upserts: challenge_id, user_id, progress, completed,
-- completed_at, joined_at
CREATE TABLE IF NOT EXISTS public.group_challenge_participants (
challenge_id uuid NOT NULL,
user_id uuid NOT NULL,
progress numeric NOT NULL DEFAULT 0,
completed boolean NOT NULL DEFAULT false,
completed_at timestamptz,
joined_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (challenge_id, user_id)
);
ALTER TABLE public.group_challenge_participants ADD COLUMN IF NOT EXISTS progress numeric NOT NULL DEFAULT 0;
ALTER TABLE public.group_challenge_participants ADD COLUMN IF NOT EXISTS completed boolean NOT NULL DEFAULT false;
ALTER TABLE public.group_challenge_participants ADD COLUMN IF NOT EXISTS completed_at timestamptz;
ALTER TABLE public.group_challenge_participants ADD COLUMN IF NOT EXISTS joined_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_gcpart_challenge ON public.group_challenge_participants (challenge_id);
CREATE INDEX IF NOT EXISTS idx_gcpart_user ON public.group_challenge_participants (user_id);
-- ββ 10. user_stats_summary ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- Server INSERTs: total_study_seconds, streak_days, max_streak_days,
-- session_count
-- JS READs: total_hours, weekly_hours, monthly_hours, current_streak,
-- longest_streak, total_sessions, last_session_at
-- Underlying columns for server INSERT
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS total_study_seconds bigint NOT NULL DEFAULT 0;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS streak_days integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS max_streak_days integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS session_count integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS last_study_date date;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
-- JS-read columns β drop if currently GENERATED (immutable), then add as plain
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='total_hours';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN total_hours; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS total_hours numeric NOT NULL DEFAULT 0;
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='weekly_hours';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN weekly_hours; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS weekly_hours numeric NOT NULL DEFAULT 0;
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='monthly_hours';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN monthly_hours; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS monthly_hours numeric NOT NULL DEFAULT 0;
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='current_streak';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN current_streak; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS current_streak integer NOT NULL DEFAULT 0;
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='longest_streak';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN longest_streak; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS longest_streak integer NOT NULL DEFAULT 0;
DO $$
DECLARE v_gen boolean;
BEGIN
SELECT (is_generated = 'ALWAYS') INTO v_gen FROM information_schema.columns
WHERE table_schema='public' AND table_name='user_stats_summary' AND column_name='total_sessions';
IF v_gen IS TRUE THEN ALTER TABLE public.user_stats_summary DROP COLUMN total_sessions; END IF;
END $$;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS total_sessions integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_stats_summary ADD COLUMN IF NOT EXISTS last_session_at timestamptz;
CREATE INDEX IF NOT EXISTS idx_stats_user_id ON public.user_stats_summary (user_id);
CREATE INDEX IF NOT EXISTS idx_stats_total_hours ON public.user_stats_summary (total_hours DESC);
CREATE INDEX IF NOT EXISTS idx_stats_weekly_hours ON public.user_stats_summary (weekly_hours DESC);
-- ββ 11. user_points βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ALTER TABLE public.user_points ADD COLUMN IF NOT EXISTS points integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_points ADD COLUMN IF NOT EXISTS lifetime_points integer NOT NULL DEFAULT 0;
ALTER TABLE public.user_points ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_points_user_id ON public.user_points (user_id);
CREATE INDEX IF NOT EXISTS idx_points_points ON public.user_points (points DESC);
CREATE INDEX IF NOT EXISTS idx_points_lifetime ON public.user_points (lifetime_points DESC);
-- ββ 12. user_profiles ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ALTER TABLE public.user_profiles ADD COLUMN IF NOT EXISTS profile_data jsonb NOT NULL DEFAULT '{}'::jsonb;
ALTER TABLE public.user_profiles ADD COLUMN IF NOT EXISTS updated_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_profiles_user_id ON public.user_profiles (user_id);
-- ββ 13. daily_user_stats ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads: user_id, date, seconds_studied
CREATE TABLE IF NOT EXISTS public.daily_user_stats (
user_id uuid NOT NULL,
date date NOT NULL,
seconds_studied bigint NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, date)
);
ALTER TABLE public.daily_user_stats ADD COLUMN IF NOT EXISTS seconds_studied bigint NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_daily_user_date ON public.daily_user_stats (user_id, date DESC);
-- ββ 14. study_sessions_log ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads: user_id, duration_minutes, ended_at
CREATE TABLE IF NOT EXISTS public.study_sessions_log (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL,
duration_minutes integer NOT NULL DEFAULT 0,
started_at timestamptz NOT NULL DEFAULT now(),
ended_at timestamptz NOT NULL DEFAULT now(),
subject text,
notes text,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE public.study_sessions_log ADD COLUMN IF NOT EXISTS duration_minutes integer NOT NULL DEFAULT 0;
ALTER TABLE public.study_sessions_log ADD COLUMN IF NOT EXISTS ended_at timestamptz NOT NULL DEFAULT now();
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON public.study_sessions_log (user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_started_at ON public.study_sessions_log (started_at DESC);
-- ββ 15. store_items βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads: id, name, description, price, currency, category, image
CREATE TABLE IF NOT EXISTS public.store_items (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
name text NOT NULL DEFAULT '',
description text,
price integer NOT NULL DEFAULT 0,
currency text NOT NULL DEFAULT 'coins',
category text NOT NULL DEFAULT 'theme',
image text,
active boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS description text;
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS price integer NOT NULL DEFAULT 0;
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS currency text NOT NULL DEFAULT 'coins';
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS category text NOT NULL DEFAULT 'theme';
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS image text;
ALTER TABLE public.store_items ADD COLUMN IF NOT EXISTS active boolean NOT NULL DEFAULT true;
-- ββ 16. user_inventory ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS reads/inserts/updates: id, user_id, item_id, equipped
CREATE TABLE IF NOT EXISTS public.user_inventory (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL,
item_id uuid NOT NULL,
equipped boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (user_id, item_id)
);
ALTER TABLE public.user_inventory ADD COLUMN IF NOT EXISTS equipped boolean NOT NULL DEFAULT false;
-- ββ 17. notifications βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CREATE TABLE IF NOT EXISTS public.notifications (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
type text NOT NULL DEFAULT 'system',
title text NOT NULL DEFAULT '',
body text NOT NULL DEFAULT '',
data jsonb NOT NULL DEFAULT '{}'::jsonb,
read_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notif_user_time ON public.notifications (user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_notif_unread ON public.notifications (user_id, read_at) WHERE read_at IS NULL;
-- ββ 18. user_presence βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CREATE TABLE IF NOT EXISTS public.user_presence (
user_id uuid PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
status text NOT NULL DEFAULT 'offline',
current_subject text,
last_seen timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_presence_status ON public.user_presence (status);
CREATE INDEX IF NOT EXISTS idx_presence_last_seen ON public.user_presence (last_seen DESC);
-- ββ 19. RPC: is_premium_user βββββββββββββββββββββββββββββββββββββββββββββββββ
CREATE OR REPLACE FUNCTION public.is_premium_user(uid uuid)
RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER
AS $$ SELECT true; $$;
-- ββ 20. RPC: get_invite_details βββββββββββββββββββββββββββββββββββββββββββββββ
-- JS calls: .rpc("get_invite_details", { p_code: token })
-- FIXED: searches token column (not invite_code)
CREATE OR REPLACE FUNCTION public.get_invite_details(p_code text)
RETURNS TABLE (
group_id uuid,
group_name text,
description text,
member_count bigint,
is_valid boolean
)
LANGUAGE sql STABLE SECURITY DEFINER
AS $$
SELECT
g.id AS group_id,
g.name AS group_name,
g.description,
COUNT(gm.user_id) AS member_count,
(
(gi.expires_at IS NULL OR gi.expires_at > now())
AND (gi.max_uses IS NULL OR gi.uses_count < gi.max_uses)
) AS is_valid
FROM public.group_invites gi
JOIN public.groups g ON g.id = gi.group_id
LEFT JOIN public.group_members gm ON gm.group_id = g.id
WHERE (gi.token = p_code OR gi.invite_code = p_code)
AND (g.is_active = true OR g.is_active IS NULL)
AND g.deleted_at IS NULL
GROUP BY g.id, g.name, g.description,
gi.expires_at, gi.max_uses, gi.uses_count;
$$;
-- ββ 21. RPC: accept_invite ββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- JS calls: .rpc("accept_invite", { p_code: token })
-- JS checks: if (!e.success) throw ...
-- FIXED: searches token column; returns { success: true/false }
CREATE OR REPLACE FUNCTION public.accept_invite(p_code text)
RETURNS jsonb
LANGUAGE plpgsql SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_invite public.group_invites%ROWTYPE;
v_uid uuid := auth.uid();
BEGIN
IF v_uid IS NULL THEN
RETURN jsonb_build_object('success', false, 'error', 'Not authenticated');
END IF;
SELECT * INTO v_invite
FROM public.group_invites
WHERE token = p_code OR invite_code = p_code
LIMIT 1;
IF NOT FOUND THEN
RETURN jsonb_build_object('success', false, 'error', 'Invite not found');
END IF;
IF v_invite.expires_at IS NOT NULL AND v_invite.expires_at < now() THEN
RETURN jsonb_build_object('success', false, 'error', 'Invite has expired');
END IF;
IF v_invite.max_uses IS NOT NULL AND v_invite.uses_count >= v_invite.max_uses THEN
RETURN jsonb_build_object('success', false, 'error', 'Invite has reached maximum uses');
END IF;
-- Add member β silent no-op if already a member
INSERT INTO public.group_members (group_id, user_id, role)
VALUES (v_invite.group_id, v_uid, 'member')
ON CONFLICT (group_id, user_id) DO NOTHING;
-- Track usage + keep token/invite_code in sync
UPDATE public.group_invites
SET
uses_count = uses_count + 1,
invite_code = COALESCE(invite_code, token),
token = COALESCE(token, invite_code)
WHERE id = v_invite.id;
RETURN jsonb_build_object('success', true, 'group_id', v_invite.group_id);
END;
$$;
-- ββ 22. RPC: get_membership_snapshot βββββββββββββββββββββββββββββββββββββββββ
-- TWO callers, two different parameter names:
-- App-pJGjDiPw.js: .rpc("get_membership_snapshot", { p_user_id: userId })
-- Subscription-UaefsAtQ: .rpc("get_membership_snapshot", { target_user_id: userId })
-- FIX: Both parameters DEFAULT NULL β COALESCE picks whichever is non-null.
-- PostgREST routes named args by matching the declared param names, so each
-- caller will only fill in its own key; the other will be NULL.
CREATE OR REPLACE FUNCTION public.get_membership_snapshot(
p_user_id uuid DEFAULT NULL,
target_user_id uuid DEFAULT NULL
)
RETURNS jsonb
LANGUAGE sql STABLE SECURITY DEFINER
AS $$
SELECT jsonb_build_object(
'user_id', u.id,
'plan_type', u.plan_type,
'plan_expires_at', u.plan_expires_at,
'is_premium', true,
'points', COALESCE(up.points, 0),
'lifetime_points', COALESCE(up.lifetime_points, 0),
'billing_status', 'active',
'access_ends_at', '2099-12-31T23:59:59Z'
)
FROM public.users u
LEFT JOIN public.user_points up ON up.user_id = u.id
WHERE u.id = COALESCE(p_user_id, target_user_id);
$$;
-- ββ 23. RPC: get_group_analytics_from_snapshots βββββββββββββββββββββββββββββββ
-- JS calls: .rpc("get_group_analytics_from_snapshots", { p_group_id, p_days })
CREATE OR REPLACE FUNCTION public.get_group_analytics_from_snapshots(
p_group_id uuid,
p_days integer DEFAULT 7
)
RETURNS TABLE (
date date,
total_seconds bigint,
active_members bigint
)
LANGUAGE sql STABLE SECURITY DEFINER
AS $$
SELECT
d.date,
COALESCE(SUM(d.seconds_studied), 0)::bigint AS total_seconds,
COUNT(DISTINCT d.user_id)::bigint AS active_members
FROM public.daily_user_stats d
JOIN public.group_members gm
ON gm.user_id = d.user_id
AND gm.group_id = p_group_id
WHERE d.date >= (CURRENT_DATE - (p_days - 1))
GROUP BY d.date
ORDER BY d.date;
$$;
-- ββ 24. RPC: get_leaderboard βββββββββββββββββββββββββββββββββββββββββββββββββ
-- Called by server.mjs fetch interceptor when app calls the missing edge fn.
-- Also callable directly: SELECT * FROM get_leaderboard('weekly', 50, 0);
CREATE OR REPLACE FUNCTION public.get_leaderboard(
p_period text DEFAULT 'weekly',
p_limit integer DEFAULT 50,
p_offset integer DEFAULT 0
)
RETURNS TABLE (
rank bigint,
user_id uuid,
username text,
name text,
avatar_url text,
total_hours numeric,
weekly_hours numeric,
monthly_hours numeric,
total_sessions integer,
current_streak integer,
last_session_at timestamptz,
score numeric
)
LANGUAGE plpgsql STABLE SECURITY DEFINER
AS $$
BEGIN
RETURN QUERY
SELECT
ROW_NUMBER() OVER (
ORDER BY
CASE p_period
WHEN 'monthly' THEN s.monthly_hours
WHEN 'daily' THEN s.weekly_hours
ELSE s.weekly_hours
END DESC NULLS LAST,
s.total_hours DESC NULLS LAST
) AS rank,
s.user_id,
u.username,
u.name,
u.avatar_url,
COALESCE(s.total_hours, 0) AS total_hours,
COALESCE(s.weekly_hours, 0) AS weekly_hours,
COALESCE(s.monthly_hours,0) AS monthly_hours,
COALESCE(s.total_sessions, 0)::integer AS total_sessions,
COALESCE(s.current_streak, 0)::integer AS current_streak,
s.last_session_at,
COALESCE(
CASE p_period
WHEN 'monthly' THEN s.monthly_hours
ELSE s.weekly_hours
END, 0
) AS score
FROM public.user_stats_summary s
JOIN public.users u ON u.id = s.user_id
ORDER BY score DESC NULLS LAST, s.total_hours DESC NULLS LAST
LIMIT p_limit
OFFSET p_offset;
END;
$$;
-- ββ 25. RPC: get_group_leaderboard βββββββββββββββββββββββββββββββββββββββββββ
CREATE OR REPLACE FUNCTION public.get_group_leaderboard(
p_group_id uuid,
p_limit integer DEFAULT 20
)
RETURNS TABLE (
rank bigint,
user_id uuid,
username text,
name text,
avatar_url text,
total_hours numeric,
weekly_hours numeric,
total_sessions integer
)
LANGUAGE sql STABLE SECURITY DEFINER
AS $$
SELECT
ROW_NUMBER() OVER (
ORDER BY COALESCE(s.weekly_hours, 0) DESC NULLS LAST
) AS rank,
gm.user_id,
u.username,
u.name,
u.avatar_url,
COALESCE(s.total_hours, 0) AS total_hours,
COALESCE(s.weekly_hours, 0) AS weekly_hours,
COALESCE(s.total_sessions,0)::integer AS total_sessions
FROM public.group_members gm
JOIN public.users u ON u.id = gm.user_id
LEFT JOIN public.user_stats_summary s ON s.user_id = gm.user_id
WHERE gm.group_id = p_group_id
ORDER BY COALESCE(s.weekly_hours,0) DESC NULLS LAST
LIMIT p_limit;
$$;
-- ββ 26. RPC: finish_session_sync βββββββββββββββββββββββββββββββββββββββββββββ
-- Called by server.mjs fetch interceptor when app calls the missing
-- finish-session edge function. Writes session data into:
-- study_sessions_log, daily_user_stats, user_stats_summary
CREATE OR REPLACE FUNCTION public.finish_session_sync(
p_session_id uuid,
p_action text DEFAULT 'complete',
p_duration_minutes integer DEFAULT 0,
p_group_id uuid DEFAULT NULL,
p_session_type text DEFAULT 'focus',
p_notes text DEFAULT NULL,
p_ended_at timestamptz DEFAULT NULL
)
RETURNS jsonb
LANGUAGE plpgsql SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_uid uuid := auth.uid();
v_today date := CURRENT_DATE;
v_secs bigint;
v_hrs numeric;
v_row_count bigint;
v_was_found boolean;
BEGIN
IF v_uid IS NULL THEN
RETURN jsonb_build_object('error', 'Not authenticated');
END IF;
-- delete action: remove session and exit
IF p_action = 'delete' THEN
DELETE FROM public.study_sessions_log
WHERE id = p_session_id AND user_id = v_uid;
v_was_found := FOUND;
RETURN jsonb_build_object(
'already_absent', NOT v_was_found,
'affected_group_ids', CASE WHEN p_group_id IS NOT NULL
THEN jsonb_build_array(p_group_id)
ELSE '[]'::jsonb END,
'challenge_updates', '[]'::jsonb
);
END IF;
v_secs := GREATEST(0, p_duration_minutes) * 60;
v_hrs := round(p_duration_minutes::numeric / 60, 4);
-- Insert session log β skip silently on duplicate
INSERT INTO public.study_sessions_log
(id, user_id, duration_minutes, started_at, ended_at, subject, notes)
VALUES (
p_session_id,
v_uid,
p_duration_minutes,
COALESCE(p_ended_at, now()) - (p_duration_minutes || ' minutes')::interval,
COALESCE(p_ended_at, now()),
p_session_type,
p_notes
)
ON CONFLICT (id) DO NOTHING;
GET DIAGNOSTICS v_row_count = ROW_COUNT;
IF v_row_count = 0 THEN
-- Already processed: don't double-count stats
RETURN jsonb_build_object(
'already_processed', true,
'affected_group_ids', '[]'::jsonb,
'challenge_updates', '[]'::jsonb
);
END IF;
-- Upsert daily stats
INSERT INTO public.daily_user_stats (user_id, date, seconds_studied)
VALUES (v_uid, v_today, v_secs)
ON CONFLICT (user_id, date) DO UPDATE
SET seconds_studied = daily_user_stats.seconds_studied + EXCLUDED.seconds_studied;
-- Update running totals in user_stats_summary
INSERT INTO public.user_stats_summary
(user_id, total_study_seconds, total_hours, weekly_hours, monthly_hours,
session_count, total_sessions, last_session_at, last_study_date, updated_at)
VALUES
(v_uid, v_secs, v_hrs, v_hrs, v_hrs, 1, 1,
COALESCE(p_ended_at, now()), v_today, now())
ON CONFLICT (user_id) DO UPDATE SET
total_study_seconds = user_stats_summary.total_study_seconds + v_secs,
total_hours = round((user_stats_summary.total_study_seconds + v_secs)::numeric / 3600, 2),
weekly_hours = user_stats_summary.weekly_hours + v_hrs,
monthly_hours = user_stats_summary.monthly_hours + v_hrs,
session_count = user_stats_summary.session_count + 1,
total_sessions = user_stats_summary.total_sessions + 1,
last_session_at = COALESCE(p_ended_at, now()),
last_study_date = v_today,
updated_at = now();
RETURN jsonb_build_object(
'already_processed', false,
'affected_group_ids', CASE WHEN p_group_id IS NOT NULL
THEN jsonb_build_array(p_group_id)
ELSE '[]'::jsonb END,
'challenge_updates', '[]'::jsonb
);
END;
$$;
-- ββ 27. GRANT EXECUTE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
GRANT EXECUTE ON FUNCTION public.is_premium_user(uuid)
TO anon, authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.get_invite_details(text)
TO anon, authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.accept_invite(text)
TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.get_membership_snapshot(uuid, uuid)
TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.get_group_analytics_from_snapshots(uuid, integer)
TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.get_leaderboard(text, integer, integer)
TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.get_group_leaderboard(uuid, integer)
TO authenticated, service_role;
GRANT EXECUTE ON FUNCTION public.finish_session_sync(uuid, text, integer, uuid, text, text, timestamptz)
TO authenticated, service_role;
-- ββ 27. RLS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-- Note: server.mjs injects the service_role key which bypasses all RLS.
-- These policies protect any direct anon/authenticated client access.
ALTER TABLE public.users ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_points ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_stats_summary ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.daily_user_stats ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.study_sessions_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.store_items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_inventory ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_presence ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_members ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_chat_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_challenges ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_challenge_participants ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_announcements ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_invites ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.group_milestones ENABLE ROW LEVEL SECURITY;
DO $$ BEGIN
-- users: public read (for avatar/username display); own row for writes
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='users' AND policyname='users_read_public') THEN
CREATE POLICY users_read_public ON public.users FOR SELECT USING (true);
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='users' AND policyname='users_own') THEN
CREATE POLICY users_own ON public.users
FOR ALL USING (id = auth.uid()) WITH CHECK (id = auth.uid());
END IF;
-- user_profiles
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_profiles' AND policyname='profiles_own') THEN
CREATE POLICY profiles_own ON public.user_profiles
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- user_points: all read (leaderboard); own write
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_points' AND policyname='points_read_all') THEN
CREATE POLICY points_read_all ON public.user_points FOR SELECT USING (true);
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_points' AND policyname='points_own_write') THEN
CREATE POLICY points_own_write ON public.user_points
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- user_stats_summary: all read (leaderboard); own write
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_stats_summary' AND policyname='stats_read_all') THEN
CREATE POLICY stats_read_all ON public.user_stats_summary FOR SELECT USING (true);
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_stats_summary' AND policyname='stats_own_write') THEN
CREATE POLICY stats_own_write ON public.user_stats_summary
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- daily_user_stats: own rows
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='daily_user_stats' AND policyname='daily_own') THEN
CREATE POLICY daily_own ON public.daily_user_stats
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- study_sessions_log: own rows
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='study_sessions_log' AND policyname='sessions_own') THEN
CREATE POLICY sessions_own ON public.study_sessions_log
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- store_items: all read
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='store_items' AND policyname='store_read_all') THEN
CREATE POLICY store_read_all ON public.store_items FOR SELECT USING (true);
END IF;
-- user_inventory: own rows
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_inventory' AND policyname='inventory_own') THEN
CREATE POLICY inventory_own ON public.user_inventory
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- notifications: own rows
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='notifications' AND policyname='notif_own') THEN
CREATE POLICY notif_own ON public.notifications
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- user_presence: all auth read; own write
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_presence' AND policyname='presence_read_auth') THEN
CREATE POLICY presence_read_auth ON public.user_presence
FOR SELECT USING (auth.role() = 'authenticated');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='user_presence' AND policyname='presence_own_write') THEN
CREATE POLICY presence_own_write ON public.user_presence
FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid());
END IF;
-- groups: public groups readable; members can read private ones; owner writes
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='groups' AND policyname='groups_read_public') THEN
CREATE POLICY groups_read_public ON public.groups
FOR SELECT USING (is_public = true AND deleted_at IS NULL);
END IF;
-- Always drop+recreate to avoid recursive subquery on group_members
DROP POLICY IF EXISTS groups_member_read ON public.groups;
CREATE POLICY groups_member_read ON public.groups
FOR SELECT USING (public._is_group_member(id, auth.uid()));
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='groups' AND policyname='groups_auth_insert') THEN
CREATE POLICY groups_auth_insert ON public.groups
FOR INSERT WITH CHECK (auth.role() = 'authenticated');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='groups' AND policyname='groups_owner_update') THEN
CREATE POLICY groups_owner_update ON public.groups
FOR UPDATE USING (owner_id = auth.uid()) WITH CHECK (owner_id = auth.uid());
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE tablename='groups' AND policyname='groups_owner_delete') THEN
CREATE POLICY groups_owner_delete ON public.groups
FOR DELETE USING (owner_id = auth.uid());
END IF;