Compare commits
13 Commits
bae0a2bdaa
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 20e281e0cf | |||
| 8819cc76a1 | |||
| 9bdc1633a0 | |||
| 1df03d4287 | |||
| 90210702c3 | |||
| a45155e0c5 | |||
| 82c3d2c85a | |||
| e8be289660 | |||
| 233df1d99d | |||
| 30fae1a2f9 | |||
| c896545cf0 | |||
| 36bc594924 | |||
| 8b1081019f |
@@ -0,0 +1,39 @@
|
|||||||
|
-- Generic owned-content classification on the EXISTING ownership table.
|
||||||
|
--
|
||||||
|
-- Core owns ONE instance-based ownership model for every kind of owned content.
|
||||||
|
-- There is deliberately no parallel "items" table: a manager, a consumable, a
|
||||||
|
-- kit and a player are all rows in `owned_cards`, differing only by
|
||||||
|
-- `content_kind`. Two copies of one definition remain TWO rows (instance-based
|
||||||
|
-- ownership: `card_id` is the definition, `id` is the instance).
|
||||||
|
--
|
||||||
|
-- `content_kind` is a game-INDEPENDENT vocabulary. Game adapters translate their
|
||||||
|
-- own taxonomy (e.g. FIFA 17 `cardsubtypeid` / resource ranges) into one of these
|
||||||
|
-- tokens before ownership reaches Core; a game's numeric ids NEVER land here.
|
||||||
|
--
|
||||||
|
-- BACKFILL: none needed — every pre-existing row is a player card, which is
|
||||||
|
-- exactly the column DEFAULT, so the ALTER backfills all existing ownership as
|
||||||
|
-- 'player' in place. (Verified against a real populated club snapshot: 1986
|
||||||
|
-- owned rows, all players.)
|
||||||
|
ALTER TABLE owned_cards ADD COLUMN content_kind TEXT NOT NULL DEFAULT 'player'
|
||||||
|
CHECK (content_kind IN (
|
||||||
|
'player', 'manager', 'staff', 'consumable',
|
||||||
|
'kit', 'badge', 'ball', 'stadium', 'misc'
|
||||||
|
));
|
||||||
|
|
||||||
|
-- Optional stack count for content that is owned as an instance CARRYING a
|
||||||
|
-- count rather than as a bare instance.
|
||||||
|
--
|
||||||
|
-- Evidence (real profile, 1995 owned items): consumables are instance-based with
|
||||||
|
-- an OPTIONAL count — some carry a wire `amount` (observed 1,2,4,5,10,15), some
|
||||||
|
-- omit the key entirely, and two copies of one definition exist as two distinct
|
||||||
|
-- instances. So a count is a per-instance ATTRIBUTE, never a replacement for the
|
||||||
|
-- instance: NULL means "not a stack", a positive integer is the stack size.
|
||||||
|
-- Collapsing instances into counts is forbidden by the ownership model above.
|
||||||
|
ALTER TABLE owned_cards ADD COLUMN quantity INTEGER
|
||||||
|
CHECK (quantity IS NULL OR quantity >= 1);
|
||||||
|
|
||||||
|
-- Every club projection reads one kind at a time (players for the squad, kits
|
||||||
|
-- for the club room, consumables for the item list), so the club+kind pair is
|
||||||
|
-- the hot access path.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_owned_cards_club_kind
|
||||||
|
ON owned_cards(club_id, content_kind);
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
-- Generalise the two-slot kit designation (migration 0024) into the full set of
|
||||||
|
-- active club designations.
|
||||||
|
--
|
||||||
|
-- Ownership still lives ONLY in `owned_cards`; this table records which owned
|
||||||
|
-- INSTANCE currently occupies each club-scoped role. A row here is a pointer,
|
||||||
|
-- never a second ownership authority.
|
||||||
|
--
|
||||||
|
-- Lifecycle invariants enforced by the schema, not by convention:
|
||||||
|
-- * `PRIMARY KEY (club_id, slot)` — at most one active item per role.
|
||||||
|
-- * `owned_card_id ... UNIQUE` — one owned instance can occupy at most ONE
|
||||||
|
-- slot, so "the same card is both the home and the away kit" is unstorable.
|
||||||
|
-- * `REFERENCES owned_cards(id) ON DELETE CASCADE` — quick-selling/consuming
|
||||||
|
-- the item removes the designation, so a sold item can never be projected
|
||||||
|
-- back to the client as active.
|
||||||
|
-- * the BEFORE UPDATE trigger below — a market transfer moves ownership by
|
||||||
|
-- UPDATE (the row id survives), which no FK action can see, so the
|
||||||
|
-- designation is dropped explicitly before the owner changes.
|
||||||
|
--
|
||||||
|
-- `squad_managers` (migration 0023) is squad-scoped, not club-scoped, and is
|
||||||
|
-- deliberately NOT folded in here.
|
||||||
|
CREATE TABLE IF NOT EXISTS club_active_items (
|
||||||
|
club_id TEXT NOT NULL REFERENCES clubs(id) ON DELETE CASCADE,
|
||||||
|
slot TEXT NOT NULL CHECK (slot IN (
|
||||||
|
'home_kit', 'away_kit', 'badge', 'ball', 'stadium'
|
||||||
|
)),
|
||||||
|
owned_card_id TEXT NOT NULL UNIQUE REFERENCES owned_cards(id) ON DELETE CASCADE,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (club_id, slot)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_club_active_items_owned
|
||||||
|
ON club_active_items(owned_card_id);
|
||||||
|
|
||||||
|
-- Carry every existing kit designation over: 'home' -> 'home_kit',
|
||||||
|
-- 'away' -> 'away_kit'. No designation is lost and none is invented.
|
||||||
|
INSERT INTO club_active_items (club_id, slot, owned_card_id, updated_at)
|
||||||
|
SELECT club_id,
|
||||||
|
CASE slot WHEN 'home' THEN 'home_kit' ELSE 'away_kit' END,
|
||||||
|
owned_card_id,
|
||||||
|
updated_at
|
||||||
|
FROM club_kit_assignments
|
||||||
|
WHERE slot IN ('home', 'away');
|
||||||
|
|
||||||
|
-- 0024's trigger lives ON owned_cards, so DROP TABLE would NOT remove it and
|
||||||
|
-- every subsequent ownership transfer would fail on a missing table. Drop it
|
||||||
|
-- explicitly first, then replace it with the generalised one.
|
||||||
|
DROP TRIGGER IF EXISTS clear_club_kit_assignment_before_transfer;
|
||||||
|
DROP TABLE club_kit_assignments;
|
||||||
|
|
||||||
|
CREATE TRIGGER IF NOT EXISTS clear_club_active_item_before_transfer
|
||||||
|
BEFORE UPDATE OF club_id ON owned_cards
|
||||||
|
WHEN OLD.club_id <> NEW.club_id
|
||||||
|
BEGIN
|
||||||
|
DELETE FROM club_active_items WHERE owned_card_id = OLD.id;
|
||||||
|
END;
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
-- Durable idempotency for applying a consumable to a target.
|
||||||
|
--
|
||||||
|
-- Same discipline as `match_completions` (migration 0022): ONE effect per
|
||||||
|
-- (profile_id, action_identity). A sequential replay, a restart replay, a
|
||||||
|
-- concurrent duplicate, or a retried HTTP request all collide on this UNIQUE and
|
||||||
|
-- are refused BEFORE the target is mutated and BEFORE the source is consumed —
|
||||||
|
-- so a consumable can never be spent twice, and its effect can never be applied
|
||||||
|
-- twice from one spend.
|
||||||
|
--
|
||||||
|
-- `action_identity` is opaque to Core: the game adapter/host derives a stable
|
||||||
|
-- per-application token from its own wire request. Core never parses it.
|
||||||
|
--
|
||||||
|
-- `source_owned_card_id` / `target_owned_card_id` are deliberately NOT foreign
|
||||||
|
-- keys: the source row is DELETEd (or decremented to zero and deleted) by the
|
||||||
|
-- very transaction that writes this record, and the target may later be sold.
|
||||||
|
-- This table is an audit + replay record, not an ownership reference.
|
||||||
|
--
|
||||||
|
-- `effect` is the caller-supplied outcome summary stored verbatim as JSON text.
|
||||||
|
-- Core defines NO per-category formula: what a given consumable does to its
|
||||||
|
-- target is the calling game adapter's reversed behaviour, and an unreversed
|
||||||
|
-- behaviour must not be invented here.
|
||||||
|
CREATE TABLE consumable_applications (
|
||||||
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
profile_id TEXT NOT NULL REFERENCES profiles(id),
|
||||||
|
action_identity TEXT NOT NULL,
|
||||||
|
source_owned_card_id TEXT NOT NULL,
|
||||||
|
source_card_id TEXT NOT NULL,
|
||||||
|
source_content_kind TEXT NOT NULL,
|
||||||
|
-- 1 = the source instance was destroyed; 0 = a stack was decremented.
|
||||||
|
source_consumed INTEGER NOT NULL,
|
||||||
|
-- Remaining stack size after a decrement, NULL when the instance was destroyed.
|
||||||
|
source_quantity_after INTEGER,
|
||||||
|
target_owned_card_id TEXT,
|
||||||
|
effect TEXT NOT NULL,
|
||||||
|
applied_at TEXT NOT NULL,
|
||||||
|
UNIQUE(profile_id, action_identity)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_consumable_applications_profile
|
||||||
|
ON consumable_applications(profile_id);
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- Per-instance match-contract counter on an owned instance.
|
||||||
|
--
|
||||||
|
-- NULLABLE ON PURPOSE. NULL means "Core tracks no contract for this instance",
|
||||||
|
-- which is NOT the same as zero: a game whose contracts start at a pack-fresh
|
||||||
|
-- default (FIFA 17 hands out 7) must supply that default itself, so the number
|
||||||
|
-- stays in the game adapter and never becomes a Core constant. Every row that
|
||||||
|
-- pre-dates this migration therefore reads back NULL and keeps its exact prior
|
||||||
|
-- meaning — the migration is a pure widening, not a backfill.
|
||||||
|
--
|
||||||
|
-- `>= 0` only: the cap is a per-application input (the caller's game rule), not
|
||||||
|
-- a schema invariant, so the CHECK refuses the one value that is nonsense in
|
||||||
|
-- every game rather than pinning someone else's ceiling.
|
||||||
|
--
|
||||||
|
-- ALTER TABLE ADD COLUMN, NEVER a table rebuild: `owned_cards` carries the
|
||||||
|
-- `clear_club_active_item_before_transfer` trigger installed by 0026, and a
|
||||||
|
-- DROP/recreate would silently take it with it — exactly the failure 0026:44-46
|
||||||
|
-- documents for 0024's trigger.
|
||||||
|
ALTER TABLE owned_cards ADD COLUMN contract_matches INTEGER
|
||||||
|
CHECK (contract_matches IS NULL OR contract_matches >= 0);
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
-- Per-instance attribute training on an owned instance.
|
||||||
|
--
|
||||||
|
-- WHY A TABLE AND NOT COLUMNS. A training effect is (attribute slot, amount),
|
||||||
|
-- and a game may author one per slot. Six nullable columns would encode the
|
||||||
|
-- slot in the schema and force a migration to add a seventh; a row per slot
|
||||||
|
-- keeps the slot a value. It is also the smallest shape that lets the PRIMARY
|
||||||
|
-- KEY do the work described below.
|
||||||
|
--
|
||||||
|
-- WHY THE PRIMARY KEY IS (owned_card_id, attribute_index). Whether FIFA 17
|
||||||
|
-- REPLACES, STACKS, MERGES or REFUSES a second training on an attribute that
|
||||||
|
-- already carries one is UNKNOWN: no shipped table encodes it, and the client
|
||||||
|
-- holds no consumable-effect logic at all to reverse (no binary in the install
|
||||||
|
-- reads `fcc_trainingcards`, so effects are server-authoritative). Rather than
|
||||||
|
-- pick one of those behaviours and ship a guess as though it were recovered,
|
||||||
|
-- the key makes a second application to the SAME slot a constraint violation,
|
||||||
|
-- which the apply path turns into an explicit refusal that consumes nothing.
|
||||||
|
-- The unknown is therefore enforced by the schema instead of being papered over.
|
||||||
|
-- When the behaviour is proven, the change is a deliberate one-line relaxation
|
||||||
|
-- plus the arithmetic it implies — not an unpicking of accumulated bad state.
|
||||||
|
--
|
||||||
|
-- `attribute_index` is a slot in CORE's own six-attribute card model, in the
|
||||||
|
-- declaration order of `CardDefinition` (0 pace, 1 shooting, 2 passing,
|
||||||
|
-- 3 dribbling, 4 defending, 5 physical). It is deliberately NOT a FIFA
|
||||||
|
-- attribute name: mapping "GK speed" onto slot 4 is the FIFA 17 adapter's
|
||||||
|
-- reversed knowledge, and Core stays game-neutral by only ever indexing its own
|
||||||
|
-- model. The CHECK pins the slot to that model's width.
|
||||||
|
--
|
||||||
|
-- `amount` is bounded at 99 because it is added to an attribute whose domain is
|
||||||
|
-- 1..=99; a larger stored value could not mean anything. The tighter, per-game
|
||||||
|
-- ceiling (FIFA 17 authors only 5/10/15) is validated at apply time, where the
|
||||||
|
-- game's table is in scope, not here.
|
||||||
|
--
|
||||||
|
-- ON DELETE CASCADE is load-bearing: the pool enables `foreign_keys`
|
||||||
|
-- (`db.rs:20`), so quick-selling or otherwise destroying a trained instance
|
||||||
|
-- takes its training with it and cannot leave a row pointing at a dead item.
|
||||||
|
CREATE TABLE owned_card_training (
|
||||||
|
owned_card_id TEXT NOT NULL REFERENCES owned_cards(id) ON DELETE CASCADE,
|
||||||
|
attribute_index INTEGER NOT NULL CHECK (attribute_index BETWEEN 0 AND 5),
|
||||||
|
amount INTEGER NOT NULL CHECK (amount >= 1 AND amount <= 99),
|
||||||
|
-- The definition that granted it, kept for audit and for the eventual
|
||||||
|
-- lifecycle work; Core never interprets it.
|
||||||
|
source_card_id TEXT NOT NULL,
|
||||||
|
applied_at TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (owned_card_id, attribute_index)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The projection reads every effect for a set of instances on each /collection
|
||||||
|
-- call, so the lookup is by instance.
|
||||||
|
CREATE INDEX idx_owned_card_training_owned ON owned_card_training(owned_card_id);
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- Reshape attribute training to AT MOST ONE effect per instance, replaceable.
|
||||||
|
--
|
||||||
|
-- WHY THIS SUPERSEDES 0029'S SHAPE. 0029 keyed on (owned_card_id,
|
||||||
|
-- attribute_index) and recorded that same-slot behaviour was UNKNOWN, enforcing
|
||||||
|
-- the unknown as a refusal. That was the honest shape while the semantics were
|
||||||
|
-- unrecovered. They are now recovered, and BOTH halves of 0029's shape are
|
||||||
|
-- wrong:
|
||||||
|
--
|
||||||
|
-- * "You can only boost one attribute or all six. You can not do it with 2, 3,
|
||||||
|
-- 4 or 5 attributes." -- so two effects must never coexist on one instance,
|
||||||
|
-- which the old composite key permitted (and which staging demonstrated by
|
||||||
|
-- holding a slot-4 and a slot-1 effect at once).
|
||||||
|
-- * "When you apply a new training card to a player, he loses the improved
|
||||||
|
-- attributes of previous training cards. It does not accumulate, it
|
||||||
|
-- replaces." -- so a second apply REPLACES, it does not refuse.
|
||||||
|
--
|
||||||
|
-- Both quotes are from the contemporaneous FIFA 17-specific training guide
|
||||||
|
-- (fifauteam, published 2016-09-08), corroborated by the shipped table: each
|
||||||
|
-- family has exactly 21 rows = 7 card types x 3 levels, and the 7th type in each
|
||||||
|
-- family (subtypes 57 and 67) is the only one flagged `weightrare = 2` with
|
||||||
|
-- amounts 3/6/10, matching the documented RARE "ALL" card at +3/+6/+10.
|
||||||
|
-- DOCUMENTED, corroborated TABLE_PROVEN. It is NOT LIVE_PROVEN against EA.
|
||||||
|
--
|
||||||
|
-- 0029 is left intact rather than rewritten: it is already applied to the
|
||||||
|
-- supervised staging environment, so migration history matters there.
|
||||||
|
--
|
||||||
|
-- NEW SHAPE. One row per instance, so "one attribute or all six" is a
|
||||||
|
-- representable invariant instead of a convention:
|
||||||
|
-- attribute_index INTEGER NULL -- a slot in Core's six-attribute model, or
|
||||||
|
-- NULL meaning ALL SIX slots (the rare card).
|
||||||
|
-- The PRIMARY KEY on owned_card_id alone is what makes a second application a
|
||||||
|
-- REPLACE (delete-then-insert inside the one apply transaction) rather than an
|
||||||
|
-- accumulation.
|
||||||
|
--
|
||||||
|
-- The 1..=15 amount bound is NOT tightened here: 15 is the single-attribute
|
||||||
|
-- ceiling while the all-six card authors at most 10, and which ceiling applies
|
||||||
|
-- depends on the card family -- a per-game rule that belongs at apply time where
|
||||||
|
-- the game's table is in scope, not in the schema.
|
||||||
|
--
|
||||||
|
-- DATA CARRIED FORWARD: where an instance somehow holds several effects (only
|
||||||
|
-- reachable on staging under 0029's shape), the MOST RECENT survives, which is
|
||||||
|
-- exactly the "replaces" rule applied retroactively.
|
||||||
|
|
||||||
|
CREATE TABLE owned_card_training_new (
|
||||||
|
owned_card_id TEXT NOT NULL PRIMARY KEY REFERENCES owned_cards(id) ON DELETE CASCADE,
|
||||||
|
attribute_index INTEGER CHECK (attribute_index IS NULL OR attribute_index BETWEEN 0 AND 5),
|
||||||
|
amount INTEGER NOT NULL CHECK (amount >= 1 AND amount <= 99),
|
||||||
|
source_card_id TEXT NOT NULL,
|
||||||
|
applied_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO owned_card_training_new
|
||||||
|
(owned_card_id, attribute_index, amount, source_card_id, applied_at)
|
||||||
|
SELECT t.owned_card_id, t.attribute_index, t.amount, t.source_card_id, t.applied_at
|
||||||
|
FROM owned_card_training t
|
||||||
|
JOIN (
|
||||||
|
SELECT owned_card_id, MAX(applied_at) AS newest
|
||||||
|
FROM owned_card_training
|
||||||
|
GROUP BY owned_card_id
|
||||||
|
) pick
|
||||||
|
ON pick.owned_card_id = t.owned_card_id
|
||||||
|
AND pick.newest = t.applied_at
|
||||||
|
GROUP BY t.owned_card_id;
|
||||||
|
|
||||||
|
DROP TABLE owned_card_training;
|
||||||
|
ALTER TABLE owned_card_training_new RENAME TO owned_card_training;
|
||||||
+8
-2
@@ -172,8 +172,9 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
|||||||
// ClubB: squad manager assignment (append-only; own lines).
|
// ClubB: squad manager assignment (append-only; own lines).
|
||||||
.route("/club/manager", get(routes::club::get_squad_manager))
|
.route("/club/manager", get(routes::club::get_squad_manager))
|
||||||
.route("/club/manager", put(routes::club::put_squad_manager))
|
.route("/club/manager", put(routes::club::put_squad_manager))
|
||||||
.route("/club/kits", get(routes::club::get_active_kits))
|
// Active club-item designations (home/away kit, badge, ball, stadium).
|
||||||
.route("/club/kits", put(routes::club::put_active_kits))
|
.route("/club/active-items", get(routes::club::get_active_items))
|
||||||
|
.route("/club/active-items", put(routes::club::put_active_item))
|
||||||
.route("/cards", get(routes::cards::get_cards))
|
.route("/cards", get(routes::cards::get_cards))
|
||||||
.route("/cards/:card_id", get(routes::cards::get_card))
|
.route("/cards/:card_id", get(routes::cards::get_card))
|
||||||
.route("/collection", get(routes::cards::get_collection))
|
.route("/collection", get(routes::cards::get_collection))
|
||||||
@@ -191,6 +192,10 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
|||||||
post(routes::economy::post_redeem_entitlement),
|
post(routes::economy::post_redeem_entitlement),
|
||||||
)
|
)
|
||||||
.route("/economy/sell-item", post(routes::economy::post_sell_item))
|
.route("/economy/sell-item", post(routes::economy::post_sell_item))
|
||||||
|
.route(
|
||||||
|
"/consumables/apply",
|
||||||
|
post(routes::consumables::post_apply_consumable),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/economy/grant-reward",
|
"/economy/grant-reward",
|
||||||
post(routes::economy::post_grant_reward),
|
post(routes::economy::post_grant_reward),
|
||||||
@@ -236,6 +241,7 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
|||||||
.route("/squad", post(routes::squad::post_squad))
|
.route("/squad", post(routes::squad::post_squad))
|
||||||
.route("/squad/ext", get(routes::squad::get_squad_ext))
|
.route("/squad/ext", get(routes::squad::get_squad_ext))
|
||||||
.route("/squad/replace", put(routes::squad::put_squad_replace))
|
.route("/squad/replace", put(routes::squad::put_squad_replace))
|
||||||
|
.route("/squad/roles", put(routes::squad::put_squad_roles))
|
||||||
.route("/squads", get(routes::squad::get_squads))
|
.route("/squads", get(routes::squad::get_squads))
|
||||||
.route("/squads/:squad_id", get(routes::squad::get_squad_by_id))
|
.route("/squads/:squad_id", get(routes::squad::get_squad_by_id))
|
||||||
.route("/squads/:squad_id", delete(routes::squad::delete_squad))
|
.route("/squads/:squad_id", delete(routes::squad::delete_squad))
|
||||||
|
|||||||
+23
@@ -57,6 +57,29 @@ async fn main() -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `openfut-core reclassify <request.json> [--dry-run]` — correct the
|
||||||
|
// content_kind of already-imported owned rows. A profile import is
|
||||||
|
// once-only, so a taxonomy fix cannot arrive by re-importing; the adapter
|
||||||
|
// supplies card_id -> kind because only it can map its own taxonomy.
|
||||||
|
// Idempotent. `--dry-run` runs the same statements and rolls back, so an
|
||||||
|
// operator can see what a production run would touch before it touches it.
|
||||||
|
if std::env::args().nth(1).as_deref() == Some("reclassify") {
|
||||||
|
let path = std::env::args()
|
||||||
|
.nth(2)
|
||||||
|
.context("usage: openfut-core reclassify <request.json> [--dry-run]")?;
|
||||||
|
let dry_run = std::env::args().any(|a| a == "--dry-run");
|
||||||
|
let pool = db::init_pool(&cfg.database_url, cfg.max_connections).await?;
|
||||||
|
db::run_migrations(&pool).await?;
|
||||||
|
let raw = std::fs::read_to_string(&path)
|
||||||
|
.with_context(|| format!("read reclassify request {path}"))?;
|
||||||
|
let mut req: openfut_core::services::import::ReclassifyRequest =
|
||||||
|
serde_json::from_str(&raw).context("parse reclassify request JSON")?;
|
||||||
|
req.dry_run |= dry_run;
|
||||||
|
let outcome = openfut_core::services::import::reclassify_owned_content(&pool, &req).await?;
|
||||||
|
println!("{}", serde_json::to_string_pretty(&outcome)?);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
info!("OpenFUT Core starting on {}", cfg.listen_addr);
|
info!("OpenFUT Core starting on {}", cfg.listen_addr);
|
||||||
|
|
||||||
let pool = db::init_pool(&cfg.database_url, cfg.max_connections).await?;
|
let pool = db::init_pool(&cfg.database_url, cfg.max_connections).await?;
|
||||||
|
|||||||
+263
-1
@@ -54,6 +54,165 @@ impl Quality {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What KIND of content one owned instance is.
|
||||||
|
///
|
||||||
|
/// The game-independent ownership vocabulary: Core has exactly one instance-based
|
||||||
|
/// ownership model (`owned_cards`) and this enum is the only thing that
|
||||||
|
/// distinguishes a manager from a player from a chemistry style. It carries NO
|
||||||
|
/// game numerics — a game adapter translates its own taxonomy (FIFA 17
|
||||||
|
/// `cardsubtypeid`, resource ranges, …) into these tokens before ownership
|
||||||
|
/// reaches Core, and translates them back on the way out.
|
||||||
|
///
|
||||||
|
/// The tokens are the persisted values of `owned_cards.content_kind` and are
|
||||||
|
/// pinned by that column's CHECK constraint (migration 0025).
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
#[sqlx(rename_all = "lowercase")]
|
||||||
|
pub enum ContentKind {
|
||||||
|
/// A playable footballer card.
|
||||||
|
#[default]
|
||||||
|
Player,
|
||||||
|
/// A squad manager.
|
||||||
|
Manager,
|
||||||
|
/// Non-manager club staff (fitness/goalkeeping/… coaches, physios, scouts).
|
||||||
|
Staff,
|
||||||
|
/// A single-use item applied to a target (contract, fitness, healing,
|
||||||
|
/// chemistry style, position modifier, training).
|
||||||
|
Consumable,
|
||||||
|
/// A club kit (occupies the home or away designation).
|
||||||
|
Kit,
|
||||||
|
/// A club badge/crest.
|
||||||
|
Badge,
|
||||||
|
/// A match ball.
|
||||||
|
Ball,
|
||||||
|
/// A club stadium.
|
||||||
|
Stadium,
|
||||||
|
/// Owned content that is legitimately none of the above.
|
||||||
|
Misc,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentKind {
|
||||||
|
/// The canonical persisted token.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ContentKind::Player => "player",
|
||||||
|
ContentKind::Manager => "manager",
|
||||||
|
ContentKind::Staff => "staff",
|
||||||
|
ContentKind::Consumable => "consumable",
|
||||||
|
ContentKind::Kit => "kit",
|
||||||
|
ContentKind::Badge => "badge",
|
||||||
|
ContentKind::Ball => "ball",
|
||||||
|
ContentKind::Stadium => "stadium",
|
||||||
|
ContentKind::Misc => "misc",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every kind, in declaration order (for exhaustive round-trip checks).
|
||||||
|
pub const ALL: [ContentKind; 9] = [
|
||||||
|
ContentKind::Player,
|
||||||
|
ContentKind::Manager,
|
||||||
|
ContentKind::Staff,
|
||||||
|
ContentKind::Consumable,
|
||||||
|
ContentKind::Kit,
|
||||||
|
ContentKind::Badge,
|
||||||
|
ContentKind::Ball,
|
||||||
|
ContentKind::Stadium,
|
||||||
|
ContentKind::Misc,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ContentKind {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::str::FromStr for ContentKind {
|
||||||
|
type Err = String;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"player" => Ok(ContentKind::Player),
|
||||||
|
"manager" => Ok(ContentKind::Manager),
|
||||||
|
"staff" => Ok(ContentKind::Staff),
|
||||||
|
"consumable" => Ok(ContentKind::Consumable),
|
||||||
|
"kit" => Ok(ContentKind::Kit),
|
||||||
|
"badge" => Ok(ContentKind::Badge),
|
||||||
|
"ball" => Ok(ContentKind::Ball),
|
||||||
|
"stadium" => Ok(ContentKind::Stadium),
|
||||||
|
"misc" => Ok(ContentKind::Misc),
|
||||||
|
other => Err(format!("unknown content kind '{other}'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A club-scoped "active item" designation slot.
|
||||||
|
///
|
||||||
|
/// One owned instance may occupy at most one slot and each slot holds at most one
|
||||||
|
/// instance (migration 0026 `club_active_items`). Each slot admits exactly one
|
||||||
|
/// [`ContentKind`], so a badge can never be installed as a kit.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ActiveSlot {
|
||||||
|
HomeKit,
|
||||||
|
AwayKit,
|
||||||
|
Badge,
|
||||||
|
Ball,
|
||||||
|
Stadium,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActiveSlot {
|
||||||
|
/// The canonical persisted token (`club_active_items.slot`).
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
ActiveSlot::HomeKit => "home_kit",
|
||||||
|
ActiveSlot::AwayKit => "away_kit",
|
||||||
|
ActiveSlot::Badge => "badge",
|
||||||
|
ActiveSlot::Ball => "ball",
|
||||||
|
ActiveSlot::Stadium => "stadium",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one content kind this slot accepts.
|
||||||
|
pub fn required_kind(self) -> ContentKind {
|
||||||
|
match self {
|
||||||
|
ActiveSlot::HomeKit | ActiveSlot::AwayKit => ContentKind::Kit,
|
||||||
|
ActiveSlot::Badge => ContentKind::Badge,
|
||||||
|
ActiveSlot::Ball => ContentKind::Ball,
|
||||||
|
ActiveSlot::Stadium => ContentKind::Stadium,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const ALL: [ActiveSlot; 5] = [
|
||||||
|
ActiveSlot::HomeKit,
|
||||||
|
ActiveSlot::AwayKit,
|
||||||
|
ActiveSlot::Badge,
|
||||||
|
ActiveSlot::Ball,
|
||||||
|
ActiveSlot::Stadium,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ActiveSlot {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str(self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::str::FromStr for ActiveSlot {
|
||||||
|
type Err = String;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"home_kit" => Ok(ActiveSlot::HomeKit),
|
||||||
|
"away_kit" => Ok(ActiveSlot::AwayKit),
|
||||||
|
"badge" => Ok(ActiveSlot::Badge),
|
||||||
|
"ball" => Ok(ActiveSlot::Ball),
|
||||||
|
"stadium" => Ok(ActiveSlot::Stadium),
|
||||||
|
other => Err(format!("unknown active-item slot '{other}'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A card definition loaded from JSON data files.
|
/// A card definition loaded from JSON data files.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct CardDefinition {
|
pub struct CardDefinition {
|
||||||
@@ -72,9 +231,28 @@ pub struct CardDefinition {
|
|||||||
pub physical: u8,
|
pub physical: u8,
|
||||||
pub rarity: Rarity,
|
pub rarity: Rarity,
|
||||||
pub image_path: Option<String>,
|
pub image_path: Option<String>,
|
||||||
|
/// EA's authored definition rating for a NON-PLAYER: a staff card's `value`
|
||||||
|
/// from its shipped family table, or a consumable's own rating.
|
||||||
|
///
|
||||||
|
/// This is deliberately NOT `overall`. `overall` feeds pricing and squad
|
||||||
|
/// projection, so it stays 0 for every non-player; `source_rating` is the
|
||||||
|
/// separate authoritative number the game's own tier rules read (bronze
|
||||||
|
/// `<65`, silver `65..=74`, gold `>=75`). `None` for players, whose rating
|
||||||
|
/// IS `overall`, and `None` whenever Core tracks no authored value — a
|
||||||
|
/// caller MUST fail closed rather than substitute a tier.
|
||||||
|
///
|
||||||
|
/// MUST stay `Option`: `CardDefinition` has no `#[serde(default)]`, so a
|
||||||
|
/// required field would reject every already-shipped content pack, whereas
|
||||||
|
/// a missing `Option` deserializes to `None`.
|
||||||
|
pub source_rating: Option<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A card instance owned by a club (stored in DB).
|
/// One owned content INSTANCE (stored in DB).
|
||||||
|
///
|
||||||
|
/// Instance-based: `id` is the instance, `card_id` the definition, so two copies
|
||||||
|
/// of one definition are two rows. `content_kind` says what the instance IS;
|
||||||
|
/// `quantity` is an optional per-instance stack size (`None` = not a stack) and
|
||||||
|
/// never a substitute for an instance.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
pub struct OwnedCard {
|
pub struct OwnedCard {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@@ -86,4 +264,88 @@ pub struct OwnedCard {
|
|||||||
pub chemistry_style: String,
|
pub chemistry_style: String,
|
||||||
pub position_override: Option<String>,
|
pub position_override: Option<String>,
|
||||||
pub training_bonus: i64,
|
pub training_bonus: i64,
|
||||||
|
pub content_kind: ContentKind,
|
||||||
|
pub quantity: Option<i64>,
|
||||||
|
/// Match-contracts remaining on this instance, or `None` when Core tracks
|
||||||
|
/// no contract for it. `None` is not zero: the pack-fresh starting value is
|
||||||
|
/// a per-game rule the caller supplies, never a Core default.
|
||||||
|
pub contract_matches: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ONE canonical column list for reading an [`OwnedCard`].
|
||||||
|
///
|
||||||
|
/// `sqlx::FromRow` needs every field present in the row, so a hand-written
|
||||||
|
/// partial column list decodes into a runtime `ColumnNotFound` rather than a
|
||||||
|
/// compile error. Every read goes through this const so adding a column can
|
||||||
|
/// never leave a stale SELECT behind; append `WHERE …` to it.
|
||||||
|
pub const OWNED_CARD_SELECT: &str = "SELECT id, club_id, card_id, is_loan, \
|
||||||
|
loan_matches_remaining, acquired_at, chemistry_style, position_override, \
|
||||||
|
training_bonus, content_kind, quantity, contract_matches FROM owned_cards";
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// The persisted token, the serde token and the parser MUST agree for every
|
||||||
|
/// kind: the DB CHECK, the HTTP body and the adapter all read the same
|
||||||
|
/// vocabulary, so a divergence would silently mis-classify ownership.
|
||||||
|
#[test]
|
||||||
|
fn content_kind_round_trips_token_serde_and_parse() {
|
||||||
|
for kind in ContentKind::ALL {
|
||||||
|
let token = kind.as_str();
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&kind).unwrap(),
|
||||||
|
format!("\"{token}\""),
|
||||||
|
"serde token must equal the persisted token"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_str::<ContentKind>(&format!("\"{token}\"")).unwrap(),
|
||||||
|
kind
|
||||||
|
);
|
||||||
|
assert_eq!(ContentKind::from_str(token).unwrap(), kind);
|
||||||
|
assert_eq!(kind.to_string(), token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vocabulary is closed and pinned to migration 0025's CHECK list.
|
||||||
|
#[test]
|
||||||
|
fn content_kind_vocabulary_is_exactly_the_contract() {
|
||||||
|
let tokens: Vec<&str> = ContentKind::ALL.iter().map(|k| k.as_str()).collect();
|
||||||
|
assert_eq!(
|
||||||
|
tokens,
|
||||||
|
vec![
|
||||||
|
"player",
|
||||||
|
"manager",
|
||||||
|
"staff",
|
||||||
|
"consumable",
|
||||||
|
"kit",
|
||||||
|
"badge",
|
||||||
|
"ball",
|
||||||
|
"stadium",
|
||||||
|
"misc"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(ContentKind::from_str("Player").is_err(), "case-sensitive");
|
||||||
|
assert!(ContentKind::from_str("coach").is_err());
|
||||||
|
assert_eq!(ContentKind::default(), ContentKind::Player);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn active_slot_round_trips_and_pins_its_required_kind() {
|
||||||
|
for slot in ActiveSlot::ALL {
|
||||||
|
let token = slot.as_str();
|
||||||
|
assert_eq!(ActiveSlot::from_str(token).unwrap(), slot);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_string(&slot).unwrap(),
|
||||||
|
format!("\"{token}\"")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(ActiveSlot::HomeKit.required_kind(), ContentKind::Kit);
|
||||||
|
assert_eq!(ActiveSlot::AwayKit.required_kind(), ContentKind::Kit);
|
||||||
|
assert_eq!(ActiveSlot::Badge.required_kind(), ContentKind::Badge);
|
||||||
|
assert_eq!(ActiveSlot::Ball.required_kind(), ContentKind::Ball);
|
||||||
|
assert_eq!(ActiveSlot::Stadium.required_kind(), ContentKind::Stadium);
|
||||||
|
assert!(ActiveSlot::from_str("home").is_err(), "0024's old token");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -133,6 +133,23 @@ pub struct CompleteMatchRequest {
|
|||||||
/// its own wire). Only a caller using Core's season model opts in.
|
/// its own wire). Only a caller using Core's season model opts in.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub advance_season: bool,
|
pub advance_season: bool,
|
||||||
|
/// Owned-card instances that TOOK THE FIELD in this match, whose one-match
|
||||||
|
/// training effects it consumes.
|
||||||
|
///
|
||||||
|
/// Supplied by the caller rather than derived here, and deliberately so.
|
||||||
|
/// FIFA 17's training rule keys on the player PLAYING, and who played is
|
||||||
|
/// game-specific knowledge Core does not have: its match wire carries no
|
||||||
|
/// lineup at all (LIVE_PROVEN over 36,149 captured requests). Core must also
|
||||||
|
/// not resolve it from the squad at completion time, because the squad at
|
||||||
|
/// end is provably not the squad that started — a captured match began at
|
||||||
|
/// 20:33:20 and the next squad save landed 12 minutes later with no
|
||||||
|
/// `/match/end` in between. The adapter therefore snapshots at kickoff and
|
||||||
|
/// passes the result here.
|
||||||
|
///
|
||||||
|
/// Empty expires nothing, so a caller that cannot identify participants is
|
||||||
|
/// simply inert instead of clearing a whole club.
|
||||||
|
#[serde(default)]
|
||||||
|
pub participants: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Outcome of [`crate::services::match_service::complete_match`].
|
/// Outcome of [`crate::services::match_service::complete_match`].
|
||||||
@@ -158,6 +175,10 @@ pub struct MatchCompletionResult {
|
|||||||
/// Owned card ids removed because their loan expired on this match. Empty
|
/// Owned card ids removed because their loan expired on this match. Empty
|
||||||
/// unless the caller set `expire_loans`, and empty on a replay.
|
/// unless the caller set `expire_loans`, and empty on a replay.
|
||||||
pub expired_loans: Vec<String>,
|
pub expired_loans: Vec<String>,
|
||||||
|
/// Owned card instances whose one-match training effect this match consumed.
|
||||||
|
/// Empty when the caller passed no participants, and empty on a replay —
|
||||||
|
/// the effect is consumed exactly once, by the first completion.
|
||||||
|
pub expired_training: Vec<String>,
|
||||||
/// Present when this match ended a Core season. `None` unless the caller set
|
/// Present when this match ended a Core season. `None` unless the caller set
|
||||||
/// `advance_season`, and `None` on a replay.
|
/// `advance_season`, and `None` on a replay.
|
||||||
pub season_end: Option<crate::models::season::SeasonEndSummary>,
|
pub season_end: Option<crate::models::season::SeasonEndSummary>,
|
||||||
|
|||||||
+94
-44
@@ -9,11 +9,11 @@ use serde_json::{json, Value};
|
|||||||
use crate::{
|
use crate::{
|
||||||
app::AppState,
|
app::AppState,
|
||||||
error::{AppError, AppResult},
|
error::{AppError, AppResult},
|
||||||
models::card::OwnedCard,
|
models::card::{OwnedCard, OWNED_CARD_SELECT},
|
||||||
services::{
|
services::{
|
||||||
club as club_svc, economy as economy_svc,
|
club as club_svc, economy as economy_svc,
|
||||||
inventory::{self, OwnedItemQuery, OwnedItemView},
|
inventory::{self, OwnedItemQuery, OwnedItemView},
|
||||||
profile as profile_svc,
|
profile as profile_svc, training as training_svc,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -114,45 +114,91 @@ pub async fn get_collection(
|
|||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
|
|
||||||
let owned = sqlx::query_as::<_, OwnedCard>(
|
let owned = sqlx::query_as::<_, OwnedCard>(&format!("{OWNED_CARD_SELECT} WHERE club_id = ?"))
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, chemistry_style, position_override, training_bonus FROM owned_cards WHERE club_id = ?"
|
.bind(&club.id)
|
||||||
)
|
.fetch_all(&state.pool)
|
||||||
.bind(&club.id)
|
.await?;
|
||||||
.fetch_all(&state.pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let views: Vec<OwnedItemView> = owned
|
// One query for the whole club, not one per item: this projection walks
|
||||||
.iter()
|
// every owned row, and a per-item lookup here is the N+1 it has suffered
|
||||||
.filter_map(|o| {
|
// before.
|
||||||
state.card_db.get(&o.card_id).map(|def| {
|
let training = training_svc::load_for_club(&state.pool, &club.id).await?;
|
||||||
let effective_overall = def.overall as i64 + o.training_bonus;
|
|
||||||
let effective_position = o.position_override.as_deref().unwrap_or(&def.position);
|
|
||||||
let body = json!({
|
|
||||||
"owned_card_id": o.id,
|
|
||||||
"is_loan": o.is_loan,
|
|
||||||
"loan_matches_remaining": o.loan_matches_remaining,
|
|
||||||
"acquired_at": o.acquired_at,
|
|
||||||
"chemistry_style": o.chemistry_style,
|
|
||||||
"position_override": o.position_override,
|
|
||||||
"training_bonus": o.training_bonus,
|
|
||||||
"effective_overall": effective_overall,
|
|
||||||
"effective_position": effective_position,
|
|
||||||
"card": def,
|
|
||||||
});
|
|
||||||
OwnedItemView {
|
|
||||||
owned_card_id: o.id.clone(),
|
|
||||||
base_overall: def.overall,
|
|
||||||
effective_overall,
|
|
||||||
position: effective_position.to_string(),
|
|
||||||
nation: def.nation.clone(),
|
|
||||||
league: def.league.clone(),
|
|
||||||
club: def.club.clone(),
|
|
||||||
body,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
|
// An owned row whose definition is absent from the loaded content CANNOT be
|
||||||
|
// projected (there is nothing to project), but it must never vanish in
|
||||||
|
// silence: that silent `filter_map` drop is how a real club once served
|
||||||
|
// `total: 0` while 1986 owned rows sat in the DB. So: keep the drop (a
|
||||||
|
// missing definition is not a 500), but LOG each one and report the count in
|
||||||
|
// the envelope so a caller and an operator both see it.
|
||||||
|
let mut unresolved: Vec<&str> = Vec::new();
|
||||||
|
let mut views: Vec<OwnedItemView> = Vec::with_capacity(owned.len());
|
||||||
|
for o in &owned {
|
||||||
|
let Some(def) = state.card_db.get(&o.card_id) else {
|
||||||
|
tracing::warn!(
|
||||||
|
owned_card_id = %o.id,
|
||||||
|
card_id = %o.card_id,
|
||||||
|
content_kind = %o.content_kind,
|
||||||
|
club_id = %club.id,
|
||||||
|
"owned item dropped from /collection: no card definition loaded"
|
||||||
|
);
|
||||||
|
unresolved.push(o.card_id.as_str());
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let effective_overall = def.overall as i64 + o.training_bonus;
|
||||||
|
let effective_position = o.position_override.as_deref().unwrap_or(&def.position);
|
||||||
|
// Attribute training is per-instance state, so the finished attributes
|
||||||
|
// belong in the envelope beside the finished rating. The raw effect goes
|
||||||
|
// out too: a caller that needs to show WHICH attribute was trained
|
||||||
|
// cannot recover that by differencing against a definition it may not
|
||||||
|
// have. At most ONE effect per instance -- FIFA 17 replaces rather than
|
||||||
|
// accumulates, so this is an Option, not a list.
|
||||||
|
let effect = training.get(&o.id);
|
||||||
|
let body = json!({
|
||||||
|
"owned_card_id": o.id,
|
||||||
|
"content_kind": o.content_kind,
|
||||||
|
"quantity": o.quantity,
|
||||||
|
"is_loan": o.is_loan,
|
||||||
|
"loan_matches_remaining": o.loan_matches_remaining,
|
||||||
|
"acquired_at": o.acquired_at,
|
||||||
|
"chemistry_style": o.chemistry_style,
|
||||||
|
"position_override": o.position_override,
|
||||||
|
"training_bonus": o.training_bonus,
|
||||||
|
// Core's stored value verbatim: `null` means Core tracks no contract
|
||||||
|
// for this instance, which is NOT zero. Substituting a default here
|
||||||
|
// would bake one game's pack-fresh number into every game's envelope.
|
||||||
|
"contract_matches": o.contract_matches,
|
||||||
|
"effective_overall": effective_overall,
|
||||||
|
"effective_position": effective_position,
|
||||||
|
"effective_attributes": training_svc::effective_attributes_json(def, effect),
|
||||||
|
"training": effect,
|
||||||
|
"card": def,
|
||||||
|
});
|
||||||
|
views.push(OwnedItemView {
|
||||||
|
owned_card_id: o.id.clone(),
|
||||||
|
content_kind: o.content_kind,
|
||||||
|
base_overall: def.overall,
|
||||||
|
effective_overall,
|
||||||
|
position: effective_position.to_string(),
|
||||||
|
nation: def.nation.clone(),
|
||||||
|
league: def.league.clone(),
|
||||||
|
club: def.club.clone(),
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !unresolved.is_empty() {
|
||||||
|
unresolved.sort_unstable();
|
||||||
|
unresolved.dedup();
|
||||||
|
tracing::warn!(
|
||||||
|
club_id = %club.id,
|
||||||
|
owned_rows = owned.len(),
|
||||||
|
dropped = owned.len() - views.len(),
|
||||||
|
definitions = ?unresolved,
|
||||||
|
"/collection dropped owned items with missing definitions"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let owned_rows = owned.len();
|
||||||
|
let unresolved_items = owned_rows - views.len();
|
||||||
let page = inventory::apply_query(views, &query);
|
let page = inventory::apply_query(views, &query);
|
||||||
let returned = page.items.len();
|
let returned = page.items.len();
|
||||||
Ok(Json(json!({
|
Ok(Json(json!({
|
||||||
@@ -161,6 +207,12 @@ pub async fn get_collection(
|
|||||||
"returned": returned,
|
"returned": returned,
|
||||||
"offset": page.offset,
|
"offset": page.offset,
|
||||||
"limit": page.limit,
|
"limit": page.limit,
|
||||||
|
// Ownership truth vs. what could be projected. `owned_rows` counts every
|
||||||
|
// row Core actually owns for this club; `unresolved_items` counts those
|
||||||
|
// dropped for want of a definition. Both zero-cost when nothing is wrong.
|
||||||
|
"owned_rows": owned_rows,
|
||||||
|
"unresolved_items": unresolved_items,
|
||||||
|
"unresolved_definitions": unresolved,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,11 +225,9 @@ pub async fn delete_owned_card(
|
|||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
|
|
||||||
let owned = sqlx::query_as::<_, OwnedCard>(
|
let owned = sqlx::query_as::<_, OwnedCard>(&format!(
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, \
|
"{OWNED_CARD_SELECT} WHERE id = ? AND club_id = ?"
|
||||||
chemistry_style, position_override, training_bonus \
|
))
|
||||||
FROM owned_cards WHERE id = ? AND club_id = ?",
|
|
||||||
)
|
|
||||||
.bind(&owned_card_id)
|
.bind(&owned_card_id)
|
||||||
.bind(&club.id)
|
.bind(&club.id)
|
||||||
.fetch_optional(&state.pool)
|
.fetch_optional(&state.pool)
|
||||||
|
|||||||
+76
-29
@@ -1,8 +1,8 @@
|
|||||||
use crate::extractors::GameId;
|
use crate::extractors::GameId;
|
||||||
use crate::{
|
use crate::{
|
||||||
app::AppState,
|
app::AppState,
|
||||||
error::AppResult,
|
error::{AppError, AppResult},
|
||||||
models::club::Club,
|
models::{card::ActiveSlot, club::Club},
|
||||||
services::{
|
services::{
|
||||||
checkin as checkin_svc, club as club_svc, profile as profile_svc, statistics as stats_svc,
|
checkin as checkin_svc, club as club_svc, profile as profile_svc, statistics as stats_svc,
|
||||||
},
|
},
|
||||||
@@ -10,6 +10,7 @@ use crate::{
|
|||||||
use axum::{extract::State, Json};
|
use axum::{extract::State, Json};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
pub async fn get_club(State(state): State<AppState>, game: GameId) -> AppResult<Json<Club>> {
|
pub async fn get_club(State(state): State<AppState>, game: GameId) -> AppResult<Json<Club>> {
|
||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
@@ -138,15 +139,36 @@ pub async fn get_squad_manager(
|
|||||||
Ok(Json(json!({ "manager": manager })))
|
Ok(Json(json!({ "manager": manager })))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A manager write. The three states are DISTINCT and must stay that way:
|
||||||
|
///
|
||||||
|
/// | body | meaning |
|
||||||
|
/// | --- | --- |
|
||||||
|
/// | `{}` — field absent | say nothing about the manager; leave it as it is |
|
||||||
|
/// | `{"owned_card_id": null}` | explicitly remove the current manager |
|
||||||
|
/// | `{"owned_card_id": "<id>"}` | assign that owned card |
|
||||||
|
///
|
||||||
|
/// A plain `Option<String>` collapsed the first two into `None`, so a caller
|
||||||
|
/// that simply had nothing to say silently deleted the assignment. That is how a
|
||||||
|
/// FIFA 17 client with a destroyed squad model wiped a real manager row. The
|
||||||
|
/// double option keeps "absent" and "null" apart.
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct SetManagerRequest {
|
pub struct SetManagerRequest {
|
||||||
/// The owned card to assign as manager, or `null`/absent to clear it.
|
#[serde(default, deserialize_with = "deserialize_present_option")]
|
||||||
pub owned_card_id: Option<String>,
|
pub owned_card_id: Option<Option<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Assign (or, with a null/absent `owned_card_id`, clear) the active squad's
|
/// Deserialize a field that is present-but-null into `Some(None)`, leaving an
|
||||||
/// manager. Fail-closed: the card must be owned by this club and the club must
|
/// absent field as `None` (supplied by `#[serde(default)]`).
|
||||||
/// have a squad. Returns the resulting assignment.
|
fn deserialize_present_option<'de, D>(d: D) -> Result<Option<Option<String>>, D::Error>
|
||||||
|
where
|
||||||
|
D: serde::Deserializer<'de>,
|
||||||
|
{
|
||||||
|
Option::<String>::deserialize(d).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assign, explicitly remove, or leave unchanged the active squad's manager.
|
||||||
|
/// Fail-closed: the card must be owned by this club and the club must have a
|
||||||
|
/// squad. Returns the resulting assignment.
|
||||||
pub async fn put_squad_manager(
|
pub async fn put_squad_manager(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
game: GameId,
|
game: GameId,
|
||||||
@@ -155,48 +177,73 @@ pub async fn put_squad_manager(
|
|||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
match req.owned_card_id {
|
match req.owned_card_id {
|
||||||
Some(owned_card_id) => {
|
Some(Some(owned_card_id)) => {
|
||||||
club_svc::set_squad_manager(&state.pool, &club.id, &owned_card_id).await?
|
club_svc::set_squad_manager(&state.pool, &club.id, &owned_card_id).await?
|
||||||
}
|
}
|
||||||
None => club_svc::clear_squad_manager(&state.pool, &club.id).await?,
|
// Explicit null: a deliberate removal, which is a legitimate operation.
|
||||||
|
Some(None) => club_svc::clear_squad_manager(&state.pool, &club.id).await?,
|
||||||
|
// Absent: this request expresses no manager decision. Touch nothing.
|
||||||
|
None => {}
|
||||||
}
|
}
|
||||||
let manager = club_svc::get_squad_manager(&state.pool, &club.id).await?;
|
let manager = club_svc::get_squad_manager(&state.pool, &club.id).await?;
|
||||||
Ok(Json(json!({ "manager": manager })))
|
Ok(Json(json!({ "manager": manager })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return the club's ownership-backed active home/away kit assignments.
|
/// Every active club-item designation, slot-keyed and EXPLICIT: all five slots
|
||||||
pub async fn get_active_kits(
|
/// are always present, an empty slot being `null`. A caller therefore never has
|
||||||
|
/// to guess whether a missing key means "no item" or "unsupported slot".
|
||||||
|
fn active_items_body(items: &club_svc::ActiveClubItems) -> AppResult<Value> {
|
||||||
|
let mut body = serde_json::Map::new();
|
||||||
|
for slot in ActiveSlot::ALL {
|
||||||
|
body.insert(
|
||||||
|
slot.as_str().to_string(),
|
||||||
|
serde_json::to_value(items.get(slot))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(Value::Object(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the club's ownership-backed active item designations.
|
||||||
|
pub async fn get_active_items(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
game: GameId,
|
game: GameId,
|
||||||
) -> AppResult<Json<Value>> {
|
) -> AppResult<Json<Value>> {
|
||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
let kits = club_svc::get_active_club_kits(&state.pool, &club.id).await?;
|
let items = club_svc::get_active_club_items(&state.pool, &club.id).await?;
|
||||||
Ok(Json(json!({ "home": kits.home, "away": kits.away })))
|
Ok(Json(json!({ "active_items": active_items_body(&items)? })))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct SetActiveKitsRequest {
|
pub struct SetActiveItemRequest {
|
||||||
pub home_owned_card_id: Option<String>,
|
/// Which club role to write: home_kit | away_kit | badge | ball | stadium.
|
||||||
pub away_owned_card_id: Option<String>,
|
///
|
||||||
|
/// Taken as a string and parsed here so an unknown slot comes back as this
|
||||||
|
/// crate's `400 {"error": …}` envelope, like every other bad request, rather
|
||||||
|
/// than axum's plain-text deserialization rejection.
|
||||||
|
pub slot: String,
|
||||||
|
/// The owned instance to designate, or `null`/absent to clear the slot.
|
||||||
|
#[serde(default)]
|
||||||
|
pub owned_card_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Atomically replace both active kit assignments. Core enforces ownership and
|
/// Write ONE active club-item designation. Core enforces ownership and that the
|
||||||
/// distinct instances; game adapters enforce their own definition taxonomy.
|
/// slot admits the item's `content_kind`; game adapters own their own mapping
|
||||||
pub async fn put_active_kits(
|
/// from a wire item onto that generic kind.
|
||||||
|
pub async fn put_active_item(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
game: GameId,
|
game: GameId,
|
||||||
Json(req): Json<SetActiveKitsRequest>,
|
Json(req): Json<SetActiveItemRequest>,
|
||||||
) -> AppResult<Json<Value>> {
|
) -> AppResult<Json<Value>> {
|
||||||
|
let slot = ActiveSlot::from_str(&req.slot).map_err(AppError::BadRequest)?;
|
||||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
club_svc::set_active_club_kits(
|
match req.owned_card_id {
|
||||||
&state.pool,
|
Some(owned_card_id) => {
|
||||||
&club.id,
|
club_svc::set_active_club_item(&state.pool, &club.id, slot, &owned_card_id).await?
|
||||||
req.home_owned_card_id.as_deref(),
|
}
|
||||||
req.away_owned_card_id.as_deref(),
|
None => club_svc::clear_active_club_item(&state.pool, &club.id, slot).await?,
|
||||||
)
|
}
|
||||||
.await?;
|
let items = club_svc::get_active_club_items(&state.pool, &club.id).await?;
|
||||||
let kits = club_svc::get_active_club_kits(&state.pool, &club.id).await?;
|
Ok(Json(json!({ "active_items": active_items_body(&items)? })))
|
||||||
Ok(Json(json!({ "home": kits.home, "away": kits.away })))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
//! `POST /consumables/apply` — the HTTP boundary for Core's atomic
|
||||||
|
//! apply-one-consumable transaction.
|
||||||
|
//!
|
||||||
|
//! Game-neutral like the rest of Core's surface: the caller names an owned source
|
||||||
|
//! instance, an owned target and a described [`InstanceEffect`]; Core resolves the
|
||||||
|
//! game-scoped active profile and its club from the `X-OpenFUT-Game` header, so no
|
||||||
|
//! caller can reach across clubs. Everything after that is one durable SQLite
|
||||||
|
//! transaction in [`consume::consume_item`], guarded by
|
||||||
|
//! `UNIQUE(profile_id, action_identity)`.
|
||||||
|
//!
|
||||||
|
//! The effect vocabulary is closed and validated by Core — see
|
||||||
|
//! [`crate::services::instance_effect`] for why the host describes an effect
|
||||||
|
//! instead of supplying one.
|
||||||
|
|
||||||
|
use axum::{extract::State, Json};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
app::AppState,
|
||||||
|
error::AppResult,
|
||||||
|
extractors::GameId,
|
||||||
|
models::card::ContentKind,
|
||||||
|
services::{
|
||||||
|
club as club_svc,
|
||||||
|
consume::{self, ConsumeOutcome, ConsumeRequest, ConsumeTarget, SourceConsumption},
|
||||||
|
instance_effect::InstanceEffect,
|
||||||
|
profile as profile_svc,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ApplyConsumableRequest {
|
||||||
|
/// Opaque, stable per-application token. Core never parses it; it only
|
||||||
|
/// enforces uniqueness, so a retried HTTP request replays instead of
|
||||||
|
/// applying twice.
|
||||||
|
pub action_identity: String,
|
||||||
|
pub source_owned_card_id: String,
|
||||||
|
pub target_owned_card_id: String,
|
||||||
|
/// The kind the target MUST be. The caller states it because only the caller
|
||||||
|
/// knows which family its consumable belongs to; a mismatch is refused rather
|
||||||
|
/// than applied to whatever happens to be there.
|
||||||
|
pub target_kind: ContentKind,
|
||||||
|
pub effect: InstanceEffect,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `POST /consumables/apply` — atomic validate + apply + consume-once.
|
||||||
|
///
|
||||||
|
/// `applied: false` in the response means the `action_identity` was already
|
||||||
|
/// recorded: nothing was mutated and the recorded outcome is echoed.
|
||||||
|
pub async fn post_apply_consumable(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
game: GameId,
|
||||||
|
Json(req): Json<ApplyConsumableRequest>,
|
||||||
|
) -> AppResult<Json<ConsumeOutcome>> {
|
||||||
|
// Both ids are needed: the profile scopes the replay guard, the club scopes
|
||||||
|
// ownership. Same resolution pair as `cards::get_collection`.
|
||||||
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
|
|
||||||
|
let outcome = consume::consume_item(
|
||||||
|
&state.pool,
|
||||||
|
&profile.id,
|
||||||
|
&club.id,
|
||||||
|
&ConsumeRequest {
|
||||||
|
action_identity: &req.action_identity,
|
||||||
|
source_owned_card_id: &req.source_owned_card_id,
|
||||||
|
// A consumable is the only thing that can be applied, and it is spent
|
||||||
|
// whole: FIFA-style stacking is the adapter's projection, not an
|
||||||
|
// ownership model Core has for these instances.
|
||||||
|
expected_source_kind: ContentKind::Consumable,
|
||||||
|
consumption: SourceConsumption::DestroyInstance,
|
||||||
|
target: ConsumeTarget::OwnedCard {
|
||||||
|
owned_card_id: &req.target_owned_card_id,
|
||||||
|
expected_kind: req.target_kind,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
&req.effect,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(Json(outcome))
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ pub mod achievements;
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod cards;
|
pub mod cards;
|
||||||
pub mod club;
|
pub mod club;
|
||||||
|
pub mod consumables;
|
||||||
pub mod division;
|
pub mod division;
|
||||||
pub mod draft;
|
pub mod draft;
|
||||||
pub mod economy;
|
pub mod economy;
|
||||||
|
|||||||
@@ -235,3 +235,45 @@ pub async fn put_squad_replace(
|
|||||||
"slots_written": out.slots_written,
|
"slots_written": out.slots_written,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct RolePatchReq {
|
||||||
|
/// Owned card to flag as captain. Omitted means "leave the captain alone" —
|
||||||
|
/// it is NEVER a request to clear it. Clearing has no established client
|
||||||
|
/// semantics and is deliberately not invented here.
|
||||||
|
#[serde(default)]
|
||||||
|
pub captain_owned_card_id: Option<String>,
|
||||||
|
pub extension: OpaqueExtensionWrite,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `PUT /squad/roles` — patch ONLY role assignments (captain) plus the opaque
|
||||||
|
/// game extension, atomically.
|
||||||
|
///
|
||||||
|
/// Distinct from `/squad/replace` on purpose. A role-only update carries no slot
|
||||||
|
/// array, and describing it as a replacement with zero slots trips the
|
||||||
|
/// empty-replacement guard — which is correct behaviour for a replacement and
|
||||||
|
/// wrong for a patch. This route never touches player assignments, the squad
|
||||||
|
/// manager, or club actives.
|
||||||
|
pub async fn put_squad_roles(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
game: GameId,
|
||||||
|
Json(req): Json<RolePatchReq>,
|
||||||
|
) -> AppResult<Json<Value>> {
|
||||||
|
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||||
|
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||||
|
|
||||||
|
let out = squad_svc::patch_squad_roles(
|
||||||
|
&state.pool,
|
||||||
|
game.as_str(),
|
||||||
|
&club.id,
|
||||||
|
req.captain_owned_card_id.as_deref(),
|
||||||
|
&req.extension,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(Json(json!({
|
||||||
|
"squad_id": out.squad.id,
|
||||||
|
"canonical_fingerprint": out.canonical_fingerprint,
|
||||||
|
"captain_changed": out.captain_changed,
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|||||||
+306
-139
@@ -1,7 +1,10 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
db::Pool,
|
db::Pool,
|
||||||
error::{AppError, AppResult},
|
error::{AppError, AppResult},
|
||||||
models::{card::OwnedCard, club::Club},
|
models::{
|
||||||
|
card::{ActiveSlot, ContentKind, OwnedCard, OWNED_CARD_SELECT},
|
||||||
|
club::Club,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
|
||||||
@@ -134,9 +137,6 @@ pub async fn spend_coins(pool: &Pool, club_id: &str, amount: i64) -> AppResult<i
|
|||||||
// durably and re-validates ownership on read; the FIFA 17 adapter owns the wire
|
// durably and re-validates ownership on read; the FIFA 17 adapter owns the wire
|
||||||
// meaning of "manager" (itemType/contract/chemistry), never Core.
|
// meaning of "manager" (itemType/contract/chemistry), never Core.
|
||||||
|
|
||||||
const OWNED_SELECT: &str = "SELECT id, club_id, card_id, is_loan, loan_matches_remaining, \
|
|
||||||
acquired_at, chemistry_style, position_override, training_bonus FROM owned_cards";
|
|
||||||
|
|
||||||
/// The club's most-recently-updated squad id (its "active" squad), matching the
|
/// The club's most-recently-updated squad id (its "active" squad), matching the
|
||||||
/// selection `squad::get_squad` uses, or `None` when the club has no squad yet.
|
/// selection `squad::get_squad` uses, or `None` when the club has no squad yet.
|
||||||
pub async fn active_squad_id(pool: &Pool, club_id: &str) -> AppResult<Option<String>> {
|
pub async fn active_squad_id(pool: &Pool, club_id: &str) -> AppResult<Option<String>> {
|
||||||
@@ -166,7 +166,8 @@ pub async fn get_squad_manager_for_squad(
|
|||||||
club_id: &str,
|
club_id: &str,
|
||||||
) -> AppResult<Option<OwnedCard>> {
|
) -> AppResult<Option<OwnedCard>> {
|
||||||
Ok(sqlx::query_as::<_, OwnedCard>(&format!(
|
Ok(sqlx::query_as::<_, OwnedCard>(&format!(
|
||||||
"{OWNED_SELECT} WHERE id = (SELECT owned_card_id FROM squad_managers WHERE squad_id = ?) \
|
"{OWNED_CARD_SELECT} \
|
||||||
|
WHERE id = (SELECT owned_card_id FROM squad_managers WHERE squad_id = ?) \
|
||||||
AND club_id = ?"
|
AND club_id = ?"
|
||||||
))
|
))
|
||||||
.bind(squad_id)
|
.bind(squad_id)
|
||||||
@@ -194,11 +195,16 @@ pub async fn set_squad_manager_for_squad(
|
|||||||
squad_id: &str,
|
squad_id: &str,
|
||||||
owned_card_id: &str,
|
owned_card_id: &str,
|
||||||
) -> AppResult<()> {
|
) -> AppResult<()> {
|
||||||
|
// One transaction: both existence checks and the write. Validating on the
|
||||||
|
// pool and then inserting left a window in which the squad or the card could
|
||||||
|
// be removed between the check and the write, persisting an assignment whose
|
||||||
|
// preconditions no longer held.
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
let squad_ok =
|
let squad_ok =
|
||||||
sqlx::query_scalar::<_, String>("SELECT id FROM squads WHERE id = ? AND club_id = ?")
|
sqlx::query_scalar::<_, String>("SELECT id FROM squads WHERE id = ? AND club_id = ?")
|
||||||
.bind(squad_id)
|
.bind(squad_id)
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
if squad_ok.is_none() {
|
if squad_ok.is_none() {
|
||||||
return Err(AppError::NotFound(format!("squad '{squad_id}' not found")));
|
return Err(AppError::NotFound(format!("squad '{squad_id}' not found")));
|
||||||
@@ -207,7 +213,7 @@ pub async fn set_squad_manager_for_squad(
|
|||||||
sqlx::query_scalar::<_, String>("SELECT id FROM owned_cards WHERE id = ? AND club_id = ?")
|
sqlx::query_scalar::<_, String>("SELECT id FROM owned_cards WHERE id = ? AND club_id = ?")
|
||||||
.bind(owned_card_id)
|
.bind(owned_card_id)
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
if card_ok.is_none() {
|
if card_ok.is_none() {
|
||||||
return Err(AppError::NotFound(format!(
|
return Err(AppError::NotFound(format!(
|
||||||
@@ -222,8 +228,9 @@ pub async fn set_squad_manager_for_squad(
|
|||||||
.bind(squad_id)
|
.bind(squad_id)
|
||||||
.bind(owned_card_id)
|
.bind(owned_card_id)
|
||||||
.bind(&now)
|
.bind(&now)
|
||||||
.execute(pool)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,94 +247,137 @@ pub async fn clear_squad_manager(pool: &Pool, club_id: &str) -> AppResult<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// ───────────────────────── active club kits ────────────────────────────────
|
// ─────────────────────── active club item designations ──────────────────────
|
||||||
|
//
|
||||||
|
// Generic, ownership-backed club state (migration 0026 `club_active_items`):
|
||||||
|
// which owned INSTANCE currently occupies each club-scoped role (home/away kit,
|
||||||
|
// badge, ball, stadium). Ownership itself never lives here — a designation is a
|
||||||
|
// pointer into `owned_cards`, revalidated against current ownership on every
|
||||||
|
// read, so a stale row can never project an item the club does not own.
|
||||||
|
//
|
||||||
|
// Core enforces the generic invariants (ownership, one instance per slot, slot
|
||||||
|
// admits exactly one `ContentKind`); a game adapter maps its own taxonomy onto
|
||||||
|
// `ContentKind` before it gets here.
|
||||||
|
|
||||||
/// The ownership-backed home and away kit assignments for one club.
|
/// Every active club-item designation, keyed by slot.
|
||||||
|
///
|
||||||
|
/// Slots with no designation are simply absent. Held as a `Vec` rather than a
|
||||||
|
/// map so the projection order is the canonical [`ActiveSlot::ALL`] order.
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct ActiveClubKits {
|
pub struct ActiveClubItems {
|
||||||
pub home: Option<OwnedCard>,
|
pub items: Vec<(ActiveSlot, OwnedCard)>,
|
||||||
pub away: Option<OwnedCard>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_club_kit_slot(pool: &Pool, club_id: &str, slot: &str) -> AppResult<Option<OwnedCard>> {
|
impl ActiveClubItems {
|
||||||
|
/// The owned instance occupying `slot`, if any.
|
||||||
|
pub fn get(&self, slot: ActiveSlot) -> Option<&OwnedCard> {
|
||||||
|
self.items
|
||||||
|
.iter()
|
||||||
|
.find(|(s, _)| *s == slot)
|
||||||
|
.map(|(_, card)| card)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read one slot's designation, revalidated against current club ownership.
|
||||||
|
async fn get_active_club_item(
|
||||||
|
pool: &Pool,
|
||||||
|
club_id: &str,
|
||||||
|
slot: ActiveSlot,
|
||||||
|
) -> AppResult<Option<OwnedCard>> {
|
||||||
Ok(sqlx::query_as::<_, OwnedCard>(&format!(
|
Ok(sqlx::query_as::<_, OwnedCard>(&format!(
|
||||||
"{OWNED_SELECT} WHERE id = ( \
|
"{OWNED_CARD_SELECT} WHERE id = ( \
|
||||||
SELECT owned_card_id FROM club_kit_assignments WHERE club_id = ? AND slot = ? \
|
SELECT owned_card_id FROM club_active_items WHERE club_id = ? AND slot = ? \
|
||||||
) AND club_id = ?"
|
) AND club_id = ?"
|
||||||
))
|
))
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.bind(slot)
|
.bind(slot.as_str())
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read both active kit roles. Each assignment is revalidated against current
|
/// Read every active club-item designation. Each is revalidated against current
|
||||||
/// ownership, so a stale/corrupt row never surfaces another club's item.
|
/// ownership, so a stale/corrupt row never surfaces another club's item.
|
||||||
pub async fn get_active_club_kits(pool: &Pool, club_id: &str) -> AppResult<ActiveClubKits> {
|
pub async fn get_active_club_items(pool: &Pool, club_id: &str) -> AppResult<ActiveClubItems> {
|
||||||
Ok(ActiveClubKits {
|
let mut items = Vec::new();
|
||||||
home: get_club_kit_slot(pool, club_id, "home").await?,
|
for slot in ActiveSlot::ALL {
|
||||||
away: get_club_kit_slot(pool, club_id, "away").await?,
|
if let Some(card) = get_active_club_item(pool, club_id, slot).await? {
|
||||||
})
|
items.push((slot, card));
|
||||||
}
|
|
||||||
|
|
||||||
/// Atomically replace both active kit roles. Core enforces generic ownership and
|
|
||||||
/// distinct-instance invariants; the game adapter validates that each definition
|
|
||||||
/// is a kit before asking Core to assign it.
|
|
||||||
pub async fn set_active_club_kits(
|
|
||||||
pool: &Pool,
|
|
||||||
club_id: &str,
|
|
||||||
home_owned_card_id: Option<&str>,
|
|
||||||
away_owned_card_id: Option<&str>,
|
|
||||||
) -> AppResult<()> {
|
|
||||||
if home_owned_card_id.is_some() && home_owned_card_id == away_owned_card_id {
|
|
||||||
return Err(AppError::BadRequest(
|
|
||||||
"home and away kits must be different owned items".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut tx = pool.begin().await?;
|
|
||||||
for owned_card_id in [home_owned_card_id, away_owned_card_id]
|
|
||||||
.into_iter()
|
|
||||||
.flatten()
|
|
||||||
{
|
|
||||||
let owned = sqlx::query_scalar::<_, String>(
|
|
||||||
"SELECT id FROM owned_cards WHERE id = ? AND club_id = ?",
|
|
||||||
)
|
|
||||||
.bind(owned_card_id)
|
|
||||||
.bind(club_id)
|
|
||||||
.fetch_optional(&mut *tx)
|
|
||||||
.await?;
|
|
||||||
if owned.is_none() {
|
|
||||||
return Err(AppError::NotFound(format!(
|
|
||||||
"owned card '{owned_card_id}' not found"
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(ActiveClubItems { items })
|
||||||
|
}
|
||||||
|
|
||||||
sqlx::query("DELETE FROM club_kit_assignments WHERE club_id = ?")
|
/// Designate `owned_card_id` as `club_id`'s active item for `slot`, replacing any
|
||||||
.bind(club_id)
|
/// existing designation for that slot.
|
||||||
|
///
|
||||||
|
/// Fail-closed, in one transaction:
|
||||||
|
/// * the instance MUST be owned by `club_id` (so a client cannot install
|
||||||
|
/// another club's item, nor an id that does not exist);
|
||||||
|
/// * its `content_kind` MUST be the kind the slot admits (a badge in
|
||||||
|
/// `home_kit` is rejected, not silently accepted);
|
||||||
|
/// * an instance already designated for a DIFFERENT slot is released first, so
|
||||||
|
/// the `owned_card_id UNIQUE` invariant is upheld by an explicit move rather
|
||||||
|
/// than a constraint error.
|
||||||
|
pub async fn set_active_club_item(
|
||||||
|
pool: &Pool,
|
||||||
|
club_id: &str,
|
||||||
|
slot: ActiveSlot,
|
||||||
|
owned_card_id: &str,
|
||||||
|
) -> AppResult<()> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
|
let owned = sqlx::query_as::<_, (String, ContentKind)>(
|
||||||
|
"SELECT id, content_kind FROM owned_cards WHERE id = ? AND club_id = ?",
|
||||||
|
)
|
||||||
|
.bind(owned_card_id)
|
||||||
|
.bind(club_id)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let Some((_, kind)) = owned else {
|
||||||
|
return Err(AppError::NotFound(format!(
|
||||||
|
"owned card '{owned_card_id}' not found"
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let required = slot.required_kind();
|
||||||
|
if kind != required {
|
||||||
|
return Err(AppError::BadRequest(format!(
|
||||||
|
"slot '{slot}' requires content kind '{required}', but owned card \
|
||||||
|
'{owned_card_id}' is '{kind}'"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release this instance from any other slot, then take the target slot.
|
||||||
|
sqlx::query("DELETE FROM club_active_items WHERE owned_card_id = ?")
|
||||||
|
.bind(owned_card_id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
let now = Utc::now().to_rfc3339();
|
let now = Utc::now().to_rfc3339();
|
||||||
for (slot, owned_card_id) in [("home", home_owned_card_id), ("away", away_owned_card_id)] {
|
sqlx::query(
|
||||||
if let Some(owned_card_id) = owned_card_id {
|
"INSERT OR REPLACE INTO club_active_items \
|
||||||
sqlx::query(
|
(club_id, slot, owned_card_id, updated_at) VALUES (?, ?, ?, ?)",
|
||||||
"INSERT INTO club_kit_assignments \
|
)
|
||||||
(club_id, slot, owned_card_id, updated_at) VALUES (?, ?, ?, ?)",
|
.bind(club_id)
|
||||||
)
|
.bind(slot.as_str())
|
||||||
.bind(club_id)
|
.bind(owned_card_id)
|
||||||
.bind(slot)
|
.bind(&now)
|
||||||
.bind(owned_card_id)
|
.execute(&mut *tx)
|
||||||
.bind(&now)
|
.await?;
|
||||||
.execute(&mut *tx)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear `club_id`'s designation for `slot` (idempotent — an already-empty slot
|
||||||
|
/// is a successful no-op).
|
||||||
|
pub async fn clear_active_club_item(pool: &Pool, club_id: &str, slot: ActiveSlot) -> AppResult<()> {
|
||||||
|
sqlx::query("DELETE FROM club_active_items WHERE club_id = ? AND slot = ?")
|
||||||
|
.bind(club_id)
|
||||||
|
.bind(slot.as_str())
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -357,18 +407,30 @@ mod tests {
|
|||||||
.bind(club).bind(profile).bind(club).bind(1000i64).bind(TS).bind(TS)
|
.bind(club).bind(profile).bind(club).bind(1000i64).bind(TS).bind(TS)
|
||||||
.execute(&pool).await.expect("club");
|
.execute(&pool).await.expect("club");
|
||||||
}
|
}
|
||||||
for (id, club, definition) in [
|
for (id, club, definition, kind) in [
|
||||||
("mgr", "club-a", "def-mgr"),
|
("mgr", "club-a", "def-mgr", ContentKind::Manager),
|
||||||
("mgr2", "club-a", "def-mgr"),
|
("mgr2", "club-a", "def-mgr", ContentKind::Manager),
|
||||||
("player", "club-a", "def-player"),
|
("player", "club-a", "def-player", ContentKind::Player),
|
||||||
("kit-home", "club-a", "def-kit-home"),
|
("kit-home", "club-a", "def-kit-home", ContentKind::Kit),
|
||||||
("kit-away", "club-a", "def-kit-away"),
|
("kit-away", "club-a", "def-kit-away", ContentKind::Kit),
|
||||||
("kit-away-2", "club-a", "def-kit-away-2"),
|
("kit-away-2", "club-a", "def-kit-away-2", ContentKind::Kit),
|
||||||
("foreign", "club-b", "def-kit-foreign"),
|
("badge", "club-a", "def-badge", ContentKind::Badge),
|
||||||
|
("ball", "club-a", "def-ball", ContentKind::Ball),
|
||||||
|
("stadium", "club-a", "def-stadium", ContentKind::Stadium),
|
||||||
|
("foreign", "club-b", "def-kit-foreign", ContentKind::Kit),
|
||||||
] {
|
] {
|
||||||
sqlx::query("INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at) VALUES (?, ?, ?, 0, ?)")
|
sqlx::query(
|
||||||
.bind(id).bind(club).bind(definition).bind(TS)
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at, content_kind) \
|
||||||
.execute(&pool).await.expect("owned card");
|
VALUES (?, ?, ?, 0, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(club)
|
||||||
|
.bind(definition)
|
||||||
|
.bind(TS)
|
||||||
|
.bind(kind.as_str())
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("owned card");
|
||||||
}
|
}
|
||||||
// club-a has one squad.
|
// club-a has one squad.
|
||||||
sqlx::query("INSERT INTO squads (id, club_id, name, formation, created_at, updated_at) VALUES ('sq-a', 'club-a', 'S', '4-4-2', ?, ?)")
|
sqlx::query("INSERT INTO squads (id, club_id, name, formation, created_at, updated_at) VALUES ('sq-a', 'club-a', 'S', '4-4-2', ?, ?)")
|
||||||
@@ -383,8 +445,8 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn kit_rows(pool: &db::Pool) -> i64 {
|
async fn active_item_rows(pool: &db::Pool) -> i64 {
|
||||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM club_kit_assignments")
|
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM club_active_items")
|
||||||
.fetch_one(pool)
|
.fetch_one(pool)
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -463,76 +525,160 @@ mod tests {
|
|||||||
let (_dir, _url, pool) = fixture().await;
|
let (_dir, _url, pool) = fixture().await;
|
||||||
assert!(get_squad_manager(&pool, "club-a").await.unwrap().is_none());
|
assert!(get_squad_manager(&pool, "club-a").await.unwrap().is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── active club item designations ──
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn kits_persist_across_reload_and_restart() {
|
async fn active_items_persist_across_reload_and_restart() {
|
||||||
let (dir, url, pool) = fixture().await;
|
let (dir, url, pool) = fixture().await;
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-away"))
|
for (slot, id) in [
|
||||||
.await
|
(ActiveSlot::HomeKit, "kit-home"),
|
||||||
.expect("assign kits");
|
(ActiveSlot::AwayKit, "kit-away"),
|
||||||
let current = get_active_club_kits(&pool, "club-a").await.unwrap();
|
(ActiveSlot::Badge, "badge"),
|
||||||
|
(ActiveSlot::Ball, "ball"),
|
||||||
|
(ActiveSlot::Stadium, "stadium"),
|
||||||
|
] {
|
||||||
|
set_active_club_item(&pool, "club-a", slot, id)
|
||||||
|
.await
|
||||||
|
.expect("designate");
|
||||||
|
}
|
||||||
|
let current = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
|
assert_eq!(current.items.len(), 5, "every slot filled");
|
||||||
|
// Projection order is the canonical slot order, not DB insertion order.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
current.home.as_ref().map(|item| item.id.as_str()),
|
current.items.iter().map(|(s, _)| *s).collect::<Vec<_>>(),
|
||||||
Some("kit-home")
|
ActiveSlot::ALL.to_vec()
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
current.away.as_ref().map(|item| item.id.as_str()),
|
|
||||||
Some("kit-away")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
pool.close().await;
|
pool.close().await;
|
||||||
let reopened = db::init_pool(&url, 5).await.expect("reopen");
|
let reopened = db::init_pool(&url, 5).await.expect("reopen");
|
||||||
db::run_migrations(&reopened).await.expect("migrations");
|
db::run_migrations(&reopened).await.expect("migrations");
|
||||||
let persisted = get_active_club_kits(&reopened, "club-a").await.unwrap();
|
let persisted = get_active_club_items(&reopened, "club-a").await.unwrap();
|
||||||
assert_eq!(persisted.home.map(|item| item.id), Some("kit-home".into()));
|
assert_eq!(
|
||||||
assert_eq!(persisted.away.map(|item| item.id), Some("kit-away".into()));
|
persisted.get(ActiveSlot::Stadium).map(|c| c.id.as_str()),
|
||||||
|
Some("stadium"),
|
||||||
|
"designations must survive a server restart"
|
||||||
|
);
|
||||||
drop(dir);
|
drop(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn kits_replace_clear_and_never_duplicate() {
|
async fn active_item_replace_and_clear_never_duplicate() {
|
||||||
let (_dir, _url, pool) = fixture().await;
|
let (_dir, _url, pool) = fixture().await;
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-away"))
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "kit-away")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-away-2"))
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "kit-away-2")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(kit_rows(&pool).await, 2);
|
assert_eq!(active_item_rows(&pool).await, 1, "one item per slot");
|
||||||
let current = get_active_club_kits(&pool, "club-a").await.unwrap();
|
let current = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
assert_eq!(current.away.map(|item| item.id), Some("kit-away-2".into()));
|
assert_eq!(
|
||||||
|
current.get(ActiveSlot::AwayKit).map(|c| c.id.as_str()),
|
||||||
set_active_club_kits(&pool, "club-a", None, None)
|
Some("kit-away-2")
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(kit_rows(&pool).await, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn kits_reject_invalid_references_atomically() {
|
|
||||||
let (_dir, _url, pool) = fixture().await;
|
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-away"))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert!(set_active_club_kits(&pool, "club-a", Some("foreign"), None)
|
|
||||||
.await
|
|
||||||
.is_err());
|
|
||||||
assert!(
|
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-home"))
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let unchanged = get_active_club_kits(&pool, "club-a").await.unwrap();
|
clear_active_club_item(&pool, "club-a", ActiveSlot::AwayKit)
|
||||||
assert_eq!(unchanged.home.map(|item| item.id), Some("kit-home".into()));
|
.await
|
||||||
assert_eq!(unchanged.away.map(|item| item.id), Some("kit-away".into()));
|
.unwrap();
|
||||||
assert_eq!(kit_rows(&pool).await, 2);
|
assert_eq!(active_item_rows(&pool).await, 0);
|
||||||
|
// Clearing an empty slot is an idempotent no-op.
|
||||||
|
clear_active_club_item(&pool, "club-a", ActiveSlot::AwayKit)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn kit_delete_and_transfer_clear_active_designations() {
|
async fn active_item_rejects_unowned_card_and_leaves_state_intact() {
|
||||||
let (_dir, _url, pool) = fixture().await;
|
let (_dir, _url, pool) = fixture().await;
|
||||||
set_active_club_kits(&pool, "club-a", Some("kit-home"), Some("kit-away"))
|
set_active_club_item(&pool, "club-a", ActiveSlot::HomeKit, "kit-home")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "foreign")
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"another club's item cannot be designated"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "nope")
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"a non-existent instance cannot be designated"
|
||||||
|
);
|
||||||
|
|
||||||
|
let unchanged = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
unchanged.get(ActiveSlot::HomeKit).map(|c| c.id.as_str()),
|
||||||
|
Some("kit-home")
|
||||||
|
);
|
||||||
|
assert_eq!(active_item_rows(&pool).await, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn active_item_rejects_slot_kind_mismatch() {
|
||||||
|
let (_dir, _url, pool) = fixture().await;
|
||||||
|
// A badge is not a kit; a player is not a stadium.
|
||||||
|
for (slot, id) in [
|
||||||
|
(ActiveSlot::HomeKit, "badge"),
|
||||||
|
(ActiveSlot::Stadium, "player"),
|
||||||
|
(ActiveSlot::Ball, "kit-home"),
|
||||||
|
] {
|
||||||
|
let err = set_active_club_item(&pool, "club-a", slot, id)
|
||||||
|
.await
|
||||||
|
.expect_err("slot/kind mismatch must be refused");
|
||||||
|
assert!(
|
||||||
|
matches!(err, AppError::BadRequest(_)),
|
||||||
|
"expected a bad-request, got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(active_item_rows(&pool).await, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lifecycle invariant: one owned instance can occupy at most ONE slot.
|
||||||
|
/// Re-designating it moves it rather than duplicating it.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn one_instance_cannot_occupy_two_slots() {
|
||||||
|
let (_dir, _url, pool) = fixture().await;
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::HomeKit, "kit-home")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "kit-home")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(active_item_rows(&pool).await, 1);
|
||||||
|
let current = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
|
assert!(current.get(ActiveSlot::HomeKit).is_none());
|
||||||
|
assert_eq!(
|
||||||
|
current.get(ActiveSlot::AwayKit).map(|c| c.id.as_str()),
|
||||||
|
Some("kit-home")
|
||||||
|
);
|
||||||
|
|
||||||
|
// The schema itself refuses the impossible state, not just the service.
|
||||||
|
let raw = sqlx::query(
|
||||||
|
"INSERT INTO club_active_items (club_id, slot, owned_card_id, updated_at) \
|
||||||
|
VALUES ('club-a', 'home_kit', 'kit-home', ?)",
|
||||||
|
)
|
||||||
|
.bind(TS)
|
||||||
|
.execute(&pool)
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
raw.is_err(),
|
||||||
|
"owned_card_id UNIQUE must reject a second slot"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lifecycle invariant: a designation can never point at an item the club
|
||||||
|
/// does not own — neither after a quick sell (DELETE) nor after a transfer
|
||||||
|
/// (UPDATE of club_id, which no FK action can observe).
|
||||||
|
#[tokio::test]
|
||||||
|
async fn delete_and_transfer_clear_active_designations() {
|
||||||
|
let (_dir, _url, pool) = fixture().await;
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::HomeKit, "kit-home")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::AwayKit, "kit-away")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@@ -540,19 +686,40 @@ mod tests {
|
|||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
.await
|
.await
|
||||||
.expect("quick sell kit");
|
.expect("quick sell kit");
|
||||||
let after_delete = get_active_club_kits(&pool, "club-a").await.unwrap();
|
let after_delete = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
assert!(after_delete.home.is_none());
|
assert!(after_delete.get(ActiveSlot::HomeKit).is_none());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
after_delete.away.map(|item| item.id),
|
after_delete.get(ActiveSlot::AwayKit).map(|c| c.id.as_str()),
|
||||||
Some("kit-away".into())
|
Some("kit-away")
|
||||||
);
|
);
|
||||||
|
assert_eq!(active_item_rows(&pool).await, 1);
|
||||||
|
|
||||||
sqlx::query("UPDATE owned_cards SET club_id = 'club-b' WHERE id = 'kit-away'")
|
sqlx::query("UPDATE owned_cards SET club_id = 'club-b' WHERE id = 'kit-away'")
|
||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
.await
|
.await
|
||||||
.expect("transfer kit");
|
.expect("transfer kit");
|
||||||
assert_eq!(kit_rows(&pool).await, 0);
|
assert_eq!(active_item_rows(&pool).await, 0, "transfer clears the slot");
|
||||||
let after_transfer = get_active_club_kits(&pool, "club-a").await.unwrap();
|
let after_transfer = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
assert!(after_transfer.home.is_none() && after_transfer.away.is_none());
|
assert!(after_transfer.items.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A designation whose owned row is forced out of the club WITHOUT the
|
||||||
|
/// trigger firing (raw row surgery mimicking corruption) must still never
|
||||||
|
/// project: reads revalidate ownership.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn read_revalidates_ownership_of_a_stale_designation() {
|
||||||
|
let (_dir, _url, pool) = fixture().await;
|
||||||
|
set_active_club_item(&pool, "club-a", ActiveSlot::Badge, "badge")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query("UPDATE club_active_items SET owned_card_id = 'foreign' WHERE slot = 'badge'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("corrupt the designation");
|
||||||
|
let items = get_active_club_items(&pool, "club-a").await.unwrap();
|
||||||
|
assert!(
|
||||||
|
items.get(ActiveSlot::Badge).is_none(),
|
||||||
|
"another club's item must never be projected"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -283,7 +283,7 @@ pub async fn list_unopened_entitlements(pool: &Pool, club_id: &str) -> AppResult
|
|||||||
/// DEFERRED `pool.begin()` upgrades to a write only at the first write, where
|
/// DEFERRED `pool.begin()` upgrades to a write only at the first write, where
|
||||||
/// SQLite returns SQLITE_BUSY *immediately* (bypassing the busy handler to avoid
|
/// SQLite returns SQLITE_BUSY *immediately* (bypassing the busy handler to avoid
|
||||||
/// deadlock) — the fresh-DB multi-connection write failure.
|
/// deadlock) — the fresh-DB multi-connection write failure.
|
||||||
async fn finish<T>(conn: &mut SqliteConnection, result: AppResult<T>) -> AppResult<T> {
|
pub(crate) async fn finish<T>(conn: &mut SqliteConnection, result: AppResult<T>) -> AppResult<T> {
|
||||||
match result {
|
match result {
|
||||||
Ok(v) => {
|
Ok(v) => {
|
||||||
sqlx::query("COMMIT").execute(&mut *conn).await?;
|
sqlx::query("COMMIT").execute(&mut *conn).await?;
|
||||||
|
|||||||
+150
-2
@@ -19,7 +19,10 @@
|
|||||||
//! non-imported profile is never clobbered.
|
//! non-imported profile is never clobbered.
|
||||||
//! - The whole thing commits together or not at all.
|
//! - The whole thing commits together or not at all.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use crate::db::Pool;
|
use crate::db::Pool;
|
||||||
|
use crate::models::card::ContentKind;
|
||||||
use crate::models::game_ext::{MAX_EXT_NAMESPACE_LEN, MAX_EXT_PAYLOAD_BYTES};
|
use crate::models::game_ext::{MAX_EXT_NAMESPACE_LEN, MAX_EXT_PAYLOAD_BYTES};
|
||||||
use crate::services::card_db::CardDb;
|
use crate::services::card_db::CardDb;
|
||||||
use crate::services::squad::squad_fingerprint;
|
use crate::services::squad::squad_fingerprint;
|
||||||
@@ -49,6 +52,20 @@ pub struct ImportOwnedCard {
|
|||||||
pub owned_item_id: String,
|
pub owned_item_id: String,
|
||||||
/// CardDefinitionId that MUST resolve in loaded production content.
|
/// CardDefinitionId that MUST resolve in loaded production content.
|
||||||
pub card_id: String,
|
pub card_id: String,
|
||||||
|
/// Generic content classification. Absent = `player`, which is what every
|
||||||
|
/// pre-taxonomy import produced; the adapter maps its own taxonomy (FIFA 17
|
||||||
|
/// `cardsubtypeid`, resource ranges, …) onto this before calling Core.
|
||||||
|
#[serde(default)]
|
||||||
|
pub content_kind: ContentKind,
|
||||||
|
/// Optional per-instance stack size. Absent / `null` means "not a stack"; it
|
||||||
|
/// never collapses two instances into one row.
|
||||||
|
///
|
||||||
|
/// NOT a consumable's wire `amount`: in FIFA 17 that field is the
|
||||||
|
/// definition's effect magnitude (a "+15 training" card), and every copy is
|
||||||
|
/// its own instance carrying the same value, so storing it here would claim
|
||||||
|
/// the club owns fifteen of them.
|
||||||
|
#[serde(default)]
|
||||||
|
pub quantity: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
@@ -127,6 +144,19 @@ pub async fn apply_profile_import(
|
|||||||
if req.owned.is_empty() {
|
if req.owned.is_empty() {
|
||||||
bail!("import request has zero owned cards; refusing to import an empty profile");
|
bail!("import request has zero owned cards; refusing to import an empty profile");
|
||||||
}
|
}
|
||||||
|
// A stack size is either absent ("not a stack") or a real positive count.
|
||||||
|
// Reject an explicit 0/negative up front rather than letting the column
|
||||||
|
// CHECK surface it as an opaque constraint failure mid-transaction.
|
||||||
|
for o in &req.owned {
|
||||||
|
if let Some(q) = o.quantity {
|
||||||
|
if q < 1 {
|
||||||
|
bail!(
|
||||||
|
"owned card {} has quantity {q}; a stack size must be omitted or >= 1",
|
||||||
|
o.owned_item_id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── 1. rerun identity / single-profile-per-game ──
|
// ── 1. rerun identity / single-profile-per-game ──
|
||||||
let existing: Option<(String, Option<String>)> = sqlx::query_as(
|
let existing: Option<(String, Option<String>)> = sqlx::query_as(
|
||||||
@@ -242,13 +272,17 @@ pub async fn apply_profile_import(
|
|||||||
|
|
||||||
for o in &req.owned {
|
for o in &req.owned {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at) \
|
"INSERT INTO owned_cards \
|
||||||
VALUES (?, ?, ?, 0, NULL, ?)",
|
(id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, \
|
||||||
|
content_kind, quantity) \
|
||||||
|
VALUES (?, ?, ?, 0, NULL, ?, ?, ?)",
|
||||||
)
|
)
|
||||||
.bind(&o.owned_item_id)
|
.bind(&o.owned_item_id)
|
||||||
.bind(&club_id)
|
.bind(&club_id)
|
||||||
.bind(&o.card_id)
|
.bind(&o.card_id)
|
||||||
.bind(&now)
|
.bind(&now)
|
||||||
|
.bind(o.content_kind.as_str())
|
||||||
|
.bind(o.quantity)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await
|
.await
|
||||||
.with_context(|| format!("insert owned_card {}", o.owned_item_id))?;
|
.with_context(|| format!("insert owned_card {}", o.owned_item_id))?;
|
||||||
@@ -339,3 +373,117 @@ pub async fn apply_profile_import(
|
|||||||
squad_slots,
|
squad_slots,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One adapter-supplied classification: "every owned row of this definition is
|
||||||
|
/// really this kind of content".
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct ContentKindAssignment {
|
||||||
|
pub card_id: String,
|
||||||
|
pub content_kind: ContentKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request for [`reclassify_owned_content`].
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct ReclassifyRequest {
|
||||||
|
pub game_id: String,
|
||||||
|
pub assignments: Vec<ContentKindAssignment>,
|
||||||
|
/// Compute the outcome and roll back instead of committing. Lets an operator
|
||||||
|
/// see exactly what a production run would touch before it touches it.
|
||||||
|
#[serde(default)]
|
||||||
|
pub dry_run: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||||
|
pub struct ReclassifyOutcome {
|
||||||
|
/// Rows whose `content_kind` actually changed. On a dry run, the rows that
|
||||||
|
/// WOULD change; nothing is committed.
|
||||||
|
pub updated: usize,
|
||||||
|
/// Rows already carrying the requested kind (a rerun updates nothing).
|
||||||
|
pub unchanged: usize,
|
||||||
|
/// Assignments naming a definition this game owns no copy of.
|
||||||
|
pub unmatched_definitions: Vec<String>,
|
||||||
|
/// True when the transaction was rolled back rather than committed.
|
||||||
|
pub dry_run: bool,
|
||||||
|
/// Per-kind tally of the rows that changed, so an operator can sanity-check
|
||||||
|
/// the shape of the change ("3 staff, 17 consumable") before committing.
|
||||||
|
pub updated_by_kind: BTreeMap<String, usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Correct the `content_kind` of ALREADY-IMPORTED owned rows, in one transaction.
|
||||||
|
///
|
||||||
|
/// A profile import is once-only (same fingerprint no-ops, a different one is
|
||||||
|
/// refused), so a taxonomy fix cannot arrive by re-importing. Core defaults an
|
||||||
|
/// unstated row to `player`, which means every pre-taxonomy import durably
|
||||||
|
/// recorded coaches, kits and consumables as players — wrong in the ownership
|
||||||
|
/// authority even where a catalog-driven wire looked right.
|
||||||
|
///
|
||||||
|
/// Core stays generic: the caller supplies `card_id -> kind`, because only the
|
||||||
|
/// game adapter can map its own taxonomy. Idempotent, and scoped to one game's
|
||||||
|
/// clubs so a shared database cannot be reclassified across games.
|
||||||
|
pub async fn reclassify_owned_content(
|
||||||
|
pool: &Pool,
|
||||||
|
req: &ReclassifyRequest,
|
||||||
|
) -> Result<ReclassifyOutcome> {
|
||||||
|
if req.assignments.is_empty() {
|
||||||
|
bail!("reclassify request has zero assignments");
|
||||||
|
}
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let mut updated = 0usize;
|
||||||
|
let mut unchanged = 0usize;
|
||||||
|
let mut unmatched = Vec::new();
|
||||||
|
let mut by_kind: BTreeMap<String, usize> = BTreeMap::new();
|
||||||
|
for a in &req.assignments {
|
||||||
|
// Scope by game through the owning club, so the same definition id in
|
||||||
|
// another game is never touched.
|
||||||
|
let present: i64 = sqlx::query_scalar(
|
||||||
|
"SELECT COUNT(*) FROM owned_cards o JOIN clubs c ON c.id = o.club_id \
|
||||||
|
JOIN profiles p ON p.id = c.profile_id \
|
||||||
|
WHERE p.game_id = ? AND o.card_id = ?",
|
||||||
|
)
|
||||||
|
.bind(&req.game_id)
|
||||||
|
.bind(&a.card_id)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("count owned rows for definition")?;
|
||||||
|
if present == 0 {
|
||||||
|
unmatched.push(a.card_id.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let changed = sqlx::query(
|
||||||
|
"UPDATE owned_cards SET content_kind = ? \
|
||||||
|
WHERE card_id = ? AND content_kind != ? AND club_id IN \
|
||||||
|
(SELECT c.id FROM clubs c JOIN profiles p ON p.id = c.profile_id \
|
||||||
|
WHERE p.game_id = ?)",
|
||||||
|
)
|
||||||
|
.bind(a.content_kind.as_str())
|
||||||
|
.bind(&a.card_id)
|
||||||
|
.bind(a.content_kind.as_str())
|
||||||
|
.bind(&req.game_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.context("update owned content_kind")?
|
||||||
|
.rows_affected() as usize;
|
||||||
|
updated += changed;
|
||||||
|
unchanged += present as usize - changed;
|
||||||
|
if changed > 0 {
|
||||||
|
*by_kind
|
||||||
|
.entry(a.content_kind.as_str().to_string())
|
||||||
|
.or_default() += changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A dry run does the real UPDATEs and then throws them away, so the counts
|
||||||
|
// it reports are measured rather than predicted — the same statements, the
|
||||||
|
// same WHERE clauses, just no commit.
|
||||||
|
if req.dry_run {
|
||||||
|
tx.rollback().await?;
|
||||||
|
} else {
|
||||||
|
tx.commit().await?;
|
||||||
|
}
|
||||||
|
Ok(ReclassifyOutcome {
|
||||||
|
updated,
|
||||||
|
unchanged,
|
||||||
|
unmatched_definitions: unmatched,
|
||||||
|
dry_run: req.dry_run,
|
||||||
|
updated_by_kind: by_kind,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::models::card::Quality;
|
use crate::models::card::{ContentKind, Quality};
|
||||||
|
|
||||||
/// Semantic owned-inventory query. All values are game-independent: a quality
|
/// Semantic owned-inventory query. All values are game-independent: a quality
|
||||||
/// tier, entity **names** (not ids), and semantic offset/limit. Every filter is
|
/// tier, entity **names** (not ids), and semantic offset/limit. Every filter is
|
||||||
@@ -25,6 +25,9 @@ pub struct OwnedItemQuery {
|
|||||||
/// Quality tier (gold/silver/bronze). Serialized lowercase.
|
/// Quality tier (gold/silver/bronze). Serialized lowercase.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub quality: Option<Quality>,
|
pub quality: Option<Quality>,
|
||||||
|
/// Owned-content kind (player/consumable/kit/…). Serialized lowercase.
|
||||||
|
#[serde(default)]
|
||||||
|
pub content_kind: Option<ContentKind>,
|
||||||
/// Playing position, e.g. "ST" (matched case-insensitively).
|
/// Playing position, e.g. "ST" (matched case-insensitively).
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub position: Option<String>,
|
pub position: Option<String>,
|
||||||
@@ -47,8 +50,12 @@ pub struct OwnedItemQuery {
|
|||||||
|
|
||||||
/// One owned item projected to the attributes needed for querying, plus the
|
/// One owned item projected to the attributes needed for querying, plus the
|
||||||
/// response body to hand back verbatim once it survives the filter+page.
|
/// response body to hand back verbatim once it survives the filter+page.
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct OwnedItemView {
|
pub struct OwnedItemView {
|
||||||
pub owned_card_id: String,
|
pub owned_card_id: String,
|
||||||
|
/// What kind of content this instance is; lets a caller filter without
|
||||||
|
/// re-deriving the taxonomy from definition fields.
|
||||||
|
pub content_kind: ContentKind,
|
||||||
/// Base card overall (drives quality tier).
|
/// Base card overall (drives quality tier).
|
||||||
pub base_overall: u8,
|
pub base_overall: u8,
|
||||||
/// Effective overall (base + training bonus); drives ordering.
|
/// Effective overall (base + training bonus); drives ordering.
|
||||||
@@ -78,6 +85,10 @@ pub struct QueryPage {
|
|||||||
/// Does an item satisfy every present filter (AND semantics)?
|
/// Does an item satisfy every present filter (AND semantics)?
|
||||||
fn matches(item: &OwnedItemView, q: &OwnedItemQuery) -> bool {
|
fn matches(item: &OwnedItemView, q: &OwnedItemQuery) -> bool {
|
||||||
let quality_ok = q.quality.map(|want| item.quality() == want).unwrap_or(true);
|
let quality_ok = q.quality.map(|want| item.quality() == want).unwrap_or(true);
|
||||||
|
let kind_ok = q
|
||||||
|
.content_kind
|
||||||
|
.map(|want| item.content_kind == want)
|
||||||
|
.unwrap_or(true);
|
||||||
let pos_ok = q
|
let pos_ok = q
|
||||||
.position
|
.position
|
||||||
.as_ref()
|
.as_ref()
|
||||||
@@ -98,7 +109,7 @@ fn matches(item: &OwnedItemView, q: &OwnedItemQuery) -> bool {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|c| item.club.eq_ignore_ascii_case(c))
|
.map(|c| item.club.eq_ignore_ascii_case(c))
|
||||||
.unwrap_or(true);
|
.unwrap_or(true);
|
||||||
quality_ok && pos_ok && nation_ok && league_ok && club_ok
|
quality_ok && kind_ok && pos_ok && nation_ok && league_ok && club_ok
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply the query: filter (AND) → deterministic order → paginate.
|
/// Apply the query: filter (AND) → deterministic order → paginate.
|
||||||
@@ -152,6 +163,7 @@ mod tests {
|
|||||||
) -> OwnedItemView {
|
) -> OwnedItemView {
|
||||||
OwnedItemView {
|
OwnedItemView {
|
||||||
owned_card_id: id.to_string(),
|
owned_card_id: id.to_string(),
|
||||||
|
content_kind: ContentKind::Player,
|
||||||
base_overall: overall,
|
base_overall: overall,
|
||||||
effective_overall: overall as i64,
|
effective_overall: overall as i64,
|
||||||
position: position.to_string(),
|
position: position.to_string(),
|
||||||
@@ -179,6 +191,52 @@ mod tests {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A club holds mixed content; a caller asking for one kind must get exactly
|
||||||
|
/// that kind, and the unfiltered read must still return everything.
|
||||||
|
#[test]
|
||||||
|
fn content_kind_filters_mixed_inventory() {
|
||||||
|
let mut items = fixture();
|
||||||
|
let mut kit = view("k", 0, "", "", "", "");
|
||||||
|
kit.content_kind = ContentKind::Kit;
|
||||||
|
let mut style = view("s", 0, "", "", "", "");
|
||||||
|
style.content_kind = ContentKind::Consumable;
|
||||||
|
items.push(kit);
|
||||||
|
items.push(style);
|
||||||
|
|
||||||
|
let all = apply_query(items.clone(), &OwnedItemQuery::default());
|
||||||
|
assert_eq!(all.total, 7, "no filter returns every kind");
|
||||||
|
|
||||||
|
let kits = apply_query(
|
||||||
|
items.clone(),
|
||||||
|
&OwnedItemQuery {
|
||||||
|
content_kind: Some(ContentKind::Kit),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert_eq!(ids(&kits), ["k"]);
|
||||||
|
|
||||||
|
let players = apply_query(
|
||||||
|
items.clone(),
|
||||||
|
&OwnedItemQuery {
|
||||||
|
content_kind: Some(ContentKind::Player),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert_eq!(players.total, 5);
|
||||||
|
|
||||||
|
let none = apply_query(
|
||||||
|
items,
|
||||||
|
&OwnedItemQuery {
|
||||||
|
content_kind: Some(ContentKind::Stadium),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
none.total, 0,
|
||||||
|
"a kind the club owns none of is empty, not everything"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn no_filter_returns_all_in_overall_desc_order() {
|
fn no_filter_returns_all_in_overall_desc_order() {
|
||||||
let p = apply_query(fixture(), &OwnedItemQuery::default());
|
let p = apply_query(fixture(), &OwnedItemQuery::default());
|
||||||
|
|||||||
@@ -208,11 +208,10 @@ pub async fn sell_card(
|
|||||||
return Err(AppError::BadRequest("price must be non-negative".into()));
|
return Err(AppError::BadRequest("price must be non-negative".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let owned = sqlx::query_as::<_, crate::models::card::OwnedCard>(
|
let owned = sqlx::query_as::<_, crate::models::card::OwnedCard>(&format!(
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, \
|
"{} WHERE id = ? AND club_id = ?",
|
||||||
chemistry_style, position_override, training_bonus \
|
crate::models::card::OWNED_CARD_SELECT
|
||||||
FROM owned_cards WHERE id = ? AND club_id = ?",
|
))
|
||||||
)
|
|
||||||
.bind(&req.owned_card_id)
|
.bind(&req.owned_card_id)
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
|
|||||||
@@ -3,12 +3,14 @@ use crate::{
|
|||||||
error::{AppError, AppResult},
|
error::{AppError, AppResult},
|
||||||
models::{
|
models::{
|
||||||
achievement::AchievementDefinition,
|
achievement::AchievementDefinition,
|
||||||
card::OwnedCard,
|
card::{OwnedCard, OWNED_CARD_SELECT},
|
||||||
match_result::{CompleteMatchRequest, Match, MatchCompletionResult, MatchResultKind},
|
match_result::{CompleteMatchRequest, Match, MatchCompletionResult, MatchResultKind},
|
||||||
objective::ObjectiveDefinition,
|
objective::ObjectiveDefinition,
|
||||||
profile::{coins_for_level, level_for_xp, pack_for_level, LevelUpEvent},
|
profile::{coins_for_level, level_for_xp, pack_for_level, LevelUpEvent},
|
||||||
},
|
},
|
||||||
services::{achievement, card_db::CardDb, objective, season as season_svc, statistics},
|
services::{
|
||||||
|
achievement, card_db::CardDb, objective, season as season_svc, statistics, training,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use rand::{seq::SliceRandom, Rng};
|
use rand::{seq::SliceRandom, Rng};
|
||||||
use sqlx::{Sqlite, Transaction};
|
use sqlx::{Sqlite, Transaction};
|
||||||
@@ -142,10 +144,9 @@ async fn expire_loans_tx(
|
|||||||
|
|
||||||
let mut expired = Vec::new();
|
let mut expired = Vec::new();
|
||||||
for (_sp_id, owned_id) in starters {
|
for (_sp_id, owned_id) in starters {
|
||||||
let card = sqlx::query_as::<_, OwnedCard>(
|
let card = sqlx::query_as::<_, OwnedCard>(&format!(
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at \
|
"{OWNED_CARD_SELECT} WHERE id = ? AND is_loan = 1"
|
||||||
FROM owned_cards WHERE id = ? AND is_loan = 1",
|
))
|
||||||
)
|
|
||||||
.bind(&owned_id)
|
.bind(&owned_id)
|
||||||
.fetch_optional(&mut **tx)
|
.fetch_optional(&mut **tx)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -351,6 +352,7 @@ async fn complete_match_inner(
|
|||||||
let mut level_ups = Vec::new();
|
let mut level_ups = Vec::new();
|
||||||
let mut achievements_unlocked = Vec::new();
|
let mut achievements_unlocked = Vec::new();
|
||||||
let mut expired_loans = Vec::new();
|
let mut expired_loans = Vec::new();
|
||||||
|
let mut expired_training = Vec::new();
|
||||||
let mut season_end = None;
|
let mut season_end = None;
|
||||||
|
|
||||||
// A no-contest is recorded (history + idempotency) but has ZERO economic
|
// A no-contest is recorded (history + idempotency) but has ZERO economic
|
||||||
@@ -455,6 +457,12 @@ async fn complete_match_inner(
|
|||||||
season_end =
|
season_end =
|
||||||
season_svc::record_match_tx(&mut tx, club_id, profile_id, outcome, &now).await?;
|
season_svc::record_match_tx(&mut tx, club_id, profile_id, outcome, &now).await?;
|
||||||
}
|
}
|
||||||
|
// 9. One-match training effects are consumed by the players who took the
|
||||||
|
// field. Inside the same transaction and the same `is_economic`
|
||||||
|
// guard as everything else, so a NoContest voids it exactly as it
|
||||||
|
// voids coins and statistics, and a rollback leaves the boosts intact.
|
||||||
|
expired_training =
|
||||||
|
training::expire_for_instances_tx(&mut tx, club_id, &req.participants).await?;
|
||||||
}
|
}
|
||||||
inject_fault(fault, FaultPoint::BeforeCommit)?;
|
inject_fault(fault, FaultPoint::BeforeCommit)?;
|
||||||
|
|
||||||
@@ -476,6 +484,7 @@ async fn complete_match_inner(
|
|||||||
level_ups,
|
level_ups,
|
||||||
achievements_unlocked,
|
achievements_unlocked,
|
||||||
expired_loans,
|
expired_loans,
|
||||||
|
expired_training,
|
||||||
season_end,
|
season_end,
|
||||||
match_record,
|
match_record,
|
||||||
})
|
})
|
||||||
@@ -526,6 +535,7 @@ async fn already_completed(
|
|||||||
objectives_updated: vec![],
|
objectives_updated: vec![],
|
||||||
level_ups: vec![],
|
level_ups: vec![],
|
||||||
expired_loans: vec![],
|
expired_loans: vec![],
|
||||||
|
expired_training: vec![],
|
||||||
season_end: None,
|
season_end: None,
|
||||||
achievements_unlocked: vec![],
|
achievements_unlocked: vec![],
|
||||||
match_record,
|
match_record,
|
||||||
@@ -665,6 +675,7 @@ mod match_completion_tests {
|
|||||||
goal_positions: None,
|
goal_positions: None,
|
||||||
expire_loans: false,
|
expire_loans: false,
|
||||||
advance_season: false,
|
advance_season: false,
|
||||||
|
participants: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -951,6 +962,60 @@ mod match_completion_tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Training expiry must be atomic with the match, in BOTH directions.
|
||||||
|
///
|
||||||
|
/// `BeforeCommit` is the discriminating fault: it fires AFTER the training
|
||||||
|
/// delete has already run inside the transaction. If the boost were removed
|
||||||
|
/// outside the transaction — or the transaction did not actually cover it —
|
||||||
|
/// the row would be gone here while the match itself rolled back, which is
|
||||||
|
/// exactly the split-brain state (match rejected, training consumed) that
|
||||||
|
/// must not exist.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_rolled_back_match_leaves_training_intact() {
|
||||||
|
let fx = new_fixture().await;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at) \
|
||||||
|
VALUES ('inst', ?, 'card', 0, 't')",
|
||||||
|
)
|
||||||
|
.bind(CLUB)
|
||||||
|
.execute(&fx.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_card_training \
|
||||||
|
(owned_card_id, attribute_index, amount, source_card_id, applied_at) \
|
||||||
|
VALUES ('inst', 4, 15, 'fifa17_5003012', 't')",
|
||||||
|
)
|
||||||
|
.execute(&fx.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut r = req("m", MatchResultKind::Win, 3, 1);
|
||||||
|
r.participants = vec!["inst".into()];
|
||||||
|
|
||||||
|
let failed = complete_match_inner(
|
||||||
|
&fx.pool,
|
||||||
|
PROFILE,
|
||||||
|
CLUB,
|
||||||
|
&r,
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
Some(FaultPoint::BeforeCommit),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(failed.is_err(), "the injected fault must fail the match");
|
||||||
|
assert_eq!(
|
||||||
|
count(&fx.pool, "owned_card_training").await,
|
||||||
|
1,
|
||||||
|
"a rolled-back match must NOT consume the boost"
|
||||||
|
);
|
||||||
|
|
||||||
|
// And the clean retry consumes it exactly once.
|
||||||
|
let ok = complete(&fx.pool, &r).await.unwrap();
|
||||||
|
assert_eq!(ok.expired_training, vec!["inst".to_string()]);
|
||||||
|
assert_eq!(count(&fx.pool, "owned_card_training").await, 0);
|
||||||
|
}
|
||||||
|
|
||||||
fn obj(id: &str, metric: ObjectiveMetric, target: i64) -> ObjectiveDefinition {
|
fn obj(id: &str, metric: ObjectiveMetric, target: i64) -> ObjectiveDefinition {
|
||||||
ObjectiveDefinition {
|
ObjectiveDefinition {
|
||||||
id: id.into(),
|
id: id.into(),
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ pub mod achievement;
|
|||||||
pub mod card_db;
|
pub mod card_db;
|
||||||
pub mod checkin;
|
pub mod checkin;
|
||||||
pub mod club;
|
pub mod club;
|
||||||
|
pub mod consume;
|
||||||
pub mod draft;
|
pub mod draft;
|
||||||
pub mod economy;
|
pub mod economy;
|
||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod fut_champs;
|
pub mod fut_champs;
|
||||||
pub mod game_ext;
|
pub mod game_ext;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
|
pub mod instance_effect;
|
||||||
pub mod inventory;
|
pub mod inventory;
|
||||||
pub mod market;
|
pub mod market;
|
||||||
pub mod match_service;
|
pub mod match_service;
|
||||||
@@ -21,4 +23,5 @@ pub mod settings;
|
|||||||
pub mod squad;
|
pub mod squad;
|
||||||
pub mod squad_rules;
|
pub mod squad_rules;
|
||||||
pub mod statistics;
|
pub mod statistics;
|
||||||
|
pub mod training;
|
||||||
pub mod upgrades;
|
pub mod upgrades;
|
||||||
|
|||||||
+6
-5
@@ -350,11 +350,10 @@ async fn submit_sbc_transaction(
|
|||||||
|
|
||||||
let mut cards = Vec::with_capacity(owned_card_ids.len());
|
let mut cards = Vec::with_capacity(owned_card_ids.len());
|
||||||
for owned_id in owned_card_ids {
|
for owned_id in owned_card_ids {
|
||||||
let row = sqlx::query_as::<_, crate::models::card::OwnedCard>(
|
let row = sqlx::query_as::<_, crate::models::card::OwnedCard>(&format!(
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, \
|
"{} WHERE id = ? AND club_id = ?",
|
||||||
chemistry_style, position_override, training_bonus \
|
crate::models::card::OWNED_CARD_SELECT
|
||||||
FROM owned_cards WHERE id = ? AND club_id = ?",
|
))
|
||||||
)
|
|
||||||
.bind(owned_id)
|
.bind(owned_id)
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(&mut **tx)
|
.fetch_optional(&mut **tx)
|
||||||
@@ -818,6 +817,8 @@ mod tests {
|
|||||||
physical: 60,
|
physical: 60,
|
||||||
rarity: Rarity::Bronze,
|
rarity: Rarity::Bronze,
|
||||||
image_path: None,
|
image_path: None,
|
||||||
|
// A player's rating IS `overall`; no separate authored value.
|
||||||
|
source_rating: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+172
-19
@@ -2,7 +2,7 @@ use crate::{
|
|||||||
db::Pool,
|
db::Pool,
|
||||||
error::{AppError, AppResult},
|
error::{AppError, AppResult},
|
||||||
models::{
|
models::{
|
||||||
card::{CardDefinition, OwnedCard},
|
card::{CardDefinition, OwnedCard, OWNED_CARD_SELECT},
|
||||||
game_ext::{GameEntityExt, OpaqueExtensionWrite},
|
game_ext::{GameEntityExt, OpaqueExtensionWrite},
|
||||||
squad::{
|
squad::{
|
||||||
SaveSquadRequest, SlotAssignment, Squad, SquadPlayer, SquadPlayerInput, SquadReplaced,
|
SaveSquadRequest, SlotAssignment, Squad, SquadPlayer, SquadPlayerInput, SquadReplaced,
|
||||||
@@ -88,14 +88,19 @@ pub async fn validate_formation(
|
|||||||
|
|
||||||
let mut gk_count = 0usize;
|
let mut gk_count = 0usize;
|
||||||
for sp in &starters {
|
for sp in &starters {
|
||||||
let owned = sqlx::query_as::<_, OwnedCard>(
|
let owned = sqlx::query_as::<_, OwnedCard>(&format!(
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, chemistry_style, position_override, training_bonus FROM owned_cards WHERE id = ? AND club_id = ?",
|
"{OWNED_CARD_SELECT} WHERE id = ? AND club_id = ?"
|
||||||
)
|
))
|
||||||
.bind(&sp.owned_card_id)
|
.bind(&sp.owned_card_id)
|
||||||
.bind(club_id)
|
.bind(club_id)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| AppError::NotFound(format!("owned card {} not found or does not belong to this club", sp.owned_card_id)))?;
|
.ok_or_else(|| {
|
||||||
|
AppError::NotFound(format!(
|
||||||
|
"owned card {} not found or does not belong to this club",
|
||||||
|
sp.owned_card_id
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
if let Some(card) = card_db.get(&owned.card_id) {
|
if let Some(card) = card_db.get(&owned.card_id) {
|
||||||
if card.position == "GK" {
|
if card.position == "GK" {
|
||||||
@@ -137,13 +142,10 @@ pub async fn calculate_chemistry(
|
|||||||
// Load all starter card definitions (N separate queries, fine for 11 players)
|
// Load all starter card definitions (N separate queries, fine for 11 players)
|
||||||
let mut player_cards: Vec<(String, CardDefinition)> = Vec::new();
|
let mut player_cards: Vec<(String, CardDefinition)> = Vec::new();
|
||||||
for sp in &starters {
|
for sp in &starters {
|
||||||
let owned = sqlx::query_as::<_, OwnedCard>(
|
let owned = sqlx::query_as::<_, OwnedCard>(&format!("{OWNED_CARD_SELECT} WHERE id = ?"))
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at \
|
.bind(&sp.owned_card_id)
|
||||||
FROM owned_cards WHERE id = ?",
|
.fetch_optional(pool)
|
||||||
)
|
.await?;
|
||||||
.bind(&sp.owned_card_id)
|
|
||||||
.fetch_optional(pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if let Some(o) = owned {
|
if let Some(o) = owned {
|
||||||
if let Some(card) = card_db.get(&o.card_id) {
|
if let Some(card) = card_db.get(&o.card_id) {
|
||||||
@@ -270,13 +272,13 @@ async fn replace_squad_inner(
|
|||||||
// though it did.
|
// though it did.
|
||||||
let mut resolved: Vec<(SlotAssignmentRef, OwnedCard)> = Vec::new();
|
let mut resolved: Vec<(SlotAssignmentRef, OwnedCard)> = Vec::new();
|
||||||
for s in &replacement.slots {
|
for s in &replacement.slots {
|
||||||
let owned = sqlx::query_as::<_, OwnedCard>(
|
let owned = sqlx::query_as::<_, OwnedCard>(&format!("{OWNED_CARD_SELECT} WHERE id = ?"))
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, chemistry_style, position_override, training_bonus FROM owned_cards WHERE id = ?",
|
.bind(&s.owned_card_id)
|
||||||
)
|
.fetch_optional(pool)
|
||||||
.bind(&s.owned_card_id)
|
.await?
|
||||||
.fetch_optional(pool)
|
.ok_or_else(|| {
|
||||||
.await?
|
AppError::NotFound(format!("owned card {} not found", s.owned_card_id))
|
||||||
.ok_or_else(|| AppError::NotFound(format!("owned card {} not found", s.owned_card_id)))?;
|
})?;
|
||||||
|
|
||||||
if owned.club_id != club_id {
|
if owned.club_id != club_id {
|
||||||
// Deliberately the same message as "not found": whether a card
|
// Deliberately the same message as "not found": whether a card
|
||||||
@@ -343,6 +345,32 @@ async fn replace_squad_inner(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A replacement carrying no slots would DELETE every assignment below and
|
||||||
|
// insert nothing, silently emptying the squad. No product flow does that:
|
||||||
|
// a full-replacement client sends its COMPLETE slot array, so an empty list
|
||||||
|
// means the caller's own model was destroyed, not that the user emptied
|
||||||
|
// their squad. Mirroring that damage into the authority is unrecoverable,
|
||||||
|
// so refuse it.
|
||||||
|
//
|
||||||
|
// Observed for real: a FIFA 17 client whose in-memory squad had been
|
||||||
|
// destroyed by a bad parse wrote its emptiness back twice, taking
|
||||||
|
// `squad_players` from 18 rows to 0 while the request logged 200/ok.
|
||||||
|
//
|
||||||
|
// Checked inside the transaction so a concurrent write cannot slip between
|
||||||
|
// the count and the delete. A newly created squad counts 0 and is unaffected.
|
||||||
|
if replacement.slots.is_empty() {
|
||||||
|
let existing =
|
||||||
|
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM squad_players WHERE squad_id = ?")
|
||||||
|
.bind(&squad_id)
|
||||||
|
.fetch_one(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if existing > 0 {
|
||||||
|
return Err(AppError::BadRequest(format!(
|
||||||
|
"refusing to empty a populated squad: replacement carried no slots, but squad '{squad_id}' holds {existing} assignments"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
sqlx::query("DELETE FROM squad_players WHERE squad_id = ?")
|
sqlx::query("DELETE FROM squad_players WHERE squad_id = ?")
|
||||||
.bind(&squad_id)
|
.bind(&squad_id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -558,6 +586,131 @@ pub async fn read_squad_with_ext(
|
|||||||
Ok((squad, players, state))
|
Ok((squad, players, state))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Outcome of a role-only squad patch.
|
||||||
|
pub struct SquadRolesPatched {
|
||||||
|
pub squad: Squad,
|
||||||
|
/// Re-anchored fingerprint of the committed canonical state. The captain
|
||||||
|
/// flag is part of the fingerprint, so a captain change MUST re-anchor the
|
||||||
|
/// extension or every later read reports it stale.
|
||||||
|
pub canonical_fingerprint: String,
|
||||||
|
/// Whether the captain flag actually moved (false when it was already set).
|
||||||
|
pub captain_changed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Patch ONLY a squad's role assignments plus its opaque game extension, in one
|
||||||
|
/// transaction. Never inserts, deletes or reorders a single assignment row.
|
||||||
|
///
|
||||||
|
/// This exists because a full replacement and a role-only update are different
|
||||||
|
/// operations that the FIFA 17 client sends down the same wire path. Routing a
|
||||||
|
/// role-only update through [`replace_squad_with_extension`] means presenting it
|
||||||
|
/// as a replacement carrying zero slots, which the empty-replacement guard
|
||||||
|
/// correctly refuses — the client's captain/kick-taker change was being lost
|
||||||
|
/// with a 400. The fix is to stop mis-describing the operation, NOT to relax the
|
||||||
|
/// guard: that guard is load-bearing and stays exactly as strict.
|
||||||
|
///
|
||||||
|
/// Player assignments, the squad manager and club actives are untouched by
|
||||||
|
/// construction — this function issues no statement that can affect them.
|
||||||
|
///
|
||||||
|
/// `captain_owned_card_id` must already be assigned to this squad. Anything else
|
||||||
|
/// is refused before any write, so an invalid target leaves the whole patch
|
||||||
|
/// unapplied (captain AND extension), never half-applied.
|
||||||
|
pub async fn patch_squad_roles(
|
||||||
|
pool: &Pool,
|
||||||
|
game_id: &str,
|
||||||
|
club_id: &str,
|
||||||
|
captain_owned_card_id: Option<&str>,
|
||||||
|
ext: &OpaqueExtensionWrite,
|
||||||
|
) -> AppResult<SquadRolesPatched> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
|
||||||
|
// Resolve the club's active squad. A role patch NEVER creates a squad: with
|
||||||
|
// no squad there is nothing to assign a captain within, and inventing one
|
||||||
|
// here would let a stray patch materialise empty canonical state.
|
||||||
|
let squad = sqlx::query_as::<_, Squad>(
|
||||||
|
"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(&mut *tx)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| AppError::NotFound("no squad found for this club".into()))?;
|
||||||
|
|
||||||
|
let assigned = sqlx::query_as::<_, (String, i64, bool, bool)>(
|
||||||
|
"SELECT owned_card_id, position_index, is_captain, is_on_bench \
|
||||||
|
FROM squad_players WHERE squad_id = ?",
|
||||||
|
)
|
||||||
|
.bind(&squad.id)
|
||||||
|
.fetch_all(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut captain_changed = false;
|
||||||
|
if let Some(captain) = captain_owned_card_id {
|
||||||
|
// Validate against THIS squad's assignments, not the whole collection:
|
||||||
|
// a captain the user does not field is not a captain, and accepting an
|
||||||
|
// arbitrary owned card here would let a patch reference any inventory
|
||||||
|
// item.
|
||||||
|
// Validated BEFORE any write, so an invalid target aborts the whole
|
||||||
|
// patch — captain and extension both — rather than half-applying it.
|
||||||
|
if !assigned.iter().any(|(owned, _, _, _)| owned == captain) {
|
||||||
|
return Err(AppError::BadRequest(format!(
|
||||||
|
"captain '{captain}' is not assigned to squad '{}'",
|
||||||
|
squad.id
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let already_captain = assigned
|
||||||
|
.iter()
|
||||||
|
.any(|(owned, _, cap, _)| owned == captain && *cap);
|
||||||
|
let someone_else_captain = assigned
|
||||||
|
.iter()
|
||||||
|
.any(|(owned, _, cap, _)| *cap && owned != captain);
|
||||||
|
captain_changed = !already_captain || someone_else_captain;
|
||||||
|
sqlx::query("UPDATE squad_players SET is_captain = (owned_card_id = ?) WHERE squad_id = ?")
|
||||||
|
.bind(captain)
|
||||||
|
.bind(&squad.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-anchor to the state as it now stands, applying the captain move to the
|
||||||
|
// in-memory view rather than re-reading: same transaction, same result, one
|
||||||
|
// fewer round trip.
|
||||||
|
let canonical_fingerprint = squad_fingerprint(
|
||||||
|
&squad.id,
|
||||||
|
&squad.formation,
|
||||||
|
assigned.iter().map(|(owned, slot, cap, bench)| {
|
||||||
|
let is_cap = match captain_owned_card_id {
|
||||||
|
Some(c) => owned.as_str() == c,
|
||||||
|
None => *cap,
|
||||||
|
};
|
||||||
|
(*slot, owned.as_str(), is_cap, *bench)
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT OR REPLACE INTO game_entity_ext \
|
||||||
|
(game_id, entity_kind, entity_id, namespace, schema_version, canonical_fingerprint, payload, updated_at) \
|
||||||
|
VALUES (?, 'squad', ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(game_id)
|
||||||
|
.bind(&squad.id)
|
||||||
|
.bind(&ext.namespace)
|
||||||
|
.bind(ext.schema_version)
|
||||||
|
.bind(&canonical_fingerprint)
|
||||||
|
.bind(&ext.payload)
|
||||||
|
.bind(&now)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tx.commit().await?;
|
||||||
|
|
||||||
|
Ok(SquadRolesPatched {
|
||||||
|
squad,
|
||||||
|
canonical_fingerprint,
|
||||||
|
captain_changed,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Compatibility wrapper over [`replace_squad`].
|
/// Compatibility wrapper over [`replace_squad`].
|
||||||
///
|
///
|
||||||
/// Kept so the existing Core REST route keeps working, but it no longer has its
|
/// Kept so the existing Core REST route keeps working, but it no longer has its
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
//! Reading per-instance attribute training back out for projection.
|
||||||
|
//!
|
||||||
|
//! Writing is [`crate::services::instance_effect::InstanceEffect::ApplyTraining`],
|
||||||
|
//! inside the one apply transaction. This module is the read half: it loads the
|
||||||
|
//! effects a club's instances carry and folds them onto a definition's
|
||||||
|
//! attributes.
|
||||||
|
//!
|
||||||
|
//! The fold lives in Core rather than in each game host on purpose. The stored
|
||||||
|
//! effect names a SLOT in Core's own card model, so only Core knows which field
|
||||||
|
//! slot 4 is; a host that did the arithmetic itself would have to re-derive that
|
||||||
|
//! mapping and could disagree with the next host. Core answers with the finished
|
||||||
|
//! numbers and the raw effects, and the host chooses which it needs.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::FromRow;
|
||||||
|
|
||||||
|
use crate::{db::Pool, error::AppResult, models::card::CardDefinition};
|
||||||
|
|
||||||
|
/// The upper bound of a FIFA-style attribute. Training is added to a value whose
|
||||||
|
/// domain is 1..=99, so the fold clamps there.
|
||||||
|
///
|
||||||
|
/// This is a DOMAIN invariant of the six-attribute card model, not a reversed
|
||||||
|
/// training rule: whether FIFA 17 itself refuses to train a 95-pace player past
|
||||||
|
/// 99, or clamps like this, or wraps, is UNKNOWN. Clamping is the only behaviour
|
||||||
|
/// that keeps the projected card inside the model it is drawn from.
|
||||||
|
pub const ATTRIBUTE_MAX: i64 = 99;
|
||||||
|
|
||||||
|
/// The one training effect an instance may carry.
|
||||||
|
///
|
||||||
|
/// At most one per instance: FIFA 17 allows "one attribute or all six" and a new
|
||||||
|
/// card replaces the old, so a second concurrent effect is not representable.
|
||||||
|
#[derive(Debug, Clone, Serialize, FromRow)]
|
||||||
|
pub struct TrainingEffect {
|
||||||
|
/// Slot in Core's six-attribute model, `CardDefinition` declaration order,
|
||||||
|
/// or `None` for an effect that boosts ALL SIX slots.
|
||||||
|
pub attribute_index: Option<i64>,
|
||||||
|
pub amount: i64,
|
||||||
|
pub source_card_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every training effect held by the given club's instances, keyed by instance.
|
||||||
|
///
|
||||||
|
/// One query for the whole club rather than one per item: the projection walks
|
||||||
|
/// up to a couple of thousand owned rows, and a per-item lookup there is the
|
||||||
|
/// classic N+1 that has bitten this projection before.
|
||||||
|
pub async fn load_for_club(
|
||||||
|
pool: &Pool,
|
||||||
|
club_id: &str,
|
||||||
|
) -> AppResult<HashMap<String, TrainingEffect>> {
|
||||||
|
let rows = sqlx::query_as::<_, (String, Option<i64>, i64, String)>(
|
||||||
|
"SELECT t.owned_card_id, t.attribute_index, t.amount, t.source_card_id \
|
||||||
|
FROM owned_card_training t \
|
||||||
|
JOIN owned_cards o ON o.id = t.owned_card_id \
|
||||||
|
WHERE o.club_id = ?",
|
||||||
|
)
|
||||||
|
.bind(club_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(owned_card_id, attribute_index, amount, source_card_id)| {
|
||||||
|
(
|
||||||
|
owned_card_id,
|
||||||
|
TrainingEffect {
|
||||||
|
attribute_index,
|
||||||
|
amount,
|
||||||
|
source_card_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume the training effects of the instances that took the field, inside a
|
||||||
|
/// caller-supplied transaction. Returns the instances actually cleared.
|
||||||
|
///
|
||||||
|
/// FIFA 17 training is a ONE-MATCH effect: it "is reflected in the following
|
||||||
|
/// match and expires after this", and a card applied to someone who stays on the
|
||||||
|
/// bench or in the reserves "will continue to benefit from the training effect
|
||||||
|
/// until he plays" (DOCUMENTED — fifauteam's contemporaneous FIFA 17 guide).
|
||||||
|
/// So the trigger is the PLAYER PLAYING, not the match merely completing, and
|
||||||
|
/// the caller must pass the instances that played — never a whole club.
|
||||||
|
///
|
||||||
|
/// `club_id` is not redundant with the ids: it scopes the delete so a caller
|
||||||
|
/// cannot expire another club's effects by guessing an instance id.
|
||||||
|
///
|
||||||
|
/// Idempotent by construction. Deleting an already-absent row is a no-op, so a
|
||||||
|
/// replayed match cannot "expire twice"; combined with the caller's
|
||||||
|
/// `match_completions` uniqueness guard, the mutation happens exactly once and a
|
||||||
|
/// replay is a silent no-op rather than a second effect.
|
||||||
|
pub async fn expire_for_instances_tx(
|
||||||
|
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
|
||||||
|
club_id: &str,
|
||||||
|
instance_ids: &[String],
|
||||||
|
) -> AppResult<Vec<String>> {
|
||||||
|
let mut expired = Vec::new();
|
||||||
|
for id in instance_ids {
|
||||||
|
// DELETE .. RETURNING so the report is what the database actually
|
||||||
|
// removed, not what we hoped it would: an id that carried no training,
|
||||||
|
// or belongs to another club, simply does not appear.
|
||||||
|
let hit: Option<(String,)> = sqlx::query_as(
|
||||||
|
"DELETE FROM owned_card_training \
|
||||||
|
WHERE owned_card_id = ? \
|
||||||
|
AND owned_card_id IN (SELECT id FROM owned_cards WHERE club_id = ?) \
|
||||||
|
RETURNING owned_card_id",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(club_id)
|
||||||
|
.fetch_optional(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
if let Some((got,)) = hit {
|
||||||
|
expired.push(got);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(expired)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The definition's six attributes in canonical slot order.
|
||||||
|
///
|
||||||
|
/// THIS ORDER IS THE CONTRACT that `attribute_index` indexes. It is
|
||||||
|
/// `CardDefinition`'s own declaration order, and changing it would silently
|
||||||
|
/// re-point every stored effect at a different attribute.
|
||||||
|
pub fn base_attributes(def: &CardDefinition) -> [i64; 6] {
|
||||||
|
[
|
||||||
|
def.pace as i64,
|
||||||
|
def.shooting as i64,
|
||||||
|
def.passing as i64,
|
||||||
|
def.dribbling as i64,
|
||||||
|
def.defending as i64,
|
||||||
|
def.physical as i64,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Base attributes with any training folded in, clamped to the model's domain.
|
||||||
|
///
|
||||||
|
/// A `None` slot boosts ALL SIX attributes — FIFA 17's rare "all" training card.
|
||||||
|
/// An out-of-range slot is ignored rather than panicking: the schema already
|
||||||
|
/// refuses one, so reaching this would mean the row was written around Core, and
|
||||||
|
/// dropping it degrades one attribute instead of failing every projection.
|
||||||
|
pub fn effective_attributes(def: &CardDefinition, effect: Option<&TrainingEffect>) -> [i64; 6] {
|
||||||
|
let mut out = base_attributes(def);
|
||||||
|
let Some(e) = effect else { return out };
|
||||||
|
match e.attribute_index {
|
||||||
|
Some(slot) => {
|
||||||
|
if let Some(v) = out.get_mut(slot as usize) {
|
||||||
|
*v = (*v + e.amount).clamp(0, ATTRIBUTE_MAX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
for v in out.iter_mut() {
|
||||||
|
*v = (*v + e.amount).clamp(0, ATTRIBUTE_MAX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same six values as a named object, for the projection envelope.
|
||||||
|
pub fn effective_attributes_json(
|
||||||
|
def: &CardDefinition,
|
||||||
|
effect: Option<&TrainingEffect>,
|
||||||
|
) -> serde_json::Value {
|
||||||
|
let a = effective_attributes(def, effect);
|
||||||
|
serde_json::json!({
|
||||||
|
"pace": a[0],
|
||||||
|
"shooting": a[1],
|
||||||
|
"passing": a[2],
|
||||||
|
"dribbling": a[3],
|
||||||
|
"defending": a[4],
|
||||||
|
"physical": a[5],
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,15 +1,10 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
db::Pool,
|
db::Pool,
|
||||||
error::{AppError, AppResult},
|
error::{AppError, AppResult},
|
||||||
models::card::OwnedCard,
|
models::card::{OwnedCard, OWNED_CARD_SELECT},
|
||||||
models::chemistry_style::ChemistryStyle,
|
models::chemistry_style::ChemistryStyle,
|
||||||
};
|
};
|
||||||
|
|
||||||
const OWNED_CARD_SELECT: &str =
|
|
||||||
"SELECT id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at, \
|
|
||||||
chemistry_style, position_override, training_bonus \
|
|
||||||
FROM owned_cards";
|
|
||||||
|
|
||||||
pub const MAX_TRAINING_BONUS: i64 = 3;
|
pub const MAX_TRAINING_BONUS: i64 = 3;
|
||||||
|
|
||||||
/// Cost in coins to change a player's position.
|
/// Cost in coins to change a player's position.
|
||||||
|
|||||||
@@ -102,3 +102,106 @@ async fn preflight_passes_when_owned_card_definition_is_loaded() {
|
|||||||
.await
|
.await
|
||||||
.expect("preflight passes when the owned card's definition is loaded");
|
.expect("preflight passes when the owned card's definition is loaded");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The LOAD-BEARING backwards-compatibility property: `source_rating` was added
|
||||||
|
/// to `CardDefinition` long after packs shipped, and `CardDefinition` has no
|
||||||
|
/// `#[serde(default)]`. Every already-emitted pack omits the key, so a pack
|
||||||
|
/// without it MUST still parse — and land as `None`, never as a fabricated 0
|
||||||
|
/// that a tier rule would read as bronze.
|
||||||
|
#[test]
|
||||||
|
fn content_pack_without_source_rating_still_parses() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pack = dir.path().join("legacy-pack.json");
|
||||||
|
std::fs::write(
|
||||||
|
&pack,
|
||||||
|
r#"[{"id":"legacy_1","name":"Legacy Player","overall":84,"position":"ST",
|
||||||
|
"nation":"Nation","league":"League","club":"Club","pace":80,
|
||||||
|
"shooting":85,"passing":70,"dribbling":82,"defending":40,
|
||||||
|
"physical":75,"rarity":"gold","image_path":null}]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut db = CardDb {
|
||||||
|
cards: Default::default(),
|
||||||
|
};
|
||||||
|
assert_eq!(db.load_pack(&pack).expect("legacy pack must load"), 1);
|
||||||
|
let def = db.get("legacy_1").expect("definition merged");
|
||||||
|
assert_eq!(def.overall, 84);
|
||||||
|
assert!(
|
||||||
|
def.source_rating.is_none(),
|
||||||
|
"a missing key is None, not a substituted 0"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pack that DOES carry `source_rating` must round-trip through `CardDb` and
|
||||||
|
/// surface on `/collection` as `card.source_rating` — that envelope field is the
|
||||||
|
/// only authoritative staff/manager tier source a game host has. `overall` stays
|
||||||
|
/// 0 for the non-player because it feeds pricing and squad projection.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn collection_surfaces_source_rating_for_a_non_player() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pack = dir.path().join("staff-pack.json");
|
||||||
|
std::fs::write(
|
||||||
|
&pack,
|
||||||
|
r#"[{"id":"fifa17_3000083","name":"Manager","overall":0,"position":"",
|
||||||
|
"nation":"","league":"","club":"","pace":0,"shooting":0,"passing":0,
|
||||||
|
"dribbling":0,"defending":0,"physical":0,"rarity":"bronze",
|
||||||
|
"image_path":null,"source_rating":88}]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let pool = fresh_pool().await;
|
||||||
|
let cfg = openfut_core::config::Config {
|
||||||
|
listen_addr: "127.0.0.1:0".into(),
|
||||||
|
database_url: "sqlite::memory:".into(),
|
||||||
|
data_dir: "data".into(),
|
||||||
|
max_connections: 1,
|
||||||
|
dev_content_games: Vec::new(),
|
||||||
|
content_packs: vec![pack.clone()],
|
||||||
|
};
|
||||||
|
let app = openfut_core::app::build(pool.clone(), cfg.clone())
|
||||||
|
.await
|
||||||
|
.expect("app build with the staff pack");
|
||||||
|
create_profile(&app).await;
|
||||||
|
let club: String = sqlx::query_scalar("SELECT id FROM clubs LIMIT 1")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
insert_owned(&pool, "oc-manager", &club, "fifa17_3000083").await;
|
||||||
|
|
||||||
|
// Rebuild so preflight sees the owned row, then read the envelope.
|
||||||
|
let app = openfut_core::app::build(pool.clone(), cfg)
|
||||||
|
.await
|
||||||
|
.expect("preflight passes: the pack carries the definition");
|
||||||
|
let resp = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/collection")
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let coll: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||||
|
let entry = coll["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|c| c["owned_card_id"] == serde_json::json!("oc-manager"))
|
||||||
|
.expect("the owned manager must project");
|
||||||
|
assert_eq!(entry["card"]["source_rating"], serde_json::json!(88));
|
||||||
|
assert_eq!(
|
||||||
|
entry["card"]["overall"],
|
||||||
|
serde_json::json!(0),
|
||||||
|
"overall stays 0 for a non-player: it feeds pricing and projection"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
entry["effective_overall"],
|
||||||
|
serde_json::json!(0),
|
||||||
|
"the tier source must NOT leak into the projected overall"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//! the Core-level half of the migration mutation battery: each hostile input is
|
//! the Core-level half of the migration mutation battery: each hostile input is
|
||||||
//! rejected BEFORE any partial write, and re-runs converge instead of duplicating.
|
//! rejected BEFORE any partial write, and re-runs converge instead of duplicating.
|
||||||
|
|
||||||
|
use openfut_core::models::card::ContentKind;
|
||||||
use openfut_core::services::card_db::CardDb;
|
use openfut_core::services::card_db::CardDb;
|
||||||
use openfut_core::services::import::{
|
use openfut_core::services::import::{
|
||||||
apply_profile_import, ImportClub, ImportEntitlement, ImportExtension, ImportOwnedCard,
|
apply_profile_import, ImportClub, ImportEntitlement, ImportExtension, ImportOwnedCard,
|
||||||
@@ -34,6 +35,8 @@ fn owned(ids: &[String]) -> Vec<ImportOwnedCard> {
|
|||||||
.map(|(i, id)| ImportOwnedCard {
|
.map(|(i, id)| ImportOwnedCard {
|
||||||
owned_item_id: format!("oc-{i}"),
|
owned_item_id: format!("oc-{i}"),
|
||||||
card_id: id.clone(),
|
card_id: id.clone(),
|
||||||
|
content_kind: ContentKind::Player,
|
||||||
|
quantity: None,
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -208,6 +211,8 @@ async fn missing_definition_fails_preflight_with_no_writes() {
|
|||||||
ow.push(ImportOwnedCard {
|
ow.push(ImportOwnedCard {
|
||||||
owned_item_id: "oc-bad".into(),
|
owned_item_id: "oc-bad".into(),
|
||||||
card_id: "fifa17_definitely_absent_999999".into(),
|
card_id: "fifa17_definitely_absent_999999".into(),
|
||||||
|
content_kind: ContentKind::Player,
|
||||||
|
quantity: None,
|
||||||
});
|
});
|
||||||
let err = apply_profile_import(&pool, &db, &request("g_miss", "fp", ow, None))
|
let err = apply_profile_import(&pool, &db, &request("g_miss", "fp", ow, None))
|
||||||
.await
|
.await
|
||||||
@@ -282,3 +287,193 @@ async fn empty_owned_fails() {
|
|||||||
.expect_err("empty owned must fail");
|
.expect_err("empty owned must fail");
|
||||||
assert!(format!("{err:#}").contains("zero owned cards"), "{err:#}");
|
assert!(format!("{err:#}").contains("zero owned cards"), "{err:#}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A profile import is once-only, so a taxonomy fix cannot arrive by
|
||||||
|
/// re-importing: the same fingerprint no-ops and a different one is refused.
|
||||||
|
/// Every pre-taxonomy import therefore left coaches, kits and consumables
|
||||||
|
/// durably recorded as players — wrong in the ownership authority even where a
|
||||||
|
/// catalog-driven wire still looked right.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reclassify_corrects_already_imported_rows_and_is_idempotent() {
|
||||||
|
use openfut_core::services::import::{
|
||||||
|
reclassify_owned_content, ContentKindAssignment, ReclassifyRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pool = fresh_pool().await;
|
||||||
|
let db = CardDb::load("data").unwrap();
|
||||||
|
let ids = valid_ids(3);
|
||||||
|
// Imported before the taxonomy existed: everything landed as `player`.
|
||||||
|
let ow = owned(&ids);
|
||||||
|
let req = request("g_reclass", "fp-reclass", ow, None);
|
||||||
|
apply_profile_import(&pool, &db, &req)
|
||||||
|
.await
|
||||||
|
.expect("import");
|
||||||
|
|
||||||
|
let kind_of = |card: String| {
|
||||||
|
let pool = pool.clone();
|
||||||
|
async move {
|
||||||
|
sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT content_kind FROM owned_cards WHERE card_id = ?",
|
||||||
|
)
|
||||||
|
.bind(card)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert_eq!(kind_of(ids[0].clone()).await, "player");
|
||||||
|
|
||||||
|
let rc = ReclassifyRequest {
|
||||||
|
game_id: "g_reclass".into(),
|
||||||
|
dry_run: false,
|
||||||
|
assignments: vec![
|
||||||
|
ContentKindAssignment {
|
||||||
|
card_id: ids[0].clone(),
|
||||||
|
content_kind: ContentKind::Staff,
|
||||||
|
},
|
||||||
|
ContentKindAssignment {
|
||||||
|
card_id: ids[1].clone(),
|
||||||
|
content_kind: ContentKind::Consumable,
|
||||||
|
},
|
||||||
|
ContentKindAssignment {
|
||||||
|
card_id: "fifa17_definition_nobody_owns".into(),
|
||||||
|
content_kind: ContentKind::Kit,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let out = reclassify_owned_content(&pool, &rc)
|
||||||
|
.await
|
||||||
|
.expect("reclassify");
|
||||||
|
assert_eq!(out.updated, 2);
|
||||||
|
assert_eq!(out.unchanged, 0);
|
||||||
|
assert_eq!(
|
||||||
|
out.unmatched_definitions,
|
||||||
|
vec!["fifa17_definition_nobody_owns".to_string()],
|
||||||
|
"an assignment nobody owns is reported, never invented"
|
||||||
|
);
|
||||||
|
assert_eq!(kind_of(ids[0].clone()).await, "staff");
|
||||||
|
assert_eq!(kind_of(ids[1].clone()).await, "consumable");
|
||||||
|
// Untouched definitions keep their kind.
|
||||||
|
assert_eq!(kind_of(ids[2].clone()).await, "player");
|
||||||
|
|
||||||
|
// Rerunning converges: nothing left to change.
|
||||||
|
let again = reclassify_owned_content(&pool, &rc).await.expect("rerun");
|
||||||
|
assert_eq!(again.updated, 0);
|
||||||
|
assert_eq!(again.unchanged, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reclassification is scoped to one game, so a shared database cannot have
|
||||||
|
/// another game's identically-named definition rewritten underneath it.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reclassify_never_crosses_a_game_boundary() {
|
||||||
|
use openfut_core::services::import::{
|
||||||
|
reclassify_owned_content, ContentKindAssignment, ReclassifyRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pool = fresh_pool().await;
|
||||||
|
let db = CardDb::load("data").unwrap();
|
||||||
|
let ids = valid_ids(2);
|
||||||
|
apply_profile_import(&pool, &db, &request("g_a", "fp-a", owned(&ids), None))
|
||||||
|
.await
|
||||||
|
.expect("import a");
|
||||||
|
// Same definitions, but owned-item ids are globally unique.
|
||||||
|
let mut b_owned = owned(&ids);
|
||||||
|
for o in &mut b_owned {
|
||||||
|
o.owned_item_id = format!("b-{}", o.owned_item_id);
|
||||||
|
}
|
||||||
|
apply_profile_import(&pool, &db, &request("g_b", "fp-b", b_owned, None))
|
||||||
|
.await
|
||||||
|
.expect("import b");
|
||||||
|
|
||||||
|
let out = reclassify_owned_content(
|
||||||
|
&pool,
|
||||||
|
&ReclassifyRequest {
|
||||||
|
game_id: "g_a".into(),
|
||||||
|
dry_run: false,
|
||||||
|
assignments: vec![ContentKindAssignment {
|
||||||
|
card_id: ids[0].clone(),
|
||||||
|
content_kind: ContentKind::Kit,
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("reclassify");
|
||||||
|
assert_eq!(out.updated, 1, "only game A's copy");
|
||||||
|
|
||||||
|
let kinds: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT o.content_kind FROM owned_cards o \
|
||||||
|
JOIN clubs c ON c.id = o.club_id JOIN profiles p ON p.id = c.profile_id \
|
||||||
|
WHERE p.game_id = 'g_b' AND o.card_id = ?",
|
||||||
|
)
|
||||||
|
.bind(&ids[0])
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(kinds, vec!["player".to_string()], "game B untouched");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dry run must report the SAME counts a real run would, and leave the
|
||||||
|
/// database byte-for-byte unchanged. It runs the real UPDATEs and rolls back, so
|
||||||
|
/// the numbers are measured rather than predicted — which is the only reason an
|
||||||
|
/// operator can trust them before touching a frozen production database.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reclassify_dry_run_reports_the_real_counts_and_commits_nothing() {
|
||||||
|
use openfut_core::services::import::{
|
||||||
|
reclassify_owned_content, ContentKindAssignment, ReclassifyRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pool = fresh_pool().await;
|
||||||
|
let db = CardDb::load("data").unwrap();
|
||||||
|
let ids = valid_ids(3);
|
||||||
|
apply_profile_import(&pool, &db, &request("g_dry", "fp-dry", owned(&ids), None))
|
||||||
|
.await
|
||||||
|
.expect("import");
|
||||||
|
|
||||||
|
let kinds = || {
|
||||||
|
let pool = pool.clone();
|
||||||
|
async move {
|
||||||
|
sqlx::query_scalar::<_, String>("SELECT content_kind FROM owned_cards ORDER BY card_id")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let before = kinds().await;
|
||||||
|
|
||||||
|
let mut rc = ReclassifyRequest {
|
||||||
|
game_id: "g_dry".into(),
|
||||||
|
dry_run: true,
|
||||||
|
assignments: vec![
|
||||||
|
ContentKindAssignment {
|
||||||
|
card_id: ids[0].clone(),
|
||||||
|
content_kind: ContentKind::Staff,
|
||||||
|
},
|
||||||
|
ContentKindAssignment {
|
||||||
|
card_id: ids[1].clone(),
|
||||||
|
content_kind: ContentKind::Consumable,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
let dry = reclassify_owned_content(&pool, &rc).await.expect("dry run");
|
||||||
|
assert!(dry.dry_run);
|
||||||
|
assert_eq!(dry.updated, 2);
|
||||||
|
assert_eq!(
|
||||||
|
dry.updated_by_kind,
|
||||||
|
[("consumable".to_string(), 1), ("staff".to_string(), 1)]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
"the per-kind shape is what an operator sanity-checks"
|
||||||
|
);
|
||||||
|
assert_eq!(kinds().await, before, "a dry run commits NOTHING");
|
||||||
|
|
||||||
|
// The real run then reports exactly what the dry run promised.
|
||||||
|
rc.dry_run = false;
|
||||||
|
let real = reclassify_owned_content(&pool, &rc)
|
||||||
|
.await
|
||||||
|
.expect("real run");
|
||||||
|
assert!(!real.dry_run);
|
||||||
|
assert_eq!(real.updated, dry.updated);
|
||||||
|
assert_eq!(real.updated_by_kind, dry.updated_by_kind);
|
||||||
|
assert_ne!(kinds().await, before, "the real run DID commit");
|
||||||
|
}
|
||||||
|
|||||||
@@ -1115,6 +1115,118 @@ async fn test_quick_sell_owned_card() {
|
|||||||
assert_eq!(coins_after, coins_before + coins_received);
|
assert_eq!(coins_after, coins_before + coins_received);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `POST /consumables/apply` end to end, in the exact wire shape a game host
|
||||||
|
/// sends: destroy the consumable, move the target's contract counter, surface it
|
||||||
|
/// on `/collection`, and REPLAY (not re-apply) a retried request.
|
||||||
|
///
|
||||||
|
/// Built on its own pool so a consumable instance can be minted directly — the
|
||||||
|
/// starter packs only yield players, and Core has no route that creates one.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_apply_contract_consumable_over_http() {
|
||||||
|
let pool = sqlx::sqlite::SqlitePoolOptions::new()
|
||||||
|
.connect("sqlite::memory:")
|
||||||
|
.await
|
||||||
|
.expect("in-memory sqlite");
|
||||||
|
sqlx::migrate!("./migrations")
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrations");
|
||||||
|
let app = openfut_core::build_app(pool.clone(), "data")
|
||||||
|
.await
|
||||||
|
.expect("app build");
|
||||||
|
auth(&app, "ContractApplier").await;
|
||||||
|
|
||||||
|
let (_, packs) = json_get(&app, "/packs").await;
|
||||||
|
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||||
|
let (s, _) = json_post(
|
||||||
|
&app,
|
||||||
|
&format!("/packs/open/{pack_id}"),
|
||||||
|
serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
|
||||||
|
let (_, coll) = json_get(&app, "/collection").await;
|
||||||
|
let target = coll["collection"][0].clone();
|
||||||
|
let target_id = target["owned_card_id"].as_str().unwrap().to_string();
|
||||||
|
let card_id = target["card"]["id"].as_str().unwrap().to_string();
|
||||||
|
assert!(
|
||||||
|
target["contract_matches"].is_null(),
|
||||||
|
"a pack-fresh instance must report NULL, not a substituted default"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Mint the consumable into the target's own club, reusing a definition the
|
||||||
|
// content pack already loaded so `/collection` can still project it.
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at, content_kind) \
|
||||||
|
SELECT 'contract-card', club_id, ?, 0, ?, 'consumable' FROM owned_cards WHERE id = ?",
|
||||||
|
)
|
||||||
|
.bind(&card_id)
|
||||||
|
.bind("2026-01-01T00:00:00Z")
|
||||||
|
.bind(&target_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("mint a consumable");
|
||||||
|
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"action_identity": format!("fifa17:apply:contract-card->{target_id}"),
|
||||||
|
"source_owned_card_id": "contract-card",
|
||||||
|
"target_owned_card_id": target_id,
|
||||||
|
"target_kind": "player",
|
||||||
|
"effect": {
|
||||||
|
"kind": "add_contract_matches",
|
||||||
|
"amount": 15,
|
||||||
|
"cap": 99,
|
||||||
|
"default_when_unset": 7,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let (s, applied) = json_post(&app, "/consumables/apply", request.clone()).await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{applied}");
|
||||||
|
assert_eq!(applied["applied"], serde_json::json!(true));
|
||||||
|
assert_eq!(applied["source_destroyed"], serde_json::json!(true));
|
||||||
|
assert!(applied["source_quantity_after"].is_null());
|
||||||
|
assert_eq!(
|
||||||
|
applied["target_owned_card_id"],
|
||||||
|
serde_json::json!(target_id)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
applied["effect"],
|
||||||
|
serde_json::json!({
|
||||||
|
"kind": "add_contract_matches", "granted": 15, "before": 7, "after": 22
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let (_, after) = json_get(&app, "/collection").await;
|
||||||
|
let items = after["collection"].as_array().unwrap();
|
||||||
|
let projected = items
|
||||||
|
.iter()
|
||||||
|
.find(|c| c["owned_card_id"] == serde_json::json!(target_id))
|
||||||
|
.expect("target still owned");
|
||||||
|
assert_eq!(projected["contract_matches"], serde_json::json!(22));
|
||||||
|
assert!(
|
||||||
|
!items
|
||||||
|
.iter()
|
||||||
|
.any(|c| c["owned_card_id"] == serde_json::json!("contract-card")),
|
||||||
|
"the consumable must be spent, not merely marked"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A retried request replays: no second grant, and no resurrection of the
|
||||||
|
// source it already destroyed.
|
||||||
|
let (s, replay) = json_post(&app, "/consumables/apply", request).await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
assert_eq!(replay["applied"], serde_json::json!(false));
|
||||||
|
assert_eq!(replay["effect"], applied["effect"]);
|
||||||
|
let (_, twice) = json_get(&app, "/collection").await;
|
||||||
|
let projected = twice["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|c| c["owned_card_id"] == serde_json::json!(target_id))
|
||||||
|
.expect("target still owned")
|
||||||
|
.clone();
|
||||||
|
assert_eq!(projected["contract_matches"], serde_json::json!(22));
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_objective_get_by_id() {
|
async fn test_objective_get_by_id() {
|
||||||
let app = build_test_app().await;
|
let app = build_test_app().await;
|
||||||
@@ -2904,6 +3016,412 @@ async fn test_squad_ext_replace_read_roundtrip_and_idempotency() {
|
|||||||
assert_eq!(other["extension"]["state"], "missing");
|
assert_eq!(other["extension"]["state"], "missing");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A full replacement that carries no slots MUST NOT empty a populated squad.
|
||||||
|
///
|
||||||
|
/// Regression: a FIFA 17 client whose in-memory squad had been destroyed by a
|
||||||
|
/// bad parse wrote that emptiness back through `/squad/replace`, taking the
|
||||||
|
/// canonical squad from 18 assignments to 0 while the request logged 200/ok.
|
||||||
|
/// The squad is the authority's state, so mirroring a broken client's model is
|
||||||
|
/// unrecoverable data loss.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_squad_replace_refuses_to_empty_a_populated_squad() {
|
||||||
|
let app = build_test_app().await;
|
||||||
|
auth(&app, "SquadWipeGuardUser").await;
|
||||||
|
|
||||||
|
let (_, packs) = json_get(&app, "/packs").await;
|
||||||
|
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||||
|
json_post(
|
||||||
|
&app,
|
||||||
|
&format!("/packs/open/{pack_id}"),
|
||||||
|
serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (_, coll) = json_get(&app, "/collection").await;
|
||||||
|
let ids: Vec<String> = coll["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.take(2)
|
||||||
|
.map(|c| c["owned_card_id"].as_str().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let ext_write = serde_json::json!({
|
||||||
|
"namespace": "fifa17.squad", "schema_version": 1, "payload": "{\"custom\":\"[1]\"}"
|
||||||
|
});
|
||||||
|
let client_reported = serde_json::json!({
|
||||||
|
"client_reported_chemistry": 52,
|
||||||
|
"client_reported_rating": 90,
|
||||||
|
"client_reported_star_rating": 90
|
||||||
|
});
|
||||||
|
let populate = serde_json::json!({
|
||||||
|
"name": "OpenFUT",
|
||||||
|
"formation": "f442",
|
||||||
|
"slots": [
|
||||||
|
{"owned_card_id": ids[0], "slot": 0, "is_captain": true, "is_on_bench": false},
|
||||||
|
{"owned_card_id": ids[1], "slot": 1, "is_captain": false, "is_on_bench": false},
|
||||||
|
],
|
||||||
|
"client_reported": client_reported,
|
||||||
|
"extension": ext_write,
|
||||||
|
});
|
||||||
|
let (s, put) = json_put(&app, "/squad/replace", populate).await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{put}");
|
||||||
|
assert_eq!(put["slots_written"], 2);
|
||||||
|
|
||||||
|
// The destructive write: a well-formed replacement that simply carries no
|
||||||
|
// slots. It must be REFUSED, not applied — this is the exact shape that
|
||||||
|
// emptied a real squad.
|
||||||
|
let (s, err) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/replace",
|
||||||
|
serde_json::json!({
|
||||||
|
"name": "OpenFUT",
|
||||||
|
"formation": "f442",
|
||||||
|
"slots": [],
|
||||||
|
"client_reported": client_reported,
|
||||||
|
"extension": ext_write,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
s,
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"an empty replacement must be refused, not applied: {err}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The squad is untouched — the refusal rolled back, it did not half-apply.
|
||||||
|
let (s, ext) = json_get(&app, "/squad/ext?namespace=fifa17.squad").await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
assert_eq!(
|
||||||
|
ext["players"].as_array().unwrap().len(),
|
||||||
|
2,
|
||||||
|
"both assignments survive the refused replacement"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A role-only patch must move the captain and re-anchor the extension WITHOUT
|
||||||
|
/// disturbing a single assignment.
|
||||||
|
///
|
||||||
|
/// Regression: FIFA 17's captain/kick-taker screen sends a body with no
|
||||||
|
/// `players`, which the host presented to `/squad/replace` as a replacement
|
||||||
|
/// carrying zero slots. The empty-replacement guard correctly refused it, so
|
||||||
|
/// every captain change died with a 400 (surfaced to the client as 502). The
|
||||||
|
/// operation, not the guard, was wrong.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_squad_roles_patch_moves_captain_without_touching_assignments() {
|
||||||
|
let app = build_test_app().await;
|
||||||
|
auth(&app, "RolePatchUser").await;
|
||||||
|
|
||||||
|
let (_, packs) = json_get(&app, "/packs").await;
|
||||||
|
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||||
|
json_post(
|
||||||
|
&app,
|
||||||
|
&format!("/packs/open/{pack_id}"),
|
||||||
|
serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (_, coll) = json_get(&app, "/collection").await;
|
||||||
|
let ids: Vec<String> = coll["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.take(2)
|
||||||
|
.map(|c| c["owned_card_id"].as_str().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let client_reported = serde_json::json!({
|
||||||
|
"client_reported_chemistry": 52,
|
||||||
|
"client_reported_rating": 90,
|
||||||
|
"client_reported_star_rating": 90
|
||||||
|
});
|
||||||
|
let (s, put) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/replace",
|
||||||
|
serde_json::json!({
|
||||||
|
"name": "OpenFUT",
|
||||||
|
"formation": "f442",
|
||||||
|
"slots": [
|
||||||
|
{"owned_card_id": ids[0], "slot": 0, "is_captain": true, "is_on_bench": false},
|
||||||
|
{"owned_card_id": ids[1], "slot": 1, "is_captain": false, "is_on_bench": false},
|
||||||
|
],
|
||||||
|
"client_reported": client_reported,
|
||||||
|
"extension": {"namespace": "fifa17.squad", "schema_version": 1,
|
||||||
|
"payload": "{\"custom\":\"[1]\",\"kit_numbers\":{\"a\":7}}"},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{put}");
|
||||||
|
let before_fp = put["canonical_fingerprint"].as_str().unwrap().to_string();
|
||||||
|
|
||||||
|
// Move the captain to the second player, carrying a new opaque payload.
|
||||||
|
let (s, patched) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/roles",
|
||||||
|
serde_json::json!({
|
||||||
|
"captain_owned_card_id": ids[1],
|
||||||
|
"extension": {"namespace": "fifa17.squad", "schema_version": 1,
|
||||||
|
"payload": "{\"custom\":\"[0,8,16]\",\"kit_numbers\":{\"a\":7}}"},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{patched}");
|
||||||
|
assert_eq!(patched["captain_changed"], true);
|
||||||
|
assert_ne!(
|
||||||
|
patched["canonical_fingerprint"].as_str().unwrap(),
|
||||||
|
before_fp,
|
||||||
|
"the captain is part of the fingerprint, so a captain move MUST re-anchor it"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (s, ext) = json_get(&app, "/squad/ext?namespace=fifa17.squad").await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
let players = ext["players"].as_array().unwrap();
|
||||||
|
assert_eq!(players.len(), 2, "a role patch must not add or drop slots");
|
||||||
|
let captain_of = |owned: &str| -> bool {
|
||||||
|
players
|
||||||
|
.iter()
|
||||||
|
.find(|p| p["owned_card_id"] == owned)
|
||||||
|
.map(|p| p["is_captain"] == true)
|
||||||
|
.unwrap_or(false)
|
||||||
|
};
|
||||||
|
assert!(captain_of(&ids[1]), "the new captain is flagged");
|
||||||
|
assert!(!captain_of(&ids[0]), "the previous captain is cleared");
|
||||||
|
// Fresh, not stale: the patch re-anchored the extension it wrote.
|
||||||
|
assert_eq!(
|
||||||
|
ext["extension"]["payload"], "{\"custom\":\"[0,8,16]\",\"kit_numbers\":{\"a\":7}}",
|
||||||
|
"the patch's payload is the one stored"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A role patch naming a captain who is not in the squad must change NOTHING —
|
||||||
|
/// not the captain, not the extension. All-or-nothing, validated before any write.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_squad_roles_patch_rejects_unfielded_captain_and_rolls_back() {
|
||||||
|
let app = build_test_app().await;
|
||||||
|
auth(&app, "RolePatchRollbackUser").await;
|
||||||
|
|
||||||
|
let (_, packs) = json_get(&app, "/packs").await;
|
||||||
|
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||||
|
json_post(
|
||||||
|
&app,
|
||||||
|
&format!("/packs/open/{pack_id}"),
|
||||||
|
serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (_, coll) = json_get(&app, "/collection").await;
|
||||||
|
let ids: Vec<String> = coll["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.take(3)
|
||||||
|
.map(|c| c["owned_card_id"].as_str().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let original_payload = "{\"custom\":\"[1]\"}";
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/replace",
|
||||||
|
serde_json::json!({
|
||||||
|
"name": "OpenFUT",
|
||||||
|
"formation": "f442",
|
||||||
|
"slots": [
|
||||||
|
{"owned_card_id": ids[0], "slot": 0, "is_captain": true, "is_on_bench": false},
|
||||||
|
{"owned_card_id": ids[1], "slot": 1, "is_captain": false, "is_on_bench": false},
|
||||||
|
],
|
||||||
|
"client_reported": serde_json::json!({}),
|
||||||
|
"extension": {"namespace": "fifa17.squad", "schema_version": 1,
|
||||||
|
"payload": original_payload},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
|
||||||
|
// ids[2] is owned but NOT fielded — a patch must not accept it.
|
||||||
|
let (s, err) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/roles",
|
||||||
|
serde_json::json!({
|
||||||
|
"captain_owned_card_id": ids[2],
|
||||||
|
"extension": {"namespace": "fifa17.squad", "schema_version": 1,
|
||||||
|
"payload": "{\"custom\":\"[9,9,9]\"}"},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
s,
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"a captain not assigned to the squad must be refused: {err}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (s, ext) = json_get(&app, "/squad/ext?namespace=fifa17.squad").await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
let players = ext["players"].as_array().unwrap();
|
||||||
|
assert!(
|
||||||
|
players
|
||||||
|
.iter()
|
||||||
|
.any(|p| p["owned_card_id"] == ids[0].as_str() && p["is_captain"] == true),
|
||||||
|
"the original captain survives a refused patch"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
ext["extension"]["payload"], original_payload,
|
||||||
|
"the extension must NOT be written when the captain is refused"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `PUT /club/manager` must keep three states apart: absent = say nothing,
|
||||||
|
/// explicit null = remove, id = assign.
|
||||||
|
///
|
||||||
|
/// Regression: `owned_card_id` was a plain `Option<String>`, so serde collapsed
|
||||||
|
/// "field absent" and "field null" into the same `None` and the route treated
|
||||||
|
/// both as a clear. A caller with nothing to say therefore DELETED the manager —
|
||||||
|
/// how a FIFA 17 client with a destroyed squad model wiped a real manager row
|
||||||
|
/// (WAL commit 468, squad_managers 1 -> 0).
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_manager_absent_field_leaves_assignment_untouched() {
|
||||||
|
let app = build_test_app().await;
|
||||||
|
auth(&app, "ManagerGuardUser").await;
|
||||||
|
|
||||||
|
let (_, packs) = json_get(&app, "/packs").await;
|
||||||
|
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||||
|
json_post(
|
||||||
|
&app,
|
||||||
|
&format!("/packs/open/{pack_id}"),
|
||||||
|
serde_json::json!({}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (_, coll) = json_get(&app, "/collection").await;
|
||||||
|
let ids: Vec<String> = coll["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.take(3)
|
||||||
|
.map(|c| c["owned_card_id"].as_str().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// A squad must exist for a manager to attach to.
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/squad/replace",
|
||||||
|
serde_json::json!({
|
||||||
|
"name": "OpenFUT", "formation": "f442",
|
||||||
|
"slots": [{"owned_card_id": ids[0], "slot": 0, "is_captain": true, "is_on_bench": false}],
|
||||||
|
"client_reported": {"client_reported_chemistry": 50, "client_reported_rating": 80,
|
||||||
|
"client_reported_star_rating": 80},
|
||||||
|
"extension": {"namespace": "fifa17.squad", "schema_version": 1, "payload": "{}"},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK);
|
||||||
|
|
||||||
|
// Assign.
|
||||||
|
let (s, body) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/manager",
|
||||||
|
serde_json::json!({"owned_card_id": ids[1]}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["manager"]["id"], ids[1].as_str());
|
||||||
|
|
||||||
|
// ABSENT field: the destructive shape. Must change nothing.
|
||||||
|
let (s, body) = json_put(&app, "/club/manager", serde_json::json!({})).await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(
|
||||||
|
body["manager"]["id"],
|
||||||
|
ids[1].as_str(),
|
||||||
|
"an absent owned_card_id must LEAVE the manager, never clear it"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reassign to a different owned card: authentic, still allowed.
|
||||||
|
let (s, body) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/manager",
|
||||||
|
serde_json::json!({"owned_card_id": ids[2]}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["manager"]["id"], ids[2].as_str());
|
||||||
|
|
||||||
|
// Same manager again: idempotent no-op, still assigned.
|
||||||
|
let (s, body) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/manager",
|
||||||
|
serde_json::json!({"owned_card_id": ids[2]}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["manager"]["id"], ids[2].as_str());
|
||||||
|
|
||||||
|
// A card this club does not own is refused.
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/manager",
|
||||||
|
serde_json::json!({"owned_card_id": "not-a-real-owned-card"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
s,
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"an unowned manager must be refused"
|
||||||
|
);
|
||||||
|
let (_, body) = json_get(&app, "/club/manager").await;
|
||||||
|
assert_eq!(
|
||||||
|
body["manager"]["id"],
|
||||||
|
ids[2].as_str(),
|
||||||
|
"a refused assignment must not disturb the current manager"
|
||||||
|
);
|
||||||
|
|
||||||
|
// EXPLICIT null: a deliberate removal is legitimate and still works.
|
||||||
|
let (s, body) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/manager",
|
||||||
|
serde_json::json!({"owned_card_id": null}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert!(
|
||||||
|
body["manager"].is_null(),
|
||||||
|
"an explicit null must still remove the manager: {body}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Absent against a squad with NO manager: not over-guarded, plain no-op.
|
||||||
|
let (s, body) = json_put(&app, "/club/manager", serde_json::json!({})).await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{body}");
|
||||||
|
assert!(body["manager"].is_null());
|
||||||
|
|
||||||
|
// The squad's player assignment survived every one of those manager writes.
|
||||||
|
let (_, ext) = json_get(&app, "/squad/ext?namespace=fifa17.squad").await;
|
||||||
|
assert_eq!(
|
||||||
|
ext["players"].as_array().unwrap().len(),
|
||||||
|
1,
|
||||||
|
"manager writes must never disturb player assignments"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A malformed manager body is a PARSER rejection, distinguishable from the
|
||||||
|
/// guard's behaviour: a wrong-typed field is refused outright rather than being
|
||||||
|
/// silently treated as "absent" and passed through as a no-op.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_manager_malformed_body_is_rejected_not_treated_as_absent() {
|
||||||
|
let app = build_test_app().await;
|
||||||
|
auth(&app, "ManagerMalformedUser").await;
|
||||||
|
let resp = app
|
||||||
|
.clone()
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method("PUT")
|
||||||
|
.uri("/club/manager")
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.body(Body::from(r#"{"owned_card_id": 12345}"#))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let s = resp.status();
|
||||||
|
assert!(
|
||||||
|
s == StatusCode::UNPROCESSABLE_ENTITY || s == StatusCode::BAD_REQUEST,
|
||||||
|
"a non-string owned_card_id must be a parser rejection, got {s}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─────────────────────────── economy HTTP boundary ──────────────────────────
|
// ─────────────────────────── economy HTTP boundary ──────────────────────────
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -3378,3 +3896,427 @@ async fn test_economy_settle_sale_route_rejects_self_dealing() {
|
|||||||
Some(SELLER_CLUB)
|
Some(SELLER_CLUB)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── generic active club-item designations + collection taxonomy ───────────────
|
||||||
|
|
||||||
|
/// Insert one owned instance of a given content kind directly, since there is no
|
||||||
|
/// route that grants a kit/badge/ball/stadium yet (the game adapter/import does).
|
||||||
|
async fn seed_owned_kind(
|
||||||
|
pool: &sqlx::SqlitePool,
|
||||||
|
id: &str,
|
||||||
|
club_id: &str,
|
||||||
|
card_id: &str,
|
||||||
|
kind: &str,
|
||||||
|
) {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at, content_kind) \
|
||||||
|
VALUES (?, ?, ?, 0, '2026-01-01T00:00:00Z', ?)",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(club_id)
|
||||||
|
.bind(card_id)
|
||||||
|
.bind(kind)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.expect("seed owned item");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn club_id_of(pool: &sqlx::SqlitePool) -> String {
|
||||||
|
sqlx::query_scalar::<_, String>("SELECT id FROM clubs LIMIT 1")
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_active_items_get_returns_every_slot_explicitly() {
|
||||||
|
let (app, _pool) = build_test_app_with_pool().await;
|
||||||
|
auth(&app, "CAGE").await;
|
||||||
|
let (s, j) = json_get(&app, "/club/active-items").await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{j}");
|
||||||
|
for slot in ["home_kit", "away_kit", "badge", "ball", "stadium"] {
|
||||||
|
assert!(
|
||||||
|
j["active_items"][slot].is_null(),
|
||||||
|
"slot {slot} must be present and null on a fresh club: {j}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_active_items_put_set_and_clear_roundtrip() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
auth(&app, "CAGE").await;
|
||||||
|
let club = club_id_of(&pool).await;
|
||||||
|
// A real definition id keeps the collection projection honest; the kind is
|
||||||
|
// what the designation validates against.
|
||||||
|
seed_owned_kind(&pool, "kit-1", &club, "card_bronze_001", "kit").await;
|
||||||
|
seed_owned_kind(&pool, "badge-1", &club, "card_bronze_002", "badge").await;
|
||||||
|
|
||||||
|
let (s, j) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "home_kit", "owned_card_id": "kit-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{j}");
|
||||||
|
assert_eq!(j["active_items"]["home_kit"]["id"], "kit-1");
|
||||||
|
assert_eq!(j["active_items"]["home_kit"]["content_kind"], "kit");
|
||||||
|
assert!(j["active_items"]["badge"].is_null());
|
||||||
|
|
||||||
|
let (s, j) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "badge", "owned_card_id": "badge-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{j}");
|
||||||
|
assert_eq!(j["active_items"]["badge"]["id"], "badge-1");
|
||||||
|
assert_eq!(j["active_items"]["home_kit"]["id"], "kit-1");
|
||||||
|
|
||||||
|
// A null owned_card_id clears just that slot.
|
||||||
|
let (s, j) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "home_kit", "owned_card_id": null }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{j}");
|
||||||
|
assert!(j["active_items"]["home_kit"].is_null());
|
||||||
|
assert_eq!(j["active_items"]["badge"]["id"], "badge-1");
|
||||||
|
|
||||||
|
// The designation is durable, not per-response.
|
||||||
|
let (_, j) = json_get(&app, "/club/active-items").await;
|
||||||
|
assert_eq!(j["active_items"]["badge"]["id"], "badge-1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_active_items_put_rejects_kind_and_ownership_violations() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
auth(&app, "CAGE").await;
|
||||||
|
let club = club_id_of(&pool).await;
|
||||||
|
seed_owned_kind(&pool, "badge-1", &club, "card_bronze_002", "badge").await;
|
||||||
|
|
||||||
|
// A badge is not a kit.
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "home_kit", "owned_card_id": "badge-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
// An item the club does not own.
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "badge", "owned_card_id": "nope" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
// A slot outside the recovered equipped-state vocabulary.
|
||||||
|
let (s, _) = json_put(
|
||||||
|
&app,
|
||||||
|
"/club/active-items",
|
||||||
|
serde_json::json!({ "slot": "league_logo", "owned_card_id": "badge-1" }),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(s, StatusCode::BAD_REQUEST);
|
||||||
|
|
||||||
|
let (_, j) = json_get(&app, "/club/active-items").await;
|
||||||
|
assert!(j["active_items"]["home_kit"].is_null());
|
||||||
|
assert!(j["active_items"]["badge"].is_null());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_collection_carries_content_kind_and_filters_on_it() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
auth(&app, "CAGE").await;
|
||||||
|
let club = club_id_of(&pool).await;
|
||||||
|
seed_owned_kind(&pool, "kit-1", &club, "card_bronze_001", "kit").await;
|
||||||
|
seed_owned_kind(&pool, "player-1", &club, "card_bronze_002", "player").await;
|
||||||
|
|
||||||
|
let (s, j) = json_get(&app, "/collection").await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "{j}");
|
||||||
|
let kinds: Vec<&str> = j["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|c| c["content_kind"].as_str().expect("content_kind present"))
|
||||||
|
.collect();
|
||||||
|
assert!(kinds.contains(&"kit"), "kinds: {kinds:?}");
|
||||||
|
assert!(kinds.contains(&"player"), "kinds: {kinds:?}");
|
||||||
|
|
||||||
|
let (_, only_kits) = json_get(&app, "/collection?content_kind=kit").await;
|
||||||
|
assert_eq!(only_kits["total"], 1);
|
||||||
|
assert_eq!(only_kits["collection"][0]["owned_card_id"], "kit-1");
|
||||||
|
|
||||||
|
let (_, none) = json_get(&app, "/collection?content_kind=stadium").await;
|
||||||
|
assert_eq!(none["total"], 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_collection_reports_owned_rows_it_cannot_project() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
auth(&app, "CAGE").await;
|
||||||
|
let club = club_id_of(&pool).await;
|
||||||
|
// An owned row whose definition is NOT in loaded content: it cannot be
|
||||||
|
// projected, but it must be counted and named, never silently dropped.
|
||||||
|
seed_owned_kind(&pool, "ghost", &club, "definitely_absent_999", "consumable").await;
|
||||||
|
|
||||||
|
let (s, j) = json_get(&app, "/collection").await;
|
||||||
|
assert_eq!(s, StatusCode::OK, "a missing definition must not 500: {j}");
|
||||||
|
assert_eq!(j["unresolved_items"], 1);
|
||||||
|
assert_eq!(j["unresolved_definitions"][0], "definitely_absent_999");
|
||||||
|
assert_eq!(
|
||||||
|
j["owned_rows"].as_i64().unwrap(),
|
||||||
|
j["total"].as_i64().unwrap() + 1,
|
||||||
|
"owned_rows is ownership truth, total is what could be projected: {j}"
|
||||||
|
);
|
||||||
|
let ids: Vec<&str> = j["collection"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|c| c["owned_card_id"].as_str().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert!(!ids.contains(&"ghost"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─────────────────── One-match training expiry (lifecycle row 12) ────────────
|
||||||
|
//
|
||||||
|
// FIFA 17 training is a ONE-MATCH effect that is consumed by the player PLAYING,
|
||||||
|
// not by the match merely completing: a card on someone who stays on the bench
|
||||||
|
// "will continue to benefit from the training effect until he plays"
|
||||||
|
// (DOCUMENTED). Core therefore expires exactly the instances the caller says
|
||||||
|
// took the field, and nothing else.
|
||||||
|
|
||||||
|
/// Seed a club with two owned instances, both carrying a training effect.
|
||||||
|
/// Returns `(club_id, played_id, benched_id)`.
|
||||||
|
async fn seed_two_trained(
|
||||||
|
app: &axum::Router,
|
||||||
|
pool: &sqlx::SqlitePool,
|
||||||
|
who: &str,
|
||||||
|
) -> (String, String, String) {
|
||||||
|
auth(app, who).await;
|
||||||
|
let club_id: String = sqlx::query_scalar("SELECT id FROM clubs LIMIT 1")
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.expect("club exists after auth");
|
||||||
|
for id in ["played", "benched"] {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at) \
|
||||||
|
VALUES (?, ?, 'card_raregold_001', 0, '2026-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(&club_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_card_training \
|
||||||
|
(owned_card_id, attribute_index, amount, source_card_id, applied_at) \
|
||||||
|
VALUES (?, 4, 15, 'fifa17_5003012', '2026-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
(club_id, "played".to_string(), "benched".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn training_rows(pool: &sqlx::SqlitePool) -> Vec<String> {
|
||||||
|
sqlx::query_scalar("SELECT owned_card_id FROM owned_card_training ORDER BY owned_card_id")
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The core of the documented rule: only the players who took the field lose
|
||||||
|
/// their boost. Expiring the whole squad — or the whole club — would clear the
|
||||||
|
/// benched player the rule explicitly protects.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_match_expires_training_only_for_the_players_who_played() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
let (_club, played, benched) = seed_two_trained(&app, &pool, "ExpiryScope").await;
|
||||||
|
|
||||||
|
let (status, body) = json_post(
|
||||||
|
&app,
|
||||||
|
"/matches/complete",
|
||||||
|
serde_json::json!({
|
||||||
|
"match_identity": "expiry-scope-1", "result": "win",
|
||||||
|
"squad_id": "dummy", "opponent_name": "Bot",
|
||||||
|
"goals_for": 1, "goals_against": 0, "mode": "squad_battles",
|
||||||
|
"participants": [played]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["expired_training"], serde_json::json!(["played"]));
|
||||||
|
assert_eq!(
|
||||||
|
training_rows(&pool).await,
|
||||||
|
vec![benched],
|
||||||
|
"the benched player must keep his boost"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A caller that cannot identify participants must be INERT, never a club wipe.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_match_with_no_participants_expires_nothing() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
seed_two_trained(&app, &pool, "ExpiryNone").await;
|
||||||
|
|
||||||
|
let (status, body) = json_post(
|
||||||
|
&app,
|
||||||
|
"/matches/complete",
|
||||||
|
serde_json::json!({
|
||||||
|
"match_identity": "expiry-none-1", "result": "win",
|
||||||
|
"squad_id": "dummy", "opponent_name": "Bot",
|
||||||
|
"goals_for": 1, "goals_against": 0, "mode": "squad_battles"
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["expired_training"], serde_json::json!([]));
|
||||||
|
assert_eq!(training_rows(&pool).await, vec!["benched", "played"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replay safety. The economic guard already stops double rewards; the training
|
||||||
|
/// mutation must ride the SAME canonical identity so a resubmitted completion
|
||||||
|
/// cannot consume a second, freshly-applied boost.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_replayed_completion_does_not_expire_training_twice() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
let (_club, played, _benched) = seed_two_trained(&app, &pool, "ExpiryReplay").await;
|
||||||
|
|
||||||
|
let submit = || {
|
||||||
|
json_post(
|
||||||
|
&app,
|
||||||
|
"/matches/complete",
|
||||||
|
serde_json::json!({
|
||||||
|
"match_identity": "expiry-replay-1", "result": "win",
|
||||||
|
"squad_id": "dummy", "opponent_name": "Bot",
|
||||||
|
"goals_for": 1, "goals_against": 0, "mode": "squad_battles",
|
||||||
|
"participants": [played]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_, first) = submit().await;
|
||||||
|
assert_eq!(first["applied"], true);
|
||||||
|
assert_eq!(first["expired_training"], serde_json::json!(["played"]));
|
||||||
|
|
||||||
|
// Re-apply a boost to the same instance, then replay the SAME match.
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_card_training \
|
||||||
|
(owned_card_id, attribute_index, amount, source_card_id, applied_at) \
|
||||||
|
VALUES ('played', 4, 15, 'fifa17_5003012', '2026-01-02T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (_, second) = submit().await;
|
||||||
|
assert_eq!(second["applied"], false, "replay must not re-apply");
|
||||||
|
assert_eq!(
|
||||||
|
second["expired_training"],
|
||||||
|
serde_json::json!([]),
|
||||||
|
"a replay reports no mutation"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
training_rows(&pool).await.contains(&"played".to_string()),
|
||||||
|
"the replay must NOT consume the newly applied boost"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `NoContest` is a voided match: it grants no coins, XP or statistics, so it
|
||||||
|
/// must not consume a one-match effect either. Core's `is_economic` guard is the
|
||||||
|
/// single place that decides this, and training now sits inside it.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_no_contest_match_does_not_expire_training() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
let (_club, played, _benched) = seed_two_trained(&app, &pool, "ExpiryVoid").await;
|
||||||
|
|
||||||
|
let (status, body) = json_post(
|
||||||
|
&app,
|
||||||
|
"/matches/complete",
|
||||||
|
serde_json::json!({
|
||||||
|
"match_identity": "expiry-void-1", "result": "no_contest",
|
||||||
|
"squad_id": "dummy", "opponent_name": "Bot",
|
||||||
|
"goals_for": 0, "goals_against": 0, "mode": "squad_battles",
|
||||||
|
"participants": [played]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(body["expired_training"], serde_json::json!([]));
|
||||||
|
assert_eq!(
|
||||||
|
training_rows(&pool).await,
|
||||||
|
vec!["benched", "played"],
|
||||||
|
"a voided match consumes nothing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An id belonging to somebody else's club must not be expirable by guessing it.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn training_expiry_is_scoped_to_the_completing_club() {
|
||||||
|
let (app, pool) = build_test_app_with_pool().await;
|
||||||
|
seed_two_trained(&app, &pool, "ExpiryScoped").await;
|
||||||
|
|
||||||
|
// A genuinely separate club, built properly so the FKs hold — the point of
|
||||||
|
// the test is club scoping, not a dangling row.
|
||||||
|
//
|
||||||
|
// created_at is deliberately in the FUTURE: `get_active_profile` selects
|
||||||
|
// `WHERE game_id = ? ORDER BY created_at ASC LIMIT 1`, and `game_id`
|
||||||
|
// defaults to 'fifa23' (migration 0016), so a rival dated earlier than the
|
||||||
|
// authed profile would silently BECOME the active profile and this test
|
||||||
|
// would assert the opposite of what it means.
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO profiles (id, username, created_at, updated_at) \
|
||||||
|
VALUES ('other-profile', 'Rival', '2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO clubs (id, profile_id, name, created_at, updated_at) \
|
||||||
|
VALUES ('other-club', 'other-profile', 'Rival FC', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at) \
|
||||||
|
VALUES ('foreign', 'other-club', 'card_raregold_001', 0, '2026-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_card_training \
|
||||||
|
(owned_card_id, attribute_index, amount, source_card_id, applied_at) \
|
||||||
|
VALUES ('foreign', 4, 15, 'fifa17_5003012', '2026-01-01T00:00:00Z')",
|
||||||
|
)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let (status, body) = json_post(
|
||||||
|
&app,
|
||||||
|
"/matches/complete",
|
||||||
|
serde_json::json!({
|
||||||
|
"match_identity": "expiry-scoped-1", "result": "win",
|
||||||
|
"squad_id": "dummy", "opponent_name": "Bot",
|
||||||
|
"goals_for": 1, "goals_against": 0, "mode": "squad_battles",
|
||||||
|
"participants": ["foreign"]
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(status, StatusCode::OK, "{body}");
|
||||||
|
assert_eq!(
|
||||||
|
body["expired_training"],
|
||||||
|
serde_json::json!([]),
|
||||||
|
"another club's effect must not be reachable"
|
||||||
|
);
|
||||||
|
assert!(training_rows(&pool).await.contains(&"foreign".to_string()));
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,365 @@
|
|||||||
|
//! Owned-content model migrations (0025 content_kind/quantity, 0026
|
||||||
|
//! club_active_items, 0027 consumable_applications, 0028 contract_matches).
|
||||||
|
//!
|
||||||
|
//! Two things must hold on a DB that already contains real ownership:
|
||||||
|
//! * every pre-existing owned row survives and reads back as a `player` with no
|
||||||
|
//! stack size and no tracked contract (the band is a pure widening, never a
|
||||||
|
//! rewrite and never a backfill of someone else's default);
|
||||||
|
//! * every existing kit designation lands in `club_active_items` under its
|
||||||
|
//! generalised slot token, and the old table + trigger are gone.
|
||||||
|
//!
|
||||||
|
//! 0028 additionally must NOT be a table rebuild: `owned_cards` carries 0026's
|
||||||
|
//! `clear_club_active_item_before_transfer` trigger, and a DROP/recreate would
|
||||||
|
//! take it along silently. The trigger assertions below therefore run AFTER the
|
||||||
|
//! whole band, not just after 0026.
|
||||||
|
//!
|
||||||
|
//! The first is proved against a COPY of a real populated club snapshot (1986
|
||||||
|
//! owned rows) when `OPENFUT_CORE_SNAPSHOT_DB` points at one; the second is
|
||||||
|
//! proved by staging a DB at migration 0025, writing 0024-era kit rows, and then
|
||||||
|
//! letting the remaining migrations run.
|
||||||
|
|
||||||
|
use std::borrow::Cow;
|
||||||
|
|
||||||
|
use openfut_core::models::card::{ActiveSlot, ContentKind};
|
||||||
|
use sqlx::migrate::Migrator;
|
||||||
|
use sqlx::sqlite::SqlitePoolOptions;
|
||||||
|
use sqlx::{Row, SqlitePool};
|
||||||
|
|
||||||
|
const OWNED_CONTENT_MIGRATION: i64 = 25;
|
||||||
|
|
||||||
|
async fn pool_for(path: &std::path::Path) -> SqlitePool {
|
||||||
|
let opts = sqlx::sqlite::SqliteConnectOptions::new()
|
||||||
|
.filename(path)
|
||||||
|
.create_if_missing(true)
|
||||||
|
.foreign_keys(true);
|
||||||
|
SqlitePoolOptions::new()
|
||||||
|
.max_connections(1)
|
||||||
|
.connect_with(opts)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|e| panic!("open {}: {e}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The full migrator, truncated after `version`. Used to stage a DB in the state
|
||||||
|
/// it had BEFORE the migrations under test, so their data carry-over is exercised
|
||||||
|
/// on rows that really pre-date them.
|
||||||
|
fn migrator_upto(version: i64) -> Migrator {
|
||||||
|
let full = sqlx::migrate!("./migrations");
|
||||||
|
let subset: Vec<_> = full
|
||||||
|
.iter()
|
||||||
|
.filter(|m| m.version < version)
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
Migrator {
|
||||||
|
migrations: Cow::Owned(subset),
|
||||||
|
ignore_missing: true,
|
||||||
|
locking: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn table_exists(pool: &SqlitePool, name: &str) -> bool {
|
||||||
|
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?")
|
||||||
|
.bind(name)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
> 0
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn trigger_names(pool: &SqlitePool) -> Vec<String> {
|
||||||
|
sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='trigger' ORDER BY name",
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage a DB at pre-0025 state with two 0024-era kit designations, then run the
|
||||||
|
/// rest of the migrations: the designations MUST be carried over, not dropped.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn kit_assignments_migrate_into_club_active_items() {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let db = dir.path().join("staged.db");
|
||||||
|
let pool = pool_for(&db).await;
|
||||||
|
migrator_upto(OWNED_CONTENT_MIGRATION)
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrate to pre-0025");
|
||||||
|
assert!(
|
||||||
|
table_exists(&pool, "club_kit_assignments").await,
|
||||||
|
"staging must actually be at the 0024 schema"
|
||||||
|
);
|
||||||
|
|
||||||
|
let ts = "2026-01-01T00:00:00Z";
|
||||||
|
sqlx::query("INSERT INTO profiles (id, username, created_at, updated_at) VALUES ('p','p',?,?)")
|
||||||
|
.bind(ts)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO clubs (id, profile_id, name, coins, created_at, updated_at) \
|
||||||
|
VALUES ('c','p','c',0,?,?)",
|
||||||
|
)
|
||||||
|
.bind(ts)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
for id in ["kit-h", "kit-a", "spare"] {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at) \
|
||||||
|
VALUES (?, 'c', ?, 0, ?)",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.bind(format!("def-{id}"))
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
for (slot, owned) in [("home", "kit-h"), ("away", "kit-a")] {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO club_kit_assignments (club_id, slot, owned_card_id, updated_at) \
|
||||||
|
VALUES ('c', ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(slot)
|
||||||
|
.bind(owned)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now the migrations under test.
|
||||||
|
sqlx::migrate!("./migrations")
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrate to head");
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!table_exists(&pool, "club_kit_assignments").await,
|
||||||
|
"the old kit table must be gone"
|
||||||
|
);
|
||||||
|
assert!(table_exists(&pool, "club_active_items").await);
|
||||||
|
assert!(table_exists(&pool, "consumable_applications").await);
|
||||||
|
|
||||||
|
let rows =
|
||||||
|
sqlx::query("SELECT slot, owned_card_id, updated_at FROM club_active_items ORDER BY slot")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let carried: Vec<(String, String, String)> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|r| (r.get(0), r.get(1), r.get(2)))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
carried,
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
ActiveSlot::AwayKit.as_str().into(),
|
||||||
|
"kit-a".to_string(),
|
||||||
|
ts.to_string()
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ActiveSlot::HomeKit.as_str().into(),
|
||||||
|
"kit-h".to_string(),
|
||||||
|
ts.to_string()
|
||||||
|
),
|
||||||
|
],
|
||||||
|
"home -> home_kit, away -> away_kit, timestamps preserved"
|
||||||
|
);
|
||||||
|
|
||||||
|
// 0024's trigger is replaced, never merely orphaned: an ownership transfer
|
||||||
|
// must still clear the designation (and must not fail on a missing table).
|
||||||
|
let names = trigger_names(&pool).await;
|
||||||
|
assert!(
|
||||||
|
!names.contains(&"clear_club_kit_assignment_before_transfer".to_string()),
|
||||||
|
"the old trigger must be dropped, got {names:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
names.contains(&"clear_club_active_item_before_transfer".to_string()),
|
||||||
|
"the generalised trigger must exist, got {names:?}"
|
||||||
|
);
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO clubs (id, profile_id, name, coins, created_at, updated_at) \
|
||||||
|
VALUES ('c2','p','c2',0,?,?)",
|
||||||
|
)
|
||||||
|
.bind(ts)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query("UPDATE owned_cards SET club_id = 'c2' WHERE id = 'kit-h'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("transfer must succeed after the trigger swap");
|
||||||
|
let remaining =
|
||||||
|
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM club_active_items WHERE club_id='c'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(remaining, 1, "the transferred kit's designation is cleared");
|
||||||
|
|
||||||
|
// Backfilled ownership reads back as the default kind with no stack size.
|
||||||
|
let (kind, quantity) = sqlx::query_as::<_, (ContentKind, Option<i64>)>(
|
||||||
|
"SELECT content_kind, quantity FROM owned_cards WHERE id = 'spare'",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(kind, ContentKind::Player);
|
||||||
|
assert_eq!(quantity, None);
|
||||||
|
|
||||||
|
// 0028: the column exists and every row that pre-dates it reads back NULL.
|
||||||
|
// NULL is not zero — it means Core tracks no contract for the instance, so a
|
||||||
|
// backfill here would have invented one game's pack-fresh number for all of
|
||||||
|
// them.
|
||||||
|
let contract = sqlx::query_scalar::<_, Option<i64>>(
|
||||||
|
"SELECT contract_matches FROM owned_cards WHERE id = 'spare'",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.expect("0028 must have added contract_matches");
|
||||||
|
assert_eq!(contract, None, "a pre-existing row tracks no contract");
|
||||||
|
assert!(
|
||||||
|
sqlx::query("UPDATE owned_cards SET contract_matches = -1 WHERE id = 'spare'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"contract_matches CHECK must reject a negative count"
|
||||||
|
);
|
||||||
|
|
||||||
|
// And the new column constraints are real, not documentation.
|
||||||
|
assert!(
|
||||||
|
sqlx::query("UPDATE owned_cards SET content_kind = 'coach' WHERE id = 'spare'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"content_kind CHECK must reject a token outside the vocabulary"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
sqlx::query("UPDATE owned_cards SET quantity = 0 WHERE id = 'spare'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"quantity CHECK must reject a non-positive stack"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO club_active_items (club_id, slot, owned_card_id, updated_at) \
|
||||||
|
VALUES ('c', 'league_logo', 'spare', ?)"
|
||||||
|
)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"slot CHECK must reject a token outside the recovered equipped-state set"
|
||||||
|
);
|
||||||
|
drop(dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The migrations must apply cleanly to a COPY of a REAL populated club DB,
|
||||||
|
/// leave every owned row intact, and carry a real kit designation over.
|
||||||
|
///
|
||||||
|
/// The snapshot predates migration 0024, so the copy is first brought up to the
|
||||||
|
/// 0024 schema and given two kit designations pointing at REAL owned instances;
|
||||||
|
/// only then do the migrations under test run. That way the carry-over is proved
|
||||||
|
/// on production ownership, not on synthetic rows.
|
||||||
|
///
|
||||||
|
/// Point `OPENFUT_CORE_SNAPSHOT_DB` at a real `core.db` to run it; without that
|
||||||
|
/// the test reports the skip rather than passing silently on nothing.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn migrations_apply_to_a_real_populated_snapshot() {
|
||||||
|
let Ok(source) = std::env::var("OPENFUT_CORE_SNAPSHOT_DB") else {
|
||||||
|
eprintln!(
|
||||||
|
"SKIPPED migrations_apply_to_a_real_populated_snapshot: set \
|
||||||
|
OPENFUT_CORE_SNAPSHOT_DB=/path/to/core.db to run it"
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let copy = dir.path().join("core.db");
|
||||||
|
// Copy, never open the source: the snapshot is read-only evidence.
|
||||||
|
std::fs::copy(&source, ©).unwrap_or_else(|e| panic!("copy {source}: {e}"));
|
||||||
|
let pool = pool_for(©).await;
|
||||||
|
|
||||||
|
let before = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM owned_cards")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.expect("snapshot must already hold ownership");
|
||||||
|
assert!(
|
||||||
|
before > 0,
|
||||||
|
"the snapshot must be populated to prove anything"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Bring the copy to the 0024 schema and designate two REAL owned instances
|
||||||
|
// as this club's kits, exactly as the pre-generalisation server would have.
|
||||||
|
migrator_upto(OWNED_CONTENT_MIGRATION)
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrate the snapshot to pre-0025");
|
||||||
|
let real: Vec<(String, String)> =
|
||||||
|
sqlx::query_as("SELECT id, club_id FROM owned_cards ORDER BY id LIMIT 2")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(real.len(), 2, "need two real owned instances");
|
||||||
|
let ts = "2026-01-01T00:00:00Z";
|
||||||
|
for (slot, (owned_id, club_id)) in ["home", "away"].into_iter().zip(&real) {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO club_kit_assignments (club_id, slot, owned_card_id, updated_at) \
|
||||||
|
VALUES (?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(club_id)
|
||||||
|
.bind(slot)
|
||||||
|
.bind(owned_id)
|
||||||
|
.bind(ts)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("stage a real kit designation");
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlx::migrate!("./migrations")
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrations must apply to real populated data");
|
||||||
|
|
||||||
|
let (after, players, stacked, contracted) = sqlx::query_as::<_, (i64, i64, i64, i64)>(
|
||||||
|
"SELECT COUNT(*), \
|
||||||
|
SUM(CASE WHEN content_kind = 'player' THEN 1 ELSE 0 END), \
|
||||||
|
SUM(CASE WHEN quantity IS NOT NULL THEN 1 ELSE 0 END), \
|
||||||
|
SUM(CASE WHEN contract_matches IS NOT NULL THEN 1 ELSE 0 END) \
|
||||||
|
FROM owned_cards",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(after, before, "no owned row may be lost or duplicated");
|
||||||
|
assert_eq!(players, before, "every backfilled row is a player");
|
||||||
|
assert_eq!(stacked, 0, "no pre-existing row gains a stack size");
|
||||||
|
assert_eq!(contracted, 0, "no pre-existing row gains a contract count");
|
||||||
|
|
||||||
|
assert!(table_exists(&pool, "club_active_items").await);
|
||||||
|
assert!(!table_exists(&pool, "club_kit_assignments").await);
|
||||||
|
assert!(table_exists(&pool, "consumable_applications").await);
|
||||||
|
|
||||||
|
let carried: Vec<(String, String)> =
|
||||||
|
sqlx::query_as("SELECT slot, owned_card_id FROM club_active_items ORDER BY slot")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
carried,
|
||||||
|
vec![
|
||||||
|
(ActiveSlot::AwayKit.as_str().into(), real[1].0.clone()),
|
||||||
|
(ActiveSlot::HomeKit.as_str().into(), real[0].0.clone()),
|
||||||
|
],
|
||||||
|
"real kit designations must land in club_active_items"
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
"snapshot: {after} owned rows survive as content_kind='player'; \
|
||||||
|
designations carried over: {carried:?}"
|
||||||
|
);
|
||||||
|
drop(dir);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user