diff --git a/README.md b/README.md index bfb1c80..091c790 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The [handbook](docs/USER-GUIDE.md) documents every current user flow: steps, def - Private multiplayer rooms with a C#-owned simulation clock, SignalR snapshots, guest driver claims/readiness, host controls, live pit calls, reconnect, spectator support, guest removal and driver/host handover. Rooms are temporary and use one API instance. See [the multiplayer guide](docs/guide/07-multiplayer.md). - Fictional driver recruitment: generated stat-based prospects, a 12,000-credit budget, six-driver roster, custom 210-point builds, two swappable race seats, browser persistence and lineup application to local/new multiplayer races. See [recruiting flows](docs/guide/08-driver-recruitment.md). - Live signed-roster availability in the sandbox, per-slot build selection and partial-lineup sync. **Race this circuit** starts a separate fictional race on the current replay's approximate outline with your selected signed drivers; generated pit lanes are validated before use. -- A local three-race championship with a frozen signed lineup and four rivals, saved calendar/results, points/countback, team score and resumable in-race checkpoints. Entry is free; recruiting prizes/training and multiplayer championships remain future increments. See [championship flows](docs/guide/09-championship.md). +- A local three-race championship with a frozen signed lineup and four rivals, saved calendar/results, points/countback, team score and resumable in-race checkpoints. Saved rounds offer claim-once recruiting rewards with atomic balance/receipts and cross-tab locks. Entry is free; training and multiplayer championships remain future increments. See [championship flows](docs/guide/09-championship.md). - On-demand tool bundles, recovery from tool download failures, indexed replay lookups, a read-only setup doctor, and a one-command local preview. - Light/dark themes with a header toggle, system preference on first visit, and a browser-saved choice across races. - Save, revisit, and delete replay moments. Bookmarks are isolated by race and survive API restarts in PostgreSQL. diff --git a/docs/DEMO.md b/docs/DEMO.md index 43c9bd2..a6a49fe 100644 --- a/docs/DEMO.md +++ b/docs/DEMO.md @@ -28,7 +28,7 @@ The next session increment also lets you choose **Race distance (laps)**, select ## Engineering evidence -- [Testing guide](TESTING.md): 84 frontend unit checks, nine Node checks, 62 browser scenarios, real API/database integration and dedicated storage/room concurrency checks. +- [Testing guide](TESTING.md): 93 frontend unit checks, nine Node checks, 67 browser scenarios, real API/database integration and dedicated storage/room concurrency checks. - [v1.3 architecture and limitations](V1.3.md): separate recorded/fictional state, independent enrichment, data quality and model assumptions. - `node scripts/benchmark-replay.mjs`: reproducible lookup-only comparison against v1.2 with correctness assertions. - GitHub Actions builds and tests the application and container; release branches publish an image. Hosting, accounts and multiplayer are later scope. diff --git a/docs/FOLLOW-UP-PLAN.md b/docs/FOLLOW-UP-PLAN.md index 94da922..ca0c4d9 100644 --- a/docs/FOLLOW-UP-PLAN.md +++ b/docs/FOLLOW-UP-PLAN.md @@ -53,7 +53,7 @@ Fictional recruiting now adds generated prospects/fees, a browser-local budget a Roster/venue integration now fills empty team seats on signing, keeps signed choices current in an open sandbox, applies selected profiles to new unsaved grids and supports explicit partial sync/per-slot swaps without silently resetting active runs. **Race this circuit** prepares the open replay's approximate outline as a validated independent race venue, with a generated connected pit route and the selected signed drivers. Historical results remain separate; public hosting and a protected cross-device team economy are still later work. -The next local-career increment implements a three-round championship using saved/custom and cached replay venues, two frozen signed builds plus four rivals, exact classified results, points/countback, team totals and saved race checkpoints. See [championship flows](guide/09-championship.md). Next: integrate carefully bounded prize credits, then capped driver training, then consider multiplayer championships. The current cup does not change recruiting credits. +The local-career increment implements a three-round championship using saved/custom and cached replay venues, two frozen signed builds plus four rivals, exact classified results, points/countback, team totals and saved race checkpoints. Saved completed rounds now offer explicit claim-once recruiting rewards: 200 plus 20 per team point, with receipts/balance in one record, cross-tab coordination, owner binding and legacy linking. See [championship flows](guide/09-championship.md). Next: capped driver training, a fuller transaction history, then consider multiplayer championships and a protected server economy. ## Branch and validation workflow diff --git a/docs/TESTING.md b/docs/TESTING.md index 06ce5cd..78368c2 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -6,7 +6,7 @@ Run `node scripts/check-docs.mjs` from the repository root. CI runs the same che When changing a flow, update its chapter and `docs/flows.json`, then run `node scripts/update-guide-index.mjs` and the checker. Follow [CONTRIBUTING](../CONTRIBUTING.md). Checks catch structural drift; reviewing the steps against actual behavior remains necessary. Documentation-only changes need this check, without repeating unrelated application suites locally. -## Playwright: 62 browser scenarios +## Playwright: 67 browser scenarios | Area | Coverage | | --- | --- | @@ -35,7 +35,8 @@ When changing a flow, update its chapter and `docs/flows.json`, then run `node s | Multiplayer | Two independent guest sessions, readiness, synchronized clock/results, live calls, reload/reconnect, driver/host handover, invalid invitations, mobile leave, real-hub concurrent claim conflicts, token/ownership/host checks, forged-time rejection and guest removal | | Fictional recruitment | Generated sign/release/scouting fees and persistence, custom point limits, saved seat swaps and applied performance, new multiplayer room copies, mobile/failed-write behavior, stale-tab protection, raw backup and confirmed corrupted-profile recovery | | Roster/venue integration | Same-window/cross-tab signed-roster availability without resetting an active run, explicit partial sync and per-slot swaps, saved-grid preservation, replay-outline racing, valid pit geometry, new-room hosting and historical replay isolation | -| Local championship | Complete three-venue season/results/standings, between-round reload, frozen recruiting budget, live checkpoint and pit-call restore, animation pause/close persistence, stale-tab locking/reload, mobile failed-write preservation and backed-up corrupted-save recovery | +| Local championship | Complete three-venue season/results/standings, between-round reload, no automatic budget changes before explicit reward claims, live checkpoint and pit-call restore, animation pause/close persistence, stale-tab locking/reload, mobile failed-write preservation and backed-up corrupted-save recovery | +| Championship rewards | Saved-result payout and recruiting purchase, reload/receipt persistence, denied-write retry, real Web Locks with simultaneous tab claims, legacy linking/team-reset protection and unsupported-coordination handling | | Sector map | Completed-reference alignment, saved layout preference, no invented coordinates during gaps, hidden markers before coverage or in estimate mode | | Tool loading | Studio bundle stays deferred until opened; a failed download returns to a usable replay | @@ -43,7 +44,7 @@ These scenarios run against the production frontend build in Chromium. Historica ## Other checks -- 84 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results. +- 93 Vitest checks cover replay timing and indexed boundary/seek behavior, track interpolation, map/layout preferences, recorded sample lookup and sector alignment, trails, share links, named layouts, geometry/rounding/import validation, deterministic strategy math, held-out pace evaluation, sandbox route/service transitions, setup migration, finish timing/frame invariance, result ordering, cancellation/repeat visits and pit-lane finishes. Recruiting checks cover seeded stats/identities, custom constraints, budget/fees/refunds, roster limits, seat swapping, applied settings and storage/revision failures. A committed shared fixture checks browser/server parity for rounded geometry, pit traversal/service/rejoin and finite results. - `Pitwall.RoomChecks` checks authoritative room physics, frame invariance, validation, concurrent seat claims, host/driver authorization, reconnect, handover, guest removal and departure. It also consumes `data/testing/room-model.json`; fixture changes need review, rather than automatic regeneration to make a failure pass. - Nine Node tests cover catalog filtering, identifiers, location alignment/quality, measured-sector/pit normalization, local environment parsing, bounded ports and connection-string escaping. - `Pitwall.StoreChecks` verifies enrichment preservation, downgrade protection, concurrent writes, safe bundle seeding and bookmarks against both in-memory storage and PostgreSQL. It creates uniquely named test rows and removes only those rows. diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md index 766a307..7933469 100644 --- a/docs/USER-GUIDE.md +++ b/docs/USER-GUIDE.md @@ -2,7 +2,7 @@ **Product version:** 1.4.0 -**Last reviewed:** 2026-11-21 +**Last reviewed:** 2026-11-22 This is the current handbook for what each flow does, how to use it, what is saved, and how to recover. The [three-minute demo](DEMO.md) is a quick tour; release notes describe historical changes. This guide describes the current app. @@ -69,6 +69,7 @@ Saving to PostgreSQL, saving in your browser and downloading a file are differen | Multiplayer room | Reconnect while that API process retains it | Guest token in tab session storage; rooms are in server memory even with PostgreSQL | | Recruiting team | Yes, same browser origin | Autosaved market, roster, lineup and credits; applying to a grid is separate | | Local championship | Yes, same browser origin | One frozen calendar/lineup, results and latest saved race checkpoint; no importer | +| Championship reward receipts | Yes, with recruiting team | Credits/claim ID saved together; explicit claims read committed cup results and require Web Locks | Closing a studio or scenario without saving can lose its draft. Clearing browser data, changing browser/profile, or using another hostname/port can change which browser saves you see. A normal database-backed API restart does not erase server caches/bookmarks. @@ -90,7 +91,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser -94 documented flows. Each ID links directly to its instructions. +98 documented flows. Each ID links directly to its instructions. ### Start Pitwall and choose a race @@ -217,6 +218,7 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [TEAM-07](guide/08-driver-recruitment.md#team-07) | Recover from storage failures or another tab's changes | | [TEAM-08](guide/08-driver-recruitment.md#team-08) | Export a record or explicitly start fresh | | [TEAM-09](guide/08-driver-recruitment.md#team-09) | Sync signed drivers directly into a sandbox | +| [TEAM-10](guide/08-driver-recruitment.md#team-10) | Inspect championship earnings and spend prize credits | ### Local three-race championships @@ -230,6 +232,9 @@ Closing a studio or scenario without saving can lose its draft. Clearing browser | [CUP-06](guide/09-championship.md#cup-06) | Recover from failed saves or another editing tab | | [CUP-07](guide/09-championship.md#cup-07) | Export a cup or replace it with a new championship | | [CUP-08](guide/09-championship.md#cup-08) | Recover an unreadable saved championship | +| [CUP-09](guide/09-championship.md#cup-09) | Claim saved round rewards for recruiting | +| [CUP-10](guide/09-championship.md#cup-10) | Retry safely and coordinate reward claims across tabs | +| [CUP-11](guide/09-championship.md#cup-11) | Link an older cup and understand team resets | ## How this stays current diff --git a/docs/flows.json b/docs/flows.json index 9fe49ab..fae6049 100644 --- a/docs/flows.json +++ b/docs/flows.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "productVersion": "1.4.0", - "lastReviewed": "2026-11-21", + "lastReviewed": "2026-11-22", "chapters": [ { "path": "docs/guide/01-start-library.md", @@ -1158,6 +1158,66 @@ "frontend/e2e/championship.spec.ts", "frontend/src/App.tsx" ] + }, + { + "id": "CUP-09", + "title": "Claim saved round rewards for recruiting", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-09", + "sources": [ + "frontend/src/championship-rewards.ts", + "frontend/src/championship-rewards.test.ts", + "frontend/src/recruitment.ts", + "frontend/src/championship.ts", + "frontend/src/LocalChampionship.tsx", + "frontend/src/DriverRecruitment.tsx", + "frontend/e2e/rewards.spec.ts" + ] + }, + { + "id": "CUP-10", + "title": "Retry safely and coordinate reward claims across tabs", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-10", + "sources": [ + "frontend/src/championship-rewards.ts", + "frontend/src/championship-rewards.test.ts", + "frontend/src/recruitment.ts", + "frontend/src/championship.ts", + "frontend/src/LocalChampionship.tsx", + "frontend/src/DriverRecruitment.tsx", + "frontend/e2e/rewards.spec.ts" + ] + }, + { + "id": "CUP-11", + "title": "Link an older cup and understand team resets", + "guide": "docs/guide/09-championship.md", + "anchor": "cup-11", + "sources": [ + "frontend/src/championship-rewards.ts", + "frontend/src/championship-rewards.test.ts", + "frontend/src/recruitment.ts", + "frontend/src/championship.ts", + "frontend/src/LocalChampionship.tsx", + "frontend/src/DriverRecruitment.tsx", + "frontend/e2e/rewards.spec.ts" + ] + }, + { + "id": "TEAM-10", + "title": "Inspect championship earnings and spend prize credits", + "guide": "docs/guide/08-driver-recruitment.md", + "anchor": "team-10", + "sources": [ + "frontend/src/championship-rewards.ts", + "frontend/src/championship-rewards.test.ts", + "frontend/src/recruitment.ts", + "frontend/src/championship.ts", + "frontend/src/LocalChampionship.tsx", + "frontend/src/DriverRecruitment.tsx", + "frontend/e2e/rewards.spec.ts" + ] } ] } diff --git a/docs/guide/06-maintenance.md b/docs/guide/06-maintenance.md index 1a7d83d..1da15a2 100644 --- a/docs/guide/06-maintenance.md +++ b/docs/guide/06-maintenance.md @@ -18,6 +18,7 @@ | Saved circuits/sandbox setups/strategy scenarios | Browser only | Browser only | Same origin isolation | | Recruiting roster/market/lineup/credits | Browser only, autosaved on successful transactions | Browser only | Same origin; separate from server rooms and guest ownership | | Local championship/results/race checkpoint | Browser only | Browser only | One cup per origin; independent of recruiting credits and server rooms | +| Claimed championship rewards | Credits and receipts in recruiting team record | Same browser record | Explicit claim bridges saved cup results into budget; no server-account economy | | Unsaved drafts, tool selections, simulation clock | Current page/tool session | Current page/tool session | Not automatically restored | | Multiplayer rooms/shared race clock | API process memory; lost on restart | API process memory; lost on restart | Guest credential in tab session storage, no token in invitation | | Exported files | Download location you choose | Download location you choose | Not automatically re-imported | diff --git a/docs/guide/08-driver-recruitment.md b/docs/guide/08-driver-recruitment.md index a9dc1e2..71b34f5 100644 --- a/docs/guide/08-driver-recruitment.md +++ b/docs/guide/08-driver-recruitment.md @@ -11,7 +11,7 @@ Recruitment manages fictional driver profiles. It is separate from real players **How:** Open **Driver recruitment** from the replay toolbar, or **Custom circuit studio → Circuit race sandbox → Recruit and manage drivers**. The sandbox pauses when opening its manager. Read your credits and roster count at the top. -**Result and storage:** A fresh team starts with 12,000 credits, six generated prospects, an empty six-driver-capacity roster and two unassigned race seats. The first successful initialization saves that market; reopening does not reroll it. The same team is shared across fictional circuits on this browser origin. An unsaved custom-driver draft is separate from the saved team. +**Result and storage:** A fresh team starts with 12,000 credits, six generated prospects, an empty six-driver-capacity roster and two unassigned race seats. Claimed championship rewards can grow the balance above the starting amount, up to 1,000,000 credits. The first successful initialization saves that market; reopening does not reroll it. The same team is shared across fictional circuits on this browser origin. An unsaved custom-driver draft is separate from the saved team. **Recovery and limits:** Storage errors show a warning; unreadable existing data is not silently replaced. **Load latest team** rereads saved state without changing the custom draft or current race. Different browsers/profiles, schemes, hostnames and ports have separate teams. There is no server-synchronized budget or competitive economy verification. @@ -35,7 +35,7 @@ Recruitment manages fictional driver profiles. It is separate from real players **Result and storage:** Signing deducts the fee and saves the roster/market/budget together. A signing fills the first empty selected race seat automatically; further signings become reserves when both are occupied. The fee is `500 + round((pace² × 0.45 + consistency² × 0.25 + pitDiscipline² × 0.15) / 25) × 25`. Release refunds 40% of that driver's signing fee, rounded down, and clears its selected seats. Release does not return a driver to the market. Existing race copies retain that driver until replaced. -**Recovery and limits:** Insufficient funds or a full roster disable signing. Re-signing a removed market ID is rejected. Signed names must be distinct ignoring case. Releases are immediate and have no undo; the refund is smaller than the signing cost. There are no recurring wages or race income yet. +**Recovery and limits:** Insufficient funds or a full roster disable signing. Re-signing a removed market ID is rejected. Signed names must be distinct ignoring case. Releases are immediate and have no undo; the refund is smaller than the signing cost. Spend credits first if a release refund would exceed the 1,000,000-credit cap. There are no recurring wages; saved championship rewards provide explicit race income. ## TEAM-04 — Build and sign a custom driver @@ -94,7 +94,7 @@ Recruitment manages fictional driver profiles. It is separate from real players **How:** **Export team JSON** downloads the currently displayed team, including seed/market, roster, lineup and credits. **Start fresh team** opens an explanation; **Confirm fresh team** replaces saved recruiting data with a new 12,000-credit team, or **Keep current team** cancels. -**Result and storage:** A confirmed reset replaces this browser origin's recruiting record. Existing circuits, local race grid copies and multiplayer rooms remain separate. Resetting does not save or clear those copies. If you are viewing an unreadable saved record's fallback, back up the raw stored data before resetting; exporting the displayed fallback does not recover the old record. +**Result and storage:** A confirmed reset replaces this browser origin's recruiting record, including reward receipts, and creates a new team identity. Existing circuits, local race grid copies, championship definitions and multiplayer rooms remain separate. The fresh identity cannot claim rewards from an older linked cup. Resetting does not save or clear those copies. If you are viewing an unreadable saved record's fallback, back up the raw stored data before resetting; exporting the displayed fallback does not recover the old record. **Recovery and limits:** There is no team importer or reset undo. A failed reset write retains the old record and reports an error. Other recruiting tabs must load the latest team after a reset. Credits are fictional, so a fresh-team reset is allowed; this is not a protected online economy. @@ -108,3 +108,14 @@ Recruitment manages fictional driver profiles. It is separate from real players **Result and storage:** New unsaved grids automatically use available selected team seats; a stored circuit/race setup retains its own grid until explicitly synced. Signing itself never resets a running race. A grid selection copies the profile's name, colour, derived pace and service duration. Choosing a build already in another slot swaps the builds while keeping each slot's planned pit lap. Sync/selection records ordinary sandbox undo history and restarts its local run; geometry, base pace and distance stay intact. Selecting team seat two can grow a one-driver grid to two. **Recovery and limits:** Save circuit/race setup separately to persist a copied grid. Unreadable roster storage disables selection/sync while leaving the manual grid usable. Releasing a profile removes it from available choices but does not erase an already copied grid driver. Existing multiplayer rooms keep their frozen driver definitions. Shared browser storage does not synchronize across devices or different origins/profiles. + + +## TEAM-10 — Inspect championship earnings and spend prize credits + +**What:** See claimed race income alongside the recruiting budget. + +**How:** Claim a completed-round reward in **Local championship**, then open **Driver recruitment → Championship earnings**. Read total claimed credits/count and the latest ten receipts. Use the updated balance for ordinary market signings, custom builds or scouting. + +**Result and storage:** Every receipt remains in the versioned team JSON (up to 1,000); showing only ten does not delete older duplicate-proof IDs. Exports include the receipts. Older team saves without a receipt field read as an empty history while retaining roster, lineup, market and credits; the next successful save stores the normalized field. Rewards update an open sandbox/recruiting view through normal team notifications; stale recruiting writes still fail revision checks rather than erase income. + +**Recovery and limits:** Receipt totals are gross claimed income, not a complete spending ledger or current balance. Purchases/releases still change the balance normally. Training and a full transaction history remain later work. Team reset clears the recruiting record and changes its identity; it does not grant ownership of previously entered championships. diff --git a/docs/guide/09-championship.md b/docs/guide/09-championship.md index fa95501..d00d157 100644 --- a/docs/guide/09-championship.md +++ b/docs/guide/09-championship.md @@ -2,7 +2,7 @@ [Guide home](../USER-GUIDE.md) · [Recruiting](08-driver-recruitment.md) · [Race sandbox](05-race-sandbox.md) -This cup is a local fictional career loop. It uses the sandbox pace/pit model, keeps a frozen six-driver field and saves one championship per browser origin. Prize credits, driver training, seasons and multiplayer championships are later increments. +This cup is a local fictional career loop. It uses the sandbox pace/pit model, keeps a frozen six-driver field and saves one championship per browser origin. Saved round rewards can fund recruiting; driver training, seasons and multiplayer championships are later increments. ## CUP-01 — Enter a championship with your signed lineup @@ -11,9 +11,9 @@ This cup is a local fictional career loop. It uses the sandbox pace/pit model, k **How:** Sign/select both race seats in **Driver recruitment**, then open **Local championship** in the replay toolbar. Set **Championship name**, **Laps per round** (1–50) and **Base lap seconds** (30–300). Entry is free. Defaults are **Midnight Cup**, three laps and 60 seconds. -**Result and storage:** Creation freezes driver identities, names, colours, pace, service and scheduled pit assumptions for all three rounds. The four rivals have fixed, differing pace; one has a scheduled visit. Later recruiting purchases, releases, seat changes or resets do not modify an existing cup. The recruiting budget remains separate and unchanged. +**Result and storage:** Creation freezes driver identities, names, colours, pace, service and scheduled pit assumptions for all three rounds. It also records the entering recruiting team's identity for rewards. The four rivals have fixed, differing pace; one has a scheduled visit. Later recruiting purchases, releases, seat changes or resets do not modify an existing cup. Racing itself leaves the recruiting budget unchanged until a completed-round reward is explicitly claimed. -**Recovery and limits:** Missing/incomplete signed seats reject entry without creating a save. There are no prize credits, training, entry fees, wages or income in this first increment. It is a local game, not a server-verified competitive economy. Close the panel to manage recruiting, then reopen and create the cup. +**Recovery and limits:** Missing/incomplete signed seats reject entry without creating a save. Entry is free; there is no training, wage system or automatic income. Rewards are local game credits, not a server-verified competitive economy. Close the panel to manage recruiting, then reopen and create the cup. ## CUP-02 — Choose the three-round calendar @@ -46,7 +46,7 @@ This cup is a local fictional career loop. It uses the sandbox pace/pit model, k **Result and storage:** Places 1–6 earn 25/18/15/12/10/8 points. Your team score sums its two driver scores. Equal points use wins, then second-place counts, thirds and later places, then initial grid order. A round records automatically once, in calendar order, only after all six finish. A saved final result cannot be awarded again by reloading. -**Recovery and limits:** There is no skip, replay-for-more-points or result editing UI. Exact race-time ties retain grid order. Standings are driver standings plus your team total, not a multi-constructor championship. Results do not pay recruiting credits yet. +**Recovery and limits:** There is no skip, replay-for-more-points or result editing UI. Exact race-time ties retain grid order. Standings are driver standings plus your team total, not a multi-constructor championship. Saved results unlock the explicit reward claim below; points alone do not automatically change recruiting credits. ## CUP-05 — Save and resume a race or between-round progress @@ -79,7 +79,7 @@ This cup is a local fictional career loop. It uses the sandbox pace/pit model, k **Result and storage:** Replacement changes only the championship key. Recruiting, custom circuit saves, ordinary sandbox setups and multiplayer rooms remain independent. The old cup stays stored until a valid replacement is successfully written. A new cup freezes the then-current selected signed lineup. -**Recovery and limits:** There is no archive list, JSON importer or replacement undo. Export before replacing if you want an inspection copy of the old season. Leaving the replacement form without creating a new cup retains the old cup; unsaved old-race progress still needs a checkpoint before a hard refresh. +**Recovery and limits:** There is no archive list, JSON importer or replacement undo. Claim available rewards before replacing: unclaimed payouts from the old cup become unavailable, and the replacement form shows that total. Already-paid receipts and credits remain with the recruiting team. An exported inspection file is not a supported way to restore claims. Leaving the replacement form without creating a new cup retains the old cup; unsaved old-race progress still needs a checkpoint before a hard refresh. ## CUP-08 — Recover an unreadable saved championship @@ -91,3 +91,36 @@ This cup is a local fictional career loop. It uses the sandbox pace/pit model, k **Result and storage:** The backup wraps the original raw saved string. Reads and failed creation attempts do not overwrite it. Discard checks that the saved string has not changed since it was shown, so a newer save from another tab is not silently removed. **Recovery and limits:** Discard has no undo/import UI. If storage itself is unavailable, restore access before retrying; a backup cannot be read from blocked storage. The operation removes only the championship record, not signed drivers or custom circuits. + + +## CUP-09 — Claim saved round rewards for recruiting + +**What:** Turn completed championship results into recruiting credits. + +**How:** Finish/save a round, inspect **Round rewards**, then choose **Claim round [n] reward**. Each saved round pays `200 + 20 × team points` credits. The six-car points schedule means a two-driver payout ranges from 560 to 1,060 credits. Read the **recruiting credits** total and claimed badge; the money is available immediately in **Driver recruitment**. + +**Result and storage:** Claiming pauses the local race and first saves any pending championship result. The claim operation rereads the committed cup, validates its owner and completed result, recalculates the payout, then writes recruiting credits and its receipt together in the single team record. The receipt identifies cup, round, points, amount, venue and claim time. Rewards from all completed rounds stay available while that cup remains saved, so claiming before starting the next round is optional. + +**Recovery and limits:** Unfinished/unsaved rounds cannot pay. Replacing/discarding the cup makes its unclaimed rewards unavailable. Payout does not scale with lap count or base pace. A newly created cup can earn its own rewards; this is not an anti-farming or tamper-proof server economy. Training remains a later feature. + + +## CUP-10 — Retry safely and coordinate reward claims across tabs + +**What:** Avoid duplicate payouts and preserve the budget when a write fails. + +**How:** Wait for **reward claimed** and its claimed badge. If a reward write fails, restore storage access and retry the same button. If another tab claims first, the current view updates or the pending request reports **already claimed** without adding credits again. + +**Result and storage:** The receipt key is cup ID plus round, retained in the same recruiting record as the balance. Claims take the browser's recruiting-team lock and then the championship lock; ordinary recruiting/cup writes use the same respective locks. Simultaneous claims serialize. A repeated claim returns its existing receipt without a new payout or revision. A lost acknowledgement can be retried safely. A failed pre-write/quota attempt leaves both balance and receipt unchanged; no second championship-side paid flag is needed. + +**Recovery and limits:** Reward claims require Web Locks support; unsupported environments disable claiming rather than promise safe coordination. One active editing tab is still recommended for race checkpoints. Credits cap at 1,000,000; spend before claiming a payout that would exceed it. All duplicate-proof receipts are retained up to 1,000 claims; reaching that limit rejects new claims instead of silently pruning history. Browser clearing, manual storage edits and external account sync are outside this local guarantee. + + +## CUP-11 — Link an older cup and understand team resets + +**What:** Preserve existing saves while binding reward ownership to a recruiting identity. + +**How:** Cups created with rewards enabled record their entering team ID automatically. For an older saved cup without that field, use **Link older cup to original team**. Both original signed driver profiles must still exist on the current recruiting roster. The link must save successfully before claims unlock. + +**Result and storage:** Linking adds the team identity without changing frozen drivers, race progress or results. A linked cup can pay saved completed rounds to that team even if its lineup later changes or profiles are released. A fresh-team reset creates a new identity and clears its old balance/history, so the fresh team cannot reclaim the older linked cup's rewards. + +**Recovery and limits:** Already-bound cups cannot be transferred to another team. An unlinked legacy cup whose original profiles are no longer available cannot be safely linked through this UI; keep it for inspection or begin a new cup. Matching team names alone is insufficient. Team exports/backups are inspection records, not an account-recovery/import flow. diff --git a/frontend/e2e/rewards.spec.ts b/frontend/e2e/rewards.spec.ts new file mode 100644 index 0000000..01d26a9 --- /dev/null +++ b/frontend/e2e/rewards.spec.ts @@ -0,0 +1,109 @@ +import {test,expect,type Page} from "@playwright/test"; +import {newTrack} from "../src/custom-track"; +import {advanceChampionship,beginRound,championshipKey,createChampionship} from "../src/championship"; +import {roundReward} from "../src/championship-rewards"; +import {createDriver,newTeam,signingFee,teamKey} from "../src/recruitment"; + +function fixtures(){ + const team={...createDriver(createDriver(newTeam(42),{id:"reward-one",name:"Reward One",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"reward-two",name:"Reward Two",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1}; + const cup=advanceChampionship(beginRound(createChampionship("Prize Cup",team,Array.from({length:3},(_,i)=>({id:`prize-${i}`,label:`Prize venue ${i+1}`,track:newTrack()})),1,30)),1000); + return {team,cup}; +} +async function openSaved(page:Page,legacy=false){ + const {team,cup}=fixtures();if(legacy)delete cup.rewardTeamId; + await page.addInitScript(({teamKey,cupKey,team,cup})=>{ + if(!localStorage.getItem(teamKey))localStorage.setItem(teamKey,JSON.stringify(team)); + if(!localStorage.getItem(cupKey))localStorage.setItem(cupKey,JSON.stringify(cup)); + },{teamKey,cupKey:championshipKey,team,cup}); + await page.goto("/?race=monza-2024");await page.getByRole("button",{name:"Local championship",exact:true}).click(); + return {team,cup,panel:page.getByRole("dialog",{name:"Local championship",exact:true})}; +} +test("a saved reward survives reload and can fund another signed build",async({page})=>{ + const {team,cup,panel}=await openSaved(page),amount=roundReward(cup,0).amount; + await panel.getByRole("button",{name:"Claim round 1 reward",exact:true}).click(); + await expect(panel.getByTestId("reward-status")).toContainText(`+${amount.toLocaleString("en-US")} credits`); + await expect(panel.getByTestId("cup-recruiting-credits")).toHaveText(`${(team.credits+amount).toLocaleString("en-US")} recruiting credits`); + await page.reload();await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByText(`Round 1 claimed · +${amount.toLocaleString("en-US")} credits`,{exact:true})).toBeVisible(); + await expect(panel.getByRole("button",{name:"Claim round 1 reward",exact:true})).toHaveCount(0); + await panel.getByRole("button",{name:"Begin round 2",exact:true}).click(); + await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click(); + await panel.getByRole("button",{name:"Advance championship lap",exact:true}).click(); + await expect(panel.getByRole("status")).toContainText("Saved 2/3 results"); + const progressed=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),championshipKey); + const secondAmount=roundReward(progressed,1).amount; + await panel.getByRole("button",{name:"Claim round 2 reward",exact:true}).click(); + await expect(panel.getByTestId("reward-status")).toContainText("Round 2 reward claimed"); + await panel.getByRole("button",{name:"Close Local championship",exact:true}).click(); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + const manager=page.getByRole("dialog",{name:"Driver recruitment",exact:true}); + await expect(manager.getByRole("region",{name:"Championship earnings",exact:true})).toContainText("Prize Cup"); + await manager.getByLabel("Custom driver name",{exact:true}).fill("Prize rookie"); + await manager.getByRole("button",{name:"Create and sign custom driver",exact:true}).click(); + await expect(manager.getByTestId("roster-count")).toHaveText("3/6 drivers"); + const saved=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + expect(saved.credits).toBe(team.credits+amount+secondAmount-signingFee({pace:70,consistency:70,pitDiscipline:70}));expect(saved.rewardClaims).toHaveLength(2); +}); + +test("a denied reward write leaves credits and receipt unchanged and a retry pays once on mobile",async({page})=>{ + await page.setViewportSize({width:390,height:844});await page.emulateMedia({colorScheme:"light"}); + const {team,cup,panel}=await openSaved(page),amount=roundReward(cup,0).amount; + await page.evaluate(key=>{const original=Storage.prototype.setItem;let fail=true;Storage.prototype.setItem=function(k,v){if(k===key&&fail){fail=false;throw new Error("Reward write denied");}return original.call(this,k,v);};},teamKey); + await panel.getByRole("button",{name:"Claim round 1 reward",exact:true}).click(); + await expect(panel.getByRole("alert")).toContainText("Reward write denied"); + const before=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + expect(before.credits).toBe(team.credits);expect(before.rewardClaims).toEqual([]); + await panel.getByRole("button",{name:"Claim round 1 reward",exact:true}).click(); + await expect(panel.getByTestId("reward-status")).toContainText("reward claimed"); + const after=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + expect(after.credits).toBe(team.credits+amount);expect(after.rewardClaims).toHaveLength(1); + expect(await panel.evaluate(e=>e.scrollWidth<=e.clientWidth)).toBe(true); +}); + +test("two tabs queued on the real browser lock claim one receipt and one payout",async({page,context})=>{ + const {team,cup,panel}=await openSaved(page),amount=roundReward(cup,0).amount; + const other=await context.newPage(); + try{ + await other.goto("/?race=monza-2024");await other.getByRole("button",{name:"Local championship",exact:true}).click(); + const second=other.getByRole("dialog",{name:"Local championship",exact:true}); + await page.evaluate(key=>{ + const state=window as unknown as {rewardLockHeld:boolean;releaseRewardLock?:()=>void}; + state.rewardLockHeld=false; + void navigator.locks.request(key,()=>new Promise(resolve=>{state.rewardLockHeld=true;state.releaseRewardLock=resolve;})); + },teamKey); + await expect.poll(()=>page.evaluate(()=>(window as unknown as {rewardLockHeld:boolean}).rewardLockHeld)).toBe(true); + await Promise.all([panel.getByRole("button",{name:"Claim round 1 reward",exact:true}).click(),second.getByRole("button",{name:"Claim round 1 reward",exact:true}).click()]); + await expect(panel.getByTestId("reward-status")).toHaveText("Saving reward…");await expect(second.getByTestId("reward-status")).toHaveText("Saving reward…"); + await page.evaluate(()=>(window as unknown as {releaseRewardLock?:()=>void}).releaseRewardLock?.()); + await expect(panel.getByText(`Round 1 claimed · +${amount.toLocaleString("en-US")} credits`,{exact:true})).toBeVisible(); + await expect(second.getByText(`Round 1 claimed · +${amount.toLocaleString("en-US")} credits`,{exact:true})).toBeVisible(); + const saved=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey); + expect(saved.credits).toBe(team.credits+amount);expect(saved.rewardClaims).toHaveLength(1);expect(saved.revision).toBe(team.revision+1); + }finally{await page.evaluate(()=>(window as unknown as {releaseRewardLock?:()=>void}).releaseRewardLock?.());await other.close();} +}); + +test("legacy cups link to their original team and a team reset cannot reclaim paid rounds",async({page})=>{ + const {panel}=await openSaved(page,true); + await expect(panel.getByRole("button",{name:"Claim round 1 reward",exact:true})).toBeDisabled(); + await panel.getByRole("button",{name:"Link older cup to original team",exact:true}).click(); + await expect(panel.getByTestId("reward-status")).toContainText("Older cup linked"); + await panel.getByRole("button",{name:"Claim round 1 reward",exact:true}).click(); + await expect(panel.getByTestId("reward-status")).toContainText("reward claimed"); + await panel.getByRole("button",{name:"Close Local championship",exact:true}).click(); + await page.getByRole("button",{name:"Driver recruitment",exact:true}).click(); + await page.getByRole("button",{name:"Start fresh team",exact:true}).click();await page.getByRole("button",{name:"Confirm fresh team",exact:true}).click(); + await expect(page.getByTestId("roster-count")).toHaveText("0/6 drivers"); + await page.getByRole("button",{name:"Close Driver recruitment",exact:true}).click(); + await page.getByRole("button",{name:"Local championship",exact:true}).click(); + await expect(panel.getByText("This cup belongs to another recruiting team. A fresh team cannot claim its rewards.",{exact:true})).toBeVisible(); + await expect(panel.getByRole("button",{name:"Claim round 1 reward",exact:true})).toBeDisabled(); + const saved=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),teamKey);expect(saved.credits).toBe(12000);expect(saved.rewardClaims).toEqual([]); +}); + +test("unsupported browser coordination disables claims without changing the balance",async({page})=>{ + await page.addInitScript(()=>Object.defineProperty(navigator,"locks",{value:undefined,configurable:true})); + const {team,panel}=await openSaved(page); + await expect(panel.getByText("This browser cannot coordinate reward claims across tabs. Web Locks support is required.",{exact:true})).toBeVisible(); + await expect(panel.getByRole("button",{name:"Claim round 1 reward",exact:true})).toBeDisabled(); + expect(await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).credits,teamKey)).toBe(team.credits); +}); diff --git a/frontend/src/DriverRecruitment.tsx b/frontend/src/DriverRecruitment.tsx index 2e7f13d..d7121b2 100644 --- a/frontend/src/DriverRecruitment.tsx +++ b/frontend/src/DriverRecruitment.tsx @@ -76,7 +76,7 @@ export default function DriverRecruitment({onClose, setup, onApply}: { - {confirmReset &&

