diff --git a/.github/workflows/desktop-ci.yml b/.github/workflows/desktop-ci.yml index 130270bd..a21b3348 100644 --- a/.github/workflows/desktop-ci.yml +++ b/.github/workflows/desktop-ci.yml @@ -5,7 +5,7 @@ name: Desktop checks # server/src/shared/** code the desktop app imports from the server # this workflow and the release workflow # A change to only the server, the web app or the docs does not start this workflow. -# The release builds (Windows, macOS, Linux) are a separate workflow that runs on a tag or by hand. +# The release builds (Windows, macOS, Linux) are a separate workflow that runs only by hand. on: pull_request: diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 7f56a017..14ca4423 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -1,9 +1,16 @@ name: Desktop release -# Builds the Edorax desktop app for Windows, macOS and Linux and attaches the installers to a GitHub release. +# Builds the Edorax desktop app for Windows, macOS and Linux. # -# Make a release: git tag desktop-v0.1.0 && git push origin desktop-v0.1.0 -# Try the builds: run this workflow by hand (Actions tab). The installers are kept as workflow artifacts. +# Make a release: bump "version" in desktop/package.json, commit, then +# git tag desktop-v && git push origin desktop-v +# The tag must match the version in desktop/package.json. +# +# Or by hand: Actions tab -> "Desktop release" -> "Run workflow", then pick the branch. +# publish = false (default) build only; the installers are kept as workflow artifacts. +# publish = true also tag the commit as desktop-v +# (or reuse that tag if it was pushed for this commit) +# and attach the installers to a GitHub pre-release. # # The app carries no labs. It downloads them from the server after sign-in, so this workflow needs no secrets. # The installers are not code signed yet: Windows SmartScreen and macOS Gatekeeper will warn on first open. @@ -12,6 +19,11 @@ on: push: tags: ["desktop-v*"] workflow_dispatch: + inputs: + publish: + description: "Publish a GitHub pre-release (tag desktop-v) after building" + type: boolean + default: false permissions: contents: write @@ -43,6 +55,10 @@ jobs: node-version: 22 cache: pnpm cache-dependency-path: desktop/pnpm-lock.yaml + # The .deb and .rpm makers need these tools on the Linux runner. + - if: runner.os == 'Linux' + run: sudo apt-get update -qq && sudo apt-get install -y -qq fakeroot rpm + working-directory: . - run: pnpm install --frozen-lockfile # The desktop build imports shared code from server/src/shared, which needs the server's packages. - run: pnpm --dir ../server install --frozen-lockfile @@ -57,9 +73,26 @@ jobs: release: name: Publish release needs: make - if: startsWith(github.ref, 'refs/tags/desktop-v') + if: inputs.publish || startsWith(github.ref, 'refs/tags/desktop-v') runs-on: ubuntu-latest steps: + - uses: actions/checkout@v4 + - name: Work out the tag from desktop/package.json + id: tag + run: | + version=$(node -p "require('./desktop/package.json').version") + tag="desktop-v${version}" + if [ "${GITHUB_REF_TYPE}" = "tag" ] && [ "${GITHUB_REF_NAME}" != "${tag}" ]; then + echo "::error::Pushed tag ${GITHUB_REF_NAME} does not match desktop/package.json (${tag}). Bump the version or fix the tag." + exit 1 + fi + # A tag pushed by hand for this same commit is fine; a tag on another commit means the version was not bumped. + existing=$(git ls-remote --tags origin "refs/tags/${tag}^{}" "refs/tags/${tag}" | awk '{print $1}' | head -n1) + if [ -n "$existing" ] && [ "$existing" != "$GITHUB_SHA" ]; then + echo "::error::Tag ${tag} already exists on another commit. Bump the version in desktop/package.json first." + exit 1 + fi + echo "tag=${tag}" >> "$GITHUB_OUTPUT" - uses: actions/download-artifact@v4 with: path: dist @@ -68,7 +101,9 @@ jobs: run: find dist -type f | sort - uses: softprops/action-gh-release@v2 with: - name: Edorax desktop ${{ github.ref_name }} + tag_name: ${{ steps.tag.outputs.tag }} + target_commitish: ${{ github.sha }} + name: Edorax desktop ${{ steps.tag.outputs.tag }} # A first release stays a pre-release until it has been tried on all three systems. prerelease: true generate_release_notes: true @@ -78,3 +113,5 @@ jobs: dist/**/*.nupkg dist/**/RELEASES dist/**/*.zip + dist/**/*.deb + dist/**/*.rpm diff --git a/desktop/.gitignore b/desktop/.gitignore index 89626b92..fb5cedff 100644 --- a/desktop/.gitignore +++ b/desktop/.gitignore @@ -149,3 +149,6 @@ playwright-report/ # Shell labs are copied from Edorax Core by `pnpm sync:labs`; Core owns them. /labs/ + +# Slim copy of the built IDE that Forge ships (scripts/stage-ide.mjs). +/.ide-bundle/ diff --git a/desktop/forge.config.mts b/desktop/forge.config.mts index 992e485f..982c9b38 100644 --- a/desktop/forge.config.mts +++ b/desktop/forge.config.mts @@ -1,7 +1,10 @@ import { preparePty } from './scripts/prepare-pty.mjs'; +import { stageIde } from './scripts/stage-ide.mjs'; import type { ForgeConfig } from '@electron-forge/shared-types'; import { MakerSquirrel } from '@electron-forge/maker-squirrel'; import { MakerZIP } from '@electron-forge/maker-zip'; +import { MakerDeb } from '@electron-forge/maker-deb'; +import { MakerRpm } from '@electron-forge/maker-rpm'; import { VitePlugin } from '@electron-forge/plugin-vite'; import { FusesPlugin } from '@electron-forge/plugin-fuses'; import { FuseV1Options, FuseVersion } from '@electron/fuses'; @@ -11,6 +14,10 @@ const config: ForgeConfig = { generateAssets: async () => { await preparePty(); }, + // Ship only the built IDE (lib, plugins, package.json), not ide/node_modules and its sources. + prePackage: async () => { + await stageIde(); + }, }, packagerConfig: { asar: { unpack: '**/node_modules/node-pty/**' }, @@ -22,11 +29,13 @@ const config: ForgeConfig = { !file.startsWith('/node_modules/node-pty') && !file.startsWith('/node_modules/node-addon-api'), name: 'Edorax', + executableName: 'Edorax', icon: './assets/edorax', extraResource: [ './assets/edorax.png', './assets/edorax-dock.png', - './ide', + // Staged by scripts/stage-ide.mjs; still lands at resources/ide. + './.ide-bundle/ide', ], }, // TEMPORARY: node-pty's Electron rebuild needs a working Visual Studio install, which this machine @@ -35,9 +44,33 @@ const config: ForgeConfig = { rebuildConfig: { onlyModules: [] }, makers: [ new MakerSquirrel({}), - // Zip for every system. Linux uses the zip for now: the .deb and .rpm makers crash in this - // dependency layout (an old glob picks up the wrong minimatch), so they are left out until that is fixed. + // Zip for every system. new MakerZIP({}, ['darwin', 'win32', 'linux']), + // Debian and Ubuntu: `sudo apt install ./edorax__amd64.deb`. The package sets up the + // sandbox helper, the menu entry and the `edorax` command by itself. These makers take their + // settings directly (no `options` wrapper), and `electron-forge make --targets ...` ignores them. + new MakerDeb({ + name: 'edorax', + productName: 'Edorax', + genericName: 'Learning app', + bin: 'Edorax', + maintainer: 'Edorax ', + homepage: 'https://www.edorax.com', + categories: ['Education', 'Development'], + icon: './assets/edorax.png', + }), + // Fedora and RHEL: `sudo dnf install ./edorax-.x86_64.rpm`. + new MakerRpm({ + name: 'edorax', + productName: 'Edorax', + genericName: 'Learning app', + bin: 'Edorax', + homepage: 'https://www.edorax.com', + categories: ['Education', 'Development'], + icon: './assets/edorax.png', + // rpm 4.20+ (current ubuntu-latest) breaks the stock template's relative `cp -r usr/*`. + specTemplate: './packaging/rpm.spec.ejs', + }), ], plugins: [ new VitePlugin({ diff --git a/desktop/package.json b/desktop/package.json index bdc51fee..ae12062a 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -1,7 +1,7 @@ { "name": "desktop", "productName": "Edorax", - "version": "0.1.0", + "version": "0.1.2", "private": true, "description": "Edorax desktop learning workspace", "keywords": [], @@ -21,7 +21,7 @@ "sync:labs": "node scripts/sync-labs.mjs", "lint:fix": "oxlint --fix && oxfmt --write", "typecheck": "tsc --noEmit", - "test": "tsx --test tests/api.test.ts tests/labs.test.ts tests/local-runtime.test.ts tests/ide.test.ts tests/shell-labs.test.ts tests/shell-labs-catalog.test.ts tests/guided-labs.test.ts tests/docker-setup.test.ts tests/app-version.test.ts tests/update-service.test.ts", + "test": "tsx --test tests/api.test.ts tests/labs.test.ts tests/local-runtime.test.ts tests/ide.test.ts tests/shell-labs.test.ts tests/shell-labs-catalog.test.ts tests/guided-labs.test.ts tests/docker-setup.test.ts tests/app-version.test.ts tests/update-service.test.ts tests/lab-progress.test.ts", "test:ui": "playwright test", "dev:ui": "vite --config vite.renderer.config.mts --host 127.0.0.1 --port 5179 --strictPort", "test:labs": "tsx --test tests/labs.integration.test.ts tests/shell-labs.integration.test.ts", @@ -78,6 +78,7 @@ }, "overrides": { "dompurify": "3.4.17", - "minimatch": "^11.0.5" + "minimatch": "^11.0.5", + "glob@7>minimatch": "^3.1.2" } } diff --git a/desktop/packaging/rpm.spec.ejs b/desktop/packaging/rpm.spec.ejs new file mode 100644 index 00000000..9e3203c6 --- /dev/null +++ b/desktop/packaging/rpm.spec.ejs @@ -0,0 +1,64 @@ +<% /* Copy of electron-installer-redhat 4.0.0 resources/spec.ejs. Only change: %install copies from %{_topdir}/BUILD/usr + instead of a relative usr/, because rpm 4.20+ runs %install from BUILD/--build. */ %> +%define _binary_payload w<%= compressionLevel %>.xzdio + +%if "%{_host_cpu}" != "%{_target_cpu}" +%global __strip /bin/true +%endif + +Name: <%= name %> +Version: <%= version %> +Release: <%= revision %>%{?dist} +<% if (description) { print(`Summary: ${description}\n`) } +%> +<% if (license) { print(`License: ${license}\n`) } +if (homepage) { print(`URL: ${homepage}\n`) } +if (license || homepage) { print('\n') } + +%>Requires: <%= requires.join(', ') %> +AutoReqProv: no + +<% if (productDescription) { +%>%description +<% print(productDescription) +print('\n\n\n') } + + +%>%install +mkdir -p %{buildroot}/usr/ +cp <%= process.platform === 'darwin' ? '-R' : '-r' %> %{_topdir}/BUILD/usr/* %{buildroot}/usr/ + + +%files +/usr/bin/<%= name %> +/usr/lib/<%= name %>/ +/usr/share/applications/<%= name %>.desktop +/usr/share/doc/<%= name %>/ +<% if (_.isObject(icon)) { + _.forEach(icon, function (path, resolution) { + %>/usr/share/icons/hicolor/<%= resolution %>/apps/<%= name %><%= resolution === 'symbolic' ? '-symbolic' : '' %>.<%= ['scalable', 'symbolic'].includes(resolution) ? 'svg' : 'png' %> +<% }) } else { + %>/usr/share/pixmaps/<%= name %>.png +<% } %> + +<% if (pre) { + %>%pre +<% print(pre) +if (preun || post || postun) print('\n\n\n') } + + +%><% if (preun) { + %>%preun +<% print(preun) +if (post || postun) print('\n\n\n') } + + +%><% if (post) { + %>%post +<% print(post) +if (postun) print('\n\n\n') } + + +%><% if (postun) { + %>%postun +<% print(postun) } %> diff --git a/desktop/pnpm-lock.yaml b/desktop/pnpm-lock.yaml index 73bf1de7..f6100a2c 100644 --- a/desktop/pnpm-lock.yaml +++ b/desktop/pnpm-lock.yaml @@ -7,6 +7,7 @@ settings: overrides: dompurify: 3.4.17 minimatch: ^11.0.5 + glob@7>minimatch: ^3.1.2 importers: @@ -1205,6 +1206,9 @@ packages: bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} @@ -1218,6 +1222,9 @@ packages: bl@4.1.0: resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + brace-expansion@1.1.22: + resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==} + brace-expansion@5.0.12: resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==} engines: {node: 20 || >=22} @@ -1319,6 +1326,9 @@ packages: resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} engines: {node: ^12.20.0 || >=14} + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + convert-to-spaces@2.0.1: resolution: {integrity: sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -2062,6 +2072,9 @@ packages: resolution: {integrity: sha512-snPlVppFcYWfLLFQGhDxUyBcHNtMlWmn3jtj7pEaO+DP8pqL0IvAzXhMYmn1z9ASNtgmwLBdFxSf4tMUB0OTKA==} engines: {node: 20 || >=22} + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -3623,6 +3636,9 @@ snapshots: bail@2.0.2: {} + balanced-match@1.0.2: + optional: true + balanced-match@4.0.4: {} base64-js@1.5.1: {} @@ -3637,6 +3653,12 @@ snapshots: inherits: 2.0.4 readable-stream: 3.6.2 + brace-expansion@1.1.22: + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + optional: true + brace-expansion@5.0.12: dependencies: balanced-match: 4.0.4 @@ -3722,6 +3744,9 @@ snapshots: commander@9.5.0: {} + concat-map@0.0.1: + optional: true + convert-to-spaces@2.0.1: {} cpu-features@0.0.10: @@ -4054,7 +4079,7 @@ snapshots: fs.realpath: 1.0.0 inflight: 1.0.6 inherits: 2.0.4 - minimatch: 11.0.5 + minimatch: 3.1.5 once: 1.4.0 path-is-absolute: 1.0.1 optional: true @@ -4761,6 +4786,11 @@ snapshots: '@isaacs/nonrecursive-glob-match': 1.1.0 brace-expansion: 5.0.12 + minimatch@3.1.5: + dependencies: + brace-expansion: 1.1.22 + optional: true + minimist@1.2.8: optional: true diff --git a/desktop/pnpm-workspace.yaml b/desktop/pnpm-workspace.yaml index 447fce2d..af77e1fc 100644 --- a/desktop/pnpm-workspace.yaml +++ b/desktop/pnpm-workspace.yaml @@ -10,3 +10,4 @@ allowBuilds: overrides: dompurify: 3.4.17 minimatch: ^11.0.5 + "glob@7>minimatch": ^3.1.2 diff --git a/desktop/scripts/stage-ide.mjs b/desktop/scripts/stage-ide.mjs new file mode 100644 index 00000000..37837827 --- /dev/null +++ b/desktop/scripts/stage-ide.mjs @@ -0,0 +1,39 @@ +// Copies only what the Theia IDE needs at runtime into .ide-bundle/ide, which Forge ships as a +// resource. The production build bundles the backend (lib/backend/main.js, with its native +// binaries in lib/backend/native) and the frontend (lib/frontend), so ide/node_modules, src-gen, +// the build scripts and the lockfiles are not needed in the installed app. +import { cp, rm, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const desktop = fileURLToPath(new URL('..', import.meta.url)); +const source = path.join(desktop, 'ide'); +const target = path.join(desktop, '.ide-bundle', 'ide'); + +const keep = ['lib', 'plugins', 'package.json']; +// Source maps are only useful when debugging the IDE itself. +const skip = (file) => file.endsWith('.map'); + +export async function stageIde() { + await stat(path.join(source, 'lib', 'backend', 'main.js')).catch(() => { + throw new Error('The IDE is not built. Run `pnpm ide:setup` (or `pnpm ide:build`) first.'); + }); + await rm(target, { recursive: true, force: true }); + for (const entry of keep) { + const from = path.join(source, entry); + // plugins/ only exists after `pnpm --dir ide run download:plugins`; the app creates it if missing. + if (!(await stat(from).catch(() => null))) { + console.warn(`stage-ide: skipping missing ide/${entry}`); + continue; + } + await cp(from, path.join(target, entry), { + recursive: true, + filter: (file) => !skip(file), + }); + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { + await stageIde(); + console.log(`Staged IDE runtime at ${target}`); +} diff --git a/desktop/src/domain/leaderboard.ts b/desktop/src/domain/leaderboard.ts index d5b5caf9..290dfda1 100644 --- a/desktop/src/domain/leaderboard.ts +++ b/desktop/src/domain/leaderboard.ts @@ -48,13 +48,46 @@ export function isLeaderboardSelection(value: unknown): value is LeaderboardSele return categoryOk && scopeOk && courseOk; } -export const LEAGUE_TIER_ORDER: LeagueTier[] = ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'DIAMOND']; +export const LEAGUE_TIER_ORDER: LeagueTier[] = ['BRONZE', 'SILVER', 'GOLD', 'PLATINUM', 'COBALT', 'JADE', 'QUARTZ', 'AURORA', 'ZENITH', 'DIAMOND']; + +export const LEAGUE_WEEKLY_GOALS: Record = { + BRONZE: 100, + SILVER: 200, + GOLD: 400, + PLATINUM: 700, + COBALT: 1_000, + JADE: 1_400, + QUARTZ: 1_900, + AURORA: 2_500, + ZENITH: 3_200, + DIAMOND: 4_000, +}; + +export const LEAGUE_TIER_MARKS: Record = { + BRONZE: 'Br', + SILVER: 'Si', + GOLD: 'Go', + PLATINUM: 'Pt', + COBALT: 'Co', + JADE: 'Ja', + QUARTZ: 'Qz', + AURORA: 'Au', + ZENITH: 'Ze', + DIAMOND: 'Di', +}; + +export const LEAGUE_PROMOTION_PERCENT = 0.1; export const LEAGUE_TIER_LABELS: Record = { BRONZE: 'Bronze', SILVER: 'Silver', GOLD: 'Gold', PLATINUM: 'Platinum', + COBALT: 'Cobalt', + JADE: 'Jade', + QUARTZ: 'Quartz', + AURORA: 'Aurora', + ZENITH: 'Zenith', DIAMOND: 'Diamond', }; diff --git a/desktop/src/domain/shell-labs.ts b/desktop/src/domain/shell-labs.ts index 029ed689..cb9e9c39 100644 --- a/desktop/src/domain/shell-labs.ts +++ b/desktop/src/domain/shell-labs.ts @@ -314,6 +314,10 @@ export interface ShellLabsAPI { list(): Promise; /** Asks the server for newer labs and saves them on this computer. Never rejects: a failure comes back as a plain message. */ refresh(): Promise; + /** Passed steps per lab, kept on the learner's account. Null when signed out or offline. Never rejects. */ + progress(): Promise | null>; + /** Saves the passed steps of one lab on the account. False when it could not. Never rejects. */ + saveProgress(slug: string, steps: string[]): Promise; view(slug: string): Promise; status(slug: string): Promise; start(slug: string): Promise; diff --git a/desktop/src/ide/runtime.ts b/desktop/src/ide/runtime.ts index 7167a149..b11b6722 100644 --- a/desktop/src/ide/runtime.ts +++ b/desktop/src/ide/runtime.ts @@ -40,7 +40,14 @@ export class TheiaRuntime { : process.platform === 'win32' ? 'node.exe' : 'node'; - const main = path.join(this.directory, 'src-gen/backend/main.js'); + // The production build bundles the backend into lib/backend/main.js, which runs without + // node_modules. src-gen/backend/main.js is the unbundled entry and needs ide/node_modules. + const bundledMain = path.join(this.directory, 'lib/backend/main.js'); + const sourceMain = path.join(this.directory, 'src-gen/backend/main.js'); + const main = await access(bundledMain).then( + () => bundledMain, + () => sourceMain, + ); try { await access(main); } catch { diff --git a/desktop/src/main.ts b/desktop/src/main.ts index 33de5307..e99bd342 100644 --- a/desktop/src/main.ts +++ b/desktop/src/main.ts @@ -764,6 +764,21 @@ else { requireRenderer(event); return refreshLabsFromServer(); }); + // Progress lives on the learner's account. Both calls swallow failures: progress is also kept on + // this computer, so the labs work offline and the next sync catches the account up. + ipcMain.handle('shell-labs:progress', async (event) => { + requireRenderer(event); + if (!previewClient.sessionSnapshot()) return null; + const result = await previewClient.request('/api/v1/shell-labs/progress', 'GET'); + const data = result.ok ? (result.data as { progress?: unknown } | null)?.progress : null; + return data && typeof data === 'object' && !Array.isArray(data) ? data : null; + }); + ipcMain.handle('shell-labs:save-progress', async (event, slug, steps) => { + requireRenderer(event); + if (typeof slug !== 'string' || !Array.isArray(steps) || !previewClient.sessionSnapshot()) return false; + const result = await previewClient.request(`/api/v1/shell-labs/progress/${encodeURIComponent(slug)}`, 'PUT', { steps }); + return result.ok; + }); ipcMain.handle('shell-labs:view', (event, slug) => { requireRenderer(event); const lab = getShellLab(slug); diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts index 91c74091..f6677013 100644 --- a/desktop/src/preload.ts +++ b/desktop/src/preload.ts @@ -68,6 +68,8 @@ const api: DesktopAPI = { }, list: () => ipcRenderer.invoke('shell-labs:list'), refresh: () => ipcRenderer.invoke('shell-labs:refresh'), + progress: () => ipcRenderer.invoke('shell-labs:progress'), + saveProgress: (slug, steps) => ipcRenderer.invoke('shell-labs:save-progress', slug, steps), view: (slug) => ipcRenderer.invoke('shell-labs:view', slug), status: (slug) => ipcRenderer.invoke('shell-labs:status', slug), start: (slug) => ipcRenderer.invoke('shell-labs:start', slug), diff --git a/desktop/src/ui/leaderboard/LeaderboardPage.tsx b/desktop/src/ui/leaderboard/LeaderboardPage.tsx index bd460efc..43de5838 100644 --- a/desktop/src/ui/leaderboard/LeaderboardPage.tsx +++ b/desktop/src/ui/leaderboard/LeaderboardPage.tsx @@ -93,7 +93,8 @@ export function LeaderboardPage({ initialSelection }: { initialSelection?: Leade if (!view || view.status !== 'ready') return; const key = `${view.category}|${view.scope}|${view.courseId ?? 'global'}`; const onPodium = view.you.rank >= 1 && view.you.rank <= 3 && view.you.score > 0; - const promoted = view.league?.lastWeek?.outcome === 'PROMOTED'; + const outcome = view.league?.lastWeek?.outcome; + const promoted = outcome === 'PROMOTED' || outcome === 'PROMOTED_TARGET' || outcome === 'PROMOTED_BOTH'; if ((!onPodium && !promoted) || celebrated.current === key) return; celebrated.current = key; const timer = window.setTimeout(() => { diff --git a/desktop/src/ui/leaderboard/LeaderboardParts.tsx b/desktop/src/ui/leaderboard/LeaderboardParts.tsx index 4d73b3c3..5ae8926f 100644 --- a/desktop/src/ui/leaderboard/LeaderboardParts.tsx +++ b/desktop/src/ui/leaderboard/LeaderboardParts.tsx @@ -1,9 +1,12 @@ import type { ReactNode } from 'react'; import { LEAGUE_TIER_LABELS, + LEAGUE_TIER_ORDER, + LEAGUE_WEEKLY_GOALS, formatNumber, formatScore, initials, + LEAGUE_PROMOTION_PERCENT, nextLeagueTier, prevLeagueTier, resetLabel, @@ -28,6 +31,39 @@ export function Pill({ tone, children }: { tone: keyof typeof PILL; children: Re return {children}; } +const BADGE_COLORS: Record = { + BRONZE: '#c87945', + SILVER: '#b7c4d2', + GOLD: '#f0b936', + PLATINUM: '#91a8b8', + COBALT: '#3276c8', + JADE: '#35a77d', + QUARTZ: '#a78bda', + AURORA: '#5fb7bd', + ZENITH: '#665ed0', + DIAMOND: '#55aee8', +}; + +export function LeagueBadge({ tier }: { tier: LeagueTier }) { + const colors = BADGE_COLORS[tier]; + return ( + + {LEAGUE_TIER_LABELS[tier]} League + + {tier === 'BRONZE' ? : null} + {tier === 'SILVER' ? : null} + {tier === 'GOLD' ? : null} + {tier === 'PLATINUM' ? : null} + {tier === 'COBALT' ? : null} + {tier === 'JADE' ? : null} + {tier === 'QUARTZ' ? : null} + {tier === 'AURORA' ? : null} + {tier === 'ZENITH' ? : null} + {tier === 'DIAMOND' ? : null} + + ); +} + export function Rank({ rank, highlight }: { rank: number; highlight?: boolean }) { const tone = MEDAL[rank] ?? (highlight ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground'); return ( @@ -121,14 +157,19 @@ function LeagueOutcome({ league }: { league: LeagueInfo }) { const last = league.lastWeek; if (!last) return null; const box = 'rounded-xl border px-4 py-2.5 text-sm font-medium'; - if (last.outcome === 'PROMOTED') { + if (last.outcome === 'PROMOTED' || last.outcome === 'PROMOTED_TARGET' || last.outcome === 'PROMOTED_BOTH') { const to = nextLeagueTier(last.fromTier); + const path = last.outcome === 'PROMOTED_TARGET' ? 'by reaching your weekly goal' : last.outcome === 'PROMOTED_BOTH' ? 'by rank and your weekly goal' : 'by rank'; return (

