mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-10-31 18:19:43 +00:00
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:
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" } }
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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.
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user