Games, Point Rules and Leaderboards
A game holds scoring rules and transactions for a project. Point rules determine which events award or deduct points; transactions record those changes; leaderboard calculations present the resulting scores. Quiz scores and game points can be connected, but they remain different values.
Prerequisites
Select the owning project and confirm Gamification is available. Game views and mutations use the game policy; point-rule and transaction actions have their own policies. A portal app also needs a binding to the game and appropriate dependency actions. Dashboard permission does not automatically grant attendees write access to scoring data.
Prepare a controlled test audience and one real event source, such as an offered quiz or platform event. Keep the game's authoritative scores on the server rather than awarding points only in browser state.
Dashboard access and resource permissions
The project game list is /p/{team}/{project}/games on the dashboard host. Open a returned game link to use Settings, Game Point Rules, Attendee Points, Transactions, Leaderboard and Advanced Settings. Game Sessions appears for session-enabled games. The game editor disables autosave; save and reload configuration before validating scoring or leaderboard changes.
| Resource | View/list | Manage |
|---|---|---|
| Game | view_games | manage_games |
| Point rule | view_game_point_rules | manage_game_point_rules |
| Point transaction | view_point_transactions | manage_point_transactions |
| Game session | view_game_sessions | manage_game_sessions |
These are current policy mappings, not universal grants for every nested route. Game list/detail/create/update/delete use their corresponding policy actions; leaderboard recalculation authorizes game update. The convenience quick-add quiz-rule endpoint also authorizes game update, rather than following the ordinary rule-create controller. Do not infer its permission from another rule editor or assume a game's management grant covers every transaction/session operation. Validate intended and excluded principals, project ownership and attendee bindings for the actual action used.
Quick-add creates a predefined active rule when no rule with its event key and name already exists; that narrow duplicate check does not prevent another differently named rule from awarding for the same behavior. Inspect all matching rules, amounts and limits before accepting events. The convenience path does not verify that a quiz or other event producer is connected, and its success does not prove a transaction was awarded.
Configure a game
- Open Services → Game Management where the project's navigation exposes it. Create a named game with its project-unique slug and description.
- In Settings, decide whether to enable game sessions. Session-based scoring requires an active session when points are posted to it.
- Choose the intended Default Leaderboard Type: Individual Cumulative, Session High Score or Group/Team Cumulative.
- Review the available Segment By Field configuration if the leaderboard should be segmented by an attendee field.
- In Leaderboard, choose the display-name field, relevant groups and segment configuration. Use a field appropriate for attendee-facing display.
- Save the configuration and bind a test portal app to this game's identifier.
Changing display-name/group/segment configuration affects presentation and the population being compared. It is not an instruction to rewrite transactions or merge attendee identities.
Create a point rule
Open Game Point Rules and create a rule for one well-defined behavior. Configure:
| Control | Purpose |
|---|---|
| Status | Active or Disabled |
| Name/Description | Explain the behavior and intended award |
| Trigger Source | System event or custom event |
| Trigger Event | A supported event selected from the offered catalog |
| Custom Event Key/Conditions | Match the intended custom event and its data |
| Social Stream | Scope stream-specific triggers when required |
| Group | Restrict the intended attendee population |
| Action Type | Award or Deduct |
| Base Points | The base amount for one qualifying action |
| Allow Points Multiplier/Max Multiplier Value | Allow and bound an event-provided multiplier |
| Max Awards Total | Limit uses of this rule across attendees |
| Max Awards Per Attendee | Limit repeated uses for one attendee |
Award limits count transactions, not total point value. Zero means unlimited for that limit in the current model. A ten-point award with a per-attendee limit of one is different from allowing ten separate one-point awards.
Use the actual trigger catalog and editor's conditions. A custom event name alone does not establish who may post it or whether the data satisfies the rule. Test the intended event payload and a deliberately nonmatching event before activating a real game.
For quiz integration, use the offered automatic/default quiz rule setup when appropriate and inspect the created rules. A quiz's calculation and an award linked to its event are distinct. Avoid creating duplicate manual rules for the same behavior without understanding the resulting awards.
Bind and integrate an attendee app
Declare the game's supported model/actions and a configuration selector in the app, then bind the installation to the intended game. Read the platform's server score/leaderboard result and display it in the matching UI.
For a legitimate score-generating action, use the deployed runtime/API operation and its required game, rule, attendee and session context. Retain the operation's idempotency identifier when retrying the same event. The transaction service supports idempotency keys; generating a fresh key for every retry turns those retries into separate intended transactions.
Check award limits, matching conditions, group scope, multiplier bounds and session state on the authoritative server path. A visible "Earn points" button or a local total is not evidence that an award was accepted. Verify the stored transaction and resulting server score after the action.
Session lifecycle
A session-aware installed app starts a session through the supported game-sessions API. The service creates it active with a session key and start timestamp. It refuses a second active session for the same attendee/game. Supply the returned session identifier for session-based point transactions.
At develop commit 25e1564 (reviewed 2026-10-19), a session create authorized only through :own fills the attendee from the signed-in owner before checking for an existing active session. A different supplied attendee is refused before querying that person's sessions. Own scope therefore does not permit an additional concurrent session or impersonation. The create/update service preserves ownership authorization exceptions rather than wrapping them as generic service failures. Confirm deployed HTTP behavior and actual session state; no live sessions were created for this review.
When play finishes, the app uses the supported session-update operation to mark it completed; an abandoned play can be marked abandoned. The service records the end time and calculates the completed session's score from server transactions. Ending a session that is already inactive is rejected. The admin Game Sessions table reviews history and flags/unflags completed sessions; it does not provide a general Start/Complete editor.
Find the deployed session/action schemas through the API Catalog and REST reference. For application bindings and invocation, use Apps, Portals and Widgets, Permissions and Dependencies and the runtime store.
Update a game session through REST
Use PUT or PATCH /api/v1/projects/{teamSlug}/{projectSlug}/games/{game}/sessions/{session} with an authenticated principal authorized for manage_game_sessions. The relation controller scopes the parent game to the project and selects a session through that game's sessions relation. In this Orion controller the parent lookup uses the game's numeric primary key, even though the Game model's dashboard route key is a slug. Supply the numeric game ID and numeric session-row ID, not a game slug or the returned session_key. The earlier reviewed update service had no independent current-attendee ownership check. Develop 25e1564 adds model ownership guards when an own grant supplies authorization; wider grants remain a separate path. Test effective principal and row isolation before exposing an integration to attendees.
A minimal completion body is:
{"status":"completed"}
status is required for both methods. The current session must be active; updating an already completed or abandoned session raises a 409 service exception. The validated values are active, completed and abandoned, but an update to active still stamps an end time. For normal finishing, send completed or abandoned; do not use the update as a heartbeat or assume active means no side effects. Confirm deployed HTTP exception mapping rather than relying only on the exception's numeric code.
The service handles other fields as follows:
| Field | Actual update behavior |
|---|---|
player_display_name | Optional string, maximum 255 characters; a supplied value replaces the name. Omission preserves it; null does not satisfy the selected string rule. |
metadata | Optional nullable array/object. Nonempty input shallow-merges into the existing map; colliding nested values replace the whole nested value. Omission, null or an empty array preserves prior metadata and cannot clear it. |
total_points | Validates as an optional integer but is ignored as a client assignment. Completion calculates a total using the server point-transaction service; other statuses retain the prior stored total. |
ended_at | Has a nullable date validation rule, including comparison to request started_at, but the updater uses server time. Omit it; it cannot backdate the session. |
| Identity/start/flag fields | game_id, attendee_id, session_key, started_at and flagged are not selected update fields. Use the appropriate separate workflows rather than treating this API as a general session editor. |
The session save runs inside the service's explicit transaction. Cache invalidation/priming happens afterward; a cache failure can report an error after the session has been saved. Positive completed scores attempt a leaderboard update after persistence; that helper catches/logs its own exceptions, so success does not prove the leaderboard refreshed. The default Orion outer transaction is disabled. None of this makes a retry safe or prevents concurrent completions: the active-state check is not a documented lock/idempotency guarantee.
After a timeout/error, read the session and inspect transactions before retrying. If it is already inactive, reconcile the stored result and leaderboard through authorized workflows rather than reopening it or issuing repeated completion calls. A successful response/refetch is raw session-model output through the dependency resource, not the parent Game resource; do not assume a public-safe attendee projection or expose session_key/metadata broadly. Confirm the deployed envelope and privacy restrictions before publishing a client.
The isolated example/rules/service checks use synthetic score, transaction, cache and save doubles. They do not award points, create a session or verify real routing, ownership, database rollback, concurrent updates, score aggregation or leaderboard delivery.
Submit custom scoring events
The point-transaction collection API exposes read/list/search operations; it is not the write endpoint for awarding points. Submit supported custom events through POST /api/v1/projects/{teamSlug}/{projectSlug}/games/{gameId}/award-points, using the numeric game ID. The route uses Sanctum authentication and project-context middleware. The selected controller/request does not add an independent resource-policy or current-attendee ownership check; do not assume manage_point_transactions or a supplied attendee ID proves enforcement here. Verify the intended principal and denied/cross-project cases before exposing a scoring client.
For a configured active rule with event key synthetic.action, this synthetic body illustrates the request shape. Replace the attendee, event key and condition data with the approved project values, and create a fresh opaque key for each real event:
{"attendee_id":42,"events":[{"event_key":"synthetic.action","timestamp":"2026-10-15T12:00:00Z","idempotency_key":"synthetic-event-0001","data":{"action":"example"}}]}
This is a shape/rules example, not an instruction to award points to attendee 42. The isolated verifier treats existence checks as synthetic; real attendee, rule, session and project acceptance is separate.
Player and validation context
Use an existing attendee_id, or the numeric session_id of the intended active session. A session-linked attendee takes precedence, with a conflicting explicit attendee producing 409. An anonymous session needs its stored display name or a supplied player_display_name. Although request validation accepts session_key, the selected controller does not resolve a session from that key: key-only requests do not establish player context. Do not substitute it for a numeric session ID.
The preparer checks the route's gameId against the current project's games when both values are available. Other rule-building code reads a route key named game, while this route supplies gameId. Its conditional session-key/event-key constraints therefore do not establish the intended game-specific validation on this route. Attendee/session existence checks are global. The controller loads a supplied session by numeric ID without the parent-game relation check implied by one error message. The later transaction path checks active status but does not itself establish session/game ownership. Correct identifiers and a successful request are not proof of isolation.
A request contains 1–30 events. Each requires string event_key, a parseable date timestamp and string idempotency_key; duplicate keys within the request are rejected case-insensitively. Optional multiplier must be numeric and nonnegative. Optional data and event_metadata are arrays/objects. The processor does not use the supplied timestamp to backdate a transaction or enforce an event-age window.
Rule evaluation and duplicate handling
Rules are selected for the target game by event key. Missing, unknown and inactive rules produce per-event errors. The processor checks configured custom conditions only when both the submitted data and configured conditions are nonempty. Omitting data or supplying an empty value does not establish that conditions passed. Provide all required condition data and verify enforcement with a nonmatching case; do not rely on this handler alone as proof that an untrusted client performed a qualifying action. Malformed condition configuration can also be skipped by the evaluator.
The service calculates points from rule base points and multiplier. Disabled multipliers force 1; enabled multipliers cap values above a positive maximum and permit zero. Award versus deduction comes from the rule, not a client-supplied points total. The creation path checks active sessions, allocation limits for linked attendees, applicable custom-event group membership and the maximum calculated point value. Those checks do not repair every identity/condition limitation above.
Idempotency lookup and the migration's unique key are global, rather than scoped to the game, attendee or project. Reusing an existing key can report a skipped transaction from that global lookup; a skip is not independent evidence it belongs to this action. Use opaque, globally unique keys tied to immutable events and retain the same key only when retrying that same event. Do not reuse an example key across players/projects or generate a new key merely because a response was lost. Request-level duplicate rejection, lookup comparison and deployed database collation/concurrency are separate behaviors.
Read every batch result and recover safely
| Result | Meaning |
|---|---|
| 200 with created/skipped counts | No per-event errors reported; a skipped-only batch can return success without a new award. |
207 with success: true | Some events errored while others were created or skipped. Inspect errors, indices and all counts; success is not all-events success. |
| 422 with batch counts/errors | Every processed event failed. Validation or missing player context can also return a different 422 envelope before processing. |
| 500 or lost response | Processing/downstream work may be incomplete after transactions were saved. Reconcile stored transactions and scores before retrying. |
The service's transaction loop collects per-event errors instead of making every batch all-or-nothing. Database failures may behave differently from validation errors in the same transaction. Cache/leaderboard, session-summary, broadcast and workflow processing occur after the loop's transaction; a later failure can surface after records exist. No response establishes exactly-once downstream delivery. The selected outer Orion transaction setting does not wrap this separate explicit controller workflow.
Compare requested event keys/IDs with created_transactions, skipped_transactions and per-event errors, then verify the stored history and resulting score. Reconcile failed downstream work through authorized management workflows; do not delete history, reopen a completed session, broaden credentials or replay with new keys as a recovery shortcut. Real allocation/group/condition/privacy, PostgreSQL rollback/uniqueness, concurrent duplicate, cache/leaderboard and event/workflow acceptance remain required. No live scoring action is executed by the documentation checks.
Read leaderboards and recent game activity
Use POST operations under /api/v1/projects/{teamSlug}/{projectSlug}/games/{gameId}: /leaderboard, /member-lookup and /recent-activity. The game ID is numeric. These use Sanctum/project context and request preparation; the selected controller/request adds no separate resource-policy or current-attendee ownership check. Verify actual allowed/denied principals and display-field privacy before exposing results in a public App.
For a basic leaderboard:
{"leaderboard_type":"attendee_cumulative","time_range":"all_time","limit":10,"timezone":"UTC"}
The request fills omitted values with attendee cumulative, all time, descending, limit 10, offset 0, name full_name, blank subtitle/search and UTC. Explicit invalid values are not equivalent to omission. Limit is 1–100 and offset is nonnegative. Select the meaning you need:
| Leaderboard type | Population |
|---|---|
attendee_cumulative | Attendees by cumulative points |
attendee_high_score | Attendees by their highest individual transaction score |
session_high_score | Individual sessions by session score |
group_cumulative | Group totals |
segment_cumulative | Values of the game's configured attendee segment field |
individual_transaction | Individual point transactions |
Supported time-range names are today, this_week, this_month and all_time; custom objects require start_date and end_date. The selected validation parses both dates but does not reject reversed order. Supply explicit ordered ISO timestamps and an intended valid timezone. The names are not a guarantee of identical populations across modes. Search is at most 100 characters. Names/subtitles select fields using strings up to 50 characters, not a permission-filtered field allowlist; use approved display fields and verify actual output. Attendee fields and session display names may be sensitive even when rendered as leaderboard labels.
Omit game_ids to use the route game. An explicitly supplied array replaces that default; empty arrays currently pass validation and are forwarded rather than falling back. Do not send an empty override. Supply only intended nonempty project game IDs, and similarly verify optional group filters. Project-aware array checks depend on current project context. Optional attendee/session IDs use existence rules that do not independently prove ownership by the current player or selected game.
The data array and meta object form the response. meta.count is the number of returned entries, not the total population. Empty results have a smaller metadata shape; do not require sort/pagination/lock keys to exist in that case. Nonempty entry fields vary by ranking type. Preserve returned member identifiers and their type; do not infer a universal attendee ID from a rank row.
Member lookup and recent activity differ
Member lookup requires a string member_id and an explicit type. It accepts only attendee cumulative, session high score, group cumulative and segment cumulative; it does not accept attendee high score or individual transaction. Use the returned member ID: attendee IDs are numeric strings, sessions/groups have their respective session_/group_ prefixes, and segments use segment: identifiers. Request-level string validation does not verify every format or member scope. Lookup uses all-time ranking; it cannot reproduce a filtered leaderboard's rank simply by resending that member ID. Missing/nonpositive scores and invalid formats can return an error object with HTTP 200, so inspect the body before displaying a successful lookup.
Recent activity retrieves at most ten newest items using an all-time feed. Its shared request may accept limit/offset/time-range fields, but that retrieval path does not apply them as an independently paged/time-filtered feed. Metadata can reflect requested pagination fields without proving those controls affected retrieval. Multi-game activity combines game feeds and selects ten newest entries; it is not the full transaction history or an audit/export replacement.
Cache and lock controls
All-time unlocked/unsearched ranking can use Redis; other ranking paths use database/cache behavior. The selected database cache TTL is 15 seconds. A successful read can initialize or refresh derived cache state; it does not prove upstream transactions, names, updates or reporting pipelines are current. Compare like-for-like game population, mode, time window, search and flags before diagnosing a disagreement.
lock_leaderboard and lock_datetime are query controls, not a command to stop awards or save a persistent competition lock. The service's active cutoff depends on the flag, timestamp and current time; the returned lock metadata is not proof that a future cutoff has taken effect. Send an actual boolean: preparation turns an unrecognized boolean string into null, which extraction treats as false. Verify behavior before using a cutoff for an event result.
The separate POST /leaderboard/clear mutates derived caches and emits a leaderboard update. It clears the game's ranking/database caches and shared name cache; it does not delete point history or recalculate every authoritative result. The selected controller adds no separate clear-policy check beyond route/request behavior. Do not invoke it as a routine client reload or a substitute for an authorized dashboard recalculation. Review authorization and cache/broadcast effects in a controlled environment first. No clear operation runs in the documentation checks.
These read/format checks do not prove Redis/database queries, ranking/tie correctness, field privacy, project isolation, real cache freshness or deployed role enforcement. Retain the game/mode/window and minimal non-sensitive response evidence when reporting discrepancies; keep detailed cache and database recovery in private runbooks.
Subscribe to game notifications
Use Events as a message catalog, then verify the real producer and authorized channel for the intended host. The selected broadcast methods at platform 7d7becc8f4317fe5949ff9f8b5ed97535c318b79 have these branches:
| Broadcast alias | Channel and payload behavior |
|---|---|
PointsAwarded | Uses private portal.Game.{gameId}.{userSession} when the event's user-session value is truthy; otherwise private portal.Game.{gameId}. Payload is under data. |
LeaderboardUpdated | Always uses private portal.Game.{gameId}. data.game_id is present; data.activity is omitted when no activity was supplied and can be an empty array when supplied. |
For PointsAwarded, data includes game_id, nullable attendee_id and session_id, signed total_points, transaction_count, event_types, a timestamp and is_batch (transaction count greater than one). A negative total can represent deduction/reversal behavior; do not assume every notification awards positive points. The timestamp comes from the server clock as ISO 8601; event_types is the array of unique transaction event-key values. The eight fields listed above are expected in this selected output: a missing identifier field is not the same as an explicit null. If required fields are missing or malformed, do not apply a local points delta; use the authorized read workflow and report the sanitized shape. These selected-method checks do not validate every constructor/service input or prove that a write emitted the event.
Private does not mean project-isolated. In the reviewed portal channel registration, the general game callback returns true for its authenticated Sanctum/web/admin guards without an additional game/project check. The session-suffixed callback compares the supplied suffix with the current server session ID, also without a separate game/project check. The plain portal guard is not in these callbacks' declared guard lists. Confirm the supported client authentication flow and negative cross-game/project cases in the intended environment; do not widen credentials or treat a hidden UI as the boundary. Session identifiers are sensitive: never copy them into public examples, analytics, feedback or issue reports.
Keep the authorized server session consistent when using the session channel; the suffix is not an attendee ID or a game-session row ID. The platform page-render service supplies userSession from the current request session; use only the existing authorized runtime context, never a guessed or copied identifier. In the reviewed non-injected portal dependency-listener branch, automatic session listeners are created for AiInterface, not Game. A client listening only to the general game channel can therefore miss session-targeted point notifications. The injected store/custom client path and its authentication must be separately verified for the target App; do not ship a session-targeted game integration assuming the generic listener covers it. Ask the platform/App owner to establish the supported subscription and expected cross-game/project denials before release. A leaderboard notification still uses the general game channel and is not a full authoritative rankings response. Read the permitted leaderboard/resource again when an update signal requires fresh data.
Treat these broadcasts as update signals, not a durable scoring receipt or proof of settled downstream work. On a missing update, inspect the selected channel branch, alias, authentication/session context, point-transaction result and queue/provider outcome. Do not award points again just to force a notification. For a replay, missed connection or stale leaderboard, use the supported read workflow and reconcile the underlying transaction before another mutation. Actual reconnect ordering, isolation, queue delivery and browser behavior remain environment acceptance work; no live points or subscription were created by this review.
Inspect scores and adjust transactions
- Attendee Points shows per-attendee totals and links to the attendee.
- Transactions provides the scoring history and Export Transactions.
- Game Sessions is available for session-enabled games; distinguish a cumulative score from a session high score.
- Leaderboard → Recalculate Leaderboard recomputes the supported leaderboard when the account can update the game.
Authorized transaction updates can flag/unflag transactions. This changes their contribution through the platform's transaction service; it is not a general editable points field. Inspect award/deduction direction and flag status when investigating an unexpected total. Retain the history and explain the adjustment to colleagues.
Leaderboard recalculation does not prove the upstream action generated the correct transactions. Start with transaction history, then the current score and leaderboard representation. Deleting a game or a point rule can affect related transactions and reporting; review the offered confirmation and dependent records before removing it.
Verification example
Configure a test rule awarding ten points for one supported event, with Max Awards Per Attendee = 1 and no multiplier. Then check:
- An eligible attendee performs the event once: one ten-point transaction and the expected server score appear.
- The attendee performs another eligible action after reaching the rule limit: the limit prevents another award.
- Test idempotency separately with a rule that permits at least two awards: retry the original event with the same key and verify only one transaction exists, then submit a new qualifying action with a new key and verify a second award. This separates duplicate handling from the per-attendee limit.
- An excluded attendee or nonmatching event produces no award.
- A session-based action against a completed session is rejected.
- An authorized flag/unflag adjustment updates the corresponding total and leaderboard behavior.
These are project acceptance steps. Use a test game and controlled event source; the docs build does not execute this live scoring scenario.
Troubleshooting
| Symptom | Check |
|---|---|
| No points awarded | Rule active state, offered trigger/event key, event conditions, group, limits and active session |
| Too many points | Duplicate matching rules, changed retry keys, multiplier and unlimited award settings |
| Score differs from quiz result | Quiz scoring versus game point-rule awards and event completion |
| Leaderboard differs from attendee total | Leaderboard mode, session/group/segment population, flagged transactions and cache/recalculation |
| Manual update denied | Transaction/game policy and current project scope |
| Display exposes unexpected identity | Selected display-name field and portal read-field permissions |
| Total changed after removing a rule | Related transaction effects and retained audit/history |
Implementation reference
Reviewed against app/Http/Controllers/Admin/Project/GameController.php, app/Http/Controllers/Admin/GamePointRuleController.php, PointTransactionController.php, PointTransactionHistoryController.php, app/Models/Game.php, GamePointRule.php, PointTransaction.php, GameSession.php, app/Services/PointTransactionService.php, LeaderboardService.php, GameSessionService.php, app/Http/Controllers/Api/Ver1/GameSessionController.php, and the Games pages and game/gamePointRule composables at experience-portal commit 0cab696769c165d93328253378ad7e51ec7ab62e on 2026-10-13. Validate device/custom-event behavior in the target project before launching a game.