rest API added
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import { push, location } from 'svelte-spa-router';
|
||||
import { auth } from './stores/auth.js';
|
||||
import { navContext } from './stores/navContext.js';
|
||||
import { supabase } from './supabase.js';
|
||||
import { getProfile } from './api/profile.js';
|
||||
|
||||
$: loc = $location || '';
|
||||
@@ -78,7 +79,7 @@
|
||||
userMenuOpen = !userMenuOpen;
|
||||
if (userMenuOpen && $auth.user?.id && !profileLoading) {
|
||||
profileLoading = true;
|
||||
getProfile($auth.user.id).then((p) => {
|
||||
getProfile(supabase, $auth.user.id).then((p) => {
|
||||
profile = p;
|
||||
profileLoading = false;
|
||||
}).catch(() => { profileLoading = false; });
|
||||
@@ -98,7 +99,7 @@
|
||||
/** Load profile (including avatar) when user is logged in, so avatar shows after refresh */
|
||||
$: if (!$auth.loading && $auth.user?.id && !profile && !profileLoading) {
|
||||
profileLoading = true;
|
||||
getProfile($auth.user.id)
|
||||
getProfile(supabase, $auth.user.id)
|
||||
.then((p) => {
|
||||
profile = p;
|
||||
profileLoading = false;
|
||||
|
||||
@@ -119,7 +119,7 @@ describe('Navbar', () => {
|
||||
expect(screen.getByRole('menu')).toBeInTheDocument()
|
||||
expect(screen.getByRole('menuitem', { name: 'Settings' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('menuitem', { name: 'Logout' })).toBeInTheDocument()
|
||||
await waitFor(() => expect(getProfile).toHaveBeenCalledWith('u1'))
|
||||
await waitFor(() => expect(getProfile).toHaveBeenCalledWith(expect.anything(), 'u1'))
|
||||
})
|
||||
|
||||
it('goSettings: Settings link calls push and closes menu', async () => {
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
export async function fetchMyDecks(client, userId) {
|
||||
const { data, error } = await client
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, copied_from_deck_id, version, copied_from_version')
|
||||
.eq('owner_id', userId)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const decks = data ?? [];
|
||||
if (decks.length === 0) return [];
|
||||
|
||||
const deckIds = decks.map((d) => d.id);
|
||||
const sourceDeckIds = [...new Set(decks.map((d) => d.copied_from_deck_id).filter(Boolean))];
|
||||
const ratingDeckIds = [...new Set([...deckIds, ...sourceDeckIds])];
|
||||
|
||||
const [questionCounts, ratingsRows, sourceTitlesRows] = await Promise.all([
|
||||
Promise.all(
|
||||
decks.map(async (d) => {
|
||||
const { count, error: e } = await client
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
ratingDeckIds.length > 0
|
||||
? client.from('deck_ratings').select('deck_id, rating').in('deck_id', ratingDeckIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
sourceDeckIds.length > 0
|
||||
? client.from('decks').select('id, title, version, updated_at').in('id', sourceDeckIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
]);
|
||||
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
const sourceById = new Map((sourceTitlesRows.data ?? []).map((d) => [d.id, d]));
|
||||
|
||||
return decks.map((d, i) => {
|
||||
const showRatingDeckId = d.copied_from_deck_id || d.id;
|
||||
const rating = getRating(showRatingDeckId);
|
||||
const canRate = !!d.copied_from_deck_id;
|
||||
const sourceDeck = d.copied_from_deck_id ? sourceById.get(d.copied_from_deck_id) : null;
|
||||
const source_deck_title = sourceDeck?.title ?? 'Deck';
|
||||
const source_version = sourceDeck?.version ?? 1;
|
||||
const my_version = d.copied_from_version ?? 0;
|
||||
const versionOutdated = source_version > my_version;
|
||||
const sourceNewerByTime =
|
||||
sourceDeck?.updated_at &&
|
||||
d.updated_at &&
|
||||
new Date(sourceDeck.updated_at).getTime() > new Date(d.updated_at).getTime();
|
||||
const needs_update =
|
||||
!!d.copied_from_deck_id && (versionOutdated || sourceNewerByTime);
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
...rating,
|
||||
can_rate: canRate,
|
||||
rateable_deck_id: d.copied_from_deck_id || null,
|
||||
source_deck_title,
|
||||
source_version,
|
||||
needs_update,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string | null | undefined} [userId] - Current user id; when set, each deck gets user_has_this (true if user owns it or already has a copy).
|
||||
*/
|
||||
export async function fetchPublishedDecks(client, userId) {
|
||||
const { data, error } = await client
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, owner_id')
|
||||
.eq('published', true)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const decks = data ?? [];
|
||||
if (decks.length === 0) return [];
|
||||
|
||||
const deckIds = decks.map((d) => d.id);
|
||||
const ownerIds = [...new Set(decks.map((d) => d.owner_id).filter(Boolean))];
|
||||
|
||||
const promises = [
|
||||
Promise.all(
|
||||
decks.map(async (d) => {
|
||||
const { count, error: e } = await client
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
ownerIds.length > 0
|
||||
? client.from('profiles').select('id, display_name, email').in('id', ownerIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
client.from('deck_ratings').select('deck_id, rating').in('deck_id', deckIds),
|
||||
];
|
||||
|
||||
if (userId) {
|
||||
promises.push(
|
||||
client
|
||||
.from('decks')
|
||||
.select('copied_from_deck_id')
|
||||
.eq('owner_id', userId)
|
||||
.not('copied_from_deck_id', 'is', null)
|
||||
);
|
||||
}
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
const [questionCounts, profilesRows, ratingsRows, myDecksRows] = results;
|
||||
|
||||
const myCopiedFromIds = new Set();
|
||||
if (userId && myDecksRows?.data) {
|
||||
for (const row of myDecksRows.data) {
|
||||
if (row.copied_from_deck_id) myCopiedFromIds.add(row.copied_from_deck_id);
|
||||
}
|
||||
}
|
||||
|
||||
const profilesById = new Map(
|
||||
(profilesRows.data ?? []).map((p) => [p.id, { display_name: p.display_name, email: p.email }])
|
||||
);
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
return decks.map((d, i) => {
|
||||
const profile = profilesById.get(d.owner_id);
|
||||
const owner_email = profile?.email ?? profile?.display_name ?? 'User';
|
||||
const user_has_this =
|
||||
!!userId && (d.owner_id === userId || myCopiedFromIds.has(d.id));
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
owner_display_name: profile?.display_name ?? 'User',
|
||||
owner_email,
|
||||
...getRating(d.id),
|
||||
user_has_this,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} ownerId - Owner of the decks to list.
|
||||
* @param {string | null | undefined} [viewerId] - Current user id; when set, each deck gets user_has_this (true if viewer owns it or already has a copy).
|
||||
*/
|
||||
export async function fetchPublishedDecksByOwner(client, ownerId, viewerId) {
|
||||
const { data: decks, error } = await client
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, owner_id')
|
||||
.eq('published', true)
|
||||
.eq('owner_id', ownerId)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const deckList = decks ?? [];
|
||||
if (deckList.length === 0) {
|
||||
const { data: profile } = await client.from('profiles').select('id, display_name, email').eq('id', ownerId).single();
|
||||
return {
|
||||
decks: [],
|
||||
owner_email: profile?.email ?? profile?.display_name ?? 'User',
|
||||
owner_display_name: profile?.display_name ?? profile?.email ?? 'User',
|
||||
};
|
||||
}
|
||||
|
||||
const deckIds = deckList.map((d) => d.id);
|
||||
const promises = [
|
||||
Promise.all(
|
||||
deckList.map(async (d) => {
|
||||
const { count, error: e } = await client
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
client.from('deck_ratings').select('deck_id, rating').in('deck_id', deckIds),
|
||||
];
|
||||
|
||||
if (viewerId && viewerId !== ownerId) {
|
||||
promises.push(
|
||||
client
|
||||
.from('decks')
|
||||
.select('copied_from_deck_id')
|
||||
.eq('owner_id', viewerId)
|
||||
.not('copied_from_deck_id', 'is', null)
|
||||
);
|
||||
}
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
const [questionCounts, ratingsRows, myDecksRows] = results;
|
||||
|
||||
const myCopiedFromIds = new Set();
|
||||
if (viewerId && viewerId !== ownerId && myDecksRows?.data) {
|
||||
for (const row of myDecksRows.data) {
|
||||
if (row.copied_from_deck_id) myCopiedFromIds.add(row.copied_from_deck_id);
|
||||
}
|
||||
}
|
||||
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
const { data: profile } = await client.from('profiles').select('id, display_name, email').eq('id', ownerId).single();
|
||||
const owner_email = profile?.email ?? profile?.display_name ?? 'User';
|
||||
const owner_display_name = profile?.display_name ?? profile?.email ?? 'User';
|
||||
|
||||
const decksWithMeta = deckList.map((d, i) => {
|
||||
const user_has_this =
|
||||
!!viewerId &&
|
||||
(viewerId === ownerId || myCopiedFromIds.has(d.id));
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
owner_email,
|
||||
owner_display_name,
|
||||
...getRating(d.id),
|
||||
user_has_this,
|
||||
};
|
||||
});
|
||||
|
||||
return { decks: decksWithMeta, owner_email, owner_display_name };
|
||||
}
|
||||
|
||||
export async function fetchDeckWithQuestions(client, deckId) {
|
||||
const { data: deck, error: deckError } = await client
|
||||
.from('decks')
|
||||
.select('*')
|
||||
.eq('id', deckId)
|
||||
.single();
|
||||
if (deckError || !deck) throw deckError || new Error('Deck not found');
|
||||
const { data: questions, error: qError } = await client
|
||||
.from('questions')
|
||||
.select('*')
|
||||
.eq('deck_id', deckId)
|
||||
.order('sort_order', { ascending: true });
|
||||
if (qError) throw qError;
|
||||
return { ...deck, questions: questions ?? [] };
|
||||
}
|
||||
|
||||
/** Copy a published deck (and its questions) into the current user's account. New deck is unpublished. */
|
||||
export async function copyDeckToUser(client, deckId, userId) {
|
||||
const source = await fetchDeckWithQuestions(client, deckId);
|
||||
if (!source.published) throw new Error('Deck is not available to copy');
|
||||
const questions = (source.questions ?? []).map((q) => ({
|
||||
prompt: q.prompt ?? '',
|
||||
explanation: q.explanation ?? '',
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
return createDeck(client, userId, {
|
||||
title: source.title,
|
||||
description: source.description ?? '',
|
||||
config: source.config ?? {},
|
||||
questions,
|
||||
copiedFromDeckId: deckId,
|
||||
copiedFromVersion: source.version ?? 1,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createDeck(client, ownerId, { title, description, config, questions, copiedFromDeckId, copiedFromVersion }) {
|
||||
const row = {
|
||||
owner_id: ownerId,
|
||||
title: title.trim(),
|
||||
description: (description ?? '').trim(),
|
||||
config: config ?? {},
|
||||
};
|
||||
if (copiedFromDeckId != null) row.copied_from_deck_id = copiedFromDeckId;
|
||||
if (copiedFromVersion != null) row.copied_from_version = copiedFromVersion;
|
||||
const { data: deck, error: deckError } = await client
|
||||
.from('decks')
|
||||
.insert(row)
|
||||
.select('id')
|
||||
.single();
|
||||
if (deckError || !deck) throw deckError || new Error('Failed to create deck');
|
||||
if (questions && questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: deck.id,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await client.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
return deck.id;
|
||||
}
|
||||
|
||||
export async function updateDeck(client, deckId, { title, description, config, questions }) {
|
||||
const { data: current, error: fetchErr } = await client
|
||||
.from('decks')
|
||||
.select('version, published')
|
||||
.eq('id', deckId)
|
||||
.single();
|
||||
if (fetchErr) throw fetchErr;
|
||||
const bumpVersion = current?.published === true;
|
||||
const nextVersion = bumpVersion ? (current?.version ?? 1) + 1 : (current?.version ?? 1);
|
||||
const updatePayload = {
|
||||
title: title.trim(),
|
||||
description: (description ?? '').trim(),
|
||||
config: config ?? {},
|
||||
version: nextVersion,
|
||||
};
|
||||
const { error: deckError } = await client
|
||||
.from('decks')
|
||||
.update(updatePayload)
|
||||
.eq('id', deckId);
|
||||
if (deckError) throw deckError;
|
||||
const { error: delError } = await client.from('questions').delete().eq('deck_id', deckId);
|
||||
if (delError) throw delError;
|
||||
if (questions && questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: deckId,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await client.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
}
|
||||
|
||||
export async function togglePublished(client, deckId, published) {
|
||||
const { error } = await client.from('decks').update({ published }).eq('id', deckId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
export async function deleteDeck(client, deckId) {
|
||||
const { error } = await client.from('decks').delete().eq('id', deckId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get source deck and copy deck with questions for the "Update from community" preview.
|
||||
* Copy must be owned by userId and have copied_from_deck_id.
|
||||
* @returns {{ source: object, copy: object, changes: string[] }}
|
||||
*/
|
||||
export async function getSourceUpdatePreview(client, copyDeckId, userId) {
|
||||
const { data: copy, error: copyErr } = await client
|
||||
.from('decks')
|
||||
.select('*')
|
||||
.eq('id', copyDeckId)
|
||||
.eq('owner_id', userId)
|
||||
.single();
|
||||
if (copyErr || !copy?.copied_from_deck_id) throw new Error('Deck not found or not a copy');
|
||||
const sourceId = copy.copied_from_deck_id;
|
||||
const [source, copyQuestionsRows] = await Promise.all([
|
||||
fetchDeckWithQuestions(client, sourceId),
|
||||
client.from('questions').select('*').eq('deck_id', copyDeckId).order('sort_order', { ascending: true }),
|
||||
]);
|
||||
if (!source.published) throw new Error('Source deck is no longer available');
|
||||
const copyQuestions = copyQuestionsRows.data ?? [];
|
||||
const copyWithQuestions = { ...copy, questions: copyQuestions };
|
||||
|
||||
const changes = [];
|
||||
if ((source.title ?? '').trim() !== (copy.title ?? '').trim()) {
|
||||
changes.push(`Title: "${(copy.title ?? '').trim()}" → "${(source.title ?? '').trim()}"`);
|
||||
}
|
||||
if ((source.description ?? '').trim() !== (copy.description ?? '').trim()) {
|
||||
changes.push('Description updated');
|
||||
}
|
||||
const srcLen = (source.questions ?? []).length;
|
||||
const copyLen = copyQuestions.length;
|
||||
if (srcLen !== copyLen) {
|
||||
changes.push(`Questions: ${copyLen} → ${srcLen}`);
|
||||
} else {
|
||||
const anyDifferent = (source.questions ?? []).some((sq, i) => {
|
||||
const cq = copyQuestions[i];
|
||||
if (!cq) return true;
|
||||
return (sq.prompt ?? '') !== (cq.prompt ?? '') || (sq.explanation ?? '') !== (cq.explanation ?? '');
|
||||
});
|
||||
if (anyDifferent) changes.push('Some question content updated');
|
||||
}
|
||||
if (changes.length === 0) changes.push('Content is in sync (version metadata will update)');
|
||||
|
||||
return { source, copy: copyWithQuestions, changes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a community copy to match the current source deck (title, description, config, questions, copied_from_version).
|
||||
*/
|
||||
export async function applySourceUpdate(client, copyDeckId, userId) {
|
||||
const { data: copy, error: copyErr } = await client
|
||||
.from('decks')
|
||||
.select('id, copied_from_deck_id')
|
||||
.eq('id', copyDeckId)
|
||||
.eq('owner_id', userId)
|
||||
.single();
|
||||
if (copyErr || !copy?.copied_from_deck_id) throw new Error('Deck not found or not a copy');
|
||||
const source = await fetchDeckWithQuestions(client, copy.copied_from_deck_id);
|
||||
if (!source.published) throw new Error('Source deck is no longer available');
|
||||
|
||||
const { error: deckError } = await client
|
||||
.from('decks')
|
||||
.update({
|
||||
title: source.title ?? '',
|
||||
description: source.description ?? '',
|
||||
config: source.config ?? {},
|
||||
copied_from_version: source.version ?? 1,
|
||||
})
|
||||
.eq('id', copyDeckId);
|
||||
if (deckError) throw deckError;
|
||||
|
||||
const { error: delError } = await client.from('questions').delete().eq('deck_id', copyDeckId);
|
||||
if (delError) throw delError;
|
||||
const questions = source.questions ?? [];
|
||||
if (questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: copyDeckId,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await client.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
}
|
||||
|
||||
/** True if the user already has this deck (owns it or has added a copy). */
|
||||
export async function userHasDeck(client, deckId, userId) {
|
||||
if (!userId) return false;
|
||||
const { data, error } = await client
|
||||
.from('decks')
|
||||
.select('id')
|
||||
.eq('owner_id', userId)
|
||||
.or(`id.eq.${deckId},copied_from_deck_id.eq.${deckId}`)
|
||||
.limit(1);
|
||||
if (error) throw error;
|
||||
return (data?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** Get all reviews (ratings + comments) for a deck with reviewer display names. */
|
||||
export async function getDeckReviews(client, deckId) {
|
||||
const { data: ratings, error: rError } = await client
|
||||
.from('deck_ratings')
|
||||
.select('user_id, rating, comment, created_at')
|
||||
.eq('deck_id', deckId)
|
||||
.order('created_at', { ascending: false });
|
||||
if (rError) throw rError;
|
||||
const list = ratings ?? [];
|
||||
if (list.length === 0) return [];
|
||||
const userIds = [...new Set(list.map((r) => r.user_id).filter(Boolean))];
|
||||
const { data: profiles } = await client
|
||||
.from('profiles')
|
||||
.select('id, display_name, email, avatar_url')
|
||||
.in('id', userIds);
|
||||
const byId = new Map((profiles ?? []).map((p) => [p.id, p]));
|
||||
return list.map((r) => {
|
||||
const p = byId.get(r.user_id);
|
||||
return {
|
||||
rating: r.rating,
|
||||
comment: r.comment || null,
|
||||
user_id: r.user_id,
|
||||
display_name: p?.display_name ?? null,
|
||||
email: p?.email ?? null,
|
||||
avatar_url: p?.avatar_url ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Get the current user's rating (and comment) for a deck, or null if none. */
|
||||
export async function getMyDeckRating(client, deckId, userId) {
|
||||
if (!userId) return null;
|
||||
const { data, error } = await client
|
||||
.from('deck_ratings')
|
||||
.select('rating, comment')
|
||||
.eq('deck_id', deckId)
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
/** Submit or update rating (and optional comment) for a deck. Upserts by (deck_id, user_id). */
|
||||
export async function submitDeckRating(client, deckId, userId, { rating, comment }) {
|
||||
const row = {
|
||||
deck_id: deckId,
|
||||
user_id: userId,
|
||||
rating: Math.min(5, Math.max(1, Math.round(rating))),
|
||||
comment: (comment ?? '').trim() || null,
|
||||
};
|
||||
const { error } = await client.from('deck_ratings').upsert(row, {
|
||||
onConflict: 'deck_id,user_id',
|
||||
});
|
||||
if (error) throw error;
|
||||
}
|
||||
+1
-517
@@ -1,519 +1,3 @@
|
||||
import { supabase } from '../supabase.js';
|
||||
|
||||
export async function fetchMyDecks(userId) {
|
||||
const { data, error } = await supabase
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, copied_from_deck_id, version, copied_from_version')
|
||||
.eq('owner_id', userId)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const decks = data ?? [];
|
||||
if (decks.length === 0) return [];
|
||||
|
||||
const deckIds = decks.map((d) => d.id);
|
||||
const sourceDeckIds = [...new Set(decks.map((d) => d.copied_from_deck_id).filter(Boolean))];
|
||||
const ratingDeckIds = [...new Set([...deckIds, ...sourceDeckIds])];
|
||||
|
||||
const [questionCounts, ratingsRows, sourceTitlesRows] = await Promise.all([
|
||||
Promise.all(
|
||||
decks.map(async (d) => {
|
||||
const { count, error: e } = await supabase
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
ratingDeckIds.length > 0
|
||||
? supabase.from('deck_ratings').select('deck_id, rating').in('deck_id', ratingDeckIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
sourceDeckIds.length > 0
|
||||
? supabase.from('decks').select('id, title, version, updated_at').in('id', sourceDeckIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
]);
|
||||
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
const sourceById = new Map((sourceTitlesRows.data ?? []).map((d) => [d.id, d]));
|
||||
|
||||
return decks.map((d, i) => {
|
||||
const showRatingDeckId = d.copied_from_deck_id || d.id;
|
||||
const rating = getRating(showRatingDeckId);
|
||||
const canRate = !!d.copied_from_deck_id;
|
||||
const sourceDeck = d.copied_from_deck_id ? sourceById.get(d.copied_from_deck_id) : null;
|
||||
const source_deck_title = sourceDeck?.title ?? 'Deck';
|
||||
const source_version = sourceDeck?.version ?? 1;
|
||||
const my_version = d.copied_from_version ?? 0;
|
||||
const versionOutdated = source_version > my_version;
|
||||
const sourceNewerByTime =
|
||||
sourceDeck?.updated_at &&
|
||||
d.updated_at &&
|
||||
new Date(sourceDeck.updated_at).getTime() > new Date(d.updated_at).getTime();
|
||||
const needs_update =
|
||||
!!d.copied_from_deck_id && (versionOutdated || sourceNewerByTime);
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
...rating,
|
||||
can_rate: canRate,
|
||||
rateable_deck_id: d.copied_from_deck_id || null,
|
||||
source_deck_title,
|
||||
source_version,
|
||||
needs_update,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string | null | undefined} [userId] - Current user id; when set, each deck gets user_has_this (true if user owns it or already has a copy).
|
||||
*/
|
||||
export async function fetchPublishedDecks(userId) {
|
||||
const { data, error } = await supabase
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, owner_id')
|
||||
.eq('published', true)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const decks = data ?? [];
|
||||
if (decks.length === 0) return [];
|
||||
|
||||
const deckIds = decks.map((d) => d.id);
|
||||
const ownerIds = [...new Set(decks.map((d) => d.owner_id).filter(Boolean))];
|
||||
|
||||
const promises = [
|
||||
Promise.all(
|
||||
decks.map(async (d) => {
|
||||
const { count, error: e } = await supabase
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
ownerIds.length > 0
|
||||
? supabase.from('profiles').select('id, display_name, email').in('id', ownerIds)
|
||||
: Promise.resolve({ data: [] }),
|
||||
supabase.from('deck_ratings').select('deck_id, rating').in('deck_id', deckIds),
|
||||
];
|
||||
|
||||
if (userId) {
|
||||
promises.push(
|
||||
supabase
|
||||
.from('decks')
|
||||
.select('copied_from_deck_id')
|
||||
.eq('owner_id', userId)
|
||||
.not('copied_from_deck_id', 'is', null)
|
||||
);
|
||||
}
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
const [questionCounts, profilesRows, ratingsRows, myDecksRows] = results;
|
||||
|
||||
const myCopiedFromIds = new Set();
|
||||
if (userId && myDecksRows?.data) {
|
||||
for (const row of myDecksRows.data) {
|
||||
if (row.copied_from_deck_id) myCopiedFromIds.add(row.copied_from_deck_id);
|
||||
}
|
||||
}
|
||||
|
||||
const profilesById = new Map(
|
||||
(profilesRows.data ?? []).map((p) => [p.id, { display_name: p.display_name, email: p.email }])
|
||||
);
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
return decks.map((d, i) => {
|
||||
const profile = profilesById.get(d.owner_id);
|
||||
const owner_email = profile?.email ?? profile?.display_name ?? 'User';
|
||||
const user_has_this =
|
||||
!!userId && (d.owner_id === userId || myCopiedFromIds.has(d.id));
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
owner_display_name: profile?.display_name ?? 'User',
|
||||
owner_email,
|
||||
...getRating(d.id),
|
||||
user_has_this,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} ownerId - Owner of the decks to list.
|
||||
* @param {string | null | undefined} [viewerId] - Current user id; when set, each deck gets user_has_this (true if viewer owns it or already has a copy).
|
||||
*/
|
||||
export async function fetchPublishedDecksByOwner(ownerId, viewerId) {
|
||||
const { data: decks, error } = await supabase
|
||||
.from('decks')
|
||||
.select('id, title, description, config, published, created_at, updated_at, owner_id')
|
||||
.eq('published', true)
|
||||
.eq('owner_id', ownerId)
|
||||
.order('updated_at', { ascending: false });
|
||||
if (error) throw error;
|
||||
const deckList = decks ?? [];
|
||||
if (deckList.length === 0) {
|
||||
const { data: profile } = await supabase.from('profiles').select('id, display_name, email').eq('id', ownerId).single();
|
||||
return {
|
||||
decks: [],
|
||||
owner_email: profile?.email ?? profile?.display_name ?? 'User',
|
||||
owner_display_name: profile?.display_name ?? profile?.email ?? 'User',
|
||||
};
|
||||
}
|
||||
|
||||
const deckIds = deckList.map((d) => d.id);
|
||||
const promises = [
|
||||
Promise.all(
|
||||
deckList.map(async (d) => {
|
||||
const { count, error: e } = await supabase
|
||||
.from('questions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('deck_id', d.id);
|
||||
if (e) return 0;
|
||||
return count ?? 0;
|
||||
})
|
||||
),
|
||||
supabase.from('deck_ratings').select('deck_id, rating').in('deck_id', deckIds),
|
||||
];
|
||||
|
||||
if (viewerId && viewerId !== ownerId) {
|
||||
promises.push(
|
||||
supabase
|
||||
.from('decks')
|
||||
.select('copied_from_deck_id')
|
||||
.eq('owner_id', viewerId)
|
||||
.not('copied_from_deck_id', 'is', null)
|
||||
);
|
||||
}
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
const [questionCounts, ratingsRows, myDecksRows] = results;
|
||||
|
||||
const myCopiedFromIds = new Set();
|
||||
if (viewerId && viewerId !== ownerId && myDecksRows?.data) {
|
||||
for (const row of myDecksRows.data) {
|
||||
if (row.copied_from_deck_id) myCopiedFromIds.add(row.copied_from_deck_id);
|
||||
}
|
||||
}
|
||||
|
||||
const ratingByDeck = new Map();
|
||||
for (const r of ratingsRows.data ?? []) {
|
||||
if (!ratingByDeck.has(r.deck_id)) ratingByDeck.set(r.deck_id, []);
|
||||
ratingByDeck.get(r.deck_id).push(r.rating);
|
||||
}
|
||||
const getRating = (deckId) => {
|
||||
const arr = ratingByDeck.get(deckId);
|
||||
if (!arr?.length) return { average_rating: 0, rating_count: 0 };
|
||||
const sum = arr.reduce((a, b) => a + b, 0);
|
||||
return { average_rating: Math.round((sum / arr.length) * 100) / 100, rating_count: arr.length };
|
||||
};
|
||||
|
||||
const { data: profile } = await supabase.from('profiles').select('id, display_name, email').eq('id', ownerId).single();
|
||||
const owner_email = profile?.email ?? profile?.display_name ?? 'User';
|
||||
const owner_display_name = profile?.display_name ?? profile?.email ?? 'User';
|
||||
|
||||
const decksWithMeta = deckList.map((d, i) => {
|
||||
const user_has_this =
|
||||
!!viewerId &&
|
||||
(viewerId === ownerId || myCopiedFromIds.has(d.id));
|
||||
return {
|
||||
...d,
|
||||
question_count: questionCounts[i],
|
||||
owner_email,
|
||||
owner_display_name,
|
||||
...getRating(d.id),
|
||||
user_has_this,
|
||||
};
|
||||
});
|
||||
|
||||
return { decks: decksWithMeta, owner_email, owner_display_name };
|
||||
}
|
||||
|
||||
export async function fetchDeckWithQuestions(deckId) {
|
||||
const { data: deck, error: deckError } = await supabase
|
||||
.from('decks')
|
||||
.select('*')
|
||||
.eq('id', deckId)
|
||||
.single();
|
||||
if (deckError || !deck) throw deckError || new Error('Deck not found');
|
||||
const { data: questions, error: qError } = await supabase
|
||||
.from('questions')
|
||||
.select('*')
|
||||
.eq('deck_id', deckId)
|
||||
.order('sort_order', { ascending: true });
|
||||
if (qError) throw qError;
|
||||
return { ...deck, questions: questions ?? [] };
|
||||
}
|
||||
|
||||
/** Copy a published deck (and its questions) into the current user's account. New deck is unpublished. */
|
||||
export async function copyDeckToUser(deckId, userId) {
|
||||
const source = await fetchDeckWithQuestions(deckId);
|
||||
if (!source.published) throw new Error('Deck is not available to copy');
|
||||
const questions = (source.questions ?? []).map((q) => ({
|
||||
prompt: q.prompt ?? '',
|
||||
explanation: q.explanation ?? '',
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
return createDeck(userId, {
|
||||
title: source.title,
|
||||
description: source.description ?? '',
|
||||
config: source.config ?? {},
|
||||
questions,
|
||||
copiedFromDeckId: deckId,
|
||||
copiedFromVersion: source.version ?? 1,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createDeck(ownerId, { title, description, config, questions, copiedFromDeckId, copiedFromVersion }) {
|
||||
const row = {
|
||||
owner_id: ownerId,
|
||||
title: title.trim(),
|
||||
description: (description ?? '').trim(),
|
||||
config: config ?? {},
|
||||
};
|
||||
if (copiedFromDeckId != null) row.copied_from_deck_id = copiedFromDeckId;
|
||||
if (copiedFromVersion != null) row.copied_from_version = copiedFromVersion;
|
||||
const { data: deck, error: deckError } = await supabase
|
||||
.from('decks')
|
||||
.insert(row)
|
||||
.select('id')
|
||||
.single();
|
||||
if (deckError || !deck) throw deckError || new Error('Failed to create deck');
|
||||
if (questions && questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: deck.id,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await supabase.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
return deck.id;
|
||||
}
|
||||
|
||||
export async function updateDeck(deckId, { title, description, config, questions }) {
|
||||
const { data: current, error: fetchErr } = await supabase
|
||||
.from('decks')
|
||||
.select('version, published')
|
||||
.eq('id', deckId)
|
||||
.single();
|
||||
if (fetchErr) throw fetchErr;
|
||||
const bumpVersion = current?.published === true;
|
||||
const nextVersion = bumpVersion ? (current?.version ?? 1) + 1 : (current?.version ?? 1);
|
||||
const updatePayload = {
|
||||
title: title.trim(),
|
||||
description: (description ?? '').trim(),
|
||||
config: config ?? {},
|
||||
version: nextVersion,
|
||||
};
|
||||
const { error: deckError } = await supabase
|
||||
.from('decks')
|
||||
.update(updatePayload)
|
||||
.eq('id', deckId);
|
||||
if (deckError) throw deckError;
|
||||
const { error: delError } = await supabase.from('questions').delete().eq('deck_id', deckId);
|
||||
if (delError) throw delError;
|
||||
if (questions && questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: deckId,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await supabase.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
}
|
||||
|
||||
export async function togglePublished(deckId, published) {
|
||||
const { error } = await supabase.from('decks').update({ published }).eq('id', deckId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
export async function deleteDeck(deckId) {
|
||||
const { error } = await supabase.from('decks').delete().eq('id', deckId);
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get source deck and copy deck with questions for the "Update from community" preview.
|
||||
* Copy must be owned by userId and have copied_from_deck_id.
|
||||
* @returns {{ source: object, copy: object, changes: string[] }}
|
||||
*/
|
||||
export async function getSourceUpdatePreview(copyDeckId, userId) {
|
||||
const { data: copy, error: copyErr } = await supabase
|
||||
.from('decks')
|
||||
.select('*')
|
||||
.eq('id', copyDeckId)
|
||||
.eq('owner_id', userId)
|
||||
.single();
|
||||
if (copyErr || !copy?.copied_from_deck_id) throw new Error('Deck not found or not a copy');
|
||||
const sourceId = copy.copied_from_deck_id;
|
||||
const [source, copyQuestionsRows] = await Promise.all([
|
||||
fetchDeckWithQuestions(sourceId),
|
||||
supabase.from('questions').select('*').eq('deck_id', copyDeckId).order('sort_order', { ascending: true }),
|
||||
]);
|
||||
if (!source.published) throw new Error('Source deck is no longer available');
|
||||
const copyQuestions = copyQuestionsRows.data ?? [];
|
||||
const copyWithQuestions = { ...copy, questions: copyQuestions };
|
||||
|
||||
const changes = [];
|
||||
if ((source.title ?? '').trim() !== (copy.title ?? '').trim()) {
|
||||
changes.push(`Title: "${(copy.title ?? '').trim()}" → "${(source.title ?? '').trim()}"`);
|
||||
}
|
||||
if ((source.description ?? '').trim() !== (copy.description ?? '').trim()) {
|
||||
changes.push('Description updated');
|
||||
}
|
||||
const srcLen = (source.questions ?? []).length;
|
||||
const copyLen = copyQuestions.length;
|
||||
if (srcLen !== copyLen) {
|
||||
changes.push(`Questions: ${copyLen} → ${srcLen}`);
|
||||
} else {
|
||||
const anyDifferent = (source.questions ?? []).some((sq, i) => {
|
||||
const cq = copyQuestions[i];
|
||||
if (!cq) return true;
|
||||
return (sq.prompt ?? '') !== (cq.prompt ?? '') || (sq.explanation ?? '') !== (cq.explanation ?? '');
|
||||
});
|
||||
if (anyDifferent) changes.push('Some question content updated');
|
||||
}
|
||||
if (changes.length === 0) changes.push('Content is in sync (version metadata will update)');
|
||||
|
||||
return { source, copy: copyWithQuestions, changes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a community copy to match the current source deck (title, description, config, questions, copied_from_version).
|
||||
*/
|
||||
export async function applySourceUpdate(copyDeckId, userId) {
|
||||
const { data: copy, error: copyErr } = await supabase
|
||||
.from('decks')
|
||||
.select('id, copied_from_deck_id')
|
||||
.eq('id', copyDeckId)
|
||||
.eq('owner_id', userId)
|
||||
.single();
|
||||
if (copyErr || !copy?.copied_from_deck_id) throw new Error('Deck not found or not a copy');
|
||||
const source = await fetchDeckWithQuestions(copy.copied_from_deck_id);
|
||||
if (!source.published) throw new Error('Source deck is no longer available');
|
||||
|
||||
const { error: deckError } = await supabase
|
||||
.from('decks')
|
||||
.update({
|
||||
title: source.title ?? '',
|
||||
description: source.description ?? '',
|
||||
config: source.config ?? {},
|
||||
copied_from_version: source.version ?? 1,
|
||||
})
|
||||
.eq('id', copyDeckId);
|
||||
if (deckError) throw deckError;
|
||||
|
||||
const { error: delError } = await supabase.from('questions').delete().eq('deck_id', copyDeckId);
|
||||
if (delError) throw delError;
|
||||
const questions = source.questions ?? [];
|
||||
if (questions.length > 0) {
|
||||
const rows = questions.map((q, i) => ({
|
||||
deck_id: copyDeckId,
|
||||
sort_order: i,
|
||||
prompt: (q.prompt ?? '').trim(),
|
||||
explanation: (q.explanation ?? '').trim() || null,
|
||||
answers: Array.isArray(q.answers) ? q.answers : [],
|
||||
correct_answer_indices: Array.isArray(q.correct_answer_indices) ? q.correct_answer_indices : [],
|
||||
}));
|
||||
const { error: qError } = await supabase.from('questions').insert(rows);
|
||||
if (qError) throw qError;
|
||||
}
|
||||
}
|
||||
|
||||
/** True if the user already has this deck (owns it or has added a copy). */
|
||||
export async function userHasDeck(deckId, userId) {
|
||||
if (!userId) return false;
|
||||
const { data, error } = await supabase
|
||||
.from('decks')
|
||||
.select('id')
|
||||
.eq('owner_id', userId)
|
||||
.or(`id.eq.${deckId},copied_from_deck_id.eq.${deckId}`)
|
||||
.limit(1);
|
||||
if (error) throw error;
|
||||
return (data?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** Get all reviews (ratings + comments) for a deck with reviewer display names. */
|
||||
export async function getDeckReviews(deckId) {
|
||||
const { data: ratings, error: rError } = await supabase
|
||||
.from('deck_ratings')
|
||||
.select('user_id, rating, comment, created_at')
|
||||
.eq('deck_id', deckId)
|
||||
.order('created_at', { ascending: false });
|
||||
if (rError) throw rError;
|
||||
const list = ratings ?? [];
|
||||
if (list.length === 0) return [];
|
||||
const userIds = [...new Set(list.map((r) => r.user_id).filter(Boolean))];
|
||||
const { data: profiles } = await supabase
|
||||
.from('profiles')
|
||||
.select('id, display_name, email, avatar_url')
|
||||
.in('id', userIds);
|
||||
const byId = new Map((profiles ?? []).map((p) => [p.id, p]));
|
||||
return list.map((r) => {
|
||||
const p = byId.get(r.user_id);
|
||||
return {
|
||||
rating: r.rating,
|
||||
comment: r.comment || null,
|
||||
user_id: r.user_id,
|
||||
display_name: p?.display_name ?? null,
|
||||
email: p?.email ?? null,
|
||||
avatar_url: p?.avatar_url ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Get the current user's rating (and comment) for a deck, or null if none. */
|
||||
export async function getMyDeckRating(deckId, userId) {
|
||||
if (!userId) return null;
|
||||
const { data, error } = await supabase
|
||||
.from('deck_ratings')
|
||||
.select('rating, comment')
|
||||
.eq('deck_id', deckId)
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
|
||||
/** Submit or update rating (and optional comment) for a deck. Upserts by (deck_id, user_id). */
|
||||
export async function submitDeckRating(deckId, userId, { rating, comment }) {
|
||||
const row = {
|
||||
deck_id: deckId,
|
||||
user_id: userId,
|
||||
rating: Math.min(5, Math.max(1, Math.round(rating))),
|
||||
comment: (comment ?? '').trim() || null,
|
||||
};
|
||||
const { error } = await supabase.from('deck_ratings').upsert(row, {
|
||||
onConflict: 'deck_id,user_id',
|
||||
});
|
||||
if (error) throw error;
|
||||
}
|
||||
export * from './decks-core.js';
|
||||
|
||||
+29
-28
@@ -1,4 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { supabase } from '../supabase.js'
|
||||
import * as decksApi from './decks.js'
|
||||
|
||||
const nextResults = []
|
||||
@@ -53,7 +54,7 @@ describe('decks API', () => {
|
||||
describe('fetchMyDecks', () => {
|
||||
it('returns empty array when no decks', async () => {
|
||||
nextResults.push({ data: [], error: null })
|
||||
const result = await decksApi.fetchMyDecks('user1')
|
||||
const result = await decksApi.fetchMyDecks(supabase, 'user1')
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
@@ -63,7 +64,7 @@ describe('decks API', () => {
|
||||
]
|
||||
nextResults.push({ data: decks, error: null }, { data: [], error: null }, { data: [], error: null })
|
||||
countResults.push({ count: 3, error: null })
|
||||
const result = await decksApi.fetchMyDecks('user1')
|
||||
const result = await decksApi.fetchMyDecks(supabase, 'user1')
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0].question_count).toBe(3)
|
||||
expect(result[0].title).toBe('Deck 1')
|
||||
@@ -73,7 +74,7 @@ describe('decks API', () => {
|
||||
describe('fetchPublishedDecks', () => {
|
||||
it('returns empty array when no published decks', async () => {
|
||||
nextResults.push({ data: [], error: null })
|
||||
const result = await decksApi.fetchPublishedDecks()
|
||||
const result = await decksApi.fetchPublishedDecks(supabase)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -83,91 +84,91 @@ describe('decks API', () => {
|
||||
const deck = { id: 'd1', title: 'Deck', version: 1 }
|
||||
const questions = [{ id: 'q1', prompt: 'Q?', sort_order: 0 }]
|
||||
nextResults.push({ data: deck, error: null }, { data: questions, error: null })
|
||||
const result = await decksApi.fetchDeckWithQuestions('d1')
|
||||
const result = await decksApi.fetchDeckWithQuestions(supabase, 'd1')
|
||||
expect(result).toMatchObject({ ...deck, questions })
|
||||
expect(result.questions).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('throws when deck not found', async () => {
|
||||
nextResults.push({ data: null, error: new Error('Not found') })
|
||||
await expect(decksApi.fetchDeckWithQuestions('bad')).rejects.toThrow()
|
||||
await expect(decksApi.fetchDeckWithQuestions(supabase, 'bad')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('userHasDeck', () => {
|
||||
it('returns false when userId is null', async () => {
|
||||
expect(await decksApi.userHasDeck('d1', null)).toBe(false)
|
||||
expect(await decksApi.userHasDeck(supabase, 'd1', null)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when user has deck', async () => {
|
||||
nextResults.push({ data: [{ id: 'd1' }], error: null })
|
||||
expect(await decksApi.userHasDeck('d1', 'user1')).toBe(true)
|
||||
expect(await decksApi.userHasDeck(supabase, 'd1', 'user1')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when no match', async () => {
|
||||
nextResults.push({ data: [], error: null })
|
||||
expect(await decksApi.userHasDeck('d1', 'user1')).toBe(false)
|
||||
expect(await decksApi.userHasDeck(supabase, 'd1', 'user1')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('togglePublished', () => {
|
||||
it('calls update and throws on error', async () => {
|
||||
nextResults.push({ error: new Error('DB error') })
|
||||
await expect(decksApi.togglePublished('d1', true)).rejects.toThrow('DB error')
|
||||
await expect(decksApi.togglePublished(supabase, 'd1', true)).rejects.toThrow('DB error')
|
||||
})
|
||||
|
||||
it('succeeds when no error', async () => {
|
||||
nextResults.push({ error: null })
|
||||
await expect(decksApi.togglePublished('d1', false)).resolves.toBeUndefined()
|
||||
await expect(decksApi.togglePublished(supabase, 'd1', false)).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteDeck', () => {
|
||||
it('throws on error', async () => {
|
||||
nextResults.push({ error: new Error('FK violation') })
|
||||
await expect(decksApi.deleteDeck('d1')).rejects.toThrow('FK violation')
|
||||
await expect(decksApi.deleteDeck(supabase, 'd1')).rejects.toThrow('FK violation')
|
||||
})
|
||||
|
||||
it('succeeds when no error', async () => {
|
||||
nextResults.push({ error: null })
|
||||
await expect(decksApi.deleteDeck('d1')).resolves.toBeUndefined()
|
||||
await expect(decksApi.deleteDeck(supabase, 'd1')).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMyDeckRating', () => {
|
||||
it('returns null when userId is null', async () => {
|
||||
expect(await decksApi.getMyDeckRating('d1', null)).toBe(null)
|
||||
expect(await decksApi.getMyDeckRating(supabase, 'd1', null)).toBe(null)
|
||||
})
|
||||
|
||||
it('returns rating and comment when present', async () => {
|
||||
nextResults.push({ data: { rating: 4, comment: 'Great!' }, error: null })
|
||||
const result = await decksApi.getMyDeckRating('d1', 'user1')
|
||||
const result = await decksApi.getMyDeckRating(supabase, 'd1', 'user1')
|
||||
expect(result).toEqual({ rating: 4, comment: 'Great!' })
|
||||
})
|
||||
|
||||
it('returns null when no rating', async () => {
|
||||
nextResults.push({ data: null, error: null })
|
||||
expect(await decksApi.getMyDeckRating('d1', 'user1')).toBe(null)
|
||||
expect(await decksApi.getMyDeckRating(supabase, 'd1', 'user1')).toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
describe('submitDeckRating', () => {
|
||||
it('clamps rating to 1-5 and trims comment', async () => {
|
||||
nextResults.push({ error: null })
|
||||
await decksApi.submitDeckRating('d1', 'user1', { rating: 10, comment: ' ok ' })
|
||||
await decksApi.submitDeckRating(supabase, 'd1', 'user1', { rating: 10, comment: ' ok ' })
|
||||
expect(nextResults.length).toBe(0)
|
||||
})
|
||||
|
||||
it('throws on error', async () => {
|
||||
nextResults.push({ error: new Error('Unique violation') })
|
||||
await expect(decksApi.submitDeckRating('d1', 'user1', { rating: 3 })).rejects.toThrow('Unique violation')
|
||||
await expect(decksApi.submitDeckRating(supabase, 'd1', 'user1', { rating: 3 })).rejects.toThrow('Unique violation')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDeckReviews', () => {
|
||||
it('returns empty array when no ratings', async () => {
|
||||
nextResults.push({ data: [], error: null })
|
||||
const result = await decksApi.getDeckReviews('d1')
|
||||
const result = await decksApi.getDeckReviews(supabase, 'd1')
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
@@ -176,7 +177,7 @@ describe('decks API', () => {
|
||||
{ data: [{ user_id: 'u1', rating: 5, comment: 'Nice', created_at: '2025-01-01' }], error: null },
|
||||
{ data: [{ id: 'u1', display_name: 'Alice', email: '[email protected]', avatar_url: null }], error: null }
|
||||
)
|
||||
const result = await decksApi.getDeckReviews('d1')
|
||||
const result = await decksApi.getDeckReviews(supabase, 'd1')
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toMatchObject({ rating: 5, comment: 'Nice', display_name: 'Alice', email: '[email protected]' })
|
||||
})
|
||||
@@ -185,13 +186,13 @@ describe('decks API', () => {
|
||||
describe('createDeck', () => {
|
||||
it('creates deck and returns id', async () => {
|
||||
nextResults.push({ data: { id: 'new-id' }, error: null })
|
||||
const id = await decksApi.createDeck('user1', { title: 'Title', description: 'Desc', config: {} })
|
||||
const id = await decksApi.createDeck(supabase, 'user1', { title: 'Title', description: 'Desc', config: {} })
|
||||
expect(id).toBe('new-id')
|
||||
})
|
||||
|
||||
it('throws when insert fails', async () => {
|
||||
nextResults.push({ data: null, error: new Error('Failed') })
|
||||
await expect(decksApi.createDeck('user1', { title: 'T', description: '', config: {} })).rejects.toThrow()
|
||||
await expect(decksApi.createDeck(supabase, 'user1', { title: 'T', description: '', config: {} })).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -202,7 +203,7 @@ describe('decks API', () => {
|
||||
{ error: null },
|
||||
{ error: null }
|
||||
)
|
||||
await decksApi.updateDeck('d1', { title: 'New', description: '', config: {}, questions: [] })
|
||||
await decksApi.updateDeck(supabase, 'd1', { title: 'New', description: '', config: {}, questions: [] })
|
||||
expect(nextResults.length).toBe(0)
|
||||
})
|
||||
|
||||
@@ -212,7 +213,7 @@ describe('decks API', () => {
|
||||
{ error: null },
|
||||
{ error: null }
|
||||
)
|
||||
await decksApi.updateDeck('d1', { title: 'T', description: '', config: {}, questions: [] })
|
||||
await decksApi.updateDeck(supabase, 'd1', { title: 'T', description: '', config: {}, questions: [] })
|
||||
expect(nextResults.length).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -223,7 +224,7 @@ describe('decks API', () => {
|
||||
{ data: { id: 's1', title: 'S', published: false, questions: [] }, error: null },
|
||||
{ data: [], error: null }
|
||||
)
|
||||
await expect(decksApi.copyDeckToUser('s1', 'user1')).rejects.toThrow('not available to copy')
|
||||
await expect(decksApi.copyDeckToUser(supabase, 's1', 'user1')).rejects.toThrow('not available to copy')
|
||||
})
|
||||
|
||||
it('creates copy and returns new deck id', async () => {
|
||||
@@ -232,7 +233,7 @@ describe('decks API', () => {
|
||||
{ data: [], error: null },
|
||||
{ data: { id: 'new-id' }, error: null }
|
||||
)
|
||||
const id = await decksApi.copyDeckToUser('s1', 'user1')
|
||||
const id = await decksApi.copyDeckToUser(supabase, 's1', 'user1')
|
||||
expect(id).toBe('new-id')
|
||||
})
|
||||
})
|
||||
@@ -240,7 +241,7 @@ describe('decks API', () => {
|
||||
describe('getSourceUpdatePreview', () => {
|
||||
it('throws when deck not found or not a copy', async () => {
|
||||
nextResults.push({ data: null, error: new Error('Not found') })
|
||||
await expect(decksApi.getSourceUpdatePreview('d1', 'user1')).rejects.toThrow('not found or not a copy')
|
||||
await expect(decksApi.getSourceUpdatePreview(supabase, 'd1', 'user1')).rejects.toThrow('not found or not a copy')
|
||||
})
|
||||
|
||||
it('returns source, copy and changes', async () => {
|
||||
@@ -251,7 +252,7 @@ describe('decks API', () => {
|
||||
{ data: sourceDeck, error: null },
|
||||
{ data: [{ prompt: 'Q' }], error: null }
|
||||
)
|
||||
const result = await decksApi.getSourceUpdatePreview('c1', 'user1')
|
||||
const result = await decksApi.getSourceUpdatePreview(supabase, 'c1', 'user1')
|
||||
expect(result.source).toBeDefined()
|
||||
expect(result.copy).toBeDefined()
|
||||
expect(result.changes).toEqual(expect.any(Array))
|
||||
@@ -261,7 +262,7 @@ describe('decks API', () => {
|
||||
describe('applySourceUpdate', () => {
|
||||
it('throws when deck not a copy', async () => {
|
||||
nextResults.push({ data: null, error: new Error('Not found') })
|
||||
await expect(decksApi.applySourceUpdate('d1', 'user1')).rejects.toThrow()
|
||||
await expect(decksApi.applySourceUpdate(supabase, 'd1', 'user1')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { supabase } from '../supabase.js';
|
||||
|
||||
/** Resolve email for login when user enters a username (display_name). Returns null if not found. */
|
||||
export async function getEmailForUsername(username) {
|
||||
export async function getEmailForUsername(client, username) {
|
||||
const trimmed = (username ?? '').trim();
|
||||
if (!trimmed) return null;
|
||||
const { data, error } = await supabase
|
||||
const { data, error } = await client
|
||||
.from('profiles')
|
||||
.select('email')
|
||||
.ilike('display_name', trimmed)
|
||||
@@ -13,8 +13,8 @@ export async function getEmailForUsername(username) {
|
||||
return data[0].email;
|
||||
}
|
||||
|
||||
export async function getProfile(userId) {
|
||||
const { data, error } = await supabase
|
||||
export async function getProfile(client, userId) {
|
||||
const { data, error } = await client
|
||||
.from('profiles')
|
||||
.select('id, display_name, email, avatar_url')
|
||||
.eq('id', userId)
|
||||
@@ -23,13 +23,13 @@ export async function getProfile(userId) {
|
||||
return data ?? null;
|
||||
}
|
||||
|
||||
export async function updateProfile(userId, { display_name, avatar_url }) {
|
||||
export async function updateProfile(client, userId, { display_name, avatar_url }) {
|
||||
const updates = {};
|
||||
if (display_name !== undefined) updates.display_name = display_name?.trim() || null;
|
||||
if (avatar_url !== undefined) updates.avatar_url = avatar_url || null;
|
||||
updates.updated_at = new Date().toISOString();
|
||||
|
||||
const { data, error } = await supabase
|
||||
const { data, error } = await client
|
||||
.from('profiles')
|
||||
.update(updates)
|
||||
.eq('id', userId)
|
||||
|
||||
+14
-13
@@ -1,4 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { supabase } from '../supabase.js'
|
||||
import * as profileApi from './profile.js'
|
||||
|
||||
const nextResults = []
|
||||
@@ -38,24 +39,24 @@ describe('profile API', () => {
|
||||
|
||||
describe('getEmailForUsername', () => {
|
||||
it('returns null for empty or whitespace username', async () => {
|
||||
expect(await profileApi.getEmailForUsername('')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(' ')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(null)).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, '')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, ' ')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, null)).toBe(null)
|
||||
})
|
||||
|
||||
it('returns email when profile found', async () => {
|
||||
nextResults.push({ data: [{ email: '[email protected]' }], error: null })
|
||||
const email = await profileApi.getEmailForUsername('johndoe')
|
||||
const email = await profileApi.getEmailForUsername(supabase, 'johndoe')
|
||||
expect(email).toBe('[email protected]')
|
||||
})
|
||||
|
||||
it('returns null when error or no data', async () => {
|
||||
nextResults.push({ data: [], error: null })
|
||||
expect(await profileApi.getEmailForUsername('x')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, 'x')).toBe(null)
|
||||
nextResults.push({ data: null, error: { message: 'err' } })
|
||||
expect(await profileApi.getEmailForUsername('y')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, 'y')).toBe(null)
|
||||
nextResults.push({ data: [{}], error: null })
|
||||
expect(await profileApi.getEmailForUsername('z')).toBe(null)
|
||||
expect(await profileApi.getEmailForUsername(supabase, 'z')).toBe(null)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,19 +64,19 @@ describe('profile API', () => {
|
||||
it('returns profile when found', async () => {
|
||||
const p = { id: 'u1', display_name: 'Alice', email: '[email protected]', avatar_url: null }
|
||||
nextResults.push({ data: p, error: null })
|
||||
const result = await profileApi.getProfile('u1')
|
||||
const result = await profileApi.getProfile(supabase, 'u1')
|
||||
expect(result).toEqual(p)
|
||||
})
|
||||
|
||||
it('returns null when not found (PGRST116)', async () => {
|
||||
nextResults.push({ data: null, error: { code: 'PGRST116' } })
|
||||
const result = await profileApi.getProfile('u1')
|
||||
const result = await profileApi.getProfile(supabase, 'u1')
|
||||
expect(result).toBe(null)
|
||||
})
|
||||
|
||||
it('throws when other error', async () => {
|
||||
nextResults.push({ data: null, error: new Error('Network error') })
|
||||
await expect(profileApi.getProfile('u1')).rejects.toThrow('Network error')
|
||||
await expect(profileApi.getProfile(supabase, 'u1')).rejects.toThrow('Network error')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -83,19 +84,19 @@ describe('profile API', () => {
|
||||
it('updates display_name and returns data', async () => {
|
||||
const updated = { id: 'u1', display_name: 'New Name', email: '[email protected]', avatar_url: null }
|
||||
nextResults.push({ data: updated, error: null })
|
||||
const result = await profileApi.updateProfile('u1', { display_name: 'New Name' })
|
||||
const result = await profileApi.updateProfile(supabase, 'u1', { display_name: 'New Name' })
|
||||
expect(result).toEqual(updated)
|
||||
})
|
||||
|
||||
it('trims display_name and allows avatar_url', async () => {
|
||||
nextResults.push({ data: { id: 'u1' }, error: null })
|
||||
await profileApi.updateProfile('u1', { display_name: ' Trim ', avatar_url: 'path/to/av.jpg' })
|
||||
await profileApi.updateProfile(supabase, 'u1', { display_name: ' Trim ', avatar_url: 'path/to/av.jpg' })
|
||||
expect(nextResults.length).toBe(0)
|
||||
})
|
||||
|
||||
it('throws on error', async () => {
|
||||
nextResults.push({ data: null, error: new Error('DB error') })
|
||||
await expect(profileApi.updateProfile('u1', { display_name: 'X' })).rejects.toThrow('DB error')
|
||||
await expect(profileApi.updateProfile(supabase, 'u1', { display_name: 'X' })).rejects.toThrow('DB error')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ function createAuthStore() {
|
||||
return false;
|
||||
}
|
||||
if (!email.includes('@')) {
|
||||
const resolved = await getEmailForUsername(email);
|
||||
const resolved = await getEmailForUsername(supabase, email);
|
||||
if (!resolved) {
|
||||
update((s) => ({ ...s, error: 'No account with that username.' }));
|
||||
return false;
|
||||
@@ -79,7 +79,7 @@ function createAuthStore() {
|
||||
update((s) => ({ ...s, error: null }));
|
||||
if (data?.user?.id && data?.session && (displayName || '').trim()) {
|
||||
try {
|
||||
await updateProfile(data.user.id, { display_name: (displayName || '').trim() });
|
||||
await updateProfile(supabase, data.user.id, { display_name: (displayName || '').trim() });
|
||||
} catch (_) {}
|
||||
}
|
||||
const needsConfirmation = data?.user && !data?.session;
|
||||
|
||||
@@ -67,7 +67,7 @@ describe('auth store', () => {
|
||||
mockGetEmailForUsername.mockResolvedValue('[email protected]')
|
||||
mockSignInWithPassword.mockResolvedValue({ error: null })
|
||||
const result = await auth.login('username', 'pass')
|
||||
expect(mockGetEmailForUsername).toHaveBeenCalledWith('username')
|
||||
expect(mockGetEmailForUsername).toHaveBeenCalledWith(expect.anything(), 'username')
|
||||
expect(mockSignInWithPassword).toHaveBeenCalledWith({
|
||||
email: '[email protected]',
|
||||
password: 'pass',
|
||||
@@ -112,7 +112,7 @@ describe('auth store', () => {
|
||||
mockSignUp.mockResolvedValue({ data: { user, session: {} }, error: null })
|
||||
mockUpdateProfile.mockResolvedValue(undefined)
|
||||
await auth.register('[email protected]', 'pass', 'Alice')
|
||||
expect(mockUpdateProfile).toHaveBeenCalledWith('u1', { display_name: 'Alice' })
|
||||
expect(mockUpdateProfile).toHaveBeenCalledWith(expect.anything(), 'u1', { display_name: 'Alice' })
|
||||
})
|
||||
|
||||
it('register with signUp error returns success false', async () => {
|
||||
|
||||
Reference in New Issue
Block a user