This replaces the saved roster, market, lineup and credits with a fresh team. Existing races and saved circuits keep their copied drivers. Export your team first if you want a record.

} + {confirmReset &&

This replaces the saved roster, market, lineup, credits and reward receipts with a new team identity. Existing races keep their copied drivers, but the fresh team cannot reclaim the old team's cup rewards. Export your team first if you want a record.

}

Race lineup

{([0,1] as const).map(i => @@ -132,7 +165,7 @@ export default function LocalChampionship({race,onClose}:{race:Race;onClose:()=>
{catalogError&&

Cached venue list unavailable: {catalogError}. Current/saved circuits can still be selected.

}
{champ&&}
- {champ&&

Creating this replaces the saved championship, including its results and any checkpoint. Export the old championship first if needed.

} + {champ&&

Creating this replaces the saved championship, including its results and any checkpoint. {unclaimed.toLocaleString("en-US")} unclaimed reward credits from completed rounds will no longer be available. Claim them before replacing the cup, or export an inspection record first.

}
:champ&&<>

{champ.name}

{champ.teamName}{champ.results.length}/3 rounds complete{dirty?"Unsaved progress": "Saved"}
    {champ.venues.map((v,i)=>
  1. {v.label} · {i)}
@@ -154,6 +187,22 @@ export default function LocalChampionship({race,onClose}:{race:Race;onClose:()=> } {!champ.session&&last&&

{champ.results.length===3?"Championship complete":"Round complete"} · {champ.venues[last.round].label}

    {last.classification.map((r,i)=>
  1. {champ.entrants.find(d=>d.id===r.driverId)!.name} · {r.finishTime.toFixed(3)}s · +{championshipPoints[i]} points
  2. )}
}

Driver standings

{rows.map((r,i)=>
{i+1}{r.driver.name}{champ.ownDriverIds.includes(r.driver.id)?" · your team":""}{r.finishes[0]} wins{r.points} pts
)}

Team points: {rows.filter(r=>champ.ownDriverIds.includes(r.driver.id)).reduce((sum,r)=>sum+r.points,0)}

+

Round rewards

{rewardAccount.team?`${rewardAccount.team.credits.toLocaleString("en-US")} recruiting credits`:"Recruiting account unavailable"}
+

Each saved round pays 200 credits plus 20 per team point (560–1,060 credits). Claims pause the race, use saved results and add the credits/receipt in one write. Claim before replacing the cup. Rewards are local game credits, not a server-verified economy.

+ {rewardAccount.error&&

{rewardAccount.error}

} + {!champ.rewardTeamId&&<>

This older cup has no recruiting-team link. Link it only if both original signed drivers remain on your current roster.

} + {champ.rewardTeamId&&!ownsRewards&&

This cup belongs to another recruiting team. A fresh team cannot claim its rewards.

} + {!lockSupport&&

This browser cannot coordinate reward claims across tabs. Web Locks support is required.

} + {!champ.results.length&&

Finish and save a round to unlock its reward.

} + {champ.results.map(result=>{ + const payout=roundReward(champ,result.round),receipt=claims.find(c=>c.championshipId===champ.id&&c.round===result.round); + return
Round {result.round+1} · {champ.venues[result.round].label} · {payout.teamPoints} team points · {payout.amount.toLocaleString("en-US")} credits + {receipt?Round {result.round+1} claimed · +{receipt.amount.toLocaleString("en-US")} credits:} +
; + })} + {rewardError&&

Reward not claimed: {rewardError}

} +

{rewardBusy?"Saving reward…":rewardMessage}

+

Scoring: 25/18/15/12/10/8. Ties use wins, then seconds, thirds and later places, then original grid order. Signed builds and rivals are frozen for this cup; later recruiting changes apply to the next championship.

}

{busy?"Saving/loading…":message}

Checkpoints save about every two seconds, on pauses/round finishes and on normal panel close. A hard refresh/crash can lose the last unsaved seconds. Saved races reopen paused. Storage is browser-origin local, and only one active editing tab is supported. Export is an inspection record; no championship importer is implemented.

diff --git a/frontend/src/championship-rewards.test.ts b/frontend/src/championship-rewards.test.ts new file mode 100644 index 0000000..28f738b --- /dev/null +++ b/frontend/src/championship-rewards.test.ts @@ -0,0 +1,103 @@ +import {afterEach,beforeEach,describe,it,expect,vi} from "vitest"; +import {newTrack} from "./custom-track"; +import {advanceChampionship,beginRound,championshipKey,createChampionship,linkLegacyRewardTeam,parseChampionship} from "./championship"; +import {claimRoundReward,roundReward} from "./championship-rewards"; +import {createDriver,maximumCredits,newTeam,parseTeam,resetTeam,saveTeam,teamKey} from "./recruitment"; + +function locks(){ + const pending=new Map>(); + return {request(name:string,work:()=>T|Promise):Promise{ + const prior=pending.get(name)??Promise.resolve(); + const result=prior.catch(()=>{}).then(work); + pending.set(name,result.then(()=>{},()=>{}));return result; + }}; +} +const originalTeam=()=>({...createDriver(createDriver(newTeam(1),{id:"one",name:"One",color:"#64d2b6",origin:"custom",stats:{pace:70,consistency:70,pitDiscipline:70}}),{id:"two",name:"Two",color:"#ff665d",origin:"custom",stats:{pace:60,consistency:60,pitDiscipline:60}}),revision:1}); +describe("atomic, claim-once championship rewards",()=>{ + let data:Map; + beforeEach(()=>{ + data=new Map();vi.stubGlobal("navigator",{locks:locks()}); + vi.stubGlobal("localStorage",{getItem:(key:string)=>data.get(key)??null,setItem:(key:string,value:string)=>data.set(key,value)}); + }); + afterEach(()=>vi.unstubAllGlobals()); + function fixture(finished=true){ + const team=originalTeam(); + let cup=createChampionship("Reward Cup",team,Array.from({length:3},(_,i)=>({id:`venue-${i}`,label:`Venue ${i+1}`,track:newTrack()})),1,30); + cup=beginRound(cup);if(finished)cup=advanceChampionship(cup,1000); + data.set(teamKey,JSON.stringify(team));data.set(championshipKey,JSON.stringify(cup));return {team,cup}; + } + it("migrates old team records and credits the saved payout plus its receipt in one record",async()=>{ + const {team,cup}=fixture(); + const {rewardClaims:_,...legacy}=team;data.set(teamKey,JSON.stringify(legacy)); + expect(parseTeam(legacy).rewardClaims).toEqual([]); + const payout=roundReward(cup,0),result=await claimRoundReward(cup.id,0); + expect(result.alreadyClaimed).toBe(false);expect(result.receipt.amount).toBe(200+20*payout.teamPoints); + const stored=parseTeam(JSON.parse(data.get(teamKey)!)); + expect(stored.credits).toBe(team.credits+payout.amount);expect(stored.rewardClaims).toHaveLength(1); + expect(stored.roster).toEqual(team.roster);expect(stored.lineup).toEqual(team.lineup); + expect(JSON.parse(data.get(championshipKey)!).results).toEqual(cup.results); + }); + it("makes concurrent requests and retries idempotent without adding another receipt or revision",async()=>{ + const {team,cup}=fixture(),payout=roundReward(cup,0).amount; + const responses=await Promise.all(Array.from({length:8},()=>claimRoundReward(cup.id,0))); + expect(responses.filter(r=>!r.alreadyClaimed)).toHaveLength(1); + const stored=JSON.parse(data.get(teamKey)!);expect(stored.credits).toBe(team.credits+payout);expect(stored.rewardClaims).toHaveLength(1); + const before=data.get(teamKey);await claimRoundReward(cup.id,0);expect(data.get(teamKey)).toBe(before); + }); + it("rejects unfinished, uncommitted and replaced results without touching the team",async()=>{ + const {cup}=fixture(false),before=data.get(teamKey); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Finish and save/); + advanceChampionship(cup,1000); // An unsaved view is deliberately insufficient. + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Finish and save/); + await expect(claimRoundReward("another-cup",0)).rejects.toThrow(/changed/); + expect(data.get(teamKey)).toBe(before); + }); + it("does not mark a claim on failed writes and safely recovers a lost acknowledgement",async()=>{ + const {team,cup}=fixture(),before=data.get(teamKey); + const write=(key:string,value:string)=>data.set(key,value); + vi.stubGlobal("localStorage",{getItem:(key:string)=>data.get(key)??null,setItem:()=>{throw new Error("Storage denied");}}); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/denied/);expect(data.get(teamKey)).toBe(before); + vi.stubGlobal("localStorage",{getItem:(key:string)=>data.get(key)??null,setItem:(key:string,value:string)=>{write(key,value);throw new Error("Acknowledgement lost");}}); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Acknowledgement/); + vi.stubGlobal("localStorage",{getItem:(key:string)=>data.get(key)??null,setItem:write}); + const retry=await claimRoundReward(cup.id,0);expect(retry.alreadyClaimed).toBe(true); + expect(retry.team.credits).toBe(team.credits+roundReward(cup,0).amount);expect(retry.team.rewardClaims).toHaveLength(1); + }); + it("preserves newer recruitment changes and makes a stale purchase reload after a reward",async()=>{ + const {team,cup}=fixture(); + const newer=await saveTeam(team,{...team,name:"Updated Racing"}); + const paid=await claimRoundReward(cup.id,0);expect(paid.team.name).toBe("Updated Racing");expect(paid.team.roster).toEqual(newer.roster); + await expect(saveTeam(newer,{...newer,credits:newer.credits-250})).rejects.toThrow(/another tab/); + expect(JSON.parse(data.get(teamKey)!).credits).toBe(paid.team.credits); + }); + it("keeps a fresh team from reclaiming an older team's championship",async()=>{ + const {cup}=fixture();await claimRoundReward(cup.id,0); + const fresh=await resetTeam();expect(fresh.rewardClaims).toEqual([]); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/different recruiting team/); + expect(JSON.parse(data.get(teamKey)!).credits).toBe(12000); + }); + it("links legacy cups only through their original signed profiles and persists the owner before paying",async()=>{ + const {team,cup}=fixture();const legacy={...cup};delete legacy.rewardTeamId; + expect(parseChampionship(legacy).rewardTeamId).toBeUndefined();data.set(championshipKey,JSON.stringify(legacy)); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Link this older/); + expect(()=>linkLegacyRewardTeam(legacy,newTeam(42))).toThrow(/original two/); + const linked=linkLegacyRewardTeam(legacy,team);data.set(championshipKey,JSON.stringify(linked)); + expect((await claimRoundReward(cup.id,0)).alreadyClaimed).toBe(false); + }); + it("refuses unsafe browser coordination and over-cap balances rather than partially paying",async()=>{ + const {team,cup}=fixture();vi.stubGlobal("navigator",{}); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Web Locks/); + vi.stubGlobal("navigator",{locks:locks()});data.set(teamKey,JSON.stringify({...team,credits:maximumCredits})); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/Spend some credits/); + const stored=parseTeam(JSON.parse(data.get(teamKey)!));expect(stored.credits).toBe(maximumCredits);expect(stored.rewardClaims).toEqual([]); + }); + it("accepts earned balances above starting funds but retains every duplicate-proof receipt at the history limit",async()=>{ + const {team,cup}=fixture();data.set(teamKey,JSON.stringify({...team,credits:12000})); + const paid=await claimRoundReward(cup.id,0);expect(parseTeam(paid.team).credits).toBeGreaterThan(12000); + const history=Array.from({length:1000},(_,i)=>({...paid.receipt,championshipId:`previous-${i}`})); + data.set(teamKey,JSON.stringify({...team,rewardClaims:history})); + await expect(claimRoundReward(cup.id,0)).rejects.toThrow(/history limit/); + expect(parseTeam(JSON.parse(data.get(teamKey)!)).rewardClaims).toHaveLength(1000); + expect(()=>parseTeam({...team,rewardClaims:[paid.receipt,paid.receipt]})).toThrow(/Duplicate/); + }); +}); diff --git a/frontend/src/championship-rewards.ts b/frontend/src/championship-rewards.ts new file mode 100644 index 0000000..6bda598 --- /dev/null +++ b/frontend/src/championship-rewards.ts @@ -0,0 +1,42 @@ +import {championshipKey,championshipPoints,parseChampionship,type Championship} from "./championship"; +import {announceTeam,maximumCredits,maximumRewardClaims,parseTeam,rewardBaseCredits,rewardCreditsPerPoint,teamKey,type RewardReceipt,type Team} from "./recruitment"; + +export function roundReward(c:Championship,round:number) { + if(!Number.isInteger(round)||round<0||round>2)throw new Error("Choose a valid championship round."); + const result=c.results[round]; + if(!result||result.round!==round)throw new Error("Finish and save this round before claiming its reward."); + const teamPoints=result.classification.reduce((total,r,i)=>total+(c.ownDriverIds.includes(r.driverId)?championshipPoints[i]:0),0); + return {teamPoints,amount:rewardBaseCredits+teamPoints*rewardCreditsPerPoint}; +} +export function readRewardTeam():{team:Team|null;error:string} { + try { + const raw=localStorage.getItem(teamKey); + return raw===null?{team:null,error:"No saved recruiting team is available. Open Driver recruitment first."}:{team:parseTeam(JSON.parse(raw)),error:""}; + }catch{return {team:null,error:"The recruiting account could not be read. Recover it in Driver recruitment before claiming rewards."};} +} +export async function claimRoundReward(championshipId:string,round:number):Promise<{team:Team;receipt:RewardReceipt;alreadyClaimed:boolean}> { + if(typeof navigator==="undefined"||!navigator.locks)throw new Error("Reward claims require browser Web Locks support to coordinate tabs safely."); + if(!championshipId||championshipId.length>80||!Number.isInteger(round)||round<0||round>2)throw new Error("Choose a valid championship reward."); + // Lock order is always team → championship. The balance and receipt use one atomic record write. + return navigator.locks.request(teamKey,()=>navigator.locks.request(championshipKey,()=>{ + const teamRaw=localStorage.getItem(teamKey); + if(teamRaw===null)throw new Error("No saved recruiting team is available."); + const team=parseTeam(JSON.parse(teamRaw)); + const previous=team.rewardClaims.find(r=>r.championshipId===championshipId&&r.round===round); + if(previous)return {team,receipt:previous,alreadyClaimed:true}; + const cupRaw=localStorage.getItem(championshipKey); + if(cupRaw===null)throw new Error("The saved championship is no longer available."); + const cup=parseChampionship(JSON.parse(cupRaw)); + if(cup.id!==championshipId)throw new Error("The saved championship changed. Load it again before claiming."); + if(!cup.rewardTeamId)throw new Error("Link this older cup to its original recruiting team before claiming rewards."); + if(cup.rewardTeamId!==team.id)throw new Error("This championship belongs to a different recruiting team. Start a new cup for this team."); + const payout=roundReward(cup,round); + if(team.rewardClaims.length>=maximumRewardClaims)throw new Error("The 1,000-receipt history limit has been reached. No credits or receipts were changed."); + if(team.credits+payout.amount>maximumCredits)throw new Error("Spend some credits before claiming; the balance cap is 1,000,000."); + const receipt:RewardReceipt={version:1,championshipId:cup.id,championshipName:cup.name,venueLabel:cup.venues[round].label,round,...payout,claimedAt:new Date().toISOString()}; + const saved=parseTeam({...team,revision:team.revision+1,credits:team.credits+payout.amount,rewardClaims:[...team.rewardClaims,receipt]}); + localStorage.setItem(teamKey,JSON.stringify(saved)); + announceTeam(); + return {team:saved,receipt,alreadyClaimed:false}; + })); +} diff --git a/frontend/src/championship.ts b/frontend/src/championship.ts index 75a4859..8262987 100644 --- a/frontend/src/championship.ts +++ b/frontend/src/championship.ts @@ -11,6 +11,7 @@ export type Championship = { version:1;id:string;revision:number;name:string;teamName:string;ownDriverIds:string[]; entrants:SandboxDriver[];venues:Venue[];results:RoundResult[]; session:{round:number;elapsed:number;states:PreviewState[]}|null; + rewardTeamId?:string|null; }; export function createChampionship(name:string,team:Team,choices:{id:string;label:string;track:CustomTrack}[],laps:number,baseLapSeconds:number):Championship { if(!name.trim()||name.trim().length>48)throw new Error("Use a championship name of 1–48 characters."); @@ -26,7 +27,7 @@ export function createChampionship(name:string,team:Team,choices:{id:string;labe if(errors.length)throw new Error(`${v.label}: ${errors.join(" ")}`); return {...v,track,setup}; }); - return {version:1,id:crypto.randomUUID(),revision:0,name:name.trim(),teamName:team.name,ownDriverIds:entrants.slice(0,2).map(d=>d.id),entrants,venues,results:[],session:null}; + return {version:1,id:crypto.randomUUID(),revision:0,name:name.trim(),teamName:team.name,ownDriverIds:entrants.slice(0,2).map(d=>d.id),entrants,venues,results:[],session:null,rewardTeamId:team.id}; } export function beginRound(c:Championship):Championship { if(c.session)throw new Error("Finish the active round before starting another."); @@ -81,6 +82,7 @@ function parseSession(raw:NonNullable,c:Championship):N export function parseChampionship(raw:unknown):Championship { if(!raw||typeof raw!=="object")throw new Error("Invalid saved championship."); const r=raw as Championship; + if(r.rewardTeamId!==undefined&&r.rewardTeamId!==null&&(typeof r.rewardTeamId!=="string"||!r.rewardTeamId||r.rewardTeamId.length>64))throw new Error("Invalid championship reward owner."); if(r.version!==1||typeof r.id!=="string"||!r.id||r.id.length>80||!Number.isSafeInteger(r.revision)||r.revision<0|| typeof r.name!=="string"||!r.name.trim()||r.name.length>48||typeof r.teamName!=="string"||r.teamName.length>32|| !Array.isArray(r.venues)||r.venues.length!==3||!Array.isArray(r.entrants)||r.entrants.length!==6|| @@ -102,6 +104,11 @@ export function parseChampionship(raw:unknown):Championship { const c={...r,venues,results,entrants:venues[0].setup.drivers}; return {...c,session:r.session===null?null:parseSession(r.session,c)}; } +export function linkLegacyRewardTeam(c:Championship,team:Team):Championship { + if(c.rewardTeamId&&c.rewardTeamId!==team.id)throw new Error("This cup belongs to another recruiting team."); + if(!c.ownDriverIds.every(id=>team.roster.some(d=>`recruit:${d.id}`===id)))throw new Error("The original two signed drivers must still be on this team's roster to link an older cup."); + return {...c,rewardTeamId:team.id}; +} export function readChampionship():{championship:Championship|null;raw:string|null;error:string} { try { const raw=localStorage.getItem(championshipKey); diff --git a/frontend/src/recruitment.ts b/frontend/src/recruitment.ts index 71973f1..210986b 100644 --- a/frontend/src/recruitment.ts +++ b/frontend/src/recruitment.ts @@ -2,10 +2,18 @@ import {newSandboxDriver, type SandboxDriver, type SandboxSetup} from "./sandbox export const teamKey = "pitwall.recruitment.v1"; export const teamUpdatedEvent = "pitwall-team-updated"; -function announceTeam() { +export function announceTeam() { if (typeof window !== "undefined") window.dispatchEvent(new Event(teamUpdatedEvent)); } export const startingCredits = 12000; +export const maximumCredits = 1000000; +export const maximumRewardClaims = 1000; +export const rewardBaseCredits = 200; +export const rewardCreditsPerPoint = 20; +export type RewardReceipt = { + version:1;championshipId:string;championshipName:string;venueLabel:string; + round:number;teamPoints:number;amount:number;claimedAt:string; +}; export const customPoints = 210; export const refreshFee = 250; export type DriverStats = { pace: number; consistency: number; pitDiscipline: number }; @@ -16,6 +24,7 @@ export type Team = { version: 1; id: string; revision: number; name: string; credits: number; seed: number; generation: number; roster: RecruitDriver[]; market: RecruitDriver[]; lineup: [string | null, string | null]; + rewardClaims: RewardReceipt[]; }; const firstNames = ["Nova", "Arden", "Luca", "Mika", "Alex", "Sora", "Remy", "Kai", "Zara", "Eden", "Rio", "Avery"]; const lastNames = ["Vega", "Marin", "Vale", "Sato", "Reed", "Silva", "Costa", "Quinn", "Mercer", "Blake", "Moreau", "Park"]; @@ -38,7 +47,7 @@ export function generateMarket(seed: number, generation: number): RecruitDriver[ } export function newTeam(seed = crypto.getRandomValues(new Uint32Array(1))[0] || 1): Team { return {version: 1, id: crypto.randomUUID(), revision: 0, name: "Midnight Racing", credits: startingCredits, - seed, generation: 0, roster: [], market: generateMarket(seed, 0), lineup: [null, null]}; + seed, generation: 0, roster: [], market: generateMarket(seed, 0), lineup: [null, null], rewardClaims: []}; } export const overall = (s: DriverStats) => Math.round((s.pace + s.consistency + s.pitDiscipline) / 3); export const pointsUsed = (s: DriverStats) => s.pace + s.consistency + s.pitDiscipline; @@ -62,7 +71,7 @@ export function parseTeam(raw: unknown): Team { const t = raw as Team; if (t.version !== 1 || typeof t.id !== "string" || !t.id || t.id.length > 64 || !Number.isSafeInteger(t.revision) || t.revision < 0 || typeof t.name !== "string" || !t.name.trim() || t.name.trim().length > 32 || - !Number.isInteger(t.credits) || t.credits < 0 || t.credits > startingCredits || + !Number.isSafeInteger(t.credits) || t.credits < 0 || t.credits > maximumCredits || !Number.isInteger(t.seed) || t.seed < 1 || t.seed > 4294967295 || !Number.isInteger(t.generation) || t.generation < 0 || t.generation > 1000000 || !Array.isArray(t.roster) || t.roster.length > 6 || !Array.isArray(t.market) || t.market.length > 6 || !Array.isArray(t.lineup) || t.lineup.length !== 2) throw new Error("Saved team has invalid budget, roster, market or version."); @@ -71,7 +80,20 @@ export function parseTeam(raw: unknown): Team { if (new Set(ids).size !== ids.length || new Set(roster.map(d => d.name.toLowerCase())).size !== roster.length || market.some(d => d.origin !== "market") || t.lineup.some(id => id !== null && !roster.some(d => d.id === id)) || (t.lineup[0] !== null && t.lineup[0] === t.lineup[1])) throw new Error("Saved team contains duplicate drivers or an invalid lineup."); - return {...t, name: t.name.trim(), roster, market, lineup: [...t.lineup]}; + const claims = t.rewardClaims === undefined ? [] : t.rewardClaims; + if(!Array.isArray(claims)||claims.length>maximumRewardClaims)throw new Error("Invalid reward receipt history."); + const claimIds=new Set(); + for(const receipt of claims){ + if(!receipt||receipt.version!==1||typeof receipt.championshipId!=="string"||!receipt.championshipId||receipt.championshipId.length>80|| + typeof receipt.championshipName!=="string"||receipt.championshipName.length>48||typeof receipt.venueLabel!=="string"||receipt.venueLabel.length>80|| + !Number.isInteger(receipt.round)||receipt.round<0||receipt.round>2||!Number.isInteger(receipt.teamPoints)||receipt.teamPoints<18||receipt.teamPoints>43|| + receipt.amount!==rewardBaseCredits+rewardCreditsPerPoint*receipt.teamPoints||typeof receipt.claimedAt!=="string"||receipt.claimedAt.length>40||!Number.isFinite(Date.parse(receipt.claimedAt))) + throw new Error("Invalid reward receipt."); + const id=`${receipt.championshipId}:${receipt.round}`; + if(claimIds.has(id))throw new Error("Duplicate reward receipt."); + claimIds.add(id); + } + return {...t, name: t.name.trim(), roster, market, lineup: [...t.lineup], rewardClaims: claims.map(r=>({...r}))}; } function hire(t: Team, driver: RecruitDriver): Team { if (t.roster.length >= 6) throw new Error("Your roster is full. Release a driver before signing another."); @@ -95,6 +117,7 @@ export function createDriver(team: Team, draft: RecruitDriver): Team { export function releaseDriver(team: Team, id: string): Team { const driver = team.roster.find(d => d.id === id); if (!driver) throw new Error("This driver is not on your roster."); + if(team.credits+releaseRefund(driver)>maximumCredits)throw new Error("Spend some credits before releasing this driver; the balance cap is 1,000,000."); return {...team, credits: team.credits + releaseRefund(driver), roster: team.roster.filter(d => d.id !== id), lineup: team.lineup.map(d => d === id ? null : d) as Team["lineup"]}; }