mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-10-31 18:19:43 +00:00
Initial commit
This commit is contained in:
commit
4d53d83769
73 files changed
+37728
No files matched your search
Executable
+51
@@ -0,0 +1,51 @@
|
||||
[project]
|
||||
id = "REPLACE_WITH_YOUR_PROJECT_ID"
|
||||
name = "Sauci"
|
||||
|
||||
[api]
|
||||
enabled = true
|
||||
port = 54321
|
||||
schemas = ["public", "graphql_public"]
|
||||
extra_search_path = ["public", "extensions"]
|
||||
max_rows = 1000
|
||||
|
||||
[db]
|
||||
port = 54322
|
||||
shadow_port = 54320
|
||||
major_version = 15
|
||||
|
||||
[studio]
|
||||
enabled = true
|
||||
port = 54323
|
||||
api_url = "http://localhost"
|
||||
|
||||
[auth]
|
||||
enabled = true
|
||||
site_url = "exp://localhost:8081"
|
||||
additional_redirect_urls = ["sauci://auth/callback"]
|
||||
jwt_expiry = 3600
|
||||
enable_refresh_token_rotation = true
|
||||
refresh_token_reuse_interval = 10
|
||||
enable_signup = true
|
||||
|
||||
[auth.external.google]
|
||||
enabled = true
|
||||
client_id = "env(GOOGLE_CLIENT_ID)"
|
||||
secret = "env(GOOGLE_CLIENT_SECRET)"
|
||||
|
||||
[auth.external.apple]
|
||||
enabled = true
|
||||
client_id = "env(APPLE_CLIENT_ID)"
|
||||
secret = "env(APPLE_CLIENT_SECRET)"
|
||||
|
||||
[auth.email]
|
||||
enable_signup = true
|
||||
double_confirm_changes = true
|
||||
enable_confirmations = false
|
||||
|
||||
[auth.sms]
|
||||
enable_signup = false
|
||||
enable_confirmations = false
|
||||
|
||||
[functions]
|
||||
verify_jwt = true
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
|
||||
};
|
||||
|
||||
interface JoinCoupleBody {
|
||||
invite_code: string;
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
// Handle CORS preflight
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get("SUPABASE_URL")!,
|
||||
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
|
||||
);
|
||||
|
||||
// Get user from JWT
|
||||
const authHeader = req.headers.get("Authorization");
|
||||
if (!authHeader) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Missing authorization header" }),
|
||||
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser(
|
||||
authHeader.replace("Bearer ", "")
|
||||
);
|
||||
|
||||
if (authError || !user) {
|
||||
console.error("Auth Error:", authError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: `Invalid token: ${authError?.message || 'No user found'}` }),
|
||||
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const method = req.method;
|
||||
|
||||
if (method === "POST") {
|
||||
// Check if user is already in a couple
|
||||
const { data: existingProfile } = await supabase
|
||||
.from("profiles")
|
||||
.select("couple_id")
|
||||
.eq("id", user.id)
|
||||
.single();
|
||||
|
||||
if (existingProfile?.couple_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "You are already in a couple" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
|
||||
if (body.invite_code) {
|
||||
// Join existing couple
|
||||
const { invite_code }: JoinCoupleBody = body;
|
||||
|
||||
// Find couple by invite code
|
||||
const { data: couple, error: coupleError } = await supabase
|
||||
.from("couples")
|
||||
.select("id")
|
||||
.eq("invite_code", invite_code.toLowerCase())
|
||||
.single();
|
||||
|
||||
if (coupleError || !couple) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Invalid invite code" }),
|
||||
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if couple already has 2 members
|
||||
const { count } = await supabase
|
||||
.from("profiles")
|
||||
.select("*", { count: "exact", head: true })
|
||||
.eq("couple_id", couple.id);
|
||||
|
||||
if (count && count >= 2) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "This couple already has two partners" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Update user's profile with couple_id
|
||||
const { error: updateError } = await supabase
|
||||
.from("profiles")
|
||||
.update({ couple_id: couple.id })
|
||||
.eq("id", user.id);
|
||||
|
||||
if (updateError) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to join couple" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, couple_id: couple.id }),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
} else {
|
||||
// Create new couple
|
||||
const { data: couple, error: createError } = await supabase
|
||||
.from("couples")
|
||||
.insert({})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (createError || !couple) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to create couple" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Update user's profile with couple_id
|
||||
await supabase
|
||||
.from("profiles")
|
||||
.update({ couple_id: couple.id })
|
||||
.eq("id", user.id);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
couple_id: couple.id,
|
||||
invite_code: couple.invite_code
|
||||
}),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (method === "DELETE") {
|
||||
// Leave couple
|
||||
const { error } = await supabase
|
||||
.from("profiles")
|
||||
.update({ couple_id: null })
|
||||
.eq("id", user.id);
|
||||
|
||||
if (error) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to leave couple" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true }),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Method not allowed" }),
|
||||
{ status: 405, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Internal server error" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
});
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
|
||||
};
|
||||
|
||||
interface NotificationBody {
|
||||
couple_id: string;
|
||||
match_id: string;
|
||||
}
|
||||
|
||||
interface ExpoPushMessage {
|
||||
to: string;
|
||||
title: string;
|
||||
body: string;
|
||||
sound?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function sendExpoPushNotifications(messages: ExpoPushMessage[]) {
|
||||
if (messages.length === 0) return;
|
||||
|
||||
const response = await fetch("https://exp.host/--/api/v2/push/send", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(messages),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.text();
|
||||
console.error("Expo push error:", error);
|
||||
throw new Error(`Failed to send push notification: ${error}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
// Handle CORS preflight
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get("SUPABASE_URL")!,
|
||||
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
|
||||
);
|
||||
|
||||
const { couple_id, match_id }: NotificationBody = await req.json();
|
||||
|
||||
if (!couple_id || !match_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Missing couple_id or match_id" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Get push tokens for both partners
|
||||
const { data: profiles, error: profilesError } = await supabase
|
||||
.from("profiles")
|
||||
.select("push_token, name")
|
||||
.eq("couple_id", couple_id)
|
||||
.not("push_token", "is", null);
|
||||
|
||||
if (profilesError) {
|
||||
console.error("Error fetching profiles:", profilesError);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to fetch profiles" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (!profiles || profiles.length === 0) {
|
||||
return new Response(
|
||||
JSON.stringify({ success: false, message: "No push tokens found" }),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Get match details for the notification
|
||||
const { data: match } = await supabase
|
||||
.from("matches")
|
||||
.select(`
|
||||
*,
|
||||
question:questions(text)
|
||||
`)
|
||||
.eq("id", match_id)
|
||||
.single();
|
||||
|
||||
// Build push messages
|
||||
const messages: ExpoPushMessage[] = profiles
|
||||
.filter((p) => p.push_token)
|
||||
.map((profile) => ({
|
||||
to: profile.push_token!,
|
||||
title: "It's a match! 💕",
|
||||
body: match?.question?.text
|
||||
? `You both agreed: "${match.question.text.substring(0, 50)}..."`
|
||||
: "You and your partner agreed on something new!",
|
||||
sound: "default",
|
||||
data: { match_id, type: "match" },
|
||||
}));
|
||||
|
||||
// Send notifications
|
||||
await sendExpoPushNotifications(messages);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ success: true, sent: messages.length }),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Internal server error" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
});
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
|
||||
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
|
||||
};
|
||||
|
||||
type Answer = "yes" | "no" | "maybe";
|
||||
type MatchType = "yes_yes" | "yes_maybe" | "maybe_maybe";
|
||||
|
||||
interface SubmitResponseBody {
|
||||
question_id: string;
|
||||
answer: Answer;
|
||||
}
|
||||
|
||||
function calculateMatch(a1: Answer, a2: Answer): MatchType | null {
|
||||
if (a1 === "no" || a2 === "no") return null;
|
||||
if (a1 === "yes" && a2 === "yes") return "yes_yes";
|
||||
if (a1 === "maybe" && a2 === "maybe") return "maybe_maybe";
|
||||
return "yes_maybe";
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
// Handle CORS preflight
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
const supabase = createClient(
|
||||
Deno.env.get("SUPABASE_URL")!,
|
||||
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
|
||||
);
|
||||
|
||||
// Get user from JWT
|
||||
const authHeader = req.headers.get("Authorization");
|
||||
if (!authHeader) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Missing authorization header" }),
|
||||
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const { data: { user }, error: authError } = await supabase.auth.getUser(
|
||||
authHeader.replace("Bearer ", "")
|
||||
);
|
||||
|
||||
if (authError || !user) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Invalid token" }),
|
||||
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
const { question_id, answer }: SubmitResponseBody = await req.json();
|
||||
|
||||
if (!question_id || !answer) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Missing question_id or answer" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Get user's profile and couple
|
||||
const { data: profile, error: profileError } = await supabase
|
||||
.from("profiles")
|
||||
.select("couple_id")
|
||||
.eq("id", user.id)
|
||||
.single();
|
||||
|
||||
if (profileError || !profile?.couple_id) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "User is not in a couple" }),
|
||||
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Save or update response
|
||||
const { data: response, error: responseError } = await supabase
|
||||
.from("responses")
|
||||
.upsert(
|
||||
{
|
||||
user_id: user.id,
|
||||
question_id,
|
||||
couple_id: profile.couple_id,
|
||||
answer,
|
||||
},
|
||||
{ onConflict: "user_id,question_id" }
|
||||
)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (responseError) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to save response", details: responseError }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
// Check for partner's response
|
||||
const { data: partnerResponse } = await supabase
|
||||
.from("responses")
|
||||
.select("answer")
|
||||
.eq("couple_id", profile.couple_id)
|
||||
.eq("question_id", question_id)
|
||||
.neq("user_id", user.id)
|
||||
.single();
|
||||
|
||||
let match = null;
|
||||
|
||||
if (partnerResponse) {
|
||||
const matchType = calculateMatch(answer, partnerResponse.answer as Answer);
|
||||
|
||||
if (matchType) {
|
||||
// Create or update match
|
||||
const { data: newMatch, error: matchError } = await supabase
|
||||
.from("matches")
|
||||
.upsert(
|
||||
{
|
||||
couple_id: profile.couple_id,
|
||||
question_id,
|
||||
match_type: matchType,
|
||||
is_new: true,
|
||||
},
|
||||
{ onConflict: "couple_id,question_id" }
|
||||
)
|
||||
.select(`
|
||||
*,
|
||||
question:questions(*)
|
||||
`)
|
||||
.single();
|
||||
|
||||
if (!matchError) {
|
||||
match = newMatch;
|
||||
|
||||
// Trigger push notification
|
||||
try {
|
||||
await supabase.functions.invoke("send-notification", {
|
||||
body: { couple_id: profile.couple_id, match_id: newMatch.id },
|
||||
});
|
||||
} catch (notifyError) {
|
||||
console.error("Failed to send notification:", notifyError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ response, match }),
|
||||
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Internal server error" }),
|
||||
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
-- Enable necessary extensions
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
|
||||
-- Create custom types
|
||||
CREATE TYPE public.answer_type AS ENUM ('yes', 'no', 'maybe');
|
||||
CREATE TYPE public.match_type AS ENUM ('yes_yes', 'yes_maybe', 'maybe_maybe');
|
||||
|
||||
-- Couples table (must be created first due to FK references)
|
||||
CREATE TABLE public.couples (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
invite_code TEXT UNIQUE DEFAULT substr(md5(random()::text), 1, 8),
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- User profiles (extends auth.users)
|
||||
CREATE TABLE public.profiles (
|
||||
id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
name TEXT,
|
||||
avatar_url TEXT,
|
||||
push_token TEXT,
|
||||
is_premium BOOLEAN DEFAULT FALSE,
|
||||
couple_id UUID REFERENCES public.couples(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Question packs
|
||||
CREATE TABLE public.question_packs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
icon TEXT,
|
||||
is_premium BOOLEAN DEFAULT FALSE,
|
||||
is_public BOOLEAN DEFAULT TRUE,
|
||||
sort_order INT DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Questions within packs
|
||||
CREATE TABLE public.questions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
pack_id UUID NOT NULL REFERENCES public.question_packs(id) ON DELETE CASCADE,
|
||||
text TEXT NOT NULL,
|
||||
intensity INT DEFAULT 1 CHECK (intensity BETWEEN 1 AND 5),
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- User responses to questions
|
||||
CREATE TABLE public.responses (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
|
||||
question_id UUID NOT NULL REFERENCES public.questions(id) ON DELETE CASCADE,
|
||||
couple_id UUID NOT NULL REFERENCES public.couples(id) ON DELETE CASCADE,
|
||||
answer public.answer_type NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(user_id, question_id)
|
||||
);
|
||||
|
||||
-- Matches between partners
|
||||
CREATE TABLE public.matches (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
couple_id UUID NOT NULL REFERENCES public.couples(id) ON DELETE CASCADE,
|
||||
question_id UUID NOT NULL REFERENCES public.questions(id) ON DELETE CASCADE,
|
||||
match_type public.match_type NOT NULL,
|
||||
is_new BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(couple_id, question_id)
|
||||
);
|
||||
|
||||
-- Create indexes for common queries
|
||||
CREATE INDEX idx_profiles_couple_id ON public.profiles(couple_id);
|
||||
CREATE INDEX idx_questions_pack_id ON public.questions(pack_id);
|
||||
CREATE INDEX idx_responses_couple_question ON public.responses(couple_id, question_id);
|
||||
CREATE INDEX idx_matches_couple_id ON public.matches(couple_id);
|
||||
CREATE INDEX idx_matches_is_new ON public.matches(is_new) WHERE is_new = TRUE;
|
||||
|
||||
-- Function to auto-create profile on signup
|
||||
CREATE OR REPLACE FUNCTION public.handle_new_user()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
INSERT INTO public.profiles (id, name, avatar_url)
|
||||
VALUES (
|
||||
NEW.id,
|
||||
COALESCE(NEW.raw_user_meta_data->>'name', NEW.raw_user_meta_data->>'full_name'),
|
||||
NEW.raw_user_meta_data->>'avatar_url'
|
||||
);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql SECURITY DEFINER;
|
||||
|
||||
-- Trigger to create profile on signup
|
||||
CREATE TRIGGER on_auth_user_created
|
||||
AFTER INSERT ON auth.users
|
||||
FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
|
||||
|
||||
-- Function to update updated_at timestamp
|
||||
CREATE OR REPLACE FUNCTION public.update_updated_at()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger to auto-update updated_at on profiles
|
||||
CREATE TRIGGER update_profiles_updated_at
|
||||
BEFORE UPDATE ON public.profiles
|
||||
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at();
|
||||
@@ -0,0 +1,87 @@
|
||||
-- Enable Row Level Security on all tables
|
||||
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.couples ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.question_packs ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.questions ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.responses ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE public.matches ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Profiles policies
|
||||
CREATE POLICY "Users can view own profile"
|
||||
ON public.profiles FOR SELECT
|
||||
USING (auth.uid() = id);
|
||||
|
||||
CREATE POLICY "Users can update own profile"
|
||||
ON public.profiles FOR UPDATE
|
||||
USING (auth.uid() = id);
|
||||
|
||||
CREATE POLICY "Users can view partner profile"
|
||||
ON public.profiles FOR SELECT
|
||||
USING (
|
||||
couple_id IS NOT NULL AND
|
||||
couple_id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid())
|
||||
);
|
||||
|
||||
-- Couples policies
|
||||
CREATE POLICY "Users can view own couple"
|
||||
ON public.couples FOR SELECT
|
||||
USING (id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid()));
|
||||
|
||||
CREATE POLICY "Authenticated users can create couples"
|
||||
ON public.couples FOR INSERT
|
||||
WITH CHECK (auth.role() = 'authenticated');
|
||||
|
||||
CREATE POLICY "Users can view couple by invite code"
|
||||
ON public.couples FOR SELECT
|
||||
USING (TRUE); -- Allow reading by invite_code for joining
|
||||
|
||||
-- Question packs policies (public packs visible to all)
|
||||
CREATE POLICY "Anyone can view public packs"
|
||||
ON public.question_packs FOR SELECT
|
||||
USING (is_public = TRUE);
|
||||
|
||||
CREATE POLICY "Premium users can view premium packs"
|
||||
ON public.question_packs FOR SELECT
|
||||
USING (
|
||||
is_premium = FALSE OR
|
||||
EXISTS (SELECT 1 FROM public.profiles WHERE id = auth.uid() AND is_premium = TRUE)
|
||||
);
|
||||
|
||||
-- Questions policies
|
||||
CREATE POLICY "Anyone can view questions in visible packs"
|
||||
ON public.questions FOR SELECT
|
||||
USING (
|
||||
pack_id IN (
|
||||
SELECT id FROM public.question_packs
|
||||
WHERE is_public = TRUE OR (
|
||||
is_premium = TRUE AND
|
||||
EXISTS (SELECT 1 FROM public.profiles WHERE id = auth.uid() AND is_premium = TRUE)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Responses policies
|
||||
CREATE POLICY "Users can view own responses"
|
||||
ON public.responses FOR SELECT
|
||||
USING (user_id = auth.uid());
|
||||
|
||||
CREATE POLICY "Users can insert own responses"
|
||||
ON public.responses FOR INSERT
|
||||
WITH CHECK (user_id = auth.uid());
|
||||
|
||||
CREATE POLICY "Users can update own responses"
|
||||
ON public.responses FOR UPDATE
|
||||
USING (user_id = auth.uid());
|
||||
|
||||
-- Matches policies
|
||||
CREATE POLICY "Users can view couple matches"
|
||||
ON public.matches FOR SELECT
|
||||
USING (
|
||||
couple_id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid())
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can update match seen status"
|
||||
ON public.matches FOR UPDATE
|
||||
USING (
|
||||
couple_id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid())
|
||||
);
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
-- Seed data: Initial question packs for testing
|
||||
|
||||
-- Starter Pack (free)
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
'Starter Pack',
|
||||
'Perfect for couples just getting started. Light and playful questions to break the ice.',
|
||||
'🌟',
|
||||
FALSE,
|
||||
TRUE,
|
||||
1
|
||||
);
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, intensity) VALUES
|
||||
('a1b2c3d4-e5f6-7890-abcd-ef1234567890', 'Would you like to try a couples massage together?', 1),
|
||||
('a1b2c3d4-e5f6-7890-abcd-ef1234567890', 'Would you enjoy a candlelit dinner at home?', 1),
|
||||
('a1b2c3d4-e5f6-7890-abcd-ef1234567890', 'Would you like to slow dance in the living room?', 1),
|
||||
('a1b2c3d4-e5f6-7890-abcd-ef1234567890', 'Would you enjoy a bath or shower together?', 2),
|
||||
('a1b2c3d4-e5f6-7890-abcd-ef1234567890', 'Would you like to give your partner a back rub?', 1);
|
||||
|
||||
-- Date Night Pack (free)
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'b2c3d4e5-f678-9012-bcde-f23456789012',
|
||||
'Date Night',
|
||||
'Spice up your date nights with these romantic suggestions.',
|
||||
'🌹',
|
||||
FALSE,
|
||||
TRUE,
|
||||
2
|
||||
);
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, intensity) VALUES
|
||||
('b2c3d4e5-f678-9012-bcde-f23456789012', 'Would you enjoy stargazing together?', 1),
|
||||
('b2c3d4e5-f678-9012-bcde-f23456789012', 'Would you like to cook a meal together?', 1),
|
||||
('b2c3d4e5-f678-9012-bcde-f23456789012', 'Would you enjoy a picnic in the park?', 1),
|
||||
('b2c3d4e5-f678-9012-bcde-f23456789012', 'Would you like to watch a romantic movie together?', 1),
|
||||
('b2c3d4e5-f678-9012-bcde-f23456789012', 'Would you enjoy a weekend getaway?', 2);
|
||||
|
||||
-- Adventure Pack (premium)
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'c3d4e5f6-7890-1234-cdef-345678901234',
|
||||
'Adventure',
|
||||
'For couples ready to explore more adventurous activities together.',
|
||||
'🔥',
|
||||
TRUE,
|
||||
TRUE,
|
||||
3
|
||||
);
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, intensity) VALUES
|
||||
('c3d4e5f6-7890-1234-cdef-345678901234', 'Would you like to try role-playing scenarios?', 3),
|
||||
('c3d4e5f6-7890-1234-cdef-345678901234', 'Would you enjoy using massage oils?', 2),
|
||||
('c3d4e5f6-7890-1234-cdef-345678901234', 'Would you like to write love letters to each other?', 2),
|
||||
('c3d4e5f6-7890-1234-cdef-345678901234', 'Would you enjoy a blindfolded experience?', 3),
|
||||
('c3d4e5f6-7890-1234-cdef-345678901234', 'Would you like to plan a surprise for your partner?', 2);
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
-- Add Adult / After Dark pack
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'd4e5f607-8901-2345-defa-456789012345',
|
||||
'After Dark',
|
||||
'Our most intimate and explicit questions for couples ready to explore their deepest fantasies.',
|
||||
'😈',
|
||||
TRUE,
|
||||
TRUE,
|
||||
4
|
||||
);
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, intensity) VALUES
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to try using toys during intimacy?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy exploring BDSM (e.g., light bondage)?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to watch adult content together?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy trying intimacy in a new or daring location?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to experiment with temperature play (e.g., ice or wax)?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy role-playing a "stranger" or "first date" scenario?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to try "dirty talk" or more explicit communication?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy a full-body sensory massage with oils and feathers?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to explore "edging" or delayed gratification?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy sharing your deepest, most explicit fantasies?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to try shower sex or water play?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy a roleplay involving a "student/teacher" or similar dynamic?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to experiment with leather, latex, or other textures?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy trying "impact play" (e.g., spanking)?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy a weekend dedicated entirely to intimacy and exploration?', 2),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to try "blindfolded feeding" or sensory food play?', 2),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy exploring your partner''s "no-go" zones with permission?', 3),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you like to try "synchronized breathing" or Tantric techniques?', 2),
|
||||
('d4e5f607-8901-2345-defa-456789012345', 'Would you enjoy making a "video for us" to watch later?', 3);
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Fix infinite recursion in profiles RLS policy
|
||||
|
||||
-- Create a secure function to look up couple_id without triggering recursion
|
||||
CREATE OR REPLACE FUNCTION public.get_auth_user_couple_id()
|
||||
RETURNS UUID
|
||||
LANGUAGE sql
|
||||
SECURITY DEFINER
|
||||
STABLE
|
||||
AS $$
|
||||
SELECT couple_id FROM public.profiles WHERE id = auth.uid();
|
||||
$$;
|
||||
|
||||
-- Drop the recursive policy
|
||||
DROP POLICY IF EXISTS "Users can view partner profile" ON public.profiles;
|
||||
|
||||
-- Recreate the policy using the secure function
|
||||
CREATE POLICY "Users can view partner profile"
|
||||
ON public.profiles FOR SELECT
|
||||
USING (
|
||||
couple_id IS NOT NULL AND
|
||||
couple_id = public.get_auth_user_couple_id()
|
||||
);
|
||||
|
||||
-- Also fix the Matches policy which has the same issue
|
||||
DROP POLICY IF EXISTS "Users can view couple matches" ON public.matches;
|
||||
|
||||
CREATE POLICY "Users can view couple matches"
|
||||
ON public.matches FOR SELECT
|
||||
USING (
|
||||
couple_id = public.get_auth_user_couple_id()
|
||||
);
|
||||
|
||||
-- And the update matches policy
|
||||
DROP POLICY IF EXISTS "Users can update match seen status" ON public.matches;
|
||||
|
||||
CREATE POLICY "Users can update match seen status"
|
||||
ON public.matches FOR UPDATE
|
||||
USING (
|
||||
couple_id = public.get_auth_user_couple_id()
|
||||
);
|
||||
|
||||
-- And the Couples policy
|
||||
DROP POLICY IF EXISTS "Users can view own couple" ON public.couples;
|
||||
|
||||
CREATE POLICY "Users can view own couple"
|
||||
ON public.couples FOR SELECT
|
||||
USING (
|
||||
id = public.get_auth_user_couple_id()
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
-- Create couple_packs table to track enabled packs per couple
|
||||
CREATE TABLE public.couple_packs (
|
||||
couple_id UUID NOT NULL REFERENCES public.couples(id) ON DELETE CASCADE,
|
||||
pack_id UUID NOT NULL REFERENCES public.question_packs(id) ON DELETE CASCADE,
|
||||
enabled BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
PRIMARY KEY (couple_id, pack_id)
|
||||
);
|
||||
|
||||
-- RLS Policies
|
||||
ALTER TABLE public.couple_packs ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- Couples can view their own pack settings
|
||||
CREATE POLICY "Couples can view their own pack settings"
|
||||
ON public.couple_packs
|
||||
FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.profiles
|
||||
WHERE profiles.id = auth.uid()
|
||||
AND profiles.couple_id = couple_packs.couple_id
|
||||
)
|
||||
);
|
||||
|
||||
-- Couples can insert/update their own pack settings
|
||||
CREATE POLICY "Couples can modify their own pack settings"
|
||||
ON public.couple_packs
|
||||
FOR ALL
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.profiles
|
||||
WHERE profiles.id = auth.uid()
|
||||
AND profiles.couple_id = couple_packs.couple_id
|
||||
)
|
||||
);
|
||||
|
||||
-- Function to handle default packs for new couples (Optional, but good UX)
|
||||
-- For now, we'll just assume if no record exists, it's not enabled?
|
||||
-- Or maybe better: if no record exists, it IS enabled if it's not premium?
|
||||
-- Actually, the user wants to "select which packs are active".
|
||||
-- Let's stick to explicit records.
|
||||
@@ -0,0 +1,64 @@
|
||||
-- Create messages table
|
||||
CREATE TABLE IF NOT EXISTS public.messages (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
match_id UUID NOT NULL REFERENCES public.matches(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
content TEXT,
|
||||
media_path TEXT,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
CONSTRAINT content_or_media CHECK (content IS NOT NULL OR media_path IS NOT NULL)
|
||||
);
|
||||
|
||||
-- RLS for messages
|
||||
ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "Users can view messages in their matches"
|
||||
ON public.messages
|
||||
FOR SELECT
|
||||
USING (
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.matches m
|
||||
WHERE m.id = messages.match_id
|
||||
AND m.couple_id IN (
|
||||
SELECT couple_id FROM public.profiles
|
||||
WHERE id = auth.uid()
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can insert messages in their matches"
|
||||
ON public.messages
|
||||
FOR INSERT
|
||||
WITH CHECK (
|
||||
auth.uid() = user_id AND
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.matches m
|
||||
WHERE m.id = messages.match_id
|
||||
AND m.couple_id IN (
|
||||
SELECT couple_id FROM public.profiles
|
||||
WHERE id = auth.uid()
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Storage bucket for chat media
|
||||
INSERT INTO storage.buckets (id, name, public)
|
||||
VALUES ('chat-media', 'chat-media', true)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Storage policies
|
||||
CREATE POLICY "Users can upload chat media"
|
||||
ON storage.objects
|
||||
FOR INSERT
|
||||
WITH CHECK (
|
||||
bucket_id = 'chat-media' AND
|
||||
auth.role() = 'authenticated'
|
||||
);
|
||||
|
||||
CREATE POLICY "Users can view chat media"
|
||||
ON storage.objects
|
||||
FOR SELECT
|
||||
USING (bucket_id = 'chat-media');
|
||||
|
||||
-- Realtime
|
||||
alter publication supabase_realtime add table messages;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Add read_at column
|
||||
ALTER TABLE public.messages ADD COLUMN IF NOT EXISTS read_at TIMESTAMPTZ;
|
||||
|
||||
-- Allow users to update read_at for messages where they are NOT the sender
|
||||
CREATE POLICY "Users can mark messages as read"
|
||||
ON public.messages
|
||||
FOR UPDATE
|
||||
USING (
|
||||
auth.uid() != user_id AND
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.matches m
|
||||
WHERE m.id = messages.match_id
|
||||
AND m.couple_id IN (
|
||||
SELECT couple_id FROM public.profiles
|
||||
WHERE id = auth.uid()
|
||||
)
|
||||
)
|
||||
)
|
||||
WITH CHECK (
|
||||
auth.uid() != user_id
|
||||
);
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Add Explicit / Wild pack
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'e5f6a7b8-9012-3456-abcd-567890123456',
|
||||
'Explicit & Wild',
|
||||
'Unleash your wildest desires with our most explicit questions. Uses direct language for couples who want to get straight to the point.',
|
||||
'🔥',
|
||||
TRUE,
|
||||
TRUE,
|
||||
5
|
||||
);
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, intensity) VALUES
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you let me cum on your face?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to swallow my cum?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you like to be fucked rough, with hair pulling and choking?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to use a butt plug during sex?', 4),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you let me treat you like a slut in the bedroom?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to make a sex tape where we show everything?', 4),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you be into a gangbang fantasy?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want a creampie (cum inside)?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you like to use a strap-on to fuck me?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to rim my asshole?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to try fisting?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you lick my cum off your own body?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to deep throat until you gag?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you like to watch me have sex with someone else?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to have anal sex until I cum?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you be down for a threesome?', 5),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want me to edge you until you are begging to cum?', 4),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you like to wake me up with oral sex?', 4),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Do you want to be spanked hard enough to leave marks?', 4),
|
||||
('e5f6a7b8-9012-3456-abcd-567890123456', 'Would you enjoy being tied up and helpless while I use you?', 5);
|
||||
@@ -0,0 +1,70 @@
|
||||
CREATE OR REPLACE FUNCTION public.get_recommended_questions(target_pack_id UUID DEFAULT NULL)
|
||||
RETURNS TABLE (
|
||||
id UUID,
|
||||
text TEXT,
|
||||
pack_id UUID,
|
||||
intensity INT,
|
||||
partner_answered BOOLEAN
|
||||
) LANGUAGE plpgsql SECURITY DEFINER AS $$
|
||||
DECLARE
|
||||
v_user_id UUID;
|
||||
v_couple_id UUID;
|
||||
BEGIN
|
||||
v_user_id := auth.uid();
|
||||
|
||||
-- Get couple_id
|
||||
SELECT p.couple_id INTO v_couple_id
|
||||
FROM public.profiles p
|
||||
WHERE p.id = v_user_id;
|
||||
|
||||
IF v_couple_id IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
RETURN QUERY
|
||||
WITH user_config_exists AS (
|
||||
SELECT 1 FROM public.couple_packs WHERE couple_id = v_couple_id LIMIT 1
|
||||
),
|
||||
active_packs AS (
|
||||
-- Case 0: Specific pack requested
|
||||
SELECT target_pack_id AS pack_id
|
||||
WHERE target_pack_id IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- Case 1: No specific pack, config exists -> use enabled packs
|
||||
SELECT cp.pack_id
|
||||
FROM public.couple_packs cp
|
||||
WHERE target_pack_id IS NULL
|
||||
AND cp.couple_id = v_couple_id AND cp.enabled = TRUE
|
||||
AND EXISTS (SELECT 1 FROM user_config_exists)
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- Case 2: No specific pack, no config -> use all public packs
|
||||
SELECT p.id AS pack_id
|
||||
FROM public.question_packs p
|
||||
WHERE target_pack_id IS NULL
|
||||
AND p.is_public = TRUE
|
||||
AND NOT EXISTS (SELECT 1 FROM user_config_exists)
|
||||
)
|
||||
SELECT
|
||||
q.id,
|
||||
q.text,
|
||||
q.pack_id,
|
||||
q.intensity,
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.couple_id = v_couple_id
|
||||
AND r.user_id != v_user_id
|
||||
) AS partner_answered
|
||||
FROM public.questions q
|
||||
WHERE q.pack_id IN (SELECT ap.pack_id FROM active_packs ap)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.user_id = v_user_id
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,79 @@
|
||||
-- Add partner_text column to questions table
|
||||
ALTER TABLE public.questions ADD COLUMN IF NOT EXISTS partner_text TEXT;
|
||||
|
||||
-- Update get_recommended_questions to include partner_text
|
||||
-- Must drop first because return type changes
|
||||
DROP FUNCTION IF EXISTS public.get_recommended_questions(uuid);
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.get_recommended_questions(target_pack_id UUID DEFAULT NULL)
|
||||
RETURNS TABLE (
|
||||
id UUID,
|
||||
text TEXT,
|
||||
partner_text TEXT,
|
||||
pack_id UUID,
|
||||
intensity INT,
|
||||
partner_answered BOOLEAN
|
||||
) LANGUAGE plpgsql SECURITY DEFINER AS $$
|
||||
DECLARE
|
||||
v_user_id UUID;
|
||||
v_couple_id UUID;
|
||||
BEGIN
|
||||
v_user_id := auth.uid();
|
||||
|
||||
-- Get couple_id
|
||||
SELECT p.couple_id INTO v_couple_id
|
||||
FROM public.profiles p
|
||||
WHERE p.id = v_user_id;
|
||||
|
||||
IF v_couple_id IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
RETURN QUERY
|
||||
WITH user_config_exists AS (
|
||||
SELECT 1 FROM public.couple_packs WHERE couple_id = v_couple_id LIMIT 1
|
||||
),
|
||||
active_packs AS (
|
||||
-- Case 0: Specific pack requested
|
||||
SELECT target_pack_id AS pack_id
|
||||
WHERE target_pack_id IS NOT NULL
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- Case 1: No specific pack, config exists -> use enabled packs
|
||||
SELECT cp.pack_id
|
||||
FROM public.couple_packs cp
|
||||
WHERE target_pack_id IS NULL
|
||||
AND cp.couple_id = v_couple_id AND cp.enabled = TRUE
|
||||
AND EXISTS (SELECT 1 FROM user_config_exists)
|
||||
|
||||
UNION ALL
|
||||
|
||||
-- Case 2: No specific pack, no config -> use all public packs
|
||||
SELECT p.id AS pack_id
|
||||
FROM public.question_packs p
|
||||
WHERE target_pack_id IS NULL
|
||||
AND p.is_public = TRUE
|
||||
AND NOT EXISTS (SELECT 1 FROM user_config_exists)
|
||||
)
|
||||
SELECT
|
||||
q.id,
|
||||
q.text,
|
||||
q.partner_text,
|
||||
q.pack_id,
|
||||
q.intensity,
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.couple_id = v_couple_id
|
||||
AND r.user_id != v_user_id
|
||||
) AS partner_answered
|
||||
FROM public.questions q
|
||||
WHERE q.pack_id IN (SELECT ap.pack_id FROM active_packs ap)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.user_id = v_user_id
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Add a new pack for two-part questions
|
||||
INSERT INTO public.question_packs (id, name, description, icon, is_premium, is_public, sort_order)
|
||||
VALUES (
|
||||
'd4e5f6f7-8901-2345-defa-456789012345',
|
||||
'Giving & Receiving',
|
||||
'Explore different roles and dynamics with these two-part questions.',
|
||||
'🌓',
|
||||
FALSE,
|
||||
TRUE,
|
||||
4
|
||||
) ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO public.questions (pack_id, text, partner_text, intensity) VALUES
|
||||
('d4e5f6f7-8901-2345-defa-456789012345', 'Finish on your partner''s face', 'Have your partner finish on your face', 4),
|
||||
('d4e5f6f7-8901-2345-defa-456789012345', 'Give your partner a full body massage', 'Receive a full body massage from your partner', 2),
|
||||
('d4e5f6f7-8901-2345-defa-456789012345', 'Tie your partner up', 'Be tied up by your partner', 4),
|
||||
('d4e5f6f7-8901-2345-defa-456789012345', 'Blindfold your partner', 'Be blindfolded by your partner', 3),
|
||||
('d4e5f6f7-8901-2345-defa-456789012345', 'Feed your partner while they are blindfolded', 'Be fed by your partner while blindfolded', 2);
|
||||
@@ -0,0 +1,75 @@
|
||||
-- Update get_recommended_questions to handle two-part questions role assignment
|
||||
-- And return is_two_part for prioritization in the app
|
||||
DROP FUNCTION IF EXISTS public.get_recommended_questions(uuid);
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.get_recommended_questions(target_pack_id UUID DEFAULT NULL)
|
||||
RETURNS TABLE (
|
||||
id UUID,
|
||||
text TEXT,
|
||||
partner_text TEXT, -- Keep this for reference if needed, but 'text' will be the display one
|
||||
is_two_part BOOLEAN,
|
||||
pack_id UUID,
|
||||
intensity INT,
|
||||
partner_answered BOOLEAN
|
||||
) LANGUAGE plpgsql SECURITY DEFINER AS $$
|
||||
DECLARE
|
||||
v_user_id UUID;
|
||||
v_couple_id UUID;
|
||||
BEGIN
|
||||
v_user_id := auth.uid();
|
||||
|
||||
-- Get couple_id
|
||||
SELECT p.couple_id INTO v_couple_id
|
||||
FROM public.profiles p
|
||||
WHERE p.id = v_user_id;
|
||||
|
||||
IF v_couple_id IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
RETURN QUERY
|
||||
WITH user_config_exists AS (
|
||||
SELECT 1 FROM public.couple_packs WHERE couple_id = v_couple_id LIMIT 1
|
||||
),
|
||||
active_packs AS (
|
||||
SELECT target_pack_id AS pack_id WHERE target_pack_id IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT cp.pack_id FROM public.couple_packs cp
|
||||
WHERE target_pack_id IS NULL AND cp.couple_id = v_couple_id AND cp.enabled = TRUE
|
||||
AND EXISTS (SELECT 1 FROM user_config_exists)
|
||||
UNION ALL
|
||||
SELECT p.id AS pack_id FROM public.question_packs p
|
||||
WHERE target_pack_id IS NULL AND p.is_public = TRUE
|
||||
AND NOT EXISTS (SELECT 1 FROM user_config_exists)
|
||||
)
|
||||
SELECT
|
||||
q.id,
|
||||
-- Logic: Show partner_text IF partner has already answered, otherwise show text
|
||||
CASE
|
||||
WHEN q.partner_text IS NOT NULL AND EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.couple_id = v_couple_id
|
||||
AND r.user_id != v_user_id
|
||||
) THEN q.partner_text
|
||||
ELSE q.text
|
||||
END as text,
|
||||
q.partner_text,
|
||||
q.partner_text IS NOT NULL as is_two_part,
|
||||
q.pack_id,
|
||||
q.intensity,
|
||||
EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.couple_id = v_couple_id
|
||||
AND r.user_id != v_user_id
|
||||
) AS partner_answered
|
||||
FROM public.questions q
|
||||
WHERE q.pack_id IN (SELECT ap.pack_id FROM active_packs ap)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM public.responses r
|
||||
WHERE r.question_id = q.id
|
||||
AND r.user_id = v_user_id
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Allow users to view their partner's responses in addition to their own
|
||||
DROP POLICY IF EXISTS "Users can view own responses" ON public.responses;
|
||||
|
||||
CREATE POLICY "Users can view couple responses"
|
||||
ON public.responses FOR SELECT
|
||||
USING (
|
||||
user_id = auth.uid() OR
|
||||
couple_id IN (SELECT couple_id FROM public.profiles WHERE id = auth.uid())
|
||||
);
|
||||
Reference in new issue
Block a user