feat: Phase 3 — polish & settings complete

Card pool:
- TOTW cards (5): overall 88-92, rarity "totw"
- Hero cards (5): overall 85-88, rarity "hero"
- Icon cards (5): overall 93-95, rarity "icon" (permanent, non-loan)

Packs:
- TOTW Pack (30,000 coins): 5 TOTW cards guaranteed
- Icon Pack (50,000 coins): 3 icon cards guaranteed
- Hero Pack (20,000 coins): 5 hero cards guaranteed

Objectives:
- Milestone objectives (6): win 10/50, score 100/500 goals, 10 SBCs, 25 packs

Formations:
- GET /formations returns 12 valid formation strings

Multiple named squads (#20):
- POST /squad with no squad_id always creates a new squad
- POST /squad with squad_id updates that specific squad
- GET /squads: list all squads for the club (metadata only)
- GET /squads/🆔 squad with players + chemistry
- DELETE /squads/🆔 remove a squad

Per-position goal stats (#41):
- Migration 0003: position_goals table
- POST /matches/result accepts optional goal_positions: ["ST","CAM",...]
- GET /statistics now includes position_goals map

Settings (#44-46):
- GET /settings: { difficulty, preferred_formation } with defaults
- PUT /settings: upsert any key-value combination

Draft mode skeleton (#38):
- GET /draft/squad?difficulty=... returns a randomly generated 11-player squad

Integration tests:
- 9 new tests covering: formations, pack buy/open, SBC submit, settings R/W,
  multiple squads, draft endpoint, goal position tracking, win streak

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
funman300
2026-06-25 15:46:20 -07:00
parent 0afce0dd59
commit 4ae1081aa9
21 changed files with 739 additions and 138 deletions
+9 -2
View File
@@ -12,7 +12,7 @@ use crate::{
};
use anyhow::Result;
use axum::{
routing::{get, post},
routing::{delete, get, post, put},
Router,
};
use std::sync::Arc;
@@ -103,6 +103,7 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
let router = Router::new()
.route("/health", get(routes::health::get_health))
.route("/formations", get(routes::health::get_formations))
.route("/auth/local", post(routes::auth::post_auth_local))
.route("/profile", get(routes::profile::get_profile))
.route("/club", get(routes::club::get_club))
@@ -114,6 +115,9 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
.route("/packs/open/:pack_id", post(routes::packs::post_open_pack))
.route("/squad", get(routes::squad::get_squad))
.route("/squad", post(routes::squad::post_squad))
.route("/squads", get(routes::squad::get_squads))
.route("/squads/:squad_id", get(routes::squad::get_squad_by_id))
.route("/squads/:squad_id", delete(routes::squad::delete_squad))
.route("/objectives", get(routes::objectives::get_objectives))
.route(
"/objectives/claim",
@@ -123,8 +127,8 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
.route("/matches/opponent", get(routes::matches::get_opponent))
.route("/matches/result", post(routes::matches::post_match_result))
.route("/sbc", get(routes::sbc::get_sbcs))
.route("/sbc/:sbc_id", get(routes::sbc::get_sbc))
.route("/sbc/submit", post(routes::sbc::post_sbc_submit))
.route("/sbc/:sbc_id", get(routes::sbc::get_sbc))
.route("/market", get(routes::market::get_market))
.route("/market/buy", post(routes::market::post_market_buy))
.route("/market/sell", post(routes::market::post_market_sell))
@@ -134,6 +138,9 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
"/statistics/history",
get(routes::statistics::get_statistics_history),
)
.route("/settings", get(routes::settings::get_settings))
.route("/settings", put(routes::settings::put_settings))
.route("/draft/squad", get(routes::draft::get_draft_squad))
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.with_state(state);
+1
View File
@@ -17,6 +17,7 @@ pub struct SubmitMatchRequest {
pub goals_for: i64,
pub goals_against: i64,
pub mode: String,
pub goal_positions: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
+1
View File
@@ -41,6 +41,7 @@ pub struct SquadPlayer {
#[derive(Debug, Deserialize)]
pub struct SaveSquadRequest {
pub squad_id: Option<String>,
pub name: Option<String>,
pub formation: Option<String>,
pub players: Vec<SquadPlayerInput>,
+32
View File
@@ -0,0 +1,32 @@
use axum::{
extract::{Query, State},
Json,
};
use serde::Deserialize;
use serde_json::{json, Value};
use crate::{app::AppState, error::AppResult, services::match_service};
#[derive(Deserialize)]
pub struct DraftQuery {
pub difficulty: Option<String>,
}
/// Returns a randomly generated draft squad from the card pool.
/// Difficulty controls minimum card overall. The front-end is responsible
/// for presenting per-position pick choices; this endpoint provides the pool.
pub async fn get_draft_squad(
State(state): State<AppState>,
Query(query): Query<DraftQuery>,
) -> AppResult<Json<Value>> {
let difficulty = query.difficulty.as_deref().unwrap_or("beginner");
let generated = match_service::generate_opponent(&state.card_db, difficulty);
Ok(Json(json!({
"mode": "draft",
"difficulty": difficulty,
"squad_rating": generated["squad_rating"],
"formation": generated["formation"],
"cards": generated["cards"],
})))
}
+10
View File
@@ -11,3 +11,13 @@ pub async fn get_health() -> (StatusCode, Json<Value>) {
})),
)
}
pub async fn get_formations() -> Json<Value> {
Json(json!({
"formations": [
"4-4-2", "4-3-3", "4-2-3-1", "4-5-1",
"3-5-2", "3-4-3", "5-3-2", "5-4-1",
"4-1-2-1-2", "4-3-2-1", "4-4-1-1", "4-2-2-2"
]
}))
}
+2
View File
@@ -1,6 +1,7 @@
pub mod auth;
pub mod cards;
pub mod club;
pub mod draft;
pub mod health;
pub mod market;
pub mod matches;
@@ -8,5 +9,6 @@ pub mod objectives;
pub mod packs;
pub mod profile;
pub mod sbc;
pub mod settings;
pub mod squad;
pub mod statistics;
+30
View File
@@ -0,0 +1,30 @@
use axum::{extract::State, Json};
use serde_json::{json, Value};
use crate::{app::AppState, error::AppResult, services::settings as settings_svc};
fn defaults(settings: &std::collections::HashMap<String, String>) -> Value {
json!({
"difficulty": settings.get("difficulty").cloned().unwrap_or_else(|| "beginner".into()),
"preferred_formation": settings.get("preferred_formation").cloned().unwrap_or_else(|| "4-4-2".into()),
})
}
pub async fn get_settings(State(state): State<AppState>) -> AppResult<Json<Value>> {
let settings = settings_svc::get_all(&state.pool).await?;
Ok(Json(defaults(&settings)))
}
pub async fn put_settings(
State(state): State<AppState>,
Json(req): Json<Value>,
) -> AppResult<Json<Value>> {
if let Some(difficulty) = req.get("difficulty").and_then(|v| v.as_str()) {
settings_svc::upsert(&state.pool, "difficulty", difficulty).await?;
}
if let Some(formation) = req.get("preferred_formation").and_then(|v| v.as_str()) {
settings_svc::upsert(&state.pool, "preferred_formation", formation).await?;
}
let settings = settings_svc::get_all(&state.pool).await?;
Ok(Json(defaults(&settings)))
}
+63 -22
View File
@@ -1,4 +1,7 @@
use axum::{extract::State, Json};
use axum::{
extract::{Path, State},
Json,
};
use serde_json::{json, Value};
use crate::{
@@ -15,28 +18,27 @@ pub async fn get_squad(State(state): State<AppState>) -> AppResult<Json<Value>>
let (squad, players) = squad_svc::get_squad(&state.pool, &club.id).await?;
let chemistry = squad_svc::calculate_chemistry(&state.pool, &state.card_db, &players).await?;
let enriched: Vec<Value> = players
.iter()
.map(|sp| {
json!({
"squad_player_id": sp.id,
"owned_card_id": sp.owned_card_id,
"position_index": sp.position_index,
"is_captain": sp.is_captain,
"is_on_bench": sp.is_on_bench,
})
})
.collect();
Ok(Json(squad_response(&squad, &players, chemistry)))
}
Ok(Json(json!({
"squad": {
"id": squad.id,
"name": squad.name,
"formation": squad.formation,
},
"players": enriched,
"chemistry": chemistry,
})))
pub async fn get_squads(State(state): State<AppState>) -> AppResult<Json<Value>> {
let profile = profile_svc::get_active_profile(&state.pool).await?;
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
let squads = squad_svc::list_squads(&state.pool, &club.id).await?;
Ok(Json(json!({ "squads": squads })))
}
pub async fn get_squad_by_id(
State(state): State<AppState>,
Path(squad_id): Path<String>,
) -> AppResult<Json<Value>> {
let profile = profile_svc::get_active_profile(&state.pool).await?;
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
let (squad, players) = squad_svc::get_squad_by_id(&state.pool, &club.id, &squad_id).await?;
let chemistry = squad_svc::calculate_chemistry(&state.pool, &state.card_db, &players).await?;
Ok(Json(squad_response(&squad, &players, chemistry)))
}
pub async fn post_squad(
@@ -53,3 +55,42 @@ pub async fn post_squad(
let squad = squad_svc::save_squad(&state.pool, &club.id, &req).await?;
Ok(Json(json!({ "squad": squad })))
}
pub async fn delete_squad(
State(state): State<AppState>,
Path(squad_id): Path<String>,
) -> AppResult<Json<Value>> {
let profile = profile_svc::get_active_profile(&state.pool).await?;
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
squad_svc::delete_squad(&state.pool, &club.id, &squad_id).await?;
Ok(Json(json!({ "deleted": squad_id })))
}
fn squad_response(
squad: &crate::models::squad::Squad,
players: &[crate::models::squad::SquadPlayer],
chemistry: Value,
) -> Value {
let enriched: Vec<Value> = players
.iter()
.map(|sp| {
json!({
"squad_player_id": sp.id,
"owned_card_id": sp.owned_card_id,
"position_index": sp.position_index,
"is_captain": sp.is_captain,
"is_on_bench": sp.is_on_bench,
})
})
.collect();
json!({
"squad": {
"id": squad.id,
"name": squad.name,
"formation": squad.formation,
},
"players": enriched,
"chemistry": chemistry,
})
}
+14 -3
View File
@@ -8,14 +8,25 @@ use serde_json::{json, Value};
use crate::{
app::AppState,
error::AppResult,
models::{match_result::Match, statistics::Statistics},
models::match_result::Match,
services::{profile as profile_svc, statistics as stats_svc},
};
pub async fn get_statistics(State(state): State<AppState>) -> AppResult<Json<Statistics>> {
pub async fn get_statistics(State(state): State<AppState>) -> AppResult<Json<Value>> {
let profile = profile_svc::get_active_profile(&state.pool).await?;
let stats = stats_svc::get_or_create(&state.pool, &profile.id).await?;
Ok(Json(stats))
let pos_goals = stats_svc::get_position_goals(&state.pool, &profile.id).await?;
let pos_map: serde_json::Map<String, Value> = pos_goals
.into_iter()
.map(|(pos, goals)| (pos, Value::Number(goals.into())))
.collect();
let mut val = serde_json::to_value(&stats)?;
if let Some(obj) = val.as_object_mut() {
obj.insert("position_goals".into(), Value::Object(pos_map));
}
Ok(Json(val))
}
#[derive(Deserialize)]
+4
View File
@@ -148,6 +148,10 @@ pub async fn process_match(
)
.await?;
if let Some(positions) = &req.goal_positions {
statistics::record_position_goals(pool, profile_id, positions).await?;
}
let mut objectives_updated = Vec::new();
let mut completed =
+1
View File
@@ -6,5 +6,6 @@ pub mod objective;
pub mod pack;
pub mod profile;
pub mod sbc;
pub mod settings;
pub mod squad;
pub mod statistics;
+23
View File
@@ -0,0 +1,23 @@
use crate::{db::Pool, error::AppResult};
use std::collections::HashMap;
pub async fn get_all(pool: &Pool) -> AppResult<HashMap<String, String>> {
let rows: Vec<(String, String)> = sqlx::query_as("SELECT key, value FROM settings")
.fetch_all(pool)
.await?;
Ok(rows.into_iter().collect())
}
pub async fn upsert(pool: &Pool, key: &str, value: &str) -> AppResult<()> {
let now = chrono::Utc::now().to_rfc3339();
sqlx::query(
"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) \
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
)
.bind(key)
.bind(value)
.bind(&now)
.execute(pool)
.await?;
Ok(())
}
+76 -27
View File
@@ -11,24 +11,55 @@ use uuid::Uuid;
pub async fn get_squad(pool: &Pool, club_id: &str) -> AppResult<(Squad, Vec<SquadPlayer>)> {
let squad = sqlx::query_as::<_, Squad>(
"SELECT id, club_id, name, formation, created_at, updated_at FROM squads WHERE club_id = ? ORDER BY created_at DESC LIMIT 1"
"SELECT id, club_id, name, formation, created_at, updated_at FROM squads WHERE club_id = ? ORDER BY updated_at DESC LIMIT 1"
)
.bind(club_id)
.fetch_optional(pool)
.await?
.ok_or_else(|| AppError::NotFound("no squad found for this club".into()))?;
let players = sqlx::query_as::<_, SquadPlayer>(
"SELECT id, squad_id, owned_card_id, position_index, is_captain, is_on_bench FROM squad_players WHERE squad_id = ?"
)
.bind(&squad.id)
.fetch_all(pool)
.await?;
let players = get_players(pool, &squad.id).await?;
Ok((squad, players))
}
/// Validate that the squad has exactly 11 starters with exactly one GK.
pub async fn get_squad_by_id(
pool: &Pool,
club_id: &str,
squad_id: &str,
) -> AppResult<(Squad, Vec<SquadPlayer>)> {
let squad = sqlx::query_as::<_, Squad>(
"SELECT id, club_id, name, formation, created_at, updated_at FROM squads WHERE id = ? AND club_id = ?",
)
.bind(squad_id)
.bind(club_id)
.fetch_optional(pool)
.await?
.ok_or_else(|| AppError::NotFound(format!("squad '{squad_id}' not found")))?;
let players = get_players(pool, &squad.id).await?;
Ok((squad, players))
}
pub async fn list_squads(pool: &Pool, club_id: &str) -> AppResult<Vec<Squad>> {
let squads = sqlx::query_as::<_, Squad>(
"SELECT id, club_id, name, formation, created_at, updated_at FROM squads WHERE club_id = ? ORDER BY updated_at DESC",
)
.bind(club_id)
.fetch_all(pool)
.await?;
Ok(squads)
}
async fn get_players(pool: &Pool, squad_id: &str) -> AppResult<Vec<SquadPlayer>> {
let players = sqlx::query_as::<_, SquadPlayer>(
"SELECT id, squad_id, owned_card_id, position_index, is_captain, is_on_bench FROM squad_players WHERE squad_id = ?",
)
.bind(squad_id)
.fetch_all(pool)
.await?;
Ok(players)
}
pub async fn validate_formation(
pool: &Pool,
card_db: &CardDb,
@@ -74,7 +105,6 @@ pub async fn validate_formation(
Ok(())
}
/// Calculate chemistry for the starting XI. Returns total and per-player scores.
pub async fn calculate_chemistry(
pool: &Pool,
card_db: &CardDb,
@@ -98,7 +128,6 @@ pub async fn calculate_chemistry(
}
}
// Per-player chemistry: club links (max 4) + league links (max 3) + nation links (max 3), capped at 10
let player_chems: Vec<i64> = cards
.iter()
.enumerate()
@@ -137,27 +166,34 @@ pub async fn calculate_chemistry(
pub async fn save_squad(pool: &Pool, club_id: &str, req: &SaveSquadRequest) -> AppResult<Squad> {
let now = chrono::Utc::now().to_rfc3339();
let existing = sqlx::query_scalar::<_, Option<String>>(
"SELECT id FROM squads WHERE club_id = ? ORDER BY created_at DESC LIMIT 1",
)
.bind(club_id)
.fetch_one(pool)
.await?;
let squad_id = if let Some(ref id) = req.squad_id {
// Update existing squad — verify ownership
let verified =
sqlx::query_scalar::<_, String>("SELECT id FROM squads WHERE id = ? AND club_id = ?")
.bind(id)
.bind(club_id)
.fetch_optional(pool)
.await?
.ok_or_else(|| AppError::NotFound(format!("squad '{id}' not found")))?;
sqlx::query(
"UPDATE squads SET name = COALESCE(?, name), formation = COALESCE(?, formation), updated_at = ? WHERE id = ?",
)
.bind(req.name.as_deref())
.bind(req.formation.as_deref())
.bind(&now)
.bind(&verified)
.execute(pool)
.await?;
let squad_id = if let Some(id) = existing {
sqlx::query("UPDATE squads SET name = COALESCE(?, name), formation = COALESCE(?, formation), updated_at = ? WHERE id = ?")
.bind(req.name.as_deref())
.bind(req.formation.as_deref())
.bind(&now)
.bind(&id)
.execute(pool)
.await?;
sqlx::query("DELETE FROM squad_players WHERE squad_id = ?")
.bind(&id)
.bind(&verified)
.execute(pool)
.await?;
id
verified
} else {
// Create a new squad
let squad = Squad::new(
club_id,
req.name.as_deref().unwrap_or("My Squad"),
@@ -201,3 +237,16 @@ pub async fn save_squad(pool: &Pool, club_id: &str, req: &SaveSquadRequest) -> A
Ok(squad)
}
pub async fn delete_squad(pool: &Pool, club_id: &str, squad_id: &str) -> AppResult<()> {
let deleted = sqlx::query("DELETE FROM squads WHERE id = ? AND club_id = ?")
.bind(squad_id)
.bind(club_id)
.execute(pool)
.await?;
if deleted.rows_affected() == 0 {
return Err(AppError::NotFound(format!("squad '{squad_id}' not found")));
}
Ok(())
}
+28
View File
@@ -102,3 +102,31 @@ pub async fn increment_sbcs_completed(pool: &Pool, profile_id: &str) -> AppResul
.await?;
Ok(())
}
pub async fn record_position_goals(
pool: &Pool,
profile_id: &str,
positions: &[String],
) -> AppResult<()> {
for position in positions {
sqlx::query(
"INSERT INTO position_goals (profile_id, position, goals) VALUES (?, ?, 1) \
ON CONFLICT(profile_id, position) DO UPDATE SET goals = goals + 1",
)
.bind(profile_id)
.bind(position)
.execute(pool)
.await?;
}
Ok(())
}
pub async fn get_position_goals(pool: &Pool, profile_id: &str) -> AppResult<Vec<(String, i64)>> {
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT position, goals FROM position_goals WHERE profile_id = ? ORDER BY goals DESC",
)
.bind(profile_id)
.fetch_all(pool)
.await?;
Ok(rows)
}