feat: implement knowledge testing system with leaderboard, quiz generation, and PocketBase integration

This commit is contained in:
RaymondVerhoef
2026-05-14 16:53:10 +02:00
parent 42d7209773
commit 74ba5d3dc0
15 changed files with 590 additions and 512 deletions

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
import { Trash2, Edit2, Save, X, RefreshCw, AlertCircle, Plus, Link as LinkIcon } from 'lucide-react';
import { storage } from '../../lib/storage';
import * as db from '../../lib/db';
import { anthropicApi } from '../../lib/api';
import Button from '../ui/Button';
@@ -16,13 +16,12 @@ const KnowledgeGraph = () => {
const [analyzeError, setAnalyzeError] = useState(null);
const [newRelData, setNewRelData] = useState({ target: '', type: 'related_to' });
// Load data into state so it can update
const [topics, setTopics] = useState([]);
const [relations, setRelations] = useState([]);
useEffect(() => {
setTopics(storage.get('kb:topics', []));
setRelations(storage.get('kb:relations', []));
db.getTopics().then(setTopics);
db.getRelations().then(setRelations);
}, []);
useEffect(() => {
@@ -58,9 +57,7 @@ const KnowledgeGraph = () => {
const zoom = d3.zoom()
.scaleExtent([0.1, 4])
.on('zoom', (event) => {
g.attr('transform', event.transform);
});
.on('zoom', (event) => { g.attr('transform', event.transform); });
svg.call(zoom);
@@ -141,65 +138,62 @@ const KnowledgeGraph = () => {
setIsEditing(true);
};
const saveEdit = () => {
const updatedTopics = topics.map(t =>
t.id === selectedNode.id ? { ...t, ...editData } : t
);
storage.set('kb:topics', updatedTopics);
setTopics(updatedTopics);
const saveEdit = async () => {
await db.upsertTopic({ ...selectedNode, ...editData });
const updated = topics.map(t => t.id === selectedNode.id ? { ...t, ...editData } : t);
setTopics(updated);
setSelectedNode({ ...selectedNode, ...editData });
setIsEditing(false);
};
const deleteNode = () => {
const deleteNode = async () => {
if (confirm(`Are you sure you want to delete "${selectedNode.label}"? This will also remove any relations connected to it.`)) {
const updatedTopics = topics.filter(t => t.id !== selectedNode.id);
const updatedRelations = relations.filter(r => r.source !== selectedNode.id && r.target !== selectedNode.id);
storage.set('kb:topics', updatedTopics);
storage.set('kb:relations', updatedRelations);
await db.saveTopics(updatedTopics);
await db.saveRelations(updatedRelations);
await db.deleteContent(selectedNode.id);
await db.setQuizBank(selectedNode.id, []);
setTopics(updatedTopics);
setRelations(updatedRelations);
setSelectedNode(null);
setIsEditing(false);
// Clear associated content to keep it clean
storage.remove(`kb:content:${selectedNode.id}`);
storage.remove(`quiz:bank:${selectedNode.id}`);
}
};
const addRelation = () => {
const addRelation = async () => {
if (!newRelData.target) return;
const rawRelations = storage.get('kb:relations', []);
const isDup = rawRelations.some(r => r.source === selectedNode.id && r.target === newRelData.target && r.type === newRelData.type);
const isDup = relations.some(r => (r.source.id || r.source) === selectedNode.id && (r.target.id || r.target) === newRelData.target && r.type === newRelData.type);
if (isDup) return;
const updated = [...rawRelations, { source: selectedNode.id, target: newRelData.target, type: newRelData.type }];
storage.set('kb:relations', updated);
setRelations(updated);
const newRel = { source: selectedNode.id, target: newRelData.target, type: newRelData.type };
await db.addRelation(newRel);
setRelations([...relations, newRel]);
setNewRelData({ target: '', type: 'related_to' });
};
const removeRelation = (sourceId, targetId, type) => {
const rawRelations = storage.get('kb:relations', []);
const updated = rawRelations.filter(r => !(r.source === sourceId && r.target === targetId && r.type === type));
storage.set('kb:relations', updated);
setRelations(updated);
const removeRelation = async (sourceId, targetId, type) => {
await db.removeRelation(sourceId, targetId, type);
setRelations(relations.filter(r => !(
(r.source.id || r.source) === sourceId &&
(r.target.id || r.target) === targetId &&
r.type === type
)));
};
const analyzeGraph = async () => {
if (!confirm('This will send the entire graph to the AI to evaluate content, merge duplicates, and create new logical relations. This may take a moment. Proceed?')) return;
setIsAnalyzing(true);
setAnalyzeError(null);
try {
const currentTopics = storage.get('kb:topics', []);
const currentRelations = storage.get('kb:relations', []);
const systemPrompt = `You are a strict Data Quality AI maintaining a Knowledge Graph.
const currentTopics = await db.getTopics();
const currentRelations = await db.getRelations();
const systemPrompt = `You are a strict Data Quality AI maintaining a Knowledge Graph.
Your goal is to evaluate the provided topics and relations, identify duplicates to merge, useless nodes to delete, and new logical relations to add.
Rules:
@@ -221,17 +215,15 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
const responseText = await anthropicApi.generateContent(systemPrompt, userPrompt);
const jsonMatch = responseText.match(/\{[\s\S]*\}/);
if (!jsonMatch) throw new Error('AI returned invalid format.');
const actions = JSON.parse(jsonMatch[0]);
let updatedTopics = [...currentTopics];
let updatedRelations = [...currentRelations];
// Process Merges
if (actions.merges && Array.isArray(actions.merges)) {
for (const merge of actions.merges) {
updatedTopics = updatedTopics.filter(t => t.id !== merge.deleteId);
// Redirect relations
updatedRelations = updatedRelations.map(r => {
if (r.source === merge.deleteId) return { ...r, source: merge.keepId };
if (r.target === merge.deleteId) return { ...r, target: merge.keepId };
@@ -240,33 +232,27 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
}
}
// Process Deletions
if (actions.deletions && Array.isArray(actions.deletions)) {
updatedTopics = updatedTopics.filter(t => !actions.deletions.includes(t.id));
updatedRelations = updatedRelations.filter(r => !actions.deletions.includes(r.source) && !actions.deletions.includes(r.target));
}
// Process New Relations
if (actions.newRelations && Array.isArray(actions.newRelations)) {
for (const newRel of actions.newRelations) {
// Prevent exact duplicates
const isDup = updatedRelations.some(r => r.source === newRel.source && r.target === newRel.target && r.type === newRel.type);
if (!isDup) {
updatedRelations.push(newRel);
}
if (!isDup) updatedRelations.push(newRel);
}
}
// Final cleanup to remove self-referencing relations that might occur after merges
updatedRelations = updatedRelations.filter(r => r.source !== r.target);
storage.set('kb:topics', updatedTopics);
storage.set('kb:relations', updatedRelations);
await db.saveTopics(updatedTopics);
await db.saveRelations(updatedRelations);
setTopics(updatedTopics);
setRelations(updatedRelations);
setSelectedNode(null);
} catch (e) {
setAnalyzeError(e.message || 'Analysis failed. Please try again.');
} finally {
@@ -286,13 +272,11 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
)}
</div>
{/* Node Info Panel */}
<div className="w-full md:w-80 bg-paper p-6 overflow-y-auto border-t md:border-t-0 border-bg-warm flex flex-col">
{/* Global Action */}
<div className="mb-6 pb-4 border-b border-bg-warm">
<Button
onClick={analyzeGraph}
disabled={isAnalyzing || topics.length === 0}
<Button
onClick={analyzeGraph}
disabled={isAnalyzing || topics.length === 0}
className="w-full flex justify-center items-center gap-2"
>
<RefreshCw size={16} className={isAnalyzing ? "animate-spin" : ""} />
@@ -319,23 +303,23 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
</div>
)}
</div>
{selectedNode ? (
isEditing ? (
<div className="space-y-4 flex-1">
<div>
<label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">Label</label>
<input
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
value={editData.label}
onChange={e => setEditData({...editData, label: e.target.value})}
<input
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
value={editData.label}
onChange={e => setEditData({...editData, label: e.target.value})}
/>
</div>
<div>
<label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">Type</label>
<select
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
value={editData.type}
<select
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg"
value={editData.type}
onChange={e => setEditData({...editData, type: e.target.value})}
>
<option value="concept">Concept</option>
@@ -345,10 +329,10 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
</div>
<div>
<label className="text-xs text-fg-muted uppercase tracking-wider mb-1 block">Description</label>
<textarea
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg min-h-[100px]"
value={editData.description}
onChange={e => setEditData({...editData, description: e.target.value})}
<textarea
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-3 py-1.5 text-sm bg-bg min-h-[100px]"
value={editData.description}
onChange={e => setEditData({...editData, description: e.target.value})}
/>
</div>
<div className="flex gap-2 pt-2">
@@ -364,9 +348,7 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
</div>
<div>
<p className="text-xs text-fg-muted uppercase tracking-wider mb-1">Type</p>
<span className="inline-block px-2 py-1 bg-bg-warm rounded-[var(--r-pill)] text-xs font-mono">
{selectedNode.type}
</span>
<span className="inline-block px-2 py-1 bg-bg-warm rounded-[var(--r-pill)] text-xs font-mono">{selectedNode.type}</span>
</div>
<div>
<p className="text-xs text-fg-muted uppercase tracking-wider mb-1">Description</p>
@@ -376,11 +358,10 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
<p className="text-xs text-fg-muted uppercase tracking-wider mb-1">ID</p>
<p className="text-xs font-mono text-fg-muted break-all">{selectedNode.id}</p>
</div>
<div className="pt-4 border-t border-bg-warm">
<p className="text-xs text-fg-muted uppercase tracking-wider mb-3">Relations</p>
{/* Existing Relations where selectedNode is source */}
<div className="space-y-2 mb-4">
{relations.filter(r => (r.source.id || r.source) === selectedNode.id).map((rel, idx) => {
const targetId = rel.target.id || rel.target;
@@ -390,7 +371,7 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
<div className="text-xs">
<span className="font-mono text-teal">{rel.type}</span> &rarr; {targetTopic ? targetTopic.label : targetId}
</div>
<button
<button
onClick={() => removeRelation(selectedNode.id, targetId, rel.type)}
className="text-fg-muted hover:text-red-500 p-1"
title="Remove Relation"
@@ -402,10 +383,9 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
})}
</div>
{/* Add New Relation */}
<div className="bg-bg rounded-[var(--r-sm)] p-3 border border-bg-warm space-y-2">
<p className="text-xs font-medium flex items-center gap-1"><LinkIcon size={12}/> Add Relation</p>
<select
<select
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-2 py-1 text-xs bg-paper"
value={newRelData.type}
onChange={e => setNewRelData({...newRelData, type: e.target.value})}
@@ -415,7 +395,7 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
<option value="part_of">part_of</option>
<option value="executed_by">executed_by</option>
</select>
<select
<select
className="w-full border border-bg-warm rounded-[var(--r-sm)] px-2 py-1 text-xs bg-paper"
value={newRelData.target}
onChange={e => setNewRelData({...newRelData, target: e.target.value})}
@@ -425,8 +405,8 @@ Analyze this graph and return ONLY the optimized JSON object with this EXACT str
<option key={t.id} value={t.id}>{t.label}</option>
))}
</select>
<Button
onClick={addRelation}
<Button
onClick={addRelation}
disabled={!newRelData.target}
className="w-full py-1 text-xs mt-1"
>

View File

@@ -4,7 +4,8 @@ import Card from '../ui/Card';
import Button from '../ui/Button';
import Input from '../ui/Input';
import Tag from '../ui/Tag';
import { storage } from '../../lib/storage';
import * as db from '../../lib/db';
import { pb } from '../../lib/pb';
import { useApp } from '../../store/AppContext';
const TeamManager = () => {
@@ -12,44 +13,32 @@ const TeamManager = () => {
const [users, setUsers] = useState([]);
const [isEditing, setIsEditing] = useState(false);
const [editingId, setEditingId] = useState(null);
const [formData, setFormData] = useState({ name: '', role: 'user', pin: '' });
const [message, setMessage] = useState('');
const loadUsers = () => {
setUsers(storage.get('users:registry', []));
const loadUsers = async () => {
const members = await db.getTeamMembers();
setUsers(members);
};
useEffect(() => { loadUsers(); }, []);
const handleSave = (e) => {
const handleSave = async (e) => {
e.preventDefault();
if (!formData.name || !formData.pin) return;
let updatedUsers = [...users];
if (editingId) {
updatedUsers = updatedUsers.map(u => u.id === editingId ? { ...u, ...formData } : u);
await db.updateTeamMember(editingId, { name: formData.name, role: formData.role, pin: formData.pin });
setMessage('User updated successfully.');
} else {
const newUser = {
id: `u_${Date.now()}`,
name: formData.name,
role: formData.role,
pin: formData.pin,
registeredAt: new Date().toISOString()
};
updatedUsers.push(newUser);
await db.addTeamMember({ name: formData.name, role: formData.role, pin: formData.pin });
setMessage('User added successfully.');
}
storage.set('users:registry', updatedUsers);
setUsers(updatedUsers);
await loadUsers();
setFormData({ name: '', role: 'user', pin: '' });
setIsEditing(false);
setEditingId(null);
// In a real app we'd trigger a global state update, but here the user has to refresh or re-login if they edit themselves.
setTimeout(() => setMessage(''), 3000);
};
@@ -59,20 +48,21 @@ const TeamManager = () => {
setEditingId(user.id);
};
const handleDelete = (id) => {
const handleDelete = async (id) => {
if (id === state.currentUser?.id) {
alert("You cannot delete yourself.");
return;
}
if (confirm("Are you sure you want to delete this user?")) {
const updated = users.filter(u => u.id !== id);
storage.set('users:registry', updated);
setUsers(updated);
// Also remove them from leaderboard
const lb = storage.get('leaderboard:current', []);
storage.set('leaderboard:current', lb.filter(e => e.userId !== id));
await db.deleteTeamMember(id);
// Also remove from leaderboard
try {
const entry = await pb.collection('leaderboard').getFirstListItem(`user_id="${id}"`);
await pb.collection('leaderboard').delete(entry.id);
} catch { /* no leaderboard entry, nothing to do */ }
await loadUsers();
setMessage('User deleted.');
setTimeout(() => setMessage(''), 3000);
}
@@ -92,27 +82,26 @@ const TeamManager = () => {
</div>
)}
{/* Form */}
<Card className="border border-bg-warm">
<h2 className="text-xl font-bold flex items-center gap-2 mb-4">
{isEditing ? <Edit2 size={20} className="text-teal" /> : <UserPlus size={20} className="text-teal" />}
{isEditing ? 'Edit Team Member' : 'Add New Team Member'}
</h2>
<form onSubmit={handleSave} className="flex flex-col sm:flex-row gap-4 items-end">
<div className="flex-1 w-full">
<Input
label="Full Name"
placeholder="e.g. Jane Doe"
value={formData.name}
onChange={e => setFormData({...formData, name: e.target.value})}
required
<Input
label="Full Name"
placeholder="e.g. Jane Doe"
value={formData.name}
onChange={e => setFormData({...formData, name: e.target.value})}
required
/>
</div>
<div className="flex-1 w-full">
<label className="block text-sm font-medium mb-1.5 text-fg">Role</label>
<select
value={formData.role}
<select
value={formData.role}
onChange={e => setFormData({...formData, role: e.target.value})}
className="w-full h-11 px-3 rounded-[var(--r-sm)] border border-bg-warm bg-paper text-sm focus:outline-none focus:ring-2 focus:ring-teal/30 focus:border-teal"
>
@@ -121,13 +110,13 @@ const TeamManager = () => {
</select>
</div>
<div className="flex-1 w-full">
<Input
label="Login PIN"
type="text"
placeholder="e.g. 1234"
value={formData.pin}
onChange={e => setFormData({...formData, pin: e.target.value})}
required
<Input
label="Login PIN"
type="text"
placeholder="e.g. 1234"
value={formData.pin}
onChange={e => setFormData({...formData, pin: e.target.value})}
required
/>
</div>
<div className="flex gap-2 w-full sm:w-auto">
@@ -143,7 +132,6 @@ const TeamManager = () => {
</form>
</Card>
{/* List */}
<Card className="p-0 border border-bg-warm overflow-hidden">
<div className="divide-y divide-bg-warm">
{users.map(user => (
@@ -160,14 +148,14 @@ const TeamManager = () => {
<p className="text-sm text-fg-muted">PIN: {user.pin}</p>
</div>
</div>
<div className="flex items-center gap-3">
<Tag variant={user.role === 'admin' ? 'dark' : 'default'} className="hidden sm:inline-flex">{user.role}</Tag>
<button onClick={() => handleEdit(user)} className="p-2 text-fg-muted hover:text-teal transition-colors">
<Edit2 size={16} />
</button>
<button
onClick={() => handleDelete(user.id)}
<button
onClick={() => handleDelete(user.id)}
disabled={user.id === state.currentUser?.id}
className="p-2 text-fg-muted hover:text-red-500 disabled:opacity-30 transition-colors"
>

245
src/lib/db.js Normal file
View File

@@ -0,0 +1,245 @@
import { pb } from './pb';
// ── Topics ──────────────────────────────────────────────────────────────────
export async function getTopics() {
return pb.collection('topics').getFullList({ sort: 'created' });
}
export async function saveTopics(topics) {
const existing = await pb.collection('topics').getFullList({ fields: 'id' });
await Promise.all(existing.map(r => pb.collection('topics').delete(r.id)));
return Promise.all(topics.map(t => pb.collection('topics').create({
id: t.id,
label: t.label,
type: t.type,
description: t.description,
})));
}
export async function upsertTopic(topic) {
try {
await pb.collection('topics').getOne(topic.id);
return pb.collection('topics').update(topic.id, topic);
} catch {
return pb.collection('topics').create({ id: topic.id, ...topic });
}
}
// ── Relations ────────────────────────────────────────────────────────────────
export async function getRelations() {
return pb.collection('relations').getFullList();
}
export async function saveRelations(relations) {
const existing = await pb.collection('relations').getFullList({ fields: 'id' });
await Promise.all(existing.map(r => pb.collection('relations').delete(r.id)));
return Promise.all(relations.map(r => pb.collection('relations').create(r)));
}
export async function addRelation(relation) {
return pb.collection('relations').create(relation);
}
export async function removeRelation(source, target, type) {
const records = await pb.collection('relations').getFullList({
filter: `source="${source}" && target="${target}" && type="${type}"`,
});
return Promise.all(records.map(r => pb.collection('relations').delete(r.id)));
}
// ── Content ──────────────────────────────────────────────────────────────────
export async function getContent(topicId) {
try {
const r = await pb.collection('content').getFirstListItem(`topic_id="${topicId}"`);
return r.data;
} catch { return null; }
}
export async function setContent(topicId, data) {
try {
const r = await pb.collection('content').getFirstListItem(`topic_id="${topicId}"`);
return pb.collection('content').update(r.id, { data });
} catch {
return pb.collection('content').create({ topic_id: topicId, data });
}
}
export async function deleteContent(topicId) {
try {
const r = await pb.collection('content').getFirstListItem(`topic_id="${topicId}"`);
return pb.collection('content').delete(r.id);
} catch { /* no record, nothing to do */ }
}
// ── Quiz Banks ───────────────────────────────────────────────────────────────
export async function getQuizBank(topicId) {
try {
const r = await pb.collection('quiz_banks').getFirstListItem(`topic_id="${topicId}"`);
return r.questions || [];
} catch { return []; }
}
export async function setQuizBank(topicId, questions) {
try {
const r = await pb.collection('quiz_banks').getFirstListItem(`topic_id="${topicId}"`);
return pb.collection('quiz_banks').update(r.id, { questions });
} catch {
return pb.collection('quiz_banks').create({ topic_id: topicId, questions });
}
}
export async function deleteQuestionFromBank(topicId, questionId) {
const questions = await getQuizBank(topicId);
return setQuizBank(topicId, questions.filter(q => q.id !== questionId));
}
// ── Sources ──────────────────────────────────────────────────────────────────
export async function getSources() {
return pb.collection('sources').getFullList({ sort: '-created' });
}
export async function addSource(source) {
return pb.collection('sources').create(source);
}
export async function updateSourceStatus(id, status, error = '') {
return pb.collection('sources').update(id, { status, error });
}
export async function deleteSource(id) {
return pb.collection('sources').delete(id);
}
// ── Team Members ─────────────────────────────────────────────────────────────
export async function getTeamMembers() {
return pb.collection('team_members').getFullList({ sort: 'created' });
}
export async function addTeamMember(member) {
return pb.collection('team_members').create(member);
}
export async function updateTeamMember(id, data) {
return pb.collection('team_members').update(id, data);
}
export async function deleteTeamMember(id) {
return pb.collection('team_members').delete(id);
}
// ── Quiz Results ─────────────────────────────────────────────────────────────
export async function getQuizResult(userId, weekNumber) {
try {
return await pb.collection('quiz_results').getFirstListItem(
`user_id="${userId}" && week_number=${weekNumber}`
);
} catch { return null; }
}
export async function saveQuizResult(userId, weekNumber, result) {
return pb.collection('quiz_results').create({
user_id: userId,
week_number: weekNumber,
score: result.score,
total: result.total,
percentage: result.percentage,
time_used: result.timeUsed,
completed_at: result.completedAt,
breakdown: result.breakdown,
points_earned: result.pointsEarned,
});
}
// ── Quiz Cache ────────────────────────────────────────────────────────────────
export async function getCachedQuiz(userId, weekNumber) {
try {
return await pb.collection('quiz_cache').getFirstListItem(
`user_id="${userId}" && week_number=${weekNumber}`
);
} catch { return null; }
}
export async function setCachedQuiz(userId, weekNumber, quiz) {
try {
const r = await pb.collection('quiz_cache').getFirstListItem(
`user_id="${userId}" && week_number=${weekNumber}`
);
return pb.collection('quiz_cache').update(r.id, { questions: quiz.questions, meta: quiz.meta });
} catch {
return pb.collection('quiz_cache').create({
user_id: userId, week_number: weekNumber, questions: quiz.questions, meta: quiz.meta,
});
}
}
// ── Learn Progress ────────────────────────────────────────────────────────────
export async function getLearnDone(userId, weekNumber) {
try {
const r = await pb.collection('learn_progress').getFirstListItem(
`user_id="${userId}" && week_number=${weekNumber}`
);
return r.done;
} catch { return false; }
}
export async function setLearnDone(userId, weekNumber) {
try {
const r = await pb.collection('learn_progress').getFirstListItem(
`user_id="${userId}" && week_number=${weekNumber}`
);
return pb.collection('learn_progress').update(r.id, { done: true });
} catch {
return pb.collection('learn_progress').create({ user_id: userId, week_number: weekNumber, done: true });
}
}
// ── Leaderboard ───────────────────────────────────────────────────────────────
export async function getLeaderboard() {
return pb.collection('leaderboard').getFullList({ sort: '-points' });
}
export async function upsertLeaderboardEntry(userId, name, pointsDelta, testsCompletedDelta = 0) {
try {
const r = await pb.collection('leaderboard').getFirstListItem(`user_id="${userId}"`);
return pb.collection('leaderboard').update(r.id, {
points: (r.points || 0) + pointsDelta,
tests_completed: (r.tests_completed || 0) + testsCompletedDelta,
});
} catch {
return pb.collection('leaderboard').create({
user_id: userId,
name,
points: pointsDelta,
tests_completed: testsCompletedDelta,
learnings_completed: 0,
});
}
}
// ── Settings ──────────────────────────────────────────────────────────────────
export async function getSetting(key, defaultValue = null) {
try {
const r = await pb.collection('settings').getFirstListItem(`key="${key}"`);
return r.value ?? defaultValue;
} catch { return defaultValue; }
}
export async function setSetting(key, value) {
try {
const r = await pb.collection('settings').getFirstListItem(`key="${key}"`);
return pb.collection('settings').update(r.id, { value: String(value) });
} catch {
return pb.collection('settings').create({ key, value: String(value) });
}
}

View File

@@ -1,5 +1,5 @@
import { anthropicApi } from './api';
import { storage } from './storage';
import * as db from './db';
const SYSTEM_PROMPT = `You are an AI knowledge extractor for Respellion, an IT company built on radical transparency.
You receive a source text. Your task is to extract core concepts, roles, and processes, and return them as a structured JSON Knowledge Graph.
@@ -25,32 +25,15 @@ ALWAYS return a valid JSON object in the following format:
}
Return JSON only. No markdown blocks or other text.`;
/**
* Voert tekst door de Anthropic API en slaat de resulterende topics op.
* @param {string} textContent De te analyseren tekst.
* @param {string} sourceName Naam van de bron (voor tracking).
*/
export async function processSourceText(textContent, sourceName) {
// 1. Sla de bron eerst op als "processing"
const sourceId = `src_${Date.now()}`;
const newSource = {
id: sourceId,
name: sourceName,
status: 'processing',
date: new Date().toISOString()
};
const sources = storage.get('admin:sources', []);
storage.set('admin:sources', [newSource, ...sources]);
const rec = await db.addSource({ name: sourceName, status: 'processing' });
const sourceId = rec.id;
try {
// 2. Roep Anthropic API aan
const responseText = await anthropicApi.generateContent(SYSTEM_PROMPT, `Analyze the following text:\n\n${textContent}`);
// 3. Parse JSON (veilig)
const responseText = await anthropicApi.generateContent(SYSTEM_PROMPT, `Analyze the following text:\n\n${textContent}`);
let extractedData;
try {
// Zoek naar JSON in de response (indien het toch in markdown was verpakt)
const jsonMatch = responseText.match(/\{[\s\S]*\}/);
const jsonStr = jsonMatch ? jsonMatch[0] : responseText;
extractedData = JSON.parse(jsonStr);
@@ -58,36 +41,23 @@ export async function processSourceText(textContent, sourceName) {
throw new Error('AI response was not valid JSON.');
}
// 4. Deduplicatie en opslag van Topics en Relaties
mergeKnowledgeGraph(extractedData);
// 5. Markeer bron als voltooid
updateSourceStatus(sourceId, 'completed');
await mergeKnowledgeGraph(extractedData);
await db.updateSourceStatus(sourceId, 'completed');
return { success: true, data: extractedData };
} catch (error) {
// Markeer bron als mislukt
updateSourceStatus(sourceId, 'failed', error.message);
await db.updateSourceStatus(sourceId, 'failed', error.message);
throw error;
}
}
function updateSourceStatus(sourceId, status, errorMsg = '') {
const sources = storage.get('admin:sources', []);
const updated = sources.map(s =>
s.id === sourceId ? { ...s, status, error: errorMsg } : s
);
storage.set('admin:sources', updated);
}
async function mergeKnowledgeGraph(newData) {
const existingTopics = await db.getTopics();
const existingRelations = await db.getRelations();
function mergeKnowledgeGraph(newData) {
const existingTopics = storage.get('kb:topics', []);
const existingRelations = storage.get('kb:relations', []);
// Simpele deduplicatie op ID
const topicsMap = new Map(existingTopics.map(t => [t.id, t]));
if (newData.topics && Array.isArray(newData.topics)) {
for (const t of newData.topics) {
if (!topicsMap.has(t.id)) {
@@ -96,11 +66,9 @@ function mergeKnowledgeGraph(newData) {
}
}
// Voeg relaties toe (we gaan er nu vanuit dat ze uniek genoeg zijn of dubbele negeren)
const newRelations = [...existingRelations];
if (newData.relations && Array.isArray(newData.relations)) {
for (const r of newData.relations) {
// Simpele check om exacte duplicaten te voorkomen
const isDup = newRelations.some(ex => ex.source === r.source && ex.target === r.target && ex.type === r.type);
if (!isDup) {
newRelations.push(r);
@@ -108,6 +76,6 @@ function mergeKnowledgeGraph(newData) {
}
}
storage.set('kb:topics', Array.from(topicsMap.values()));
storage.set('kb:relations', newRelations);
await db.saveTopics(Array.from(topicsMap.values()));
await db.saveRelations(newRelations);
}

View File

@@ -1,5 +1,5 @@
import { anthropicApi } from './api';
import { storage } from './storage';
import * as db from './db';
const CONTENT_GENERATION_SYSTEM = `You are an expert learning content writer for Respellion, an internal IT company.
You write training material for employees based on knowledge topics.
@@ -33,12 +33,8 @@ const CONTENT_SCHEMA = `{
}
}`;
/**
* Get the assigned topic for a user for a given week using round-robin.
* hash(userId + weekNumber) % topicCount
*/
export function getAssignedTopic(userId, weekNumber) {
const topics = storage.get('kb:topics', []);
export async function getAssignedTopic(userId, weekNumber) {
const topics = await db.getTopics();
if (!topics || topics.length === 0) return null;
const str = `${userId}:${weekNumber}`;
@@ -51,43 +47,24 @@ export function getAssignedTopic(userId, weekNumber) {
return topics[index];
}
/**
* Returns the cache key for a topic's content.
*/
export function getContentCacheKey(topicId) {
return `kb:content:${topicId}`;
export async function getCachedContent(topicId) {
return db.getContent(topicId);
}
/**
* Returns cached content for a topic, or null if none exists.
*/
export function getCachedContent(topicId) {
return storage.get(getContentCacheKey(topicId), null);
export async function getAllGeneratedContent() {
const topics = await db.getTopics();
const results = await Promise.all(
topics.map(async topic => {
const content = await db.getContent(topic.id);
return { topic, content, hasContent: !!content };
})
);
return results.filter(item => item.hasContent);
}
/**
* List all topics that have generated content.
*/
export function getAllGeneratedContent() {
const topics = storage.get('kb:topics', []);
return topics
.map(topic => ({
topic,
content: getCachedContent(topic.id),
hasContent: !!getCachedContent(topic.id),
}))
.filter(item => item.hasContent);
}
/**
* Generate a complete learning module for a topic.
* Uses cached version if available (unless force = true).
*/
export async function generateLearningContent(topic, force = false) {
const cacheKey = getContentCacheKey(topic.id);
if (!force) {
const cached = storage.get(cacheKey);
const cached = await db.getContent(topic.id);
if (cached) {
console.log(`[Learn] Cache hit for topic: ${topic.id}`);
return cached;
@@ -115,17 +92,12 @@ Provide at least 3 article sections, 4 slides, 3 stats, and 3-5 steps in the inf
throw new Error('AI could not generate valid learning content. Please try again.');
}
storage.set(cacheKey, content);
await db.setContent(topic.id, content);
return content;
}
/**
* Refine existing content for a topic using a natural language instruction.
* Sends current content + refinement prompt to AI, saves new version.
*/
export async function refineLearningContent(topic, refinementInstruction) {
const cacheKey = getContentCacheKey(topic.id);
const existing = storage.get(cacheKey);
const existing = await db.getContent(topic.id);
const prompt = `You have previously generated the following learning module for the topic "${topic.label}":
@@ -146,22 +118,16 @@ Apply the refinement and return the complete updated JSON object using the same
throw new Error('AI could not process the refinement. Please try a different instruction.');
}
storage.set(cacheKey, content);
await db.setContent(topic.id, content);
return content;
}
/**
* Delete cached content for a topic, forcing a fresh generation next time.
*/
export function deleteCachedContent(topicId) {
storage.remove(getContentCacheKey(topicId));
export async function deleteCachedContent(topicId) {
return db.deleteContent(topicId);
}
/**
* Generate a new custom topic metadata on the fly from user input.
*/
export async function generateCustomTopic(label) {
const prompt = `A user wants to learn about "${label}".
const prompt = `A user wants to learn about "${label}".
Create a short description (2-3 sentences) and categorize it.
Return ONLY a JSON object with this structure:
@@ -172,7 +138,7 @@ Return ONLY a JSON object with this structure:
}`;
const responseText = await anthropicApi.generateContent(
"You are a knowledge graph AI categorizing topics.",
"You are a knowledge graph AI categorizing topics.",
prompt
);
@@ -185,9 +151,6 @@ Return ONLY a JSON object with this structure:
throw new Error('Could not process custom topic. Please try again.');
}
// Add to global knowledge base so others can see it too
const topics = storage.get('kb:topics', []);
storage.set('kb:topics', [...topics, newTopic]);
await db.upsertTopic(newTopic);
return newTopic;
}

6
src/lib/pb.js Normal file
View File

@@ -0,0 +1,6 @@
import PocketBase from 'pocketbase';
const pbUrl = import.meta.env.VITE_PB_URL ||
(typeof window !== 'undefined' ? window.location.origin + '/pb' : 'http://localhost:8090');
export const pb = new PocketBase(pbUrl);

View File

@@ -1,21 +1,15 @@
import { anthropicApi } from './api';
import { storage } from './storage';
import * as db from './db';
const QUIZ_SYSTEM = `You are a quiz generator for Respellion, an internal IT company learning platform.
You generate multiple-choice questions to test employee knowledge on specific topics.
Always write in clear, professional English.
ALWAYS return valid JSON only — no markdown code blocks, no extra text.`;
/**
* Select topics for the weekly test:
* - 50% from the user's assigned learning topic this week
* - 50% from random other topics (review)
*/
function selectTestTopics(userId, weekNumber) {
const topics = storage.get('kb:topics', []);
if (!topics || topics.length === 0) return [];
async function selectTestTopics(userId, weekNumber) {
const topics = await db.getTopics();
if (!topics || topics.length === 0) return { primaryTopic: null, reviewTopics: [] };
// Deterministic hash for the user's current topic
const str = `${userId}:${weekNumber}`;
let hash = 0;
for (let i = 0; i < str.length; i++) {
@@ -25,7 +19,6 @@ function selectTestTopics(userId, weekNumber) {
const primaryIndex = Math.abs(hash) % topics.length;
const primaryTopic = topics[primaryIndex];
// Pick up to 5 "review" topics (random, different from primary)
const others = topics.filter((_, i) => i !== primaryIndex);
const shuffled = others.sort(() => 0.5 - Math.random());
const reviewTopics = shuffled.slice(0, Math.min(5, shuffled.length));
@@ -33,19 +26,12 @@ function selectTestTopics(userId, weekNumber) {
return { primaryTopic, reviewTopics };
}
/**
* Retrieve cached quiz, or null.
*/
export function getCachedQuiz(userId, weekNumber) {
return storage.get(`quiz:${userId}:week:${weekNumber}`, null);
export async function getCachedQuiz(userId, weekNumber) {
return db.getCachedQuiz(userId, weekNumber);
}
/**
* Exported helper for admin: manually trigger generation for a topic.
*/
export async function forceGenerateTopicQuestions(topic, count = 10) {
const bankKey = `quiz:bank:${topic.id}`;
let bank = storage.get(bankKey, []);
let bank = await db.getQuizBank(topic.id);
const prompt = `Generate exactly ${count} multiple-choice quiz questions based on this knowledge topic:
@@ -88,77 +74,52 @@ Rules:
}
bank = [...bank, ...newQuestions];
storage.set(bankKey, bank);
await db.setQuizBank(topic.id, bank);
return newQuestions;
}
/**
* Ensure a topic has enough questions in its bank, generating more if needed.
* Returns exactly `count` questions.
*/
async function getOrGenerateTopicQuestions(topic, count) {
const bankKey = `quiz:bank:${topic.id}`;
let bank = storage.get(bankKey, []);
let bank = await db.getQuizBank(topic.id);
// If we don't have enough questions, ask AI to generate a batch of 10
if (bank.length < count) {
await forceGenerateTopicQuestions(topic, 10);
bank = storage.get(bankKey, []); // reload
bank = await db.getQuizBank(topic.id);
}
// Shuffle and pick `count` questions
const shuffled = [...bank].sort(() => 0.5 - Math.random());
return shuffled.slice(0, Math.min(count, shuffled.length));
}
/**
* Admin Helper: get question bank for a topic
*/
export function getTopicQuestionBank(topicId) {
return storage.get(`quiz:bank:${topicId}`, []);
export async function getTopicQuestionBank(topicId) {
return db.getQuizBank(topicId);
}
/**
* Admin Helper: delete a single question
*/
export function deleteQuestion(topicId, questionId) {
const bankKey = `quiz:bank:${topicId}`;
const bank = storage.get(bankKey, []);
storage.set(bankKey, bank.filter(q => q.id !== questionId));
export async function deleteQuestion(topicId, questionId) {
return db.deleteQuestionFromBank(topicId, questionId);
}
/**
* Generate 10 MCQ questions for a user's weekly test.
* Caches the result so the same quiz is served on retry.
* Pulls from topic-specific question banks, generating more if banks are low.
*/
export async function generateWeeklyQuiz(userId, weekNumber, force = false) {
const cacheKey = `quiz:${userId}:week:${weekNumber}`;
if (!force) {
const cached = storage.get(cacheKey);
const cached = await db.getCachedQuiz(userId, weekNumber);
if (cached) return cached;
}
const { primaryTopic, reviewTopics } = selectTestTopics(userId, weekNumber);
const { primaryTopic, reviewTopics } = await selectTestTopics(userId, weekNumber);
if (!primaryTopic) throw new Error('No topics available to generate a quiz.');
const questions = [];
// Get 5 questions for the primary topic
const primaryQs = await getOrGenerateTopicQuestions(primaryTopic, 5);
questions.push(...primaryQs);
// Get 1 question for each of the up to 5 review topics
for (const rt of reviewTopics) {
const rtQs = await getOrGenerateTopicQuestions(rt, 1);
questions.push(...rtQs);
}
// If there are fewer than 10 questions (e.g. no review topics yet), pad with more from primary
if (questions.length < 10) {
const needed = 10 - questions.length;
// We already took 5, so let's try to get enough extra unique questions
const extraQs = await getOrGenerateTopicQuestions(primaryTopic, needed + 5);
const extraQs = await getOrGenerateTopicQuestions(primaryTopic, needed + 5);
const existingIds = new Set(questions.map(q => q.id));
for (const eq of extraQs) {
if (!existingIds.has(eq.id) && questions.length < 10) {
@@ -167,58 +128,33 @@ export async function generateWeeklyQuiz(userId, weekNumber, force = false) {
}
}
// Shuffle the final 10 questions
questions.sort(() => 0.5 - Math.random());
const quiz = { questions };
quiz.meta = {
userId,
weekNumber,
generatedAt: new Date().toISOString(),
primaryTopic: primaryTopic.label,
const quiz = {
questions,
meta: {
userId,
weekNumber,
generatedAt: new Date().toISOString(),
primaryTopic: primaryTopic.label,
},
};
storage.set(cacheKey, quiz);
await db.setCachedQuiz(userId, weekNumber, quiz);
return quiz;
}
/**
* Save a completed test result.
*/
export function saveTestResult(userId, weekNumber, result) {
const key = `quiz:result:${userId}:week:${weekNumber}`;
storage.set(key, result);
export async function saveTestResult(userId, weekNumber, result) {
await db.saveQuizResult(userId, weekNumber, result);
// Update leaderboard points
const leaderboard = storage.get('leaderboard:current', []);
const entry = leaderboard.find(e => e.userId === userId);
const pointsEarned = result.score * 2; // 2 pts per correct answer
if (entry) {
entry.points += pointsEarned;
entry.testsCompleted = (entry.testsCompleted || 0) + 1;
} else {
const users = storage.get('users:registry', []);
const user = users.find(u => u.id === userId);
leaderboard.push({
userId,
name: user?.name || 'Unknown',
points: pointsEarned,
testsCompleted: 1,
learningsCompleted: 0,
});
}
// Sort desc
leaderboard.sort((a, b) => b.points - a.points);
storage.set('leaderboard:current', leaderboard);
const pointsEarned = result.score * 2;
const members = await db.getTeamMembers();
const member = members.find(m => m.id === userId);
await db.upsertLeaderboardEntry(userId, member?.name || 'Unknown', pointsEarned, 1);
return { pointsEarned };
}
/**
* Get a previously completed test result, or null.
*/
export function getTestResult(userId, weekNumber) {
return storage.get(`quiz:result:${userId}:week:${weekNumber}`, null);
export async function getTestResult(userId, weekNumber) {
return db.getQuizResult(userId, weekNumber);
}

View File

@@ -5,6 +5,7 @@ import Tag from '../../components/ui/Tag';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import { storage } from '../../lib/storage';
import * as db from '../../lib/db';
import UploadZone from '../../components/admin/UploadZone';
import KnowledgeGraph from '../../components/admin/KnowledgeGraph';
import ContentManager from '../../components/admin/ContentManager';
@@ -20,8 +21,9 @@ const Admin = () => {
const [useSimulation, setUseSimulation] = useState(false);
const [saveStatus, setSaveStatus] = useState(null);
const loadSources = () => {
setSources(storage.get('admin:sources', []));
const loadSources = async () => {
const data = await db.getSources();
setSources(data);
};
useEffect(() => {
@@ -44,11 +46,10 @@ const Admin = () => {
setTimeout(() => setSaveStatus(null), 3000);
};
const handleDeleteSource = (id) => {
const handleDeleteSource = async (id) => {
if (confirm('Are you sure you want to delete this source? This will not delete topics already extracted.')) {
const updated = sources.filter(s => s.id !== id);
storage.set('admin:sources', updated);
setSources(updated);
await db.deleteSource(id);
await loadSources();
}
};
@@ -63,10 +64,9 @@ const Admin = () => {
return (
<div className="flex flex-col md:flex-row h-[calc(100vh-64px)] overflow-hidden">
{/* Admin Sidebar */}
<div className="w-full md:w-64 bg-paper border-r border-bg-warm flex-shrink-0 flex flex-row md:flex-col p-4 gap-2 overflow-x-auto md:overflow-y-auto">
<h2 className="hidden md:block text-teal font-bold text-lg mb-4 px-2">Knowledge Mgmt</h2>
{navItems.map(({ key, icon: Icon, label, bottom }) => (
<button
key={key}
@@ -79,15 +79,13 @@ const Admin = () => {
))}
</div>
{/* Admin Main Content */}
<div className="flex-1 overflow-y-auto p-4 md:p-8 bg-bg pb-24 md:pb-8">
{/* ── Sources ─────────────────────────────── */}
{activeTab === 'sources' && (
<div className="animate-in fade-in duration-300 max-w-4xl mx-auto">
<h1 className="text-3xl text-teal mb-2">Source Material</h1>
<p className="text-fg-muted mb-8">Upload files to feed the AI knowledge extraction pipeline.</p>
<UploadZone onUploadComplete={loadSources} />
<h3 className="text-xl mb-4 mt-12">Recent Sources</h3>
@@ -109,7 +107,7 @@ const Admin = () => {
<div>
<p className="font-medium">{source.name}</p>
<p className="text-xs text-fg-muted flex items-center gap-1 mt-1">
<Clock size={12} /> {new Date(source.date).toLocaleString()}
<Clock size={12} /> {new Date(source.created).toLocaleString()}
</p>
</div>
</div>
@@ -129,7 +127,6 @@ const Admin = () => {
</div>
)}
{/* ── Content Manager ──────────────────────── */}
{activeTab === 'content' && (
<div className="animate-in fade-in duration-300 max-w-4xl mx-auto">
<h1 className="text-3xl text-teal mb-2">Learning Content</h1>
@@ -138,7 +135,6 @@ const Admin = () => {
</div>
)}
{/* ── Test Manager ─────────────────────────── */}
{activeTab === 'tests' && (
<div className="animate-in fade-in duration-300 max-w-4xl mx-auto">
<h1 className="text-3xl text-teal mb-2">Question Banks</h1>
@@ -147,18 +143,16 @@ const Admin = () => {
</div>
)}
{/* ── Knowledge Graph ──────────────────────── */}
{activeTab === 'graph' && (
<div className="animate-in fade-in duration-300 h-full flex flex-col">
<h1 className="text-3xl text-teal mb-2">Knowledge Graph</h1>
<p className="text-fg-muted mb-4">Visual map of all extracted Respellion knowledge.</p>
<Card className="flex-1 p-0 border border-bg-warm overflow-hidden bg-paper min-h-[400px]">
<KnowledgeGraph />
<KnowledgeGraph />
</Card>
</div>
)}
{/* ── Team ────────────────────────────────── */}
{activeTab === 'team' && (
<div className="animate-in fade-in duration-300 max-w-4xl mx-auto">
<h1 className="text-3xl text-teal mb-2">Team Management</h1>
@@ -167,17 +161,16 @@ const Admin = () => {
</div>
)}
{/* ── Settings ────────────────────────────── */}
{activeTab === 'settings' && (
<div className="animate-in fade-in duration-300 max-w-2xl">
<h1 className="text-3xl text-teal mb-2">Settings</h1>
<p className="text-fg-muted mb-8">Manage API keys and application configuration.</p>
<Card className="border border-bg-warm">
<form onSubmit={saveSettings} className="space-y-6">
<div>
<h3 className="text-lg font-medium mb-4">AI Configuration</h3>
<Input
<Input
label="Anthropic API Key"
type="password"
placeholder="sk-ant-..."
@@ -185,7 +178,7 @@ const Admin = () => {
onChange={(e) => setApiKey(e.target.value)}
/>
<div className="mt-4">
<Input
<Input
label="Model ID"
placeholder="claude-sonnet-4-20250514"
value={model}
@@ -205,9 +198,9 @@ const Admin = () => {
<p className="text-sm text-fg-muted">Use simulated AI responses when the API is unavailable.</p>
</div>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
<input
type="checkbox"
className="sr-only peer"
checked={useSimulation}
onChange={(e) => setUseSimulation(e.target.checked)}
/>
@@ -221,7 +214,7 @@ const Admin = () => {
</div>
)}
</div>
<div className="flex items-center gap-4 pt-4">
<Button type="submit">
<Save size={18} className="mr-2" /> Save Settings

View File

@@ -1,47 +1,62 @@
import React from 'react';
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useApp } from '../store/AppContext';
import Card from '../components/ui/Card';
import Button from '../components/ui/Button';
import Tag from '../components/ui/Tag';
import { storage } from '../lib/storage';
import * as db from '../lib/db';
import { getAssignedTopic } from '../lib/learningService';
import { getTestResult } from '../lib/testService';
const Dashboard = () => {
const { state } = useApp();
const { currentUser, weekNumber } = state;
const topic = getAssignedTopic(currentUser?.id, weekNumber);
const learnDone = storage.get(`user:${currentUser?.id}:week:${weekNumber}:learn_done`, false);
const testResult = getTestResult(currentUser?.id, weekNumber);
const allUsers = storage.get('users:registry', []);
const nonAdminIds = allUsers.filter(u => u.role !== 'admin').map(u => u.id);
const leaderboard = storage.get('leaderboard:current', [])
.filter(u => nonAdminIds.includes(u.userId))
.sort((a, b) => b.points - a.points);
const top3 = leaderboard.slice(0, 3);
const myRank = leaderboard.findIndex(u => u.userId === currentUser?.id) + 1;
const myPoints = leaderboard.find(u => u.userId === currentUser?.id)?.points || 0;
const [dashData, setDashData] = useState({
topic: null,
learnDone: false,
testResult: null,
top3: [],
myRank: 0,
myPoints: 0,
activity: [],
});
// Gather recent activity from past weeks
const activity = [];
for (let w = weekNumber; w >= Math.max(1, weekNumber - 3); w--) {
const pastLearn = storage.get(`user:${currentUser?.id}:week:${w}:learn_done`, false);
const pastTest = getTestResult(currentUser?.id, w);
const pastTopic = getAssignedTopic(currentUser?.id, w);
if (pastTest) {
activity.push({ type: 'test', week: w, topic: pastTopic?.label, score: pastTest.percentage, points: pastTest.pointsEarned });
}
if (pastLearn) {
activity.push({ type: 'learn', week: w, topic: pastTopic?.label });
}
}
useEffect(() => {
if (!currentUser) return;
const load = async () => {
const [topic, learnDone, testResult, allUsers, leaderboard] = await Promise.all([
getAssignedTopic(currentUser.id, weekNumber),
db.getLearnDone(currentUser.id, weekNumber),
db.getQuizResult(currentUser.id, weekNumber),
db.getTeamMembers(),
db.getLeaderboard(),
]);
const nonAdminIds = allUsers.filter(u => u.role !== 'admin').map(u => u.id);
const filtered = leaderboard.filter(u => nonAdminIds.includes(u.user_id));
const top3 = filtered.slice(0, 3);
const myRank = filtered.findIndex(u => u.user_id === currentUser.id) + 1;
const myPoints = filtered.find(u => u.user_id === currentUser.id)?.points || 0;
const activity = [];
for (let w = weekNumber; w >= Math.max(1, weekNumber - 3); w--) {
const [pastLearn, pastTest, pastTopic] = await Promise.all([
db.getLearnDone(currentUser.id, w),
db.getQuizResult(currentUser.id, w),
getAssignedTopic(currentUser.id, w),
]);
if (pastTest) activity.push({ type: 'test', week: w, topic: pastTopic?.label, score: pastTest.percentage, points: pastTest.points_earned });
if (pastLearn) activity.push({ type: 'learn', week: w, topic: pastTopic?.label });
}
setDashData({ topic, learnDone, testResult, top3, myRank, myPoints, activity });
};
load();
}, [currentUser, weekNumber]);
const { topic, learnDone, testResult, top3, myRank, myPoints, activity } = dashData;
return (
<div className="p-6 md:p-10 space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
@@ -118,7 +133,7 @@ const Dashboard = () => {
</div>
</Card>
</div>
<div>
<h3 className="text-2xl mb-4">Mini Leaderboard</h3>
<Card className="border border-bg-warm">
@@ -127,10 +142,10 @@ const Dashboard = () => {
<div className="text-center text-fg-muted py-4">No points yet</div>
) : (
top3.map((u, i) => (
<div key={u.userId} className="flex items-center justify-between">
<div key={u.user_id} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<span className={`font-mono font-bold ${i === 0 ? 'text-yellow-500' : 'text-teal'}`}>{i + 1}.</span>
<span className="font-medium">{u.name} {u.userId === currentUser?.id && '(You)'}</span>
<span className="font-medium">{u.name} {u.user_id === currentUser?.id && '(You)'}</span>
</div>
<Tag variant="dark">{u.points} pts</Tag>
</div>

View File

@@ -4,12 +4,12 @@ import { motion } from 'framer-motion';
import Card from '../components/ui/Card';
import Tag from '../components/ui/Tag';
import { useApp } from '../store/AppContext';
import { storage } from '../lib/storage';
import * as db from '../lib/db';
const BADGE_RULES = [
{ id: 'first_test', icon: Star, label: 'First Steps', condition: (u) => u.testsCompleted > 0 },
{ id: 'first_test', icon: Star, label: 'First Steps', condition: (u) => u.tests_completed > 0 },
{ id: 'perfectionist', icon: Award, label: 'Perfectionist', condition: (u) => u.perfectScores > 0 },
{ id: 'veteran', icon: Medal, label: 'Veteran', condition: (u) => u.testsCompleted >= 5 },
{ id: 'veteran', icon: Medal, label: 'Veteran', condition: (u) => u.tests_completed >= 5 },
];
const Leaderboard = () => {
@@ -17,40 +17,38 @@ const Leaderboard = () => {
const [board, setBoard] = useState([]);
useEffect(() => {
// Re-evaluate badges before displaying
let data = storage.get('leaderboard:current', []);
const allUsers = storage.get('users:registry', []);
// Filter out admins from the leaderboard entirely
const nonAdminIds = allUsers.filter(u => u.role !== 'admin').map(u => u.id);
data = data.filter(entry => nonAdminIds.includes(entry.userId));
const load = async () => {
const [leaderboardData, allUsers] = await Promise.all([
db.getLeaderboard(),
db.getTeamMembers(),
]);
const userMap = new Map(data.map(u => [u.userId, u]));
const nonAdminIds = allUsers.filter(u => u.role !== 'admin').map(u => u.id);
let data = leaderboardData.filter(entry => nonAdminIds.includes(entry.user_id));
allUsers.forEach(user => {
if (!userMap.has(user.id) && user.role !== 'admin') {
data.push({
userId: user.id,
name: user.name,
points: 0,
testsCompleted: 0,
});
// Ensure all non-admin users appear even if they have no points yet
const inBoard = new Set(data.map(e => e.user_id));
for (const user of allUsers) {
if (!inBoard.has(user.id) && user.role !== 'admin') {
data.push({ user_id: user.id, name: user.name, points: 0, tests_completed: 0, perfectScores: 0 });
}
}
});
// Check for perfect scores by peeking at test results
data = data.map(entry => {
let perfectScores = 0;
// Loop over all possible weeks
for (let w = 1; w <= state.weekNumber; w++) {
const result = storage.get(`quiz:result:${entry.userId}:week:${w}`);
if (result && result.percentage === 100) perfectScores++;
}
return { ...entry, perfectScores };
});
// Compute perfect scores per user
data = await Promise.all(data.map(async entry => {
let perfectScores = 0;
for (let w = 1; w <= state.weekNumber; w++) {
const result = await db.getQuizResult(entry.user_id, w);
if (result && result.percentage === 100) perfectScores++;
}
return { ...entry, perfectScores };
}));
data.sort((a, b) => b.points - a.points);
setBoard(data);
data.sort((a, b) => b.points - a.points);
setBoard(data);
};
load();
}, [state.weekNumber]);
return (
@@ -61,10 +59,8 @@ const Leaderboard = () => {
<p className="text-fg-muted">Compete, learn, and earn badges based on your weekly knowledge tests.</p>
</div>
{/* Top 3 Podium */}
{board.length >= 3 && (
<div className="flex justify-center items-end gap-2 md:gap-6 mb-16 h-64 mt-12">
{/* 2nd Place */}
<motion.div initial={{ y: 50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0.2 }} className="w-1/3 max-w-[140px] flex flex-col items-center">
<div className="relative mb-4">
<div className="w-16 h-16 rounded-full bg-slate-200 border-4 border-paper flex items-center justify-center text-slate-500 font-bold text-2xl shadow-lg z-10 relative">2</div>
@@ -75,7 +71,6 @@ const Leaderboard = () => {
<div className="w-full h-24 bg-gradient-to-t from-slate-200/50 to-transparent rounded-t-[var(--r-sm)] mt-4"></div>
</motion.div>
{/* 1st Place */}
<motion.div initial={{ y: 50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} className="w-1/3 max-w-[160px] flex flex-col items-center z-10">
<div className="relative mb-6">
<div className="w-20 h-20 rounded-full bg-yellow-400 border-4 border-paper flex items-center justify-center text-yellow-800 font-bold text-3xl shadow-xl z-10 relative">1</div>
@@ -87,7 +82,6 @@ const Leaderboard = () => {
<div className="w-full h-32 bg-gradient-to-t from-yellow-400/20 to-transparent rounded-t-[var(--r-sm)] mt-4 border-t border-yellow-400/30"></div>
</motion.div>
{/* 3rd Place */}
<motion.div initial={{ y: 50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0.4 }} className="w-1/3 max-w-[140px] flex flex-col items-center">
<div className="relative mb-4">
<div className="w-16 h-16 rounded-full bg-amber-700 border-4 border-paper flex items-center justify-center text-white font-bold text-2xl shadow-lg z-10 relative">3</div>
@@ -100,22 +94,20 @@ const Leaderboard = () => {
</div>
)}
{/* Full List */}
<Card className="border border-bg-warm p-0 overflow-hidden">
<div className="divide-y divide-bg-warm">
{board.map((user, index) => {
const earnedBadges = BADGE_RULES.filter(r => r.condition(user));
const isMe = user.userId === state.currentUser?.id;
const isMe = user.user_id === state.currentUser?.id;
return (
<motion.div
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: index * 0.05 }}
key={user.userId}
key={user.user_id}
className={`p-4 flex flex-col sm:flex-row sm:items-center gap-4 transition-colors ${isMe ? 'bg-teal/5 border-l-4 border-teal' : 'hover:bg-bg-warm/30'}`}
>
{/* Rank & Name */}
<div className="flex items-center gap-4 min-w-[200px]">
<span className={`font-mono text-lg font-bold w-6 text-center ${
index === 0 ? 'text-yellow-500' :
@@ -130,12 +122,11 @@ const Leaderboard = () => {
{isMe && <Tag variant="accent" className="text-[10px]">You</Tag>}
</p>
<p className="text-xs text-fg-muted flex items-center gap-1">
<CheckSquare size={12} /> {user.testsCompleted || 0} tests completed
<CheckSquare size={12} /> {user.tests_completed || 0} tests completed
</p>
</div>
</div>
{/* Points */}
<div className="flex-1 flex sm:justify-center">
<div className="flex items-center gap-1.5 text-teal font-bold bg-teal/10 px-3 py-1 rounded-full text-sm">
<TrendingUp size={14} />
@@ -143,7 +134,6 @@ const Leaderboard = () => {
</div>
</div>
{/* Badges */}
<div className="flex gap-2 sm:justify-end min-w-[120px]">
{earnedBadges.length > 0 ? (
earnedBadges.map(b => (

View File

@@ -9,7 +9,7 @@ import Input from '../components/ui/Input';
import LearningContentViewer from '../components/ui/LearningContentViewer';
import { useApp } from '../store/AppContext';
import { getAssignedTopic, generateLearningContent, getCachedContent, generateCustomTopic } from '../lib/learningService';
import { storage } from '../lib/storage';
import * as db from '../lib/db';
const Leren = () => {
const { state } = useApp();
@@ -39,12 +39,17 @@ const Leren = () => {
useEffect(() => {
if (state.currentUser) {
const assigned = getAssignedTopic(state.currentUser.id, state.weekNumber);
setAssignedTopic(assigned);
setAllTopics(storage.get('kb:topics', []));
const done = storage.get(`user:${state.currentUser.id}:week:${state.weekNumber}:learn_done`, false);
if (done) setWeeklyDone(true);
const load = async () => {
const [assigned, topics, done] = await Promise.all([
getAssignedTopic(state.currentUser.id, state.weekNumber),
db.getTopics(),
db.getLearnDone(state.currentUser.id, state.weekNumber),
]);
setAssignedTopic(assigned);
setAllTopics(topics);
if (done) setWeeklyDone(true);
};
load();
}
}, [state.currentUser, state.weekNumber]);
@@ -97,11 +102,11 @@ const Leren = () => {
}
};
const doComplete = () => {
const doComplete = async () => {
setSessionDone(true);
if (!weeklyDone) {
setWeeklyDone(true);
storage.set(`user:${state.currentUser.id}:week:${state.weekNumber}:learn_done`, true);
await db.setLearnDone(state.currentUser.id, state.weekNumber);
}
};
@@ -114,14 +119,12 @@ const Leren = () => {
doComplete();
};
const handleSubmitFeedback = () => {
const handleSubmitFeedback = async () => {
if (feedbackText.trim()) {
storage.set(`user:${state.currentUser.id}:feedback:${activeTopic.id}`, {
text: feedbackText.trim(),
topicId: activeTopic.id,
week: state.weekNumber,
timestamp: Date.now(),
});
await db.setSetting(
`feedback:${state.currentUser.id}:${activeTopic.id}:${state.weekNumber}`,
feedbackText.trim()
);
}
setShowFeedbackModal(false);
doComplete();

View File

@@ -1,12 +1,12 @@
import React, { createContext, useContext, useReducer, useEffect } from 'react';
import { storage } from '../lib/storage';
import * as db from '../lib/db';
const AppContext = createContext();
const initialState = {
currentUser: null, // will hold user object if logged in
users: [], // array of registered users
weekNumber: 1, // current learning week
currentUser: null,
users: [],
weekNumber: 1,
isLoading: true
};
@@ -20,25 +20,11 @@ function appReducer(state, action) {
isLoading: false
};
case 'LOGIN':
return {
...state,
currentUser: action.payload
};
return { ...state, currentUser: action.payload };
case 'LOGOUT':
return {
...state,
currentUser: null
};
case 'REGISTER_USER':
return {
...state,
users: [...state.users, action.payload]
};
return { ...state, currentUser: null };
case 'ADVANCE_WEEK':
return {
...state,
weekNumber: state.weekNumber + 1
};
return { ...state, weekNumber: state.weekNumber + 1 };
default:
return state;
}
@@ -47,48 +33,31 @@ function appReducer(state, action) {
export function AppProvider({ children }) {
const [state, dispatch] = useReducer(appReducer, initialState);
// Initialize app state from storage
useEffect(() => {
const loadState = () => {
let users = storage.get('users:registry');
// Seed first admin if no users exist
if (!users || users.length === 0) {
const initialAdmin = {
id: 'u_1',
name: 'Admin',
role: 'admin',
pin: '0000',
registeredAt: new Date().toISOString()
};
users = [initialAdmin];
storage.set('users:registry', users);
// Also seed initial empty leaderboard
storage.set('leaderboard:current', []);
}
const storedWeek = storage.get('admin:current_week') || 1;
const loadState = async () => {
let members = await db.getTeamMembers();
if (!members || members.length === 0) {
const created = await db.addTeamMember({ name: 'Admin', role: 'admin', pin: '0000' });
members = [created];
}
const storedWeek = Number(await db.getSetting('admin:current_week', 1));
// Automatically login if we saved session (optional, simpler to require login per session)
const sessionUserId = sessionStorage.getItem('respellion_session');
if (sessionUserId) {
const user = users.find(u => u.id === sessionUserId);
const user = members.find(u => u.id === sessionUserId);
if (user) {
dispatch({ type: 'LOGIN', payload: user });
}
}
dispatch({
type: 'INIT_APP',
payload: { users, weekNumber: storedWeek }
});
dispatch({ type: 'INIT_APP', payload: { users: members, weekNumber: storedWeek } });
};
loadState();
loadState().catch(console.error);
}, []);
// Expose dispatch actions as convenient methods
const login = (userId, pin) => {
const user = state.users.find(u => u.id === userId && u.pin === pin);
if (user) {