mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-10-31 10:19:43 +00:00
Merge admin portal coverage for quiz, dares loop, subscriptions, couples, and live draw into staging
This commit is contained in:
commit
f52b8536be
22 files changed
+2091
-79
No files matched your search
@@ -11,8 +11,10 @@ import { QuestionAnalyticsPage } from '@/pages/content/QuestionAnalyticsPage';
|
||||
import { TagsPage } from '@/pages/content/TagsPage';
|
||||
import { DarePacksPage } from '@/pages/content/DarePacksPage';
|
||||
import { DaresPage } from '@/pages/content/DaresPage';
|
||||
import { QuizQuestionsPage } from '@/pages/content/QuizQuestionsPage';
|
||||
import { UsersPage } from '@/pages/users/UsersPage';
|
||||
import { UserDetailPage } from '@/pages/users/UserDetailPage';
|
||||
import { CouplesPage } from '@/pages/users/CouplesPage';
|
||||
import { MatchChatPage } from '@/pages/users/MatchChatPage';
|
||||
import { AuditLogsPage } from '@/pages/AuditLogsPage';
|
||||
import { AdminsPage } from '@/pages/admins/AdminsPage';
|
||||
@@ -20,6 +22,8 @@ import { RedemptionCodesPage } from '@/pages/RedemptionCodesPage';
|
||||
import { FeedbackPage } from '@/pages/FeedbackPage';
|
||||
import { UsageInsightsPage } from '@/pages/UsageInsightsPage';
|
||||
import { UserActivityPage } from '@/pages/activity/UserActivityPage';
|
||||
import { SentDaresPage } from '@/pages/activity/SentDaresPage';
|
||||
import { LiveDrawSessionsPage } from '@/pages/activity/LiveDrawSessionsPage';
|
||||
import { AiSettingsPage } from '@/pages/AiSettingsPage';
|
||||
import { AppSettingsPage } from '@/pages/AppSettingsPage';
|
||||
import { FlaggedMessagesPage } from '@/pages/FlaggedMessagesPage';
|
||||
@@ -108,6 +112,14 @@ function App() {
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/quiz-questions"
|
||||
element={
|
||||
<ProtectedRoute requiredPermission={PERMISSION_KEYS.MANAGE_QUESTIONS}>
|
||||
<QuizQuestionsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* User management */}
|
||||
<Route
|
||||
@@ -142,6 +154,14 @@ function App() {
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/couples"
|
||||
element={
|
||||
<ProtectedRoute requiredPermission={PERMISSION_KEYS.VIEW_USERS}>
|
||||
<CouplesPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/activity"
|
||||
element={
|
||||
@@ -150,6 +170,22 @@ function App() {
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/activity/sent-dares"
|
||||
element={
|
||||
<ProtectedRoute requiredPermission={PERMISSION_KEYS.VIEW_ACTIVITY}>
|
||||
<SentDaresPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/activity/live-draw"
|
||||
element={
|
||||
<ProtectedRoute requiredPermission={PERMISSION_KEYS.VIEW_USERS}>
|
||||
<LiveDrawSessionsPage />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* System */}
|
||||
<Route
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export interface StrokePoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface StrokeSegment {
|
||||
id: string;
|
||||
userId: string;
|
||||
points: StrokePoint[];
|
||||
color: string;
|
||||
width: number;
|
||||
timestamp: number;
|
||||
isEraser: boolean;
|
||||
}
|
||||
|
||||
export const STROKE_CANVAS_BACKGROUND = '#1a1a2e';
|
||||
|
||||
/**
|
||||
* Renders a `live_draw_sessions.strokes` array to a canvas. Points are stored
|
||||
* as 0..1 fractions of the drawing surface, so this scales to whatever size
|
||||
* the canvas element is laid out at.
|
||||
*/
|
||||
export function StrokeCanvas({ strokes }: { strokes: StrokeSegment[] }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const w = canvas.clientWidth;
|
||||
const h = canvas.clientHeight;
|
||||
canvas.width = w * dpr;
|
||||
canvas.height = h * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
ctx.fillStyle = STROKE_CANVAS_BACKGROUND;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
|
||||
for (const stroke of strokes) {
|
||||
if (stroke.points.length === 0) continue;
|
||||
ctx.strokeStyle = stroke.isEraser ? STROKE_CANVAS_BACKGROUND : stroke.color;
|
||||
ctx.lineWidth = stroke.width;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.beginPath();
|
||||
|
||||
const first = stroke.points[0];
|
||||
ctx.moveTo(first.x * w, first.y * h);
|
||||
|
||||
if (stroke.points.length === 1) {
|
||||
ctx.lineTo(first.x * w + 0.1, first.y * h + 0.1);
|
||||
} else {
|
||||
for (let i = 1; i < stroke.points.length; i++) {
|
||||
const prev = stroke.points[i - 1];
|
||||
const curr = stroke.points[i];
|
||||
const midX = ((prev.x + curr.x) / 2) * w;
|
||||
const midY = ((prev.y + curr.y) / 2) * h;
|
||||
|
||||
if (i === 1) {
|
||||
ctx.lineTo(midX, midY);
|
||||
} else {
|
||||
ctx.quadraticCurveTo(prev.x * w, prev.y * h, midX, midY);
|
||||
}
|
||||
}
|
||||
const last = stroke.points[stroke.points.length - 1];
|
||||
ctx.lineTo(last.x * w, last.y * h);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
}, [strokes]);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl overflow-hidden border" style={{ background: STROKE_CANVAS_BACKGROUND }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ width: '100%', aspectRatio: '4/3', display: 'block' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,10 @@ import {
|
||||
PieChart,
|
||||
Tags,
|
||||
Zap,
|
||||
HelpCircle,
|
||||
Heart,
|
||||
Swords,
|
||||
Pencil,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
@@ -68,6 +72,12 @@ const contentNav: NavItem[] = [
|
||||
icon: <Tags className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.MANAGE_PACKS,
|
||||
},
|
||||
{
|
||||
label: 'Quiz Questions',
|
||||
href: '/quiz-questions',
|
||||
icon: <HelpCircle className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.MANAGE_QUESTIONS,
|
||||
},
|
||||
];
|
||||
|
||||
const usersNav: NavItem[] = [
|
||||
@@ -83,6 +93,24 @@ const usersNav: NavItem[] = [
|
||||
icon: <Activity className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.VIEW_ACTIVITY,
|
||||
},
|
||||
{
|
||||
label: 'Sent Dares',
|
||||
href: '/activity/sent-dares',
|
||||
icon: <Swords className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.VIEW_ACTIVITY,
|
||||
},
|
||||
{
|
||||
label: 'Live Draw Sessions',
|
||||
href: '/activity/live-draw',
|
||||
icon: <Pencil className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.VIEW_USERS,
|
||||
},
|
||||
{
|
||||
label: 'Couples',
|
||||
href: '/couples',
|
||||
icon: <Heart className="h-5 w-5" />,
|
||||
requiredPermission: PERMISSION_KEYS.VIEW_USERS,
|
||||
},
|
||||
{
|
||||
label: 'Usage Insights',
|
||||
href: '/usage-insights',
|
||||
|
||||
@@ -7,6 +7,7 @@ const AUDITED_TABLES = [
|
||||
'categories',
|
||||
'dare_packs',
|
||||
'dares',
|
||||
'quiz_questions',
|
||||
'profiles',
|
||||
'couples',
|
||||
'responses',
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildCoupleSearchFilter, coupleStatusFromMemberCount } from './couples';
|
||||
|
||||
describe('coupleStatusFromMemberCount', () => {
|
||||
it('treats zero or one member as pending', () => {
|
||||
expect(coupleStatusFromMemberCount(0)).toBe('pending');
|
||||
expect(coupleStatusFromMemberCount(1)).toBe('pending');
|
||||
});
|
||||
|
||||
it('treats two or more members as paired', () => {
|
||||
expect(coupleStatusFromMemberCount(2)).toBe('paired');
|
||||
expect(coupleStatusFromMemberCount(3)).toBe('paired');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildCoupleSearchFilter', () => {
|
||||
it('returns null for an empty or blank search', () => {
|
||||
expect(buildCoupleSearchFilter('')).toBeNull();
|
||||
expect(buildCoupleSearchFilter(' ')).toBeNull();
|
||||
});
|
||||
|
||||
it('matches a uuid-shaped search as an exact id filter', () => {
|
||||
expect(buildCoupleSearchFilter('a1b2c3d4-1111-1111-1111-111111111111')).toEqual({
|
||||
column: 'id', op: 'eq', value: 'a1b2c3d4-1111-1111-1111-111111111111',
|
||||
});
|
||||
});
|
||||
|
||||
it('treats any other search as a partial invite code match', () => {
|
||||
expect(buildCoupleSearchFilter('SUNSET42')).toEqual({
|
||||
column: 'invite_code', op: 'ilike', value: '%SUNSET42%',
|
||||
});
|
||||
});
|
||||
|
||||
it('trims surrounding whitespace before deciding the filter shape', () => {
|
||||
expect(buildCoupleSearchFilter(' sunset42 ')).toEqual({
|
||||
column: 'invite_code', op: 'ilike', value: '%sunset42%',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
// Couples do not carry an explicit "paired" flag (see apps/api/src/domains/couples/schema.ts).
|
||||
// Pairing is inferred from how many profiles currently reference the couple id, the same
|
||||
// approach UsersPage already uses inline for the couple badge on a profile row.
|
||||
|
||||
export type CoupleStatus = 'paired' | 'pending';
|
||||
|
||||
/**
|
||||
* Derive whether a couple is fully paired from the number of profiles that
|
||||
* reference it. A couple starts with one member (the creator) and becomes
|
||||
* paired once a partner joins via invite code.
|
||||
*/
|
||||
export function coupleStatusFromMemberCount(memberCount: number): CoupleStatus {
|
||||
return memberCount >= 2 ? 'paired' : 'pending';
|
||||
}
|
||||
|
||||
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export type CoupleSearchFilter =
|
||||
| { column: 'id'; op: 'eq'; value: string }
|
||||
| { column: 'invite_code'; op: 'ilike'; value: string }
|
||||
| null;
|
||||
|
||||
/**
|
||||
* Build the admin query filter for the couples search box. A UUID-shaped
|
||||
* search term is treated as an exact id lookup; anything else is matched
|
||||
* against the invite code with a case-insensitive partial match.
|
||||
*/
|
||||
export function buildCoupleSearchFilter(rawSearch: string): CoupleSearchFilter {
|
||||
const search = rawSearch.trim();
|
||||
if (!search) return null;
|
||||
if (UUID_PATTERN.test(search)) {
|
||||
return { column: 'id', op: 'eq', value: search };
|
||||
}
|
||||
return { column: 'invite_code', op: 'ilike', value: `%${search}%` };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { clampDareIntensity, parseIntensityRange } from './dareIntensity';
|
||||
|
||||
describe('clampDareIntensity', () => {
|
||||
it('accepts values within the 1-5 range', () => {
|
||||
expect(clampDareIntensity('1')).toBe(1);
|
||||
expect(clampDareIntensity('3')).toBe(3);
|
||||
expect(clampDareIntensity('5')).toBe(5);
|
||||
});
|
||||
|
||||
it('falls back to 1 for missing, non-numeric, or out-of-range values', () => {
|
||||
expect(clampDareIntensity('')).toBe(1);
|
||||
expect(clampDareIntensity('abc')).toBe(1);
|
||||
expect(clampDareIntensity('0')).toBe(1);
|
||||
expect(clampDareIntensity('6')).toBe(1);
|
||||
});
|
||||
|
||||
it('falls back to a custom default when provided', () => {
|
||||
expect(clampDareIntensity('', 3)).toBe(3);
|
||||
expect(clampDareIntensity('9', 3)).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseIntensityRange', () => {
|
||||
it('allows both bounds blank', () => {
|
||||
expect(parseIntensityRange('', '')).toEqual({ range: { min: null, max: null }, error: null });
|
||||
});
|
||||
|
||||
it('parses valid bounds', () => {
|
||||
expect(parseIntensityRange('2', '4')).toEqual({ range: { min: 2, max: 4 }, error: null });
|
||||
});
|
||||
|
||||
it('rejects a minimum outside 1-5', () => {
|
||||
const { error } = parseIntensityRange('0', '');
|
||||
expect(error).toMatch(/Minimum intensity/);
|
||||
});
|
||||
|
||||
it('rejects a maximum outside 1-5', () => {
|
||||
const { error } = parseIntensityRange('', '6');
|
||||
expect(error).toMatch(/Maximum intensity/);
|
||||
});
|
||||
|
||||
it('rejects a minimum greater than the maximum', () => {
|
||||
const { error } = parseIntensityRange('4', '2');
|
||||
expect(error).toMatch(/cannot be greater than/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// Dares and dare packs both gate on a 1-5 intensity scale (see
|
||||
// apps/api/drizzle/0010_admin.sql and 0013_dares_loop.sql). These helpers keep
|
||||
// the admin form validation consistent with that range.
|
||||
|
||||
export const MIN_DARE_INTENSITY = 1;
|
||||
export const MAX_DARE_INTENSITY = 5;
|
||||
|
||||
/**
|
||||
* Clamp a raw form value to a valid dare intensity (1-5), falling back to 1
|
||||
* when the value is missing or not a finite number in range.
|
||||
*/
|
||||
export function clampDareIntensity(rawValue: string, fallback: number = MIN_DARE_INTENSITY): number {
|
||||
const parsed = parseInt(rawValue, 10);
|
||||
if (!Number.isFinite(parsed) || parsed < MIN_DARE_INTENSITY || parsed > MAX_DARE_INTENSITY) {
|
||||
return fallback;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export interface IntensityRange {
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse and validate an optional min/max intensity pair for a dare pack.
|
||||
* Returns the parsed range, or an error message when the values are invalid.
|
||||
*/
|
||||
export function parseIntensityRange(rawMin: string, rawMax: string): { range: IntensityRange; error: string | null } {
|
||||
const min = rawMin.trim() ? parseInt(rawMin, 10) : null;
|
||||
const max = rawMax.trim() ? parseInt(rawMax, 10) : null;
|
||||
|
||||
if (min !== null && (!Number.isFinite(min) || min < MIN_DARE_INTENSITY || min > MAX_DARE_INTENSITY)) {
|
||||
return { range: { min: null, max: null }, error: 'Minimum intensity must be between 1 and 5' };
|
||||
}
|
||||
if (max !== null && (!Number.isFinite(max) || max < MIN_DARE_INTENSITY || max > MAX_DARE_INTENSITY)) {
|
||||
return { range: { min: null, max: null }, error: 'Maximum intensity must be between 1 and 5' };
|
||||
}
|
||||
if (min !== null && max !== null && min > max) {
|
||||
return { range: { min: null, max: null }, error: 'Minimum intensity cannot be greater than maximum intensity' };
|
||||
}
|
||||
|
||||
return { range: { min, max }, error: null };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeQuizOptions, validateQuizQuestionForm } from './quizQuestions';
|
||||
|
||||
describe('sanitizeQuizOptions', () => {
|
||||
it('trims and drops empty options', () => {
|
||||
expect(sanitizeQuizOptions([' A ', '', ' ', 'B'])).toEqual(['A', 'B']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateQuizQuestionForm', () => {
|
||||
const base = {
|
||||
prompt_self: 'What is your favourite season?',
|
||||
prompt_guess: "What is your partner's favourite season?",
|
||||
options: ['Spring', 'Summer'],
|
||||
};
|
||||
|
||||
it('accepts a valid form', () => {
|
||||
expect(validateQuizQuestionForm(base)).toBeNull();
|
||||
});
|
||||
|
||||
it('requires the self prompt', () => {
|
||||
expect(validateQuizQuestionForm({ ...base, prompt_self: ' ' })).toMatch(/about yourself/);
|
||||
});
|
||||
|
||||
it('requires the guess prompt', () => {
|
||||
expect(validateQuizQuestionForm({ ...base, prompt_guess: '' })).toMatch(/about your partner/);
|
||||
});
|
||||
|
||||
it('requires at least two options', () => {
|
||||
expect(validateQuizQuestionForm({ ...base, options: ['Only one'] })).toMatch(/At least 2 options/);
|
||||
});
|
||||
|
||||
it('allows at most four options', () => {
|
||||
expect(validateQuizQuestionForm({ ...base, options: ['A', 'B', 'C', 'D', 'E'] })).toMatch(/At most 4 options/);
|
||||
});
|
||||
|
||||
it('ignores blank options when counting', () => {
|
||||
expect(validateQuizQuestionForm({ ...base, options: ['Spring', 'Summer', '', ''] })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Quiz question options are constrained by the database check
|
||||
// `array_length(options, 1) between 2 and 4` (see
|
||||
// apps/api/drizzle/0019_quiz.sql). These helpers keep the admin form
|
||||
// validation consistent with that constraint.
|
||||
|
||||
export const MIN_QUIZ_OPTIONS = 2;
|
||||
export const MAX_QUIZ_OPTIONS = 4;
|
||||
|
||||
export interface QuizQuestionFormValues {
|
||||
prompt_self: string;
|
||||
prompt_guess: string;
|
||||
options: string[];
|
||||
}
|
||||
|
||||
/** Trim options and drop any that are empty. */
|
||||
export function sanitizeQuizOptions(options: string[]): string[] {
|
||||
return options.map((option) => option.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a quiz question form. Returns an error message, or null when the
|
||||
* form is valid.
|
||||
*/
|
||||
export function validateQuizQuestionForm(form: QuizQuestionFormValues): string | null {
|
||||
if (!form.prompt_self.trim()) return 'The "about yourself" prompt is required';
|
||||
if (!form.prompt_guess.trim()) return 'The "about your partner" prompt is required';
|
||||
const cleanedOptions = sanitizeQuizOptions(form.options);
|
||||
if (cleanedOptions.length < MIN_QUIZ_OPTIONS) return `At least ${MIN_QUIZ_OPTIONS} options are required`;
|
||||
if (cleanedOptions.length > MAX_QUIZ_OPTIONS) return `At most ${MAX_QUIZ_OPTIONS} options are allowed`;
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isSentDareOverdue, SENT_DARE_STATUS_LABELS } from './sentDares';
|
||||
|
||||
describe('SENT_DARE_STATUS_LABELS', () => {
|
||||
it('has a label for every documented status', () => {
|
||||
for (const status of ['pending', 'active', 'submitted', 'completed', 'expired', 'declined', 'cancelled'] as const) {
|
||||
expect(SENT_DARE_STATUS_LABELS[status].label).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSentDareOverdue', () => {
|
||||
const now = new Date('2026-08-30T12:00:00Z');
|
||||
|
||||
it('is false when there is no expiry', () => {
|
||||
expect(isSentDareOverdue('pending', null, now)).toBe(false);
|
||||
});
|
||||
|
||||
it('is false for a terminal status even if expiry has passed', () => {
|
||||
expect(isSentDareOverdue('completed', '2026-08-01T00:00:00Z', now)).toBe(false);
|
||||
expect(isSentDareOverdue('expired', '2026-08-01T00:00:00Z', now)).toBe(false);
|
||||
});
|
||||
|
||||
it('is false for an open status whose expiry has not passed', () => {
|
||||
expect(isSentDareOverdue('active', '2026-09-01T00:00:00Z', now)).toBe(false);
|
||||
});
|
||||
|
||||
it('is true for an open status whose expiry has already passed', () => {
|
||||
expect(isSentDareOverdue('pending', '2026-08-01T00:00:00Z', now)).toBe(true);
|
||||
expect(isSentDareOverdue('active', '2026-08-01T00:00:00Z', now)).toBe(true);
|
||||
expect(isSentDareOverdue('submitted', '2026-08-01T00:00:00Z', now)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
// sent_dares status lifecycle mirrors the check constraint added in
|
||||
// apps/api/drizzle/0013_dares_loop.sql: pending -> active -> submitted -> completed,
|
||||
// with expired/declined/cancelled as terminal side branches.
|
||||
|
||||
export const SENT_DARE_STATUSES = [
|
||||
'pending', 'active', 'submitted', 'completed', 'expired', 'declined', 'cancelled',
|
||||
] as const;
|
||||
|
||||
export type SentDareStatus = typeof SENT_DARE_STATUSES[number];
|
||||
|
||||
export type BadgeVariant = 'default' | 'secondary' | 'destructive' | 'outline';
|
||||
|
||||
export const SENT_DARE_STATUS_LABELS: Record<SentDareStatus, { label: string; variant: BadgeVariant }> = {
|
||||
pending: { label: 'Pending', variant: 'secondary' },
|
||||
active: { label: 'Active', variant: 'default' },
|
||||
submitted: { label: 'Submitted', variant: 'default' },
|
||||
completed: { label: 'Completed', variant: 'outline' },
|
||||
expired: { label: 'Expired', variant: 'destructive' },
|
||||
declined: { label: 'Declined', variant: 'destructive' },
|
||||
cancelled: { label: 'Cancelled', variant: 'outline' },
|
||||
};
|
||||
|
||||
const OPEN_STATUSES: ReadonlySet<SentDareStatus> = new Set(['pending', 'active', 'submitted']);
|
||||
|
||||
/**
|
||||
* A dare is overdue when it is still in an open state but its expiry has
|
||||
* already passed. The worker sweeps these to `expired` asynchronously, so the
|
||||
* admin view can lag the true status briefly; this flags that gap for support.
|
||||
*/
|
||||
export function isSentDareOverdue(
|
||||
status: string,
|
||||
expiresAt: string | null,
|
||||
now: Date = new Date(),
|
||||
): boolean {
|
||||
if (!expiresAt) return false;
|
||||
if (!OPEN_STATUSES.has(status as SentDareStatus)) return false;
|
||||
return new Date(expiresAt).getTime() < now.getTime();
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { adminData } from '@/lib/adminApi';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { PaginationControls } from '@/components/ui/pagination';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Pencil, Eye } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { toast } from 'sonner';
|
||||
import { StrokeCanvas, type StrokeSegment } from '@/components/content/StrokeCanvas';
|
||||
|
||||
interface LiveDrawSession {
|
||||
couple_id: string;
|
||||
revision: number;
|
||||
updated_by: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface Profile {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
couple_id: string | null;
|
||||
}
|
||||
|
||||
export function LiveDrawSessionsPage() {
|
||||
const [sessions, setSessions] = useState<LiveDrawSession[]>([]);
|
||||
const [membersByCouple, setMembersByCouple] = useState<Record<string, Profile[]>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const [selectedCoupleId, setSelectedCoupleId] = useState<string | null>(null);
|
||||
const [strokes, setStrokes] = useState<StrokeSegment[]>([]);
|
||||
const [strokesLoading, setStrokesLoading] = useState(false);
|
||||
|
||||
const fetchSessions = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const from = (page - 1) * pageSize;
|
||||
const to = from + pageSize - 1;
|
||||
|
||||
const { data, error, count } = await adminData
|
||||
.from<LiveDrawSession>('live_draw_sessions')
|
||||
.select('couple_id, revision, updated_by, created_at, updated_at', { count: 'exact' })
|
||||
.order('updated_at', { ascending: false })
|
||||
.range(from, to);
|
||||
if (error) throw error;
|
||||
|
||||
const rows = data || [];
|
||||
setSessions(rows);
|
||||
setTotal(count || 0);
|
||||
|
||||
const coupleIds = rows.map((row) => row.couple_id);
|
||||
if (coupleIds.length > 0) {
|
||||
const { data: profiles } = await adminData
|
||||
.from<Profile>('profiles')
|
||||
.select('id, name, email, couple_id')
|
||||
.in('couple_id', coupleIds);
|
||||
const grouped: Record<string, Profile[]> = {};
|
||||
(profiles || []).forEach((profile) => {
|
||||
if (!profile.couple_id) return;
|
||||
(grouped[profile.couple_id] ??= []).push(profile);
|
||||
});
|
||||
setMembersByCouple(grouped);
|
||||
} else {
|
||||
setMembersByCouple({});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load live draw sessions:', error);
|
||||
toast.error('Failed to load live draw sessions');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize]);
|
||||
|
||||
useEffect(() => { fetchSessions(); }, [fetchSessions]);
|
||||
|
||||
useEffect(() => {
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (page > totalPages) setPage(totalPages);
|
||||
}, [page, pageSize, total]);
|
||||
|
||||
const previewSession = async (coupleId: string) => {
|
||||
setSelectedCoupleId(coupleId);
|
||||
setStrokesLoading(true);
|
||||
setStrokes([]);
|
||||
try {
|
||||
const { data, error } = await adminData
|
||||
.from('live_draw_sessions')
|
||||
.select('strokes')
|
||||
.eq('couple_id', coupleId)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
setStrokes((data?.strokes as StrokeSegment[]) || []);
|
||||
} catch (error) {
|
||||
console.error('Failed to load drawing:', error);
|
||||
toast.error('Failed to load drawing');
|
||||
} finally {
|
||||
setStrokesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderMembers = (coupleId: string) => {
|
||||
const members = membersByCouple[coupleId] || [];
|
||||
if (members.length === 0) return <span className="text-muted-foreground text-sm">Unknown couple</span>;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{members.map((member) => (
|
||||
<Link key={member.id} to={`/users/${member.id}`} className="text-primary hover:underline text-sm">
|
||||
{member.name || member.email || member.id}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
|
||||
<Pencil className="h-8 w-8 text-primary" />
|
||||
Live Draw Sessions
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Recent live-draw activity across couples, most recently updated first
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Couple</TableHead>
|
||||
<TableHead>Revision</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
<TableHead>Last Updated</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-8">
|
||||
<div className="flex justify-center"><Skeleton className="h-6 w-32" /></div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : sessions.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
|
||||
No live draw sessions yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
sessions.map((session) => (
|
||||
<TableRow key={session.couple_id}>
|
||||
<TableCell>{renderMembers(session.couple_id)}</TableCell>
|
||||
<TableCell><Badge variant="outline">{session.revision}</Badge></TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{format(new Date(session.created_at), 'MMM d, yyyy')}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{format(new Date(session.updated_at), 'MMM d, yyyy HH:mm')}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button variant="ghost" size="sm" onClick={() => previewSession(session.couple_id)}>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
Preview
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
{total > 0 && (
|
||||
<PaginationControls
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(size) => { setPage(1); setPageSize(size); }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selectedCoupleId && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg">Drawing Preview</CardTitle>
|
||||
<CardDescription>Read-only snapshot of the couple's shared canvas</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{strokesLoading ? (
|
||||
<Skeleton className="h-64 w-full" />
|
||||
) : strokes.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12">
|
||||
<Pencil className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">No strokes to show</p>
|
||||
</div>
|
||||
) : (
|
||||
<StrokeCanvas strokes={strokes} />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { adminData } from '@/lib/adminApi';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { PaginationControls } from '@/components/ui/pagination';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Swords, Eye, MessageSquare } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { toast } from 'sonner';
|
||||
import { SENT_DARE_STATUS_LABELS, SENT_DARE_STATUSES, isSentDareOverdue, type SentDareStatus } from '@/lib/sentDares';
|
||||
|
||||
interface Profile {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
interface SentDare {
|
||||
id: string;
|
||||
couple_id: string;
|
||||
dare_text_snapshot: string;
|
||||
custom_dare_text: string | null;
|
||||
dare_intensity_snapshot: number;
|
||||
sender_id: string;
|
||||
recipient_id: string;
|
||||
status: string;
|
||||
sent_at: string;
|
||||
expires_at: string | null;
|
||||
}
|
||||
|
||||
interface DareMessage {
|
||||
id: string;
|
||||
sender_id: string;
|
||||
content: string;
|
||||
created_at: string;
|
||||
read_at: string | null;
|
||||
}
|
||||
|
||||
const STATUS_FILTER_OPTIONS: Array<'all' | SentDareStatus> = ['all', ...SENT_DARE_STATUSES];
|
||||
|
||||
export function SentDaresPage() {
|
||||
const [dares, setDares] = useState<SentDare[]>([]);
|
||||
const [profilesById, setProfilesById] = useState<Record<string, Profile>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | SentDareStatus>('all');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const [selectedDare, setSelectedDare] = useState<SentDare | null>(null);
|
||||
const [messages, setMessages] = useState<DareMessage[]>([]);
|
||||
const [messagesLoading, setMessagesLoading] = useState(false);
|
||||
|
||||
const fetchDares = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const from = (page - 1) * pageSize;
|
||||
const to = from + pageSize - 1;
|
||||
|
||||
let query = adminData
|
||||
.from<SentDare>('sent_dares')
|
||||
.select('id, couple_id, dare_text_snapshot, custom_dare_text, dare_intensity_snapshot, sender_id, recipient_id, status, sent_at, expires_at', { count: 'exact' })
|
||||
.order('sent_at', { ascending: false })
|
||||
.range(from, to);
|
||||
|
||||
if (statusFilter !== 'all') {
|
||||
query = query.eq('status', statusFilter);
|
||||
}
|
||||
|
||||
const { data, error, count } = await query;
|
||||
if (error) throw error;
|
||||
|
||||
const rows = data || [];
|
||||
setDares(rows);
|
||||
setTotal(count || 0);
|
||||
|
||||
const userIds = [...new Set(rows.flatMap((row) => [row.sender_id, row.recipient_id]))];
|
||||
if (userIds.length > 0) {
|
||||
const { data: profiles } = await adminData
|
||||
.from<Profile>('profiles')
|
||||
.select('id, name, email')
|
||||
.in('id', userIds);
|
||||
setProfilesById((profiles || []).reduce((acc: Record<string, Profile>, profile) => {
|
||||
acc[profile.id] = profile;
|
||||
return acc;
|
||||
}, {}));
|
||||
} else {
|
||||
setProfilesById({});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load sent dares:', error);
|
||||
toast.error('Failed to load sent dares');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize, statusFilter]);
|
||||
|
||||
useEffect(() => { fetchDares(); }, [fetchDares]);
|
||||
|
||||
useEffect(() => { setPage(1); }, [statusFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (page > totalPages) setPage(totalPages);
|
||||
}, [page, pageSize, total]);
|
||||
|
||||
const renderUserLink = (userId: string) => {
|
||||
const profile = profilesById[userId];
|
||||
return (
|
||||
<Link to={`/users/${userId}`} className="text-primary hover:underline">
|
||||
{profile?.name || profile?.email || 'Unknown user'}
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
const openDetail = async (dare: SentDare) => {
|
||||
setSelectedDare(dare);
|
||||
setMessagesLoading(true);
|
||||
setMessages([]);
|
||||
try {
|
||||
const { data, error } = await adminData
|
||||
.from<DareMessage>('dare_messages')
|
||||
.select('id, sender_id, content, created_at, read_at')
|
||||
.eq('sent_dare_id', dare.id)
|
||||
.order('created_at', { ascending: true });
|
||||
if (error) throw error;
|
||||
setMessages(data || []);
|
||||
} catch (error) {
|
||||
console.error('Failed to load dare messages:', error);
|
||||
toast.error('Failed to load dare messages');
|
||||
} finally {
|
||||
setMessagesLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
|
||||
<Swords className="h-8 w-8 text-primary" />
|
||||
Sent Dares
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Review the dares loop between couples for moderation and support
|
||||
</p>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={(value) => setStatusFilter(value as 'all' | SentDareStatus)}>
|
||||
<SelectTrigger className="w-full sm:w-48">
|
||||
<SelectValue placeholder="Status" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{STATUS_FILTER_OPTIONS.map((status) => (
|
||||
<SelectItem key={status} value={status} className="capitalize">
|
||||
{status === 'all' ? 'All statuses' : SENT_DARE_STATUS_LABELS[status].label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Dare</TableHead>
|
||||
<TableHead>Sender</TableHead>
|
||||
<TableHead>Recipient</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Sent</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead className="text-right">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>
|
||||
) : dares.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
|
||||
No sent dares found.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
dares.map((dare) => {
|
||||
const statusInfo = SENT_DARE_STATUS_LABELS[dare.status as SentDareStatus];
|
||||
const overdue = isSentDareOverdue(dare.status, dare.expires_at);
|
||||
return (
|
||||
<TableRow key={dare.id}>
|
||||
<TableCell className="max-w-[280px]">
|
||||
<span className="line-clamp-2 block">{dare.custom_dare_text || dare.dare_text_snapshot}</span>
|
||||
</TableCell>
|
||||
<TableCell>{renderUserLink(dare.sender_id)}</TableCell>
|
||||
<TableCell>{renderUserLink(dare.recipient_id)}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={statusInfo?.variant ?? 'secondary'} className="capitalize">{statusInfo?.label ?? dare.status}</Badge>
|
||||
{overdue && <Badge variant="destructive">Overdue</Badge>}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{format(new Date(dare.sent_at), 'MMM d, yyyy HH:mm')}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground whitespace-nowrap">
|
||||
{dare.expires_at ? format(new Date(dare.expires_at), 'MMM d, yyyy HH:mm') : 'No expiry'}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button variant="ghost" size="sm" onClick={() => openDetail(dare)}>
|
||||
<Eye className="h-4 w-4 mr-2" />
|
||||
Messages
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
{total > 0 && (
|
||||
<PaginationControls
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(size) => { setPage(1); setPageSize(size); }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Dialog open={!!selectedDare} onOpenChange={(open) => !open && setSelectedDare(null)}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
Dare Messages
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{selectedDare && (selectedDare.custom_dare_text || selectedDare.dare_text_snapshot)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="min-h-[120px] max-h-[400px] overflow-y-auto space-y-3 bg-muted/30 rounded-md p-4">
|
||||
{messagesLoading ? (
|
||||
<Skeleton className="h-24 w-full" />
|
||||
) : messages.length === 0 ? (
|
||||
<p className="text-center text-muted-foreground py-8">No messages for this dare</p>
|
||||
) : (
|
||||
messages.map((message) => (
|
||||
<div key={message.id} className="bg-background border rounded p-3 text-sm">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="font-medium">
|
||||
{selectedDare && (message.sender_id === selectedDare.sender_id ? 'Sender' : 'Recipient')}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{format(new Date(message.created_at), 'MMM d, yyyy HH:mm')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap">{message.content}</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { Plus, Zap, Pencil, Trash2, Loader2, Crown, Eye, EyeOff, ChevronUp, Chev
|
||||
import { toast } from 'sonner';
|
||||
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
|
||||
import type { ContentReviewStatus } from '@sauci/shared';
|
||||
import { parseIntensityRange } from '@/lib/dareIntensity';
|
||||
|
||||
// =============================================================================
|
||||
// Types
|
||||
@@ -54,6 +55,9 @@ interface DarePack {
|
||||
is_explicit: boolean;
|
||||
sort_order: number;
|
||||
category_id: string | null;
|
||||
min_intensity: number | null;
|
||||
max_intensity: number | null;
|
||||
avg_intensity: number | null;
|
||||
created_at: string | null;
|
||||
dare_count?: number;
|
||||
content_status?: ContentReviewStatus | null;
|
||||
@@ -68,6 +72,8 @@ interface DarePackFormData {
|
||||
is_public: boolean;
|
||||
is_explicit: boolean;
|
||||
category_id: string;
|
||||
min_intensity: string;
|
||||
max_intensity: string;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
@@ -96,6 +102,8 @@ export function DarePacksPage() {
|
||||
is_public: false,
|
||||
is_explicit: false,
|
||||
category_id: categoryId ?? '',
|
||||
min_intensity: '',
|
||||
max_intensity: '',
|
||||
},
|
||||
(pack) => ({
|
||||
name: pack.name,
|
||||
@@ -105,6 +113,8 @@ export function DarePacksPage() {
|
||||
is_public: pack.is_public,
|
||||
is_explicit: pack.is_explicit,
|
||||
category_id: pack.category_id || '',
|
||||
min_intensity: pack.min_intensity != null ? String(pack.min_intensity) : '',
|
||||
max_intensity: pack.max_intensity != null ? String(pack.max_intensity) : '',
|
||||
})
|
||||
);
|
||||
|
||||
@@ -209,6 +219,14 @@ export function DarePacksPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const { range, error: intensityError } = parseIntensityRange(form.formData.min_intensity, form.formData.max_intensity);
|
||||
if (intensityError) {
|
||||
toast.error(intensityError);
|
||||
return;
|
||||
}
|
||||
const parsedMin = range.min;
|
||||
const parsedMax = range.max;
|
||||
|
||||
form.setSaving(true);
|
||||
try {
|
||||
if (form.editingItem) {
|
||||
@@ -220,6 +238,8 @@ export function DarePacksPage() {
|
||||
is_public: form.formData.is_public,
|
||||
is_explicit: form.formData.is_explicit,
|
||||
category_id: form.formData.category_id || null,
|
||||
min_intensity: parsedMin,
|
||||
max_intensity: parsedMax,
|
||||
});
|
||||
if (error) throw error;
|
||||
toast.success('Dare pack updated');
|
||||
@@ -232,6 +252,8 @@ export function DarePacksPage() {
|
||||
is_public: form.formData.is_public,
|
||||
is_explicit: form.formData.is_explicit,
|
||||
category_id: form.formData.category_id || null,
|
||||
min_intensity: parsedMin,
|
||||
max_intensity: parsedMax,
|
||||
sort_order: totalCount,
|
||||
});
|
||||
if (error) throw error;
|
||||
@@ -410,6 +432,36 @@ export function DarePacksPage() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="min_intensity">Min Intensity (optional)</Label>
|
||||
<Input
|
||||
id="min_intensity"
|
||||
type="number"
|
||||
min={1}
|
||||
max={5}
|
||||
value={form.formData.min_intensity}
|
||||
onChange={(e) => form.setField('min_intensity', e.target.value)}
|
||||
placeholder="1"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max_intensity">Max Intensity (optional)</Label>
|
||||
<Input
|
||||
id="max_intensity"
|
||||
type="number"
|
||||
min={1}
|
||||
max={5}
|
||||
value={form.formData.max_intensity}
|
||||
onChange={(e) => form.setField('max_intensity', e.target.value)}
|
||||
placeholder="5"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground -mt-2">
|
||||
Gates whether this pack shows for a couple based on their intensity preference. Leave blank for no gate.
|
||||
</p>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Premium</Label>
|
||||
@@ -572,6 +624,20 @@ export function DarePacksPage() {
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{(pack.min_intensity != null || pack.max_intensity != null || pack.avg_intensity != null) && (
|
||||
<div className="flex flex-wrap gap-1 mb-2">
|
||||
{(pack.min_intensity != null || pack.max_intensity != null) && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
Intensity {pack.min_intensity ?? 1}-{pack.max_intensity ?? 5}
|
||||
</Badge>
|
||||
)}
|
||||
{pack.avg_intensity != null && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
Avg {pack.avg_intensity}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{pack.dare_count} dare{pack.dare_count !== 1 ? 's' : ''}
|
||||
|
||||
@@ -39,6 +39,7 @@ import { toast } from 'sonner';
|
||||
import { IconPreview } from '@/components/ui/icon-picker';
|
||||
import { ContentReviewControl } from '@/components/content/ContentReviewControl';
|
||||
import type { ContentReviewStatus } from '@sauci/shared';
|
||||
import { clampDareIntensity, MAX_DARE_INTENSITY, MIN_DARE_INTENSITY } from '@/lib/dareIntensity';
|
||||
|
||||
// =============================================================================
|
||||
// Types
|
||||
@@ -102,9 +103,11 @@ export function DaresPage() {
|
||||
// Form state
|
||||
const [formData, setFormData] = useState<{
|
||||
text: string;
|
||||
intensity: string;
|
||||
suggested_duration_hours: string;
|
||||
}>({
|
||||
text: '',
|
||||
intensity: '1',
|
||||
suggested_duration_hours: '',
|
||||
});
|
||||
|
||||
@@ -166,7 +169,7 @@ export function DaresPage() {
|
||||
|
||||
const openCreateDialog = () => {
|
||||
setEditingDare(null);
|
||||
setFormData({ text: '', suggested_duration_hours: '' });
|
||||
setFormData({ text: '', intensity: '1', suggested_duration_hours: '' });
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
@@ -174,6 +177,7 @@ export function DaresPage() {
|
||||
setEditingDare(dare);
|
||||
setFormData({
|
||||
text: dare.text,
|
||||
intensity: String(dare.intensity ?? 1),
|
||||
suggested_duration_hours: dare.suggested_duration_hours?.toString() || '',
|
||||
});
|
||||
setDialogOpen(true);
|
||||
@@ -185,10 +189,13 @@ export function DaresPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const intensity = clampDareIntensity(formData.intensity);
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const dareData = {
|
||||
text: formData.text,
|
||||
intensity,
|
||||
suggested_duration_hours: formData.suggested_duration_hours
|
||||
? parseInt(formData.suggested_duration_hours, 10)
|
||||
: null,
|
||||
@@ -338,6 +345,31 @@ export function DaresPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="intensity">Intensity</Label>
|
||||
<Select
|
||||
value={formData.intensity}
|
||||
onValueChange={(value) => setFormData(d => ({ ...d, intensity: value }))}
|
||||
>
|
||||
<SelectTrigger id="intensity">
|
||||
<SelectValue placeholder="Select an intensity" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Array.from(
|
||||
{ length: MAX_DARE_INTENSITY - MIN_DARE_INTENSITY + 1 },
|
||||
(_, i) => MIN_DARE_INTENSITY + i,
|
||||
).map((level) => (
|
||||
<SelectItem key={level} value={String(level)}>
|
||||
{level}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
1 is mild, 5 is the most intense. Used to gate dares against a couple's intensity preference.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Suggested Duration</Label>
|
||||
<Select
|
||||
@@ -444,6 +476,7 @@ export function DaresPage() {
|
||||
<TableHead className="w-12">#</TableHead>
|
||||
<TableHead>Dare</TableHead>
|
||||
<TableHead className="w-40">Catalogue</TableHead>
|
||||
<TableHead className="w-20">Intensity</TableHead>
|
||||
<TableHead className="w-24">Duration</TableHead>
|
||||
<TableHead className="w-24">Actions</TableHead>
|
||||
</TableRow>
|
||||
@@ -478,6 +511,11 @@ export function DaresPage() {
|
||||
compact
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{dare.intensity}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{dare.suggested_duration_hours ? (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { adminData } from '@/lib/adminApi';
|
||||
import { auditedAdminData } from '@/hooks/useAuditedAdminData';
|
||||
import { useEntityForm } from '@/hooks/useEntityForm';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { PaginationControls } from '@/components/ui/pagination';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Plus, Pencil, Loader2, HelpCircle, X, Eye, EyeOff } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { MAX_QUIZ_OPTIONS, MIN_QUIZ_OPTIONS, sanitizeQuizOptions, validateQuizQuestionForm } from '@/lib/quizQuestions';
|
||||
|
||||
// =============================================================================
|
||||
// Types
|
||||
// =============================================================================
|
||||
|
||||
interface QuizQuestion {
|
||||
id: string;
|
||||
prompt_self: string;
|
||||
prompt_guess: string;
|
||||
options: string[];
|
||||
sort_order: number;
|
||||
is_active: boolean;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
interface QuizQuestionFormData {
|
||||
prompt_self: string;
|
||||
prompt_guess: string;
|
||||
options: string[];
|
||||
sort_order: string;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
type ActiveFilter = 'all' | 'active' | 'inactive';
|
||||
|
||||
const emptyOptions = () => ['', ''];
|
||||
|
||||
// =============================================================================
|
||||
// Component
|
||||
// =============================================================================
|
||||
|
||||
export function QuizQuestionsPage() {
|
||||
const [questions, setQuestions] = useState<QuizQuestion[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [totalCount, setTotalCount] = useState(0);
|
||||
const [activeFilter, setActiveFilter] = useState<ActiveFilter>('all');
|
||||
|
||||
const form = useEntityForm<QuizQuestionFormData, QuizQuestion>(
|
||||
{
|
||||
prompt_self: '',
|
||||
prompt_guess: '',
|
||||
options: emptyOptions(),
|
||||
sort_order: '0',
|
||||
is_active: true,
|
||||
},
|
||||
(question) => ({
|
||||
prompt_self: question.prompt_self,
|
||||
prompt_guess: question.prompt_guess,
|
||||
options: question.options.length ? [...question.options] : emptyOptions(),
|
||||
sort_order: String(question.sort_order),
|
||||
is_active: question.is_active,
|
||||
})
|
||||
);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const from = (page - 1) * pageSize;
|
||||
const to = from + pageSize - 1;
|
||||
|
||||
let query = adminData
|
||||
.from('quiz_questions')
|
||||
.select('*', { count: 'exact' })
|
||||
.order('sort_order', { ascending: true })
|
||||
.range(from, to);
|
||||
|
||||
if (activeFilter === 'active') {
|
||||
query = query.eq('is_active', true);
|
||||
} else if (activeFilter === 'inactive') {
|
||||
query = query.eq('is_active', false);
|
||||
}
|
||||
|
||||
const { data, error, count } = await query;
|
||||
if (error) throw error;
|
||||
setTotalCount(count || 0);
|
||||
setQuestions((data as QuizQuestion[]) || []);
|
||||
} catch (error) {
|
||||
toast.error('Failed to load quiz questions');
|
||||
console.error(error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize, activeFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
useEffect(() => {
|
||||
const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
|
||||
if (page > totalPages) {
|
||||
setPage(totalPages);
|
||||
}
|
||||
}, [page, pageSize, totalCount]);
|
||||
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [activeFilter]);
|
||||
|
||||
// =============================================================================
|
||||
// Option helpers
|
||||
// =============================================================================
|
||||
|
||||
const setOption = (index: number, value: string) => {
|
||||
form.setFields({
|
||||
options: form.formData.options.map((opt, i) => (i === index ? value : opt)),
|
||||
});
|
||||
};
|
||||
|
||||
const addOption = () => {
|
||||
if (form.formData.options.length >= MAX_QUIZ_OPTIONS) return;
|
||||
form.setFields({ options: [...form.formData.options, ''] });
|
||||
};
|
||||
|
||||
const removeOption = (index: number) => {
|
||||
if (form.formData.options.length <= MIN_QUIZ_OPTIONS) return;
|
||||
form.setFields({ options: form.formData.options.filter((_, i) => i !== index) });
|
||||
};
|
||||
|
||||
// =============================================================================
|
||||
// Handlers
|
||||
// =============================================================================
|
||||
|
||||
const handleSave = async () => {
|
||||
const validationError = validateQuizQuestionForm(form.formData);
|
||||
if (validationError) {
|
||||
toast.error(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanedOptions = sanitizeQuizOptions(form.formData.options);
|
||||
const parsedSortOrder = Number(form.formData.sort_order);
|
||||
const sortOrder = Number.isFinite(parsedSortOrder) ? parsedSortOrder : 0;
|
||||
|
||||
const payload = {
|
||||
prompt_self: form.formData.prompt_self.trim(),
|
||||
prompt_guess: form.formData.prompt_guess.trim(),
|
||||
options: cleanedOptions,
|
||||
sort_order: sortOrder,
|
||||
is_active: form.formData.is_active,
|
||||
};
|
||||
|
||||
form.setSaving(true);
|
||||
try {
|
||||
if (form.editingItem) {
|
||||
const { error } = await auditedAdminData.update('quiz_questions', form.editingItem.id, payload);
|
||||
if (error) throw error;
|
||||
toast.success('Quiz question updated');
|
||||
} else {
|
||||
const { error } = await auditedAdminData.insert('quiz_questions', payload);
|
||||
if (error) throw error;
|
||||
toast.success('Quiz question created');
|
||||
}
|
||||
|
||||
form.close();
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error('Failed to save quiz question');
|
||||
console.error(error);
|
||||
} finally {
|
||||
form.setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleActive = async (question: QuizQuestion) => {
|
||||
try {
|
||||
const { error } = await auditedAdminData.update('quiz_questions', question.id, {
|
||||
is_active: !question.is_active,
|
||||
});
|
||||
if (error) throw error;
|
||||
toast.success(question.is_active ? 'Quiz question deactivated' : 'Quiz question activated');
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error('Failed to update quiz question');
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-9 w-64" />
|
||||
<Skeleton className="h-10 w-40" />
|
||||
</div>
|
||||
<Skeleton className="h-96" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
|
||||
<HelpCircle className="h-8 w-8 text-purple-500" />
|
||||
Quiz Questions
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{totalCount} question{totalCount !== 1 ? 's' : ''} in the couples quiz pool
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={form.dialogOpen} onOpenChange={form.setDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={form.openCreate}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Question
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{form.isEditing ? 'Edit Quiz Question' : 'Add Quiz Question'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{form.isEditing
|
||||
? 'Update the quiz question details below.'
|
||||
: 'Add a new question to the couples quiz pool.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="prompt_self">Prompt (about yourself)</Label>
|
||||
<Textarea
|
||||
id="prompt_self"
|
||||
value={form.formData.prompt_self}
|
||||
onChange={(e) => form.setField('prompt_self', e.target.value)}
|
||||
placeholder="e.g., What is your idea of a perfect date night?"
|
||||
rows={2}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown when a partner answers about themselves.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="prompt_guess">Prompt (guessing about partner)</Label>
|
||||
<Textarea
|
||||
id="prompt_guess"
|
||||
value={form.formData.prompt_guess}
|
||||
onChange={(e) => form.setField('prompt_guess', e.target.value)}
|
||||
placeholder="e.g., What is your partner's idea of a perfect date night?"
|
||||
rows={2}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown when a partner guesses the other partner's answer. Same options, different phrasing.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Options ({MIN_QUIZ_OPTIONS}-{MAX_QUIZ_OPTIONS})</Label>
|
||||
{form.formData.options.length < MAX_QUIZ_OPTIONS && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={addOption}>
|
||||
<Plus className="mr-1 h-3 w-3" />
|
||||
Add Option
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{form.formData.options.map((option, index) => (
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={option}
|
||||
onChange={(e) => setOption(index, e.target.value)}
|
||||
placeholder={`Option ${index + 1}`}
|
||||
/>
|
||||
{form.formData.options.length > MIN_QUIZ_OPTIONS && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removeOption(index)}
|
||||
aria-label={`Remove option ${index + 1}`}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Both partners choose from the same list of options.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sort_order">Sort Order</Label>
|
||||
<Input
|
||||
id="sort_order"
|
||||
type="number"
|
||||
value={form.formData.sort_order}
|
||||
onChange={(e) => form.setField('sort_order', e.target.value)}
|
||||
placeholder="0"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Lower numbers are considered before higher numbers when questions have equal usage history.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Active</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Inactive questions are never selected for a new quiz session.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={form.formData.is_active}
|
||||
onCheckedChange={(checked) => form.setField('is_active', checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={form.close}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={form.saving}>
|
||||
{form.saving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Saving...
|
||||
</>
|
||||
) : (
|
||||
'Save'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Label className="text-sm text-muted-foreground">Status</Label>
|
||||
<Select value={activeFilter} onValueChange={(value) => setActiveFilter(value as ActiveFilter)}>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue placeholder="All questions" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All questions</SelectItem>
|
||||
<SelectItem value="active">Active only</SelectItem>
|
||||
<SelectItem value="inactive">Inactive only</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Quiz Questions Table */}
|
||||
{questions.length === 0 ? (
|
||||
<Card className="flex flex-col items-center justify-center py-12">
|
||||
<HelpCircle className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<h3 className="text-lg font-semibold">No quiz questions yet</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
Add questions to build the couples quiz pool
|
||||
</p>
|
||||
<Button onClick={form.openCreate}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Question
|
||||
</Button>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-16">Order</TableHead>
|
||||
<TableHead>Prompt</TableHead>
|
||||
<TableHead>Options</TableHead>
|
||||
<TableHead className="w-24">Status</TableHead>
|
||||
<TableHead className="w-32">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{questions.map((question) => (
|
||||
<TableRow key={question.id}>
|
||||
<TableCell className="font-medium text-muted-foreground">
|
||||
{question.sort_order}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<p className="line-clamp-2 font-medium">{question.prompt_self}</p>
|
||||
<p className="line-clamp-1 text-xs text-muted-foreground">{question.prompt_guess}</p>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{question.options.map((option, i) => (
|
||||
<Badge key={i} variant="outline" className="text-xs">
|
||||
{option}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={question.is_active ? 'default' : 'secondary'}>
|
||||
{question.is_active ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => form.openEdit(question)}
|
||||
aria-label="Edit question"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleToggleActive(question)}
|
||||
aria-label={question.is_active ? 'Deactivate question' : 'Activate question'}
|
||||
title={question.is_active ? 'Deactivate' : 'Activate'}
|
||||
>
|
||||
{question.is_active ? (
|
||||
<EyeOff className="h-4 w-4 text-destructive" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4 text-green-500" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{questions.length > 0 && (
|
||||
<PaginationControls
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
totalCount={totalCount}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(size) => {
|
||||
setPage(1);
|
||||
setPageSize(size);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { adminData } from '@/lib/adminApi';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { PaginationControls } from '@/components/ui/pagination';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Heart, Search, Users, Hourglass } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { toast } from 'sonner';
|
||||
import { buildCoupleSearchFilter, coupleStatusFromMemberCount } from '@/lib/couples';
|
||||
|
||||
interface Couple {
|
||||
id: string;
|
||||
invite_code: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface Profile {
|
||||
id: string;
|
||||
name: string | null;
|
||||
email: string | null;
|
||||
couple_id: string | null;
|
||||
}
|
||||
|
||||
export function CouplesPage() {
|
||||
const [couples, setCouples] = useState<Couple[]>([]);
|
||||
const [membersByCouple, setMembersByCouple] = useState<Record<string, Profile[]>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(25);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const fetchCouples = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const from = (page - 1) * pageSize;
|
||||
const to = from + pageSize - 1;
|
||||
|
||||
let query = adminData
|
||||
.from<Couple>('couples')
|
||||
.select('id, invite_code, created_at', { count: 'exact' })
|
||||
.order('created_at', { ascending: false })
|
||||
.range(from, to);
|
||||
|
||||
const filter = buildCoupleSearchFilter(search);
|
||||
if (filter) {
|
||||
query = filter.op === 'eq' ? query.eq(filter.column, filter.value) : query.ilike(filter.column, filter.value);
|
||||
}
|
||||
|
||||
const { data, error, count } = await query;
|
||||
if (error) throw error;
|
||||
|
||||
const rows = data || [];
|
||||
setCouples(rows);
|
||||
setTotal(count || 0);
|
||||
|
||||
const coupleIds = rows.map((row) => row.id);
|
||||
if (coupleIds.length > 0) {
|
||||
const { data: profiles } = await adminData
|
||||
.from<Profile>('profiles')
|
||||
.select('id, name, email, couple_id')
|
||||
.in('couple_id', coupleIds);
|
||||
const grouped: Record<string, Profile[]> = {};
|
||||
(profiles || []).forEach((profile) => {
|
||||
if (!profile.couple_id) return;
|
||||
(grouped[profile.couple_id] ??= []).push(profile);
|
||||
});
|
||||
setMembersByCouple(grouped);
|
||||
} else {
|
||||
setMembersByCouple({});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load couples:', error);
|
||||
toast.error('Failed to load couples');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize, search]);
|
||||
|
||||
useEffect(() => { fetchCouples(); }, [fetchCouples]);
|
||||
useEffect(() => { setPage(1); }, [search]);
|
||||
|
||||
useEffect(() => {
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (page > totalPages) setPage(totalPages);
|
||||
}, [page, pageSize, total]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
|
||||
<Heart className="h-8 w-8 text-primary" />
|
||||
Couples
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Look up an invite funnel by invite code or couple id
|
||||
</p>
|
||||
</div>
|
||||
<div className="relative w-full sm:w-72">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search invite code or couple id..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Invite Code</TableHead>
|
||||
<TableHead>Members</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Created</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center py-8">
|
||||
<div className="flex justify-center"><Skeleton className="h-6 w-32" /></div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : couples.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground">
|
||||
{search ? 'No couples found matching your search.' : 'No couples yet.'}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
couples.map((couple) => {
|
||||
const members = membersByCouple[couple.id] || [];
|
||||
const status = coupleStatusFromMemberCount(members.length);
|
||||
return (
|
||||
<TableRow key={couple.id}>
|
||||
<TableCell className="font-mono">{couple.invite_code}</TableCell>
|
||||
<TableCell>
|
||||
{members.length === 0 ? (
|
||||
<span className="text-muted-foreground text-sm">No members</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-1">
|
||||
{members.map((member) => (
|
||||
<Link key={member.id} to={`/users/${member.id}`} className="text-primary hover:underline text-sm">
|
||||
{member.name || member.email || member.id}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{status === 'paired' ? (
|
||||
<Badge variant="secondary" className="bg-green-100 text-green-700 hover:bg-green-200">
|
||||
<Users className="h-3 w-3 mr-1" />
|
||||
Paired
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary" className="bg-amber-100 text-amber-700 hover:bg-amber-200">
|
||||
<Hourglass className="h-3 w-3 mr-1" />
|
||||
Pending
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">
|
||||
{format(new Date(couple.created_at), 'MMM d, yyyy')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Card>
|
||||
|
||||
{total > 0 && (
|
||||
<PaginationControls
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
totalCount={total}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(size) => { setPage(1); setPageSize(size); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { adminData, adminRequest, adminBinaryRequest } from '@/lib/adminApi';
|
||||
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
|
||||
@@ -37,12 +37,14 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Crown, Users, MessageCircle, ChevronRight, Gift, Image, Video as VideoIcon, Target, User, Eye, EyeOff, CheckCircle, Package, Sparkles, Flame, Trophy, Calendar, AlertCircle, Clock, Pencil } from 'lucide-react';
|
||||
import { Crown, Users, MessageCircle, ChevronRight, Gift, Image, Video as VideoIcon, Target, User, Eye, EyeOff, CheckCircle, Package, Sparkles, Flame, Trophy, Calendar, AlertCircle, Clock, Pencil, CreditCard, Bell, Globe, BadgeCheck, HelpCircle, Swords } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import { IconPreview } from '@/components/ui/icon-picker';
|
||||
import type { AnswerType, QuestionType } from '@sauci/shared';
|
||||
import { ResponseAnswer } from '@/components/content/ResponseAnswer';
|
||||
import { MATCH_TYPE_LABELS, type AdminResponseData } from '@/lib/questionResponses';
|
||||
import { StrokeCanvas, type StrokeSegment } from '@/components/content/StrokeCanvas';
|
||||
import { SENT_DARE_STATUS_LABELS, type SentDareStatus } from '@/lib/sentDares';
|
||||
|
||||
type UsageReason = 'improve_communication' | 'spice_up_intimacy' | 'deeper_connection' | 'have_fun' | 'strengthen_relationship';
|
||||
type Gender = 'male' | 'female' | 'non-binary' | 'prefer-not-to-say';
|
||||
@@ -61,6 +63,7 @@ interface Profile {
|
||||
usage_reason: UsageReason | null;
|
||||
hide_nsfw: boolean | null;
|
||||
onboarding_completed: boolean | null;
|
||||
timezone: string | null;
|
||||
}
|
||||
|
||||
const usageReasonLabels: Record<UsageReason, { label: string; icon: string }> = {
|
||||
@@ -158,11 +161,72 @@ interface CoupleStreak {
|
||||
current_streak: number;
|
||||
longest_streak: number;
|
||||
last_active_date: string | null;
|
||||
last_completed_date: string | null;
|
||||
last_milestone_celebrated: number | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface NotificationPreferences {
|
||||
matches_enabled: boolean;
|
||||
messages_enabled: boolean;
|
||||
partner_activity_enabled: boolean;
|
||||
nudges_enabled: boolean;
|
||||
pack_changes_enabled: boolean;
|
||||
new_packs_enabled: boolean;
|
||||
streak_milestones_enabled: boolean;
|
||||
streak_reminders_enabled: boolean;
|
||||
weekly_summary_enabled: boolean;
|
||||
unpaired_reminders_enabled: boolean;
|
||||
catchup_reminders_enabled: boolean;
|
||||
dares_enabled: boolean;
|
||||
}
|
||||
|
||||
const notificationPreferenceLabels: Record<keyof NotificationPreferences, string> = {
|
||||
matches_enabled: 'Matches',
|
||||
messages_enabled: 'Messages',
|
||||
partner_activity_enabled: 'Partner activity',
|
||||
nudges_enabled: 'Nudges',
|
||||
pack_changes_enabled: 'Pack changes',
|
||||
new_packs_enabled: 'New packs',
|
||||
streak_milestones_enabled: 'Streak milestones',
|
||||
streak_reminders_enabled: 'Streak reminders',
|
||||
weekly_summary_enabled: 'Weekly summary',
|
||||
unpaired_reminders_enabled: 'Unpaired reminders',
|
||||
catchup_reminders_enabled: 'Catch-up reminders',
|
||||
dares_enabled: 'Dares',
|
||||
};
|
||||
|
||||
interface Subscription {
|
||||
id: string;
|
||||
store: string;
|
||||
product_id: string;
|
||||
status: string;
|
||||
entitlement_ids: string[];
|
||||
purchased_at: string;
|
||||
expires_at: string | null;
|
||||
revenuecat_app_user_id: string;
|
||||
}
|
||||
|
||||
interface QuizSession {
|
||||
id: string;
|
||||
status: string;
|
||||
score_percent: number | null;
|
||||
completed_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface SentDare {
|
||||
id: string;
|
||||
dare_text_snapshot: string;
|
||||
custom_dare_text: string | null;
|
||||
sender_id: string;
|
||||
recipient_id: string;
|
||||
status: string;
|
||||
sent_at: string;
|
||||
expires_at: string | null;
|
||||
}
|
||||
|
||||
const matchTypeLabels = {
|
||||
yes_yes: 'Both Yes!',
|
||||
yes_maybe: 'Yes + Maybe',
|
||||
@@ -269,25 +333,7 @@ function AdminDecryptedVideo({ messageId }: { messageId: string }) {
|
||||
return <video src={url} controls className="w-full h-full object-cover" preload="metadata" />;
|
||||
}
|
||||
|
||||
interface StrokePoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface StrokeSegment {
|
||||
id: string;
|
||||
userId: string;
|
||||
points: StrokePoint[];
|
||||
color: string;
|
||||
width: number;
|
||||
timestamp: number;
|
||||
isEraser: boolean;
|
||||
}
|
||||
|
||||
const CANVAS_BACKGROUND = '#1a1a2e';
|
||||
|
||||
function LiveDrawCanvas({ coupleId }: { coupleId: string }) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [strokes, setStrokes] = useState<StrokeSegment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -322,56 +368,6 @@ function LiveDrawCanvas({ coupleId }: { coupleId: string }) {
|
||||
};
|
||||
}, [coupleId]);
|
||||
|
||||
// Render strokes to canvas
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const w = canvas.clientWidth;
|
||||
const h = canvas.clientHeight;
|
||||
canvas.width = w * dpr;
|
||||
canvas.height = h * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
ctx.fillStyle = CANVAS_BACKGROUND;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
|
||||
for (const stroke of strokes) {
|
||||
if (stroke.points.length === 0) continue;
|
||||
ctx.strokeStyle = stroke.isEraser ? CANVAS_BACKGROUND : stroke.color;
|
||||
ctx.lineWidth = stroke.width;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineJoin = 'round';
|
||||
ctx.beginPath();
|
||||
|
||||
const first = stroke.points[0];
|
||||
ctx.moveTo(first.x * w, first.y * h);
|
||||
|
||||
if (stroke.points.length === 1) {
|
||||
ctx.lineTo(first.x * w + 0.1, first.y * h + 0.1);
|
||||
} else {
|
||||
for (let i = 1; i < stroke.points.length; i++) {
|
||||
const prev = stroke.points[i - 1];
|
||||
const curr = stroke.points[i];
|
||||
const midX = ((prev.x + curr.x) / 2) * w;
|
||||
const midY = ((prev.y + curr.y) / 2) * h;
|
||||
|
||||
if (i === 1) {
|
||||
ctx.lineTo(midX, midY);
|
||||
} else {
|
||||
ctx.quadraticCurveTo(prev.x * w, prev.y * h, midX, midY);
|
||||
}
|
||||
}
|
||||
const last = stroke.points[stroke.points.length - 1];
|
||||
ctx.lineTo(last.x * w, last.y * h);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
}, [strokes]);
|
||||
|
||||
if (loading) return <Skeleton className="h-64 w-full" />;
|
||||
if (error) return <div className="text-sm text-red-500">Failed to load drawing: {error}</div>;
|
||||
|
||||
@@ -384,13 +380,8 @@ function LiveDrawCanvas({ coupleId }: { coupleId: string }) {
|
||||
</Card>
|
||||
) : (
|
||||
<>
|
||||
<div className="rounded-xl overflow-hidden border" style={{ background: CANVAS_BACKGROUND }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ width: '100%', aspectRatio: '4/3', display: 'block' }}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{strokes.length} stroke{strokes.length !== 1 ? 's' : ''} — updates in real-time</p>
|
||||
<StrokeCanvas strokes={strokes} />
|
||||
<p className="text-xs text-muted-foreground">{strokes.length} stroke{strokes.length !== 1 ? 's' : ''} - updates in real-time</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -424,6 +415,10 @@ export function UserDetailPage() {
|
||||
const [mediaPage, setMediaPage] = useState(1);
|
||||
const [mediaPageSize, setMediaPageSize] = useState(12);
|
||||
const [mediaTotal, setMediaTotal] = useState(0);
|
||||
const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
|
||||
const [notificationPrefs, setNotificationPrefs] = useState<NotificationPreferences | null>(null);
|
||||
const [quizSessions, setQuizSessions] = useState<QuizSession[]>([]);
|
||||
const [sentDares, setSentDares] = useState<SentDare[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const canViewResponses = hasPermission(PERMISSION_KEYS.VIEW_RESPONSES);
|
||||
@@ -492,6 +487,39 @@ export function UserDetailPage() {
|
||||
.order('created_at', { ascending: false });
|
||||
setFeatureInterests((featureInterestsData || []) as FeatureInterest[]);
|
||||
|
||||
// Fetch purchase history so support can see what was bought and when it lapses,
|
||||
// instead of only the profile's is_premium boolean.
|
||||
const { data: subscriptionsData } = await adminData
|
||||
.from('subscriptions')
|
||||
.select('id, store, product_id, status, entitlement_ids, purchased_at, expires_at, revenuecat_app_user_id')
|
||||
.eq('user_id', userId)
|
||||
.order('purchased_at', { ascending: false });
|
||||
setSubscriptions((subscriptionsData || []) as Subscription[]);
|
||||
|
||||
// Fetch notification preferences (read-only visibility for support).
|
||||
const { data: notificationPrefsData } = await adminData
|
||||
.from('notification_preferences')
|
||||
.select('*')
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle();
|
||||
setNotificationPrefs(notificationPrefsData);
|
||||
|
||||
// Fetch recent dares sent by or to this user (sent_dares has no OR support
|
||||
// in the admin query builder, so this issues two filtered queries and merges).
|
||||
const [sentByUser, sentToUser] = await Promise.all([
|
||||
adminData.from('sent_dares')
|
||||
.select('id, dare_text_snapshot, custom_dare_text, sender_id, recipient_id, status, sent_at, expires_at')
|
||||
.eq('sender_id', userId).order('sent_at', { ascending: false }).limit(10),
|
||||
adminData.from('sent_dares')
|
||||
.select('id, dare_text_snapshot, custom_dare_text, sender_id, recipient_id, status, sent_at, expires_at')
|
||||
.eq('recipient_id', userId).order('sent_at', { ascending: false }).limit(10),
|
||||
]);
|
||||
const daresById = new Map<string, SentDare>();
|
||||
for (const row of [...(sentByUser.data || []), ...(sentToUser.data || [])] as SentDare[]) {
|
||||
daresById.set(row.id, row);
|
||||
}
|
||||
setSentDares([...daresById.values()].sort((a, b) => new Date(b.sent_at).getTime() - new Date(a.sent_at).getTime()).slice(0, 10));
|
||||
|
||||
if (profileData?.couple_id) {
|
||||
const { data: partnerData } = await adminData.from('profiles').select('id, name').eq('couple_id', profileData.couple_id).neq('id', userId).single();
|
||||
setPartner(partnerData);
|
||||
@@ -503,9 +531,20 @@ export function UserDetailPage() {
|
||||
.eq('couple_id', profileData.couple_id)
|
||||
.maybeSingle();
|
||||
setStreak(streakData);
|
||||
|
||||
// Fetch recent quiz sessions for the couple (quiz_sessions has no user_id
|
||||
// column; sessions belong to the couple both partners share).
|
||||
const { data: quizSessionsData } = await adminData
|
||||
.from('quiz_sessions')
|
||||
.select('id, status, score_percent, completed_at, created_at')
|
||||
.eq('couple_id', profileData.couple_id)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10);
|
||||
setQuizSessions((quizSessionsData || []) as QuizSession[]);
|
||||
} else {
|
||||
setPartner(null);
|
||||
setStreak(null);
|
||||
setQuizSessions([]);
|
||||
}
|
||||
|
||||
const responsesFrom = (responsesPage - 1) * responsesPageSize;
|
||||
@@ -789,12 +828,59 @@ export function UserDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
</div></CardContent></Card>
|
||||
{/* Subscriptions */}
|
||||
{subscriptions.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<CreditCard className="h-5 w-5 text-primary" />
|
||||
Subscriptions
|
||||
</CardTitle>
|
||||
<CardDescription>Purchase history from the store, independent of the is_premium flag</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Store</TableHead>
|
||||
<TableHead>Product</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Entitlements</TableHead>
|
||||
<TableHead>Purchased</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead>RevenueCat User</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{subscriptions.map((subscription) => (
|
||||
<TableRow key={subscription.id}>
|
||||
<TableCell className="capitalize">{subscription.store.toLowerCase().replace('_', ' ')}</TableCell>
|
||||
<TableCell className="font-mono text-xs">{subscription.product_id}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={subscription.status === 'active' ? 'default' : subscription.status === 'billing_issue' ? 'destructive' : 'secondary'} className="capitalize">
|
||||
{subscription.status.replace('_', ' ')}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">{subscription.entitlement_ids.join(', ') || '-'}</TableCell>
|
||||
<TableCell className="text-sm">{format(new Date(subscription.purchased_at), 'MMM d, yyyy')}</TableCell>
|
||||
<TableCell className="text-sm">{subscription.expires_at ? format(new Date(subscription.expires_at), 'MMM d, yyyy') : 'Never'}</TableCell>
|
||||
<TableCell className="font-mono text-xs text-muted-foreground">{subscription.revenuecat_app_user_id}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Onboarding Details */}
|
||||
<Card><CardHeader className="pb-3"><CardTitle className="text-lg flex items-center gap-2"><CheckCircle className="h-5 w-5 text-primary" />Onboarding Details</CardTitle><CardDescription>Information collected during user onboarding</CardDescription></CardHeader><CardContent><div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="flex items-start gap-3"><div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-900"><User className="h-4 w-4 text-blue-600 dark:text-blue-400" /></div><div><p className="text-sm font-medium text-muted-foreground">Gender</p><p className="font-medium">{profile.gender ? genderLabels[profile.gender] : 'Not set'}</p></div></div>
|
||||
<div className="flex items-start gap-3"><div className="p-2 rounded-lg bg-purple-100 dark:bg-purple-900"><Target className="h-4 w-4 text-purple-600 dark:text-purple-400" /></div><div><p className="text-sm font-medium text-muted-foreground">Why using Sauci</p><p className="font-medium">{profile.usage_reason ? usageReasonLabels[profile.usage_reason]?.label : 'Not set'}</p></div></div>
|
||||
<div className="flex items-start gap-3"><div className={`p-2 rounded-lg ${profile.hide_nsfw ? 'bg-gray-100 dark:bg-gray-800' : 'bg-amber-100 dark:bg-amber-900'}`}>{profile.hide_nsfw ? <EyeOff className="h-4 w-4 text-gray-500 dark:text-gray-400" /> : <Eye className="h-4 w-4 text-amber-600 dark:text-amber-400" />}</div><div><p className="text-sm font-medium text-muted-foreground">Hide NSFW</p><p className="font-medium">{profile.hide_nsfw === null ? 'Not set' : profile.hide_nsfw ? 'Yes' : 'No'}</p></div></div>
|
||||
<div className="flex items-start gap-3"><div className={`p-2 rounded-lg ${profile.onboarding_completed ? 'bg-green-100 dark:bg-green-900' : 'bg-red-100 dark:bg-red-900'}`}><CheckCircle className={`h-4 w-4 ${profile.onboarding_completed ? 'text-green-600 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`} /></div><div><p className="text-sm font-medium text-muted-foreground">Onboarding</p><p className="font-medium">{profile.onboarding_completed ? 'Completed' : 'Not completed'}</p></div></div>
|
||||
<div className="flex items-start gap-3"><div className="p-2 rounded-lg bg-teal-100 dark:bg-teal-900"><Globe className="h-4 w-4 text-teal-600 dark:text-teal-400" /></div><div><p className="text-sm font-medium text-muted-foreground">Timezone</p><p className="font-medium">{profile.timezone || 'Not reported (UTC fallback)'}</p></div></div>
|
||||
</div></CardContent></Card>
|
||||
{/* Streak Info */}
|
||||
{profile.couple_id && streak && (
|
||||
@@ -835,6 +921,16 @@ export function UserDetailPage() {
|
||||
<p className="font-medium">{streak.last_active_date ? format(new Date(streak.last_active_date), 'MMM d, yyyy') : 'Never'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="p-2 rounded-lg bg-green-100 dark:bg-green-900">
|
||||
<BadgeCheck className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground">Last Completed (both partners)</p>
|
||||
<p className="font-medium">{streak.last_completed_date ? format(new Date(streak.last_completed_date), 'MMM d, yyyy') : 'Never'}</p>
|
||||
<p className="text-xs text-muted-foreground">Determines whether the streak is alive today or tomorrow</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="p-2 rounded-lg bg-purple-100 dark:bg-purple-900">
|
||||
<Sparkles className="h-4 w-4 text-purple-600 dark:text-purple-400" />
|
||||
@@ -848,6 +944,28 @@ export function UserDetailPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Notification Preferences */}
|
||||
{notificationPrefs && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Bell className="h-5 w-5 text-primary" />
|
||||
Notification Preferences
|
||||
</CardTitle>
|
||||
<CardDescription>Read-only. Configured by the user in the mobile app</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{(Object.keys(notificationPreferenceLabels) as Array<keyof NotificationPreferences>).map((key) => (
|
||||
<Badge key={key} variant={notificationPrefs[key] ? 'default' : 'secondary'} className="gap-1">
|
||||
{notificationPrefs[key] ? <CheckCircle className="h-3 w-3" /> : <AlertCircle className="h-3 w-3" />}
|
||||
{notificationPreferenceLabels[key]}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Feature Opt-Ins */}
|
||||
{featureInterests.length > 0 && (
|
||||
<Card>
|
||||
@@ -872,6 +990,83 @@ export function UserDetailPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Quiz Sessions */}
|
||||
{quizSessions.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<HelpCircle className="h-5 w-5 text-primary" />
|
||||
Couples Quiz Sessions
|
||||
</CardTitle>
|
||||
<CardDescription>Recent quiz sessions for this couple</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Score</TableHead>
|
||||
<TableHead>Started</TableHead>
|
||||
<TableHead>Completed</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{quizSessions.map((session) => (
|
||||
<TableRow key={session.id}>
|
||||
<TableCell>
|
||||
<Badge variant={session.status === 'completed' ? 'default' : 'secondary'} className="capitalize">{session.status}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{session.score_percent !== null ? `${session.score_percent}%` : '-'}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{format(new Date(session.created_at), 'MMM d, yyyy')}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{session.completed_at ? format(new Date(session.completed_at), 'MMM d, yyyy') : '-'}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Recent Dares */}
|
||||
{sentDares.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Swords className="h-5 w-5 text-primary" />
|
||||
Recent Dares
|
||||
</CardTitle>
|
||||
<CardDescription>Dares this user sent or received. See the Sent Dares page for the full loop and messages</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Dare</TableHead>
|
||||
<TableHead>Direction</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Sent</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sentDares.map((dare) => {
|
||||
const statusInfo = SENT_DARE_STATUS_LABELS[dare.status as SentDareStatus];
|
||||
return (
|
||||
<TableRow key={dare.id}>
|
||||
<TableCell className="max-w-md line-clamp-2">{dare.custom_dare_text || dare.dare_text_snapshot}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{dare.sender_id === userId ? 'Sent' : 'Received'}</TableCell>
|
||||
<TableCell><Badge variant={statusInfo?.variant ?? 'secondary'} className="capitalize">{statusInfo?.label ?? dare.status}</Badge></TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{format(new Date(dare.sent_at), 'MMM d, yyyy')}</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{/* Tabs */}
|
||||
<Tabs defaultValue={canViewResponses ? "responses" : canViewMatches ? "matches" : canViewMedia ? "media" : "responses"}>
|
||||
<TabsList>
|
||||
|
||||
@@ -35,6 +35,12 @@ const resources: Record<string, ResourceRule> = {
|
||||
media_objects: { read: 'view_media' },
|
||||
dare_packs: { read: 'manage_packs', write: 'manage_packs' },
|
||||
dares: { read: 'manage_questions', write: 'manage_questions' },
|
||||
quiz_questions: { read: ['manage_questions', 'view_activity', 'view_users'], write: 'manage_questions' },
|
||||
quiz_sessions: { read: ['view_users', 'view_activity'] },
|
||||
quiz_answers: { read: ['view_users', 'view_activity'] },
|
||||
sent_dares: { read: ['view_users', 'view_activity', 'view_chats'] },
|
||||
dare_messages: { read: ['view_chats', 'view_activity'] },
|
||||
notification_preferences: { read: 'view_users', idColumn: 'user_id' },
|
||||
};
|
||||
|
||||
function identifier(value: string): string {
|
||||
|
||||
@@ -35,6 +35,8 @@ export const questionPacks = pgTable('question_packs', {
|
||||
contentReviewedAt: timestamp('content_reviewed_at', { withTimezone: true }),
|
||||
contentReviewedBy: uuid('content_reviewed_by').references(() => profiles.id, { onDelete: 'set null' }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
scheduledReleaseAt: timestamp('scheduled_release_at', { withTimezone: true }),
|
||||
releaseNotified: boolean('release_notified').notNull().default(false),
|
||||
}, (table) => [index('question_packs_category_id_idx').on(table.categoryId)]);
|
||||
|
||||
export const questions = pgTable('questions', {
|
||||
|
||||
@@ -21,13 +21,14 @@ describe.skipIf(!databaseUrl || !isLocal)('admin repository authorization + audi
|
||||
const responseQuestion = '88888888-8888-4888-8888-888888888888';
|
||||
const responseId = '99999999-9999-4999-8999-999999999999';
|
||||
const responseMediaId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
const quizCouple = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
|
||||
let pool: Pool; let repository: PostgresAdminRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
await adminPool.query(`create schema "${schema}"`);
|
||||
const isolated = new URL(databaseUrl!); isolated.searchParams.set('options', `-c search_path=${schema}`);
|
||||
pool = new Pool({ connectionString: isolated.toString() }); repository = new PostgresAdminRepository(isolated.toString());
|
||||
for (const name of ['0000_identity_and_feature_interests.sql','0001_couples.sql','0002_packs_catalog_progress.sql','0003_answers_matches.sql','0004_chat.sql','0005_profile_settings.sql','0006_media_storage.sql','0007_billing_redemption.sql','0008_residual_realtime.sql','0009_operations_workers.sql','0010_admin.sql']) {
|
||||
for (const name of ['0000_identity_and_feature_interests.sql','0001_couples.sql','0002_packs_catalog_progress.sql','0003_answers_matches.sql','0004_chat.sql','0005_profile_settings.sql','0006_media_storage.sql','0007_billing_redemption.sql','0008_residual_realtime.sql','0009_operations_workers.sql','0010_admin.sql','0011_question_pack_average_precision.sql','0012_catalogue_field_parity.sql','0013_dares_loop.sql','0014_daily_limit_local_reset.sql','0015_daily_limit_response_index.sql','0016_couple_streak_locality.sql','0017_streak_reminder_preference.sql','0018_cutover_source_parity.sql','0019_quiz.sql','0020_quiz_question_pool.sql']) {
|
||||
const migration = await readFile(new URL(`../drizzle/${name}`, import.meta.url), 'utf8');
|
||||
for (const statement of migration.split('--> statement-breakpoint')) if (statement.trim()) await pool.query(statement);
|
||||
}
|
||||
@@ -161,6 +162,55 @@ describe.skipIf(!databaseUrl || !isLocal)('admin repository authorization + audi
|
||||
await expect(repository.responseMedia(responseViewer, responseId)).rejects.toMatchObject({ code: 'response_media_not_found' });
|
||||
});
|
||||
|
||||
it('exposes writable quiz content and read-only quiz activity resources', async () => {
|
||||
await pool.query('insert into couples(id,invite_code) values($1,$2)', [quizCouple, 'QUIZADMN']);
|
||||
await pool.query("update admin_users set permissions=array_append(permissions,'manage_questions') where user_id=$1", [creatorUser]);
|
||||
const creator = await repository.principal(creatorUser);
|
||||
const [question] = await repository.insert(creator, 'quiz_questions', [{
|
||||
prompt_self: 'How do you show affection?', prompt_guess: 'How does your partner show affection?', options: ['Touch', 'Words'],
|
||||
}]);
|
||||
expect(question).toMatchObject({ prompt_self: 'How do you show affection?' });
|
||||
|
||||
const principal = await repository.principal(superUser);
|
||||
const listed = await repository.query(principal, 'quiz_questions', { filters: [{ column: 'id', op: 'eq', value: question!.id }] });
|
||||
expect(listed.count).toBe(1);
|
||||
expect((await repository.query(principal, 'quiz_sessions', {})).count).toBe(0);
|
||||
await expect(repository.insert(principal, 'quiz_sessions', [{
|
||||
couple_id: quizCouple, status: 'active', question_ids: [question!.id],
|
||||
}])).rejects.toMatchObject({ code: 'forbidden' });
|
||||
});
|
||||
|
||||
it('reads sent dares for user support visibility without granting write access', async () => {
|
||||
await pool.query(
|
||||
`insert into sent_dares(couple_id,custom_dare_text,dare_text_snapshot,dare_intensity_snapshot,sender_id,recipient_id,status)
|
||||
values($1,'Give a compliment','Give a compliment',2,$2,$3,'pending')`,
|
||||
[quizCouple, creatorUser, moderatorUser],
|
||||
);
|
||||
const principal = await repository.principal(superUser);
|
||||
const result = await repository.query(principal, 'sent_dares', {});
|
||||
expect(result.count).toBe(1);
|
||||
expect(result.rows[0]).toMatchObject({ dare_text_snapshot: 'Give a compliment' });
|
||||
await expect(repository.insert(principal, 'sent_dares', [{
|
||||
couple_id: quizCouple, custom_dare_text: 'x', dare_text_snapshot: 'x',
|
||||
dare_intensity_snapshot: 1, sender_id: creatorUser, recipient_id: moderatorUser, status: 'pending',
|
||||
}])).rejects.toMatchObject({ code: 'forbidden' });
|
||||
});
|
||||
|
||||
it('reads notification preferences for user support visibility without granting write access', async () => {
|
||||
await pool.query(
|
||||
"insert into notification_preferences(user_id,matches_enabled,dares_enabled) values($1,true,false)",
|
||||
[creatorUser],
|
||||
);
|
||||
const principal = await repository.principal(superUser);
|
||||
const result = await repository.query(principal, 'notification_preferences', {
|
||||
filters: [{ column: 'user_id', op: 'eq', value: creatorUser }],
|
||||
});
|
||||
expect(result).toMatchObject({ count: 1, rows: [expect.objectContaining({ matches_enabled: true, dares_enabled: false })] });
|
||||
await expect(repository.insert(principal, 'notification_preferences', [{
|
||||
user_id: moderatorUser,
|
||||
}])).rejects.toMatchObject({ code: 'forbidden' });
|
||||
});
|
||||
|
||||
it('creates all legacy admin and dare cutover tables with preserved foreign keys', async () => {
|
||||
const tables = await pool.query<{ table_name: string }>(
|
||||
`select table_name from information_schema.tables where table_schema=current_schema()
|
||||
|
||||
Reference in new issue
Block a user