Front Matter
Title: Gamification (published as "Gamification Config and Custom Badges")
Author: Krizha Onise Cortez (armaminter) and James Derick Billate — original authors (February 2026)
Updated by: Patrick Babala — author/co-author of PRs #671, #680, #749, #791, #803
Reviewers: Sean Patrick Caintic (scorevi), Jethro Lagmay (dyorgie) — original review. The update review approvers could not be resolved in this pass (GitHub tooling unavailable); the co-review for #671 is recorded at
docs/review/671-review-round-1.md.Created: February 2026
Updated: 2026-09-30
Status: Published (feature live)
References:
[3.2 Gamification] - https://github.com/wyzlab/WyzQuests/issues/35
[3.8 Custom Badges] - https://github.com/wyzlab/WyzQuests/issues/39
Milestone: [3] Develop (Content Production)
Update PRs covered by this revision: #671 admin global-achievement/trigger fetching + badge/trigger UI; #680 motivation pop-ups; #749 per-quest achievement notifications + agency badge requirements; #791 per-quest milestone XP rewards; #803 badge-upload refactor + cleanup
Related guide: Hand-Off Documentation — Gamification (product-facing flows, rules, and QA checklist). This guide holds engineering detail and cross-references the Hand-Off instead of duplicating it.
Offline limitation: sub-issue numbers beneath #35 / #39 could not be enumerated without GitHub access and are intentionally not fabricated here. Add them when GitHub is reachable.
Introduction & Goals
Problem Summary:
The Gamification System increases learner engagement by rewarding progress through quest-specific rewards and platform-wide achievements. It lets creators configure XP rewards, milestone XP, motivation points, completion messages, badges, and leaderboard participation for individual quests, while administrators define reusable global achievements, badge triggers, and agency-wide badge requirements based on learner statistics.
The feature centralizes gamification management while automatically synchronizing learner progress, achievement unlocks, and leaderboard rankings across the platform. Rewards are granted server-side from learner progress updates rather than requiring manual administration.
Goals & Non-Goals:
Goals:
Quest-specific Gamification
Allow creators to configure XP rewards for individual quests.
Allow creators to configure bonus XP rewards.
Allow creators to configure motivation point rewards.
Allow creators to configure milestone XP at 10% and 50% progress (100% uses the base XP reward). (Added in 2.0 — PR #791.)
Allow creators to customize quest completion messages.
Allow creators to upload custom badge images.
Allow creators to assign badge unlock triggers and, for agency-managed badges, condition thresholds (perfect score, record time, first attempt).
Allow creators to declare whether a badge is creator-managed or agency-managed.
Allow creators to enable or disable leaderboard participation per quest.
Validate all gamification configuration before saving.
Global Gamification
Allow administrators to manage reusable global badge definitions.
Allow administrators to create and manage global badge triggers.
Allow administrators to create and manage agency-wide badge requirements. (Added in 2.0 — PR #749.)
Associate badge triggers with learner statistics.
Automatically synchronize learner achievement progress.
Automatically unlock achievements when configured thresholds are reached.
Notify learners in-app and by email when an achievement unlocks. (Changed in 2.0 — PR #749. This was previously a non-goal.)
Display unlocked achievements throughout learner-facing pages.
Display learner rankings using accumulated global XP.
Motivation Pop-ups (Added in 2.0 — PR #680.)
Let creators attach a motivational text/media pop-up to a card or node.
Show the pop-up to the learner once per card, after Continue.
Non-goals:
Gamification does not currently award physical or monetary rewards. (Still open.)
Badge unlocks do not currently generate push notifications or email notifications.Resolved (2.0): per-quest and global achievement unlocks now generate in-app notifications and email (opt-in via learner notification preferences); push notifications remain out of scope (lib/notifications/achievement-notifications.ts,lib/notifications/notifyAchievementEmail.ts).Badge progression is not manually editable by learners. (Still open.)
The system does not currently support custom achievement formulas or scripting. (Still open.)
Global achievements are limited to predefined learner statistic columns (
constants/gamification.ts→GLOBAL_STATS). (Still open.)Leaderboards do not currently support seasonal resets. (Still open.)
Quest gamification settings do not automatically propagate to existing learner progress outside the implemented synchronization logic. (Still open.)
Glossary:
Quest Gamification — Reward configuration applied to an individual quest, including XP rewards, milestone XP, motivation points, badges, completion messages, and leaderboard settings.
Milestone XP — Additional XP granted once per learner when a quest reaches 10% or 50% progress (
xp_milestone_10,xp_milestone_50).Badge Trigger — A configurable rule that determines when a badge should unlock by comparing a learner statistic (global) or a quest outcome (per-quest) against a target.
Motivation Points — Reward points granted after completing a quest (
points_reward); distinct from XP.XP Reward — Experience points awarded for successfully completing a quest (
xp_reward, 10–1000).Bonus XP — Additional experience points granted when an achievement condition is also met (
bonus_xp).Learner Global Statistics — Aggregated learner metrics (
learner_global_stats): completed courses, chapters, lessons, community activity, purchases, and accumulated XP.Achievement Progress — Percentage-based completion value (0–100) toward unlocking an achievement (
learner_achievements.progress).Leaderboard — Ranked list of learners ordered by accumulated experience points (
learner_global_stats.xp_rewards).Quest Badge — Achievement associated with a specific quest configuration or an agency-wide badge requirement.
Global Badge — Achievement managed by platform administrators and shared across the entire platform.
Agency Badge Requirement — An administrator-defined badge applied to every quest in a given agency (
agency_badge_requirements).Motivation Pop-up — Optional per-card/per-node message (text, image, video, GIF, or audio) shown to the learner after Continue.
Milestone Earnings — Idempotent ledger (
quest_milestone_earnings) recording that a learner was paid XP for a given quest milestone.
High-Level Architecture
System Diagram:
Technologies Used:
The Gamification System is implemented using the following technologies:
Next.js App Router
React
TypeScript
Supabase (Postgres, Storage, and Auth)
Zod
React Hook Form
React Dropzone (badge upload)
TailwindCSS
Sonner toast notifications
Corrected in 2.0: the original guide listed Clerk Authentication. The platform migrated to Supabase Auth; the gamification routes resolve the caller through Supabase auth helpers (
getCurrentSupabaseUser(),authenticateRole('ADMIN'),getCreatorAuthContext()). The legacy-namedapp_users.clerk_idcolumn now stores the Supabaseauth.users.idas text, so.eq("clerk_id", uid)lookups continue to work unchanged. No gamification route imports Clerk.The system also reuses shared application services, including authentication helpers, Supabase database access, asset upload endpoints, notification/email helpers, and validation schemas.
Detailed Design & Implementation
Data Model / Schema:
quest_gamifications
Quest-specific gamification settings. Each quest has a single configuration (
UNIQUE (quest_id)) defining learner rewards, badge information, completion messaging, and leaderboard participation.
Relevant fields (migrations
20260216_create_quest_gamifications_table.sql,20260806_add_per_quest_achievement_notifications.sql,20260828_add_xp_milestones_to_quest_gamifications.sql):id(uuid, PK, defaultgen_random_uuid())quest_id(uuid, FK →quests.id, cascade, unique)xp_reward(int, NOT NULL, CHECK 10–1000)bonus_xp(int, default 0, CHECK ≥ 0)points_reward(int, default 0, CHECK ≥ 0)xp_milestone_10(int, default 0, CHECK 0–1000) — XP at 10% progressxp_milestone_50(int, default 0, CHECK 0–1000) — XP at 50% progresscompletion_message(text)badge_name(varchar(255))badge_image_url(text)badge_trigger(text[])badge_managed_by(varchar(50), NOT NULL, default'creator'; Zod enumcreator | agency)badge_description(text)perfect_score_threshold(int, default 100)record_time_minutes(int, nullable)first_attempt_required(boolean, NOT NULL, default true)show_xp_progress(boolean, default true)leaderboard_enabled(boolean, default false)created_at,updated_at(trigger-maintained)
Example:
{"quest_id": "...","xp_reward": 100,"bonus_xp": 25,"points_reward": 10,"xp_milestone_10": 15,"xp_milestone_50": 30,"completion_message": "Great job!","badge_name": "Explorer","badge_image_url": "...","badge_trigger": ["quest_completion"],"badge_managed_by": "creator","show_xp_progress": true,"leaderboard_enabled": true}
global_badge_trigger (singular table name)
Global badge triggers define reusable unlock conditions for administrator-created achievements. Each trigger maps a learner statistic to a required target value.
Relevant fields (
20260423_create_global_gamification_tables.sql):trigger_id(uuid, PK)trigger_name(varchar(255), UNIQUE, NOT NULL)learner_stat(varchar(255), NOT NULL) — one of theGLOBAL_STATSkeystarget(int, NOT NULL)
global_achievements
Stores platform-wide achievements managed by administrators.
Relevant fields (
20260423_create_global_gamification_tables.sql):id(uuid, PK)badge_name(varchar(255), NOT NULL)description(text, NOT NULL)trigger_id(uuid, NOT NULL, FK →global_badge_trigger.trigger_id)badge_image_url(text)show_xp_progress(boolean, default true)leaderboard_enabled(boolean, default false)completion_message(text)created_at,updated_at
learner_global_stats
Stores accumulated learner statistics used to evaluate global achievement progress and to rank the leaderboard.
Relevant fields (
20260423_create_global_gamification_tables.sql):user_id(uuid, PK, FK →app_users.id, cascade)xp_rewards,completed_courses,completed_chapters,completed_lessons,product_purchases,community_posts,community_interactions(int, default 0, CHECK ≥ 0)created_at,updated_at
learner_achievements
Stores each learner's achievement progress and unlock status. Rows cover both global achievements (
is_quest = false) and quest/agency badges (is_quest = true).
Relevant fields (
20260423_create_global_gamification_tables.sql, extended by20260806_add_per_quest_achievement_notifications.sql):user_id(uuid, FK →app_users.id, cascade)achievement_id(uuid; no FK — referencesglobal_achievements.id,quest_gamifications.id, oragency_badge_requirements.iddepending onis_quest)progress(int, default 0, CHECK 0–100)unlocked_at(timestamp, nullable)is_quest(boolean, default false)quest_id(uuid, nullable, FK →quests.id, cascade) — added for per-quest badgescreated_at,updated_atPK:
(user_id, achievement_id)
agency_badge_requirements (Added in 2.0 — PR #749.)
Administrator-defined badges applied across every quest in an agency.
Relevant fields (
20260806_add_per_quest_achievement_notifications.sql):id(uuid, PK)agency_id(uuid, FK →agencies.id, cascade)badge_name(varchar(255), NOT NULL)description(text, nullable)badge_image_url(text, nullable)condition_type(varchar(50), NOT NULL, CHECK INquest_completion,perfect_score,record_time,first_attempt)perfect_score_threshold(int, default 100)record_time_minutes(int, nullable)first_attempt_required(boolean, NOT NULL, default true)enabled(boolean, NOT NULL, default true)created_at,updated_at
quest_milestone_earnings (Added in 2.0 — PR #791.)
Idempotent ledger preventing double payment of milestone XP.
Relevant fields (
20260828_add_quest_milestone_earnings.sql):enrollment_id(uuid, FK →quest_enrollments.id, cascade)milestone(int, NOT NULL, CHECK IN10,50,100)xp_amount(int, NOT NULL, default 0)awarded_at(timestamptz, NOT NULL, defaultnow())PK:
(enrollment_id, milestone)
SQL functions (RPCs):
award_quest_milestone_xp(p_enrollment_id, p_milestone, p_xp_amount, p_completed_courses = 0)→ boolean.SECURITY DEFINER,search_path = public. Inserts intoquest_milestone_earningswithON CONFLICT DO NOTHING; credits XP only when a new row was inserted, upsertinglearner_global_statsviaGREATEST(...).add_learner_xp(...)— legacy; no TypeScript caller references it.get_learner_group_stats(group_id)/get_learner_group_stats_bulk(group_ids)— read-only aggregates joininglearner_achievements(global,is_quest = false) toglobal_achievements.get_quest_creator_agency(quest_uuid)— resolves the owning agency for a quest; used by the quest-achievement engine.
API Specification:
Quest Gamification APIs:
GET
/api/creator/gamification/[questId]— Retrieves a quest's gamification configuration. Agency members may read any quest; otherwise the route filters bycreator_id.POST
/api/creator/gamification/[questId]— Creates configuration(s) after validating withcreateGamificationSchema; accepts a single quest ID or a comma-joined list and returns a per-questresults[]array. Returns"Config already exists"per already-configured quest.PATCH
/api/creator/gamification/[questId]— Updates an existing configuration after validating withupdateGamificationSchema; ownership verified viaverifyAgencyResourceOwnership(). Returns the validated request payload.GET
/api/creator/global-badge-triggers— Returnsglobal_badge_triggerrows for the creator badge-trigger dropdown.DELETE
/api/creator/delete-badge-upload— Best-effort cleanup of an orphaned badge blob; body{ file_path }; enforcesfile_pathstarts withbackground-assets/{authContext.userInternalId}/, then removes it from thepublic-assetsbucket. (Added in 2.0 — PR #803.)POST
/api/creator/upload-assets— Uploads a badge image (usage_context = BADGE,asset_type = IMAGE) and returns the public URL used within the configuration (called bylib/backgroundAssets/uploadBadgeAssetFile.ts).
Global Gamification APIs:
GET
/api/admin/global-achievements— Returns all administrator-defined achievements with their trigger relation.POST
/api/admin/global-achievements— Creates a global achievement; requiresbadge_name,description,trigger_id,badge_image_url.PATCH
/api/admin/global-achievements?id=— Updates an achievement.DELETE
/api/admin/global-achievements?id=— Deletes an achievement.GET
/api/admin/global-achievements/trigger— Returns all badge triggers.POST
/api/admin/global-achievements/trigger— Creates a badge trigger; requirestrigger_nameandlearner_stat.PATCH
/api/admin/global-achievements/trigger?id=— Updates a badge trigger.DELETE
/api/admin/global-achievements/trigger?id=— Deletes a badge trigger.GET
/api/admin/global-achievements/get-trigger?id=— Fetches a single badge trigger.GET
/api/admin/global-achievements/badge?id=— Fetches a single global achievement definition.GET/POST/PATCH/DELETE
/api/admin/agency-badge-requirements— CRUD for agency-wide badge requirements, validated byagencyBadgeRequirementSchema. (Added in 2.0 — PR #749.)GET/POST
/api/admin/gamification/global— Legacy "global" config stored as a zero-UUID row inquest_gamifications(00000000-0000-0000-0000-000000000000), withxp_rewardhardcoded to 10. Superseded conceptually byglobal_achievements; retained for backward compatibility.GET
/api/creator/list-quests//api/admin/list-all-quests— Returns quests available for gamification configuration.
Learner Gamification APIs:
GET
/api/learner/global-achievements— Returns global (non-quest) achievement progress and unlocked achievements. Seedslearner_global_statszeros andlearner_achievementsrows on first use, then enriches in code becauselearner_achievementshas no FK toglobal_achievements.PATCH
/api/learner/global-achievements— Synchronizes achievement progress/unlock. Clamps progress to 0–100, guards against re-unlock with.is("unlocked_at", null), and on a fresh unlock fires in-app + email notifications without awaiting.GET
/api/learner/global-stats— Returns the learner's aggregated stats; returns zeros when none exist.PATCH
/api/learner/global-stats— Increments one stat by{ stat_name, value }.POST
/api/learner/global-stats— Upserts all stat columns.GET
/api/learner/leaderboard— Returns leaderboard rows ordered bycurrent_rank.GET
/api/learner/quest-achievements— Returns quest-specific (and agency) badges: active enrollments merged with creator-managedquest_gamificationsbadges and enabledagency_badge_requirements. (Added in 2.0 — PR #749.)POST
/api/learner/update-progress— The primary learner write path. Persists weighted progress (60% visits / 40% interactables), then awaitsawardMilestoneQuestXp()(10%, 50%) and, at 100%,evaluateAndAwardQuestAchievements().POST
/api/learner/reset-quest— Resets a learner's quest progress to 0. Milestone earnings are intentionally not re-armed, so reset does not allow re-farming milestone XP.POST
/api/learner/achievements/progress— Alternate achievement-progress upsert. See Known Limitations: it lacks the.is("unlocked_at", null)guard used by the global-achievements PATCH.
Logic & Workflows:
Quest Gamification Workflow:
Creator opens the Gamification page (
/creator/gamification).The system retrieves available quests.
The creator selects one or more quests.
Existing quest gamification settings and available badge triggers are retrieved.
The configuration form is populated with existing values, defaults, or "Mixed" for differing values across selected quests.
The creator updates XP rewards, milestone XP, motivation points, badges, completion message, progress display, and leaderboard settings.
If the badge image changes, the file is staged locally and only uploaded on Save; orphaned blobs are cleaned up with
delete-badge-upload.The configuration is validated using the shared Zod schema.
The system creates new configuration(s) or updates existing one(s); entries that already exist are re-sent as PATCH.
Success or validation feedback is displayed.
Admin Global Badge Management Workflow:
Administrator opens the Global Gamification page (
/admin/gamification).Existing badge triggers, global achievements, and agency badge requirements are retrieved.
Administrator creates or edits a global achievement.
Administrator selects a badge trigger linked to a learner statistic.
Badge images are uploaded when necessary.
The configuration is validated.
The achievement is saved to the database.
Agency Badge Requirement Workflow (Added in 2.0 — PR #749.)
Administrator opens Agency Badge Requirements.
Administrator creates a requirement and picks a condition type (
quest_completion,perfect_score,record_time,first_attempt) plus its thresholds.On quest completion, the engine evaluates every enabled requirement for the quest's owning agency and awards any that pass.
Learner Achievement Synchronization Workflow:
Learner signs into the platform.
useGamificationLogic()executes during learner-layout initialization (app/learner/LearnerLayoutClient.tsx).Learner global statistics and achievements are retrieved (
GET /api/learner/global-stats,GET /api/learner/global-achievements).For each locked achievement, the learner's matching stat is compared to the trigger target.
Achievements meeting their target are unlocked; others receive an updated progress percentage (clamped 0–100).
Unlocks trigger in-app and email notifications (respecting learner preferences).
Achievement pages and dashboard components display the updated progress.
Quest Completion Reward Workflow (Added in 2.0 — PRs #749 / #791.)
Learner progress is saved through
POST /api/learner/update-progress.The route computes the weighted percentage and persists it.
At 10% and 50%,
awardMilestoneQuestXp()pays any configuredxp_milestone_10/xp_milestone_50once per enrollment (idempotent viaquest_milestone_earnings).At 100%,
evaluateAndAwardQuestAchievements()awards the basexp_reward(plusbonus_xpwhen the configured trigger conditions pass, creditingcompleted_courses), awards the creator-managed per-quest badge when its triggers pass, and awards any matching agency badge requirements.Each fresh badge unlock fires in-app and email notifications.
Leaderboard Workflow:
Learner opens the Leaderboard page (
/learner/leaderboard).Global learner statistics are retrieved (
GET /api/learner/global-stats,GET /api/learner/leaderboard).Leaderboard rankings are generated using accumulated XP.
Current learner rank and rank changes are calculated.
Leaderboard results are displayed.
Motivation Pop-up Workflow (Added in 2.0 — PR #680.)
Creator attaches a motivation pop-up to a card (Form Editor) or node (Visual Canvas) using Text / Image / Video / GIF / Audio from Upload Local, Via Link, or From Assets.
Media is uploaded through
upload-motivation-media(Form Editor) or the signed-URLquest-content-nodes/get-upload-urlflow (Visual Canvas).On the learner side,
MotivationPopupis shown after the learner clicks Continue, once per card per playthrough; text/image/GIF auto-dismiss after 5 seconds.The motivation media model is documented in depth in the Form Editor and Visual Canvas technical guides; it is included here because motivation is part of the reward experience.
Infrastructure & Operations
Dependencies:
Supabase (Postgres) — Stores gamification configuration, learner stats, achievements, and milestone earnings.
Supabase Storage (
public-assets) — Badge and motivation media storage.Supabase Auth — User authentication and authorization (
getCurrentSupabaseUser,authenticateRole('ADMIN'),getCreatorAuthContext).React Hook Form — Form state management in gamification forms.
Zod — Form and API validation (
shared/schemas/gamificationSchema.ts,agencyBadgeRequirementSchema.ts).React Dropzone — Badge image upload.
Sonner Toast — Success and error notifications.
Email service (
lib/email) — Achievement-unlocked emails viarenderAchievementUnlockedEmail.Corrected in 2.0: Clerk Authentication was replaced by Supabase Auth;
app_users.clerk_idis a legacy column name that now holds the Supabase auth UUID.
Monitoring & Alerting:
The Gamification System validates creator and administrator inputs using shared Zod schemas before saving any configuration.
Validation includes:
XP Reward range validation (10–1000)
Bonus XP validation (≥ 0)
Motivation Points validation (≥ 0)
Milestone XP validation (0–1000)
Badge information validation (name, description, image URL)
Completion message validation
Badge trigger validation and agency condition thresholds
Learner synchronization additionally validates achievement existence, learner statistic availability, progress range (0–100), and achievement unlock conditions.
The current implementation relies on API responses and server logs to monitor failed configuration saves, asset upload and orphan-cleanup failures, validation failures, achievement synchronization and milestone-award failures, notification/email delivery failures, and leaderboard retrieval failures.
Relevant log/notification helpers:
lib/gamification/quest-achievements.ts,lib/notifications/achievement-notifications.ts,lib/notifications/notifyAchievementEmail.ts.
Deployment Plan:
Execute the Gamification Supabase migrations in order:
20260216_create_quest_gamifications_table.sql20260423_create_global_gamification_tables.sql20260806_add_per_quest_achievement_notifications.sql20260828_add_xp_milestones_to_quest_gamifications.sql20260828_add_quest_milestone_earnings.sql20260828_backfill_quest_milestone_earnings.sqlRLS sweeps:
20260612_update_rls_policies_multi_role.sql,20260911_supabase_rls_auth_uid.sql,20260922_export_core_table_rls.sql
Verify Row Level Security (RLS) policies, including
global_badge_trigger.Ensure the
public-assetsStorage MIME allow-list includes badge image types.Deploy updated creator, administrator, and learner pages.
Deploy updated API routes and the milestone/achievement engine.
Verify badge image upload and orphan cleanup.
Verify quest gamification configuration, global achievement synchronization, agency badge requirements, milestone XP, and the leaderboard.
Promote changes to staging after successful validation.
Testing & Quality Assurance
Test Strategy:
Automated coverage (current):
tests/gamification/badge-assignment.test.ts— placeholder only; asserts a locally mockedassignBadgeToLearnerand does not exercise real application code.tests/agency/groups/learner-groups.test.ts— assertsxp_rewardsandbadgesare passed through/aggregated bylearnerGroupService.getGroupDetail.tests/e2e/suspension/suspension.spec.ts— asserts/api/learner/leaderboardis reachable and returns 200 after unsuspension.tests/unit/resolve-target.test.ts— assertsACHIEVEMENT_UNLOCKEDresolves as a static notification target.
Manual coverage:
Quest Gamification: create configuration, update configuration, milestone XP fields, badge image upload, orphan cleanup, validation failures, XP/motivation validation.
Global Gamification: create/update/delete badge, create/update/delete trigger, agency badge requirements CRUD.
Learner: achievement synchronization, achievement unlocking + notifications, milestone XP award at 10/50/100%, reset-quest behavior, leaderboard generation, progress calculation.
Motivation pop-ups: attach text/image/video/GIF/audio, source options, once-per-card display.
Known Limitations:
Badge unlocks do not currently generate push or email notifications.Resolved (2.0): in-app + email notifications now exist (PR #749); push remains out of scope.Seasonal leaderboard resets are not implemented. (Still open.)
Achievement formulas are limited to predefined learner statistic columns. (Still open.)
Learners cannot manually edit achievement progress. (Still open.)
Quest gamification updates do not automatically recalculate previously synchronized learner achievements. (Still open.)
Physical or monetary rewards are outside the scope of the current implementation. (Still open.)
streak_bonusis advertised but not implemented.constants/gamification.tsandtypes/gamification.d.tsliststreak_bonus, buttriggerConditionsMet()inlib/gamification/quest-achievements.tshandles onlyquest_completion,perfect_score,speed_bonus,record_time, andfirst_attempt; an unknown key falls through tofalse, so a badge configured only withstreak_bonusnever awards. (Documented in 2.0.)Trigger vocabulary drift. Per-quest badges use
speed_bonus(gamificationSchema.ts), while agency requirements userecord_time(agencyBadgeRequirementSchema.ts); the engine aliases them.global_badge_triggeralso ships empty, andconstants/gamification.tsuses string keys (e.g."quest_completion") as placeholder trigger IDs. (Documented in 2.0.)Trigger edit may fail.
PATCH /api/admin/global-achievements/triggerwritesupdated_at, but no migration adds that column toglobal_badge_trigger; the response also passes arguments toApiResponseHelper.successin reversed order (flagged indocs/review/671-review-round-1.md). (Documented in 2.0.)Leaderboard rank columns are schema drift.
GET /api/learner/leaderboardorders bycurrent_rankand readsprevious_rank, but no gamification migration defines those columns onlearner_global_stats. (Documented in 2.0.)Incomplete trigger config awards by default. An empty
badge_triggerarray is treated asquest_completion(award) bytriggerConditionsMet(). (Documented in 2.0.)Two overlapping achievement-progress write paths.
PATCH /api/learner/global-achievementsguards re-unlock;POST /api/learner/achievements/progressperforms an unguarded upsert and can overwrite/re-unlock. (Documented in 2.0.)Client-controlled stat name.
PATCH /api/learner/global-statsbuilds{ [body.stat_name]: ... }from an unvalidated client string; unknown keys fail at PostgREST. (Documented in 2.0.)No automated tests cover the quest-achievement engine, milestone XP, gamification UI components, or the achievements/leaderboard pages. (Documented in 2.0.)
Maintenance & Support
Troubleshooting:
Gamification configuration cannot be saved
Verify all required fields are completed.
Verify the selected quest exists.
Verify validation passes (
createGamificationSchema/updateGamificationSchema).Verify creator or administrator permissions (
getCreatorAuthContext/verifyAgencyResourceOwnership).If the quest already has a configuration, POST returns
"Config already exists"— use PATCH instead.
Badge image upload fails
Verify the upload endpoint (
/api/creator/upload-assets) is reachable.Verify the uploaded file type is a supported image.
Verify Supabase Storage configuration (
public-assetsbucket + MIME allow-list).On save failure, verify orphaned blobs were cleaned up via
/api/creator/delete-badge-upload.
Achievement does not unlock
Verify learner statistics have been updated.
Verify the configured
global_badge_trigger.targetandlearner_stat.Verify
useGamificationLogic()executes successfully (client-side global achievements).Verify learner achievement records exist.
For quest badges, verify progress reached 100% and the trigger conditions passed.
Milestone XP is not awarded
Verify
xp_milestone_10/xp_milestone_50are greater than 0 (a 0 value awards nothing and is not recorded).Verify the learner crossed the 10% / 50% threshold with a real node visit.
Verify
quest_milestone_earningshas no existing row for that enrollment/milestone (idempotent by design).
Agency badge is not awarded
Verify the requirement is
enabled.Verify the requirement's
agency_idmatches the quest's owning agency (get_quest_creator_agency).Verify the condition type and thresholds (perfect score / record time / first attempt).
Achievement notification or email is not delivered
Verify the learner's notification preferences (
achievements_in_app,achievements_email).Verify the unlock was a fresh unlock (not a re-unlock).
Verify the email service and branding data.
Badge trigger edit fails
Verify
global_badge_triggerhas a matchingtrigger_id.Note the
updated_atcolumn write and reversed response arguments documented in Known Limitations.
Leaderboard does not update
Verify learner global statistics exist.
Verify the leaderboard API returns data.
Verify learner XP has been synchronized.
Changelog:
v1.0 (February 2026) — Initial implementation of the Gamification System supporting quest-specific rewards, global achievements, learner synchronization, and leaderboard functionality.
v2.0 (2026-09-30) — documented by Patrick Babala:
Per-quest milestone XP rewards (PR #791):
xp_milestone_10/xp_milestone_50,quest_milestone_earningsledger + backfill,awardMilestoneQuestXp, and the milestone tier UI (QuestXpSettings).Per-quest achievement notifications and agency badge requirements (PR #749):
agency_badge_requirements,badge_managed_by, per-quest badge conditions/thresholds,quest-achievementsAPI,lib/gamification/quest-achievements.ts, in-app + email notifications.Badge-upload refactor (PR #803): shared
components/gamification/BadgeUpload.tsx, deferred upload to Save,lib/backgroundAssets/uploadBadgeAssetFile.ts, and/api/creator/delete-badge-uploadcleanup.Admin global-achievement/trigger fetching + badge/trigger UI fixes (PR #671).
Motivation pop-ups (PR #680):
MotivationPopup,CanvasMotivationSection,upload-motivation-media.Corrections: Clerk → Supabase Auth; refreshed schema (new tables/columns), endpoints, and helpers; References updated with issue + PR links; Open Questions/Non-goals marked resolved where implemented; new layered architecture diagram.
Document version:
2.0 - Updated by Patrick Babala, 2026-09-30. Overhauled for the current codebase: per-quest milestone XP, per-quest achievement notifications, agency badge requirements, badge-upload refactor, motivation pop-ups, Supabase Auth, refreshed schema/APIs/helpers, corrected references, and a redrawn layered architecture diagram.
1.2 - Published, additional title “Custom Badges”, July 2026.
1.1 - Published, Initial internal technical guide for the Gamification System, July 2026.
1.0 - Draft, Feature pushed to dev server after initial dev review, 03/03/2026