13 Commits
Author SHA1 Message Date
nmemmertandClaude Sonnet 5.5 a2fb3b056a Add free-type spell checker for students
Build and Push Docker Image / build-and-push (push) Successful in 1m5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-19 17:01:02 -04:00
nmemmertandClaude Sonnet 4.6 91fe38c00d Fix parent doc viewer: sign comment permissions server-side
Build and Push Docker Image / build-and-push (push) Successful in 35s
Client-side permission overrides invalidated the JWT. Move the
comment-only config to a new PIN-protected endpoint that signs
the correct permissions before returning to the browser.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 16:38:34 -04:00
nmemmertandClaude Sonnet 4.6 3e53efd752 Allow parent to add comments on submitted documents
Build and Push Docker Image / build-and-push (push) Successful in 38s
Switch admin doc viewer from view mode to comment-only mode so the
parent can annotate student work without editing the text.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 15:44:07 -04:00
nmemmertandClaude Sonnet 4.6 3d1e887c19 Add cache-busting query strings and no-cache for HTML files
Build and Push Docker Image / build-and-push (push) Successful in 39s
Proxy was caching old admin.js; ?v=3 query string forces a fresh fetch.
Also extend no-cache header to .html files so future deploys propagate immediately.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 15:39:40 -04:00
nmemmertandClaude Sonnet 4.6 3eb6322427 Show error message in admin docs panel instead of staying on Loading
Build and Push Docker Image / build-and-push (push) Successful in 38s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 15:01:41 -04:00
nmemmertandClaude Sonnet 4.6 ad3e0bc7be Fix editor full-screen and add parent-side doc viewer
Build and Push Docker Image / build-and-push (push) Successful in 45s
Student editor:
- Add body.docs-editor-open class when editor opens; hide hero, nav,
  confetti so nothing bleeds behind the fixed overlay

Admin docs panel:
- New "Documents" sidebar entry listing all submitted docs with student
  name, date, and unread badge
- Click any doc to open it in OnlyOffice in view (read-only) mode
- Download button for offline access
- /api/docs/bykey/:key/editor-config server route for admin viewer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:54:38 -04:00
nmemmertandClaude Sonnet 4.6 6a5ac46294 Disable browser caching for CSS and JS files
Build and Push Docker Image / build-and-push (push) Successful in 39s
Prevents stale styles/scripts after deployments.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:40:45 -04:00
nmemmertandClaude Sonnet 4.6 402fbfa16d Raise docs editor z-index to 10000 to cover nav bar and all overlays
Build and Push Docker Image / build-and-push (push) Successful in 44s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:36:55 -04:00
nmemmertandClaude Sonnet 4.6 4126a1bf55 Move docs editor overlay outside section so fixed positioning works
Build and Push Docker Image / build-and-push (push) Successful in 35s
The editor div was inside #tab-docs (.tab-panel) whose ancestor chain
could trap position:fixed. Moving it to a sibling of <section> so the
full-screen overlay covers the entire viewport unconditionally.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:33:24 -04:00
nmemmertandClaude Sonnet 4.6 9375332f6a Fix New Document button and make editor full-screen
Build and Push Docker Image / build-and-push (push) Successful in 35s
- Replace prompt() with inline title form (button → input → Create/Cancel)
- Editor view: position:fixed inset:0 z-index:200 so it covers full screen
- Docs editor toolbar moved into CSS (was duplicated in styles)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:29:01 -04:00
nmemmertandClaude Sonnet 4.6 95c0da5c51 Redesign student UI and add OnlyOffice document integration
Build and Push Docker Image / build-and-push (push) Successful in 33s
- Student section: new hero gradient header, fixed bottom nav bar with
  icon+label pills (Today/Courses/Spelling/Inbox/Docs)
- Today rows: card style with left accent stripe, lift on hover
- Course cards: grid layout with top color bar per course
- Docs tab: list view with doc cards, OnlyOffice editor embedded via
  iframe using server-signed JWT config
- Server: documents table, CRUD routes, OnlyOffice callback endpoint
  for auto-save, /api/docs/:id/editor-config returns signed config
- Blank DOCX template embedded as base64 for new document creation
- OnlyOffice server: https://onlyoffice.necloud.us (set ONLYOFFICE_JWT_SECRET
  env var to match your Document Server JWT secret)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 14:12:39 -04:00
nmemmertandClaude Sonnet 4.6 16e3bbbd83 Fix seed.js constraints: empty string for quiz body and SA choices, one assignment per student
Build and Push Docker Image / build-and-push (push) Successful in 36s
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 13:44:21 -04:00
nmemmertandClaude Sonnet 4.6 43850693ac Fix Settings nav and scope admin sidebar active-class toggle
Build and Push Docker Image / build-and-push (push) Successful in 36s
- Include .admin-sidebar-footer .nav-pill in click listener so Settings is reachable
- Update showPanel to toggle active class on both .admin-nav and footer pills

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-10-19 13:39:09 -04:00
10 changed files with 824 additions and 83 deletions

No files matched your search