- Promoted to {to ? LEAGUE_TIER_LABELS[to] : 'a higher league'} last week. + Promoted to {to ? LEAGUE_TIER_LABELS[to] : 'a higher league'} last week {path}.

); } + if (last.outcome === 'RECOVERY_HELD' || last.outcome === 'SHIELD_HELD') { + const protection = last.outcome === 'RECOVERY_HELD' ? 'recovery quest' : 'League Shield'; + return

Your {protection} protected your league place last week.

; + } if (last.outcome === 'DEMOTED') { const to = prevLeagueTier(last.fromTier); return ( @@ -165,6 +206,51 @@ export function LeagueCard({ const isDemoting = demoteCount > 0 && league.rank >= league.demotionZone && Boolean(prev); const best = bestScore ?? 0; const label = 'This week compared with your best week'; + const currentIndex = LEAGUE_TIER_ORDER.indexOf(league.tier); + + const journey = ( +
+
+
+

League journey

+

Your weekly path

+
+ {currentIndex + 1} of {LEAGUE_TIER_ORDER.length} +
+
    + {LEAGUE_TIER_ORDER.map((tier, index) => { + const current = tier === league.tier; + const nextTier = tier === next; + const past = currentIndex > index; + return ( +
  1. +
    + 0 && past ? 'bg-primary' : 'bg-border'}`} /> + + + + +
    + {LEAGUE_TIER_LABELS[tier]} + {current ? 'You are here' : nextTier ? 'Next' : past ? 'Complete' : 'Upcoming'} +
  2. + ); + })} +
+
+
+

Current league

+

{LEAGUE_TIER_LABELS[league.tier]} · {formatNumber(league.goal)} XP goal

+

Reach the goal or finish in the top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}%.

+
+
+

Next league

+

{next ? `${LEAGUE_TIER_LABELS[next]} · ${formatNumber(LEAGUE_WEEKLY_GOALS[next])} XP goal` : 'Diamond · final league'}

+

{next ? `You are one tier away from ${LEAGUE_TIER_LABELS[next]}.` : 'You have reached the top of the league journey.'}

+
+
+
+ ); return (
@@ -191,6 +277,8 @@ export function LeagueCard({ + {journey} +
@@ -199,8 +287,10 @@ export function LeagueCard({
{next && promoteCount > 0 ? (

- Top {promoteCount} promote to {LEAGUE_TIER_LABELS[next]} + Top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}% ({promoteCount} {promoteCount === 1 ? 'spot' : 'spots'}) or the weekly goal promotes to {LEAGUE_TIER_LABELS[next]}

+ ) : next && league.goal > 0 ? ( +

Reach the weekly goal to promote

) : prev && demoteCount > 0 ? (

Bottom {demoteCount} demote to {LEAGUE_TIER_LABELS[prev]} @@ -212,6 +302,31 @@ export function LeagueCard({ )}

+ {league.goal > 0 ? ( +
+
+ + {league.goalMet ? 'Weekly goal met' : 'Achievement promotion'} + + {formatNumber(score)} / {formatNumber(league.goal)} XP +
+ +

Reach your goal or finish in the top {Math.round(LEAGUE_PROMOTION_PERCENT * 100)}%. Both paths unlock the next league.

+
+ ) : null} + + {league.recovery ? ( +
+
+ Recovery quest + + {league.recovery.completed ? 'Complete' : 'In progress'} + +
+

Complete {league.recovery.chapterTarget} chapter and earn {formatNumber(league.recovery.xpTarget)} XP to protect against one demotion.

+
+ ) : null} + {best > 0 ? (
diff --git a/desktop/src/ui/shell-labs/ShellLabs.tsx b/desktop/src/ui/shell-labs/ShellLabs.tsx index fcb2e2ef..8e7c669b 100644 --- a/desktop/src/ui/shell-labs/ShellLabs.tsx +++ b/desktop/src/ui/shell-labs/ShellLabs.tsx @@ -1,8 +1,8 @@ import { useEffect, useState } from 'react'; -import { ArrowLeft, Clock, Terminal } from 'lucide-react'; +import { ArrowLeft, CheckCircle2, Clock, Terminal } from 'lucide-react'; import { SHELL_TOPICS, type ShellLabSummary, type ShellTopic } from '../../domain/shell-labs'; import { ShellLabPage } from './ShellLabPage'; -import { errorText, passedSteps } from './progress'; +import { errorText, passedSteps, syncPassedSteps } from './progress'; /** * Labs that need a real kernel of their own (systemd as PID 1, mount and loop devices). They arrive @@ -31,6 +31,12 @@ export function ShellLabs({ onBack, topic: only }: { onBack: () => void; topic?: .catch((reason: unknown) => setError(errorText(reason))); }, []); + // Progress also lives on the account: bring in steps done on another computer or before a reinstall. + const [, setSynced] = useState(0); + useEffect(() => { + void syncPassedSteps().then((changed) => changed && setSynced((n) => n + 1)); + }, []); + if (open) return setOpen(null)} />; return ( @@ -90,9 +96,13 @@ export function ShellLabs({ onBack, topic: only }: { onBack: () => void; topic?: {lab.minutes} min - - {done ? `${Math.min(done, lab.steps)} of ${lab.steps} steps done` : `${lab.steps} steps`} - + {done >= lab.steps ? ( + + Completed + + ) : ( + {done ? `${done} of ${lab.steps} steps done` : `${lab.steps} steps`} + )} diff --git a/desktop/src/ui/shell-labs/progress.ts b/desktop/src/ui/shell-labs/progress.ts index 4a8481ed..630c8604 100644 --- a/desktop/src/ui/shell-labs/progress.ts +++ b/desktop/src/ui/shell-labs/progress.ts @@ -17,7 +17,7 @@ export function passedSteps(slug: string): string[] { return Array.isArray(steps) ? steps.filter((step) => typeof step === 'string') : []; } -export function savePassedSteps(slug: string, steps: string[]) { +function writeLocal(slug: string, steps: string[]) { try { const all = read(); if (steps.length) all[slug] = steps; @@ -28,6 +28,39 @@ export function savePassedSteps(slug: string, steps: string[]) { } } +/** Saves on this computer and, in the background, on the learner's account. */ +export function savePassedSteps(slug: string, steps: string[]) { + writeLocal(slug, steps); + void window.buildment?.shellLabs?.saveProgress?.(slug, steps).catch(() => {}); +} + +/** + * Joins this computer's progress with the account's, so a reinstall or a second computer still shows + * what was done. A step done on either side stays done. Steps found only on this computer are sent + * to the account. Returns true when something changed here. Never rejects. + */ +export async function syncPassedSteps(): Promise { + try { + const remote = await window.buildment?.shellLabs?.progress?.(); + if (!remote) return false; + let changed = false; + const local = read(); + for (const slug of new Set([...Object.keys(local), ...Object.keys(remote)])) { + const mine = Array.isArray(local[slug]) ? local[slug] : []; + const theirs = Array.isArray(remote[slug]) ? remote[slug].filter((step) => typeof step === 'string') : []; + const joined = [...new Set([...theirs, ...mine])]; + if (joined.length > mine.length) { + writeLocal(slug, joined); + changed = true; + } + if (joined.length > theirs.length) void window.buildment.shellLabs.saveProgress(slug, joined).catch(() => {}); + } + return changed; + } catch { + return false; + } +} + /** IPC errors arrive as "Error invoking remote method 'x': Error: message". Keep the message. */ export function errorText(error: unknown) { const text = error instanceof Error ? error.message : String(error); diff --git a/desktop/tests/lab-progress.test.ts b/desktop/tests/lab-progress.test.ts new file mode 100644 index 00000000..4f52e09b --- /dev/null +++ b/desktop/tests/lab-progress.test.ts @@ -0,0 +1,73 @@ +import assert from 'node:assert/strict'; +import { beforeEach, describe, it } from 'node:test'; +import { passedSteps, savePassedSteps, syncPassedSteps } from '../src/ui/shell-labs/progress'; + +// The progress helpers run in the page; give them a tiny localStorage and a fake app bridge. +const store = new Map(); +const g = globalThis as Record; +g.localStorage = { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => void store.set(key, value), +}; + +let remote: Record | null = null; +let sent: { slug: string; steps: string[] }[] = []; +g.window = { + buildment: { + shellLabs: { + progress: async () => remote, + saveProgress: async (slug: string, steps: string[]) => { + sent.push({ slug, steps }); + return true; + }, + }, + }, +}; + +beforeEach(() => { + store.clear(); + remote = {}; + sent = []; +}); + +describe('lab progress sync', () => { + it('shows steps that exist only on the account', async () => { + remote = { 'linux-102': ['a', 'b'], 'docker-first-container': ['x'] }; + assert.equal(await syncPassedSteps(), true); + assert.deepEqual(passedSteps('linux-102'), ['a', 'b']); + assert.deepEqual(passedSteps('docker-first-container'), ['x']); + assert.deepEqual(sent, []); + }); + + it('sends steps that exist only on this computer to the account', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a', 'b'] })); + assert.equal(await syncPassedSteps(), false); + assert.deepEqual(sent, [{ slug: 'linux-101', steps: ['a', 'b'] }]); + }); + + it('keeps a step done on either side', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a'] })); + remote = { 'linux-101': ['b'] }; + assert.equal(await syncPassedSteps(), true); + assert.deepEqual(passedSteps('linux-101').sort(), ['a', 'b']); + assert.deepEqual(sent[0].steps.sort(), ['a', 'b']); + }); + + it('changes nothing when signed out or offline', async () => { + store.set('edorax:shell-labs:v1', JSON.stringify({ 'linux-101': ['a'] })); + remote = null; + assert.equal(await syncPassedSteps(), false); + assert.deepEqual(passedSteps('linux-101'), ['a']); + assert.deepEqual(sent, []); + }); + + it('saving a lab also saves it on the account, and a reset sends an empty list', () => { + savePassedSteps('linux-101', ['a']); + savePassedSteps('linux-101', []); + assert.deepEqual(sent, [ + { slug: 'linux-101', steps: ['a'] }, + { slug: 'linux-101', steps: [] }, + ]); + assert.deepEqual(passedSteps('linux-101'), []); + }); +}); diff --git a/docs/12-course-variants-and-publishing.mdx b/docs/12-course-variants-and-publishing.mdx index e343cff9..8705a8a6 100644 --- a/docs/12-course-variants-and-publishing.mdx +++ b/docs/12-course-variants-and-publishing.mdx @@ -89,6 +89,21 @@ module sequence, including every variant-only module. `omitLessonKeys` removes inherited lessons from retained shared modules. New graded work gets separate progress. Keep keys stable and review the effect on every variant before approval. +A course without lesson keys removes a lesson by its public address, the last part of +its reader link: + +```yaml +remove: + lessons: + - slug: 39-5-the-old-summary + redirectTo: 39-5-part-1-the-bucket +``` + +`redirectTo` is optional. With it, an old link to the removed lesson opens the named +lesson instead of a "not found" page. The target must be in the course after the publish. +Leave the entry in `course.yaml`: a lesson that an earlier release already removed is +skipped, and the redirect is kept. Leaving a lesson file out of the package never removes it. + The older `multi-vendor-marketplace` source folder now has a manifest with stable keys for all 385 lessons. Its `repositoryTargetSlug` points to the existing `freshmarket-multi-vendor-marketplace-v3` database course. The publisher requires diff --git a/docs/14-gamification.mdx b/docs/14-gamification.mdx index 6899dac3..14f6ae77 100644 --- a/docs/14-gamification.mdx +++ b/docs/14-gamification.mdx @@ -144,18 +144,27 @@ The `/leaderboard` page serves several boards from one read, | Streak | `streak` | `global` | current active-day streak, counted in each learner's own timezone | - **Leagues.** The global weekly board is a league. Every opted-in learner sits in a tier - (`User.leagueTier`, Bronze → Diamond; new learners start at Bronze). At the Monday 00:00 UTC - reset (`POST /api/v1/jobs/leaderboard-reset`, cron-secret protected), the closed week's global XP - ranks each tier: the top 10% promote, the bottom 20% demote, everyone else holds. Diamond has - nothing to promote to, Bronze nothing to demote from, and leagues under 10 learners have no - demotion zone. The reset is idempotent (advisory lock, one `LeaguePlacement` row per learner per - week) and excludes learners who already opted out or hid game elements. + (`User.leagueTier`, Bronze → Diamond through Cobalt, Jade, Quartz, Aurora and Zenith; new learners + start at Bronze). At the Monday 00:00 UTC + reset (`POST /api/v1/jobs/leaderboard-reset`, cron-secret protected), a learner can promote in + either of two ways: finish in the top 10% of a tier with at least five eligible learners, or reach + the tier's published weekly XP goal. The fixed goals are Bronze 100, Silver 200, Gold 400, + Platinum 700, Cobalt 1,000, Jade 1,400, Quartz 1,900, Aurora 2,500, Zenith 3,200 and Diamond + 4,000 XP. Both paths unlock one tier only. Diamond has nothing to + promote to, Bronze nothing to demote from, and leagues under 10 learners have no demotion zone. + The reset is idempotent (advisory lock, one `LeaguePlacement` row per learner per week) and + excludes learners who already opted out or hid game elements. +- **Recovery.** A learner in the demotion zone can complete the recovery quest by completing one + chapter and earning 50 XP in the closed week. Recovery protection holds the learner's tier before + a League Shield is consumed. Neither protection grants promotion, and only one protection applies + to a settlement. - **Recognition boards.** All-time, speed and streak carry no promotion stakes — they exist so different strengths shine. Podium, neighbourhood and personal-best bars work as on the course board. -- **What a learner sees.** Per board: a league card (tier, rank, promotion and demotion zones, last - week's outcome), an animated top-three podium, the learners nearest their rank, and last week's - winners. Reaching a podium or getting promoted fires confetti and the celebration sound. +- **What a learner sees.** Per board: a league card (tier, rank, top-10-percent zone, published goal, + recovery progress, last week's outcome), an animated top-three podium, the learners nearest their + rank, and last week's winners. Reaching a podium or getting promoted fires confetti and the + celebration sound. - The per-course board keeps its own endpoint, contract and settlement logic; the hub delegates to it for `weekly_xp` + `course`, so the dashboard card and the old contract are untouched. diff --git a/docs/gamification-todo.md b/docs/gamification-todo.md index d5e26735..d0a57d87 100644 --- a/docs/gamification-todo.md +++ b/docs/gamification-todo.md @@ -4,19 +4,18 @@ Source: `Buildment_Gamification_Design_Concepts.pdf` concept book + researched m (Duolingo leagues/personal-records, PUBG seasonal tiers, Pluralsight mastery-gating) + Devmaxx competitor signal. -## Status vs upstream (2026-10-31) +## Status vs upstream (2026-11-15) - **Phase 1 (league) largely landed upstream** in PR #161 `feat(leaderboard): multi-category hub with - weekly leagues`: cross-course weekly league, Bronze→Diamond tiers, top 10% promote / bottom 20% - demote at Monday 00:00 UTC, per-course board kept, hub UI + categories, privacy, "beat your best". + weekly leagues`: cross-course weekly league, ten tiers from Bronze to Diamond, top-10-percent or fixed-goal promotion / + bottom 20% demotion at Monday 00:00 UTC, per-course board kept, hub UI + categories, privacy, + "beat your best". Files: `services/gamification/league.ts`, `leaderboard-categories.ts`, `shared/gamification/leagues.ts`, migration `leaderboard_leagues`. -- **Two divergences from this plan's choices were shipped:** +- **One divergence from this plan's choices remains:** - Grouping is **tier-based (percentile)**, not the planned ~30-person random same-pace cohorts (they explicitly chose tiers over cohorts). - - **Achievement promotion was not built** — only competitive percentile (top 10% / bottom 20%); - no escalating XP-target promotion path. -- **Still open:** Phase 2 career ladder, Phase 3 Build Credits/marketplace, Phase 4 daily/monthly/ - recovery/mascot-loading + a dedicated **My Records** surface, Phase 5 share/experiments. +- **Still open:** Phase 4 daily/monthly/recap/notifications and the loading companion, plus Phase 5 + experiments. ## Core decisions (locked) - **Two layers**: a short-horizon **league** + a permanent **career ladder**, plus a **rewards** loop. @@ -50,22 +49,23 @@ competitor signal. - **My Records**: read-only, in scope. ## Phase 0 — Foundation -- [ ] Confirm the two-layer model as source of truth (decisions above are the locked scope) -- [ ] Feature-flag inventory: `GAMIFICATION_LEAGUE_TIERS`, `GAMIFICATION_CAREER_LEVELS`, - `GAMIFICATION_CREDITS`, `GAMIFICATION_RECOVERY` (each `null` when off) +- [x] Confirm the two-layer model as source of truth (decisions above are the locked scope) +- [x] Feature-flag inventory: `GAMIFICATION_LEAGUE_TIERS`, `GAMIFICATION_CAREER_LEVELS`, + `GAMIFICATION_CREDITS`, `GAMIFICATION_RECOVERY` (each `false` when off) ## Phase 1 — League (cross-course, Duolingo-style) — ✅ MAJORITY LANDED UPSTREAM (PR #161) - [x] **Landed:** cross-course weekly league (global XP across all courses), weekly reset Monday 00:00 - UTC, tiers (Bronze→Diamond), top 10% / bottom 20% promotion & demotion, per-course board + UTC, ten tiers from Bronze through Diamond, top-10-percent or fixed-goal / bottom 20% promotion & demotion, per-course board retained, hub UI + categories (`weekly_xp/global`, `all_time_xp/global`, `speed/global`, `streak/global`), privacy + "beat your best" bar. - [ ] **Gap vs plan:** grouping is **tier-based**, not the planned ~30-person random same-pace cohorts (decide whether to adopt the shipped tiers or add real cohorts). -- [ ] **Gap vs plan:** **achievement promotion** (published escalating weekly-XP target) not built — - only competitive percentile. +- [x] **Achievement promotion:** fixed weekly XP goals are an alternate path to promotion. Current + goals are 100, 200, 400, 700, 1,000, 1,400, 1,900, 2,500, 3,200 and 4,000 XP in tier order. - [ ] Decouple from career: league demotion touches the league tier only; a permanent career ladder (Phase 2) does not exist yet, so nothing to decouple from today. -- [ ] Dashboard/league UI + tests: hub UI and `leaderboard-hub.test.ts` landed; confirm the rest. +- [x] Dashboard/league UI + tests: hub UI now shows the top-10-percent zone, target progress, recovery progress and + settlement reasons; shared, pure and API coverage added. ## Phase 2 — Career ladder (permanent) - [ ] **Define "mastery" in code** (verified signals advancing each tier) — do first; avoids inflation @@ -84,10 +84,10 @@ competitor signal. ## Phase 4 — Supporting loops & polish - [ ] Daily quests → chests → XP-boost (mini dose loop) - [ ] Monthly badge (quest-points + themed badge) -- [ ] **Recovery**: League Shield / recovery quest — **included** (ships with the league work) -- [ ] **My Records (personal bests)**: longest streak + best weekly XP/chapters are computed in the hub - (PR #161); still missing a dedicated profile "My Records" surface + most-XP-in-a-day / best league - finish lines; "New record!" celebration; read-only recognition +- [x] **Recovery:** League Shield plus a recovery quest requiring one completed chapter and 50 XP; + recovery protection is used before a shield at settlement. +- [x] **My Records (personal bests)**: longest streak, best weekly/day XP, best league finish and + related records are available on the Career Identity profile; read-only recognition remains. - [ ] Mascot loading/companion (Dot with a mood during skeleton loads) - [ ] Weekly recap / Monday ritual surface - [ ] Notifications: "last chance to promote", streak/recovery nudges @@ -138,21 +138,20 @@ Reviewed all 20 pages of `Buildment_Gamification_Design_Concepts_images/`. Statu | 17 | XP microinteraction | 🟡 Partial | XP awarding exists; subtle "+20 XP, 1.5s, return focus" UI not verified | | 19 | Mobile fast screens | 🟡 Partial | Responsive exists; not the dedicated League/Rewards mobile layouts | | 4/5 | Dashboard A/B (calm / arcade) | 🟡 Partial | Functional dashboard, not the exact layouts | -| 7 | **Achievement promotion (published weekly XP goal)** | ❌ Missing | Only percentile promotion (known Phase 1 gap) | +| 7 | **Achievement promotion (published weekly XP goal)** | ✅ Done | Fixed tier goals: 100 / 200 / 400 / 700 / 1,000 XP; one-tier maximum | | 10 | **Monday ritual / weekly recap** | ❌ Missing | No promotion celebration + next-goal screen | -| 18 | **Weekly missions (quest board)** | ❌ Missing | No effort-based mission → credit loop | -| 9 | Recovery quest / pause week | ❌ Missing | Shield only | +| 18 | **Weekly missions (quest board)** | ✅ Done | Weekly quest board and idempotent credit claims shipped in PR #172 | +| 9 | Recovery quest / pause week | 🟡 Partial | Recovery quest is implemented; pause week remains out of scope | | 20 | Experiments / measurement | ❌ Missing | Not built | ### Prioritized next work -- **P0:** (1) achievement promotion — published weekly XP target as an alternate promotion path; (2) - Monday ritual / weekly recap (promotion result + credits + next goal); (3) weekly missions (quest → - credits). +- **P0:** (1) Monday ritual / weekly recap (promotion result + credits + next goal); (2) daily quests, + chests and monthly badge; (3) notifications for promotion and recovery. - **P1:** category weekly track (pick one, route XP, no double-count); league journey view with XP thresholds + separate identity; leaderboard "fair / promotion secured" state. - **P2:** 3 branded share cards; mascot family reactions + motion/reduced-motion; XP microinteraction; - recovery quest / pause week; dedicated mobile League/Rewards; experiments vs non-gamified control. + pause week; dedicated mobile League/Rewards; experiments vs non-gamified control. ### Already solid Leagues + tiers, career ladder, Build Credits economy, marketplace (incl. League Shield), the Career -Identity shared profile, Records, Achievements, and the activity heatmap. \ No newline at end of file +Identity shared profile, Records, Achievements, and the activity heatmap. diff --git a/frontend/src/app/(admin)/admin/desktop-updates/page.tsx b/frontend/src/app/(admin)/admin/desktop-updates/page.tsx index a9ce56d4..e807682b 100644 --- a/frontend/src/app/(admin)/admin/desktop-updates/page.tsx +++ b/frontend/src/app/(admin)/admin/desktop-updates/page.tsx @@ -1,8 +1,7 @@ import { serverApiFetch } from "@/lib/api-server"; -import { AdminPageHeader, AdminPanel } from "@/components/admin/admin-ui"; +import { AdminPageHeader } from "@/components/admin/admin-ui"; import { DesktopUpdatesPanel } from "@/components/admin/desktop-updates-panel"; import { forceDesktopUpdateToLatest, saveDesktopUpdateRules } from "@/server/actions/admin/desktop-updates"; -import { formatUpdatedAt, platformLabel } from "@/lib/desktop-updates"; import type { DesktopUpdatesView } from "@/shared/api/desktop-updates"; // The admin layout already requires the ADMIN role for everything under /admin. @@ -14,43 +13,8 @@ export default async function AdminDesktopUpdatesPage() { - -
- {policies.map((policy) => ( - -

{platformLabel(policy.platform)}

-
-
-
Minimum version
-
{policy.minimumVersion}
-
-
-
Latest version
-
{policy.latestVersion}
-
-
-
Blocked versions
-
- {policy.blockedVersions.length > 0 ? policy.blockedVersions.join(", ") : "None"} -
-
-
-

- {policy.isDefault || !policy.updatedAt ? ( - "Not set: using defaults" - ) : ( - <> - Changed by {policy.updatedBy ? policy.updatedBy.name || policy.updatedBy.email : "unknown"} on{" "} - - - )} -

-
- ))} -
-
); diff --git a/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx new file mode 100644 index 00000000..06ada52d --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/enrollment-edit-form.tsx @@ -0,0 +1,64 @@ +import type { ReactNode } from "react"; +import type { AdminEnrollmentDetail } from "@/shared/api/admin"; +import { AdminActionForm } from "@/components/admin/admin-action-form"; +import { adminSelectClassName } from "@/components/admin/admin-ui"; +import { updateEnrollmentAction } from "@/server/actions/admin/enrollments"; + +const LIFECYCLES = [ + ["ACTIVE", "Active — has access"], + ["COMPLETED", "Completed — has access"], + ["PAYMENT_REQUIRED", "Payment required — no access"], + ["PENDING_ACCOUNT", "Pending account — no access"], + ["CANCELLED", "Cancelled — no access"], + ["EXPIRED", "Expired — no access"], +] as const; +const PAYMENT_STATUSES = [ + ["PENDING", "Pending"], + ["SUCCEEDED", "Paid"], + ["FAILED", "Failed"], + ["REFUNDED", "Refunded"], +] as const; + +function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) { + return ( + + ); +} + +function Select({ name, value, options }: { name: string; value: string; options: ReadonlyArray }) { + return ( + + ); +} + +/** Admin edit of the two things that can be changed by hand: course access and payment status. */ +export function EnrollmentEditForm({ enrollment }: { enrollment: AdminEnrollmentDetail }) { + const payment = enrollment.payment; + return ( + + +
+ + + + ) : ( +

No payment record, so there is no payment status to change.

+ )} +
+
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx new file mode 100644 index 00000000..6867af23 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/[enrollmentId]/page.tsx @@ -0,0 +1,211 @@ +import Link from "next/link"; +import type { ReactNode } from "react"; +import type { AdminEnrollmentDetail } from "@/shared/api/admin"; +import { serverApiFetchOrNotFound } from "@/lib/api-server"; +import { formatPriceCents } from "@/lib/format-price"; +import { Badge } from "@/components/ui/badge"; +import { requireRole } from "@/server/auth/guards"; +import { AdminBackLink, AdminPanel, AdminSection } from "@/components/admin/admin-ui"; +import { PaymentStatusBadge, discountKindLabel, providerLabel, wasCharged } from "../payment-badge"; +import { DeleteEnrollmentButton } from "../delete-enrollment-button"; +import { EnrollmentEditForm } from "./enrollment-edit-form"; +import { RefundEnrollmentButton } from "@/components/admin/refund-enrollment-button"; + +const dateTime = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }); +const when = (iso: string | null) => (iso ? dateTime.format(new Date(iso)) : "—"); + +function Field({ label, children, strong }: { label: string; children: ReactNode; strong?: boolean }) { + return ( +
+
{label}
+
{children}
+
+ ); +} + +function StatTile({ label, value, hint }: { label: string; value: string; hint?: string }) { + return ( +
+

{label}

+

{value}

+ {hint ?

{hint}

: null} +
+ ); +} + +export default async function AdminEnrollmentDetailPage({ params }: { params: Promise<{ enrollmentId: string }> }) { + await requireRole("ADMIN"); + const { enrollmentId } = await params; + const enrollment = await serverApiFetchOrNotFound( + `/api/v1/admin/enrollments/${encodeURIComponent(enrollmentId)}` + ); + const { learner, course, payment } = enrollment; + const money = (cents: number) => formatPriceCents(cents, payment?.currency); + const charged = wasCharged(payment?.status); + + return ( +
+ ← Back to enrollments + +
+
+

Enrollment

+

{course.title}

+

+ {learner.userId ? ( + + {learner.name ?? learner.email} + + ) : ( + {learner.email ?? "Unknown learner"} + )} + {learner.name && learner.email ? · {learner.email} : null} +

+
+
+ + {enrollment.lifecycle.replace(/_/g, " ").toLowerCase()} + {enrollment.source.toLowerCase()} + {payment?.provider ? {providerLabel(payment.provider)} : null} + +
+
+ + {payment ? ( + <> +
+ 0 ? `${money(payment.amountCents)} due` : undefined} + /> + + +
+ +
+ + +
+ {money(payment.originalAmountCents)} + −{money(payment.discountAmountCents)} + −{money(payment.organizationContributionCents)} + {money(payment.learnerAmountCents)} + {money(payment.amountCents)} + {payment.fundingSource?.replace(/_/g, " ") ?? "—"} +
+
+
+ + + +
+ {money(payment.platformRevenueCents)} + {money(payment.instructorShareCents)} + {payment.instructorPayoutStatus.replace(/_/g, " ").toLowerCase()} + {when(payment.instructorPayoutPaidAt)} + + + {enrollment.instructor.name ?? enrollment.instructor.email} + + +
+
+
+
+ + + +
+ {payment.provider ? providerLabel(payment.provider) : "—"} + + {payment.providerRef ?? "—"} + + {payment.currency} + {when(payment.createdAt)} + {when(payment.paidAt)} + {when(payment.updatedAt)} +
+ {payment.status === "SUCCEEDED" && payment.provider === "polar" ? ( +
+

Preview the saved policy and choose Standard, Full, or a custom refund.

+ +
+ ) : null} +
+
+ + ) : ( + +

+ No payment is recorded for this enrollment. It was free, or access was granted without a charge. +

+
+ )} + + + + {enrollment.discounts.length === 0 ? ( +

No coupon or campaign was used. The learner was charged the full price.

+ ) : ( +
    + {enrollment.discounts.map((discount) => ( +
  • +
    +
    + {discountKindLabel(discount.kind)} +

    {discount.label}

    +
    +

    + {discount.code ? {discount.code} : "No code"} + {discount.autoApplied ? " · applied automatically" : ""} + {discount.organizationName ? ` · from ${discount.organizationName}` : ""} + {discount.status ? ` · ${discount.status.toLowerCase()}` : ""} + {discount.appliedAt ? ` · ${when(discount.appliedAt)}` : ""} +

    +
    +

    {discount.percentOff}% off

    +
  • + ))} +
+ )} +
+
+ + + +
+ {when(enrollment.createdAt)} + {when(enrollment.startedAt)} + {when(enrollment.completedAt)} + {enrollment.percentComplete}% · {enrollment.status.replace(/_/g, " ").toLowerCase()} + {enrollment.organization?.name ?? "—"} + + {enrollment.id} + +
+
+
+ + + + + + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx b/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx new file mode 100644 index 00000000..5f561358 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/delete-enrollment-button.tsx @@ -0,0 +1,40 @@ +import { Trash2 } from "lucide-react"; +import { AdminActionForm } from "@/components/admin/admin-action-form"; +import { deleteEnrollmentAction } from "@/server/actions/admin/enrollments"; + +/** Trash icon that deletes the enrollment and everything attached to it, after a confirm. */ +export function DeleteEnrollmentButton({ + enrollmentId, + learner, + courseTitle, + paid, + redirectToList, +}: { + enrollmentId: string; + learner: string; + courseTitle: string; + paid: string | null; + redirectToList?: boolean; +}) { + return ( + } + confirm={{ + question: `Delete ${learner}'s enrollment in ${courseTitle}?`, + description: + "This permanently removes the enrollment from the database with its progress, answers, payment record and certificate. " + + (paid ? `The ${paid} payment is not refunded; refund it first if the learner should get money back. ` : "") + + "This cannot be undone.", + confirmLabel: "Delete permanently", + }} + > + + {redirectToList ? : null} + + ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/page.tsx b/frontend/src/app/(admin)/admin/enrollments/page.tsx new file mode 100644 index 00000000..b0111edd --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/page.tsx @@ -0,0 +1,196 @@ +import Link from "next/link"; +import type { AdminEnrollmentsView } from "@/shared/api/admin"; +import { serverApiFetch } from "@/lib/api-server"; +import { formatPriceCents } from "@/lib/format-price"; +import { Badge } from "@/components/ui/badge"; +import { requireRole } from "@/server/auth/guards"; +import { DeleteEnrollmentButton } from "./delete-enrollment-button"; +import { + AdminEmptyState, + AdminPageHeader, + AdminTable, + AdminTableBody, + AdminTableCell, + AdminTableHead, + AdminTableHeaderCell, + AdminTableRow, +} from "@/components/admin/admin-ui"; +import { buildListQuery } from "@/components/admin/admin-list-controls"; +import { AdminLiveFilterBar } from "@/components/admin/admin-live-filter-bar"; +import { AdminPagination } from "@/components/admin/admin-pagination"; +import { DiscountBadge, PaymentStatusBadge, providerLabel, wasCharged } from "./payment-badge"; +import { RefundEnrollmentButton } from "@/components/admin/refund-enrollment-button"; + +type SearchParams = { query?: string; payment?: string; lifecycle?: string; discount?: string; page?: string }; + +const dateFormat = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); + +export default async function AdminEnrollmentsPage({ searchParams }: { searchParams: Promise }) { + await requireRole("ADMIN"); + const sp = await searchParams; + const filters = { query: sp.query, payment: sp.payment, lifecycle: sp.lifecycle, discount: sp.discount }; + const filtering = Boolean(sp.query || sp.payment || sp.lifecycle || sp.discount); + + const listQuery = buildListQuery({ ...filters, page: sp.page && sp.page !== "1" ? sp.page : undefined }); + const { enrollments, page } = await serverApiFetch( + `/api/v1/admin/enrollments${listQuery ? `?${listQuery}` : ""}` + ); + + const hrefFor = (next: number) => { + const qs = buildListQuery({ ...filters, page: next > 1 ? String(next) : undefined }); + return `/admin/enrollments${qs ? `?${qs}` : ""}`; + }; + + return ( +
+ + + + + {enrollments.length === 0 ? ( + + ) : ( + + + + Learner + Course + Enrolled + Payment + Discount + List price + Learner paid + + Actions + + + + + {enrollments.map((row) => { + const payment = row.payment; + return ( + + + + {row.learner.name ?? row.learner.email ?? "Unknown learner"} + + {row.learner.name && row.learner.email ? ( +

{row.learner.email}

+ ) : null} +
+ +

{row.course.title}

+
+ {row.lifecycle.replace(/_/g, " ").toLowerCase()} + {row.source.toLowerCase()} + {payment?.provider ? ( + + {providerLabel(payment.provider)} + + ) : null} +
+
+ + {dateFormat.format(new Date(row.createdAt))} + + + + + + {row.discounts.length > 0 ? ( +
+ {row.discounts.map((discount) => ( + + ))} +
+ ) : ( + — + )} +
+ + {payment ? formatPriceCents(payment.originalAmountCents, payment.currency) : "—"} + + + {payment && wasCharged(payment.status) ? ( + formatPriceCents(payment.amountCents, payment.currency) + ) : payment && payment.amountCents > 0 ? ( + + {formatPriceCents(payment.amountCents, payment.currency)} due + + ) : ( + formatPriceCents(0, payment?.currency) + )} + + +
+ {payment ? : null} + +
+
+
+ ); + })} +
+
+ )} + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx b/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx new file mode 100644 index 00000000..b108c544 --- /dev/null +++ b/frontend/src/app/(admin)/admin/enrollments/payment-badge.tsx @@ -0,0 +1,52 @@ +import type { AdminEnrollmentDiscount, AdminPaymentStatus } from "@/shared/api/admin"; +import { Badge } from "@/components/ui/badge"; + +const LABELS: Record = { + PENDING: "Pending", + SUCCEEDED: "Paid", + FAILED: "Failed", + REFUNDED: "Refunded", +}; + +/** Payment status for an enrollment; no payment row means free or granted by an admin. */ +export function PaymentStatusBadge({ status }: { status: AdminPaymentStatus | null }) { + if (!status) return No payment; + const variant = status === "SUCCEEDED" ? "secondary" : status === "FAILED" || status === "REFUNDED" ? "destructive" : "outline"; + return {LABELS[status]}; +} + +/** Whether money changed hands: a completed payment, or one that was later refunded. */ +export function wasCharged(status: AdminPaymentStatus | null | undefined) { + return status === "SUCCEEDED" || status === "REFUNDED"; +} + +const DISCOUNT_KIND_LABELS: Record = { + campaign: "Campaign", + instructor_coupon: "Coupon", + organization_coupon: "Org coupon", + admin_enrollment: "Admin enrollment", +}; + +/** Short badge for one coupon or campaign, e.g. "Campaign · BLACKFRIDAY · 30% off". */ +export function DiscountBadge({ discount }: { discount: AdminEnrollmentDiscount }) { + if (discount.kind === "admin_enrollment") { + return Admin enrollment · {discount.percentOff}% off; + } + const parts = [DISCOUNT_KIND_LABELS[discount.kind], discount.code ?? discount.label, `${discount.percentOff}% off`]; + return ( + + {parts.join(" · ")} + + ); +} + +export function discountKindLabel(kind: AdminEnrollmentDiscount["kind"]) { + return DISCOUNT_KIND_LABELS[kind]; +} + +const PROVIDER_LABELS: Record = { polar: "Polar", admin: "Admin", manual: "Manual" }; + +/** Who took the payment: polar, admin, manual, or another provider name as stored. */ +export function providerLabel(provider: string) { + return PROVIDER_LABELS[provider] ?? provider; +} diff --git a/frontend/src/app/(admin)/admin/settings/app/page.tsx b/frontend/src/app/(admin)/admin/settings/app/page.tsx new file mode 100644 index 00000000..574ef86f --- /dev/null +++ b/frontend/src/app/(admin)/admin/settings/app/page.tsx @@ -0,0 +1,22 @@ +import { serverApiFetch } from "@/lib/api-server"; +import { requireRole } from "@/server/auth/guards"; +import { AdminPageHeader } from "@/components/admin/admin-ui"; +import { AppSettingsDashboard } from "@/components/admin/app-settings-view"; +import type { AppSettingsView } from "@/shared/api/admin"; + +export default async function AdminAppSettingsPage() { + await requireRole("ADMIN"); + const data = await serverApiFetch("/api/v1/admin/settings/app"); + + return ( +
+ + + +
+ ); +} diff --git a/frontend/src/app/(admin)/admin/settings/page.tsx b/frontend/src/app/(admin)/admin/settings/page.tsx new file mode 100644 index 00000000..eb6ec9fa --- /dev/null +++ b/frontend/src/app/(admin)/admin/settings/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function AdminSettingsRedirectPage() { + redirect("/admin/settings/app"); +} diff --git a/frontend/src/app/(admin)/admin/users/[userId]/page.tsx b/frontend/src/app/(admin)/admin/users/[userId]/page.tsx index dd0ab105..3ea1bddc 100644 --- a/frontend/src/app/(admin)/admin/users/[userId]/page.tsx +++ b/frontend/src/app/(admin)/admin/users/[userId]/page.tsx @@ -1,5 +1,6 @@ import Link from "next/link"; -import type { AdminCoursesView, AdminUserDetail } from "@/shared/api/admin"; +import type { AdminCoursesView, AdminRefundBreakdown, AdminUserDetail } from "@/shared/api/admin"; +import { formatPriceCents } from "@/lib/format-price"; import { serverApiFetch, serverApiFetchOrNotFound } from "@/lib/api-server"; import { Badge } from "@/components/ui/badge"; import { AdminActionForm } from "@/components/admin/admin-action-form"; @@ -7,6 +8,7 @@ import { AdminEnrollUserDialog } from "@/components/admin/admin-enroll-user-dial import { requireRole } from "@/server/auth/guards"; import { forceVerifyEmailAction, + refundEnrollmentAction, reinstateUserAction, removeUserEnrollmentAction, revokeUserSessionsAction, @@ -28,6 +30,16 @@ import { adminSelectClassName, } from "@/components/admin/admin-ui"; +/** The confirm text for a refund: every amount, and what happens to access. */ +function refundDescription(refund: AdminRefundBreakdown, email: string, courseTitle: string) { + const money = (cents: number) => formatPriceCents(cents, refund.currency); + return ( + `${email} paid ${money(refund.paidCents)}. Polar sends back ${money(refund.refundCents)}, keeping Polar’s fees: ` + + `${money(refund.fixedFeeCents)} transaction fee, ${money(refund.internationalFeeCents)} international fee (1.5%) and ` + + `${money(refund.platformFeeCents)} Polar fee (5%), all charged by Polar. Their access to ${courseTitle} ends straight away. A refund cannot be undone.` + ); +} + function StatTile({ label, value }: { label: string; value: string | number }) { return (
@@ -310,6 +322,24 @@ export default async function AdminUserDetailPage({ {row.lastActiveAt ? new Date(row.lastActiveAt).toLocaleDateString() : "—"} +
+ {row.refund ? ( + + + + + ) : null} +
))} diff --git a/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx b/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx index c7e5a456..e794d26b 100644 --- a/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx +++ b/frontend/src/app/(learn)/(catalog)/labs/shell/page.tsx @@ -1,11 +1,12 @@ import type { Metadata } from "next"; -import { Container, FolderOpen, LogIn, MonitorDown, Terminal } from "lucide-react"; +import Link from "next/link"; +import { ArrowRight, Container, FolderOpen, LogIn, MonitorDown, Terminal } from "lucide-react"; import { SITE_SHARE_IMAGE } from "@/lib/site"; -import { AreaHero, AreaPage, AreaSection, CardGrid, ComingSoonPanel, InfoCard } from "@/components/areas/area-page"; +import { AreaHero, AreaPage, AreaSection, CardGrid, InfoCard } from "@/components/areas/area-page"; export const metadata: Metadata = { title: "Shell labs and the desktop app", - description: "Real shell work on real machines, in the Edorax desktop app. What it does today and what is coming.", + description: "46 hands-on shell labs on real Linux machines, containers and networks, in the free Edorax desktop app. Download it here.", alternates: { canonical: "/labs/shell" }, openGraph: { title: "Shell labs on Edorax", url: "/labs/shell", images: [SITE_SHARE_IMAGE] }, }; @@ -16,9 +17,9 @@ export default function ShellLabsPage() { @@ -32,11 +33,12 @@ export default function ShellLabsPage() {
} title="What it does today">
    +
  • Run the 46 shell labs: each gives you a task, hints and a Check button that looks at the machine.
  • Browse the course catalogue and course previews.
  • Read lessons in a native reader, with the same diagrams, labs and quizzes as the web.
  • Open a course IDE beside a lesson: edit files, run a terminal, and check exercises.
  • @@ -55,22 +57,37 @@ export default function ShellLabsPage() { before it removes them. You need Docker Desktop running for this mode.

    - } title="What is coming for shell labs"> + } title="Still to come">
      -
    • Lab machines that a course defines: Linux hosts, containers and small networks.
    • -
    • Tests that check the machine after each step.
    • -
    • Progress that syncs to your account, the same as chapters.
    • +
    • Labs that need their own kernel, such as systemd and disk storage.
    • +
    • Installers that are signed, so Windows and macOS stop showing a warning.
    • +
    • An app that updates itself. For now you download a new version.

- The app is tested on Apple silicon Macs first. Windows and Intel Macs follow. Downloads will be linked here when it is ready. + Shell labs need Docker Desktop running on your computer. Your lab progress is saved on your account.

- - Visual labs are open today in the browser, with no install. - + +
+
+

Windows, macOS (Apple silicon) and Linux. Version 0.1.0, early release.

+

+ The installers are not signed yet, so Windows or macOS may show a warning the first time. Choose to run it anyway. Intel Macs are + not built yet. +

+
+ + Download the app + + +
+
); } diff --git a/frontend/src/app/(learn)/(main)/highlights/page.tsx b/frontend/src/app/(learn)/(main)/highlights/page.tsx new file mode 100644 index 00000000..4301bc1f --- /dev/null +++ b/frontend/src/app/(learn)/(main)/highlights/page.tsx @@ -0,0 +1,22 @@ +import { serverApiFetch } from "@/lib/api-server"; +import { HighlightsLibrary } from "@/components/learn/highlights-library"; +import type { UserHighlightView } from "@/server/actions/highlights"; + +export const dynamic = "force-dynamic"; + +export default async function HighlightsPage() { + let highlights: UserHighlightView[]; + try { + highlights = await serverApiFetch("/api/v1/learner/highlights"); + } catch { + return ( +
+

My Highlights

+

+ Your highlights could not be loaded. This is not the same as having none. Reload the page to try again. +

+
+ ); + } + return ; +} diff --git a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx index b3cda8b9..29a200a3 100644 --- a/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx +++ b/frontend/src/app/(learn)/courses/[courseSlug]/[chapterSlug]/page.tsx @@ -119,6 +119,7 @@ export default async function ChapterReaderPage({ recap={content.recap} streakMilestone={content.streakMilestone} headingNotes={content.headingNotes} + highlights={content.highlights} predictGate={content.predictGate} predictRevealed={content.predictRevealed} promptCourseRating={Boolean(content.promptCourseRating)} diff --git a/frontend/src/components/admin/admin-action-form.tsx b/frontend/src/components/admin/admin-action-form.tsx index 18a2955b..69b4c53e 100644 --- a/frontend/src/components/admin/admin-action-form.tsx +++ b/frontend/src/components/admin/admin-action-form.tsx @@ -43,6 +43,7 @@ export function AdminActionForm({ buttonClassName, feedbackClassName, confirm, + icon, }: { action: (state: AdminActionState, formData: FormData) => Promise; children?: React.ReactNode; @@ -55,6 +56,8 @@ export function AdminActionForm({ buttonClassName?: string; feedbackClassName?: string; confirm?: Confirmation; + /** Renders an icon-only button; `submitLabel` becomes its accessible name and tooltip. */ + icon?: React.ReactNode; }) { const [state, formAction] = useActionState(action, initial); const formRef = useRef(null); @@ -102,8 +105,10 @@ export function AdminActionForm({ // open. The confirm step validates instead. formNoValidate={confirm ? true : undefined} loadingLabel={pendingLabel ?? submitLabel} + aria-label={icon ? submitLabel : undefined} + title={icon ? submitLabel : undefined} > - {submitLabel} + {icon ?? submitLabel} {state.message ? ( diff --git a/frontend/src/components/admin/admin-workspace-shell.tsx b/frontend/src/components/admin/admin-workspace-shell.tsx index 065b7626..10a3c30f 100644 --- a/frontend/src/components/admin/admin-workspace-shell.tsx +++ b/frontend/src/components/admin/admin-workspace-shell.tsx @@ -11,7 +11,9 @@ import { History, LayoutDashboard, LineChart, + Receipt, MonitorDown, + SlidersHorizontal, Users, Wallet, } from "lucide-react"; @@ -68,6 +70,7 @@ export function AdminWorkspaceShell({ title: "Catalog & sales", items: [ { label: "Courses", href: "/admin/courses", icon: BookOpen, active: pathname.startsWith("/admin/courses") }, + { label: "Enrollments", href: "/admin/enrollments", icon: Receipt, active: pathname.startsWith("/admin/enrollments") }, { label: "Discounts", href: "/admin/discounts", icon: BadgePercent, active: pathname.startsWith("/admin/discounts") }, ], }, @@ -93,6 +96,12 @@ export function AdminWorkspaceShell({ icon: MonitorDown, active: pathname.startsWith("/admin/desktop-updates"), }, + { + label: "App settings", + href: "/admin/settings/app", + icon: SlidersHorizontal, + active: pathname === "/admin/settings" || pathname.startsWith("/admin/settings/app"), + }, { label: "Audit log", href: "/admin/audit", icon: History, active: pathname.startsWith("/admin/audit") }, ], }, diff --git a/frontend/src/components/admin/app-settings-view.tsx b/frontend/src/components/admin/app-settings-view.tsx new file mode 100644 index 00000000..62d44822 --- /dev/null +++ b/frontend/src/components/admin/app-settings-view.tsx @@ -0,0 +1,224 @@ +"use client"; + +import { useState } from "react"; +import { RefundPolicyForm } from "@/components/admin/refund-policy-form"; +import { Badge } from "@/components/ui/badge"; +import { Input } from "@/components/ui/input"; +import { + Activity, + Bot, + CheckCircle2, + Cpu, + CreditCard, + DollarSign, + Flame, + Search, + ShieldCheck, + SlidersHorizontal, + XCircle, +} from "lucide-react"; +import type { AppSettingsView, FeatureFlagInfo } from "@/shared/api/admin"; + +export function AppSettingsDashboard({ data }: { data: AppSettingsView }) { + const [activeTab, setActiveTab] = useState<"policy" | "flags" | "payment">("policy"); + const [filterQuery, setFilterQuery] = useState(""); + const [categoryFilter, setCategoryFilter] = useState("all"); + + const filteredFlags = data.featureFlags.filter((flag) => { + const matchesQuery = + flag.name.toLowerCase().includes(filterQuery.toLowerCase()) || + flag.key.toLowerCase().includes(filterQuery.toLowerCase()) || + flag.description.toLowerCase().includes(filterQuery.toLowerCase()); + const matchesCategory = categoryFilter === "all" || flag.category === categoryFilter; + return matchesQuery && matchesCategory; + }); + + const enabledCount = data.featureFlags.filter((f) => f.enabled).length; + + return ( +
+ {/* Top Navigation Tabs */} +
+ + + + + +
+ + {/* Tab 1: Refund Policy Form */} + {activeTab === "policy" && } + + {/* Tab 2: Feature Flags */} + {activeTab === "flags" && ( +
+ {/* Filter Bar */} +
+
+ + setFilterQuery(e.target.value)} + className="pl-9 text-xs" + /> +
+ +
+ {[ + { id: "all", label: "All categories" }, + { id: "gamification", label: "Gamification" }, + { id: "infra", label: "System & Cron" }, + ].map((cat) => ( + + ))} +
+
+ + {/* Feature Flags Grid */} +
+ {filteredFlags.map((flag) => { + const CategoryIcon = flag.category === "gamification" ? Flame : Cpu; + + return ( +
+
+
+
+
+ +
+
+

{flag.name}

+ {flag.key} +
+
+ + {flag.enabled ? ( + + + Enabled + + ) : ( + + + Disabled + + )} +
+ +

{flag.description}

+
+ +
+ Category: {flag.category} + Env-configured +
+
+ ); + })} +
+ + {filteredFlags.length === 0 && ( +
+ No feature flags found matching your filter. +
+ )} +
+ )} + + {/* Tab 3: Payment Gateway Overview */} + {activeTab === "payment" && ( +
+
+
+
+

Polar payment integration

+

Gateway status and checkout configuration.

+
+ + {data.polar.configured ? ( + + + Active & Connected + + ) : ( + + + Not configured + + )} +
+ +
+
+
Environment
+
{data.polar.environment || "Sandbox"}
+
+ +
+
Refund Modes Supported
+
Standard, Full, Custom
+
+ +
+
Currency
+
USD ($)
+
+
+
+
+ )} +
+ ); +} diff --git a/frontend/src/components/admin/desktop-updates-panel.tsx b/frontend/src/components/admin/desktop-updates-panel.tsx index 419a8db1..67a1d04e 100644 --- a/frontend/src/components/admin/desktop-updates-panel.tsx +++ b/frontend/src/components/admin/desktop-updates-panel.tsx @@ -1,508 +1,295 @@ "use client"; -import { useEffect, useId, useRef, useState, useTransition, type KeyboardEvent } from "react"; +import { useState, useTransition } from "react"; import { useRouter } from "next/navigation"; -import { AlertTriangle, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { toast } from "@/components/ui/app-toast"; import { AdminPanel } from "@/components/admin/admin-ui"; import { cn } from "@/lib/utils"; import { - BLOCKED_VERSIONS_MAX, DESKTOP_PLATFORMS, MESSAGE_MAX_LENGTH, - addBlockedVersion, buildUpdateRequest, + compareVersions, describeForcePlan, - joinPlatformLabels, + formatUpdatedAt, + isValidVersion, planForceToLatest, platformLabel, - removeBlockedVersion, - type RulesFormValues, } from "@/lib/desktop-updates"; import type { DesktopPlatform, DesktopUpdatePolicy, DesktopUpdateRequest } from "@/shared/api/desktop-updates"; type ActionResult = { ok: boolean; message: string }; +type Actions = { + saveRules: (input: DesktopUpdateRequest) => Promise; + forceToLatest: (input: { confirmed: Partial> }) => Promise; +}; const fieldClass = "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-60"; const labelClass = "flex flex-col gap-1 text-xs font-medium text-muted-foreground"; -const hintClass = "text-[11px] font-normal text-muted-foreground"; - -const EMPTY_VALUES: RulesFormValues = { - minimumVersion: "", - latestVersion: "", - downloadUrl: "", - message: "", - blockedVersions: [], -}; - -function prefill(policy: DesktopUpdatePolicy | null): RulesFormValues { - if (!policy) return EMPTY_VALUES; - return { - minimumVersion: policy.minimumVersion, - latestVersion: policy.latestVersion, - downloadUrl: policy.downloadUrl, - message: policy.message, - blockedVersions: [...policy.blockedVersions], - }; -} -export function DesktopUpdatesPanel({ - policies, - saveRules, - forceToLatest, -}: { - policies: DesktopUpdatePolicy[]; - saveRules: (input: DesktopUpdateRequest) => Promise; - forceToLatest: (input: { confirmed: Partial> }) => Promise; -}) { +/** Runs a server action, shows the answer, and reloads the page data when it worked. */ +function useRunner() { const router = useRouter(); - const [selected, setSelected] = useState([]); - const [result, setResult] = useState(null); - const [resets, setResets] = useState(0); const [pending, startTransition] = useTransition(); - - const allSelected = selected.length === DESKTOP_PLATFORMS.length; - const single = selected.length === 1 ? (policies.find((policy) => policy.platform === selected[0]) ?? null) : null; - - const toggle = (platform: DesktopPlatform, checked: boolean) => - setSelected(DESKTOP_PLATFORMS.filter((item) => (item === platform ? checked : selected.includes(item)))); - - const report = (next: ActionResult) => { - setResult(next); - toast(next.message, next.ok ? "success" : "error"); - if (next.ok) { - setResets((count) => count + 1); - router.refresh(); - } - }; - - const run = (work: () => Promise) => + const [result, setResult] = useState(null); + const run = (work: () => Promise, after?: () => void) => startTransition(async () => { + let next: ActionResult; try { - report(await work()); + next = await work(); } catch { - report({ ok: false, message: "Something went wrong. Please try again." }); + next = { ok: false, message: "Something went wrong. Please try again." }; + } + setResult(next); + toast(next.message, next.ok ? "success" : "error"); + if (next.ok) { + after?.(); + router.refresh(); } }); + return { pending, result, setResult, run }; +} +function Result({ result }: { result: ActionResult | null }) { + if (!result) return null; return ( - -
-

Change the update rules

-

- Choose the platforms first. Then change only the fields you need. -

-
- -
- Apply to -
- {DESKTOP_PLATFORMS.map((platform) => ( - - ))} - -
- {selected.length === 0 ? ( -

Choose at least one platform.

- ) : null} -
- - 0 ? "many" : "none"}:${resets}`} - selected={selected} - single={single} - pending={pending} - onSave={(request) => run(() => saveRules(request))} - onError={(message) => { - setResult({ ok: false, message }); - }} - /> - - run(() => forceToLatest({ confirmed }))} - /> - -
- {result ? ( -

- {result.message} -

- ) : null} -
-
+

+ {result.message} +

); } -function RulesForm({ - selected, - single, - pending, - onSave, - onError, +/** A button that asks once more before it does something that locks users out. */ +function ConfirmButton({ + label, + question, + disabled, + onConfirm, }: { - selected: DesktopPlatform[]; - single: DesktopUpdatePolicy | null; - pending: boolean; - onSave: (request: DesktopUpdateRequest) => void; - onError: (message: string) => void; + label: string; + question: string; + disabled?: boolean; + onConfirm: () => void; }) { - const [values, setValues] = useState(() => prefill(single)); - const [clearMessage, setClearMessage] = useState(false); - const [clearBlocked, setClearBlocked] = useState(false); - const [blockedInput, setBlockedInput] = useState(""); - const [blockedError, setBlockedError] = useState(""); - const [errors, setErrors] = useState([]); - const blockedErrorId = useId(); - const errorsId = useId(); - - const set = (key: K, value: RulesFormValues[K]) => { - setValues((current) => ({ ...current, [key]: value })); - setErrors([]); - }; - - const addBlocked = () => { - const outcome = addBlockedVersion(values.blockedVersions, blockedInput); - if (!outcome.ok) { - setBlockedError(outcome.error); - return; - } - setBlockedError(""); - setBlockedInput(""); - setClearBlocked(false); - set("blockedVersions", outcome.list); - }; - - const onBlockedKey = (event: KeyboardEvent) => { - if (event.key === "Enter") { - event.preventDefault(); - addBlocked(); - } - }; - - const disabled = pending || selected.length === 0; - + const [asking, setAsking] = useState(false); + if (!asking) { + return ( + + ); + } return ( -
{ - event.preventDefault(); - const built = buildUpdateRequest({ - platforms: selected, - values, - clear: { message: clearMessage, blockedVersions: clearBlocked }, - current: single, - }); - if (!built.ok) { - setErrors(built.errors); - onError(built.errors.join(" ")); - return; - } - setErrors([]); - onSave(built.request); - }} - > -

- {single - ? `The fields show the saved values for ${platformLabel(single.platform)}. Change what you need.` - : selected.length > 1 - ? "Empty fields stay as they are. Whatever you fill in is saved for every platform you chose." - : "Choose a platform to see its saved values."} -

+ + {question} + + + + ); +} -
- - -
+export function DesktopUpdatesPanel({ policies, saveRules, forceToLatest }: { policies: DesktopUpdatePolicy[] } & Actions) { + const all = useRunner(); + const plan = planForceToLatest(DESKTOP_PLATFORMS, policies); -