Initial commit

This commit is contained in:
jjbrunton committed 2025-12-27 19:10:11 +00:00
commit 4d53d83769
73 files changed
+37728

No files matched your search

+176
View File
@@ -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
View File
@@ -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
View File
@@ -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" } }
);
}
});