+13
View File
@@ -244,6 +244,19 @@ tryAlter(`ALTER TABLE lists ADD COLUMN group_name TEXT NOT NULL DEFAULT ''`);
tryAlter(`ALTER TABLE decks ADD COLUMN group_name TEXT NOT NULL DEFAULT ''`); tryAlter(`ALTER TABLE decks ADD COLUMN group_name TEXT NOT NULL DEFAULT ''`);
tryAlter(`ALTER TABLE tests ADD COLUMN item_id INTEGER`); tryAlter(`ALTER TABLE tests ADD COLUMN item_id INTEGER`);
db.exec(`CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL REFERENCES students(id) ON DELETE CASCADE,
title TEXT NOT NULL DEFAULT 'Untitled Document',
doc_key TEXT NOT NULL UNIQUE,
filename TEXT NOT NULL,
submitted INTEGER NOT NULL DEFAULT 0,
submitted_at TEXT,
parent_read INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
)`);
export const sha256 = (s) => createHash('sha256').update(String(s)).digest('hex'); export const sha256 = (s) => createHash('sha256').update(String(s)).digest('hex');
// Default parent PIN on first run // Default parent PIN on first run
+45 -1
View File
@@ -9,9 +9,11 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"dictionary-en": "^4.0.0",
"express": "^5.1.0", "express": "^5.1.0",
"mammoth": "^1.12.0", "mammoth": "^1.12.0",
"multer": "^2.2.0" "multer": "^2.2.0",
"nspell": "^2.1.5"
}, },
"engines": { "engines": {
"node": ">=24" "node": ">=24"
@@ -273,6 +275,16 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/dictionary-en": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/dictionary-en/-/dictionary-en-4.0.0.tgz",
"integrity": "sha512-3NHnE1uq33ZE/CIwaZ6gqxa4BnglHnxeAcTM0GJ7cmtRGcvX9InMK/IqLtYcUMFCUpUNgybH+DzkqdgAo3F1zg==",
"license": "(MIT AND BSD)",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/dingbat-to-unicode": { "node_modules/dingbat-to-unicode": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/dingbat-to-unicode/-/dingbat-to-unicode-1.0.1.tgz", "resolved": "https://registry.npmjs.org/dingbat-to-unicode/-/dingbat-to-unicode-1.0.1.tgz",
@@ -583,6 +595,29 @@
"node": ">= 0.10" "node": ">= 0.10"
} }
}, },
"node_modules/is-buffer": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",
"integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/is-promise": { "node_modules/is-promise": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
@@ -783,6 +818,15 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/nspell": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/nspell/-/nspell-2.1.5.tgz",
"integrity": "sha512-PSStyugKMiD9mHmqI/CR5xXrSIGejUXPlo88FBRq5Og1kO5QwQ5Ilu8D8O5I/SHpoS+mibpw6uKA8rd3vXd2Sg==",
"license": "MIT",
"dependencies": {
"is-buffer": "^2.0.0"
}
},
"node_modules/object-inspect": { "node_modules/object-inspect": {
"version": "1.13.4", "version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+3 -1
View File
@@ -11,9 +11,11 @@
"author": "NateEmmert", "author": "NateEmmert",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"dictionary-en": "^4.0.0",
"express": "^5.1.0", "express": "^5.1.0",
"mammoth": "^1.12.0", "mammoth": "^1.12.0",
"multer": "^2.2.0" "multer": "^2.2.0",
"nspell": "^2.1.5"
}, },
"engines": { "engines": {
"node": ">=24" "node": ">=24"
+21 -1
View File
@@ -57,6 +57,9 @@
<button class="nav-pill" data-panel="decks"> <button class="nav-pill" data-panel="decks">
<span class="nav-icon">🗂️</span><span class="nav-label">Flashcards</span> <span class="nav-icon">🗂️</span><span class="nav-label">Flashcards</span>
</button> </button>
<button class="nav-pill" data-panel="docs">
<span class="nav-icon">📝</span><span class="nav-label">Docs</span>
</button>
</nav> </nav>
<div class="admin-sidebar-footer"> <div class="admin-sidebar-footer">
<button class="nav-pill" data-panel="settings"> <button class="nav-pill" data-panel="settings">
@@ -679,6 +682,23 @@
</div> </div>
</section> </section>
<!-- Docs -->
<section id="panel-docs" class="panel" hidden>
<h1>Submitted Documents</h1>
<div id="admin-docs-list">
<p class="hint">Loading…</p>
</div>
<!-- Full-screen doc viewer -->
<div id="admin-doc-viewer" hidden>
<div class="docs-editor-toolbar">
<button id="btn-admin-doc-back" class="docs-back-btn">← Back to list</button>
<span id="admin-doc-viewer-title" class="docs-editor-title-text"></span>
<a id="admin-doc-download" class="docs-submit-btn" download>⬇ Download</a>
</div>
<div id="admin-doc-frame"></div>
</div>
</section>
<!-- Settings --> <!-- Settings -->
<section id="panel-settings" class="panel"> <section id="panel-settings" class="panel">
<h1>Settings</h1> <h1>Settings</h1>
@@ -773,6 +793,6 @@
</div> </div>
</div> </div>
<script src="admin.js"></script> <script src="admin.js?v=5"></script>
</body> </body>
</html> </html>
+86 -5
View File
@@ -110,7 +110,7 @@ if (parentPin) unlock();
// ---------- navigation ---------- // ---------- navigation ----------
document.querySelectorAll('.admin-nav .nav-pill').forEach((pill) => document.querySelectorAll('.admin-nav .nav-pill, .admin-sidebar-footer .nav-pill').forEach((pill) =>
pill.addEventListener('click', () => showPanel(pill.dataset.panel)) pill.addEventListener('click', () => showPanel(pill.dataset.panel))
); );
document.querySelectorAll('[data-nav]').forEach((btn) => document.querySelectorAll('[data-nav]').forEach((btn) =>
@@ -120,19 +120,19 @@ document.querySelectorAll('[data-nav]').forEach((btn) =>
const PANEL_TITLES = { const PANEL_TITLES = {
dashboard: 'Dashboard', kids: 'Kids', courses: 'Courses', planner: 'Planner', dashboard: 'Dashboard', kids: 'Kids', courses: 'Courses', planner: 'Planner',
grading: 'Grading', messages: 'Messages', gradebook: 'Gradebook', grading: 'Grading', messages: 'Messages', gradebook: 'Gradebook',
spelling: 'Spelling', decks: 'Flashcards', settings: 'Settings', spelling: 'Spelling', decks: 'Flashcards', docs: 'Documents', settings: 'Settings',
'course-detail': 'Course Detail', 'item-editor': 'Item Editor', 'course-detail': 'Course Detail', 'item-editor': 'Item Editor',
}; };
function showPanel(name) { function showPanel(name) {
document.querySelectorAll('.panel').forEach((p) => (p.hidden = p.id !== `panel-${name}`)); document.querySelectorAll('.panel').forEach((p) => (p.hidden = p.id !== `panel-${name}`));
document.querySelectorAll('.admin-nav .nav-pill').forEach((p) => p.classList.toggle('active', p.dataset.panel === name)); document.querySelectorAll('.admin-nav .nav-pill, .admin-sidebar-footer .nav-pill').forEach((p) => p.classList.toggle('active', p.dataset.panel === name));
const titleEl = document.getElementById('admin-page-title'); const titleEl = document.getElementById('admin-page-title');
if (titleEl) titleEl.textContent = PANEL_TITLES[name] || name; if (titleEl) titleEl.textContent = PANEL_TITLES[name] || name;
const loaders = { const loaders = {
dashboard: loadDashboard, kids: loadKids, courses: loadCourses, planner: loadPlannerPanel, dashboard: loadDashboard, kids: loadKids, courses: loadCourses, planner: loadPlannerPanel,
grading: loadGrading, messages: loadMessages, gradebook: loadGradebookPanel, spelling: loadSpelling, decks: loadDecks, grading: loadGrading, messages: loadMessages, gradebook: loadGradebookPanel, spelling: loadSpelling, decks: loadDecks,
settings: loadSettings, docs: loadAdminDocs, settings: loadSettings,
}; };
if (loaders[name]) loaders[name](); if (loaders[name]) loaders[name]();
if (name === 'course-detail') openCourseDetail(currentCourseId); if (name === 'course-detail') openCourseDetail(currentCourseId);
@@ -216,7 +216,7 @@ async function loadDashboard() {
const scores = recentScores.scores || recentScores || []; const scores = recentScores.scores || recentScores || [];
scoresEl.innerHTML = scores.length ? scores.slice(0, 8).map(sc => { scoresEl.innerHTML = scores.length ? scores.slice(0, 8).map(sc => {
const pct = sc.total > 0 ? Math.round(sc.score / sc.total * 100) : null; const pct = sc.points_possible > 0 ? Math.round(sc.score / sc.points_possible * 100) : null;
const cls = pct === null ? '' : pct >= 80 ? '' : pct >= 60 ? ' mid' : ' low'; const cls = pct === null ? '' : pct >= 80 ? '' : pct >= 60 ? ' mid' : ' low';
const kidName = students.find(s => s.id === sc.student_id)?.name || ''; const kidName = students.find(s => s.id === sc.student_id)?.name || '';
return `<div class="dash-score-item"> return `<div class="dash-score-item">
@@ -3290,3 +3290,84 @@ $('#app-settings-form').addEventListener('submit', async (e) => {
msg('Settings saved.'); msg('Settings saved.');
}); });
// ── Admin: Submitted Documents ────────────────────────────────────────────────
let adminDocsEditorInstance = null;
async function loadAdminDocs() {
const el = $('#admin-docs-list');
let docs;
try {
({ docs } = await api('/api/admin/docs'));
} catch (err) {
el.innerHTML = `<p class="hint" style="color:red">Error loading documents: ${esc(err.message)}</p>`;
return;
}
if (!docs.length) {
el.innerHTML = '<p class="hint">No submitted documents yet.</p>';
return;
}
el.innerHTML = docs.map((d) => `
<div class="doc-card${!d.parent_read ? ' inbox-new' : ''}" style="cursor:pointer"
data-id="${d.id}" data-key="${esc(d.doc_key)}" data-filename="${esc(d.filename)}" data-title="${esc(d.title)}">
<div class="doc-card-icon">📄</div>
<div class="doc-card-info">
<div class="doc-card-title">${esc(d.title)}${!d.parent_read ? ' <span class="feedback-badge">New</span>' : ''}</div>
<div class="doc-card-meta">${esc(d.student_name)} · Submitted ${new Date(d.submitted_at + 'Z').toLocaleDateString()}</div>
</div>
</div>
`).join('');
el.querySelectorAll('.doc-card').forEach((card) => {
card.addEventListener('click', () => openAdminDocViewer(
+card.dataset.id, card.dataset.key, card.dataset.filename, card.dataset.title
));
});
}
async function openAdminDocViewer(id, key, filename, title) {
await api(`/api/admin/docs/${id}/read`, { method: 'PUT' });
$('#admin-docs-list').hidden = true;
$('#admin-doc-viewer').hidden = false;
$('#admin-doc-viewer-title').textContent = title;
$('#admin-doc-download').href = `/api/docs/file/${filename}`;
$('#admin-doc-download').download = title + '.docx';
const frame = $('#admin-doc-frame');
frame.innerHTML = '';
if (adminDocsEditorInstance) {
try { adminDocsEditorInstance.destroyEditor(); } catch { /* ignore */ }
adminDocsEditorInstance = null;
}
const { onlyofficeUrl, config } = await api(`/api/admin/docs/bykey/${key}/editor-config`).catch(() => null) || {};
if (!onlyofficeUrl || !config) {
frame.innerHTML = `<div class="docs-error">Could not load document config.</div>`;
return;
}
function initEditor() {
adminDocsEditorInstance = new window.DocsAPI.DocEditor('admin-doc-frame', config);
}
if (window.DocsAPI) {
initEditor();
} else {
const s = document.createElement('script');
s.src = `${onlyofficeUrl}/web-apps/apps/api/documents/api.js`;
s.onload = initEditor;
s.onerror = () => { frame.innerHTML = `<div class="docs-error">Could not reach OnlyOffice server.</div>`; };
document.head.appendChild(s);
}
}
document.getElementById('btn-admin-doc-back')?.addEventListener('click', () => {
if (adminDocsEditorInstance) {
try { adminDocsEditorInstance.destroyEditor(); } catch { /* ignore */ }
adminDocsEditorInstance = null;
}
$('#admin-doc-frame').innerHTML = '';
$('#admin-doc-viewer').hidden = true;
$('#admin-docs-list').hidden = false;
loadAdminDocs();
});
+160 -1
View File
@@ -313,7 +313,7 @@ document.querySelectorAll('.nav-pill').forEach((pill) =>
pill.addEventListener('click', () => switchTab(pill.dataset.tab)) pill.addEventListener('click', () => switchTab(pill.dataset.tab))
); );
const TAB_ORDER = ['today', 'courses', 'spelling', 'inbox']; const TAB_ORDER = ['today', 'courses', 'spelling', 'inbox', 'docs'];
let currentTab = 'today'; let currentTab = 'today';
function switchTab(name) { function switchTab(name) {
@@ -331,6 +331,7 @@ function switchTab(name) {
} }
}); });
if (name === 'inbox') loadInbox(); if (name === 'inbox') loadInbox();
if (name === 'docs') loadDocs();
} }
function inboxSeenKey(studentId) { return `inbox_seen_${studentId}`; } function inboxSeenKey(studentId) { return `inbox_seen_${studentId}`; }
@@ -2518,6 +2519,164 @@ $('#btn-test').addEventListener('click', () => {
startTest(); startTest();
}); });
$('#btn-freetype').addEventListener('click', () => {
backTarget = () => openKid(currentStudent.id, 'spelling');
$('#freetype-feedback').innerHTML = '';
$('#freetype-input').value = '';
show('freetype');
$('#freetype-input').focus();
});
$('#freetype-form').addEventListener('submit', async (e) => {
e.preventDefault();
const input = $('#freetype-input');
const typed = input.value.trim();
if (!typed) return;
const fb = $('#freetype-feedback');
try {
const r = await api(`/api/spellcheck?word=${encodeURIComponent(typed)}`);
if (r.correct) {
fb.innerHTML = `<div class="banner good">✅ "${esc(r.word)}" is spelled correctly!</div>`;
} else {
const tips = r.suggestions.length
? ` Did you mean: ${r.suggestions.map((x) => `<strong>${esc(x)}</strong>`).join(', ')}?`
: '';
fb.innerHTML = `<div class="banner bad">❌ "${esc(r.word)}" is not spelled correctly.${tips}</div>`;
alert(`"${r.word}" is spelled wrong. Try again!`);
}
} catch (err) {
fb.innerHTML = `<div class="banner bad">${esc(err.message)}</div>`;
}
input.select();
});
// ---------- docs (OnlyOffice) ----------
let docsEditorInstance = null;
let currentDocId = null;
async function loadDocs() {
const sid = currentStudent?.id;
if (!sid) return;
const { docs } = await api(`/api/docs?studentId=${sid}`);
const list = $('#docs-list');
const empty = $('#docs-empty');
if (!docs.length) {
list.innerHTML = '';
empty.hidden = false;
return;
}
empty.hidden = true;
list.innerHTML = docs.map((d) => `
<div class="doc-card${d.submitted ? ' doc-submitted' : ''}" data-id="${d.id}" data-key="${esc(d.doc_key)}" data-title="${esc(d.title)}">
<div class="doc-card-icon">📄</div>
<div class="doc-card-info">
<div class="doc-card-title">${esc(d.title)}</div>
<div class="doc-card-meta">${d.submitted ? '✓ Submitted' : 'Draft'} · ${new Date(d.updated_at + 'Z').toLocaleDateString()}</div>
</div>
<button class="doc-delete-btn" data-id="${d.id}" aria-label="Delete">🗑</button>
</div>
`).join('');
list.querySelectorAll('.doc-card').forEach((card) => {
card.addEventListener('click', (e) => {
if (e.target.closest('.doc-delete-btn')) return;
openDocEditor(+card.dataset.id, card.dataset.key, card.dataset.title);
});
});
list.querySelectorAll('.doc-delete-btn').forEach((btn) => {
btn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm('Delete this document?')) return;
await api(`/api/docs/${btn.dataset.id}`, { method: 'DELETE' });
loadDocs();
});
});
}
async function openDocEditor(id, key, title) {
currentDocId = id;
$('#docs-list-view').hidden = true;
$('#docs-editor-view').hidden = false;
$('#docs-editor-title').textContent = title;
$('#btn-docs-submit').disabled = false;
$('#btn-docs-submit').textContent = 'Submit to Parent ✓';
document.body.classList.add('docs-editor-open');
const frame = $('#docs-editor-frame');
frame.innerHTML = '';
if (docsEditorInstance) {
try { docsEditorInstance.destroyEditor(); } catch { /* ignore */ }
docsEditorInstance = null;
}
const { onlyofficeUrl, config } = await api(`/api/docs/${id}/editor-config`).catch(() => null) || {};
if (!onlyofficeUrl || !config) {
frame.innerHTML = `<div class="docs-error">Could not load document config from server.</div>`;
return;
}
const apiScript = `${onlyofficeUrl}/web-apps/apps/api/documents/api.js`;
function initEditor() {
docsEditorInstance = new window.DocsAPI.DocEditor('docs-editor-frame', config);
}
if (window.DocsAPI) {
initEditor();
} else {
const s = document.createElement('script');
s.src = apiScript;
s.onload = initEditor;
s.onerror = () => {
frame.innerHTML = `<div class="docs-error">Could not load OnlyOffice editor from <code>${onlyofficeUrl}</code>. Make sure the server at <strong>${onlyofficeUrl}</strong> is reachable from this device.</div>`;
};
document.head.appendChild(s);
}
}
$('#btn-new-doc').addEventListener('click', () => {
$('#btn-new-doc').hidden = true;
$('#docs-new-form').hidden = false;
$('#docs-new-title').value = '';
$('#docs-new-title').focus();
});
$('#btn-docs-new-cancel').addEventListener('click', () => {
$('#docs-new-form').hidden = true;
$('#btn-new-doc').hidden = false;
});
$('#docs-new-form').addEventListener('submit', async (e) => {
e.preventDefault();
const title = $('#docs-new-title').value.trim() || 'Untitled Document';
$('#docs-new-form').hidden = true;
$('#btn-new-doc').hidden = false;
const { id, key } = await api('/api/docs', { method: 'POST', body: { studentId: currentStudent.id, title } });
await loadDocs();
openDocEditor(id, key, title);
});
$('#btn-docs-back').addEventListener('click', () => {
document.body.classList.remove('docs-editor-open');
if (docsEditorInstance) {
try { docsEditorInstance.destroyEditor(); } catch { /* ignore */ }
docsEditorInstance = null;
}
$('#docs-editor-frame').innerHTML = '';
$('#docs-editor-view').hidden = true;
$('#docs-list-view').hidden = false;
loadDocs();
});
$('#btn-docs-submit').addEventListener('click', async () => {
if (!currentDocId) return;
if (!confirm('Submit this document to your parent?')) return;
await api(`/api/docs/${currentDocId}/submit`, { method: 'POST' });
$('#btn-docs-submit').textContent = '✓ Submitted!';
$('#btn-docs-submit').disabled = true;
});
// ---------- boot ---------- // ---------- boot ----------
loadHome(); loadHome();
+49 -6
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homeschool</title> <title>Homeschool</title>
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css?v=3">
</head> </head>
<body> <body>
@@ -44,6 +44,7 @@
<!-- Kid home: Today's work + nav --> <!-- Kid home: Today's work + nav -->
<section id="view-kid" class="view" hidden> <section id="view-kid" class="view" hidden>
<div class="kid-hero">
<div class="kid-topbar"> <div class="kid-topbar">
<button class="back-btn" data-nav="home">← Switch</button> <button class="back-btn" data-nav="home">← Switch</button>
<div class="kid-topbar-actions"> <div class="kid-topbar-actions">
@@ -53,6 +54,7 @@
</div> </div>
</div> </div>
<h1 id="kid-greeting"></h1> <h1 id="kid-greeting"></h1>
</div>
<div id="theme-dots" class="theme-dots" hidden> <div id="theme-dots" class="theme-dots" hidden>
<button class="theme-dot theme-blue" data-theme="blue" title="Blue"></button> <button class="theme-dot theme-blue" data-theme="blue" title="Blue"></button>
<button class="theme-dot theme-green" data-theme="green" title="Green"></button> <button class="theme-dot theme-green" data-theme="green" title="Green"></button>
@@ -75,10 +77,11 @@
</div> </div>
<div class="kid-nav"> <div class="kid-nav">
<button class="nav-pill active" data-tab="today">📋 Today</button> <button class="nav-pill active" data-tab="today"><span class="np-icon">📋</span><span class="np-label">Today</span></button>
<button class="nav-pill" data-tab="courses">📚 My Courses</button> <button class="nav-pill" data-tab="courses"><span class="np-icon">📚</span><span class="np-label">Courses</span></button>
<button class="nav-pill" data-tab="spelling">✏️ Spelling</button> <button class="nav-pill" data-tab="spelling"><span class="np-icon">✏️</span><span class="np-label">Spelling</span></button>
<button class="nav-pill" data-tab="inbox">📬 Inbox<span id="inbox-badge" class="feedback-badge" hidden></span></button> <button class="nav-pill" data-tab="inbox"><span class="np-icon">📬</span><span class="np-label">Inbox<span id="inbox-badge" class="feedback-badge" hidden></span></span></button>
<button class="nav-pill" data-tab="docs"><span class="np-icon">📝</span><span class="np-label">Docs</span></button>
</div> </div>
<div id="tab-today" class="tab-panel"> <div id="tab-today" class="tab-panel">
@@ -96,6 +99,7 @@
<div class="big-actions"> <div class="big-actions">
<button id="btn-practice" class="big-btn practice">✏️ Practice</button> <button id="btn-practice" class="big-btn practice">✏️ Practice</button>
<button id="btn-test" class="big-btn test">⭐ Friday Test</button> <button id="btn-test" class="big-btn test">⭐ Friday Test</button>
<button id="btn-freetype" class="big-btn print-list">🔍 Check any word</button>
<button id="btn-print-list" class="big-btn print-list">🖨 Print my words</button> <button id="btn-print-list" class="big-btn print-list">🖨 Print my words</button>
</div> </div>
<div id="kid-test-history"></div> <div id="kid-test-history"></div>
@@ -124,8 +128,33 @@
</form> </form>
</div> </div>
</div> </div>
<div id="tab-docs" class="tab-panel" hidden>
<div id="docs-list-view">
<div class="docs-toolbar">
<button id="btn-new-doc" class="docs-new-btn">+ New Document</button>
</div>
<form id="docs-new-form" class="docs-new-form" hidden>
<input id="docs-new-title" class="docs-new-input" type="text" placeholder="Document title…" maxlength="120" autocomplete="off">
<button type="submit" class="docs-new-btn">Create</button>
<button type="button" id="btn-docs-new-cancel" class="docs-cancel-btn">Cancel</button>
</form>
<div id="docs-list"></div>
<p id="docs-empty" class="hint" hidden>No documents yet — tap + New Document to start writing!</p>
</div>
</div>
</section> </section>
<!-- Docs full-screen editor overlay (outside section so fixed positioning is never trapped) -->
<div id="docs-editor-view" hidden>
<div class="docs-editor-toolbar">
<button id="btn-docs-back" class="docs-back-btn">← Back</button>
<span id="docs-editor-title" class="docs-editor-title-text"></span>
<button id="btn-docs-submit" class="docs-submit-btn">Submit to Parent ✓</button>
</div>
<div id="docs-editor-frame"></div>
</div>
<!-- All-done celebration overlay --> <!-- All-done celebration overlay -->
<div id="celebration-overlay" hidden> <div id="celebration-overlay" hidden>
<div id="celebration-content"> <div id="celebration-content">
@@ -245,6 +274,20 @@
</div> </div>
</section> </section>
<!-- Free-type spell check -->
<section id="view-freetype" class="view" hidden>
<button class="back-btn" data-back="freetype">← Back</button>
<div class="word-card">
<p class="prompt">Type any word and I'll tell you if it's spelled right:</p>
<div id="freetype-feedback" class="feedback"></div>
<form id="freetype-form" autocomplete="off">
<input id="freetype-input" class="spell-input" type="text" autocomplete="off"
autocapitalize="off" autocorrect="off" spellcheck="false" aria-label="Type a word" enterkeyhint="go">
<p class="hint">Press Enter to check</p>
</form>
</div>
</section>
<!-- Practice (spelling) --> <!-- Practice (spelling) -->
<section id="view-practice" class="view" hidden> <section id="view-practice" class="view" hidden>
<button class="back-btn" data-back="practice">← Back</button> <button class="back-btn" data-back="practice">← Back</button>
@@ -338,6 +381,6 @@
</div> </div>
</section> </section>
<script src="app.js"></script> <script src="app.js?v=3"></script>
</body> </body>
</html> </html>
+255 -40
View File
@@ -259,11 +259,72 @@ body:has(#view-home:not([hidden])) .page-confetti { display: block; }
/* ============================================================ KID HOME (inner) */ /* ============================================================ KID HOME (inner) */
/* Full-width hero with kid accent gradient */
#view-kid {
max-width: 100%;
padding: 0 0 5rem;
text-align: left;
}
.kid-hero {
background: linear-gradient(160deg, var(--kid-accent, var(--accent)) 0%,
color-mix(in srgb, var(--kid-accent, var(--accent)) 55%, #0d1b3e) 100%);
padding-bottom: 2rem;
position: relative;
overflow: hidden;
}
.kid-hero::before {
content: '';
position: absolute; inset: 0; pointer-events: none;
background: radial-gradient(circle at 80% -10%, rgba(255,255,255,.15) 0%, transparent 55%);
}
#view-kid .kid-topbar {
background: rgba(0,0,0,.12);
padding: .65rem 1.1rem;
border-bottom: none;
}
#view-kid .back-btn {
background: rgba(255,255,255,.18);
border-color: rgba(255,255,255,.25);
color: #fff;
backdrop-filter: blur(8px);
}
#view-kid .back-btn:hover {
background: rgba(255,255,255,.28);
color: #fff;
}
#view-kid .theme-picker-btn {
background: rgba(255,255,255,.18);
border: 1.5px solid rgba(255,255,255,.25);
color: #fff;
}
#view-kid .theme-picker-btn:hover { background: rgba(255,255,255,.28); }
#kid-greeting { #kid-greeting {
font-family: var(--font-kid); font-family: var(--font-kid);
font-size: 2rem; font-size: 2.2rem;
font-weight: 800; font-weight: 900;
margin: 1rem 0; clear: both; color: #fff;
text-shadow: 0 2px 12px rgba(0,0,0,.18);
padding: .75rem 1.5rem 0;
margin: 0;
clear: both;
position: relative;
z-index: 1;
}
.streak-pill {
display: inline-block;
background: rgba(255,255,255,.2);
color: #fff;
border-radius: 999px;
padding: .3rem .9rem;
font-size: .88rem; font-weight: 700;
backdrop-filter: blur(8px);
border: 1px solid rgba(255,255,255,.25);
margin: .5rem 0 0 1.5rem;
position: relative; z-index: 1;
} }
.week-card { .week-card {
@@ -566,65 +627,123 @@ table.results tr:hover td { background: #fafbff; }
color: var(--accent); text-decoration: underline; cursor: pointer; font-size: .9rem; color: var(--accent); text-decoration: underline; cursor: pointer; font-size: .9rem;
} }
/* ============================================================ KID NAV PILLS */ /* ============================================================ KID NAV PILLS — BOTTOM BAR */
.kid-nav { .kid-nav {
display: flex; gap: .4rem; justify-content: center; position: fixed;
margin: .5rem 0 1.5rem; clear: both; flex-wrap: wrap; bottom: 0; left: 0; right: 0;
display: flex; justify-content: space-around;
background: var(--card);
border-top: 1.5px solid var(--border);
padding: .45rem .5rem .6rem;
z-index: 100;
box-shadow: 0 -4px 24px rgba(0,0,0,.08);
} }
.nav-pill {
font-family: var(--font-kid);
font-size: .95rem; font-weight: 700;
background: rgba(0,0,0,.05); color: var(--ink-2);
border: 1.5px solid var(--border);
border-radius: 999px; padding: .45rem 1.1rem; cursor: pointer;
transition: background .15s, color .15s, border-color .15s;
}
.nav-pill:hover { background: rgba(0,0,0,.08); color: var(--ink); }
.nav-pill.active {
background: var(--accent); color: #fff; border-color: var(--accent);
}
.nav-pill.active:hover { background: var(--accent-dark); }
.tab-panel { text-align: left; } .nav-pill {
flex: 1;
display: flex; flex-direction: column; align-items: center; gap: .15rem;
font-family: var(--font-kid);
font-size: .62rem; font-weight: 700; letter-spacing: .01em;
background: none; color: var(--muted);
border: none;
border-radius: 12px;
padding: .4rem .25rem .25rem;
cursor: pointer;
transition: color .15s, background .15s;
line-height: 1.1;
min-width: 0;
}
.nav-pill .np-icon { font-size: 1.35rem; line-height: 1; display: block; transition: transform .15s; }
.nav-pill .np-label { display: block; white-space: nowrap; }
.nav-pill:hover { color: var(--ink); }
.nav-pill:hover .np-icon { transform: translateY(-2px); }
.nav-pill.active { color: var(--kid-accent, var(--accent)); }
.nav-pill.active .np-icon { filter: drop-shadow(0 2px 4px rgba(0,0,0,.2)); transform: translateY(-2px); }
/* Admin nav pills still need old behaviour — scoped below in admin section */
.tab-panel {
text-align: left;
max-width: 640px;
margin: 0 auto;
padding: 1.25rem 1.25rem 1.5rem;
}
@keyframes tab-slide-right { from { transform: translateX(48px); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes tab-slide-right { from { transform: translateX(48px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
@keyframes tab-slide-left { from { transform: translateX(-48px); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes tab-slide-left { from { transform: translateX(-48px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
.tab-panel.sliding-right { animation: tab-slide-right .24s ease; } .tab-panel.sliding-right { animation: tab-slide-right .24s ease; }
.tab-panel.sliding-left { animation: tab-slide-left .24s ease; } .tab-panel.sliding-left { animation: tab-slide-left .24s ease; }
/* Pickers appear below the hero but above the tab panels */
#view-kid #theme-dots,
#view-kid #icon-grid,
#view-kid #bg-pattern-panel {
max-width: 640px;
margin: .75rem auto 0;
padding: 0 1.25rem;
}
/* ============================================================ TODAY ROWS */ /* ============================================================ TODAY ROWS */
.today-list { display: flex; flex-direction: column; gap: .65rem; }
.today-row { .today-row {
display: flex; align-items: center; gap: .85rem; width: 100%; display: flex; align-items: center; gap: 1rem; width: 100%;
background: var(--card); border: 1.5px solid var(--border); background: var(--card);
border-radius: var(--radius); padding: 1rem 1.15rem; border: none;
margin: .45rem 0; cursor: pointer; text-align: left; border-radius: 16px;
padding: 1.1rem 1.25rem 1.1rem 1.5rem;
margin: 0; cursor: pointer; text-align: left;
font-family: inherit; font-family: inherit;
transition: border-color .15s, box-shadow .15s, transform .1s; box-shadow: 0 2px 8px rgba(0,0,0,.06), 0 0 0 1.5px var(--border);
transition: transform .15s ease, box-shadow .15s ease;
position: relative; overflow: hidden;
}
.today-row::before {
content: '';
position: absolute; left: 0; top: 0; bottom: 0; width: 5px;
background: var(--accent);
border-radius: 4px 0 0 4px;
} }
.today-row:hover { .today-row:hover {
border-color: var(--accent); box-shadow: var(--shadow-sm); transform: translateY(-2px);
transform: translateX(2px); box-shadow: 0 6px 20px rgba(0,0,0,.1), 0 0 0 1.5px var(--border-hover);
} }
.today-row .row-check { font-size: 1.35rem; flex-shrink: 0; } .today-row .row-check { font-size: 1.4rem; flex-shrink: 0; width: 2rem; text-align: center; }
.today-row .row-title { flex: 1; font-size: 1rem; font-weight: 700; color: var(--ink); } .today-row .row-title { flex: 1; font-size: 1rem; font-weight: 700; color: var(--ink); line-height: 1.3; }
.today-row .row-title small { display: block; font-weight: 400; color: var(--muted); font-size: .82rem; } .today-row .row-title small { display: block; font-weight: 500; color: var(--muted); font-size: .8rem; margin-top: .12rem; }
.today-row .row-badge { font-size: .82rem; color: var(--muted); font-weight: 600; white-space: nowrap; } .today-row .row-badge { font-size: .78rem; color: var(--muted); font-weight: 600; white-space: nowrap; }
/* ============================================================ COURSE CARDS */ /* ============================================================ COURSE CARDS */
.course-cards { display: flex; flex-direction: column; gap: .65rem; } .course-cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: .85rem;
}
.course-card { .course-card {
display: flex; flex-direction: column; gap: .35rem; text-align: left; display: flex; flex-direction: column; gap: .35rem; text-align: left;
background: var(--card); border: 1.5px solid var(--border); background: var(--card);
border-left: 5px solid var(--accent); border: none;
border-radius: var(--radius); padding: 1rem 1.2rem; cursor: pointer; font-family: inherit; border-radius: 16px;
transition: border-color .15s, box-shadow .15s, transform .1s; padding: 1.25rem 1.3rem;
cursor: pointer; font-family: inherit;
box-shadow: 0 2px 8px rgba(0,0,0,.06), 0 0 0 1.5px var(--border);
transition: transform .15s ease, box-shadow .15s ease;
position: relative; overflow: hidden;
} }
.course-card:hover { box-shadow: var(--shadow); transform: translateX(2px); } .course-card::before {
.course-card strong { font-size: 1.1rem; } content: '';
.course-subject { color: var(--muted); font-size: .875rem; } position: absolute; top: 0; left: 0; right: 0; height: 5px;
.course-pct { font-size: .82rem; color: var(--muted); } background: var(--course-color, var(--accent));
}
.course-card:hover {
transform: translateY(-3px);
box-shadow: 0 8px 24px rgba(0,0,0,.1), 0 0 0 1.5px var(--border-hover);
}
.course-card strong { font-size: 1.05rem; font-weight: 800; color: var(--ink); }
.course-subject { color: var(--muted); font-size: .82rem; }
.course-pct { font-size: .78rem; color: var(--muted); margin-top: .1rem; }
/* ============================================================ UNIT BLOCKS (shared) */ /* ============================================================ UNIT BLOCKS (shared) */
@@ -2040,3 +2159,99 @@ body.bg-bubbles {
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
.ws-blank-input { color: #e2e8f0; } .ws-blank-input { color: #e2e8f0; }
} }
/* ============================================================ DOCS TAB */
.docs-toolbar { display: flex; justify-content: flex-end; margin-bottom: 1rem; }
.docs-new-btn {
background: var(--accent); color: #fff; border: none;
border-radius: 12px; padding: .6rem 1.2rem; font-size: .95rem; font-weight: 700;
cursor: pointer; font-family: inherit; transition: opacity .15s;
}
.docs-new-btn:hover { opacity: .85; }
.doc-card {
display: flex; align-items: center; gap: 1rem;
background: var(--card); border: none; border-radius: 16px;
padding: 1rem 1.25rem; margin-bottom: .65rem; cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,.06), 0 0 0 1.5px var(--border);
transition: transform .15s, box-shadow .15s;
}
.doc-card:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,.1), 0 0 0 1.5px var(--border-hover); }
.doc-card.doc-submitted { border-left: 4px solid #22c55e; }
.doc-card-icon { font-size: 2rem; flex-shrink: 0; }
.doc-card-info { flex: 1; }
.doc-card-title { font-size: 1rem; font-weight: 700; color: var(--ink); }
.doc-card-meta { font-size: .8rem; color: var(--muted); margin-top: .15rem; }
.doc-delete-btn {
background: none; border: none; cursor: pointer; font-size: 1.1rem;
opacity: .5; padding: .25rem; border-radius: 8px; transition: opacity .15s;
}
.doc-delete-btn:hover { opacity: 1; background: #fee2e2; }
.docs-editor-toolbar {
display: flex; align-items: center; gap: .75rem;
padding: .75rem 1.25rem; background: var(--card);
border-bottom: 1.5px solid var(--border);
}
.docs-back-btn {
background: none; border: 1.5px solid var(--border); color: var(--ink);
border-radius: 8px; padding: .4rem .85rem; font-size: .88rem; font-weight: 600;
cursor: pointer; font-family: inherit; white-space: nowrap;
}
.docs-editor-title-text { flex: 1; font-size: 1rem; font-weight: 700; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.docs-submit-btn {
background: #22c55e; color: #fff; border: none;
border-radius: 8px; padding: .4rem .85rem; font-size: .88rem; font-weight: 700;
cursor: pointer; font-family: inherit; white-space: nowrap; transition: opacity .15s;
}
.docs-submit-btn:hover { opacity: .85; }
.docs-submit-btn:disabled { background: var(--muted); opacity: .6; cursor: default; }
#docs-editor-view {
position: fixed; inset: 0; z-index: 10000;
display: flex; flex-direction: column;
background: #fff;
}
body.docs-editor-open .kid-hero,
body.docs-editor-open .kid-nav,
body.docs-editor-open .page-confetti,
body.docs-editor-open .tab-panel { display: none !important; }
#docs-editor-frame { flex: 1; min-height: 0; }
#docs-editor-frame iframe { width: 100%; height: 100%; border: none; display: block; }
.docs-editor-toolbar {
display: flex; align-items: center; gap: .75rem;
padding: .6rem 1rem;
background: var(--card); border-bottom: 1.5px solid var(--border);
flex-shrink: 0;
}
.docs-new-form {
display: flex; gap: .5rem; align-items: center;
margin-bottom: .75rem; flex-wrap: wrap;
}
.docs-new-input {
flex: 1; min-width: 160px;
border: 1.5px solid var(--border); border-radius: 10px;
padding: .55rem .85rem; font-size: .95rem; font-family: inherit;
background: var(--card); color: var(--ink);
outline: none;
}
.docs-new-input:focus { border-color: var(--accent); }
.docs-cancel-btn {
background: none; border: 1.5px solid var(--border); color: var(--muted);
border-radius: 10px; padding: .55rem .85rem; font-size: .9rem; font-weight: 600;
cursor: pointer; font-family: inherit;
}
.docs-error { padding: 1.5rem; color: var(--muted); font-size: .9rem; }
.docs-error code { background: var(--surface); padding: .1rem .4rem; border-radius: 4px; }
/* Admin doc viewer */
#admin-doc-viewer {
position: fixed; inset: 0; z-index: 10000;
display: flex; flex-direction: column; background: #fff;
}
#admin-doc-frame { flex: 1; min-height: 0; }
#admin-doc-frame iframe { width: 100%; height: 100%; border: none; display: block; }
+15 -24
View File
@@ -124,12 +124,12 @@ insertItem.run(itemId, laUnit1, 'lesson', 'Parts of Speech', `
const lessonPos = itemId++; const lessonPos = itemId++;
// Quiz: Parts of Speech // Quiz: Parts of Speech
insertItem.run(itemId, laUnit1, 'quiz', 'Parts of Speech Quiz', null, 20, null, 2, daysAgo(10), 1, 'none'); insertItem.run(itemId, laUnit1, 'quiz', 'Parts of Speech Quiz', '', 20, null, 2, daysAgo(10), 1, 'none');
const quizPos = itemId++; const quizPos = itemId++;
insertQ.run(qId++, quizPos, 'mc', 'Which word is a NOUN?', JSON.stringify(['quickly','beautiful','mountain','runs']), 'mountain', 5, 1); insertQ.run(qId++, quizPos, 'mc', 'Which word is a NOUN?', JSON.stringify(['quickly','beautiful','mountain','runs']), 'mountain', 5, 1);
insertQ.run(qId++, quizPos, 'mc', 'Which word is a VERB?', JSON.stringify(['slowly','purple','jump','the']), 'jump', 5, 2); insertQ.run(qId++, quizPos, 'mc', 'Which word is a VERB?', JSON.stringify(['slowly','purple','jump','the']), 'jump', 5, 2);
insertQ.run(qId++, quizPos, 'mc', 'Which word is an ADJECTIVE?', JSON.stringify(['gracefully','enormous','laugh','because']), 'enormous', 5, 3); insertQ.run(qId++, quizPos, 'mc', 'Which word is an ADJECTIVE?', JSON.stringify(['gracefully','enormous','laugh','because']), 'enormous', 5, 3);
insertQ.run(qId++, quizPos, 'sa', 'Write a sentence using a preposition.', null, null, 5, 4); insertQ.run(qId++, quizPos, 'sa', 'Write a sentence using a preposition.', '[]', '', 5, 4);
// Lesson: Sentence Structure // Lesson: Sentence Structure
insertItem.run(itemId, laUnit1, 'lesson', 'Sentence Structure', ` insertItem.run(itemId, laUnit1, 'lesson', 'Sentence Structure', `
@@ -195,11 +195,11 @@ insertItem.run(itemId, mathUnit1, 'lesson', 'Understanding Fractions', `
`, 0, null, 1, daysAgo(21), 0, 'none'); `, 0, null, 1, daysAgo(21), 0, 'none');
itemId++; itemId++;
insertItem.run(itemId, mathUnit1, 'quiz', 'Fractions Quiz', null, 30, null, 2, daysAgo(14), 1, 'none'); insertItem.run(itemId, mathUnit1, 'quiz', 'Fractions Quiz', '', 30, null, 2, daysAgo(14), 1, 'none');
const quizFrac = itemId++; const quizFrac = itemId++;
insertQ.run(qId++, quizFrac, 'mc', 'What is the simplified form of 6/9?', JSON.stringify(['1/3','2/3','3/4','6/9']), '2/3', 10, 1); insertQ.run(qId++, quizFrac, 'mc', 'What is the simplified form of 6/9?', JSON.stringify(['1/3','2/3','3/4','6/9']), '2/3', 10, 1);
insertQ.run(qId++, quizFrac, 'mc', 'Which fraction is equivalent to 1/2?', JSON.stringify(['2/3','3/4','4/8','5/9']), '4/8', 10, 2); insertQ.run(qId++, quizFrac, 'mc', 'Which fraction is equivalent to 1/2?', JSON.stringify(['2/3','3/4','4/8','5/9']), '4/8', 10, 2);
insertQ.run(qId++, quizFrac, 'sa', 'Write two fractions that are equivalent to 3/4.', null, null, 10, 3); insertQ.run(qId++, quizFrac, 'sa', 'Write two fractions that are equivalent to 3/4.', '[]', '', 10, 3);
insertItem.run(itemId, mathUnit1, 'lesson', 'Adding & Subtracting Fractions', ` insertItem.run(itemId, mathUnit1, 'lesson', 'Adding & Subtracting Fractions', `
<h2>Same Denominator</h2> <h2>Same Denominator</h2>
@@ -268,13 +268,13 @@ insertItem.run(itemId, sciUnit1, 'lesson', 'Water Cycle Overview', `
`, 0, null, 1, daysAgo(18), 0, 'none'); `, 0, null, 1, daysAgo(18), 0, 'none');
itemId++; itemId++;
insertItem.run(itemId, sciUnit1, 'quiz', 'Water Cycle Quiz', null, 25, null, 2, daysAgo(12), 1, 'none'); insertItem.run(itemId, sciUnit1, 'quiz', 'Water Cycle Quiz', '', 25, null, 2, daysAgo(12), 1, 'none');
const quizWater = itemId++; const quizWater = itemId++;
insertQ.run(qId++, quizWater, 'mc', 'What is the process where liquid water becomes water vapor?', JSON.stringify(['Condensation','Precipitation','Evaporation','Collection']), 'Evaporation', 5, 1); insertQ.run(qId++, quizWater, 'mc', 'What is the process where liquid water becomes water vapor?', JSON.stringify(['Condensation','Precipitation','Evaporation','Collection']), 'Evaporation', 5, 1);
insertQ.run(qId++, quizWater, 'mc', 'What energy source drives the water cycle?', JSON.stringify(['The moon','Wind','The sun','Earth\'s core']), 'The sun', 5, 2); insertQ.run(qId++, quizWater, 'mc', 'What energy source drives the water cycle?', JSON.stringify(['The moon','Wind','The sun','Earth\'s core']), 'The sun', 5, 2);
insertQ.run(qId++, quizWater, 'mc', 'What is it called when water falls from clouds?', JSON.stringify(['Evaporation','Condensation','Collection','Precipitation']), 'Precipitation', 5, 3); insertQ.run(qId++, quizWater, 'mc', 'What is it called when water falls from clouds?', JSON.stringify(['Evaporation','Condensation','Collection','Precipitation']), 'Precipitation', 5, 3);
insertQ.run(qId++, quizWater, 'mc', 'Which of these is NOT a form of precipitation?', JSON.stringify(['Rain','Snow','Fog','Hail']), 'Fog', 5, 4); insertQ.run(qId++, quizWater, 'mc', 'Which of these is NOT a form of precipitation?', JSON.stringify(['Rain','Snow','Fog','Hail']), 'Fog', 5, 4);
insertQ.run(qId++, quizWater, 'sa', 'Explain in your own words what condensation is.', null, null, 5, 5); insertQ.run(qId++, quizWater, 'sa', 'Explain in your own words what condensation is.', '[]', '', 5, 5);
insertItem.run(itemId, sciUnit1, 'assignment', 'Water Cycle Diagram', ` insertItem.run(itemId, sciUnit1, 'assignment', 'Water Cycle Diagram', `
Draw and label a diagram of the water cycle. Your diagram must include: Draw and label a diagram of the water cycle. Your diagram must include:
@@ -327,12 +327,12 @@ insertItem.run(itemId, histUnit1, 'lesson', 'The 13 Original Colonies', `
`, 0, null, 1, daysAgo(25), 0, 'none'); `, 0, null, 1, daysAgo(25), 0, 'none');
itemId++; itemId++;
insertItem.run(itemId, histUnit1, 'quiz', 'Colonial America Quiz', null, 20, null, 2, daysAgo(20), 1, 'none'); insertItem.run(itemId, histUnit1, 'quiz', 'Colonial America Quiz', '', 20, null, 2, daysAgo(20), 1, 'none');
const quizColonial = itemId++; const quizColonial = itemId++;
insertQ.run(qId++, quizColonial, 'mc', 'Which region was known as the "breadbasket" colonies?', JSON.stringify(['New England','Middle Colonies','Southern Colonies','Western Territories']), 'Middle Colonies', 5, 1); insertQ.run(qId++, quizColonial, 'mc', 'Which region was known as the "breadbasket" colonies?', JSON.stringify(['New England','Middle Colonies','Southern Colonies','Western Territories']), 'Middle Colonies', 5, 1);
insertQ.run(qId++, quizColonial, 'mc', 'What was the first permanent English settlement in America?', JSON.stringify(['Plymouth','Boston','Jamestown','Philadelphia']), 'Jamestown', 5, 2); insertQ.run(qId++, quizColonial, 'mc', 'What was the first permanent English settlement in America?', JSON.stringify(['Plymouth','Boston','Jamestown','Philadelphia']), 'Jamestown', 5, 2);
insertQ.run(qId++, quizColonial, 'mc', 'How many original colonies were there?', JSON.stringify(['10','12','13','15']), '13', 5, 3); insertQ.run(qId++, quizColonial, 'mc', 'How many original colonies were there?', JSON.stringify(['10','12','13','15']), '13', 5, 3);
insertQ.run(qId++, quizColonial, 'sa', 'Name two crops grown in the Southern Colonies.', null, null, 5, 4); insertQ.run(qId++, quizColonial, 'sa', 'Name two crops grown in the Southern Colonies.', '[]', '', 5, 4);
insertItem.run(itemId, histUnit1, 'lesson', 'Daily Life in the Colonies', ` insertItem.run(itemId, histUnit1, 'lesson', 'Daily Life in the Colonies', `
<h2>Life in Colonial Times</h2> <h2>Life in Colonial Times</h2>
@@ -383,11 +383,11 @@ insertItem.run(itemId, bibleUnit1, 'lesson', 'Noah and the Ark', `
`, 0, null, 1, daysAgo(10), 0, 'none'); `, 0, null, 1, daysAgo(10), 0, 'none');
itemId++; itemId++;
insertItem.run(itemId, bibleUnit1, 'quiz', 'Noah and the Ark Quiz', null, 15, null, 2, daysAgo(7), 1, 'none'); insertItem.run(itemId, bibleUnit1, 'quiz', 'Noah and the Ark Quiz', '', 15, null, 2, daysAgo(7), 1, 'none');
const quizNoah = itemId++; const quizNoah = itemId++;
insertQ.run(qId++, quizNoah, 'mc', 'Where is the story of Noah found in the Bible?', JSON.stringify(['Exodus','Matthew','Genesis','Psalms']), 'Genesis', 5, 1); insertQ.run(qId++, quizNoah, 'mc', 'Where is the story of Noah found in the Bible?', JSON.stringify(['Exodus','Matthew','Genesis','Psalms']), 'Genesis', 5, 1);
insertQ.run(qId++, quizNoah, 'mc', 'How many days and nights did it rain?', JSON.stringify(['7','20','40','100']), '40', 5, 2); insertQ.run(qId++, quizNoah, 'mc', 'How many days and nights did it rain?', JSON.stringify(['7','20','40','100']), '40', 5, 2);
insertQ.run(qId++, quizNoah, 'sa', 'What did the rainbow represent after the flood?', null, null, 5, 3); insertQ.run(qId++, quizNoah, 'sa', 'What did the rainbow represent after the flood?', '[]', '', 5, 3);
insertItem.run(itemId, bibleUnit1, 'lesson', 'David and Goliath', ` insertItem.run(itemId, bibleUnit1, 'lesson', 'David and Goliath', `
<h2>Courage and Faith</h2> <h2>Courage and Faith</h2>
@@ -446,11 +446,7 @@ insertSub.run(subId++, 1, quizNoah, 'done', 12, 15, noahAnswers, tsAgo(6));
insertSubHist.run(1, quizNoah, 12, 15, noahAnswers, tsAgo(6)); insertSubHist.run(1, quizNoah, 12, 15, noahAnswers, tsAgo(6));
// Liam's completed work // Liam's completed work
// Fractions Quiz — 20/30 (Liam, first attempt) // Fractions Quiz — 27/30 (Liam, best score)
const fracAnswersLiam1 = JSON.stringify({ 1: '2/3', 2: '3/4', 3: '4/6 and 8/12' });
insertSub.run(subId++, 2, quizFrac, 'done', 20, 30, fracAnswersLiam1, tsAgo(15));
insertSubHist.run(2, quizFrac, 20, 30, fracAnswersLiam1, tsAgo(15));
// Liam retook — 27/30
const fracAnswersLiam2 = JSON.stringify({ 1: '2/3', 2: '4/8', 3: '6/8 and 9/12' }); const fracAnswersLiam2 = JSON.stringify({ 1: '2/3', 2: '4/8', 3: '6/8 and 9/12' });
insertSub.run(subId++, 2, quizFrac, 'done', 27, 30, fracAnswersLiam2, tsAgo(12)); insertSub.run(subId++, 2, quizFrac, 'done', 27, 30, fracAnswersLiam2, tsAgo(12));
insertSubHist.run(2, quizFrac, 27, 30, fracAnswersLiam2, tsAgo(12)); insertSubHist.run(2, quizFrac, 27, 30, fracAnswersLiam2, tsAgo(12));
@@ -544,15 +540,10 @@ bibleWords.forEach(([w, s, d]) => insertWord.run(wordId++, list4, w, s, d));
console.log('Spelling lists and words created.'); console.log('Spelling lists and words created.');
/* ── assignments (connect students to lists) ──────────────── */ /* ── assignments (one active list per student) ─────────────── */
const insertAssignment = db.prepare('INSERT INTO assignments (student_id, list_id, assigned_at) VALUES (?, ?, ?)'); const insertAssignment = db.prepare('INSERT OR REPLACE INTO assignments (student_id, list_id, assigned_at) VALUES (?, ?, ?)');
insertAssignment.run(1, list1, tsAgo(14)); // Emma → Week 1 insertAssignment.run(1, list2, tsAgo(7)); // Emma → Week 2 (current)
insertAssignment.run(1, list2, tsAgo(7)); // Emma → Week 2 insertAssignment.run(2, list1, tsAgo(14)); // Liam → Week 1 (current)
insertAssignment.run(1, list3, tsAgo(18)); // Emma → Science
insertAssignment.run(1, list4, tsAgo(10)); // Emma → Bible
insertAssignment.run(2, list1, tsAgo(14)); // Liam → Week 1
insertAssignment.run(2, list2, tsAgo(7)); // Liam → Week 2
insertAssignment.run(2, list3, tsAgo(18)); // Liam → Science
/* ── spelling progress (Leitner boxes) ────────────────────── */ /* ── spelling progress (Leitner boxes) ────────────────────── */
const insertProgress = db.prepare(` const insertProgress = db.prepare(`
+177 -4
View File
@@ -4,9 +4,11 @@ import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs'; import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { readFile, writeFile, unlink } from 'node:fs/promises'; import { readFile, writeFile, unlink } from 'node:fs/promises';
import { createHash, randomUUID } from 'node:crypto'; import { createHash, createHmac, randomUUID } from 'node:crypto';
import mammoth from 'mammoth'; import mammoth from 'mammoth';
import multer from 'multer'; import multer from 'multer';
import nspell from 'nspell';
import dictionaryEn from 'dictionary-en';
import { db, sha256 } from './db.js'; import { db, sha256 } from './db.js';
const ROOT = dirname(fileURLToPath(import.meta.url)); const ROOT = dirname(fileURLToPath(import.meta.url));
@@ -15,13 +17,32 @@ const TTS_CACHE = join(DATA_DIR, 'tts-cache');
mkdirSync(TTS_CACHE, { recursive: true }); mkdirSync(TTS_CACHE, { recursive: true });
const ATTACHMENTS_DIR = join(DATA_DIR, 'attachments'); const ATTACHMENTS_DIR = join(DATA_DIR, 'attachments');
mkdirSync(ATTACHMENTS_DIR, { recursive: true }); mkdirSync(ATTACHMENTS_DIR, { recursive: true });
const DOCS_DIR = join(DATA_DIR, 'docs');
mkdirSync(DOCS_DIR, { recursive: true });
const ONLYOFFICE_URL = (process.env.ONLYOFFICE_URL || 'https://onlyoffice.necloud.us').replace(/\/$/, '');
const SERVER_URL = (process.env.SERVER_URL || 'http://localhost:3002').replace(/\/$/, '');
const ONLYOFFICE_JWT_SECRET = process.env.ONLYOFFICE_JWT_SECRET || '';
function jwtSign(payload) {
if (!ONLYOFFICE_JWT_SECRET) return undefined;
const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const sig = createHmac('sha256', ONLYOFFICE_JWT_SECRET).update(`${header}.${body}`).digest('base64url');
return `${header}.${body}.${sig}`;
}
const PIPER_BIN = process.env.PIPER_BIN || 'piper'; const PIPER_BIN = process.env.PIPER_BIN || 'piper';
const PIPER_MODEL = process.env.PIPER_MODEL || join(ROOT, 'voices', 'en_US-lessac-medium.onnx'); const PIPER_MODEL = process.env.PIPER_MODEL || join(ROOT, 'voices', 'en_US-lessac-medium.onnx');
const PIPER_OK = existsSync(PIPER_MODEL); const PIPER_OK = existsSync(PIPER_MODEL);
const app = express(); const app = express();
app.use(express.json({ limit: '15mb' })); // photos for page-scanning are base64 in the JSON body app.use(express.json({ limit: '15mb' })); // photos for page-scanning are base64 in the JSON body
app.use(express.static(join(ROOT, 'public'))); app.use(express.static(join(ROOT, 'public'), {
setHeaders(res, filePath) {
if (filePath.endsWith('.css') || filePath.endsWith('.js') || filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
}
},
}));
const docxUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } }); const docxUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } });
@@ -416,6 +437,16 @@ app.get('/api/state/:studentId', (req, res) => {
res.json({ student: { ...student, isBirthdayWeek: isBirthdayWeek(student.birthday) }, assignment, listProgress }); res.json({ student: { ...student, isBirthdayWeek: isBirthdayWeek(student.birthday) }, assignment, listProgress });
}); });
// Free-type spell check: any word, checked against a bundled English dictionary
const speller = nspell(dictionaryEn);
app.get('/api/spellcheck', (req, res) => {
const word = String(req.query.word || '').trim();
if (!/^[A-Za-z'’-]{1,60}$/.test(word)) return res.status(400).json({ error: 'Type a single word using letters only.' });
const clean = word.replace(/’/g, "'");
const correct = speller.correct(clean) || speller.correct(clean.toLowerCase());
res.json({ word, correct, suggestions: correct ? [] : speller.suggest(clean).slice(0, 4) });
});
// Build a practice session: the target list's unmastered words only. // Build a practice session: the target list's unmastered words only.
// listId overrides the student's pinned weekly assignment (used when launched from a course item). // listId overrides the student's pinned weekly assignment (used when launched from a course item).
app.get('/api/session/:studentId', (req, res) => { app.get('/api/session/:studentId', (req, res) => {
@@ -838,10 +869,10 @@ app.get('/api/admin/schedule', requirePin, (req, res) => {
app.get('/api/admin/recent-scores', requirePin, (req, res) => { app.get('/api/admin/recent-scores', requirePin, (req, res) => {
const scores = db.prepare(` const scores = db.prepare(`
SELECT s.id, s.student_id, i.title, s.score, s.total, s.submitted_at SELECT s.id, s.student_id, i.title, s.score, s.points_possible, s.completed_at
FROM submissions s FROM submissions s
JOIN items i ON i.id = s.item_id JOIN items i ON i.id = s.item_id
ORDER BY s.submitted_at DESC ORDER BY s.completed_at DESC
LIMIT 20 LIMIT 20
`).all(); `).all();
res.json({ scores }); res.json({ scores });
@@ -2435,6 +2466,148 @@ app.post('/api/admin/upload-attachment', requirePin, async (req, res) => {
return res.json({ url: `/api/attachments/${filename}`, htmlBody, originalName }); return res.json({ url: `/api/attachments/${filename}`, htmlBody, originalName });
}); });
// ── Documents (OnlyOffice) ────────────────────────────────────────────────────
app.use('/api/docs/file', express.static(DOCS_DIR));
app.get('/api/docs', (req, res) => {
const { studentId } = req.query;
if (!studentId) return res.status(400).json({ error: 'studentId required' });
const docs = db.prepare(`SELECT id, title, doc_key, submitted, submitted_at, parent_read, created_at, updated_at FROM documents WHERE student_id = ? ORDER BY updated_at DESC`).all(studentId);
res.json({ docs });
});
// Minimal blank DOCX (base64-encoded zip/OOXML)
const BLANK_DOCX = Buffer.from(
'UEsDBBQAAAAIADtxU13XeYTq8QAAALgBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH2QzU7DMBCE730Ky9cqccoBIZSkB36OwKE8wMreJFb9J69b2rdn00KREOVozXwz62nXB+/EHjPZGDq5qhspMOhobBg7+b55ru6koALBgIsBO3lEkut+0W6OCUkwHKiTUynpXinSE3qgOiYMrAwxeyj8zKNKoLcworppmlulYygYSlXmDNkvhGgfcYCdK+LpwMr5loyOpHg4e+e6TkJKzmoorKt9ML+Kqq+SmsmThyabaMkGqa6VzOL1jh/0lSfK1qB4g1xewLNRfcRslIl65xmu/0/649o4DFbjhZ/TUo4aiXh77+qL4sGG71+06jR8/wlQSwMEFAAAAAgAO3FTXSAbhuqyAAAALgEAAAsAAABfcmVscy8ucmVsc43Puw6CMBQG4J2naM4uBQdjDIXFmLAafICmPZRGeklbL7y9HRzEODie23fyN93TzOSOIWpnGdRlBQStcFJbxeAynDZ7IDFxK/nsLDJYMELXFs0ZZ57yTZy0jyQjNjKYUvIHSqOY0PBYOo82T0YXDE+5DIp6Lq5cId1W1Y6GTwPagpAVS3rJIPSyBjIsHv/h3ThqgUcnbgZt+vHlayPLPChMDB4uSCrf7TKzQHNKuorZvgBQSwMEFAAAAAgAO3FTXYwOhdB9AAAAnQAAABwAAAB3b3JkL19yZWxzL2RvY3VtZW50LnhtbC5yZWxzVcxBDsIgEIXhvacgs7egC2NMaXc9gNEDTOgIjTAQhhi9vSx1+fLnfeP8TlG9qMqW2cJhMKCIXV439hbut2V/BiUNecWYmSx8SGCeduOVIrb+kbAVUR1hsRBaKxetxQVKKEMuxL08ck3Y+qxeF3RP9KSPxpx0/TWgo/pPnb5QSwMEFAAAAAgAO3FTXf4sp2t6AQAA0wQAABEAAAB3b3JkL2RvY3VtZW50LnhtbKWUzW7DIAzH73uKiHtLMk3TFDXpYdWmXqZK3R6AEtqgAkZAk/XtB/nsNKnK2ktsBP75bzuwWH5LEVXMWA4qQ8k8RhFTFAquDhn6+nybvaDIOqIKIkCxDJ2ZRcv8YVGnBdCTZMpFnqBsWmuaodI5nWJsackksXPJqQELezenIDHs95wyXIMp8GOcxI2nDVBmrU/3SlRFLOpw8i8NNFN+cw9GEueX5oAlMceTnnm6Jo7vuODu7Nnxc4+BDJ2MSjvEbBAUQtJWUGf6CDMlbxuy6jrQZMSGCa8BlC25Hsu4leY3yx5SXSuikgINI0ie7pvBypDamxE4RX7RBknRKr9OTOIJEwmIIWKKhN85eyWScDUmvqk1l8093NfbdwMnPdL4fbS1Og6scC//wepmdFmavU/MtiTaXyBJ0/VBgSE74RX5jkfhj0T5QxT592IHxTm4zULn4bMxjdm6s2BRnVZEZOgjjFUgnC9wdyLYIdAy6jYGN0zcQ4PXP0f5D1BLAQIUAxQAAAAIADtxU13XeYTq8QAAALgBAAATAAAAAAAAAAAAAACAAQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAhQDFAAAAAgAO3FTXSAbhuqyAAAALgEAAAsAAAAAAAAAAAAAAIABIgEAAF9yZWxzLy5yZWxzUEsBAhQDFAAAAAgAO3FTXYwOhdB9AAAAnQAAABwAAAAAAAAAAAAAAIAB/QEAAHdvcmQvX3JlbHMvZG9jdW1lbnQueG1sLnJlbHNQSwECFAMUAAAACAA7cVNd/iyna3oBAADTBAAAEQAAAAAAAAAAAAAAgAG0AgAAd29yZC9kb2N1bWVudC54bWxQSwUGAAAAAAQABAADAQAAXQQAAAAA',
'base64'
);
app.post('/api/docs', async (req, res) => {
const { studentId, title = 'Untitled Document' } = req.body;
if (!studentId) return res.status(400).json({ error: 'studentId required' });
const key = randomUUID();
const filename = `${key}.docx`;
await writeFile(join(DOCS_DIR, filename), BLANK_DOCX);
const id = db.prepare(`INSERT INTO documents (student_id, title, doc_key, filename) VALUES (?, ?, ?, ?)`).run(studentId, title, key, filename).lastInsertRowid;
res.json({ id, key, title });
});
app.put('/api/docs/:id/title', (req, res) => {
const { title } = req.body;
db.prepare(`UPDATE documents SET title = ?, updated_at = datetime('now') WHERE id = ?`).run(title, req.params.id);
res.json({ ok: true });
});
app.post('/api/docs/:id/submit', (req, res) => {
const doc = db.prepare(`SELECT * FROM documents WHERE id = ?`).get(req.params.id);
if (!doc) return res.status(404).json({ error: 'Not found' });
db.prepare(`UPDATE documents SET submitted = 1, submitted_at = datetime('now'), updated_at = datetime('now') WHERE id = ?`).run(doc.id);
db.prepare(`INSERT INTO messages (student_id, sender, body) VALUES (?, 'student', ?)`).run(doc.student_id, `📄 Submitted document: "${doc.title}"`);
res.json({ ok: true });
});
app.delete('/api/docs/:id', async (req, res) => {
const doc = db.prepare(`SELECT * FROM documents WHERE id = ?`).get(req.params.id);
if (!doc) return res.status(404).json({ error: 'Not found' });
db.prepare(`DELETE FROM documents WHERE id = ?`).run(doc.id);
try { await unlink(join(DOCS_DIR, doc.filename)); } catch { /* already gone */ }
res.json({ ok: true });
});
// OnlyOffice save callback
app.post('/api/docs/callback/:key', express.json(), async (req, res) => {
const { status, url } = req.body;
// status 2 = ready to save, 6 = force-save
if (status === 2 || status === 6) {
const doc = db.prepare(`SELECT * FROM documents WHERE doc_key = ?`).get(req.params.key);
if (doc && url) {
try {
const r = await fetch(url);
const buf = Buffer.from(await r.arrayBuffer());
await writeFile(join(DOCS_DIR, doc.filename), buf);
db.prepare(`UPDATE documents SET updated_at = datetime('now') WHERE doc_key = ?`).run(req.params.key);
} catch { /* save failed silently */ }
}
}
res.json({ error: 0 });
});
// Admin: list submitted docs
app.get('/api/admin/docs', requirePin, (req, res) => {
const docs = db.prepare(`
SELECT d.id, d.title, d.doc_key, d.filename, d.submitted_at, d.parent_read, d.updated_at,
s.name AS student_name
FROM documents d JOIN students s ON s.id = d.student_id
WHERE d.submitted = 1
ORDER BY d.submitted_at DESC
`).all();
res.json({ docs });
});
app.put('/api/admin/docs/:id/read', requirePin, (req, res) => {
db.prepare(`UPDATE documents SET parent_read = 1 WHERE id = ?`).run(req.params.id);
res.json({ ok: true });
});
app.get('/api/admin/docs/config', requirePin, (req, res) => {
res.json({ onlyofficeUrl: ONLYOFFICE_URL, serverUrl: SERVER_URL });
});
app.get('/api/docs/config', (req, res) => {
res.json({ onlyofficeUrl: ONLYOFFICE_URL, serverUrl: SERVER_URL });
});
// Returns a fully-signed OnlyOffice editor config — parent comment-only view (PIN required)
app.get('/api/admin/docs/bykey/:key/editor-config', requirePin, (req, res) => {
const doc = db.prepare(`SELECT d.*, s.name AS student_name FROM documents d JOIN students s ON s.id = d.student_id WHERE d.doc_key = ?`).get(req.params.key);
if (!doc) return res.status(404).json({ error: 'Not found' });
const config = {
document: { fileType: 'docx', key: doc.doc_key, title: doc.title, url: `${SERVER_URL}/api/docs/file/${doc.filename}`, permissions: { edit: false, comment: true, download: true, print: true } },
editorConfig: { user: { id: 'parent', name: 'Parent' }, mode: 'edit', lang: 'en', customization: { logo: { visible: false }, compactHeader: true, toolbarNoTabs: true } },
type: 'desktop', height: '100%', width: '100%',
};
const token = jwtSign(config);
if (token) config.token = token;
res.json({ onlyofficeUrl: ONLYOFFICE_URL, config });
});
// Returns a fully-signed OnlyOffice editor config for a specific document
app.get('/api/docs/:id/editor-config', (req, res) => {
const doc = db.prepare(`SELECT d.*, s.name AS student_name FROM documents d JOIN students s ON s.id = d.student_id WHERE d.id = ?`).get(req.params.id);
if (!doc) return res.status(404).json({ error: 'Not found' });
const config = {
document: {
fileType: 'docx',
key: doc.doc_key,
title: doc.title,
url: `${SERVER_URL}/api/docs/file/${doc.filename}`,
permissions: { edit: true, download: true, print: true },
},
editorConfig: {
callbackUrl: `${SERVER_URL}/api/docs/callback/${doc.doc_key}`,
user: { id: String(doc.student_id), name: doc.student_name },
mode: 'edit',
lang: 'en',
customization: {
autosave: true,
forcesave: true,
logo: { visible: false },
compactHeader: true,
toolbarNoTabs: true,
},
},
type: 'desktop',
height: '100%',
width: '100%',
};
const token = jwtSign(config);
if (token) config.token = token;
res.json({ onlyofficeUrl: ONLYOFFICE_URL, config });
});
app.get('/api/health', (req, res) => res.json({ ok: true }));
app.get('/health', (req, res) => res.json({ ok: true })); app.get('/health', (req, res) => res.json({ ok: true }));
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;