This commit is contained in:
Jamie Brunton committed 2025-12-31 12:28:26 +00:00
1 parent 3ca3da4501
commit e7379ccdb1
10 files changed
+717 -11

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
# Agents Documentation
This file contains important project-specific context for Claude Code agents working on this repository.
## Redemption Code System
**IMPORTANT: Codes can only be redeemed on the website, NOT in the mobile app.**
Apple's App Store guidelines require that any premium features purchased within an iOS app must go through In-App Purchase. Adding a redemption code feature to the mobile app would violate these guidelines and risk app rejection.
### Overview
Promotional codes that grant users premium access without going through RevenueCat/App Store subscription flow.
### Database Schema
**`redemption_codes` table:**
- `id` (UUID) - Primary key
- `code` (TEXT, UNIQUE) - The redemption code
- `description` (TEXT) - Optional description
- `max_uses` (INTEGER) - Maximum number of redemptions allowed
- `current_uses` (INTEGER) - Current number of redemptions
- `expires_at` (TIMESTAMPTZ) - Optional expiration date
- `is_active` (BOOLEAN) - Whether the code can be redeemed
- `created_by` (UUID) - Admin who created the code
- `created_at` (TIMESTAMPTZ)
- `updated_at` (TIMESTAMPTZ)
**`code_redemptions` table:**
- `id` (UUID) - Primary key
- `code_id` (UUID) - Reference to redemption_codes
- `user_id` (UUID) - User who redeemed the code
- `redeemed_at` (TIMESTAMPTZ)
- UNIQUE constraint on (code_id, user_id) - Each user can only redeem a code once
### Components
1. **Admin UI** (`apps/admin/src/pages/RedemptionCodesPage.tsx`)
- Super admins can generate codes
- View all codes with usage stats
- Toggle active/inactive
- View who redeemed each code
- Delete codes
2. **Edge Function** (`apps/supabase/functions/redeem-code/index.ts`)
- **Unauthenticated** - accepts email + code in request body
- Calls the `redeem_code_by_email()` database function
- Returns success/error response
3. **Database Function** (`redeem_code_by_email(p_email TEXT, p_code TEXT)`)
- Atomic operation with row locking
- Looks up user by email (must have signed up in app first)
- Validates: code exists, is active, not expired, has uses remaining
- Checks user hasn't already redeemed
- Records redemption in `code_redemptions`
- Increments `current_uses`
- Sets `profiles.is_premium = true`
4. **Web UI** (`apps/web/app/redeem/page.tsx`)
- Public page at `/redeem`
- User enters email + redemption code
- Calls edge function via fetch
- Shows success or error message
### Environment Variables
The web app requires:
- `NEXT_PUBLIC_SUPABASE_URL` - Supabase project URL for API calls
### DO NOT
- **DO NOT** add redemption code UI to the mobile app
- **DO NOT** create any in-app mechanism to bypass App Store purchases
- **DO NOT** expose the redeem endpoint in mobile app Supabase calls
+6 -5
View File
@@ -145,14 +145,15 @@ Promotional codes that grant users premium access. **Codes can only be redeemed
**Components:** **Components:**
- **Admin UI** (`apps/admin/src/pages/RedemptionCodesPage.tsx`) - Super admins can generate, manage, and view redemption codes - **Admin UI** (`apps/admin/src/pages/RedemptionCodesPage.tsx`) - Super admins can generate, manage, and view redemption codes
- **Edge Function** (`apps/supabase/functions/redeem-code/`) - Validates and processes code redemption - **Edge Function** (`apps/supabase/functions/redeem-code/`) - Validates and processes code redemption (unauthenticated, accepts email + code)
- **Database Function** (`redeem_code(p_code)`) - Atomic redemption with validation (active, not expired, has uses remaining, user hasn't redeemed) - **Database Function** (`redeem_code_by_email(p_email, p_code)`) - Atomic redemption with validation (active, not expired, has uses remaining, user hasn't redeemed)
- **Web UI** (`apps/web/app/redeem/page.tsx`) - Public redemption page
**Flow:** **Flow:**
1. Admin generates code in admin dashboard 1. Admin generates code in admin dashboard
2. User enters code on website (NOT mobile app) 2. User visits `/redeem` on website and enters email + code
3. `redeem-code` edge function calls `redeem_code()` database function 3. `redeem-code` edge function calls `redeem_code_by_email()` database function
4. On success, user's `profiles.is_premium` is set to `true` 4. Database function looks up user by email, validates code, and sets `profiles.is_premium = true`
**Important:** Do NOT add redemption code UI to the mobile app. Apple requires in-app purchases for premium features purchased within iOS apps. **Important:** Do NOT add redemption code UI to the mobile app. Apple requires in-app purchases for premium features purchased within iOS apps.
@@ -0,0 +1,496 @@
import { useState, useEffect } from 'react';
import { supabase } from '@/config';
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Switch } from '@/components/ui/switch';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Search, Ticket, Trash2, Plus, Copy, Users } from 'lucide-react';
import { format } from 'date-fns';
import { toast } from 'sonner';
interface RedemptionCode {
id: string;
code: string;
description: string | null;
max_uses: number;
current_uses: number;
expires_at: string | null;
is_active: boolean;
created_by: string | null;
created_at: string;
updated_at: string;
}
interface CodeRedemption {
id: string;
user_id: string;
redeemed_at: string;
profile?: {
name: string | null;
email: string | null;
};
}
function generateCode(length: number = 8): string {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Removed confusing chars like 0, O, I, 1
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
export function RedemptionCodesPage() {
const [codes, setCodes] = useState<RedemptionCode[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState('');
// Add Code State
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [formData, setFormData] = useState({
code: '',
description: '',
max_uses: 1,
expires_at: '',
});
// View Redemptions State
const [viewingCode, setViewingCode] = useState<RedemptionCode | null>(null);
const [redemptions, setRedemptions] = useState<CodeRedemption[]>([]);
const [loadingRedemptions, setLoadingRedemptions] = useState(false);
// Initial load
useEffect(() => {
fetchCodes();
}, []);
const fetchCodes = async () => {
setLoading(true);
try {
const { data, error } = await supabase
.from('redemption_codes')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
setCodes(data || []);
} catch (error: any) {
console.error('Failed to load codes:', error);
toast.error("Failed to load redemption codes");
} finally {
setLoading(false);
}
};
const fetchRedemptions = async (codeId: string) => {
setLoadingRedemptions(true);
try {
const { data: redemptionData, error: redemptionError } = await supabase
.from('code_redemptions')
.select('id, user_id, redeemed_at')
.eq('code_id', codeId)
.order('redeemed_at', { ascending: false });
if (redemptionError) throw redemptionError;
if (redemptionData && redemptionData.length > 0) {
const userIds = redemptionData.map(r => r.user_id);
const { data: profileData } = await supabase
.from('profiles')
.select('id, name, email')
.in('id', userIds);
const joined = redemptionData.map(r => ({
...r,
profile: profileData?.find(p => p.id === r.user_id)
}));
setRedemptions(joined);
} else {
setRedemptions([]);
}
} catch (error: any) {
console.error('Failed to load redemptions:', error);
toast.error("Failed to load redemptions");
} finally {
setLoadingRedemptions(false);
}
};
const handleAddCode = async () => {
if (!formData.code.trim()) {
toast.error("Please enter a code");
return;
}
setIsSubmitting(true);
try {
const { error } = await auditedSupabase.insert('redemption_codes', {
code: formData.code.toUpperCase().trim(),
description: formData.description.trim() || null,
max_uses: formData.max_uses,
current_uses: 0,
expires_at: formData.expires_at || null,
is_active: true,
});
if (error) throw error;
toast.success("Redemption code created");
setIsAddDialogOpen(false);
resetForm();
fetchCodes();
} catch (error: any) {
console.error('Failed to create code:', error);
if (error.message?.includes('duplicate') || error.code === '23505') {
toast.error("This code already exists");
} else {
toast.error(error.message || "Failed to create code");
}
} finally {
setIsSubmitting(false);
}
};
const handleToggleActive = async (code: RedemptionCode) => {
try {
const { error } = await auditedSupabase.update('redemption_codes', code.id, {
is_active: !code.is_active,
});
if (error) throw error;
toast.success(code.is_active ? "Code deactivated" : "Code activated");
fetchCodes();
} catch (error: any) {
toast.error("Failed to update code");
}
};
const handleDeleteCode = async (code: RedemptionCode) => {
if (!confirm(`Are you sure you want to delete the code "${code.code}"? This cannot be undone.`)) {
return;
}
try {
const { error } = await auditedSupabase.delete('redemption_codes', code.id);
if (error) throw error;
toast.success("Code deleted");
fetchCodes();
} catch (error: any) {
toast.error("Failed to delete code");
}
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast.success("Copied to clipboard");
};
const resetForm = () => {
setFormData({
code: '',
description: '',
max_uses: 1,
expires_at: '',
});
};
const handleOpenAddDialog = () => {
resetForm();
setFormData(prev => ({ ...prev, code: generateCode() }));
setIsAddDialogOpen(true);
};
const handleViewRedemptions = (code: RedemptionCode) => {
setViewingCode(code);
fetchRedemptions(code.id);
};
const filteredCodes = codes.filter(code => {
if (!search) return true;
const query = search.toLowerCase();
return (
code.code.toLowerCase().includes(query) ||
code.description?.toLowerCase().includes(query)
);
});
const getStatusBadge = (code: RedemptionCode) => {
if (!code.is_active) {
return <Badge variant="secondary">Inactive</Badge>;
}
if (code.expires_at && new Date(code.expires_at) < new Date()) {
return <Badge variant="destructive">Expired</Badge>;
}
if (code.current_uses >= code.max_uses) {
return <Badge variant="outline">Exhausted</Badge>;
}
return <Badge variant="default">Active</Badge>;
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Redemption Codes</h1>
<p className="text-muted-foreground">
Generate and manage codes that grant premium access
</p>
</div>
<div className="flex items-center gap-4">
<div className="relative w-64">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search codes..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
/>
</div>
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogTrigger asChild>
<Button onClick={handleOpenAddDialog}>
<Plus className="h-4 w-4 mr-2" />
Generate Code
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Generate Redemption Code</DialogTitle>
<DialogDescription>
Create a new code that users can redeem for premium access.
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>Code</Label>
<div className="flex gap-2">
<Input
value={formData.code}
onChange={(e) => setFormData(prev => ({ ...prev, code: e.target.value.toUpperCase() }))}
placeholder="e.g., PREMIUM2024"
className="font-mono"
/>
<Button
variant="outline"
size="icon"
onClick={() => setFormData(prev => ({ ...prev, code: generateCode() }))}
title="Generate random code"
>
<Ticket className="h-4 w-4" />
</Button>
</div>
</div>
<div className="grid gap-2">
<Label>Description (optional)</Label>
<Input
value={formData.description}
onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
placeholder="e.g., Early adopter reward"
/>
</div>
<div className="grid gap-2">
<Label>Max Uses</Label>
<Input
type="number"
min={1}
value={formData.max_uses}
onChange={(e) => setFormData(prev => ({ ...prev, max_uses: parseInt(e.target.value) || 1 }))}
/>
<p className="text-xs text-muted-foreground">
How many times this code can be redeemed
</p>
</div>
<div className="grid gap-2">
<Label>Expires At (optional)</Label>
<Input
type="datetime-local"
value={formData.expires_at}
onChange={(e) => setFormData(prev => ({ ...prev, expires_at: e.target.value }))}
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>Cancel</Button>
<Button onClick={handleAddCode} disabled={!formData.code.trim() || isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create Code'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</div>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Code</TableHead>
<TableHead>Description</TableHead>
<TableHead>Usage</TableHead>
<TableHead>Expires</TableHead>
<TableHead>Status</TableHead>
<TableHead>Created</TableHead>
<TableHead className="w-[150px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={7} className="text-center py-8">
<div className="flex justify-center"><Skeleton className="h-6 w-32" /></div>
</TableCell>
</TableRow>
) : filteredCodes.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
{search ? 'No codes match your search.' : 'No redemption codes yet. Generate your first one!'}
</TableCell>
</TableRow>
) : (
filteredCodes.map((code) => (
<TableRow key={code.id}>
<TableCell>
<div className="flex items-center gap-2">
<code className="font-mono font-medium text-sm bg-muted px-2 py-1 rounded">
{code.code}
</code>
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={() => copyToClipboard(code.code)}
title="Copy code"
>
<Copy className="h-3 w-3" />
</Button>
</div>
</TableCell>
<TableCell className="text-muted-foreground">
{code.description || '—'}
</TableCell>
<TableCell>
<span className="font-medium">{code.current_uses}</span>
<span className="text-muted-foreground"> / {code.max_uses}</span>
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{code.expires_at
? format(new Date(code.expires_at), 'MMM d, yyyy HH:mm')
: 'Never'}
</TableCell>
<TableCell>
{getStatusBadge(code)}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{format(new Date(code.created_at), 'MMM d, yyyy')}
</TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
onClick={() => handleViewRedemptions(code)}
title="View redemptions"
>
<Users className="h-4 w-4" />
</Button>
<Switch
checked={code.is_active}
onCheckedChange={() => handleToggleActive(code)}
title={code.is_active ? "Deactivate" : "Activate"}
/>
<Button
variant="ghost"
size="icon"
className="text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => handleDeleteCode(code)}
title="Delete code"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* View Redemptions Dialog */}
<Dialog open={!!viewingCode} onOpenChange={(open) => !open && setViewingCode(null)}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>
Redemptions for <code className="font-mono bg-muted px-2 py-0.5 rounded">{viewingCode?.code}</code>
</DialogTitle>
<DialogDescription>
{viewingCode?.current_uses || 0} of {viewingCode?.max_uses} uses
</DialogDescription>
</DialogHeader>
<div className="max-h-[300px] overflow-y-auto">
{loadingRedemptions ? (
<div className="flex justify-center py-8">
<Skeleton className="h-6 w-32" />
</div>
) : redemptions.length === 0 ? (
<p className="text-center py-8 text-muted-foreground">
No one has redeemed this code yet.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>User</TableHead>
<TableHead>Redeemed At</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{redemptions.map((r) => (
<TableRow key={r.id}>
<TableCell>
<div>
<div className="font-medium">{r.profile?.name || 'Unknown'}</div>
<div className="text-xs text-muted-foreground">{r.profile?.email}</div>
</div>
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{format(new Date(r.redeemed_at), 'MMM d, yyyy HH:mm')}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setViewingCode(null)}>Close</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+3
View File
@@ -14,3 +14,6 @@ local.properties
# Bundle artifacts # Bundle artifacts
*.jsbundle *.jsbundle
# Release signing (upload keystore - can be reset via Play Console)
upload-keystore.jks
+7 -1
View File
@@ -103,13 +103,19 @@ android {
keyAlias 'androiddebugkey' keyAlias 'androiddebugkey'
keyPassword 'android' keyPassword 'android'
} }
release {
storeFile file('upload-keystore.jks')
storePassword System.getenv("KEYSTORE_PASSWORD") ?: "changeit"
keyAlias 'upload'
keyPassword System.getenv("KEY_PASSWORD") ?: "changeit"
}
} }
buildTypes { buildTypes {
debug { debug {
signingConfig signingConfigs.debug signingConfig signingConfigs.debug
} }
release { release {
signingConfig signingConfigs.debug signingConfig signingConfigs.release
shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false) shrinkResources (findProperty('android.enableShrinkResourcesInReleaseBuilds')?.toBoolean() ?: false)
minifyEnabled enableProguardInReleaseBuilds minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
@@ -0,0 +1,29 @@
{
"project_info": {
"project_number": "764866133492",
"project_id": "sauci-6840e",
"storage_bucket": "sauci-6840e.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:764866133492:android:eabdb78009a18d2ffe4da1",
"android_client_info": {
"package_name": "com.sauci.app"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyDOAqIXAd_dy7L9ZflPvNkJdNXWMaGZ1O4"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
Binary file not shown.
@@ -0,0 +1,73 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
interface RedeemCodeBody {
email: string;
code: string;
}
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
// Use service role for database operations since this is unauthenticated
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Parse request body
const { email, code }: RedeemCodeBody = await req.json();
if (!email || typeof email !== "string" || email.trim() === "") {
return new Response(
JSON.stringify({ success: false, error: "Please enter your email address" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
if (!code || typeof code !== "string" || code.trim() === "") {
return new Response(
JSON.stringify({ success: false, error: "Please enter a redemption code" }),
{ status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Call the database function to redeem the code
const { data, error } = await supabase.rpc("redeem_code_by_email", {
p_email: email.trim(),
p_code: code.trim(),
});
if (error) {
console.error("RPC error:", error);
return new Response(
JSON.stringify({ success: false, error: "Failed to redeem code. Please try again." }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// The RPC returns a JSONB object with success, error, or message
return new Response(
JSON.stringify(data),
{
status: data.success ? 200 : 400,
headers: { ...corsHeaders, "Content-Type": "application/json" }
}
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ success: false, error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
+3
View File
@@ -2,3 +2,6 @@
# Get these values from your PostHog project settings # Get these values from your PostHog project settings
NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_key_here NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_key_here
NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
+27 -5
View File
@@ -34,12 +34,34 @@ export default function RedeemPage() {
setIsLoading(true) setIsLoading(true)
// TODO: Wire up to backend try {
// For now, just simulate a delay and show success const response = await fetch(
await new Promise(resolve => setTimeout(resolve, 1500)) `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/redeem-code`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email.trim(),
code: code.trim(),
}),
}
)
setIsLoading(false) const data = await response.json()
setIsRedeemed(true)
if (data.success) {
setIsRedeemed(true)
} else {
setError(data.error || 'Failed to redeem code. Please try again.')
}
} catch (err) {
console.error('Redemption error:', err)
setError('Something went wrong. Please try again.')
} finally {
setIsLoading(false)
}
} }
// Success state // Success state