Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

96 changes: 91 additions & 5 deletions api/crates/api/src/maps/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,16 @@ pub struct MapList {
pub stats: MapStats,
}

/// The whole list at a glance, whatever the search or filter.
/// Global totals and tier-scoped newest and weekly lists.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct MapStats {
/// Maps with at least one run.
pub maps: i64,
/// Of those, the maps whose main track has each tier, tier 1 first. Empty until a tier count is
/// published.
pub by_tier: Vec<i64>,
/// The tier the newest and weekly lists describe; None describes all tiers. Totals remain global.
pub tier: Option<i16>,
/// The maps that joined the list last, newest first.
pub newest: Vec<NewestMap>,
/// The maps the most players finished a run on in the last 7 days, most first.
Expand Down Expand Up @@ -218,7 +220,7 @@ pub async fn list_maps(
tx.commit().await?;

let tier_count = tiers::tier_count(&state.db).await?;
let list_stats = map_stats(&state.db, tier_count).await?;
let list_stats = map_stats(&state.db, tier_count, query.tier).await?;
let (player, completed) = match player {
Some(player) => (
known_player(&state.db, player).await?,
Expand All @@ -244,7 +246,11 @@ pub async fn list_maps(

/// Maps with a run, how many hold each main-track tier once tiers are in force, the newest of them and the
/// week's most played.
async fn map_stats(db: &sqlx::PgPool, tier_count: Option<i16>) -> Result<MapStats, sqlx::Error> {
async fn map_stats(
db: &sqlx::PgPool,
tier_count: Option<i16>,
tier: Option<i16>,
) -> Result<MapStats, sqlx::Error> {
let rows = sqlx::query!(
r#"SELECT tier.tier AS "tier?", count(*) AS "maps!" FROM maps m
LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0
Expand All @@ -267,8 +273,11 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option<i16>) -> Result<MapStat
r#"SELECT m.name, m.listed_at AS "listed_at!",
(SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier
FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL
AND ($2::smallint IS NULL OR $2 =
(SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))
ORDER BY m.listed_at DESC, m.name LIMIT $1"#,
NEWEST
NEWEST,
tier
)
.fetch_all(db)
.await?
Expand All @@ -288,8 +297,11 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option<i16>) -> Result<MapStat
WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'
GROUP BY map_id) week
JOIN maps m ON m.id = week.map_id
WHERE $2::smallint IS NULL OR $2 =
(SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0)
ORDER BY week.players DESC, m.name LIMIT $1"#,
PLAYED_THIS_WEEK
PLAYED_THIS_WEEK,
tier
)
.fetch_all(db)
.await?
Expand All @@ -303,6 +315,7 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option<i16>) -> Result<MapStat
Ok(MapStats {
maps: rows.iter().map(|row| row.maps).sum(),
by_tier,
tier,
newest,
played_this_week,
})
Expand Down Expand Up @@ -714,6 +727,79 @@ mod tests {
assert_eq!(week, [("bhop_badges", 2), ("bhop_arcane", 1)]);
}

#[sqlx::test]
async fn stats_rank_within_a_tier_before_taking_the_top_five(db: PgPool) {
let key = setup(&db).await;
let policy = crate::policies::Policy::Tiers(crate::policies::TiersPolicy { count: 2 });
crate::policies::publish(&mut db.acquire().await.unwrap(), &policy)
.await
.unwrap();
for index in 0..12 {
let name = format!("bhop_tier_{index:02}");
let players = if index < 5 { 2 } else { 1 };
for player in 0..players {
let mut body = run(&format!("tier-{index}-{player}"), 30.0);
body["map"] = json!(name);
body["player"] = json!({
"steamid64": (76561197960287930_i64 + player).to_string(),
"name": format!("player-{player}"),
});
assert_eq!(
test_client::post(&db, "/v1/runs", Some(&key), &body)
.await
.status,
201
);
}
let map = crate::maps::MapName::try_from(name.clone()).unwrap();
crate::staff::maps::set_tier(&db, None, &map, 0, if index < 5 { 1 } else { 2 })
.await
.unwrap();
sqlx::query(
"UPDATE maps SET listed_at = now() - $1 * interval '1 minute' WHERE name = $2",
)
.bind(f64::from(index))
.bind(name)
.execute(&db)
.await
.unwrap();
}
sqlx::query("UPDATE runs SET finished_at = now() - interval '1 day'")
.execute(&db)
.await
.unwrap();

let all: MapList = test_client::get(&db, "/v1/maps").await.json();
assert_eq!(all.stats.tier, None);
assert!(
all.stats
.played_this_week
.iter()
.all(|map| map.tier == Some(1))
);
assert!(all.stats.newest.iter().all(|map| map.tier == Some(1)));

let filtered: MapList = test_client::get(&db, "/v1/maps?tier=2").await.json();
let expected: Vec<_> = (5..10)
.map(|index| format!("bhop_tier_{index:02}"))
.collect();
assert_eq!(filtered.stats.tier, Some(2));
assert_eq!(
(filtered.stats.maps, filtered.stats.by_tier),
(12, vec![5, 7])
);
assert_eq!(filtered.stats.played_this_week.len(), 5);
assert_eq!(filtered.stats.newest.len(), 5);
for (index, map) in filtered.stats.played_this_week.iter().enumerate() {
assert_eq!(map.name, expected[index]);
assert_eq!((map.tier, map.players), (Some(2), 1));
}
for (index, map) in filtered.stats.newest.iter().enumerate() {
assert_eq!(map.name, expected[index]);
assert_eq!(map.tier, Some(2));
}
}

#[sqlx::test]
async fn sorts_by_record_and_filters_by_completion(db: PgPool) {
let key = setup(&db).await;
Expand Down
10 changes: 9 additions & 1 deletion api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -7862,7 +7862,7 @@
},
"MapStats": {
"type": "object",
"description": "The whole list at a glance, whatever the search or filter.",
"description": "Global totals and tier-scoped newest and weekly lists.",
"required": [
"maps",
"by_tier",
Expand Down Expand Up @@ -7896,6 +7896,14 @@
"$ref": "#/components/schemas/PlayedMap"
},
"description": "The maps the most players finished a run on in the last 7 days, most first."
},
"tier": {
"type": [
"integer",
"null"
],
"format": "int32",
"description": "The tier the newest and weekly lists describe; None describes all tiers. Totals remain global."
}
}
},
Expand Down
4 changes: 2 additions & 2 deletions docs/design-system.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ One visual language for every page, so pages can't drift apart. See it at `/dev/

