Spaces:
Running
Running
Download algospaced-ui/src/services/cardManagerService.ts from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/services/cardManagerService.ts
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/algospaced-ui/src/services/cardManagerService.ts
-
curl -L -o cardManagerService.ts https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/algospaced-ui/src/services/cardManagerService.ts
11.6 kB
| import { supabase } from '../firebaseClient'; | |
| import { getAllCatalogProblems, type CatalogProblem } from './catalogService'; | |
| import { batchActivateProblems } from './reviewService'; | |
| import type { ProblemSolution } from '../types/reviewTypes'; | |
| export interface ManagedCard { | |
| id: string; | |
| problem_number?: number; | |
| name: string; | |
| pattern: string; | |
| difficulty: 'Easy' | 'Medium' | 'Hard'; | |
| description?: string; | |
| reference_code?: string; | |
| starter_code?: string; | |
| optimal_time?: string; | |
| optimal_space?: string; | |
| how_to_solve?: string; | |
| examples?: Array<{ input?: string; output?: string; explanation?: string } | string>; | |
| constraints?: string[] | string; | |
| solutions?: ProblemSolution[]; | |
| leetcode_url?: string; | |
| // SRS Review details | |
| is_enrolled: boolean; | |
| is_custom: boolean; | |
| fsrs_state: number | null; // 0=New, 1=Learning, 2=Review, 3=Relearning, null if not enrolled | |
| fsrs_step?: number; | |
| fsrs_stability?: number; | |
| fsrs_difficulty?: number; | |
| fsrs_elapsed_days?: number; | |
| fsrs_scheduled_days?: number; | |
| fsrs_reps?: number; | |
| fsrs_lapses?: number; | |
| next_review: string | null; | |
| last_reviewed: string | null; | |
| times_correct: number; | |
| total_attempts: number; | |
| is_due: boolean; | |
| catalogProblem?: CatalogProblem; | |
| } | |
| interface RawExplorerProblem { | |
| id: string; | |
| name: string; | |
| problem_number?: number; | |
| pattern: string; | |
| difficulty: 'Easy' | 'Medium' | 'Hard'; | |
| description?: string | null; | |
| reference_code?: string | null; | |
| starter_code?: string | null; | |
| optimal_time?: string | null; | |
| optimal_space?: string | null; | |
| how_to_solve?: string | null; | |
| examples?: Array<{ input?: string; output?: string; explanation?: string } | string> | null; | |
| constraints?: string[] | string | null; | |
| solutions?: ProblemSolution[] | string | null; | |
| fsrs_state?: number | null; | |
| fsrs_step?: number | null; | |
| fsrs_stability?: number | null; | |
| fsrs_difficulty?: number | null; | |
| fsrs_elapsed_days?: number | null; | |
| fsrs_scheduled_days?: number | null; | |
| fsrs_reps?: number | null; | |
| fsrs_lapses?: number | null; | |
| next_review?: string | null; | |
| last_reviewed?: string | null; | |
| times_correct?: number | null; | |
| total_attempts?: number | null; | |
| } | |
| async function getAuthToken(): Promise<string> { | |
| try { | |
| const { data: { session } } = await supabase.auth.getSession(); | |
| return session ? session.access_token : 'sandbox'; | |
| } catch { | |
| return 'sandbox'; | |
| } | |
| } | |
| /** | |
| * Normalizes title for consistent cross-database matching. | |
| */ | |
| function normalizeName(name: string): string { | |
| return name.toLowerCase().replace(/\s*-\s*method.*$/i, '').replace(/[^a-z0-9]+/g, ''); | |
| } | |
| function parseJsonSafe<T>(val: unknown): T | undefined { | |
| if (typeof val === 'string') { | |
| try { | |
| return JSON.parse(val) as T; | |
| } catch { | |
| return undefined; | |
| } | |
| } | |
| return (val as T) ?? undefined; | |
| } | |
| /** | |
| * Loads all cards (catalog + custom problems) merged with user SRS review statistics. | |
| */ | |
| export async function fetchManagedCards(): Promise<ManagedCard[]> { | |
| const token = await getAuthToken(); | |
| const catalog = getAllCatalogProblems(); | |
| let explorerProblems: RawExplorerProblem[] = []; | |
| try { | |
| const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems`, { | |
| headers: { | |
| 'Authorization': `Bearer ${token}` | |
| } | |
| }); | |
| if (res.ok) { | |
| explorerProblems = await res.json(); | |
| } | |
| } catch { | |
| // Graceful offline fallback | |
| explorerProblems = []; | |
| } | |
| // Maps for efficient matching | |
| const explorerByNum = new Map<number, RawExplorerProblem>(); | |
| const explorerByName = new Map<string, RawExplorerProblem>(); | |
| const matchedExplorerIds = new Set<string>(); | |
| for (const p of explorerProblems) { | |
| if (p.problem_number !== undefined && p.problem_number !== null) { | |
| explorerByNum.set(p.problem_number, p); | |
| } | |
| explorerByName.set(normalizeName(p.name), p); | |
| } | |
| const now = new Date(); | |
| const managedCards: ManagedCard[] = []; | |
| // 1. Process curated catalog problems | |
| for (const cat of catalog) { | |
| const matched = explorerByNum.get(cat.problem_number) || explorerByName.get(normalizeName(cat.name)); | |
| if (matched) { | |
| matchedExplorerIds.add(matched.id); | |
| const isEnrolled = matched.next_review !== null && matched.next_review !== undefined || (matched.fsrs_state !== null && matched.fsrs_state !== undefined); | |
| const nextReviewDate = matched.next_review ? new Date(matched.next_review) : null; | |
| const isDue = isEnrolled && nextReviewDate !== null ? nextReviewDate <= now : false; | |
| const parsedSolutions = parseJsonSafe<ProblemSolution[]>(matched.solutions); | |
| const parsedExamples = parseJsonSafe<Array<{ input?: string; output?: string; explanation?: string } | string>>(matched.examples); | |
| const parsedConstraints = parseJsonSafe<string[] | string>(matched.constraints); | |
| managedCards.push({ | |
| id: matched.id, | |
| problem_number: cat.problem_number, | |
| name: cat.name, | |
| pattern: cat.pattern, | |
| difficulty: cat.difficulty, | |
| description: matched.description || cat.description, | |
| reference_code: matched.reference_code || cat.reference_solution, | |
| starter_code: matched.starter_code || cat.starter_code, | |
| optimal_time: matched.optimal_time || cat.time_complexity, | |
| optimal_space: matched.optimal_space || cat.space_complexity, | |
| how_to_solve: matched.how_to_solve || '', | |
| examples: (parsedExamples && (Array.isArray(parsedExamples) ? parsedExamples.length > 0 : true)) | |
| ? parsedExamples | |
| : cat.examples, | |
| constraints: (parsedConstraints && (Array.isArray(parsedConstraints) ? parsedConstraints.length > 0 : true)) | |
| ? parsedConstraints | |
| : cat.constraints, | |
| solutions: parsedSolutions, | |
| leetcode_url: cat.leetcode_url, | |
| is_enrolled: isEnrolled, | |
| is_custom: false, | |
| fsrs_state: matched.fsrs_state ?? (isEnrolled ? 0 : null), | |
| fsrs_step: matched.fsrs_step ?? 0, | |
| fsrs_stability: matched.fsrs_stability ?? 0.0, | |
| fsrs_difficulty: matched.fsrs_difficulty ?? 0.0, | |
| fsrs_elapsed_days: matched.fsrs_elapsed_days ?? 0, | |
| fsrs_scheduled_days: matched.fsrs_scheduled_days ?? 0, | |
| fsrs_reps: matched.fsrs_reps ?? 0, | |
| fsrs_lapses: matched.fsrs_lapses ?? 0, | |
| next_review: matched.next_review ?? null, | |
| last_reviewed: matched.last_reviewed ?? null, | |
| times_correct: matched.times_correct ?? 0, | |
| total_attempts: matched.total_attempts ?? 0, | |
| is_due: isDue, | |
| catalogProblem: cat | |
| }); | |
| } else { | |
| // Unenrolled catalog card | |
| managedCards.push({ | |
| id: cat.id, | |
| problem_number: cat.problem_number, | |
| name: cat.name, | |
| pattern: cat.pattern, | |
| difficulty: cat.difficulty, | |
| description: cat.description, | |
| reference_code: cat.reference_solution, | |
| starter_code: cat.starter_code, | |
| optimal_time: cat.time_complexity, | |
| optimal_space: cat.space_complexity, | |
| how_to_solve: '', | |
| examples: cat.examples, | |
| constraints: cat.constraints, | |
| leetcode_url: cat.leetcode_url, | |
| is_enrolled: false, | |
| is_custom: false, | |
| fsrs_state: null, | |
| fsrs_step: 0, | |
| fsrs_stability: 0.0, | |
| fsrs_difficulty: 0.0, | |
| fsrs_elapsed_days: 0, | |
| fsrs_scheduled_days: 0, | |
| fsrs_reps: 0, | |
| fsrs_lapses: 0, | |
| next_review: null, | |
| last_reviewed: null, | |
| times_correct: 0, | |
| total_attempts: 0, | |
| is_due: false, | |
| catalogProblem: cat | |
| }); | |
| } | |
| } | |
| // 2. Add custom problems created by user not in curated catalog | |
| for (const exp of explorerProblems) { | |
| if (!matchedExplorerIds.has(exp.id)) { | |
| const isEnrolled = exp.next_review !== null && exp.next_review !== undefined || (exp.fsrs_state !== null && exp.fsrs_state !== undefined); | |
| const nextReviewDate = exp.next_review ? new Date(exp.next_review) : null; | |
| const isDue = isEnrolled && nextReviewDate !== null ? nextReviewDate <= now : false; | |
| const parsedSolutions = parseJsonSafe<ProblemSolution[]>(exp.solutions); | |
| const parsedExamples = parseJsonSafe<Array<{ input?: string; output?: string; explanation?: string } | string>>(exp.examples) || []; | |
| const parsedConstraints = parseJsonSafe<string[] | string>(exp.constraints) || []; | |
| managedCards.push({ | |
| id: exp.id, | |
| problem_number: exp.problem_number, | |
| name: exp.name, | |
| pattern: exp.pattern || 'General', | |
| difficulty: exp.difficulty || 'Medium', | |
| description: exp.description || '', | |
| reference_code: exp.reference_code || '', | |
| starter_code: exp.starter_code || '', | |
| optimal_time: exp.optimal_time || 'O(N)', | |
| optimal_space: exp.optimal_space || 'O(1)', | |
| how_to_solve: exp.how_to_solve || '', | |
| examples: parsedExamples, | |
| constraints: parsedConstraints, | |
| solutions: parsedSolutions, | |
| is_enrolled: isEnrolled, | |
| is_custom: true, | |
| fsrs_state: exp.fsrs_state ?? (isEnrolled ? 0 : null), | |
| fsrs_step: exp.fsrs_step ?? 0, | |
| fsrs_stability: exp.fsrs_stability ?? 0.0, | |
| fsrs_difficulty: exp.fsrs_difficulty ?? 0.0, | |
| fsrs_elapsed_days: exp.fsrs_elapsed_days ?? 0, | |
| fsrs_scheduled_days: exp.fsrs_scheduled_days ?? 0, | |
| fsrs_reps: exp.fsrs_reps ?? 0, | |
| fsrs_lapses: exp.fsrs_lapses ?? 0, | |
| next_review: exp.next_review ?? null, | |
| last_reviewed: exp.last_reviewed ?? null, | |
| times_correct: exp.times_correct ?? 0, | |
| total_attempts: exp.total_attempts ?? 0, | |
| is_due: isDue | |
| }); | |
| } | |
| } | |
| return managedCards; | |
| } | |
| /** | |
| * Resets SRS review progress for one or more cards back to initial FSRS state due immediately. | |
| */ | |
| export async function resetCardReviews(problemIds: string[]): Promise<boolean> { | |
| if (problemIds.length === 0) return true; | |
| const token = await getAuthToken(); | |
| const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/reviews/reset`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${token}` | |
| }, | |
| body: JSON.stringify({ problem_ids: problemIds }) | |
| }); | |
| if (!res.ok) { | |
| const err = await res.json().catch(() => ({ detail: 'Failed to reset reviews' })); | |
| throw new Error(err.detail || 'Failed to reset reviews'); | |
| } | |
| return true; | |
| } | |
| /** | |
| * Deletes a custom problem card from the database. | |
| */ | |
| export async function deleteCustomCard(problemId: string): Promise<boolean> { | |
| const token = await getAuthToken(); | |
| const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/explorer/problems/${problemId}`, { | |
| method: 'DELETE', | |
| headers: { | |
| 'Authorization': `Bearer ${token}` | |
| } | |
| }); | |
| if (!res.ok) { | |
| const err = await res.json().catch(() => ({ detail: 'Failed to delete problem' })); | |
| throw new Error(err.detail || 'Failed to delete problem'); | |
| } | |
| return true; | |
| } | |
| /** | |
| * Batch deletes multiple custom cards by ID. | |
| */ | |
| export async function deleteCustomCards(problemIds: string[]): Promise<number> { | |
| let count = 0; | |
| for (const id of problemIds) { | |
| try { | |
| await deleteCustomCard(id); | |
| count++; | |
| } catch { | |
| // Continue deleting remaining cards | |
| } | |
| } | |
| return count; | |
| } | |
| /** | |
| * Enrolls catalog problems into the SRS review queue. | |
| */ | |
| export async function enrollCatalogCards(catalogProblems: CatalogProblem[]): Promise<number> { | |
| if (catalogProblems.length === 0) return 0; | |
| const result = await batchActivateProblems(catalogProblems); | |
| return result.enrolled_count; | |
| } | |