Add question types, nudge feature, and share modal

- Add new question card components (photo, audio, text, who-likely)
- Add share preview modal for matches
- Add nudge notification system with rate limiting
- Add session-based notification improvements
- Add match confetti celebration animation
- Update onboarding flow with paywall tracking
- Remove deprecated swipe card and tutorial components
- Update GlassCard/GlassInput to use solid backgrounds
- Fix routing issues after packs screen removal
This commit is contained in:
jjbrunton committed 2026-01-25 19:17:39 +00:00
1 parent 8612b16b93
commit 1daf386765
114 files changed
+14877 -7911

No files matched your search

@@ -2,15 +2,20 @@ import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0?target=deno";
/**
* Send coalesced match notifications.
* Send session-based activity notifications.
* Called by pg_cron every minute and processes any pending notifications
* whose notify_at has passed.
* whose notify_at has passed (5 minutes of user inactivity).
*
* Sends notification to the PARTNER of the active user with copy:
* "[Partner] has been answering questions!"
*/
interface PendingMatchNotification {
id: string;
couple_id: string;
active_user_id: string | null;
match_count: number;
response_count: number;
latest_match_id: string | null;
notify_at: string;
}
@@ -67,7 +72,7 @@ Deno.serve(async (req) => {
// Get all pending notifications where notify_at has passed
const { data: pendingNotifications, error: fetchError } = await supabase
.from("pending_match_notifications")
.select("id, couple_id, match_count, latest_match_id, notify_at")
.select("id, couple_id, active_user_id, match_count, response_count, latest_match_id, notify_at")
.lte("notify_at", nowIso);
if (fetchError) {
@@ -87,19 +92,20 @@ Deno.serve(async (req) => {
const coupleIds = Array.from(new Set(pendingNotifications.map((n) => n.couple_id)));
// Fetch all push tokens + match notification preference for couples
// Fetch all profiles for couples (need name, push_token, last_active_at, prefs)
const { data: profiles, error: profilesError } = await supabase
.from("profiles")
.select(
`
id,
name,
couple_id,
push_token,
notification_preferences:notification_preferences(matches_enabled)
last_active_at,
notification_preferences:notification_preferences(partner_activity_enabled)
`
)
.in("couple_id", coupleIds)
.not("push_token", "is", null);
.in("couple_id", coupleIds);
if (profilesError) {
console.error("Error fetching profiles:", profilesError);
@@ -110,56 +116,85 @@ Deno.serve(async (req) => {
}
const profilesByCouple = new Map<string, any[]>();
const profilesById = new Map<string, any>();
for (const profile of profiles || []) {
const list = profilesByCouple.get(profile.couple_id) ?? [];
list.push(profile);
profilesByCouple.set(profile.couple_id, list);
profilesById.set(profile.id, profile);
}
// Helper to check if user is currently active (within last 5 minutes)
const isUserActive = (lastActiveAt: string | null): boolean => {
if (!lastActiveAt) return false;
const lastActive = new Date(lastActiveAt).getTime();
const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
return lastActive > fiveMinutesAgo;
};
const messages: ExpoPushMessage[] = [];
const processedIds: string[] = [];
for (const notification of pendingNotifications as PendingMatchNotification[]) {
const coupleProfiles = profilesByCouple.get(notification.couple_id) ?? [];
for (const profile of coupleProfiles) {
const prefs = Array.isArray(profile.notification_preferences)
? profile.notification_preferences[0]
: profile.notification_preferences;
// Find the active user (the one who was answering) and their partner
const activeUser = notification.active_user_id
? profilesById.get(notification.active_user_id)
: null;
// Skip if user has explicitly disabled match notifications
if (prefs && prefs.matches_enabled === false) {
continue;
}
// Find the partner (the one who should receive the notification)
const partner = coupleProfiles.find(p => p.id !== notification.active_user_id);
const count = Math.max(1, Number(notification.match_count) || 1);
const latestMatchId = notification.latest_match_id;
// If the match was deleted before the digest fired, don't notify.
if (!latestMatchId) {
continue;
}
if (count === 1) {
messages.push({
to: profile.push_token,
title: "It's a match! 💕",
body: "You and your partner matched on something new!",
sound: "default",
data: { type: "match", match_id: latestMatchId },
});
} else {
messages.push({
to: profile.push_token,
title: "New matches 💕",
body: `You have ${count} new matches`,
sound: "default",
// Include latest_match_id for backwards compatibility
data: { type: "match_digest", count, match_id: latestMatchId },
});
}
// Skip if we can't identify the partner or they have no push token
if (!partner || !partner.push_token) {
processedIds.push(notification.id);
continue;
}
// Skip if partner is currently active in the app
if (isUserActive(partner.last_active_at)) {
console.log(`Skipping notification - partner ${partner.id} is active in app`);
processedIds.push(notification.id);
continue;
}
// Check notification preferences (partner_activity_enabled)
const prefs = Array.isArray(partner.notification_preferences)
? partner.notification_preferences[0]
: partner.notification_preferences;
if (prefs && prefs.partner_activity_enabled === false) {
processedIds.push(notification.id);
continue;
}
// Get active user's name for personalized notification
const activeUserName = activeUser?.name || "Your partner";
const matchCount = Math.max(0, Number(notification.match_count) || 0);
// Build notification message
// Primary message: "[Partner] has been answering questions!"
// Include match count in body if there are matches
let body = `Tap to see what you both said`;
if (matchCount > 0) {
body = matchCount === 1
? `You have a new match! Tap to see what you both said`
: `You have ${matchCount} new matches! Tap to see what you both said`;
}
messages.push({
to: partner.push_token,
title: `${activeUserName} has been answering questions! 💕`,
body,
sound: "default",
data: {
type: "match_digest",
count: matchCount,
match_id: notification.latest_match_id,
},
});
processedIds.push(notification.id);
}
@@ -0,0 +1,229 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0?target=deno";
/**
* Send a nudge notification to partner.
* Rate limited to once per 12 hours.
*
* Called directly from the client when user taps "Nudge partner" button.
* Requires authentication via JWT.
*/
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
// Rate limit: 12 hours in milliseconds
const NUDGE_COOLDOWN_MS = 12 * 60 * 60 * 1000;
interface ExpoPushMessage {
to: string;
title: string;
body: string;
sound?: string;
data?: Record<string, unknown>;
}
async function sendExpoPushNotification(message: ExpoPushMessage) {
const response = await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(message),
});
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 });
}
if (req.method !== "POST") {
return new Response("Method not allowed", { status: 405, headers: corsHeaders });
}
try {
// Get user from JWT (manual validation as per CLAUDE.md)
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response(
JSON.stringify({ error: "Missing authorization" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Verify the JWT and get user
const token = authHeader.replace("Bearer ", "");
const { data: { user }, error: authError } = await supabase.auth.getUser(token);
if (authError || !user) {
return new Response(
JSON.stringify({ error: "Invalid token" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get the user's profile with couple info
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("id, name, couple_id, last_nudge_sent_at")
.eq("id", user.id)
.maybeSingle();
if (profileError || !profile) {
console.error("Error fetching profile:", profileError);
return new Response(
JSON.stringify({ error: "Profile not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!profile.couple_id) {
return new Response(
JSON.stringify({ error: "Not in a couple" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Check rate limiting
const now = new Date();
if (profile.last_nudge_sent_at) {
const lastNudge = new Date(profile.last_nudge_sent_at);
const timeSinceLastNudge = now.getTime() - lastNudge.getTime();
if (timeSinceLastNudge < NUDGE_COOLDOWN_MS) {
const cooldownRemaining = NUDGE_COOLDOWN_MS - timeSinceLastNudge;
const nextNudgeAvailable = new Date(lastNudge.getTime() + NUDGE_COOLDOWN_MS);
return new Response(
JSON.stringify({
error: "Rate limited",
cooldown_remaining_seconds: Math.ceil(cooldownRemaining / 1000),
next_nudge_available_at: nextNudgeAvailable.toISOString(),
}),
{ status: 429, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
}
// Get the partner
const { data: partner, error: partnerError } = await supabase
.from("profiles")
.select("id, name, push_token")
.eq("couple_id", profile.couple_id)
.neq("id", user.id)
.maybeSingle();
if (partnerError) {
console.error("Error fetching partner:", partnerError);
return new Response(
JSON.stringify({ error: "Failed to find partner" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!partner) {
return new Response(
JSON.stringify({ error: "Partner not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Update last_nudge_sent_at FIRST (prevents gaming by quickly re-sending)
const { error: updateError } = await supabase
.from("profiles")
.update({ last_nudge_sent_at: now.toISOString() })
.eq("id", user.id);
if (updateError) {
console.error("Error updating last_nudge_sent_at:", updateError);
return new Response(
JSON.stringify({ error: "Failed to update nudge timestamp" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Check partner's notification preferences
const { data: prefs } = await supabase
.from("notification_preferences")
.select("nudges_enabled")
.eq("user_id", partner.id)
.maybeSingle();
// If prefs don't exist or nudges_enabled is not explicitly false, send notification
const nudgesEnabled = prefs?.nudges_enabled !== false;
// Check if partner has a push token
if (!partner.push_token) {
console.log(`Partner ${partner.id} has no push token`);
return new Response(
JSON.stringify({
success: true,
notification_sent: false,
reason: "no_push_token",
next_nudge_available_at: new Date(now.getTime() + NUDGE_COOLDOWN_MS).toISOString(),
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Skip sending if partner has disabled nudge notifications
if (!nudgesEnabled) {
console.log(`Partner ${partner.id} has disabled nudge notifications`);
return new Response(
JSON.stringify({
success: true,
notification_sent: false,
reason: "nudges_disabled",
next_nudge_available_at: new Date(now.getTime() + NUDGE_COOLDOWN_MS).toISOString(),
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Send the push notification
const userName = profile.name || "Your partner";
await sendExpoPushNotification({
to: partner.push_token,
title: "Partner nudge",
body: `${userName} wants you to catch up!`,
sound: "default",
data: { type: "nudge" },
});
console.log(`Nudge notification sent from ${user.id} to ${partner.id}`);
return new Response(
JSON.stringify({
success: true,
notification_sent: true,
next_nudge_available_at: new Date(now.getTime() + NUDGE_COOLDOWN_MS).toISOString(),
}),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("Nudge notification error:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
+146 -94
View File
@@ -7,18 +7,48 @@ const corsHeaders = {
};
type Answer = "yes" | "no" | "maybe";
type MatchType = "yes_yes" | "yes_maybe" | "maybe_maybe";
type MatchType = "yes_yes" | "yes_maybe" | "maybe_maybe" | "both_answered";
type QuestionType = "swipe" | "text_answer" | "audio" | "photo" | "who_likely";
type ResponseData =
| { type: "text_answer"; text: string }
| { type: "audio"; media_path: string; duration_seconds: number }
| { type: "photo"; media_path: string }
| { type: "who_likely"; chosen_user_id: string };
interface SubmitResponseBody {
question_id: string;
answer: Answer;
response_data?: ResponseData; // Optional for backwards compatibility
}
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";
interface Question {
id: string;
question_type?: QuestionType;
// ... other fields
}
function calculateMatchType(question: Question, answer1: Answer, answer2: Answer): MatchType | null {
// For swipe questions (or legacy questions without type), use existing logic
if (!question.question_type || question.question_type === "swipe") {
if (answer1 === "no" || answer2 === "no") return null;
if (answer1 === "yes" && answer2 === "yes") return "yes_yes";
if (answer1 === "maybe" && answer2 === "maybe") return "maybe_maybe";
return "yes_maybe";
}
// For text/audio/photo questions: match if both answered positively
if (["text_answer", "audio", "photo"].includes(question.question_type)) {
if (answer1 === "no" || answer2 === "no") return null;
return "both_answered";
}
// For who_likely: always matches when both answered
if (question.question_type === "who_likely") {
return "both_answered";
}
return null;
}
Deno.serve(async (req) => {
@@ -54,7 +84,7 @@ Deno.serve(async (req) => {
}
// Parse request body
const { question_id, answer }: SubmitResponseBody = await req.json();
const { question_id, answer, response_data }: SubmitResponseBody = await req.json();
if (!question_id || !answer) {
return new Response(
@@ -63,6 +93,20 @@ Deno.serve(async (req) => {
);
}
// Fetch the question to get its type
const { data: question, error: questionError } = await supabase
.from("questions")
.select("id, question_type")
.eq("id", question_id)
.single();
if (questionError || !question) {
return new Response(
JSON.stringify({ error: "Question not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get user's profile and couple
const { data: profile, error: profileError } = await supabase
.from("profiles")
@@ -70,88 +114,89 @@ Deno.serve(async (req) => {
.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" } }
);
}
// Check if this is a new response or an edit (edits bypass daily limit)
const { data: existingResponse } = await supabase
.from("responses")
.select("id")
.eq("user_id", user.id)
.eq("question_id", question_id)
.maybeSingle();
const isNewResponse = !existingResponse;
// Enforce daily response limit for new responses only
if (isNewResponse) {
// Check if user has premium access
const { data: hasPremiumData } = await supabase.rpc("has_premium_access", {
check_user_id: user.id,
});
const hasPremium = hasPremiumData === true;
// If non-premium, check daily limit
if (!hasPremium) {
// Get daily limit from app_config
const { data: configData } = await supabase
.from("app_config")
.select("daily_response_limit")
.limit(1)
.maybeSingle();
const dailyLimit = configData?.daily_response_limit || 0;
// If daily limit is enabled (> 0), check if user has reached it
if (dailyLimit > 0) {
// Calculate UTC day boundaries
const now = new Date();
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const tomorrowStart = new Date(todayStart);
tomorrowStart.setUTCDate(tomorrowStart.getUTCDate() + 1);
// Count responses created today (UTC)
const { count: dailyCount } = await supabase
.from("responses")
.select("*", { count: "exact", head: true })
.eq("user_id", user.id)
.gte("created_at", todayStart.toISOString())
.lt("created_at", tomorrowStart.toISOString());
// If over limit, reject
if ((dailyCount || 0) >= dailyLimit) {
return new Response(
JSON.stringify({
error: "Daily response limit reached",
daily_limit: dailyLimit,
reset_at: tomorrowStart.toISOString(),
}),
{ status: 429, 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 (profileError || !profile?.couple_id) {
return new Response(
JSON.stringify({ error: "User is not in a couple" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Check if this is a new response or an edit (edits bypass daily limit)
const { data: existingResponse } = await supabase
.from("responses")
.select("id")
.eq("user_id", user.id)
.eq("question_id", question_id)
.maybeSingle();
const isNewResponse = !existingResponse;
// Enforce daily response limit for new responses only
if (isNewResponse) {
// Check if user has premium access
const { data: hasPremiumData } = await supabase.rpc("has_premium_access", {
check_user_id: user.id,
});
const hasPremium = hasPremiumData === true;
// If non-premium, check daily limit
if (!hasPremium) {
// Get daily limit from app_config
const { data: configData } = await supabase
.from("app_config")
.select("daily_response_limit")
.limit(1)
.maybeSingle();
const dailyLimit = configData?.daily_response_limit || 0;
// If daily limit is enabled (> 0), check if user has reached it
if (dailyLimit > 0) {
// Calculate UTC day boundaries
const now = new Date();
const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const tomorrowStart = new Date(todayStart);
tomorrowStart.setUTCDate(tomorrowStart.getUTCDate() + 1);
// Count responses created today (UTC)
const { count: dailyCount } = await supabase
.from("responses")
.select("*", { count: "exact", head: true })
.eq("user_id", user.id)
.gte("created_at", todayStart.toISOString())
.lt("created_at", tomorrowStart.toISOString());
// If over limit, reject
if ((dailyCount || 0) >= dailyLimit) {
return new Response(
JSON.stringify({
error: "Daily response limit reached",
daily_limit: dailyLimit,
reset_at: tomorrowStart.toISOString(),
}),
{ status: 429, 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,
response_data: response_data ?? null,
},
{ onConflict: "user_id,question_id" }
)
.select()
.single();
if (responseError) {
return new Response(
@@ -163,7 +208,7 @@ Deno.serve(async (req) => {
// Check for partner's response
const { data: partnerResponse } = await supabase
.from("responses")
.select("answer")
.select("answer, response_data, user_id")
.eq("couple_id", profile.couple_id)
.eq("question_id", question_id)
.neq("user_id", user.id)
@@ -172,9 +217,15 @@ Deno.serve(async (req) => {
let match = null;
if (partnerResponse) {
const matchType = calculateMatch(answer, partnerResponse.answer as Answer);
const matchType = calculateMatchType(question as Question, answer, partnerResponse.answer as Answer);
if (matchType) {
// Build response_summary for 'both_answered' matches
const responseSummary = (matchType === "both_answered") ? {
[user.id]: response_data ?? null,
[partnerResponse.user_id]: partnerResponse.response_data ?? null,
} : null;
// Create or update match
const { data: newMatch, error: matchError } = await supabase
.from("matches")
@@ -184,6 +235,7 @@ Deno.serve(async (req) => {
question_id,
match_type: matchType,
is_new: true,
response_summary: responseSummary,
},
{ onConflict: "couple_id,question_id" }
)
@@ -196,9 +248,9 @@ Deno.serve(async (req) => {
if (!matchError) {
match = newMatch;
// Match push notifications are queued via a Postgres trigger
// (pending_match_notifications) to allow short digesting.
// Match push notifications are queued via a Postgres trigger
// (pending_match_notifications) to allow short digesting.
}
}
}
+154 -96
View File
@@ -6,14 +6,22 @@ const corsHeaders = {
"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 UpdateResponseBody {
question_id: string;
new_answer: Answer;
confirm_delete_match?: boolean;
}
type Answer = "yes" | "no" | "maybe";
type MatchType = "yes_yes" | "yes_maybe" | "maybe_maybe" | "both_answered";
type QuestionType = "swipe" | "text_answer" | "audio" | "photo" | "who_likely";
type ResponseData =
| { type: "text_answer"; text: string }
| { type: "audio"; media_path: string; duration_seconds: number }
| { type: "photo"; media_path: string }
| { type: "who_likely"; chosen_user_id: string };
interface UpdateResponseBody {
question_id: string;
new_answer: Answer;
response_data?: ResponseData | null;
confirm_delete_match?: boolean;
}
interface UpdateResponseResult {
success: boolean;
@@ -21,16 +29,34 @@ interface UpdateResponseResult {
match_id?: string;
message_count?: number;
new_match?: Record<string, unknown> | null;
match_deleted?: boolean;
match_type_updated?: boolean;
}
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";
}
match_deleted?: boolean;
match_type_updated?: boolean;
}
interface Question {
id: string;
question_type?: QuestionType;
}
function calculateMatchType(question: Question, answer1: Answer, answer2: Answer): MatchType | null {
if (!question.question_type || question.question_type === "swipe") {
if (answer1 === "no" || answer2 === "no") return null;
if (answer1 === "yes" && answer2 === "yes") return "yes_yes";
if (answer1 === "maybe" && answer2 === "maybe") return "maybe_maybe";
return "yes_maybe";
}
if (["text_answer", "audio", "photo"].includes(question.question_type)) {
if (answer1 === "no" || answer2 === "no") return null;
return "both_answered";
}
if (question.question_type === "who_likely") {
return "both_answered";
}
return null;
}
Deno.serve(async (req) => {
// Handle CORS preflight
@@ -65,7 +91,7 @@ Deno.serve(async (req) => {
}
// Parse request body
const { question_id, new_answer, confirm_delete_match }: UpdateResponseBody = await req.json();
const { question_id, new_answer, response_data, confirm_delete_match }: UpdateResponseBody = await req.json();
if (!question_id || !new_answer) {
return new Response(
@@ -96,13 +122,27 @@ Deno.serve(async (req) => {
);
}
// Get current response
const { data: currentResponse, error: currentResponseError } = await supabase
.from("responses")
.select("answer")
.eq("user_id", user.id)
.eq("question_id", question_id)
.maybeSingle();
// Fetch the question to get its type
const { data: question, error: questionError } = await supabase
.from("questions")
.select("id, question_type")
.eq("id", question_id)
.single();
if (questionError || !question) {
return new Response(
JSON.stringify({ error: "Question not found" }),
{ status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get current response
const { data: currentResponse, error: currentResponseError } = await supabase
.from("responses")
.select("answer, response_data")
.eq("user_id", user.id)
.eq("question_id", question_id)
.maybeSingle();
if (currentResponseError) {
return new Response(
@@ -118,13 +158,13 @@ Deno.serve(async (req) => {
);
}
// If answer hasn't changed, return early
if (currentResponse.answer === new_answer) {
return new Response(
JSON.stringify({ success: true, message: "Answer unchanged" } as UpdateResponseResult),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// If answer hasn't changed and no response_data updates, return early
if (currentResponse.answer === new_answer && typeof response_data === "undefined") {
return new Response(
JSON.stringify({ success: true, message: "Answer unchanged" } as UpdateResponseResult),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Check if a match exists for this question
const { data: existingMatch } = await supabase
@@ -135,15 +175,28 @@ Deno.serve(async (req) => {
.maybeSingle();
// Get 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)
.maybeSingle();
const result: UpdateResponseResult = { success: true };
const { data: partnerResponse } = await supabase
.from("responses")
.select("answer, response_data, user_id")
.eq("couple_id", profile.couple_id)
.eq("question_id", question_id)
.neq("user_id", user.id)
.maybeSingle();
const result: UpdateResponseResult = { success: true };
const isNonSwipe = !!question.question_type && question.question_type !== "swipe";
const normalizedResponseData = isNonSwipe && new_answer !== "no"
? (typeof response_data !== "undefined" ? response_data : currentResponse.response_data ?? null)
: null;
const matchType = partnerResponse
? calculateMatchType(question as Question, new_answer, partnerResponse.answer as Answer)
: null;
const responseSummary = isNonSwipe && matchType === "both_answered" && partnerResponse
? {
[user.id]: normalizedResponseData ?? null,
[partnerResponse.user_id]: partnerResponse.response_data ?? null,
}
: null;
// Case 1: Changing to "no" AND match exists - requires confirmation
if (new_answer === "no" && existingMatch) {
@@ -195,63 +248,68 @@ Deno.serve(async (req) => {
result.match_deleted = true;
}
// Case 2: Changing FROM "no" to yes/maybe - may create a new match
if (currentResponse.answer === "no" && new_answer !== "no" && partnerResponse) {
const newMatchType = calculateMatch(new_answer, partnerResponse.answer as Answer);
if (newMatchType) {
// Create new match
const { data: newMatch, error: matchError } = await supabase
.from("matches")
.upsert(
{
couple_id: profile.couple_id,
question_id,
match_type: newMatchType,
is_new: true,
},
{ onConflict: "couple_id,question_id" }
)
.select(`*, question:questions(*)`)
.single();
if (!matchError && newMatch) {
result.new_match = newMatch;
// Case 2: Changing FROM "no" to yes/maybe - may create a new match
if (currentResponse.answer === "no" && new_answer !== "no" && partnerResponse) {
if (matchType) {
// Create new match
const { data: newMatch, error: matchError } = await supabase
.from("matches")
.upsert(
{
couple_id: profile.couple_id,
question_id,
match_type: matchType,
is_new: true,
response_summary: responseSummary,
},
{ onConflict: "couple_id,question_id" }
)
.select(`*, question:questions(*)`)
.single();
if (!matchError && newMatch) {
result.new_match = newMatch;
// Match push notifications are queued via a Postgres trigger
// (pending_match_notifications) to allow short digesting.
}
}
}
// Case 3: Changing between yes/maybe - may update match type
if (
currentResponse.answer !== "no" &&
new_answer !== "no" &&
existingMatch &&
partnerResponse
) {
const newMatchType = calculateMatch(new_answer, partnerResponse.answer as Answer);
if (newMatchType) {
const { error: updateMatchError } = await supabase
.from("matches")
.update({ match_type: newMatchType })
.eq("id", existingMatch.id);
if (!updateMatchError) {
result.match_type_updated = true;
}
}
}
// Update the response
const { error: updateError } = await supabase
.from("responses")
.update({ answer: new_answer })
.eq("user_id", user.id)
.eq("question_id", question_id);
}
}
}
// Case 3: Changing between yes/maybe - may update match type
if (
new_answer !== "no" &&
existingMatch &&
partnerResponse &&
matchType
) {
const updatePayload: Record<string, unknown> = { match_type: matchType };
if (isNonSwipe) {
updatePayload.response_summary = responseSummary;
}
const { error: updateMatchError } = await supabase
.from("matches")
.update(updatePayload)
.eq("id", existingMatch.id);
if (!updateMatchError) {
result.match_type_updated = true;
}
}
// Update the response
const responseUpdate: Record<string, unknown> = { answer: new_answer };
if (isNonSwipe || new_answer === "no" || typeof response_data !== "undefined") {
responseUpdate.response_data = normalizedResponseData;
}
const { error: updateError } = await supabase
.from("responses")
.update(responseUpdate)
.eq("user_id", user.id)
.eq("question_id", question_id);
if (updateError) {
return new Response(
@@ -0,0 +1,111 @@
-- Migration: Add Question Types Support
-- This migration adds support for different question types beyond the original swipe mechanic.
-- New types include: text_answer, audio, photo, and who_likely
-- 1. Create question_type enum
CREATE TYPE question_type AS ENUM ('swipe', 'text_answer', 'audio', 'photo', 'who_likely');
-- 2. Add columns to questions table
-- question_type: The type of question (defaults to 'swipe' for backwards compatibility)
-- config: JSONB field for type-specific configuration (e.g., max_length for text, duration for audio)
ALTER TABLE questions
ADD COLUMN question_type question_type NOT NULL DEFAULT 'swipe',
ADD COLUMN config JSONB DEFAULT '{}';
-- 3. Add response_data to responses table
-- This stores type-specific response data (e.g., text answer, audio URL, photo URL, selection)
-- For swipe questions, this remains NULL (the answer column is used)
ALTER TABLE responses
ADD COLUMN response_data JSONB DEFAULT NULL;
-- 4. Extend match_type enum with 'both_answered' for non-swipe question types
-- Using DO block because ADD VALUE IF NOT EXISTS doesn't work in transaction blocks
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_enum
WHERE enumlabel = 'both_answered'
AND enumtypid = (SELECT oid FROM pg_type WHERE typname = 'match_type')
) THEN
ALTER TYPE match_type ADD VALUE 'both_answered';
END IF;
END
$$;
-- 5. Add response_summary to matches table
-- This stores a summary of both partners' responses for display purposes
-- For swipe matches, this can remain NULL
-- For other types, it contains both responses for easy retrieval
ALTER TABLE matches
ADD COLUMN response_summary JSONB DEFAULT NULL;
-- 6. Create storage bucket for response media (audio, photos)
INSERT INTO storage.buckets (id, name, public)
VALUES ('response-media', 'response-media', false)
ON CONFLICT (id) DO NOTHING;
-- 7. RLS policies for response-media bucket
-- Policy: Users can upload to their own folder (user_id/*)
CREATE POLICY "Users can upload to own folder"
ON storage.objects
FOR INSERT
TO authenticated
WITH CHECK (
bucket_id = 'response-media'
AND (storage.foldername(name))[1] = auth.uid()::text
);
-- Policy: Users can update their own uploads
CREATE POLICY "Users can update own uploads"
ON storage.objects
FOR UPDATE
TO authenticated
USING (
bucket_id = 'response-media'
AND (storage.foldername(name))[1] = auth.uid()::text
)
WITH CHECK (
bucket_id = 'response-media'
AND (storage.foldername(name))[1] = auth.uid()::text
);
-- Policy: Users can delete their own uploads
CREATE POLICY "Users can delete own uploads"
ON storage.objects
FOR DELETE
TO authenticated
USING (
bucket_id = 'response-media'
AND (storage.foldername(name))[1] = auth.uid()::text
);
-- Policy: Users can read from their couple's folder (their own + partner's uploads)
-- This allows partners to see each other's media in matches
CREATE POLICY "Users can read couple media"
ON storage.objects
FOR SELECT
TO authenticated
USING (
bucket_id = 'response-media'
AND (
-- User can read their own folder
(storage.foldername(name))[1] = auth.uid()::text
OR
-- User can read their partner's folder (same couple)
(storage.foldername(name))[1] IN (
SELECT p.id::text
FROM profiles p
WHERE p.couple_id = (
SELECT couple_id FROM profiles WHERE id = auth.uid()
)
AND p.couple_id IS NOT NULL
)
)
);
-- Add comments for documentation
COMMENT ON COLUMN questions.question_type IS 'The type of question: swipe (yes/no/maybe), text_answer, audio, photo, or who_likely';
COMMENT ON COLUMN questions.config IS 'Type-specific configuration as JSONB. Examples: {"max_length": 500} for text, {"max_duration_seconds": 60} for audio';
COMMENT ON COLUMN responses.response_data IS 'Type-specific response data as JSONB. Examples: {"text": "..."} for text_answer, {"url": "..."} for audio/photo, {"selection": "partner1"} for who_likely';
COMMENT ON COLUMN matches.response_summary IS 'Summary of both partners responses for display. Contains both response_data values keyed by user_id';
@@ -0,0 +1,227 @@
-- Update get_recommended_questions to return question_type and config for new question types
-- Must DROP first because we're changing the return type signature
DROP FUNCTION IF EXISTS public.get_recommended_questions(uuid);
CREATE OR REPLACE FUNCTION public.get_recommended_questions(target_pack_id uuid DEFAULT NULL::uuid)
RETURNS TABLE(id uuid, text text, partner_text text, is_two_part boolean, pack_id uuid, intensity integer, partner_answered boolean, allowed_couple_genders text[], target_user_genders text[], question_type question_type, config jsonb)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
v_user_id UUID;
v_couple_id UUID;
v_partner_id UUID;
v_user_gender TEXT;
v_partner_gender TEXT;
v_couple_type TEXT;
v_has_premium BOOLEAN;
v_gap_threshold INTEGER;
v_my_unanswered INTEGER;
v_partner_unanswered INTEGER;
v_net_gap INTEGER;
v_user_max_intensity INTEGER;
v_partner_max_intensity INTEGER;
v_effective_max_intensity INTEGER;
v_use_couple_intensity_gate BOOLEAN;
v_daily_limit INTEGER;
v_daily_count INTEGER;
v_today_start TIMESTAMPTZ;
v_tomorrow_start TIMESTAMPTZ;
BEGIN
v_user_id := auth.uid();
SELECT p.couple_id, p.gender, COALESCE(p.max_intensity, 5)
INTO v_couple_id, v_user_gender, v_user_max_intensity
FROM public.profiles p
WHERE p.id = v_user_id;
IF v_couple_id IS NULL THEN
RETURN;
END IF;
SELECT p.id, p.gender, COALESCE(p.max_intensity, 5)
INTO v_partner_id, v_partner_gender, v_partner_max_intensity
FROM public.profiles p
WHERE p.couple_id = v_couple_id AND p.id != v_user_id
LIMIT 1;
-- Toggle: gate questions by couple-effective intensity
SELECT COALESCE(ac.couple_intensity_gate_enabled, FALSE)
INTO v_use_couple_intensity_gate
FROM app_config ac
LIMIT 1;
v_use_couple_intensity_gate := COALESCE(v_use_couple_intensity_gate, FALSE);
v_effective_max_intensity := CASE
WHEN v_use_couple_intensity_gate AND v_partner_id IS NOT NULL THEN LEAST(v_user_max_intensity, v_partner_max_intensity)
ELSE v_user_max_intensity
END;
-- Check premium access (used for both answer gap and daily limit)
v_has_premium := public.has_premium_access(v_user_id);
-- Check daily response limit (only when not browsing a specific pack and user is non-premium)
IF v_partner_id IS NOT NULL AND target_pack_id IS NULL AND NOT v_has_premium THEN
SELECT COALESCE(ac.daily_response_limit, 0) INTO v_daily_limit
FROM app_config ac
LIMIT 1;
IF v_daily_limit > 0 THEN
v_today_start := date_trunc('day', NOW() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC';
v_tomorrow_start := v_today_start + INTERVAL '1 day';
SELECT COUNT(*)::INTEGER INTO v_daily_count
FROM responses r
WHERE r.user_id = v_user_id
AND r.created_at >= v_today_start
AND r.created_at < v_tomorrow_start;
IF v_daily_count >= v_daily_limit THEN
RETURN;
END IF;
END IF;
END IF;
-- Check answer gap threshold using NET gap (only when not browsing a specific pack)
IF v_partner_id IS NOT NULL AND target_pack_id IS NULL THEN
SELECT COALESCE(ac.answer_gap_threshold, 10) INTO v_gap_threshold
FROM app_config ac
LIMIT 1;
IF v_gap_threshold > 0 THEN
WITH enabled_packs AS (
SELECT cp.pack_id
FROM couple_packs cp
WHERE cp.couple_id = v_couple_id AND cp.enabled = true
)
SELECT
COALESCE(SUM(CASE WHEN r.user_id = v_user_id AND NOT EXISTS (
SELECT 1 FROM responses pr
WHERE pr.question_id = r.question_id
AND pr.user_id = v_partner_id
) THEN 1 ELSE 0 END), 0)::integer,
COALESCE(SUM(CASE WHEN r.user_id = v_partner_id AND NOT EXISTS (
SELECT 1 FROM responses pr
WHERE pr.question_id = r.question_id
AND pr.user_id = v_user_id
) THEN 1 ELSE 0 END), 0)::integer
INTO v_my_unanswered, v_partner_unanswered
FROM responses r
INNER JOIN questions q ON q.id = r.question_id
WHERE r.couple_id = v_couple_id
AND r.user_id IN (v_user_id, v_partner_id)
AND EXISTS (SELECT 1 FROM enabled_packs)
AND q.pack_id IN (SELECT ep.pack_id FROM enabled_packs ep)
AND (
NOT v_use_couple_intensity_gate
OR q.intensity IS NULL
OR q.intensity <= v_effective_max_intensity
);
v_net_gap := GREATEST(0, v_my_unanswered - v_partner_unanswered);
IF v_net_gap >= v_gap_threshold THEN
RETURN;
END IF;
END IF;
END IF;
IF v_user_gender IS NOT NULL AND v_partner_gender IS NOT NULL THEN
IF v_user_gender < v_partner_gender THEN
v_couple_type := v_user_gender || '+' || v_partner_gender;
ELSE
v_couple_type := v_partner_gender || '+' || v_user_gender;
END IF;
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
AND EXISTS (
SELECT 1 FROM public.question_packs qp
WHERE qp.id = target_pack_id
AND (qp.is_premium = FALSE OR v_has_premium = TRUE)
)
UNION ALL
SELECT cp.pack_id FROM public.couple_packs cp
INNER JOIN public.question_packs qp ON qp.id = cp.pack_id
WHERE target_pack_id IS NULL
AND cp.couple_id = v_couple_id
AND cp.enabled = TRUE
AND (qp.is_premium = FALSE OR v_has_premium = 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 (p.is_premium = FALSE OR v_has_premium = TRUE)
AND NOT EXISTS (SELECT 1 FROM user_config_exists)
)
SELECT
q.id,
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,
q.allowed_couple_genders,
q.target_user_genders,
q.question_type, -- NEW: Return question type
q.config -- NEW: Return question config
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
)
AND (
q.allowed_couple_genders IS NULL
OR v_couple_type IS NULL
OR v_couple_type = ANY(q.allowed_couple_genders)
)
AND (
q.target_user_genders IS NULL
OR v_user_gender = ANY(q.target_user_genders)
OR 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
)
)
AND (
q.intensity IS NULL
OR q.intensity <= v_effective_max_intensity
)
ORDER BY
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
) DESC,
q.intensity ASC,
q.id ASC;
END;
$function$;
@@ -0,0 +1,109 @@
-- Session-based notification system
--
-- Changes from the previous match-based notification system:
-- 1. Notifications are triggered by ANY response, not just matches
-- 2. Tracks which user is actively answering (active_user_id)
-- 3. Only notifies the partner of the active user (not both)
-- 4. Uses rolling 5-minute inactivity window instead of fixed 2-minute delay
-- 5. Notification copy changes to "[Partner] has been answering questions!"
-- Add new columns to pending_match_notifications
ALTER TABLE pending_match_notifications
ADD COLUMN IF NOT EXISTS active_user_id UUID REFERENCES profiles(id) ON DELETE CASCADE,
ADD COLUMN IF NOT EXISTS response_count INTEGER NOT NULL DEFAULT 0;
-- Drop the old trigger on matches (we'll trigger on responses instead)
DROP TRIGGER IF EXISTS on_match_created ON matches;
-- Create or replace the notification queue function
-- Now triggers on responses instead of matches
CREATE OR REPLACE FUNCTION queue_response_notification()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = 'public'
AS $$
DECLARE
v_couple_id UUID;
BEGIN
-- Get couple_id from the response
v_couple_id := NEW.couple_id;
-- Skip if no couple_id (shouldn't happen, but safety check)
IF v_couple_id IS NULL THEN
RETURN NEW;
END IF;
-- Insert or update pending notification with rolling 5-minute window
-- The notification is for the PARTNER of the user who is answering
INSERT INTO pending_match_notifications (
couple_id,
active_user_id,
match_count,
response_count,
latest_match_id,
notify_at
)
VALUES (
v_couple_id,
NEW.user_id,
0, -- match_count starts at 0, will be incremented by match trigger if needed
1,
NULL, -- No match yet
now() + interval '5 minutes' -- Rolling 5-minute inactivity window
)
ON CONFLICT (couple_id) DO UPDATE SET
active_user_id = NEW.user_id, -- Update who is active
response_count = pending_match_notifications.response_count + 1,
notify_at = now() + interval '5 minutes', -- Reset the 5-minute timer
updated_at = now();
RETURN NEW;
END;
$$;
-- Create or replace the match count incrementer
-- This runs when a match is created to track match_count separately
CREATE OR REPLACE FUNCTION increment_pending_match_count()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = 'public'
AS $$
BEGIN
-- Update the pending notification to increment match count and store latest match
UPDATE pending_match_notifications
SET
match_count = match_count + 1,
latest_match_id = NEW.id,
updated_at = now()
WHERE couple_id = NEW.couple_id;
RETURN NEW;
END;
$$;
-- Trigger on responses table for activity tracking
CREATE TRIGGER on_response_created
AFTER INSERT ON responses
FOR EACH ROW
EXECUTE FUNCTION queue_response_notification();
-- Trigger on matches table just to track match count
CREATE TRIGGER on_match_created_count
AFTER INSERT ON matches
FOR EACH ROW
EXECUTE FUNCTION increment_pending_match_count();
-- Add index on active_user_id for efficient queries
CREATE INDEX IF NOT EXISTS idx_pending_match_notifications_active_user
ON pending_match_notifications(active_user_id);
-- Comment explaining the new behavior
COMMENT ON TABLE pending_match_notifications IS
'Session-based notification queue. Tracks when a user is actively answering questions
and sends a single digest notification to their partner after 5 minutes of inactivity.
- active_user_id: The user who was answering (their partner receives the notification)
- response_count: Total responses during this session
- match_count: Number of matches created during this session
- notify_at: When to send the notification (rolling 5-min from last activity)';
@@ -0,0 +1,14 @@
-- Add onboarding_version column to track which version of onboarding users completed
-- This allows forcing users through re-onboarding when new data is required
ALTER TABLE profiles
ADD COLUMN onboarding_version INTEGER DEFAULT 0;
-- Set existing users who completed onboarding to version 1
-- New users will default to 0 and need to complete the current version
UPDATE profiles
SET onboarding_version = 1
WHERE onboarding_completed = true;
-- Add comment for documentation
COMMENT ON COLUMN profiles.onboarding_version IS 'Version of onboarding flow completed. 0 = never completed, 1+ = completed that version. Used to force re-onboarding when new data is required.';
@@ -0,0 +1,14 @@
-- Add nudge feature support
-- Allows partners to send reminder notifications with rate limiting
-- Add nudge tracking to profiles (for rate limiting)
ALTER TABLE profiles
ADD COLUMN IF NOT EXISTS last_nudge_sent_at TIMESTAMPTZ;
-- Add nudge preference to notification_preferences
ALTER TABLE notification_preferences
ADD COLUMN IF NOT EXISTS nudges_enabled BOOLEAN DEFAULT true;
-- Comment for documentation
COMMENT ON COLUMN profiles.last_nudge_sent_at IS 'Timestamp of last nudge sent to partner (rate limited to once per 12 hours)';
COMMENT ON COLUMN notification_preferences.nudges_enabled IS 'Whether to receive nudge notifications from partner';