mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-11-01 18:19:43 +00:00
Add match archiving, chat enhancements, and daily limits
- Match archives with swipe-to-archive and unread filtering - Chat settings sheet and full-screen media modals - Match notification modal for new matches - Admin AI settings with model/provider configuration - Daily response limit feature with recommended questions - New test coverage for stores, hooks, and components - Claude Code agent and command configurations Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
595d6bd394
commit
b0f1700e40
57 files changed
+8359
-1661
No files matched your search
@@ -9,6 +9,174 @@ const corsHeaders = {
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
};
|
||||
|
||||
const DEFAULT_WHITELIST = [
|
||||
"ok",
|
||||
"okay",
|
||||
"yes",
|
||||
"no",
|
||||
"maybe",
|
||||
"thanks",
|
||||
"thank you",
|
||||
"lol",
|
||||
"lmao",
|
||||
"good night",
|
||||
"goodnight",
|
||||
"good morning",
|
||||
"love you",
|
||||
];
|
||||
|
||||
const DEFAULT_KEYWORD_TRIGGERS = [
|
||||
"suicide",
|
||||
"kill myself",
|
||||
"self harm",
|
||||
"kill you",
|
||||
"hurt you",
|
||||
"rape",
|
||||
"porn",
|
||||
"nude",
|
||||
"explicit",
|
||||
"stab",
|
||||
"shoot",
|
||||
];
|
||||
|
||||
function parseBoolean(value, defaultValue = false) {
|
||||
if (value === null || value === undefined) return defaultValue;
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "number") return value !== 0;
|
||||
if (typeof value === "string") {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["true", "1", "yes", "y", "on"].includes(normalized)) return true;
|
||||
if (["false", "0", "no", "n", "off"].includes(normalized)) return false;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
function parseNumber(value, defaultValue) {
|
||||
if (value === null || value === undefined) return defaultValue;
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
const parsed = Number(String(value).trim());
|
||||
return Number.isFinite(parsed) ? parsed : defaultValue;
|
||||
}
|
||||
|
||||
function parseStringArray(value) {
|
||||
if (!value) return [];
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.filter((item) => typeof item === "string")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return [];
|
||||
if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed
|
||||
.filter((item) => typeof item === "string")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
} catch {
|
||||
// Fall through to delimiter parsing
|
||||
}
|
||||
}
|
||||
return trimmed
|
||||
.split(/[\n,]+/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function normalizeList(values) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
values
|
||||
.map((value) => value.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function getHeuristicConfig(config) {
|
||||
const enabled = parseBoolean(config?.heuristics_enabled, false);
|
||||
const minTextLength = parseNumber(config?.heuristic_min_text_length, 12);
|
||||
const whitelistMaxLength = parseNumber(config?.heuristic_whitelist_max_length, 30);
|
||||
const skipIfNoAlnum = parseBoolean(config?.heuristic_skip_if_no_alnum, true);
|
||||
const skipMediaWithoutText = parseBoolean(config?.heuristic_skip_media_without_text, false);
|
||||
const recordReason = parseBoolean(config?.heuristic_record_reason, false);
|
||||
const useDefaultWhitelist = parseBoolean(config?.heuristic_use_default_whitelist, true);
|
||||
const useDefaultKeywords = parseBoolean(config?.heuristic_use_default_keywords, true);
|
||||
|
||||
const whitelist = parseStringArray(config?.heuristic_whitelist);
|
||||
const keywordTriggers = parseStringArray(config?.heuristic_keyword_triggers);
|
||||
|
||||
const normalizedWhitelist = normalizeList(
|
||||
useDefaultWhitelist ? DEFAULT_WHITELIST.concat(whitelist) : whitelist
|
||||
);
|
||||
const normalizedKeywordTriggers = normalizeList(
|
||||
useDefaultKeywords ? DEFAULT_KEYWORD_TRIGGERS.concat(keywordTriggers) : keywordTriggers
|
||||
);
|
||||
|
||||
return {
|
||||
enabled,
|
||||
minTextLength,
|
||||
whitelistMaxLength,
|
||||
skipIfNoAlnum,
|
||||
skipMediaWithoutText,
|
||||
recordReason,
|
||||
whitelist: normalizedWhitelist,
|
||||
keywordTriggers: normalizedKeywordTriggers,
|
||||
};
|
||||
}
|
||||
|
||||
function evaluateHeuristics(text, hasMedia, config) {
|
||||
if (!config.enabled) {
|
||||
return { shouldCallAi: true, reason: "disabled" };
|
||||
}
|
||||
|
||||
const normalized = (text || "").trim();
|
||||
const lower = normalized.toLowerCase();
|
||||
const hasText = normalized.length > 0;
|
||||
const hasAlnum = /[a-z0-9]/i.test(normalized);
|
||||
|
||||
if (config.keywordTriggers.length > 0) {
|
||||
const keywordHit = config.keywordTriggers.some((keyword) => lower.includes(keyword));
|
||||
if (keywordHit) {
|
||||
return { shouldCallAi: true, reason: "keyword_trigger" };
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasMedia && !hasText) {
|
||||
return { shouldCallAi: false, reason: "no_content" };
|
||||
}
|
||||
|
||||
if (!hasMedia) {
|
||||
if (config.skipIfNoAlnum && !hasAlnum) {
|
||||
return { shouldCallAi: false, reason: "low_signal" };
|
||||
}
|
||||
|
||||
if (normalized.length <= config.whitelistMaxLength) {
|
||||
const isWhitelisted = config.whitelist.includes(lower);
|
||||
if (isWhitelisted) {
|
||||
return { shouldCallAi: false, reason: "whitelist" };
|
||||
}
|
||||
}
|
||||
|
||||
if (normalized.length < config.minTextLength) {
|
||||
return { shouldCallAi: false, reason: "short_text" };
|
||||
}
|
||||
}
|
||||
|
||||
if (hasMedia && config.skipMediaWithoutText && !hasText) {
|
||||
return { shouldCallAi: false, reason: "media_without_text" };
|
||||
}
|
||||
|
||||
return { shouldCallAi: true, reason: "default" };
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
if (req.method === "OPTIONS") {
|
||||
return new Response("ok", { headers: corsHeaders });
|
||||
@@ -42,6 +210,8 @@ Deno.serve(async (req) => {
|
||||
return new Response(JSON.stringify({ message: "Classifier disabled" }), { status: 200, headers: corsHeaders });
|
||||
}
|
||||
|
||||
const heuristicConfig = getHeuristicConfig(config);
|
||||
|
||||
const apiKey = config.openrouter_api_key || Deno.env.get("OPENROUTER_API_KEY");
|
||||
if (!apiKey) {
|
||||
console.error("OpenRouter API Key missing");
|
||||
@@ -64,24 +234,31 @@ Deno.serve(async (req) => {
|
||||
let decryptedText = message.content;
|
||||
let mediaBase64: string | null = null;
|
||||
let mediaMimeType: string | null = null;
|
||||
const hasMedia = !!message.media_path && message.media_type === "image";
|
||||
const keysMetadata = message.keys_metadata as KeysMetadata | null;
|
||||
const encryptionIv = message.encryption_iv as string | null;
|
||||
let aesKey: CryptoKey | null = null;
|
||||
|
||||
if (version === 2) {
|
||||
const keysMetadata = message.keys_metadata as KeysMetadata;
|
||||
const encryptionIv = message.encryption_iv;
|
||||
|
||||
if (version === 2 && (message.encrypted_content || hasMedia)) {
|
||||
if (!keysMetadata || !encryptionIv) {
|
||||
return new Response(JSON.stringify({ error: "Missing encryption metadata" }), { status: 400, headers: corsHeaders });
|
||||
}
|
||||
}
|
||||
|
||||
const getAesKey = async () => {
|
||||
if (aesKey) return aesKey;
|
||||
if (!keysMetadata || !encryptionIv) {
|
||||
throw new Error("Missing encryption metadata");
|
||||
}
|
||||
const adminPrivateKeyJwkStr = Deno.env.get("ADMIN_PRIVATE_KEY_JWK");
|
||||
if (!adminPrivateKeyJwkStr) {
|
||||
throw new Error("ADMIN_PRIVATE_KEY_JWK not set");
|
||||
}
|
||||
|
||||
|
||||
const adminPrivateKey = JSON.parse(adminPrivateKeyJwkStr);
|
||||
const rawAesKey = await unwrapWithAdminKey(keysMetadata.admin_wrapped_key, adminPrivateKey);
|
||||
|
||||
const aesKey = await crypto.subtle.importKey(
|
||||
|
||||
aesKey = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
rawAesKey,
|
||||
{ name: "AES-GCM" },
|
||||
@@ -89,45 +266,60 @@ Deno.serve(async (req) => {
|
||||
["decrypt"]
|
||||
);
|
||||
|
||||
// Decrypt Text
|
||||
if (message.encrypted_content) {
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
|
||||
aesKey,
|
||||
base64ToUint8Array(message.encrypted_content)
|
||||
);
|
||||
decryptedText = new TextDecoder().decode(plaintext);
|
||||
}
|
||||
|
||||
// Decrypt Media (Image only for now)
|
||||
if (message.media_path && message.media_type === "image") {
|
||||
return aesKey;
|
||||
};
|
||||
|
||||
if (version === 2 && message.encrypted_content) {
|
||||
const key = await getAesKey();
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv as string) },
|
||||
key,
|
||||
base64ToUint8Array(message.encrypted_content)
|
||||
);
|
||||
decryptedText = new TextDecoder().decode(plaintext);
|
||||
}
|
||||
|
||||
const heuristicDecision = evaluateHeuristics(decryptedText, hasMedia, heuristicConfig);
|
||||
if (heuristicConfig.enabled && !heuristicDecision.shouldCallAi) {
|
||||
console.log(`Heuristic skip for message ${messageId}: ${heuristicDecision.reason}`);
|
||||
await updateStatus(
|
||||
supabaseAdmin,
|
||||
messageId,
|
||||
"safe",
|
||||
heuristicConfig.recordReason ? heuristicDecision.reason : null,
|
||||
"Neutral"
|
||||
);
|
||||
return new Response(JSON.stringify({ status: "safe" }), { headers: corsHeaders });
|
||||
}
|
||||
|
||||
if (hasMedia) {
|
||||
if (version === 2) {
|
||||
const key = await getAesKey();
|
||||
const { data: mediaBlob, error: downloadError } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
|
||||
if (!downloadError && mediaBlob) {
|
||||
const encryptedBytes = await mediaBlob.arrayBuffer();
|
||||
const decryptedBytes = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv) },
|
||||
aesKey,
|
||||
encryptedBytes
|
||||
);
|
||||
mediaBase64 = arrayBufferToBase64(decryptedBytes);
|
||||
mediaMimeType = "image/jpeg"; // Default or infer?
|
||||
const encryptedBytes = await mediaBlob.arrayBuffer();
|
||||
const decryptedBytes = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: base64ToUint8Array(encryptionIv as string) },
|
||||
key,
|
||||
encryptedBytes
|
||||
);
|
||||
mediaBase64 = arrayBufferToBase64(decryptedBytes);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
} else {
|
||||
const { data: mediaBlob } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
|
||||
if (mediaBlob) {
|
||||
const buffer = await mediaBlob.arrayBuffer();
|
||||
mediaBase64 = arrayBufferToBase64(buffer);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Version 1 (Plaintext)
|
||||
if (message.media_path && message.media_type === "image") {
|
||||
const { data: mediaBlob } = await supabaseAdmin.storage
|
||||
.from("chat-media")
|
||||
.download(normalizeChatMediaPath(message.media_path));
|
||||
if (mediaBlob) {
|
||||
const buffer = await mediaBlob.arrayBuffer();
|
||||
mediaBase64 = arrayBufferToBase64(buffer);
|
||||
mediaMimeType = "image/jpeg";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Construct LLM Payload
|
||||
|
||||
@@ -70,27 +70,88 @@ 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" } }
|
||||
);
|
||||
}
|
||||
|
||||
// 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,
|
||||
},
|
||||
{ onConflict: "user_id,question_id" }
|
||||
)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (responseError) {
|
||||
return new Response(
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
-- Add admin_username column to audit_logs table
|
||||
ALTER TABLE audit_logs
|
||||
ADD COLUMN admin_username TEXT;
|
||||
|
||||
-- Backfill existing audit logs with admin names from profiles
|
||||
UPDATE audit_logs
|
||||
SET admin_username = COALESCE(p.name, p.email, 'Unknown')
|
||||
FROM profiles p
|
||||
WHERE audit_logs.admin_user_id = p.id
|
||||
AND audit_logs.admin_username IS NULL;
|
||||
|
||||
-- Update the log_admin_action function to populate admin_username from profiles
|
||||
CREATE OR REPLACE FUNCTION log_admin_action(
|
||||
p_table_name TEXT,
|
||||
p_record_id UUID,
|
||||
p_action audit_action,
|
||||
p_old_values JSONB DEFAULT NULL,
|
||||
p_new_values JSONB DEFAULT NULL
|
||||
)
|
||||
RETURNS UUID
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = 'public'
|
||||
AS $$
|
||||
DECLARE
|
||||
log_id UUID;
|
||||
admin_role_val public.admin_role;
|
||||
admin_username_val TEXT;
|
||||
changed_fields_arr TEXT[];
|
||||
BEGIN
|
||||
-- Get admin role from admin_users table
|
||||
SELECT role
|
||||
INTO admin_role_val
|
||||
FROM public.admin_users
|
||||
WHERE user_id = auth.uid();
|
||||
|
||||
IF admin_role_val IS NULL THEN
|
||||
RAISE EXCEPTION 'User is not an admin';
|
||||
END IF;
|
||||
|
||||
-- Get username from profiles table (name or email as fallback)
|
||||
SELECT COALESCE(name, email, 'Unknown')
|
||||
INTO admin_username_val
|
||||
FROM public.profiles
|
||||
WHERE id = auth.uid();
|
||||
|
||||
IF p_action = 'UPDATE' AND p_old_values IS NOT NULL AND p_new_values IS NOT NULL THEN
|
||||
SELECT ARRAY(
|
||||
SELECT key FROM jsonb_each(p_new_values)
|
||||
WHERE p_old_values->key IS DISTINCT FROM p_new_values->key
|
||||
) INTO changed_fields_arr;
|
||||
END IF;
|
||||
|
||||
INSERT INTO public.audit_logs (
|
||||
table_name, record_id, action, old_values, new_values,
|
||||
changed_fields, admin_user_id, admin_role, admin_username
|
||||
)
|
||||
VALUES (
|
||||
p_table_name, p_record_id, p_action, p_old_values, p_new_values,
|
||||
changed_fields_arr, auth.uid(), admin_role_val, admin_username_val
|
||||
)
|
||||
RETURNING id INTO log_id;
|
||||
|
||||
RETURN log_id;
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,46 @@
|
||||
-- Create match_archives table for per-user match archiving
|
||||
-- Similar pattern to message_deletions table
|
||||
CREATE TABLE match_archives (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
match_id UUID NOT NULL REFERENCES matches(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
archived_at TIMESTAMPTZ DEFAULT now(),
|
||||
UNIQUE(match_id, user_id)
|
||||
);
|
||||
|
||||
-- Index for efficient lookup when filtering matches
|
||||
CREATE INDEX idx_match_archives_user_match ON match_archives(user_id, match_id);
|
||||
|
||||
-- Enable RLS on match_archives
|
||||
ALTER TABLE match_archives ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
-- RLS Policies for match_archives
|
||||
|
||||
-- Users can view their own archives (needed for filtering)
|
||||
CREATE POLICY "Users can view own archives"
|
||||
ON match_archives FOR SELECT
|
||||
USING (user_id = auth.uid());
|
||||
|
||||
-- Users can insert their own archives (for matches in their couples)
|
||||
CREATE POLICY "Users can archive matches"
|
||||
ON match_archives FOR INSERT
|
||||
WITH CHECK (
|
||||
user_id = auth.uid() AND
|
||||
EXISTS (
|
||||
SELECT 1 FROM matches m
|
||||
JOIN profiles p ON p.couple_id = m.couple_id
|
||||
WHERE m.id = match_archives.match_id
|
||||
AND p.id = auth.uid()
|
||||
)
|
||||
);
|
||||
|
||||
-- Users can delete their own archives (for unarchiving)
|
||||
CREATE POLICY "Users can unarchive matches"
|
||||
ON match_archives FOR DELETE
|
||||
USING (user_id = auth.uid());
|
||||
|
||||
-- Add to realtime for live updates
|
||||
ALTER PUBLICATION supabase_realtime ADD TABLE match_archives;
|
||||
|
||||
-- Documentation
|
||||
COMMENT ON TABLE match_archives IS 'Per-user match archives. Partner still sees the match. Delete record to unarchive.';
|
||||
@@ -0,0 +1,77 @@
|
||||
-- Add daily response limit for non-premium users
|
||||
-- This feature limits how many questions a non-premium user can answer per UTC day
|
||||
|
||||
-- Add daily_response_limit column to app_config
|
||||
ALTER TABLE app_config
|
||||
ADD COLUMN daily_response_limit INTEGER DEFAULT 0;
|
||||
|
||||
COMMENT ON COLUMN app_config.daily_response_limit IS 'Maximum number of questions a non-premium user can answer per UTC day. Set to 0 to disable daily limits.';
|
||||
|
||||
-- ============================================================================
|
||||
-- RPC FUNCTION: get_daily_response_limit_status
|
||||
-- Returns the current daily response limit status for the authenticated user
|
||||
-- ============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_daily_response_limit_status()
|
||||
RETURNS TABLE(
|
||||
responses_today INTEGER,
|
||||
limit_value INTEGER,
|
||||
remaining INTEGER,
|
||||
reset_at TIMESTAMPTZ,
|
||||
is_blocked BOOLEAN
|
||||
)
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = 'public'
|
||||
AS $$
|
||||
DECLARE
|
||||
v_user_id UUID;
|
||||
v_has_premium BOOLEAN;
|
||||
v_limit INTEGER;
|
||||
v_count INTEGER;
|
||||
v_today_start TIMESTAMPTZ;
|
||||
v_tomorrow_start TIMESTAMPTZ;
|
||||
BEGIN
|
||||
v_user_id := auth.uid();
|
||||
|
||||
-- Get limit from app_config
|
||||
SELECT COALESCE(ac.daily_response_limit, 0) INTO v_limit
|
||||
FROM app_config ac
|
||||
LIMIT 1;
|
||||
|
||||
-- If limit is 0, feature is disabled
|
||||
IF v_limit = 0 THEN
|
||||
RETURN QUERY SELECT 0, 0, 0, NULL::TIMESTAMPTZ, false;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Check if user has premium access (user or partner)
|
||||
v_has_premium := public.has_premium_access(v_user_id);
|
||||
|
||||
-- Premium users bypass the limit
|
||||
IF v_has_premium THEN
|
||||
RETURN QUERY SELECT 0, 0, 0, NULL::TIMESTAMPTZ, false;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Calculate UTC day boundaries
|
||||
v_today_start := date_trunc('day', NOW() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC';
|
||||
v_tomorrow_start := v_today_start + INTERVAL '1 day';
|
||||
|
||||
-- Count responses created today (UTC)
|
||||
SELECT COUNT(*)::INTEGER INTO v_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;
|
||||
|
||||
RETURN QUERY SELECT
|
||||
v_count,
|
||||
v_limit,
|
||||
GREATEST(0, v_limit - v_count),
|
||||
v_tomorrow_start,
|
||||
(v_count >= v_limit);
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION get_daily_response_limit_status() IS 'Returns daily response limit status for the current user. Premium users and disabled limits return is_blocked=false.';
|
||||
@@ -0,0 +1,205 @@
|
||||
-- Update get_recommended_questions to enforce daily response limit for non-premium users
|
||||
-- When daily limit is reached, return empty (old apps will show "All caught up")
|
||||
|
||||
CREATE OR REPLACE FUNCTION get_recommended_questions(target_pack_id UUID DEFAULT NULL)
|
||||
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[]
|
||||
)
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = 'public'
|
||||
AS $$
|
||||
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_gap_count INTEGER;
|
||||
v_user_max_intensity INTEGER;
|
||||
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 INTO v_partner_id, v_partner_gender
|
||||
FROM public.profiles p
|
||||
WHERE p.couple_id = v_couple_id AND p.id != v_user_id
|
||||
LIMIT 1;
|
||||
|
||||
-- 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
|
||||
-- Get daily limit from app_config
|
||||
SELECT COALESCE(ac.daily_response_limit, 0) INTO v_daily_limit
|
||||
FROM app_config ac
|
||||
LIMIT 1;
|
||||
|
||||
-- If daily limit > 0, check if user has reached it
|
||||
IF v_daily_limit > 0 THEN
|
||||
-- Calculate UTC day boundaries
|
||||
v_today_start := date_trunc('day', NOW() AT TIME ZONE 'UTC') AT TIME ZONE 'UTC';
|
||||
v_tomorrow_start := v_today_start + INTERVAL '1 day';
|
||||
|
||||
-- Count responses created today (UTC)
|
||||
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 over daily limit, return empty (old apps see "All caught up!")
|
||||
IF v_daily_count >= v_daily_limit THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
-- Check answer gap threshold (only when not browsing a specific pack)
|
||||
IF v_partner_id IS NOT NULL AND target_pack_id IS NULL THEN
|
||||
-- Get threshold from app_config
|
||||
SELECT COALESCE(ac.answer_gap_threshold, 10) INTO v_gap_threshold
|
||||
FROM app_config ac
|
||||
LIMIT 1;
|
||||
|
||||
-- If threshold > 0, check the gap
|
||||
IF v_gap_threshold > 0 THEN
|
||||
-- Count questions in ENABLED packs where user answered but partner hasn't
|
||||
WITH enabled_packs AS (
|
||||
SELECT cp.pack_id
|
||||
FROM couple_packs cp
|
||||
WHERE cp.couple_id = v_couple_id AND cp.enabled = true
|
||||
)
|
||||
SELECT COUNT(*)::integer INTO v_gap_count
|
||||
FROM responses r
|
||||
INNER JOIN questions q ON q.id = r.question_id
|
||||
WHERE r.user_id = v_user_id
|
||||
AND r.couple_id = v_couple_id
|
||||
AND EXISTS (SELECT 1 FROM enabled_packs)
|
||||
AND q.pack_id IN (SELECT ep.pack_id FROM enabled_packs ep)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM responses pr
|
||||
WHERE pr.question_id = r.question_id
|
||||
AND pr.user_id = v_partner_id
|
||||
);
|
||||
|
||||
-- If over threshold, return empty (old apps see "All caught up!")
|
||||
IF v_gap_count >= 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
|
||||
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
|
||||
)
|
||||
)
|
||||
-- Filter by user's max_intensity preference
|
||||
AND (
|
||||
q.intensity IS NULL
|
||||
OR q.intensity <= v_user_max_intensity
|
||||
);
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION get_recommended_questions(UUID) IS 'Returns recommended questions for user filtered by their intensity preference. When daily limit or answer gap threshold is exceeded for non-premium users, returns empty.';
|
||||
Reference in new issue
Block a user