-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathlocal_schema.sql
More file actions
4500 lines (2377 loc) · 163 KB
/
local_schema.sql
File metadata and controls
4500 lines (2377 loc) · 163 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
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
CREATE EXTENSION IF NOT EXISTS "pg_net" WITH SCHEMA "extensions";
CREATE EXTENSION IF NOT EXISTS "pgsodium";
COMMENT ON SCHEMA "public" IS 'standard public schema';
CREATE EXTENSION IF NOT EXISTS "pg_graphql" WITH SCHEMA "graphql";
CREATE EXTENSION IF NOT EXISTS "pg_stat_statements" WITH SCHEMA "extensions";
CREATE EXTENSION IF NOT EXISTS "pgcrypto" WITH SCHEMA "extensions";
CREATE EXTENSION IF NOT EXISTS "pgjwt" WITH SCHEMA "extensions";
CREATE EXTENSION IF NOT EXISTS "supabase_vault" WITH SCHEMA "vault";
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA "extensions";
CREATE TYPE "public"."dialectic_stage_enum" AS ENUM (
'THESIS',
'ANTITHESIS',
'SYNTHESIS',
'PARENTHESIS',
'PARALYSIS'
);
ALTER TYPE "public"."dialectic_stage_enum" OWNER TO "postgres";
CREATE TYPE "public"."org_token_usage_policy_enum" AS ENUM (
'member_tokens',
'organization_tokens'
);
ALTER TYPE "public"."org_token_usage_policy_enum" OWNER TO "postgres";
CREATE TYPE "public"."user_role" AS ENUM (
'user',
'admin'
);
ALTER TYPE "public"."user_role" OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."begin_transaction"() RETURNS "text"
LANGUAGE "plpgsql"
SET "search_path" TO ''
AS $$
BEGIN
RETURN 'Transaction block conceptually started. Client must manage actual transaction lifecycle.';
END;
$$;
ALTER FUNCTION "public"."begin_transaction"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."can_select_chat"("check_chat_id" "uuid") RETURNS boolean
LANGUAGE "sql" SECURITY DEFINER
SET "search_path" TO ''
SET "jit" TO 'off'
AS $$
SELECT EXISTS (
SELECT 1
FROM public.chats c
WHERE c.id = check_chat_id
AND (
-- Case 1: Personal chat, user is the owner
(c.organization_id IS NULL AND c.user_id = auth.uid()) OR
-- Case 2: Organization chat, user is a member of that organization
(c.organization_id IS NOT NULL AND public.is_org_member(c.organization_id, auth.uid(), 'active'))
)
);
$$;
ALTER FUNCTION "public"."can_select_chat"("check_chat_id" "uuid") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."check_existing_member_by_email"("target_org_id" "uuid", "target_email" "text") RETURNS TABLE("membership_status" "text")
LANGUAGE "plpgsql" STABLE SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
target_user_id uuid;
BEGIN
-- 1. Find user_id from email
SELECT id INTO target_user_id FROM auth.users WHERE email = target_email LIMIT 1;
-- 2. If user_id found, check membership status in the target org
IF target_user_id IS NOT NULL THEN
RETURN QUERY
SELECT om.status
FROM public.organization_members om
WHERE om.organization_id = target_org_id
AND om.user_id = target_user_id
AND om.status IN ('active', 'pending'); -- Check for active or pending join request
END IF;
-- If user_id not found or no matching membership, return empty set
RETURN;
END;
$$;
ALTER FUNCTION "public"."check_existing_member_by_email"("target_org_id" "uuid", "target_email" "text") OWNER TO "postgres";
COMMENT ON FUNCTION "public"."check_existing_member_by_email"("target_org_id" "uuid", "target_email" "text") IS 'Checks if an email is already associated with an organization as an active member or has a pending join request. Runs with definer privileges to query auth.users.';
CREATE OR REPLACE FUNCTION "public"."check_last_admin"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
v_organization_id UUID;
v_is_admin_being_removed BOOLEAN;
v_other_admin_count INTEGER;
BEGIN
IF auth.role() = 'service_role' THEN
IF TG_OP = 'DELETE' THEN
RETURN OLD;
ELSE
RETURN NEW;
END IF;
END IF;
IF TG_OP = 'DELETE' THEN
v_organization_id := OLD.organization_id;
ELSE
v_organization_id := NEW.organization_id;
END IF;
IF EXISTS (SELECT 1 FROM public.organizations WHERE id = v_organization_id AND deleted_at IS NOT NULL) THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
END IF;
v_is_admin_being_removed := (
TG_OP = 'DELETE' AND OLD.role = 'admin' AND OLD.status = 'active'
) OR (
TG_OP = 'UPDATE' AND
OLD.role = 'admin' AND OLD.status = 'active' AND
(NEW.role <> 'admin' OR NEW.status <> 'active')
);
IF NOT v_is_admin_being_removed THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
END IF;
SELECT count(*)
INTO v_other_admin_count
FROM public.organization_members om
JOIN public.organizations o ON om.organization_id = o.id
WHERE om.organization_id = v_organization_id
AND om.role = 'admin'
AND om.status = 'active'
AND o.deleted_at IS NULL
AND om.id <> OLD.id;
IF v_other_admin_count = 0 THEN
RAISE EXCEPTION 'Cannot remove or demote the last admin of organization %', v_organization_id;
END IF;
IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
END;
$$;
ALTER FUNCTION "public"."check_last_admin"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."check_org_chat_creation_permission"("p_org_id" "uuid", "p_user_id" "uuid") RETURNS boolean
LANGUAGE "plpgsql" STABLE SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
can_create BOOLEAN;
BEGIN
SELECT EXISTS (
SELECT 1
FROM public.organizations o
JOIN public.organization_members om ON o.id = om.organization_id
WHERE o.id = p_org_id
AND om.user_id = p_user_id
AND om.status = 'active'
AND (
om.role = 'admin'
OR
o.allow_member_chat_creation = true
)
) INTO can_create;
RETURN can_create;
END;
$$;
ALTER FUNCTION "public"."check_org_chat_creation_permission"("p_org_id" "uuid", "p_user_id" "uuid") OWNER TO "postgres";
COMMENT ON FUNCTION "public"."check_org_chat_creation_permission"("p_org_id" "uuid", "p_user_id" "uuid") IS 'Checks if a given active user is permitted to create a chat in a specific organization.';
CREATE OR REPLACE FUNCTION "public"."create_notification_for_user"("target_user_id" "uuid", "notification_type" "text", "notification_data" "jsonb") RETURNS "void"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
BEGIN
INSERT INTO public.notifications (user_id, type, data)
VALUES (target_user_id, notification_type, notification_data);
END;
$$;
ALTER FUNCTION "public"."create_notification_for_user"("target_user_id" "uuid", "notification_type" "text", "notification_data" "jsonb") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."create_org_and_admin_member"("p_user_id" "uuid", "p_org_name" "text", "p_org_visibility" "text") RETURNS "uuid"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
new_org_id uuid;
BEGIN
-- Insert the new organization
INSERT INTO public.organizations (name, visibility)
VALUES (p_org_name, p_org_visibility)
RETURNING id INTO new_org_id;
-- Insert the creating user as the initial admin member
INSERT INTO public.organization_members (user_id, organization_id, role, status)
VALUES (p_user_id, new_org_id, 'admin', 'active');
-- Return the new organization's ID
RETURN new_org_id;
EXCEPTION
WHEN OTHERS THEN
-- Log the error and re-raise it to ensure the transaction is rolled back
RAISE WARNING 'Error in create_org_and_admin_member: SQLSTATE: %, MESSAGE: %', SQLSTATE, SQLERRM;
RAISE;
END;
$$;
ALTER FUNCTION "public"."create_org_and_admin_member"("p_user_id" "uuid", "p_org_name" "text", "p_org_visibility" "text") OWNER TO "postgres";
COMMENT ON FUNCTION "public"."create_org_and_admin_member"("p_user_id" "uuid", "p_org_name" "text", "p_org_visibility" "text") IS 'Creates a new organization and adds the specified user as the initial admin member within a single transaction. Returns the new organization ID.';
CREATE OR REPLACE FUNCTION "public"."delete_chat_and_messages"("p_chat_id" "uuid", "p_user_id" "uuid") RETURNS "text"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
v_chat_owner_id uuid;
v_chat_org_id uuid;
v_user_role text;
BEGIN
-- 1. Check if the chat exists and get owner/org info
SELECT user_id, organization_id INTO v_chat_owner_id, v_chat_org_id
FROM public.chats
WHERE id = p_chat_id;
IF NOT FOUND THEN
RETURN 'NOT FOUND';
END IF;
-- 2. Permission Check
IF v_chat_org_id IS NOT NULL THEN
-- Organization chat
SELECT role INTO v_user_role
FROM public.organization_members
WHERE organization_id = v_chat_org_id AND user_id = p_user_id AND status = 'active';
IF v_user_role IS NULL OR NOT (v_user_role = 'admin' OR v_chat_owner_id = p_user_id) THEN
RETURN 'ORG PERMISSION DENIED';
END IF;
ELSE
-- Personal chat
IF v_chat_owner_id IS DISTINCT FROM p_user_id THEN
RETURN 'PERSONAL PERMISSION DENIED';
END IF;
END IF;
-- 3. Perform Deletions
DELETE FROM public.chat_messages WHERE chat_id = p_chat_id;
DELETE FROM public.chats WHERE id = p_chat_id;
RETURN 'DELETED';
END;
$$;
ALTER FUNCTION "public"."delete_chat_and_messages"("p_chat_id" "uuid", "p_user_id" "uuid") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."delete_chat_and_messages_debug"("p_chat_id" "uuid", "p_user_id" "uuid") RETURNS "text"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
v_chat_owner_id uuid;
v_chat_org_id uuid;
v_user_role text;
BEGIN
-- 1. Check if the chat exists and get owner/org info
SELECT user_id, organization_id INTO v_chat_owner_id, v_chat_org_id
FROM public.chats
WHERE id = p_chat_id;
IF NOT FOUND THEN
RETURN 'NOT FOUND';
END IF;
-- 2. Permission Check
IF v_chat_org_id IS NOT NULL THEN
-- Organization chat
SELECT role INTO v_user_role
FROM public.organization_members
WHERE organization_id = v_chat_org_id AND user_id = p_user_id AND status = 'active';
IF NOT (v_user_role = 'admin' OR v_chat_owner_id = p_user_id) THEN
RETURN 'ORG PERMISSION DENIED';
END IF;
ELSE
-- Personal chat
IF v_chat_owner_id IS DISTINCT FROM p_user_id THEN
RETURN 'PERSONAL PERMISSION DENIED';
END IF;
END IF;
-- 3. Perform Deletions
DELETE FROM public.chat_messages WHERE chat_id = p_chat_id;
DELETE FROM public.chats WHERE id = p_chat_id;
RETURN 'DELETED';
END;
$$;
ALTER FUNCTION "public"."delete_chat_and_messages_debug"("p_chat_id" "uuid", "p_user_id" "uuid") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."enforce_chat_update_restrictions"() RETURNS "trigger"
LANGUAGE "plpgsql"
SET "search_path" TO ''
AS $$
BEGIN
IF NEW.user_id <> OLD.user_id THEN
RAISE EXCEPTION 'Changing the user_id of a chat is not allowed.';
END IF;
IF NEW.organization_id IS DISTINCT FROM OLD.organization_id THEN
RAISE EXCEPTION 'Changing the organization_id of a chat is not allowed.';
END IF;
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."enforce_chat_update_restrictions"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."execute_sql"("query" "text") RETURNS SETOF "json"
LANGUAGE "plpgsql"
SET "search_path" TO ''
AS $$
DECLARE
constructed_query TEXT;
BEGIN
constructed_query := 'SELECT row_to_json(t) FROM (' || query || ') t';
RETURN QUERY EXECUTE constructed_query;
END;
$$;
ALTER FUNCTION "public"."execute_sql"("query" "text") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."grant_initial_free_tokens_to_user"("p_user_id" "uuid", "p_free_plan_id" "uuid") RETURNS "void"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
v_tokens_to_award NUMERIC;
v_target_wallet_id uuid;
v_system_user_id uuid;
BEGIN
BEGIN
SELECT system_user_id INTO v_system_user_id FROM _vars LIMIT 1;
IF v_system_user_id IS NULL THEN
RAISE EXCEPTION '[grant_initial_free_tokens_to_user] System user ID is not set in _vars. This table should be populated by the calling migration.';
END IF;
EXCEPTION
WHEN undefined_table THEN
RAISE EXCEPTION '[grant_initial_free_tokens_to_user] _vars temp table not found. It must be created and populated with system_user_id by the calling migration.';
END;
SELECT tokens_to_award INTO v_tokens_to_award
FROM public.subscription_plans
WHERE id = p_free_plan_id AND name = 'Free';
IF v_tokens_to_award IS NULL OR v_tokens_to_award <= 0 THEN
RAISE WARNING '[grant_initial_free_tokens_to_user] Free plan ID % (user %) not found or has no tokens to award.', p_free_plan_id, p_user_id;
RETURN;
END IF;
SELECT wallet_id INTO v_target_wallet_id
FROM public.token_wallets
WHERE user_id = p_user_id AND organization_id IS NULL;
IF v_target_wallet_id IS NULL THEN
RAISE WARNING '[grant_initial_free_tokens_to_user] Token wallet not found for user ID %.', p_user_id;
RETURN;
END IF;
PERFORM public.record_token_transaction(
p_wallet_id := v_target_wallet_id,
p_transaction_type := 'CREDIT_INITIAL_FREE_ALLOCATION',
p_input_amount_text := v_tokens_to_award::TEXT,
p_recorded_by_user_id := v_system_user_id,
p_idempotency_key := 'initial_free_' || p_user_id::text || '_' || p_free_plan_id::text,
p_related_entity_id := p_free_plan_id::VARCHAR,
p_related_entity_type := 'subscription_plans',
p_notes := 'Initial token allocation for new free plan user.',
p_payment_transaction_id := NULL
);
RAISE LOG '[grant_initial_free_tokens_to_user] Successfully called record_token_transaction for user % (tokens: %).', p_user_id, v_tokens_to_award;
EXCEPTION
WHEN OTHERS THEN
RAISE WARNING '[grant_initial_free_tokens_to_user] Error awarding tokens to user %: %', p_user_id, SQLERRM;
END;
$$;
ALTER FUNCTION "public"."grant_initial_free_tokens_to_user"("p_user_id" "uuid", "p_free_plan_id" "uuid") OWNER TO "postgres";
COMMENT ON FUNCTION "public"."grant_initial_free_tokens_to_user"("p_user_id" "uuid", "p_free_plan_id" "uuid") IS 'CORRECTED VERSION. Grants initial tokens to a new user for the free plan by calling record_token_transaction, using system_user_id from _vars.';
CREATE OR REPLACE FUNCTION "public"."handle_member_removed"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
org_name TEXT;
is_org_deleted BOOLEAN;
BEGIN
-- Check if the organization is soft-deleted (though removal might still happen)
SELECT deleted_at IS NOT NULL, name
INTO is_org_deleted, org_name
FROM public.organizations
WHERE id = NEW.organization_id; -- Use NEW or OLD, should be same org
IF NOT FOUND THEN
-- Org might be hard deleted? Or FK constraint failed?
-- For now, just exit gracefully if org not found.
RETURN NULL;
END IF;
-- Create notification for the removed user
PERFORM public.create_notification_for_user(
NEW.user_id,
'org_membership_removed',
jsonb_build_object(
'organization_id', NEW.organization_id,
'organization_name', org_name,
'target_path', '/dashboard/organizations' -- General path after removal
)
);
RETURN NULL;
END;
$$;
ALTER FUNCTION "public"."handle_member_removed"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."handle_member_role_change"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
org_name TEXT;
is_org_deleted BOOLEAN;
BEGIN
-- Check if the organization is soft-deleted
SELECT deleted_at IS NOT NULL, name
INTO is_org_deleted, org_name
FROM public.organizations
WHERE id = NEW.organization_id;
-- Only proceed if the organization exists and is not deleted
IF NOT FOUND OR is_org_deleted THEN
RETURN NULL;
END IF;
-- Create notification for the affected user
PERFORM public.create_notification_for_user(
NEW.user_id,
'org_role_changed',
jsonb_build_object(
'organization_id', NEW.organization_id,
'organization_name', org_name,
'old_role', OLD.role,
'new_role', NEW.role,
'target_path', '/dashboard/organizations/' || NEW.organization_id::text || '/settings'
)
);
RETURN NULL;
END;
$$;
ALTER FUNCTION "public"."handle_member_role_change"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."handle_new_invite_notification"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
invited_user_id uuid;
organization_name text;
inviter_name text;
full_name text;
BEGIN
-- Find the user_id associated with the invited email
SELECT id INTO invited_user_id FROM auth.users WHERE email = NEW.invited_email;
-- Only proceed if the user exists in auth.users
IF invited_user_id IS NOT NULL THEN
-- Get organization name
SELECT name INTO organization_name FROM public.organizations WHERE id = NEW.organization_id;
-- Get inviter name (optional, use email if profile/name not found)
SELECT
TRIM(p.first_name || ' ' || p.last_name),
u.email
INTO
full_name,
inviter_name
FROM auth.users u
LEFT JOIN public.user_profiles p ON u.id = p.id
WHERE u.id = NEW.invited_by_user_id;
IF full_name IS NOT NULL AND full_name <> '' THEN
inviter_name := full_name;
END IF;
INSERT INTO public.notifications (user_id, type, data)
VALUES (
invited_user_id,
'organization_invite',
jsonb_build_object(
'subject', 'Organization Invitation',
'message', COALESCE(inviter_name, 'Someone') || ' has invited you to join ' || COALESCE(organization_name, 'an organization') || ' as a ' || NEW.role_to_assign || '.',
'target_path', '/accept-invite/' || NEW.invite_token,
'organization_id', NEW.organization_id,
'organization_name', organization_name,
'invite_id', NEW.id,
'invite_token', NEW.invite_token,
'inviter_id', NEW.invited_by_user_id,
'inviter_name', inviter_name,
'assigned_role', NEW.role_to_assign
)
);
ELSE
RAISE LOG 'Invited user with email % not found in auth.users, no notification created.', NEW.invited_email;
END IF;
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."handle_new_invite_notification"() OWNER TO "postgres";
COMMENT ON FUNCTION "public"."handle_new_invite_notification"() IS 'Handles inserting a notification when a new pending invite is created.';
CREATE OR REPLACE FUNCTION "public"."handle_new_join_request"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
admin_record RECORD;
org_name TEXT;
is_org_deleted BOOLEAN;
BEGIN
-- Check if the organization is soft-deleted
SELECT deleted_at IS NOT NULL, name
INTO is_org_deleted, org_name
FROM public.organizations
WHERE id = NEW.organization_id;
-- Only proceed if the organization exists and is not deleted
IF NOT FOUND OR is_org_deleted THEN
RETURN NULL;
END IF;
-- Find all active admins of this organization
FOR admin_record IN
SELECT user_id
FROM public.organization_members
WHERE organization_id = NEW.organization_id
AND role = 'admin'
AND status = 'active'
LOOP
-- Create notification for each admin
PERFORM public.create_notification_for_user(
admin_record.user_id,
'org_join_request',
jsonb_build_object(
'requesting_user_id', NEW.user_id,
'organization_id', NEW.organization_id,
'organization_name', org_name,
'membership_id', NEW.id,
'target_path', '/dashboard/organizations/' || NEW.organization_id::text || '/members?action=review&memberId=' || NEW.id::text
)
);
END LOOP;
RETURN NULL;
END;
$$;
ALTER FUNCTION "public"."handle_new_join_request"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."handle_new_organization"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
BEGIN
INSERT INTO public.token_wallets (organization_id)
VALUES (NEW.id)
ON CONFLICT (organization_id) WHERE user_id IS NULL DO NOTHING;
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."handle_new_organization"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."handle_new_user"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
v_user_id UUID := NEW.id;
v_user_email TEXT := NEW.email;
v_raw_user_meta_data JSONB := NEW.raw_user_meta_data;
v_profile_first_name TEXT;
v_free_plan_id UUID;
v_tokens_to_award NUMERIC;
v_target_wallet_id UUID;
v_current_wallet_balance NUMERIC;
v_new_wallet_balance NUMERIC;
v_system_user_id UUID;
v_system_user_email_pattern TEXT := 'system-token-allocator-%@internal.app';
v_idempotency_key_grant TEXT;
BEGIN
RAISE LOG '[handle_new_user] Processing new user ID: %, Email: %', v_user_id, v_user_email;
v_profile_first_name := v_raw_user_meta_data ->> 'first_name';
INSERT INTO public.user_profiles (id, role, first_name)
VALUES (v_user_id, 'user', v_profile_first_name)
ON CONFLICT (id) DO NOTHING;
RAISE LOG '[handle_new_user] Ensured profile for user ID: %.', v_user_id;
INSERT INTO public.token_wallets (user_id, currency)
VALUES (v_user_id, 'AI_TOKEN')
ON CONFLICT (user_id) WHERE organization_id IS NULL
DO NOTHING
RETURNING wallet_id INTO v_target_wallet_id;
IF v_target_wallet_id IS NULL THEN
SELECT wallet_id INTO v_target_wallet_id
FROM public.token_wallets
WHERE user_id = v_user_id AND organization_id IS NULL;
END IF;
IF v_target_wallet_id IS NULL THEN
RAISE WARNING '[handle_new_user] Failed to create or find personal wallet for user ID: %. Aborting token grant.', v_user_id;
RETURN NEW;
END IF;
RAISE LOG '[handle_new_user] Ensured wallet ID: % for user ID: %.', v_target_wallet_id, v_user_id;
SELECT id, tokens_to_award INTO v_free_plan_id, v_tokens_to_award
FROM public.subscription_plans
WHERE name = 'Free'
LIMIT 1;
IF v_free_plan_id IS NULL THEN
RAISE LOG '[handle_new_user] "Free" plan not found. No initial tokens will be granted for user ID: %.', v_user_id;
ELSIF v_tokens_to_award IS NULL OR v_tokens_to_award <= 0 THEN
RAISE LOG '[handle_new_user] "Free" plan (ID: %) found, but tokens_to_award is not positive (Value: %). No initial tokens for user ID: %.', v_free_plan_id, v_tokens_to_award, v_user_id;
ELSE
RAISE LOG '[handle_new_user] "Free" plan ID: % found with % tokens to award for user ID: %.', v_free_plan_id, v_tokens_to_award, v_user_id;
INSERT INTO public.user_subscriptions (user_id, plan_id, status, current_period_start, current_period_end)
VALUES (v_user_id, v_free_plan_id, 'free', NOW(), NOW() + interval '1 month')
ON CONFLICT (user_id)
DO UPDATE SET plan_id = EXCLUDED.plan_id, status = EXCLUDED.status, updated_at = NOW(), current_period_start = EXCLUDED.current_period_start, current_period_end = EXCLUDED.current_period_end
WHERE public.user_subscriptions.status <> 'free';
RAISE LOG '[handle_new_user] Ensured user % subscribed to Free plan %.', v_user_id, v_free_plan_id;
SELECT id INTO v_system_user_id FROM auth.users WHERE email LIKE v_system_user_email_pattern ORDER BY created_at DESC LIMIT 1;
IF v_system_user_id IS NULL THEN
RAISE WARNING '[handle_new_user] System user for token allocation (pattern: %) not found. Grant for user % will be recorded by the user themselves.', v_system_user_email_pattern, v_user_id;
END IF;
v_idempotency_key_grant := 'initial_free_grant_' || v_user_id::text || '_' || v_free_plan_id::text;
IF EXISTS (SELECT 1 FROM public.token_wallet_transactions WHERE wallet_id = v_target_wallet_id AND idempotency_key = v_idempotency_key_grant) THEN
RAISE LOG '[handle_new_user] Initial free tokens (Plan ID: %) already granted to user ID: % (Wallet: %) via idempotency key: %.', v_free_plan_id, v_user_id, v_target_wallet_id, v_idempotency_key_grant;
ELSE
RAISE LOG '[handle_new_user] Attempting to grant % tokens to wallet % for user % by system user (or self): %.', v_tokens_to_award, v_target_wallet_id, v_user_id, COALESCE(v_system_user_id, v_user_id);
BEGIN
SELECT balance INTO v_current_wallet_balance FROM public.token_wallets WHERE wallet_id = v_target_wallet_id FOR UPDATE;
v_new_wallet_balance := v_current_wallet_balance + v_tokens_to_award;
UPDATE public.token_wallets SET balance = v_new_wallet_balance, updated_at = now() WHERE public.token_wallets.wallet_id = v_target_wallet_id;
INSERT INTO public.token_wallet_transactions (
wallet_id, transaction_type, amount, balance_after_txn,
recorded_by_user_id, related_entity_id, related_entity_type, notes, idempotency_key
)
VALUES (
v_target_wallet_id, 'CREDIT_INITIAL_FREE_ALLOCATION', v_tokens_to_award, v_new_wallet_balance,
COALESCE(v_system_user_id, v_user_id),
v_free_plan_id::TEXT, 'subscription_plans', 'Initial token allocation for new free plan user.', v_idempotency_key_grant
);
RAISE LOG '[handle_new_user] Successfully granted % tokens to wallet % (User ID: %). New balance: %.', v_tokens_to_award, v_target_wallet_id, v_user_id, v_new_wallet_balance;
EXCEPTION
WHEN OTHERS THEN
RAISE WARNING '[handle_new_user] Error during token grant transaction for user ID %: %.', v_user_id, SQLERRM;
END;
END IF;
END IF;
RETURN NEW;
EXCEPTION
WHEN OTHERS THEN
RAISE WARNING '[handle_new_user] Unexpected error for user ID % (Email: %): %.', COALESCE(v_user_id, 'UNKNOWN_USER_ID'), COALESCE(v_user_email, 'UNKNOWN_EMAIL'), SQLERRM;
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."handle_new_user"() OWNER TO "postgres";
COMMENT ON FUNCTION "public"."handle_new_user"() IS 'Handles new user setup: profile, wallet, Free plan subscription, and initial free tokens. V3 - Consolidated & Idempotent.';
CREATE OR REPLACE FUNCTION "public"."handle_placeholder_event"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
example_admin_id UUID;
example_requesting_user_id UUID;
example_org_id UUID;
BEGIN
example_admin_id := auth.uid();
example_requesting_user_id := '00000000-0000-0000-0000-000000000001';
example_org_id := '00000000-0000-0000-0000-000000000002';
PERFORM public.create_notification_for_user(
example_admin_id,
'join_request',
jsonb_build_object(
'requesting_user_id', example_requesting_user_id,
'organization_id', example_org_id,
'target_path', '/dashboard/organizations/' || example_org_id::text || '/members?action=review&user=' || example_requesting_user_id::text
)
);
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."handle_placeholder_event"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."handle_updated_at"() RETURNS "trigger"
LANGUAGE "plpgsql"
SET "search_path" TO ''
AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."handle_updated_at"() OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."is_admin_of_org_for_wallet"("p_organization_id" "uuid") RETURNS boolean
LANGUAGE "sql" STABLE SECURITY DEFINER
SET "search_path" TO ''
AS $$
SELECT EXISTS (
SELECT 1
FROM public.organization_members om
WHERE om.organization_id = p_organization_id
AND om.user_id = auth.uid()
AND om.role::text = 'admin'
AND om.status::text = 'active'
);
$$;
ALTER FUNCTION "public"."is_admin_of_org_for_wallet"("p_organization_id" "uuid") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."is_org_admin"("org_id" "uuid") RETURNS boolean
LANGUAGE "plpgsql" STABLE SECURITY DEFINER
SET "search_path" TO ''
AS $$
BEGIN
-- Check if the organization exists and is not deleted
IF NOT EXISTS (SELECT 1 FROM public.organizations WHERE id = org_id AND deleted_at IS NULL) THEN
RETURN FALSE;
END IF;
-- Check if the current user is an active admin member of the organization
RETURN EXISTS (
SELECT 1
FROM public.organization_members om
WHERE om.organization_id = org_id
AND om.user_id = (SELECT auth.uid())
AND om.role = 'admin'
AND om.status = 'active'
);
END;
$$;
ALTER FUNCTION "public"."is_org_admin"("org_id" "uuid") OWNER TO "postgres";
COMMENT ON FUNCTION "public"."is_org_admin"("org_id" "uuid") IS 'Checks if the current authenticated user is an active admin of the specified non-deleted organization.';
CREATE OR REPLACE FUNCTION "public"."is_org_member"("p_org_id" "uuid", "p_user_id" "uuid", "required_status" "text", "required_role" "text" DEFAULT NULL::"text") RETURNS boolean
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
is_member BOOLEAN;
BEGIN
SELECT EXISTS (
SELECT 1
FROM public.organization_members om
JOIN public.organizations o ON om.organization_id = o.id
WHERE om.organization_id = p_org_id
AND om.user_id = p_user_id
AND om.status = required_status
AND (required_role IS NULL OR om.role = required_role)
AND o.deleted_at IS NULL
) INTO is_member;
RETURN is_member;
END;
$$;
ALTER FUNCTION "public"."is_org_member"("p_org_id" "uuid", "p_user_id" "uuid", "required_status" "text", "required_role" "text") OWNER TO "postgres";
CREATE OR REPLACE FUNCTION "public"."link_pending_invites_on_signup"() RETURNS "trigger"
LANGUAGE "plpgsql" SECURITY DEFINER
SET "search_path" TO ''
AS $$
DECLARE
invite_record RECORD;
BEGIN
IF NEW.email IS NOT NULL THEN
FOR invite_record IN
SELECT id, organization_id, role_to_assign
FROM public.invites
WHERE invited_email = NEW.email
AND invited_user_id IS NULL
AND status = 'pending'
LOOP
UPDATE public.invites
SET
invited_user_id = NEW.id,
status = 'accepted'
WHERE id = invite_record.id;
INSERT INTO public.organization_members (user_id, organization_id, role, status)
VALUES (NEW.id, invite_record.organization_id, invite_record.role_to_assign, 'active')
ON CONFLICT (user_id, organization_id) DO UPDATE
SET role = EXCLUDED.role, status = 'active';
END LOOP;
END IF;
RETURN NEW;
END;
$$;
ALTER FUNCTION "public"."link_pending_invites_on_signup"() OWNER TO "postgres";
COMMENT ON FUNCTION "public"."link_pending_invites_on_signup"() IS 'Re-applied: Automatically links pending invites, creates an organization_members record with an active status, and updates the invite status to accepted for a newly signed-up user based on matching email address. Ensures no SET LOCAL ROLE is present.';
CREATE OR REPLACE FUNCTION "public"."perform_chat_rewind"("p_chat_id" "uuid", "p_rewind_from_message_id" "uuid", "p_user_id" "uuid", "p_new_user_message_content" "text", "p_new_user_message_ai_provider_id" "uuid", "p_new_assistant_message_content" "text", "p_new_assistant_message_ai_provider_id" "uuid", "p_new_user_message_system_prompt_id" "uuid" DEFAULT NULL::"uuid", "p_new_assistant_message_token_usage" "jsonb" DEFAULT NULL::"jsonb", "p_new_assistant_message_system_prompt_id" "uuid" DEFAULT NULL::"uuid", "p_new_assistant_message_error_type" "text" DEFAULT NULL::"text") RETURNS TABLE("new_user_message_id" "uuid", "new_assistant_message_id" "uuid")
LANGUAGE "plpgsql"
SET "search_path" TO ''
AS $$