## Direction
"Classic" (2026-11-07): the old sourcejump.net, updated. Replaced "Navy".
- A slate sheet (`bg`, `shadow-sheet`) between darker gutters. One cyan accent; at most one primary button per view.
- A slate sheet (`bg`, `shadow-sheet`) with gutters, halfway from 72rem to full width. One cyan accent; at most one primary button per view.
- Gamified but professional: medals, tier colors, WR badges, count-ups and small motions. No mascots, confetti, slogans or sales copy.
- Geist: 450 regular, 700 bold, matched to the old Play; Exo 2 bold (`font-server`) for server names. Times and tables use equal-width digits.
- Corners: `rounded-md` (8px) for every frame, from a panel to a field or button; `rounded-sm` (4px) for badges and rows inside a frame.
Expand Down Expand Up @@ -41,7 +41,7 @@ One visual language for every page, so pages can't drift apart. See it at `/dev/
| `DividedList`, `DividedSection` | Rows with lines between them, and a part set off by a line above, inside a `Card` or `Dialog`. The lines run to the surface's edges |
| `StepChart` | A value that changes in steps over time (WR history). Hover snaps a crosshair to the nearest point; points take focus and open their link |
| `LineChart` | One count over time from zero (players online). CSS-stretched, so it fills its box before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart |
| `TierSpread` | Maps per tier: a donut beside each tier's count and share; slices and rows link to that tier's maps, the rest dim; "All tiers" goes back (Maps page) |
| `TierSpread` | Tier donut (bar on phones) and count/share legend. Rows and slices filter maps; "All tiers" resets; other slices dim |
| `Dot` | "·" in a wrapping line; hidden on phones, where it could end one |
| `Tooltip` | Hint on hover and focus; child takes focus |
| `Menu`, `MenuItem`, `MenuLink`, `MenuSeparator` | Menu button (account; `sheet`: phone menu) |
Expand Down
2 changes: 1 addition & 1 deletion docs/site-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirect
- Staff privileges: a bitmap in `players.privileges` (`players/privileges.rs`); bit positions never change; the API names them, never numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant <steamid> <name>…`, `revoke`, `list` and the staff tools share `staff/privileges.rs`.

## Maps and leaderboards
- The map list holds every map with a run (`maps.last_run_at`, set by the ingest); whether one is ranked is open. Sorts: name, players, last/first run (`listed_at`), tier, main-track record; `tier` keeps one tier. `player` (any SteamID form) with `completed=true|false` keeps maps whose main track they have or haven't finished in the list's style; `completed` counts them. `stats`: tiers, 5 newest, 5 most players this week.
- Maps with runs (`maps.last_run_at`, set on ingest); ranking is open. Sorts: name, players, last/first run (`listed_at`), tier and main-track WR. `tier` keeps one main tier. `player` (any SteamID) with `completed=true|false` filters the style's main-track completions; `completed` counts them. `stats` totals stay global; newest and weekly lists take five within `stats.tier` (null: all). Weekly ranks count distinct players.
- Leaderboards rank PBs per map, style and track; equal times share a place, the earlier run listed first. A tie's world record belongs to whoever set it first.
- `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, for map pages to switch locally. `…/leaderboard?cursor=` pages on from there; cursors are opaque.
- WR history: every run faster than all finished before it on that board, by `finished_at`; ties don't count.
Expand Down
Loading
Loading