repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/training/mod.rs
src/core/src/club/player/training/mod.rs
pub mod history; pub mod result; pub mod training; pub use history::*; pub use training::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/calculators/mod.rs
src/core/src/club/player/calculators/mod.rs
mod calculator; pub use calculator::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/calculators/calculator.rs
src/core/src/club/player/calculators/calculator.rs
use crate::{Person, Player, PlayerStatusType}; use chrono::{Datelike, NaiveDate}; pub struct PlayerValueCalculator; impl PlayerValueCalculator { pub fn calculate(player: &Player, now: NaiveDate) -> f64 { let base_value = determine_base_value(player); let age_factor = determine_age_factor(player, now); let status_factor = determine_status_factor(player); let contract_factor = determine_contract_factor(player, now); let country_factor = determine_country_factor(player); let form_factor = determine_form_factor(player); let match_appearance_factor = determine_match_appearance_factor(player); let statistics_factor = determine_statistics_factor(player); let other_factors = determine_other_factors(player); let value = base_value * age_factor * status_factor * contract_factor * country_factor * form_factor * match_appearance_factor * statistics_factor * other_factors; value } } fn determine_base_value(player: &Player) -> f64 { const BASE_PRICE: f64 = 1_000_000.0; let technical_mean = player.skills.technical.average(); let mental_mean = player.skills.mental.average(); let physical_mean = player.skills.physical.average(); let base_value = ((technical_mean + mental_mean + physical_mean) / 3.0) as f64; BASE_PRICE * base_value } fn determine_age_factor(player: &Player, date: NaiveDate) -> f64 { match player.age(date) { age if age < 21 => 0.7, age if age < 25 => 0.8, age if age < 30 => 0.9, age if age < 35 => 0.7, age if age < 40 => 0.5, _ => 0.3, } } fn determine_status_factor(player: &Player) -> f64 { let statuses = player.statuses.get(); let mut status_factor = 1.0f64; if statuses.contains(&PlayerStatusType::Inj) { status_factor *= 0.7; } if statuses.contains(&PlayerStatusType::Unh) { status_factor *= 0.8; } if statuses.contains(&PlayerStatusType::Loa) { status_factor *= 0.9; } status_factor } fn determine_contract_factor(player: &Player, date: NaiveDate) -> f64 { let contract = match &player.contract { Some(contract) => contract, None => return 0.0, }; let remaining_years = (contract.expiration.year() as i32 - date.year() as i32) as f64; let contract_factor = match remaining_years { remaining_years if remaining_years > 2.0 => 1.0, remaining_years if remaining_years > 1.0 => 0.9, remaining_years if remaining_years > 0.5 => 0.8, _ => 0.7, }; contract_factor } fn determine_country_factor(_player: &Player) -> f64 { let country_factor = 1.0; country_factor } fn determine_form_factor(_player: &Player) -> f64 { let form_factor = 1.0; // let form = match player.statistics.get_form(date) { // Some(form) => form, // None => return 1.0, // }; // // let form_factor = match form { // form if form > 8.0 => 1.1, // form if form > 6.0 => 1.0, // form if form > 4.0 => 0.9, // form if form > 2.0 => 0.8, // _ => 0.7, // }; form_factor } fn determine_match_appearance_factor(_player: &Player) -> f64 { let match_appearance_factor = 1.0; match_appearance_factor } fn determine_statistics_factor(player: &Player) -> f64 { let match_appearance_factor = match player.statistics.played { match_appearances if match_appearances > 20 => 1.1, match_appearances if match_appearances > 10 => 1.0, match_appearances if match_appearances > 5 => 0.9, match_appearances if match_appearances > 2 => 0.8, _ => 0.7, }; match_appearance_factor } fn determine_other_factors(player: &Player) -> f64 { let mut other_factors = 1.0; if player.positions.is_goalkeeper() { other_factors *= 1.2; } if player.happiness.is_happy() { other_factors *= 1.1; } if player.attributes.loyalty > 8.0 { other_factors *= 1.1; } other_factors } #[cfg(test)] mod tests { #[test] fn calculate_is_correct() {} }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/mailbox.rs
src/core/src/club/player/mailbox/mailbox.rs
use crate::handlers::ProcessContractHandler; use crate::{Player, PlayerMailboxResult, PlayerResult}; use chrono::NaiveDate; use std::collections::VecDeque; use std::sync::Mutex; #[derive(Debug)] pub struct PlayerMessage { pub message_type: PlayerMessageType, } #[derive(Debug)] pub enum PlayerMessageType { Greeting, ContractProposal(PlayerContractProposal), } #[derive(Debug)] pub struct PlayerContractProposal { pub salary: u32, pub years: u8, } #[derive(Debug)] pub struct PlayerMailbox { messages: Mutex<VecDeque<PlayerMessage>>, } impl PlayerMailbox { pub fn new() -> Self { PlayerMailbox { messages: Mutex::new(VecDeque::new()), } } pub fn process( player: &mut Player, player_result: &mut PlayerResult, now: NaiveDate, ) -> PlayerMailboxResult { let result = PlayerMailboxResult::new(); for message in player.mailbox.get() { match message.message_type { PlayerMessageType::Greeting => {} PlayerMessageType::ContractProposal(proposal) => { ProcessContractHandler::process(player, proposal, now, player_result); } } } result } pub fn push(&self, message: PlayerMessage) { let mut messages = self.messages.lock().unwrap(); messages.push_back(message); } pub fn get(&self) -> Vec<PlayerMessage> { let mut messages = self.messages.lock().unwrap(); messages.drain(..).collect() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/result.rs
src/core/src/club/player/mailbox/result.rs
pub struct PlayerMailboxResult; impl PlayerMailboxResult { pub fn new() -> Self { PlayerMailboxResult {} } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/mod.rs
src/core/src/club/player/mailbox/mod.rs
pub mod handlers; pub mod mailbox; pub mod result; pub use mailbox::*; pub use result::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/handlers/contract_proposal.rs
src/core/src/club/player/mailbox/handlers/contract_proposal.rs
use crate::handlers::AcceptContractHandler; use crate::{PersonBehaviourState, Player, PlayerContractProposal, PlayerResult}; use chrono::NaiveDate; pub struct ProcessContractHandler; impl ProcessContractHandler { pub fn process( player: &mut Player, proposal: PlayerContractProposal, now: NaiveDate, result: &mut PlayerResult, ) { match &player.contract { Some(player_contract) => { if proposal.salary > player_contract.salary { AcceptContractHandler::process(player, proposal, now); } else { result.contract.contract_rejected = true; } } None => match player.behaviour.state { PersonBehaviourState::Poor => { result.contract.contract_rejected = true; } PersonBehaviourState::Normal => {} PersonBehaviourState::Good => { Self::process(player, proposal, now, result); } }, } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/handlers/mod.rs
src/core/src/club/player/mailbox/handlers/mod.rs
mod accept_contract; mod contract_proposal; pub use accept_contract::*; pub use contract_proposal::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/mailbox/handlers/accept_contract.rs
src/core/src/club/player/mailbox/handlers/accept_contract.rs
use crate::{ContractType, Player, PlayerClubContract, PlayerContractProposal, PlayerSquadStatus}; use chrono::NaiveDate; pub struct AcceptContractHandler; impl AcceptContractHandler { pub fn process(player: &mut Player, proposal: PlayerContractProposal, now: NaiveDate) { player.contract = Some(PlayerClubContract { shirt_number: None, salary: proposal.salary, contract_type: ContractType::FullTime, squad_status: PlayerSquadStatus::FirstTeamRegular, is_transfer_listed: false, transfer_status: Option::None, started: Option::None, expiration: now, //TODO ADD YEARS bonuses: vec![], clauses: vec![], }); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/contract/contract.rs
src/core/src/club/player/contract/contract.rs
use crate::context::SimulationContext; pub use chrono::prelude::{DateTime, Datelike, NaiveDate, Utc}; use chrono::NaiveDateTime; #[derive(Debug)] pub enum ContractType { PartTime, FullTime, Amateur, Youth, NonContract, } #[derive(Debug)] pub enum PlayerSquadStatus { Invalid, NotYetSet, KeyPlayer, FirstTeamRegular, FirstTeamSquadRotation, MainBackupPlayer, HotProspectForTheFuture, DecentYoungster, NotNeeded, SquadStatusCount, } #[derive(Debug)] pub enum PlayerTransferStatus { TransferListed, LoadListed, TransferAndLoadListed, } #[derive(Debug)] pub struct PlayerClubContract { pub shirt_number: Option<u8>, pub salary: u32, pub contract_type: ContractType, pub squad_status: PlayerSquadStatus, pub is_transfer_listed: bool, pub transfer_status: Option<PlayerTransferStatus>, pub started: Option<NaiveDate>, pub expiration: NaiveDate, pub bonuses: Vec<ContractBonus>, pub clauses: Vec<ContractClause>, } impl PlayerClubContract { pub fn new(salary: u32, expired: NaiveDate) -> Self { PlayerClubContract { shirt_number: None, salary, contract_type: ContractType::FullTime, squad_status: PlayerSquadStatus::NotYetSet, transfer_status: None, is_transfer_listed: false, started: Option::None, expiration: expired, bonuses: vec![], clauses: vec![], } } pub fn is_expired(&self, now: NaiveDateTime) -> bool { self.expiration >= now.date() } pub fn days_to_expiration(&self, now: NaiveDateTime) -> i64 { let diff = self.expiration - now.date(); diff.num_days().abs() } pub fn simulate(&mut self, context: &mut SimulationContext) { if context.check_contract_expiration() && self.is_expired(context.date) {} } } // Bonuses #[derive(Debug)] pub enum ContractBonusType { AppearanceFee, GoalFee, CleanSheetFee, TeamOfTheYear, TopGoalscorer, PromotionFee, AvoidRelegationFee, InternationalCapFee, UnusedSubstitutionFee, } #[derive(Debug)] pub struct ContractBonus { pub value: i32, pub bonus_type: ContractBonusType, } impl ContractBonus { pub fn new(value: i32, bonus_type: ContractBonusType) -> Self { ContractBonus { value, bonus_type } } } // Clauses #[derive(Debug)] pub enum ContractClauseType { MinimumFeeRelease, RelegationFeeRelease, NonPromotionRelease, YearlyWageRise, PromotionWageIncrease, RelegationWageDecrease, StaffJobRelease, SellOnFee, SellOnFeeProfit, SeasonalLandmarkGoalBonus, OneYearExtensionAfterLeagueGamesFinalSeason, MatchHighestEarner, WageAfterReachingClubCareerLeagueGames, TopDivisionPromotionWageRise, TopDivisionRelegationWageDrop, MinimumFeeReleaseToForeignClubs, MinimumFeeReleaseToHigherDivisionClubs, MinimumFeeReleaseToDomesticClubs, WageAfterReachingInternationalCaps, OptionalContractExtensionByClub, } #[derive(Debug)] pub struct ContractClause { pub value: i32, pub bonus_type: ContractClauseType, } impl ContractClause { pub fn new(value: i32, bonus_type: ContractClauseType) -> Self { ContractClause { value, bonus_type } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/club/player/contract/mod.rs
src/core/src/club/player/contract/mod.rs
pub mod contract; pub use contract::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/date.rs
src/core/src/utils/date.rs
use chrono::prelude::*; use chrono::NaiveDate; pub struct DateUtils; impl DateUtils { #[inline] pub fn is_birthday(birth_date: NaiveDate, current_date: NaiveDate) -> bool { birth_date.month() == current_date.month() && birth_date.day() == current_date.day() } #[inline] pub fn age(birthdate: NaiveDate, now: NaiveDate) -> u8 { let age_duration = now.signed_duration_since(birthdate); (age_duration.num_days() / 365) as u8 } pub fn next_saturday(date: NaiveDate) -> NaiveDate { let mut current_date = date; while current_date.weekday() != Weekday::Sat { current_date = current_date.succ_opt().unwrap(); } current_date } } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_birthday() { let birth_date = NaiveDate::from_ymd_opt(1990, 3, 16).unwrap(); let current_date = NaiveDate::from_ymd_opt(2024, 3, 16).unwrap(); assert!(DateUtils::is_birthday(birth_date, current_date)); let birth_date = NaiveDate::from_ymd_opt(1990, 3, 16).unwrap(); let current_date = NaiveDate::from_ymd_opt(2024, 3, 17).unwrap(); assert!(!DateUtils::is_birthday(birth_date, current_date)); } #[test] fn test_age() { let birth_date = NaiveDate::from_ymd_opt(1990, 3, 16).unwrap(); let current_date = NaiveDate::from_ymd_opt(2024, 3, 16).unwrap(); assert_eq!(DateUtils::age(birth_date, current_date), 34); let birth_date = NaiveDate::from_ymd_opt(1990, 3, 16).unwrap(); let current_date = NaiveDate::from_ymd_opt(2024, 3, 15).unwrap(); assert_eq!(DateUtils::age(birth_date, current_date), 34); } #[test] fn test_next_saturday() { let date = NaiveDate::from_ymd_opt(2024, 3, 12).unwrap(); // A Tuesday let next_saturday = DateUtils::next_saturday(date); assert_eq!(next_saturday, NaiveDate::from_ymd_opt(2024, 3, 16).unwrap()); let date = NaiveDate::from_ymd_opt(2024, 3, 17).unwrap(); // A Saturday let next_saturday = DateUtils::next_saturday(date); assert_eq!(next_saturday, NaiveDate::from_ymd_opt(2024, 3, 23).unwrap()); let date = NaiveDate::from_ymd_opt(2024, 3, 18).unwrap(); // A Sunday let next_saturday = DateUtils::next_saturday(date); assert_eq!(next_saturday, NaiveDate::from_ymd_opt(2024, 3, 23).unwrap()); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/estimation.rs
src/core/src/utils/estimation.rs
use std::future::Future; use std::pin::Pin; use std::time::Instant; pub struct TimeEstimation; impl TimeEstimation { pub fn estimate<T, F: FnOnce() -> T>(action: F) -> (T, u32) { let now = Instant::now(); let result = action(); (result, now.elapsed().as_millis() as u32) } pub async fn estimate_async<T, F>(action: F) -> (T, u32) where F: FnOnce() -> Pin<Box<dyn Future<Output=T> + Send>>, { let now = Instant::now(); let result = action().await; (result, now.elapsed().as_millis() as u32) } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/mod.rs
src/core/src/utils/mod.rs
mod date; mod estimation; pub mod formatting; mod logging; mod random; mod strings; pub use date::*; pub use estimation::*; pub use formatting::*; pub use logging::*; pub use random::*; pub use strings::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/strings.rs
src/core/src/utils/strings.rs
extern crate rand; use rand::*; pub struct StringUtils; impl StringUtils { #[inline] pub fn random_string(n: i32) -> String { (0..n) .map(|i| { if i == 0 { (65 + random::<u8>() % 26) as char } else { (97 + random::<u8>() % 26) as char } }) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn random_string_length_is_correct() { let random_string = StringUtils::random_string(10); assert_eq!(10, random_string.len()); } #[test] fn random_string_not_equals() { let random_string_a = StringUtils::random_string(10); let random_string_b = StringUtils::random_string(10); assert_ne!(random_string_a, random_string_b); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/logging.rs
src/core/src/utils/logging.rs
use crate::utils::TimeEstimation; use log::{debug, warn}; const MAX_DURATION_THRESHOLD_MS: u32 = 100; pub struct Logging; impl Logging { pub fn estimate<F: FnOnce()>(action: F, message: &str) { let (_, duration_ms) = TimeEstimation::estimate(action); debug!("{}, {}ms", message, duration_ms); } pub fn estimate_result<T, F: FnOnce() -> T>(action: F, message: &str) -> T { let (result, duration_ms) = TimeEstimation::estimate(action); if duration_ms > MAX_DURATION_THRESHOLD_MS { warn!("{}, {}ms", message, duration_ms); } result } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/formatting.rs
src/core/src/utils/formatting.rs
pub struct FormattingUtils; impl FormattingUtils { #[inline] pub fn format_money(amount: f64) -> String { let val = amount.abs(); if val >= 1_000_000.0 { format!("{:.1}M", amount / 1_000_000.0) } else if val >= 1_000.0 { format!("{:.1}K", amount / 1_000.0) } else if val > -1_000.0 { format!("{:.2}", amount) } else { format!("{:.0}K", amount / 1_000.0) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_format_money_millions() { assert_eq!(FormattingUtils::format_money(1_000_000.0), "1.0M"); assert_eq!(FormattingUtils::format_money(2_500_000.0), "2.5M"); assert_eq!(FormattingUtils::format_money(999_999.99), "1000.0K"); assert_eq!(FormattingUtils::format_money(-1_000_000.0), "-1.0M"); assert_eq!(FormattingUtils::format_money(-2_500_000.0), "-2.5M"); assert_eq!(FormattingUtils::format_money(-999_999.99), "-1000.0K"); } #[test] fn test_format_money_thousands() { assert_eq!(FormattingUtils::format_money(1_000.0), "1.0K"); assert_eq!(FormattingUtils::format_money(2_500.0), "2.5K"); assert_eq!(FormattingUtils::format_money(999.99), "999.99"); assert_eq!(FormattingUtils::format_money(-1_000.0), "-1.0K"); assert_eq!(FormattingUtils::format_money(-2_500.0), "-2.5K"); assert_eq!(FormattingUtils::format_money(-999.99), "-999.99"); } #[test] fn test_format_money_small() { assert_eq!(FormattingUtils::format_money(123.45), "123.45"); assert_eq!(FormattingUtils::format_money(999.0), "999.00"); assert_eq!(FormattingUtils::format_money(-123.45), "-123.45"); assert_eq!(FormattingUtils::format_money(-999.0), "-999.00"); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/random/integers.rs
src/core/src/utils/random/integers.rs
extern crate rand; use rand::*; pub struct IntegerUtils; impl IntegerUtils { #[inline] pub fn random(min: i32, max: i32) -> i32 { let random_val: f64 = random(); min + (random_val * ((max - min) as f64)) as i32 } } #[cfg(test)] mod tests { use super::*; #[test] fn random_sequential_returns_different_numbers() { let random_int_1 = IntegerUtils::random(0, 1000); let random_int_2 = IntegerUtils::random(0, 1000); assert_ne!(random_int_1, random_int_2); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/random/floats.rs
src/core/src/utils/random/floats.rs
extern crate rand; use rand::*; pub struct FloatUtils; impl FloatUtils { #[inline] pub fn random(min: f32, max: f32) -> f32 { let random_val: f32 = random(); min + (random_val * (max - min)) } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/utils/random/mod.rs
src/core/src/utils/random/mod.rs
pub mod floats; mod integers; pub use floats::*; pub use integers::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/season.rs
src/core/src/league/season.rs
#[derive(Debug)] pub enum Season { OneYear(u16), TwoYear(u16, u16), }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/result.rs
src/core/src/league/result.rs
use crate::league::{LeagueTableResult, ScheduleItem}; use crate::r#match::{GoalDetail, MatchResult, Score, TeamScore}; use crate::simulator::SimulatorData; use crate::{MatchHistoryItem, SimulationResult}; use chrono::NaiveDateTime; pub struct LeagueResult { pub league_id: u32, pub table_result: LeagueTableResult, pub match_results: Option<Vec<MatchResult>>, } impl LeagueResult { pub fn new(league_id: u32, table_result: LeagueTableResult) -> Self { LeagueResult { league_id, table_result, match_results: None, } } pub fn with_match_result( league_id: u32, table_result: LeagueTableResult, match_results: Vec<MatchResult>, ) -> Self { LeagueResult { league_id, table_result, match_results: Some(match_results), } } pub fn process(self, data: &mut SimulatorData, result: &mut SimulationResult) { if let Some(match_results) = self.match_results { for match_result in match_results { Self::process_match_results(&match_result, data); result.match_results.push(match_result); } } } fn process_match_results(result: &MatchResult, data: &mut SimulatorData) { let now = data.date; let league = data.league_mut(result.league_id).unwrap(); league.schedule.update_match_result( &result.id, &result.score, ); let home_team = data.team_mut(result.score.home_team.team_id).unwrap(); home_team.match_history.add(MatchHistoryItem::new( now, result.score.home_team.team_id, ( TeamScore::from(&result.score.home_team), TeamScore::from(&result.score.away_team), ), )); let away_team = data.team_mut(result.score.away_team.team_id).unwrap(); away_team.match_history.add(MatchHistoryItem::new( now, result.score.away_team.team_id, ( TeamScore::from(&result.score.away_team), TeamScore::from(&result.score.home_team), ), )); // process_match_events(result, data); // // fn process_match_events(result: &MatchResult, data: &mut SimulatorData) { // for match_event in &result.details.as_ref().unwrap().events { // match match_event { // MatchEvent::MatchPlayed(player_id, is_start_squad, _minutes_played) => { // let mut player = data.player_mut(*player_id).unwrap(); // // if *is_start_squad { // player.statistics.played += 1; // } else { // player.statistics.played_subs += 1; // } // } // MatchEvent::Goal(player_id) => { // let mut player = data.player_mut(*player_id).unwrap(); // player.statistics.goals += 1; // } // MatchEvent::Assist(player_id) => { // let mut player = data.player_mut(*player_id).unwrap(); // player.statistics.assists += 1; // } // MatchEvent::Injury(player_id) => {} // } // } // } } } pub struct LeagueMatch { pub id: String, pub league_id: u32, pub league_slug: String, pub date: NaiveDateTime, pub home_team_id: u32, pub away_team_id: u32, pub result: Option<LeagueMatchResultResult>, } pub struct LeagueMatchResultResult { pub home: TeamScore, pub away: TeamScore, pub details: Vec<GoalDetail>, } impl LeagueMatchResultResult { pub fn from_score(score: &Score) -> Self { LeagueMatchResultResult { home: TeamScore::from(&score.home_team), away: TeamScore::from(&score.away_team), details: score.detail().to_vec(), } } } impl From<ScheduleItem> for LeagueMatch { fn from(item: ScheduleItem) -> Self { let mut result = LeagueMatch { id: item.id.clone(), league_id: item.league_id, league_slug: item.league_slug, date: item.date, home_team_id: item.home_team_id, away_team_id: item.away_team_id, result: None, }; if let Some(res) = item.result { result.result = Some(LeagueMatchResultResult::from_score(&res)); } result } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/mod.rs
src/core/src/league/mod.rs
mod collection; mod context; mod league; pub mod result; pub mod schedule; mod season; pub mod storages; pub mod table; pub use collection::*; pub use context::*; pub use league::*; pub use result::*; pub use schedule::*; pub use season::*; pub use storages::*; pub use table::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/league.rs
src/core/src/league/league.rs
use crate::context::{GlobalContext, SimulationContext}; use crate::league::{LeagueMatch, LeagueMatchResultResult, LeagueResult, LeagueTable, MatchStorage, Schedule, ScheduleItem}; use crate::r#match::{Match, MatchResult}; use crate::utils::Logging; use crate::{Club, Team}; use chrono::{Datelike, NaiveDate}; use log::{debug, info, warn}; use rayon::iter::IntoParallelRefMutIterator; use std::collections::HashMap; #[derive(Debug)] pub struct League { pub id: u32, pub name: String, pub slug: String, pub country_id: u32, pub schedule: Schedule, pub table: LeagueTable, pub settings: LeagueSettings, pub matches: MatchStorage, pub reputation: u16, // New fields for enhanced simulation pub dynamics: LeagueDynamics, pub regulations: LeagueRegulations, pub statistics: LeagueStatistics, pub milestones: LeagueMilestones, } impl League { pub fn new( id: u32, name: String, slug: String, country_id: u32, reputation: u16, settings: LeagueSettings, ) -> Self { League { id, name, slug, country_id, schedule: Schedule::default(), table: LeagueTable::default(), matches: MatchStorage::new(), settings, reputation, dynamics: LeagueDynamics::new(), regulations: LeagueRegulations::new(), statistics: LeagueStatistics::new(), milestones: LeagueMilestones::new(), } } pub fn simulate(&mut self, clubs: &[Club], ctx: GlobalContext<'_>) -> LeagueResult { let league_name = self.name.clone(); let current_date = ctx.simulation.date.date(); info!("⚽ Simulating league: {} (Reputation: {})", league_name, self.reputation); // Phase 1: Pre-match preparations self.prepare_matchday(&ctx, clubs); // Phase 2: Table simulation let table_result = self.table.simulate(&ctx); let league_teams: Vec<u32> = clubs .iter() .flat_map(|c| c.teams.with_league(self.id)) .collect(); // Phase 3: Schedule management let mut schedule_result = self.schedule.simulate( &self.settings, ctx.with_league(self.id, String::from(&self.slug), &league_teams), ); // Phase 4: Match execution with enhanced dynamics if schedule_result.is_match_scheduled() { let match_results = self.play_scheduled_matches( &mut schedule_result.scheduled_matches, clubs, &ctx, ); self.process_match_day_results(&match_results, clubs, &ctx, current_date); return LeagueResult::with_match_result(self.id, table_result, match_results); } // Phase 5: Off-season or mid-season processing self.process_non_matchday(clubs, &ctx); LeagueResult::new(self.id, table_result) } // ========== MATCHDAY PREPARATION ========== fn prepare_matchday(&mut self, ctx: &GlobalContext<'_>, clubs: &[Club]) { debug!("Preparing matchday for {}", self.name); let current_date = ctx.simulation.date.date(); let day_of_week = current_date.weekday(); // Update attendance predictions self.dynamics.update_attendance_predictions( &self.table, day_of_week, current_date.month(), ); // Check for fixture congestion for club in clubs { for team in &club.teams.teams { if team.league_id == self.id { self.check_fixture_congestion(team, current_date); } } } // Update referee assignments (simulated) self.dynamics.assign_referees(); } fn check_fixture_congestion(&self, team: &Team, current_date: NaiveDate) { let upcoming_matches = self.schedule.get_matches_for_team_in_days(team.id, current_date, 7); if upcoming_matches.len() > 2 { debug!("⚠️ Fixture congestion for team {}: {} matches in 7 days", team.name, upcoming_matches.len()); } } // ========== MATCH EXECUTION ========== fn play_scheduled_matches( &mut self, scheduled_matches: &mut Vec<LeagueMatch>, clubs: &[Club], ctx: &GlobalContext<'_>, ) -> Vec<MatchResult> { use rayon::iter::ParallelIterator; // Play all matches in parallel let match_results: Vec<MatchResult> = scheduled_matches .par_iter_mut() .map(|scheduled_match| { Self::play_single_match_static( scheduled_match, clubs, ctx, &self.dynamics, &self.table, ) }) .collect(); // Update momentum sequentially after all matches are played for result in &match_results { self.dynamics.update_team_momentum_after_match( result.home_team_id, result.away_team_id, result, ); } match_results } fn play_single_match_static( scheduled_match: &mut LeagueMatch, clubs: &[Club], ctx: &GlobalContext<'_>, dynamics: &LeagueDynamics, table: &LeagueTable, ) -> MatchResult { let home_team = clubs .iter() .flat_map(|c| &c.teams.teams) .find(|team| team.id == scheduled_match.home_team_id) .expect("Home team not found"); let away_team = clubs .iter() .flat_map(|c| &c.teams.teams) .find(|team| team.id == scheduled_match.away_team_id) .expect("Away team not found"); // Get psychological factors let home_momentum = dynamics.get_team_momentum(scheduled_match.home_team_id); let away_momentum = dynamics.get_team_momentum(scheduled_match.away_team_id); let (home_pressure, away_pressure) = Self::calculate_match_pressures_static( home_team, away_team, ctx.simulation.date.date(), dynamics, table, ); // Prepare squads with psychological modifiers let mut home_squad = home_team.get_enhanced_match_squad(); let mut away_squad = away_team.get_enhanced_match_squad(); Self::apply_psychological_factors_static(&mut home_squad, home_momentum, home_pressure); Self::apply_psychological_factors_static(&mut away_squad, away_momentum, away_pressure); // Create and play match let match_to_play = Match::make( scheduled_match.id.clone(), scheduled_match.league_id, &scheduled_match.league_slug, home_squad, away_squad, ); let message = &format!( "play match: {} vs {} (Momentum: {:.1} vs {:.1})", &match_to_play.home_squad.team_name, &match_to_play.away_squad.team_name, home_momentum, away_momentum ); let match_result = Logging::estimate_result(|| match_to_play.play(), message); // Update match result in schedule scheduled_match.result = Some(LeagueMatchResultResult::from_score(&match_result.score)); match_result } fn get_team_momentums(&self, home_id: u32, away_id: u32) -> (f32, f32) { let home = self.dynamics.get_team_momentum(home_id); let away = self.dynamics.get_team_momentum(away_id); (home, away) } fn calculate_match_pressures( &self, home_team: &Team, away_team: &Team, current_date: NaiveDate, ) -> (f32, f32) { let home = self.calculate_match_pressure(home_team, &self.table, current_date); let away = self.calculate_match_pressure(away_team, &self.table, current_date); (home, away) } fn calculate_match_pressure( &self, team: &Team, table: &LeagueTable, _current_date: NaiveDate, ) -> f32 { let position = table.rows.iter().position(|r| r.team_id == team.id).unwrap_or(0); let total_teams = table.rows.len(); let matches_remaining = self.calculate_matches_remaining(team.id); let mut pressure: f32 = 0.5; // Base pressure // Title race pressure if position < 3 && matches_remaining < 10 { pressure += 0.3; } // Relegation battle pressure if position >= total_teams - 3 && matches_remaining < 10 { pressure += 0.4; } // Manager under pressure let losing_streak = self.dynamics.get_team_losing_streak(team.id); if losing_streak > 3 { pressure += 0.2; } pressure.min(1.0) } fn apply_psychological_factors( &self, squad: &mut crate::r#match::MatchSquad, momentum: f32, pressure: f32, ) { debug!("Team {} - Momentum: {:.2}, Pressure: {:.2}", squad.team_name, momentum, pressure); } fn apply_psychological_factors_static( squad: &mut crate::r#match::MatchSquad, momentum: f32, pressure: f32, ) { debug!("Team {} - Momentum: {:.2}, Pressure: {:.2}", squad.team_name, momentum, pressure); } fn calculate_match_pressures_static( home_team: &Team, away_team: &Team, current_date: NaiveDate, dynamics: &LeagueDynamics, table: &LeagueTable, ) -> (f32, f32) { let home = Self::calculate_match_pressure_static(home_team, table, current_date, dynamics); let away = Self::calculate_match_pressure_static(away_team, table, current_date, dynamics); (home, away) } fn calculate_match_pressure_static( team: &Team, table: &LeagueTable, _current_date: NaiveDate, dynamics: &LeagueDynamics, ) -> f32 { let position = table.rows.iter().position(|r| r.team_id == team.id).unwrap_or(0); let total_teams = table.rows.len(); let mut pressure: f32 = 0.5; // Base pressure // Title race pressure if position < 3 { pressure += 0.3; } // Relegation battle pressure if position >= total_teams - 3 { pressure += 0.4; } // Manager under pressure let losing_streak = dynamics.get_team_losing_streak(team.id); if losing_streak > 3 { pressure += 0.2; } pressure.min(1.0) } fn calculate_matches_remaining(&self, team_id: u32) -> usize { self.schedule.tours.iter() .flat_map(|t| &t.items) .filter(|item| item.result.is_none() && (item.home_team_id == team_id || item.away_team_id == team_id)) .count() } // ========== POST-MATCH PROCESSING ========== fn process_match_day_results( &mut self, match_results: &[MatchResult], clubs: &[Club], ctx: &GlobalContext<'_>, current_date: NaiveDate, ) { // Update match results and statistics self.process_match_results(match_results, clubs, ctx); // Update table standings self.table.update_from_results(match_results); // Store match results match_results.iter().for_each(|mr| { self.matches.push(mr.copy_without_data_positions()); }); // Update league dynamics self.update_league_dynamics(match_results, clubs, current_date); // Check for milestones self.check_milestones_and_events(clubs, current_date); // Apply regulatory actions self.apply_regulatory_actions(clubs, ctx); } fn process_match_results( &mut self, results: &[MatchResult], clubs: &[Club], ctx: &GlobalContext<'_>, ) { for result in results { // Update statistics self.statistics.process_match_result(result); // Process disciplinary actions self.regulations.process_disciplinary_actions(result); // Update team streaks self.dynamics.update_team_streaks( result.score.home_team.team_id, result.score.away_team.team_id, &result.score, ); // Check manager pressure self.check_manager_pressure(result, clubs, ctx.simulation.date.date()); } // Update player rankings self.statistics.update_player_rankings(clubs); } fn check_manager_pressure( &self, result: &MatchResult, _clubs: &[Club], _current_date: NaiveDate, ) { // Check home team let home_losing_streak = self.dynamics.get_team_losing_streak(result.score.home_team.team_id); if home_losing_streak > 5 { warn!("🔴 Manager under severe pressure at team {}", result.score.home_team.team_id); } // Check away team let away_losing_streak = self.dynamics.get_team_losing_streak(result.score.away_team.team_id); if away_losing_streak > 5 { warn!("🔴 Manager under severe pressure at team {}", result.score.away_team.team_id); } } // ========== LEAGUE DYNAMICS ========== fn update_league_dynamics( &mut self, _results: &[MatchResult], clubs: &[Club], _current_date: NaiveDate, ) { let total_teams = self.table.rows.len(); let matches_played = self.table.rows.first().map(|r| r.played).unwrap_or(0); let total_matches = (total_teams - 1) * 2; let season_progress = matches_played as f32 / total_matches as f32; // Update title race dynamics if season_progress > 0.6 { self.dynamics.update_title_race(&self.table); } // Update relegation battle if season_progress > 0.5 { self.dynamics.update_relegation_battle(&self.table, total_teams); } // Update European qualification race if season_progress > 0.7 { self.dynamics.update_european_race(&self.table); } // Calculate competitive balance self.statistics.update_competitive_balance(&self.table); // Update league reputation self.update_league_reputation(clubs, season_progress); } fn update_league_reputation(&mut self, _clubs: &[Club], season_progress: f32) { if season_progress < 0.1 { return; // Too early in season } let competitive_balance = self.statistics.competitive_balance_index; let avg_goals_per_game = self.statistics.total_goals as f32 / self.statistics.total_matches.max(1) as f32; let mut reputation_change: i16 = 0; if competitive_balance > 0.7 { reputation_change += 2; // High competition } if avg_goals_per_game > 2.8 { reputation_change += 1; // Entertaining matches } self.reputation = (self.reputation as i16 + reputation_change).clamp(0, 1000) as u16; } // ========== MILESTONES & EVENTS ========== fn check_milestones_and_events(&mut self, _clubs: &[Club], current_date: NaiveDate) { // Check for record-breaking performances self.milestones.check_records(&self.statistics, &self.table); // Check for special derbies or rivalry matches let upcoming_matches = self.schedule.get_matches_in_next_days(current_date, 7); for match_item in upcoming_matches { if self.dynamics.is_derby(match_item.home_team_id, match_item.away_team_id) { info!("🔥 Derby coming up: Team {} vs Team {}", match_item.home_team_id, match_item.away_team_id); } } // Season milestones let matches_played = self.table.rows.first().map(|r| r.played).unwrap_or(0); self.milestones.check_season_milestones(matches_played, &self.table); } // ========== REGULATORY ACTIONS ========== fn apply_regulatory_actions(&mut self, clubs: &[Club], ctx: &GlobalContext<'_>) { // Check Financial Fair Play violations for club in clubs { if self.regulations.check_ffp_violation(club) { warn!("⚠️ FFP violation detected for club: {}", club.name); self.regulations.apply_ffp_sanctions(club.id, &mut self.table); } } // Process pending disciplinary cases self.regulations.process_pending_cases(ctx.simulation.date.date()); } // ========== NON-MATCHDAY PROCESSING ========== fn process_non_matchday(&mut self, clubs: &[Club], ctx: &GlobalContext<'_>) { let current_date = ctx.simulation.date.date(); // End of season processing if self.is_season_end(current_date) { self.process_season_end(clubs); } // Mid-season break if self.is_winter_break(current_date) { self.process_winter_break(clubs); } // International break if self.is_international_break(current_date) { debug!("International break - no league matches"); } } fn is_season_end(&self, date: NaiveDate) -> bool { date.month() == 5 && date.day() >= 25 } fn is_winter_break(&self, date: NaiveDate) -> bool { date.month() == 12 && date.day() >= 20 && date.day() <= 31 } fn is_international_break(&self, date: NaiveDate) -> bool { (date.month() == 9 && date.day() >= 4 && date.day() <= 12) || (date.month() == 10 && date.day() >= 9 && date.day() <= 17) || (date.month() == 11 && date.day() >= 13 && date.day() <= 21) || (date.month() == 3 && date.day() >= 20 && date.day() <= 28) } fn process_season_end(&mut self, _clubs: &[Club]) { info!("🏆 Season ended for league: {}", self.name); let champion_id = self.table.rows.first().map(|r| r.team_id); if let Some(champion) = champion_id { info!("🥇 Champions: Team {}", champion); self.milestones.record_champion(champion); } self.dynamics.reset_for_new_season(); self.statistics.archive_season_stats(); } fn process_winter_break(&mut self, _clubs: &[Club]) { debug!("❄️ Winter break for league: {}", self.name); } // ========== UTILITY METHODS ========== fn get_team<'c>(&self, clubs: &'c [Club], id: u32) -> &'c Team { clubs .iter() .flat_map(|c| &c.teams.teams) .find(|team| team.id == id) .unwrap() } } // Supporting structures for enhanced simulation #[derive(Debug)] pub struct LeagueDynamics { pub team_momentum: HashMap<u32, f32>, pub team_streaks: HashMap<u32, TeamStreak>, pub title_race: TitleRace, pub relegation_battle: RelegationBattle, pub european_race: EuropeanRace, pub rivalries: Vec<(u32, u32)>, pub attendance_multiplier: f32, } impl LeagueDynamics { pub fn new() -> Self { LeagueDynamics { team_momentum: HashMap::new(), team_streaks: HashMap::new(), title_race: TitleRace::default(), relegation_battle: RelegationBattle::default(), european_race: EuropeanRace::default(), rivalries: Vec::new(), attendance_multiplier: 1.0, } } pub fn get_team_momentum(&self, team_id: u32) -> f32 { *self.team_momentum.get(&team_id).unwrap_or(&0.5) } pub fn update_team_momentum_after_match( &mut self, home_id: u32, away_id: u32, result: &MatchResult, ) { let home_won = result.score.home_team.get() > result.score.away_team.get(); let draw = result.score.home_team.get() == result.score.away_team.get(); // Read current values (or defaults) let home_val = *self.team_momentum.entry(home_id).or_insert(0.5); let away_val = *self.team_momentum.entry(away_id).or_insert(0.5); // Compute new values let (new_home, new_away) = if home_won { ( (home_val * 0.8 + 0.3).min(1.0), (away_val * 0.8 - 0.1).max(0.0), ) } else if draw { ( (home_val * 0.9 + 0.05).min(1.0), (away_val * 0.9 + 0.05).min(1.0), ) } else { ( (home_val * 0.8 - 0.1).max(0.0), (away_val * 0.8 + 0.3).min(1.0), ) }; // Write back self.team_momentum.insert(home_id, new_home); self.team_momentum.insert(away_id, new_away); } pub fn update_team_streaks(&mut self, home_id: u32, away_id: u32, score: &crate::r#match::Score) { let home_won = score.home_team.get() > score.away_team.get(); let draw = score.home_team.get() == score.away_team.get(); // Update home team streak let home_streak = self.team_streaks.entry(home_id).or_insert(TeamStreak::default()); if home_won { home_streak.winning_streak += 1; home_streak.unbeaten_streak += 1; home_streak.losing_streak = 0; } else if draw { home_streak.unbeaten_streak += 1; home_streak.winning_streak = 0; home_streak.losing_streak = 0; } else { home_streak.losing_streak += 1; home_streak.winning_streak = 0; home_streak.unbeaten_streak = 0; } // Update away team streak let away_streak = self.team_streaks.entry(away_id).or_insert(TeamStreak::default()); if !home_won && !draw { away_streak.winning_streak += 1; away_streak.unbeaten_streak += 1; away_streak.losing_streak = 0; } else if draw { away_streak.unbeaten_streak += 1; away_streak.winning_streak = 0; away_streak.losing_streak = 0; } else { away_streak.losing_streak += 1; away_streak.winning_streak = 0; away_streak.unbeaten_streak = 0; } } pub fn get_team_losing_streak(&self, team_id: u32) -> u8 { self.team_streaks.get(&team_id).map(|s| s.losing_streak).unwrap_or(0) } pub fn update_title_race(&mut self, table: &LeagueTable) { if table.rows.len() < 2 { return; } let leader_points = table.rows[0].points; let second_points = table.rows[1].points; self.title_race.leader_id = table.rows[0].team_id; self.title_race.gap_to_second = (leader_points - second_points) as i8; self.title_race.contenders = table.rows.iter() .take(5) .filter(|r| (leader_points - r.points) <= 9) .map(|r| r.team_id) .collect(); } pub fn update_relegation_battle(&mut self, table: &LeagueTable, total_teams: usize) { if total_teams < 4 { return; } let relegation_zone_start = total_teams - 3; self.relegation_battle.teams_in_danger = table.rows.iter() .skip(relegation_zone_start - 2) .map(|r| r.team_id) .collect(); } pub fn update_european_race(&mut self, table: &LeagueTable) { // Top 4-6 teams typically qualify for European competitions self.european_race.teams_in_contention = table.rows.iter() .take(8) .map(|r| r.team_id) .collect(); } pub fn is_derby(&self, team1: u32, team2: u32) -> bool { self.rivalries.iter().any(|(a, b)| (*a == team1 && *b == team2) || (*a == team2 && *b == team1) ) } pub fn update_attendance_predictions( &mut self, table: &LeagueTable, day_of_week: chrono::Weekday, month: u32, ) { self.attendance_multiplier = 1.0; // Weekend matches have higher attendance if day_of_week == chrono::Weekday::Sat || day_of_week == chrono::Weekday::Sun { self.attendance_multiplier *= 1.2; } // Summer months lower attendance if month >= 6 && month <= 8 { self.attendance_multiplier *= 0.9; } // End of season crucial matches if table.rows.first().map(|r| r.played).unwrap_or(0) > 30 { self.attendance_multiplier *= 1.3; } } pub fn assign_referees(&mut self) { // Simulated referee assignment debug!("Referees assigned for upcoming matches"); } pub fn reset_for_new_season(&mut self) { self.team_momentum.clear(); self.team_streaks.clear(); self.title_race = TitleRace::default(); self.relegation_battle = RelegationBattle::default(); self.european_race = EuropeanRace::default(); } } #[derive(Debug, Default)] pub struct TeamStreak { pub winning_streak: u8, pub losing_streak: u8, pub unbeaten_streak: u8, } #[derive(Debug, Default)] pub struct TitleRace { pub leader_id: u32, pub gap_to_second: i8, pub contenders: Vec<u32>, } #[derive(Debug, Default)] pub struct RelegationBattle { pub teams_in_danger: Vec<u32>, } #[derive(Debug, Default)] pub struct EuropeanRace { pub teams_in_contention: Vec<u32>, } #[derive(Debug)] pub struct LeagueRegulations { pub suspended_players: HashMap<u32, u8>, // player_id -> matches remaining pub yellow_card_accumulation: HashMap<u32, u8>, // player_id -> yellow cards pub ffp_violations: Vec<FFPViolation>, pub pending_cases: Vec<DisciplinaryCase>, } impl LeagueRegulations { pub fn new() -> Self { LeagueRegulations { suspended_players: HashMap::new(), yellow_card_accumulation: HashMap::new(), ffp_violations: Vec::new(), pending_cases: Vec::new(), } } pub fn process_disciplinary_actions(&mut self, _result: &MatchResult) { // Process cards and suspensions from match // This would need match details with card information } pub fn check_ffp_violation(&self, club: &Club) -> bool { // Check if club violates Financial Fair Play let deficit = club.finance.balance.outcome - club.finance.balance.income; deficit > 30_000_000 // Simplified FFP check } pub fn apply_ffp_sanctions(&mut self, club_id: u32, table: &mut LeagueTable) { self.ffp_violations.push(FFPViolation { club_id, violation_type: FFPViolationType::ExcessiveDeficit, sanction: FFPSanction::PointDeduction(6), }); // Apply point deduction if let Some(row) = table.rows.iter_mut().find(|r| r.team_id == club_id) { row.points = row.points.saturating_sub(6); } } pub fn process_pending_cases(&mut self, current_date: NaiveDate) { self.pending_cases.retain(|case| case.hearing_date > current_date); } } #[derive(Debug)] pub struct FFPViolation { pub club_id: u32, pub violation_type: FFPViolationType, pub sanction: FFPSanction, } #[derive(Debug)] pub enum FFPViolationType { ExcessiveDeficit, UnpaidDebts, FalseAccounting, } #[derive(Debug)] pub enum FFPSanction { Warning, Fine(u32), PointDeduction(u8), TransferBan, } #[derive(Debug)] pub struct DisciplinaryCase { pub player_id: u32, pub incident_type: String, pub hearing_date: NaiveDate, } #[derive(Debug)] pub struct LeagueStatistics { pub total_goals: u32, pub total_matches: u32, pub top_scorer: Option<(u32, u16)>, // player_id, goals pub top_assists: Option<(u32, u16)>, // player_id, assists pub clean_sheets: HashMap<u32, u16>, // goalkeeper_id, clean sheets pub competitive_balance_index: f32, pub average_attendance: u32, pub highest_scoring_match: Option<(u32, u32, u8, u8)>, // home_id, away_id, home_score, away_score pub biggest_win: Option<(u32, u32, u8)>, // winner_id, loser_id, goal_difference pub longest_unbeaten_run: Option<(u32, u8)>, // team_id, matches } impl LeagueStatistics { pub fn new() -> Self { LeagueStatistics { total_goals: 0, total_matches: 0, top_scorer: None, top_assists: None, clean_sheets: HashMap::new(), competitive_balance_index: 1.0, average_attendance: 0, highest_scoring_match: None, biggest_win: None, longest_unbeaten_run: None, } } pub fn process_match_result(&mut self, result: &MatchResult) { let home_goals = result.score.home_team.get(); let away_goals = result.score.away_team.get(); self.total_goals += (home_goals + away_goals) as u32; self.total_matches += 1; // Update highest scoring match let total_in_match = home_goals + away_goals; if let Some((_, _, _, current_high)) = self.highest_scoring_match { if total_in_match > current_high { self.highest_scoring_match = Some(( result.score.home_team.team_id, result.score.away_team.team_id, home_goals, away_goals )); } } else { self.highest_scoring_match = Some(( result.score.home_team.team_id, result.score.away_team.team_id, home_goals, away_goals )); } // Update biggest win let goal_diff = (home_goals as i8 - away_goals as i8).abs() as u8; if goal_diff > 0 { if let Some((_, _, current_biggest)) = self.biggest_win { if goal_diff > current_biggest { let (winner, loser) = if home_goals > away_goals { (result.score.home_team.team_id, result.score.away_team.team_id) } else { (result.score.away_team.team_id, result.score.home_team.team_id) }; self.biggest_win = Some((winner, loser, goal_diff)); } } else { let (winner, loser) = if home_goals > away_goals { (result.score.home_team.team_id, result.score.away_team.team_id) } else { (result.score.away_team.team_id, result.score.home_team.team_id) }; self.biggest_win = Some((winner, loser, goal_diff)); } } } pub fn update_player_rankings(&mut self, clubs: &[Club]) { let mut scorer_stats: HashMap<u32, u16> = HashMap::new(); let mut assist_stats: HashMap<u32, u16> = HashMap::new(); // Collect all player statistics for club in clubs { for team in &club.teams.teams { for player in &team.players.players { if player.statistics.goals > 0 { scorer_stats.insert(player.id, player.statistics.goals); } if player.statistics.assists > 0 { assist_stats.insert(player.id, player.statistics.assists); } // Track clean sheets for goalkeepers if player.positions.is_goalkeeper() && player.statistics.played > 0 { // Simplified clean sheet tracking self.clean_sheets.insert(player.id, 0); } } } } // Find top scorer self.top_scorer = scorer_stats.iter() .max_by_key(|(_, goals)| *goals) .map(|(id, goals)| (*id, *goals)); // Find top assists self.top_assists = assist_stats.iter() .max_by_key(|(_, assists)| *assists) .map(|(id, assists)| (*id, *assists)); } pub fn update_competitive_balance(&mut self, table: &LeagueTable) { if table.rows.len() < 2 { self.competitive_balance_index = 1.0; return; } // Calculate standard deviation of points let mean_points = table.rows.iter().map(|r| r.points as f32).sum::<f32>() / table.rows.len() as f32; let variance = table.rows.iter() .map(|r| { let diff = r.points as f32 - mean_points; diff * diff }) .sum::<f32>() / table.rows.len() as f32;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
true
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/context.rs
src/core/src/league/context.rs
#[derive(Clone)] pub struct LeagueContext<'l> { pub id: u32, pub slug: String, pub team_ids: &'l [u32], } impl<'l> LeagueContext<'l> { pub fn new(id: u32, slug: String, team_ids: &'l [u32]) -> Self { LeagueContext { id, slug, team_ids } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/collection.rs
src/core/src/league/collection.rs
use crate::context::GlobalContext; use crate::league::{League, LeagueResult}; use crate::{Club, Logging}; use rayon::iter::IntoParallelRefMutIterator; use rayon::iter::ParallelIterator; pub struct LeagueCollection { pub leagues: Vec<League>, } impl LeagueCollection { pub fn new(leagues: Vec<League>) -> Self { LeagueCollection { leagues } } pub fn simulate(&mut self, clubs: &[Club], ctx: &GlobalContext<'_>) -> Vec<LeagueResult> { let teams_ids: Vec<(u32, u32)> = clubs .iter() .flat_map(|c| &c.teams.teams) .map(|c| (c.id, c.league_id)) .collect(); self.leagues .par_iter_mut() .map(|league| { let league_team_ids: Vec<u32> = teams_ids .iter() .filter(|(_, league_id)| *league_id == league.id) .map(|(id, _)| *id) .collect(); { let message = &format!("simulate league: {}", &league.name); let league_slug = String::from(&league.slug); Logging::estimate_result( || { league.simulate( clubs, ctx.with_league(league.id, league_slug, &league_team_ids), ) }, message, ) } }) .collect() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/schedule/schedule.rs
src/core/src/league/schedule/schedule.rs
use crate::context::GlobalContext; use crate::league::round::RoundSchedule; use crate::league::{LeagueMatch, LeagueSettings, ScheduleGenerator, ScheduleResult, Season}; use crate::r#match::Score; use chrono::{Datelike, NaiveDate, NaiveDateTime}; use log::error; #[derive(Debug, Default)] pub struct Schedule { pub tours: Vec<ScheduleTour>, } #[derive(Debug, Clone)] pub struct ScheduleTour { pub num: u8, pub items: Vec<ScheduleItem>, } #[derive(Debug, Clone)] pub struct ScheduleItem { pub id: String, pub league_id: u32, pub league_slug: String, pub date: NaiveDateTime, pub home_team_id: u32, pub away_team_id: u32, pub result: Option<Score>, } impl Schedule { pub fn new() -> Self { Schedule { tours: Vec::new() } } pub fn simulate( &mut self, league_settings: &LeagueSettings, ctx: GlobalContext<'_>, ) -> ScheduleResult { let mut result = ScheduleResult::new(); if self.tours.is_empty() || league_settings.is_time_for_new_schedule(&ctx.simulation) { let league_ctx = ctx.league.as_ref().unwrap(); let generator = RoundSchedule::new(); match generator.generate( league_ctx.id, &league_ctx.slug, Season::OneYear(ctx.simulation.date.year() as u16), league_ctx.team_ids, league_settings, ) { Ok(generated_schedule) => { self.tours = generated_schedule; result.generated = true; } Err(error) => { error!("Generating schedule error: {}", error.message); } } } result.scheduled_matches = self .get_matches(ctx.simulation.date) .iter() .map(|sm| LeagueMatch { id: sm.id.clone(), league_id: sm.league_id, league_slug: String::from(&sm.league_slug), date: sm.date, home_team_id: sm.home_team_id, away_team_id: sm.away_team_id, result: None, }) .collect(); result } pub fn get_matches(&self, date: NaiveDateTime) -> Vec<ScheduleItem> { self.tours .iter() .flat_map(|t| &t.items) .filter(|s| s.date == date) .map(|s| { ScheduleItem::new( s.league_id, String::from(&s.league_slug), s.home_team_id, s.away_team_id, s.date, None, ) }) .collect() } pub fn get_matches_for_team(&self, team_id: u32) -> Vec<ScheduleItem> { self.tours .iter() .flat_map(|t| &t.items) .filter(|s| s.home_team_id == team_id || s.away_team_id == team_id) .map(|s| { ScheduleItem::new( s.league_id, String::from(&s.league_slug), s.home_team_id, s.away_team_id, s.date, s.result.clone(), ) }) .collect() } pub fn update_match_result(&mut self, id: &str, score: &Score) { let mut _updated = false; for tour in &mut self.tours.iter_mut().filter(|t| !t.played()) { if let Some(item) = tour.items.iter_mut().find(|i| i.id == id) { item.result = Some(score.clone()); _updated = true; } } } } #[derive(Debug, Clone)] pub struct ScheduleError { pub message: String, } impl ScheduleError { pub fn from_str(str: &'static str) -> Self { ScheduleError { message: str.to_owned(), } } } impl ScheduleItem { pub fn new( league_id: u32, league_slug: String, home_team_id: u32, away_team_id: u32, date: NaiveDateTime, result: Option<Score>, ) -> Self { let id = format!("{}_{}_{}", date.date(), home_team_id, away_team_id); ScheduleItem { id, league_id, league_slug: String::from(league_slug), date, result, home_team_id, away_team_id, } } } impl ScheduleTour { pub fn new(num: u8, games_count: usize) -> Self { ScheduleTour { num, items: Vec::with_capacity(games_count), } } pub fn played(&self) -> bool { self.items.iter().all(|i| i.result.is_some()) } pub fn start_date(&self) -> NaiveDate { self.items .iter() .min_by_key(|t| t.date) .unwrap() .date .date() } pub fn end_date(&self) -> NaiveDate { self.items .iter() .max_by_key(|t| t.date) .unwrap() .date .date() } } #[cfg(test)] mod tests { use super::*; use crate::r#match::TeamScore; use chrono::NaiveDate; #[test] fn test_schedule_tour_new() { let schedule_tour = ScheduleTour::new(1, 5); assert_eq!(schedule_tour.num, 1); assert_eq!(schedule_tour.items.capacity(), 5); } #[test] fn test_schedule_tour_played() { let item1 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 15) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let item2 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 16) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let mut items_with_results = Vec::new(); items_with_results.push(item1.clone()); items_with_results.push(item2.clone()); let schedule_tour_with_results = ScheduleTour { num: 1, items: items_with_results, }; assert!(schedule_tour_with_results.played()); let item3 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 17) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: None, }; let mut items_without_results = Vec::new(); items_without_results.push(item1); items_without_results.push(item3); let schedule_tour_without_results = ScheduleTour { num: 1, items: items_without_results, }; assert!(!schedule_tour_without_results.played()); } #[test] fn test_schedule_tour_start_date() { let item1 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 15) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let item2 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 16) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let schedule_tour = ScheduleTour { num: 1, items: vec![item1.clone(), item2.clone()], }; assert_eq!(schedule_tour.start_date(), item1.date.date()); } #[test] fn test_schedule_tour_end_date() { let item1 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd_opt(2024, 3, 15) .unwrap() .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let item2 = ScheduleItem { id: "".to_string(), league_id: 0, league_slug: "slug".to_string(), date: NaiveDate::from_ymd(2024, 3, 16) .and_hms_opt(0, 0, 0) .unwrap(), home_team_id: 0, away_team_id: 0, result: Some(Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: Vec::new(), }), }; let schedule_tour = ScheduleTour { num: 1, items: vec![item1.clone(), item2.clone()], }; assert_eq!(schedule_tour.end_date(), item2.date.date()); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/schedule/result.rs
src/core/src/league/schedule/result.rs
use crate::league::LeagueMatch; pub struct ScheduleResult { pub generated: bool, pub scheduled_matches: Vec<LeagueMatch>, } impl ScheduleResult { pub fn new() -> Self { ScheduleResult { generated: false, scheduled_matches: Vec::new(), } } pub fn is_match_scheduled(&self) -> bool { !self.scheduled_matches.is_empty() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/schedule/round.rs
src/core/src/league/schedule/round.rs
use crate::league::{ LeagueSettings, ScheduleError, ScheduleGenerator, ScheduleItem, ScheduleTour, Season, }; use crate::utils::DateUtils; use chrono::prelude::*; use chrono::Duration; use chrono::NaiveDate; use log::warn; // const DAY_PLAYING_TIMES: [(u8, u8); 4] = [(13, 0), (14, 0), (16, 0), (18, 0)]; pub struct RoundSchedule; impl Default for RoundSchedule { fn default() -> Self { Self::new() } } impl RoundSchedule { pub fn new() -> Self { RoundSchedule {} } } impl ScheduleGenerator for RoundSchedule { fn generate( &self, league_id: u32, league_slug: &str, season: Season, teams: &[u32], league_settings: &LeagueSettings, ) -> Result<Vec<ScheduleTour>, ScheduleError> { let teams_len = teams.len(); if teams_len == 0 { warn!("schedule: team_len is empty. skip generation"); ScheduleError::from_str("team_len is empty"); } let (season_year_start, _season_year_end) = match season { Season::OneYear(year) => (year, year), Season::TwoYear(start_year, end_year) => (start_year, end_year), }; let current_date = DateUtils::next_saturday( NaiveDate::from_ymd_opt( season_year_start as i32, league_settings.season_starting_half.from_month as u32, league_settings.season_starting_half.from_day as u32, ) .unwrap(), ); let current_date_time = NaiveDateTime::new(current_date, NaiveTime::from_hms_opt(0, 0, 0).unwrap()); let tours_count = (teams_len * teams_len - teams_len) / (teams_len / 2); let mut result = Vec::with_capacity(tours_count); result.extend(generate_tours( league_id, String::from(league_slug), teams, tours_count, current_date_time, )); Ok(result) } } fn generate_tours( league_id: u32, league_slug: String, teams: &[u32], tours_count: usize, mut current_date: NaiveDateTime, ) -> Vec<ScheduleTour> { let team_len = teams.len() as u32; let games_count = (team_len / 2) as usize; let mut result = Vec::with_capacity(tours_count); let mut games_offset = 0; let games = generate_game_pairs(&teams, tours_count); for tour in 0..tours_count { let mut tour = ScheduleTour::new((tour + 1) as u8, games_count); for game_idx in 0..games_count { let (home_team_id, away_team_id) = games[games_offset + game_idx as usize]; tour.items.push(ScheduleItem::new( league_id, String::from(&league_slug), home_team_id, away_team_id, current_date, None, )); } games_offset += games_count; current_date += Duration::days(7); result.push(tour); } result } fn generate_game_pairs(teams: &[u32], tours_count: usize) -> Vec<(u32, u32)> { let mut result = Vec::with_capacity(tours_count); let team_len = teams.len() as u32; let team_len_half = team_len / 2u32; let mut temp_vec = Vec::with_capacity((team_len_half + 1) as usize); for team in 0..team_len_half { temp_vec.push((teams[team as usize], teams[(team_len - team - 1) as usize])) } for team in &temp_vec { result.push((team.0, team.1)); } for _ in 0..tours_count { rotate(&mut temp_vec); for team in &temp_vec { result.push((team.0, team.1)); } } result } fn rotate(clubs: &mut [(u32, u32)]) { let teams_len = clubs.len(); let right_top = clubs[0].1; let left_bottom = clubs[teams_len - 1].0; for i in 0..teams_len - 1 { clubs[i].1 = clubs[i + 1].1; clubs[teams_len - i - 1].0 = clubs[teams_len - i - 2].0; } clubs[0].0 = right_top; clubs[teams_len - 1].1 = left_bottom; } #[cfg(test)] mod tests { use super::*; use crate::league::DayMonthPeriod; #[test] fn generate_schedule_is_correct() { let schedule = RoundSchedule::new(); const LEAGUE_ID: u32 = 1; let teams = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let league_settings = LeagueSettings { season_starting_half: DayMonthPeriod::new(1, 1, 30, 6), season_ending_half: DayMonthPeriod::new(1, 7, 1, 12), }; let schedule_tours = schedule .generate( LEAGUE_ID, "slug", Season::TwoYear(2020, 2021), &teams, &league_settings, ) .unwrap(); assert_eq!(30, schedule_tours.len()); for tour in &schedule_tours { for team_id in &teams { let home_team_id = tour .items .iter() .map(|t| t.home_team_id) .filter(|t| *t == *team_id) .count(); assert!( home_team_id < 2, "multiple home_team {} in tour {}", team_id, tour.num ); let away_team_id = tour .items .iter() .map(|t| t.away_team_id) .filter(|t| *t == *team_id) .count(); assert!( away_team_id < 2, "multiple away_team {} in tour {}", team_id, tour.num ); } } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/schedule/mod.rs
src/core/src/league/schedule/mod.rs
pub mod result; pub mod round; pub mod schedule; use crate::league::{LeagueSettings, Season}; pub use result::*; pub use schedule::*; pub trait ScheduleGenerator { fn generate( &self, league_id: u32, league_slug: &str, season: Season, teams: &[u32], league_settings: &LeagueSettings, ) -> Result<Vec<ScheduleTour>, ScheduleError>; }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/storages/match_storage.rs
src/core/src/league/storages/match_storage.rs
use crate::r#match::MatchResult; use std::collections::HashMap; #[derive(Debug)] pub struct MatchStorage { results: HashMap<String, MatchResult>, } impl Default for MatchStorage { fn default() -> Self { Self::new() } } impl MatchStorage { pub fn new() -> Self { MatchStorage { results: HashMap::new(), } } pub fn push(&mut self, match_result: MatchResult) { self.results.insert(match_result.id.clone(), match_result); } pub fn get<M>(&self, match_id: M) -> Option<&MatchResult> where M: AsRef<str>, { self.results.get(match_id.as_ref()) } } #[cfg(test)] mod tests { use super::*; use crate::r#match::{MatchResult, Score, TeamScore}; #[test] fn test_match_storage_new() { let match_storage = MatchStorage::new(); assert!(match_storage.results.is_empty()); } #[test] fn test_match_storage_push() { let mut match_storage = MatchStorage::new(); let match_result = MatchResult { id: "match_1".to_string(), league_slug: "slug".to_string(), // Fill in other fields as needed league_id: 0, details: None, score: Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: vec![], }, home_team_id: 0, away_team_id: 0, }; match_storage.push(match_result.clone()); assert_eq!(match_storage.results.len(), 1); assert_eq!( match_storage.results.get(&match_result.id), Some(&match_result) ); } #[test] fn test_match_storage_get() { let mut match_storage = MatchStorage::new(); let match_result = MatchResult { id: "match_1".to_string(), league_slug: "slug".to_string(), league_id: 0, details: None, score: Score { home_team: TeamScore::new_with_score(0, 0), away_team: TeamScore::new_with_score(0, 0), details: vec![], }, home_team_id: 0, away_team_id: 0, }; match_storage.push(match_result.clone()); assert_eq!( match_storage.get("match_1".to_string()), Some(&match_result) ); assert_eq!(match_storage.get("nonexistent_id".to_string()), None); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/storages/mod.rs
src/core/src/league/storages/mod.rs
pub mod match_storage; pub use match_storage::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/table/table.rs
src/core/src/league/table/table.rs
use crate::context::GlobalContext; use crate::league::LeagueTableResult; use crate::r#match::MatchResult; use std::cmp::Ordering; #[derive(Debug)] pub struct LeagueTable { pub rows: Vec<LeagueTableRow>, } impl LeagueTable { pub fn new(teams: &[u32]) -> Self { LeagueTable { rows: Self::generate_for_teams(teams), } } pub fn simulate(&mut self, ctx: &GlobalContext<'_>) -> LeagueTableResult { if self.rows.is_empty() { let league_ctx = ctx.league.as_ref().unwrap(); self.rows = Self::generate_for_teams(league_ctx.team_ids); } LeagueTableResult {} } fn generate_for_teams(teams: &[u32]) -> Vec<LeagueTableRow> { let mut rows = Vec::with_capacity(teams.len()); for team_id in teams { let table_row = LeagueTableRow { team_id: *team_id, played: 0, win: 0, draft: 0, lost: 0, goal_scored: 0, goal_concerned: 0, points: 0, }; rows.push(table_row) } rows } #[inline] fn get_team_mut(&mut self, team_id: u32) -> &mut LeagueTableRow { self.rows.iter_mut().find(|c| c.team_id == team_id).unwrap() } fn winner(&mut self, team_id: u32, goal_scored: u8, goal_concerned: u8) { let team = self.get_team_mut(team_id); team.played += 1; team.win += 1; team.goal_scored += goal_scored as i32; team.goal_concerned += goal_concerned as i32; team.points += 3; } fn looser(&mut self, team_id: u32, goal_scored: u8, goal_concerned: u8) { let team = self.get_team_mut(team_id); team.played += 1; team.lost += 1; team.goal_scored += goal_scored as i32; team.goal_concerned += goal_concerned as i32; } fn draft(&mut self, team_id: u32, goal_scored: u8, goal_concerned: u8) { let team = self.get_team_mut(team_id); team.played += 1; team.draft += 1; team.goal_scored += goal_scored as i32; team.goal_concerned += goal_concerned as i32; team.points += 1; } pub fn update_from_results(&mut self, match_result: &[MatchResult]) { for result in match_result { match Ord::cmp(&result.score.home_team.get(), &result.score.away_team.get()) { Ordering::Equal => { self.draft( result.score.home_team.team_id, result.score.home_team.get(), result.score.away_team.get(), ); self.draft( result.score.away_team.team_id, result.score.away_team.get(), result.score.home_team.get(), ); } Ordering::Greater => { self.winner( result.score.home_team.team_id, result.score.home_team.get(), result.score.away_team.get(), ); self.looser( result.score.away_team.team_id, result.score.away_team.get(), result.score.home_team.get(), ); } Ordering::Less => { self.looser( result.score.home_team.team_id, result.score.home_team.get(), result.score.away_team.get(), ); self.winner( result.score.away_team.team_id, result.score.away_team.get(), result.score.home_team.get(), ); } } } self.rows.sort_by(|a, b| { match b.points.cmp(&a.points) { Ordering::Equal => match (b.goal_scored - b.goal_concerned).cmp(&(a.goal_scored - a.goal_concerned)) { Ordering::Equal => b.goal_scored.cmp(&a.goal_scored), other => other, }, other => other, } }); } pub fn get(&self) -> &[LeagueTableRow] { &self.rows } } #[derive(Debug)] pub struct LeagueTableRow { pub team_id: u32, pub played: u8, pub win: u8, pub draft: u8, pub lost: u8, pub goal_scored: i32, pub goal_concerned: i32, pub points: u8, } impl LeagueTableRow {} impl Default for LeagueTable { fn default() -> Self { LeagueTable { rows: Vec::new() } } } #[cfg(test)] mod tests { use super::*; use crate::r#match::{Score, TeamScore}; #[test] fn table_draft() { let first_team_id = 1; let second_team_id = 2; let teams = vec![first_team_id, second_team_id]; let mut table = LeagueTable::new(&teams); let match_results = vec![MatchResult { league_id: 0, id: "123".to_string(), league_slug: "slug".to_string(), home_team_id: 1, away_team_id: 2, score: Score { home_team: TeamScore::new_with_score(1, 3), away_team: TeamScore::new_with_score(2, 3), details: vec![], }, details: None, }]; table.update_from_results(&match_results); let returned_table = table.get(); let home = &returned_table[0]; assert_eq!(1, home.played); assert_eq!(1, home.draft); assert_eq!(0, home.win); assert_eq!(0, home.lost); assert_eq!(3, home.goal_scored); assert_eq!(3, home.goal_concerned); assert_eq!(1, home.points); let away = &returned_table[0]; assert_eq!(1, away.played); assert_eq!(1, away.draft); assert_eq!(0, away.win); assert_eq!(0, away.lost); assert_eq!(3, away.goal_scored); assert_eq!(3, away.goal_concerned); assert_eq!(1, away.points); } #[test] fn table_winner() { let first_team_id = 1; let second_team_id = 2; let teams = vec![first_team_id, second_team_id]; let mut table = LeagueTable::new(&teams); let home_team_id = 1; let away_team_id = 2; let match_results = vec![MatchResult { league_id: 0, id: "123".to_string(), league_slug: "slug".to_string(), home_team_id, away_team_id, score: Score { home_team: TeamScore::new_with_score(1, 3), away_team: TeamScore::new_with_score(2, 0), details: vec![], }, details: None, }]; table.update_from_results(&match_results); let returned_table = table.get(); let home = returned_table .iter() .find(|c| c.team_id == home_team_id) .unwrap(); assert_eq!(1, home.team_id); assert_eq!(1, home.played); assert_eq!(0, home.draft); assert_eq!(1, home.win); assert_eq!(0, home.lost); assert_eq!(3, home.goal_scored); assert_eq!(0, home.goal_concerned); assert_eq!(3, home.points); let away = returned_table .iter() .find(|c| c.team_id == away_team_id) .unwrap(); assert_eq!(2, away.team_id); assert_eq!(1, away.played); assert_eq!(0, away.draft); assert_eq!(0, away.win); assert_eq!(1, away.lost); assert_eq!(0, away.goal_scored); assert_eq!(3, away.goal_concerned); assert_eq!(0, away.points); } #[test] fn table_looser() { let first_team_id = 1; let second_team_id = 2; let teams = vec![first_team_id, second_team_id]; let mut table = LeagueTable::new(&teams); let home_team_id = 1; let away_team_id = 2; let match_results = vec![MatchResult { league_id: 0, id: "123".to_string(), league_slug: "slug".to_string(), home_team_id, away_team_id, score: Score { home_team: TeamScore::new_with_score(1, 0), away_team: TeamScore::new_with_score(2, 3), details: vec![], }, details: None, }]; table.update_from_results(&match_results); let returned_table = table.get(); let home = returned_table .iter() .find(|c| c.team_id == home_team_id) .unwrap(); assert_eq!(1, home.team_id); assert_eq!(1, home.played); assert_eq!(0, home.draft); assert_eq!(0, home.win); assert_eq!(1, home.lost); assert_eq!(0, home.goal_scored); assert_eq!(3, home.goal_concerned); assert_eq!(0, home.points); let away = returned_table .iter() .find(|c| c.team_id == away_team_id) .unwrap(); assert_eq!(2, away.team_id); assert_eq!(1, away.played); assert_eq!(0, away.draft); assert_eq!(1, away.win); assert_eq!(0, away.lost); assert_eq!(3, away.goal_scored); assert_eq!(0, away.goal_concerned); assert_eq!(3, away.points); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/table/result.rs
src/core/src/league/table/result.rs
pub struct LeagueTableResult {}
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/league/table/mod.rs
src/core/src/league/table/mod.rs
pub mod result; pub mod table; pub use result::*; pub use table::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/country/builder.rs
src/core/src/country/builder.rs
use crate::league::LeagueCollection; use crate::transfers::market::TransferMarket; use crate::{Club, Country, CountryEconomicFactors, CountryGeneratorData, CountryRegulations, InternationalCompetition, MediaCoverage}; #[derive(Default)] pub struct CountryBuilder { id: Option<u32>, code: Option<String>, slug: Option<String>, name: Option<String>, continent_id: Option<u32>, leagues: Option<LeagueCollection>, clubs: Option<Vec<Club>>, reputation: Option<u16>, generator_data: Option<CountryGeneratorData>, transfer_market: Option<TransferMarket>, economic_factors: Option<CountryEconomicFactors>, international_competitions: Option<Vec<InternationalCompetition>>, media_coverage: Option<MediaCoverage>, regulations: Option<CountryRegulations>, } impl CountryBuilder { pub fn new() -> Self { Self::default() } pub fn id(mut self, id: u32) -> Self { self.id = Some(id); self } pub fn code(mut self, code: String) -> Self { self.code = Some(code); self } pub fn slug(mut self, slug: String) -> Self { self.slug = Some(slug); self } pub fn name(mut self, name: String) -> Self { self.name = Some(name); self } pub fn continent_id(mut self, continent_id: u32) -> Self { self.continent_id = Some(continent_id); self } pub fn leagues(mut self, leagues: LeagueCollection) -> Self { self.leagues = Some(leagues); self } pub fn clubs(mut self, clubs: Vec<Club>) -> Self { self.clubs = Some(clubs); self } pub fn reputation(mut self, reputation: u16) -> Self { self.reputation = Some(reputation); self } pub fn generator_data(mut self, generator_data: CountryGeneratorData) -> Self { self.generator_data = Some(generator_data); self } pub fn transfer_market(mut self, transfer_market: TransferMarket) -> Self { self.transfer_market = Some(transfer_market); self } pub fn economic_factors(mut self, economic_factors: CountryEconomicFactors) -> Self { self.economic_factors = Some(economic_factors); self } pub fn international_competitions(mut self, competitions: Vec<InternationalCompetition>) -> Self { self.international_competitions = Some(competitions); self } pub fn media_coverage(mut self, media_coverage: MediaCoverage) -> Self { self.media_coverage = Some(media_coverage); self } pub fn regulations(mut self, regulations: CountryRegulations) -> Self { self.regulations = Some(regulations); self } pub fn build(self) -> Result<Country, String> { Ok(Country { id: self.id.ok_or("id is required")?, code: self.code.ok_or("code is required")?, slug: self.slug.ok_or("slug is required")?, name: self.name.ok_or("name is required")?, continent_id: self.continent_id.ok_or("continent_id is required")?, leagues: self.leagues.ok_or("leagues is required")?, clubs: self.clubs.ok_or("clubs is required")?, reputation: self.reputation.unwrap_or(500), // Default reputation generator_data: self.generator_data.unwrap_or_else(CountryGeneratorData::empty), transfer_market: self.transfer_market.unwrap_or_else(TransferMarket::new), economic_factors: self.economic_factors.unwrap_or_else(CountryEconomicFactors::new), international_competitions: self.international_competitions.unwrap_or_default(), media_coverage: self.media_coverage.unwrap_or_else(MediaCoverage::new), regulations: self.regulations.unwrap_or_else(CountryRegulations::new), }) } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/country/country.rs
src/core/src/country/country.rs
use crate::context::GlobalContext; use crate::country::CountryResult; use crate::league::LeagueCollection; use crate::transfers::market::{TransferMarket}; use crate::utils::Logging; use crate::{Club, ClubResult}; use chrono::{NaiveDate}; use log::{debug, info}; use std::collections::HashMap; use crate::country::builder::CountryBuilder; pub struct Country { pub id: u32, pub code: String, pub slug: String, pub name: String, pub continent_id: u32, pub leagues: LeagueCollection, pub clubs: Vec<Club>, pub reputation: u16, pub generator_data: CountryGeneratorData, pub transfer_market: TransferMarket, pub economic_factors: CountryEconomicFactors, pub international_competitions: Vec<InternationalCompetition>, pub media_coverage: MediaCoverage, pub regulations: CountryRegulations, } impl Country { pub fn builder() -> CountryBuilder { CountryBuilder::default() } pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> CountryResult { let country_name = self.name.clone(); info!("🌍 Simulating country: {} (Reputation: {})", country_name, self.reputation); // Phase 1: League Competitions let league_results = self.simulate_leagues(&ctx); // Phase 2: Club Operations let clubs_results = self.simulate_clubs(&ctx); info!("✅ Country {} simulation complete", country_name); CountryResult::new(league_results, clubs_results) } fn simulate_leagues(&mut self, ctx: &GlobalContext<'_>) -> Vec<crate::league::LeagueResult> { self.leagues.simulate(&self.clubs, ctx) } fn simulate_clubs(&mut self, ctx: &GlobalContext<'_>) -> Vec<ClubResult> { self.clubs .iter_mut() .map(|club| { let message = &format!("simulate club: {}", &club.name); Logging::estimate_result( || club.simulate(ctx.with_club(club.id, &club.name.clone())), message, ) }) .collect() } } // Supporting structures #[derive(Debug, Clone)] pub struct CountryEconomicFactors { pub gdp_growth: f32, pub inflation_rate: f32, pub tv_revenue_multiplier: f32, pub sponsorship_market_strength: f32, pub stadium_attendance_factor: f32, } impl Default for CountryEconomicFactors { fn default() -> Self { Self::new() } } impl CountryEconomicFactors { pub fn new() -> Self { CountryEconomicFactors { gdp_growth: 0.02, inflation_rate: 0.03, tv_revenue_multiplier: 1.0, sponsorship_market_strength: 1.0, stadium_attendance_factor: 1.0, } } pub fn get_financial_multiplier(&self) -> f32 { 1.0 + self.gdp_growth - self.inflation_rate } pub fn monthly_update(&mut self) { // Simulate economic fluctuations use crate::utils::FloatUtils; self.gdp_growth += FloatUtils::random(-0.005, 0.005); self.gdp_growth = self.gdp_growth.clamp(-0.05, 0.10); self.inflation_rate += FloatUtils::random(-0.003, 0.003); self.inflation_rate = self.inflation_rate.clamp(0.0, 0.10); self.tv_revenue_multiplier += FloatUtils::random(-0.02, 0.02); self.tv_revenue_multiplier = self.tv_revenue_multiplier.clamp(0.8, 1.5); } } #[derive(Debug)] pub struct InternationalCompetition { pub name: String, pub competition_type: CompetitionType, pub participating_clubs: Vec<u32>, pub current_round: String, } impl InternationalCompetition { pub fn simulate_round(&mut self, _date: NaiveDate) { // Simulate competition rounds debug!("Simulating {} round: {}", self.name, self.current_round); } } #[derive(Debug)] pub enum CompetitionType { ChampionsLeague, EuropaLeague, ConferenceLeague, SuperCup, } #[derive(Debug)] pub struct MediaCoverage { pub intensity: f32, pub trending_stories: Vec<MediaStory>, pub pressure_targets: HashMap<u32, f32>, // club_id -> pressure level } impl Default for MediaCoverage { fn default() -> Self { Self::new() } } impl MediaCoverage { pub fn new() -> Self { MediaCoverage { intensity: 0.5, trending_stories: Vec::new(), pressure_targets: HashMap::new(), } } pub fn get_pressure_level(&self) -> f32 { self.intensity } pub fn update_from_results(&mut self, _results: &[crate::league::LeagueResult]) { // Update media intensity based on exciting results self.intensity = (self.intensity * 0.9 + 0.1).min(1.0); } pub fn generate_weekly_stories(&mut self, clubs: &[Club]) { self.trending_stories.clear(); // Generate stories based on club performance, transfers, etc. use crate::utils::IntegerUtils; for club in clubs { if IntegerUtils::random(0, 100) > 80 { self.trending_stories.push(MediaStory { club_id: club.id, story_type: StoryType::TransferRumor, intensity: 0.5, }); } } } } #[derive(Debug)] pub struct MediaStory { pub club_id: u32, pub story_type: StoryType, pub intensity: f32, } #[derive(Debug)] pub enum StoryType { TransferRumor, ManagerPressure, PlayerControversy, SuccessStory, CrisisStory, } #[derive(Debug, Clone)] pub struct CountryRegulations { pub foreign_player_limit: Option<u8>, pub salary_cap: Option<f64>, pub homegrown_requirements: Option<u8>, pub ffp_enabled: bool, // Financial Fair Play } impl CountryRegulations { pub fn new() -> Self { CountryRegulations { foreign_player_limit: None, salary_cap: None, homegrown_requirements: None, ffp_enabled: false, } } } #[derive(Debug)] struct TransferActivitySummary { total_listings: u32, active_negotiations: u32, completed_transfers: u32, total_fees_exchanged: f64, } impl TransferActivitySummary { fn new() -> Self { TransferActivitySummary { total_listings: 0, active_negotiations: 0, completed_transfers: 0, total_fees_exchanged: 0.0, } } fn get_market_heat_index(&self) -> f32 { // Calculate how "hot" the transfer market is let activity = (self.active_negotiations as f32 + self.completed_transfers as f32) / 100.0; activity.min(1.0) } } #[derive(Debug)] struct SquadAnalysis { surplus_positions: Vec<crate::PlayerPositionType>, needed_positions: Vec<crate::PlayerPositionType>, average_age: f32, quality_level: u8, } struct CountrySimulationContext { economic_multiplier: f32, transfer_market_heat: f32, media_pressure: f32, regulatory_constraints: CountryRegulations, } // Update CountryGeneratorData and PeopleNameGeneratorData as per original pub struct CountryGeneratorData { pub people_names: PeopleNameGeneratorData, } impl CountryGeneratorData { pub fn new(first_names: Vec<String>, last_names: Vec<String>) -> Self { CountryGeneratorData { people_names: PeopleNameGeneratorData { first_names, last_names, }, } } pub fn empty() -> Self { CountryGeneratorData { people_names: PeopleNameGeneratorData { first_names: Vec::new(), last_names: Vec::new(), }, } } } pub struct PeopleNameGeneratorData { pub first_names: Vec<String>, pub last_names: Vec<String>, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/country/result.rs
src/core/src/country/result.rs
use chrono::Datelike; use chrono::NaiveDate; use log::{debug, info}; use crate::league::LeagueResult; use crate::simulator::SimulatorData; use crate::{Club, ClubResult, ClubTransferStrategy, Country, SimulationResult}; use crate::shared::{Currency, CurrencyValue}; use crate::transfers::{TransferListing, TransferListingType, TransferWindowManager}; pub struct CountryResult { pub leagues: Vec<LeagueResult>, pub clubs: Vec<ClubResult>, } impl CountryResult { pub fn new(leagues: Vec<LeagueResult>, clubs: Vec<ClubResult>) -> Self { CountryResult { leagues, clubs } } pub fn process(self, data: &mut SimulatorData, result: &mut SimulationResult) { let current_date = data.date.date(); let country_id = self.get_country_id(data); // Phase 3: Pre-season activities (if applicable) if Self::is_preseason(current_date) { self.simulate_preseason_activities(data, country_id, current_date); } // Phase 4: Transfer Market Activities let _transfer_activities = self.simulate_transfer_market(data, country_id, current_date); // Phase 5: International Competitions self.simulate_international_competitions(data, country_id, current_date); // Phase 6: Economic Updates self.update_economic_factors(data, country_id, current_date); // Phase 7: Media and Public Interest self.simulate_media_coverage(data, country_id, &self.leagues); // Phase 8: End of Period Processing self.process_end_of_period(data, country_id, current_date, &self.clubs); // Phase 9: Country Reputation Update self.update_country_reputation(data, country_id, &self.leagues, &self.clubs); // Phase 1: Process league results for league_result in self.leagues { league_result.process(data, result); } // Phase 2: Process club results for club_result in self.clubs { club_result.process(data, result); } } // Helper methods fn get_country_id(&self, _data: &SimulatorData) -> u32 { // Get country ID from first club or league result // Adjust based on your actual data structure if let Some(_club_result) = self.clubs.first() { // Get club from data and return its country_id // This is a placeholder 0 } else { 0 } } fn is_preseason(date: NaiveDate) -> bool { let month = date.month(); // Preseason typically June-July in Europe month == 6 || month == 7 } fn simulate_preseason_activities(&self, data: &mut SimulatorData, country_id: u32, date: NaiveDate) { info!("⚽ Running preseason activities..."); if let Some(country) = data.country_mut(country_id) { // Schedule friendlies between clubs Self::schedule_friendly_matches(country, date); // Training camps and tours Self::organize_training_camps(country); // Preseason tournaments Self::organize_preseason_tournaments(country); } } fn simulate_transfer_market( &self, data: &mut SimulatorData, country_id: u32, current_date: NaiveDate, ) -> TransferActivitySummary { let mut summary = TransferActivitySummary::new(); // Check if transfer window is open let window_manager = TransferWindowManager::new(); if !window_manager.is_window_open(country_id, current_date) { return summary; } info!("💰 Transfer window is OPEN - simulating market activity"); // Get country to access its data if let Some(country) = data.country_mut(country_id) { // Phase 1: Clubs list players for transfer Self::list_players_for_transfer(country, current_date, &mut summary); // Phase 2: Generate interest and negotiate transfers Self::negotiate_transfers(country, current_date, &mut summary); // Phase 3: Process loan deals Self::process_loan_deals(country, current_date, &mut summary); // Phase 4: Free agents and contract expirations Self::handle_free_agents(country, current_date, &mut summary); // Phase 5: Update market based on completed deals country.transfer_market.update(current_date); debug!( "Transfer Activity - Listings: {}, Negotiations: {}, Completed: {}", summary.total_listings, summary.active_negotiations, summary.completed_transfers ); } summary } fn list_players_for_transfer( country: &mut Country, date: NaiveDate, summary: &mut TransferActivitySummary, ) { // Collect player listing data to avoid borrow conflicts let mut listings_to_add = Vec::new(); for club in &country.clubs { // Analyze squad and determine transfer needs let squad_analysis = Self::analyze_squad_needs(club); // List surplus players for player in &club.teams.teams[0].players.players { if Self::should_list_player(player, &squad_analysis, club) { let asking_price = Self::calculate_asking_price(player, club, date); listings_to_add.push(( player.id, club.id, club.teams.teams[0].id, asking_price, )); } } } // Now add all listings for (player_id, club_id, team_id, asking_price) in listings_to_add { let listing = TransferListing::new( player_id, club_id, team_id, asking_price, date, TransferListingType::Transfer, ); country.transfer_market.add_listing(listing); summary.total_listings += 1; } } fn negotiate_transfers( country: &mut Country, date: NaiveDate, summary: &mut TransferActivitySummary, ) { // Collect negotiations to process (avoid borrow conflicts) let mut negotiations_to_process = Vec::new(); // First pass: collect all potential negotiations for buying_club in &country.clubs { let budget = CurrencyValue { amount: 1_000_000.0, currency: Currency::Usd, }; // Get club's transfer strategy let strategy = ClubTransferStrategy { club_id: buying_club.id, budget: Some(budget), selling_willingness: 0.5, buying_aggressiveness: Self::calculate_buying_aggressiveness(buying_club), target_positions: Self::identify_target_positions(buying_club), reputation_level: 0, }; // Collect available listings let available_listings: Vec<_> = country .transfer_market .get_available_listings() .into_iter() .filter(|listing| listing.club_id != buying_club.id) .cloned() .collect(); // Look through available listings for listing in available_listings { // Find the player if let Some(player) = Self::find_player_in_country(country, listing.player_id) { if strategy.decide_player_interest(player) { let offer = strategy.calculate_initial_offer( player, &listing.asking_price, date, ); negotiations_to_process.push(( listing.player_id, buying_club.id, listing.club_id, offer, )); } } } } // Second pass: process all negotiations for (player_id, buying_club_id, selling_club_id, offer) in negotiations_to_process { if let Some(neg_id) = country.transfer_market.start_negotiation( player_id, buying_club_id, offer, date, ) { summary.active_negotiations += 1; // Simulate negotiation outcome if Self::simulate_negotiation_outcome(neg_id, selling_club_id, buying_club_id) { if let Some(completed) = country.transfer_market.complete_transfer(neg_id, date) { summary.completed_transfers += 1; summary.total_fees_exchanged += completed.fee.amount; } } } } } fn simulate_international_competitions( &self, data: &mut SimulatorData, country_id: u32, date: NaiveDate, ) { if let Some(country) = data.country_mut(country_id) { // Simulate continental competitions (e.g., Champions League, Europa League) for competition in &mut country.international_competitions { competition.simulate_round(date); } } } fn update_economic_factors( &self, data: &mut SimulatorData, country_id: u32, date: NaiveDate, ) { // Update country's economic indicators monthly if date.day() == 1 { if let Some(country) = data.country_mut(country_id) { country.economic_factors.monthly_update(); } } } fn simulate_media_coverage( &self, data: &mut SimulatorData, country_id: u32, league_results: &[LeagueResult], ) { if let Some(country) = data.country_mut(country_id) { country.media_coverage.update_from_results(league_results); country.media_coverage.generate_weekly_stories(&country.clubs); } } fn process_end_of_period( &self, data: &mut SimulatorData, country_id: u32, date: NaiveDate, club_results: &[ClubResult], ) { // End of season processing if date.month() == 5 && date.day() == 31 { info!("📅 End of season processing"); if let Some(country) = data.country_mut(country_id) { // Award ceremonies Self::process_season_awards(country, club_results); // Contract expirations Self::process_contract_expirations(country); // Retirements Self::process_player_retirements(country, date); } } // End of year processing if date.month() == 12 && date.day() == 31 { if let Some(country) = data.country_mut(country_id) { Self::process_year_end_finances(country); } } } fn update_country_reputation( &self, data: &mut SimulatorData, country_id: u32, _league_results: &[crate::league::LeagueResult], _club_results: &[ClubResult], ) { if let Some(country) = data.country_mut(country_id) { // Base reputation change let mut reputation_change: i16 = 0; // Factor 1: League competitiveness for league in &country.leagues.leagues { let competitiveness = Self::calculate_league_competitiveness(league); reputation_change += (competitiveness * 5.0) as i16; } // Factor 2: International competition performance let international_success = Self::calculate_international_success(country); reputation_change += international_success as i16; // Factor 3: Transfer market activity let transfer_reputation = Self::calculate_transfer_market_reputation(country); reputation_change += transfer_reputation as i16; // Apply change with bounds let new_reputation = (country.reputation as i16 + reputation_change).clamp(0, 1000) as u16; if new_reputation != country.reputation { debug!( "Country {} reputation changed: {} -> {} ({})", country.name, country.reputation, new_reputation, if reputation_change > 0 { format!("+{}", reputation_change) } else { reputation_change.to_string() } ); country.reputation = new_reputation; } } } // Helper methods fn analyze_squad_needs(_club: &Club) -> SquadAnalysis { SquadAnalysis { surplus_positions: vec![], needed_positions: vec![], average_age: 25.0, quality_level: 50, } } fn should_list_player( _player: &crate::Player, _analysis: &SquadAnalysis, _club: &Club, ) -> bool { false // Simplified for now } fn calculate_asking_price( player: &crate::Player, club: &Club, date: NaiveDate, ) -> CurrencyValue { use crate::transfers::window::PlayerValuationCalculator; let base_value = PlayerValuationCalculator::calculate_value(player, date); let multiplier = if club.finance.balance.balance < 0 { 0.9 // Financial pressure } else { 1.1 // No pressure }; CurrencyValue { amount: base_value.amount * multiplier, currency: base_value.currency, } } fn calculate_buying_aggressiveness(_club: &Club) -> f32 { 0.6 // Simplified } fn identify_target_positions(_club: &Club) -> Vec<crate::PlayerPositionType> { vec![] // Simplified } fn find_player_in_country(country: &Country, player_id: u32) -> Option<&crate::Player> { for club in &country.clubs { for team in &club.teams.teams { if let Some(player) = team.players.players.iter().find(|p| p.id == player_id) { return Some(player); } } } None } fn simulate_negotiation_outcome( _negotiation_id: u32, _selling_club: u32, _buying_club: u32, ) -> bool { use crate::utils::IntegerUtils; IntegerUtils::random(0, 100) > 60 // 40% success rate } fn schedule_friendly_matches(_country: &mut Country, _date: NaiveDate) { debug!("Scheduling preseason friendlies"); } fn organize_training_camps(_country: &mut Country) { debug!("Organizing training camps"); } fn organize_preseason_tournaments(_country: &mut Country) { debug!("Organizing preseason tournaments"); } fn process_loan_deals(_country: &mut Country, _date: NaiveDate, _summary: &mut TransferActivitySummary) { debug!("Processing loan deals"); } fn handle_free_agents(_country: &mut Country, _date: NaiveDate, _summary: &mut TransferActivitySummary) { debug!("Handling free agents"); } fn calculate_league_competitiveness(_league: &crate::league::League) -> f32 { 0.5 // Simplified } fn calculate_international_success(_country: &Country) -> i16 { 0 // Simplified } fn calculate_transfer_market_reputation(_country: &Country) -> i16 { 0 // Simplified } fn process_season_awards(_country: &mut Country, _club_results: &[ClubResult]) { debug!("Processing season awards"); } fn process_contract_expirations(_country: &mut Country) { debug!("Processing contract expirations"); } fn process_player_retirements(_country: &mut Country, _date: NaiveDate) { debug!("Processing player retirements"); } fn process_year_end_finances(_country: &mut Country) { debug!("Processing year-end finances"); } } // Supporting structures (keep these in country.rs) #[derive(Debug)] struct TransferActivitySummary { total_listings: u32, active_negotiations: u32, completed_transfers: u32, total_fees_exchanged: f64, } impl TransferActivitySummary { fn new() -> Self { TransferActivitySummary { total_listings: 0, active_negotiations: 0, completed_transfers: 0, total_fees_exchanged: 0.0, } } fn get_market_heat_index(&self) -> f32 { let activity = (self.active_negotiations as f32 + self.completed_transfers as f32) / 100.0; activity.min(1.0) } } #[derive(Debug)] struct SquadAnalysis { surplus_positions: Vec<crate::PlayerPositionType>, needed_positions: Vec<crate::PlayerPositionType>, average_age: f32, quality_level: u8, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/country/mod.rs
src/core/src/country/mod.rs
mod context; pub mod country; mod result; mod builder; pub use context::*; pub use country::*; pub use result::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/country/context.rs
src/core/src/country/context.rs
#[derive(Clone)] pub struct CountryContext { pub id: u32, } impl CountryContext { pub fn new(id: u32) -> Self { CountryContext { id } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/offer.rs
src/core/src/transfers/offer.rs
use crate::shared::CurrencyValue; use chrono::NaiveDate; #[derive(Debug, Clone)] pub struct TransferOffer { pub base_fee: CurrencyValue, pub clauses: Vec<TransferClause>, pub salary_contribution: Option<CurrencyValue>, // For loans pub contract_length: Option<u8>, // Years pub offering_club_id: u32, pub offered_date: NaiveDate, } #[derive(Debug, Clone)] pub enum TransferClause { AppearanceFee(CurrencyValue, u32), // Money after X appearances GoalBonus(CurrencyValue, u32), // Money after X goals SellOnClause(f32), // Percentage of future transfer PromotionBonus(CurrencyValue), // Money if buying club gets promoted } impl TransferOffer { pub fn new( base_fee: CurrencyValue, offering_club_id: u32, offered_date: NaiveDate, ) -> Self { TransferOffer { base_fee, clauses: Vec::new(), salary_contribution: None, contract_length: None, offering_club_id, offered_date, } } pub fn with_clause(mut self, clause: TransferClause) -> Self { self.clauses.push(clause); self } pub fn with_salary_contribution(mut self, contribution: CurrencyValue) -> Self { self.salary_contribution = Some(contribution); self } pub fn with_contract_length(mut self, years: u8) -> Self { self.contract_length = Some(years); self } pub fn total_potential_value(&self) -> f64 { let mut total = self.base_fee.amount; for clause in &self.clauses { match clause { TransferClause::AppearanceFee(fee, _) => total += fee.amount * 0.7, // Assume 70% chance of meeting appearances TransferClause::GoalBonus(fee, _) => total += fee.amount * 0.5, // Assume 50% chance of meeting goal bonus TransferClause::SellOnClause(percentage) => total += total * (*percentage as f64) * 0.3, // Assume 30% chance of future sale TransferClause::PromotionBonus(fee) => total += fee.amount * 0.2, // Assume 20% chance of promotion } } total } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/transfer.rs
src/core/src/transfers/transfer.rs
use crate::shared::CurrencyValue; use crate::Player; use chrono::{Datelike, NaiveDate}; pub struct PlayerTransfer { pub player: Player, pub club_id: u32, } impl PlayerTransfer { pub fn new(player: Player, club_id: u32) -> Self { PlayerTransfer { player, club_id } } } #[derive(Debug, Clone)] pub struct CompletedTransfer { pub player_id: u32, pub from_club_id: u32, pub to_club_id: u32, pub transfer_date: NaiveDate, pub fee: CurrencyValue, pub transfer_type: TransferType, pub season_year: u16, } #[derive(Debug, Clone)] pub enum TransferType { Permanent, Loan(NaiveDate), // End date Free, } impl CompletedTransfer { pub fn new( player_id: u32, from_club_id: u32, to_club_id: u32, transfer_date: NaiveDate, fee: CurrencyValue, transfer_type: TransferType, ) -> Self { // Determine the season year based on when transfer happened // Typically football seasons span Aug-May, so use that as reference let season_year = if transfer_date.month() >= 8 { transfer_date.year() as u16 } else { (transfer_date.year() - 1) as u16 }; CompletedTransfer { player_id, from_club_id, to_club_id, transfer_date, fee, transfer_type, season_year, } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/market.rs
src/core/src/transfers/market.rs
use crate::shared::CurrencyValue; use crate::transfers::negotiation::{NegotiationStatus, TransferNegotiation}; use crate::transfers::offer::TransferOffer; use crate::transfers::{CompletedTransfer, TransferType}; use chrono::NaiveDate; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct TransferMarket { pub listings: Vec<TransferListing>, pub negotiations: HashMap<u32, TransferNegotiation>, pub transfer_window_open: bool, pub transfer_history: Vec<CompletedTransfer>, pub next_negotiation_id: u32, } #[derive(Debug, Clone)] pub struct TransferListing { pub player_id: u32, pub club_id: u32, pub team_id: u32, pub asking_price: CurrencyValue, pub listed_date: NaiveDate, pub listing_type: TransferListingType, pub status: TransferListingStatus, } #[derive(Debug, Clone, PartialEq)] pub enum TransferListingType { Transfer, Loan, EndOfContract, } #[derive(Debug, Clone, PartialEq)] pub enum TransferListingStatus { Available, InNegotiation, Completed, Cancelled, } impl TransferListing { pub fn new( player_id: u32, club_id: u32, team_id: u32, asking_price: CurrencyValue, listed_date: NaiveDate, listing_type: TransferListingType, ) -> Self { TransferListing { player_id, club_id, team_id, asking_price, listed_date, listing_type, status: TransferListingStatus::Available, } } } impl TransferMarket { pub fn new() -> Self { TransferMarket { listings: Vec::new(), negotiations: HashMap::new(), transfer_window_open: false, transfer_history: Vec::new(), next_negotiation_id: 1, } } pub fn add_listing(&mut self, listing: TransferListing) { // Check for duplicates if !self.listings.iter().any(|l| l.player_id == listing.player_id && l.status == TransferListingStatus::Available) { self.listings.push(listing); } } pub fn get_available_listings(&self) -> Vec<&TransferListing> { self.listings.iter() .filter(|l| l.status == TransferListingStatus::Available) .collect() } pub fn get_listing_by_player(&self, player_id: u32) -> Option<&TransferListing> { self.listings.iter() .find(|l| l.player_id == player_id && l.status == TransferListingStatus::Available) } pub fn start_negotiation( &mut self, player_id: u32, buying_club_id: u32, offer: TransferOffer, current_date: NaiveDate, ) -> Option<u32> { // Find the listing if let Some(listing_index) = self.listings.iter().position(|l| l.player_id == player_id && l.status == TransferListingStatus::Available) { let listing = &mut self.listings[listing_index]; // Create a negotiation let negotiation_id = self.next_negotiation_id; self.next_negotiation_id += 1; let negotiation = TransferNegotiation::new( negotiation_id, player_id, listing_index as u32, listing.club_id, buying_club_id, offer, current_date, ); // Update listing status listing.status = TransferListingStatus::InNegotiation; // Store the negotiation self.negotiations.insert(negotiation_id, negotiation); Some(negotiation_id) } else { None } } pub fn complete_transfer(&mut self, negotiation_id: u32, current_date: NaiveDate) -> Option<CompletedTransfer> { // Find the negotiation if let Some(negotiation) = self.negotiations.get(&negotiation_id) { if negotiation.status != NegotiationStatus::Accepted { return None; } // Get the listing index let listing_idx = negotiation.listing_id as usize; if listing_idx >= self.listings.len() { return None; } // Update listing status if let Some(listing) = self.listings.get_mut(listing_idx) { listing.status = TransferListingStatus::Completed; } // Create a completed transfer record let transfer_type = match self.listings.get(listing_idx).unwrap().listing_type { TransferListingType::Loan => { // Assume 6-month loan if contract length not specified let loan_end = negotiation.current_offer.contract_length .map(|months| { current_date.checked_add_signed(chrono::Duration::days(months as i64 * 30)) .unwrap_or(current_date) }) .unwrap_or_else(|| { current_date.checked_add_signed(chrono::Duration::days(180)) .unwrap_or(current_date) }); TransferType::Loan(loan_end) } TransferListingType::EndOfContract => TransferType::Free, _ => TransferType::Permanent, }; let completed = CompletedTransfer::new( negotiation.player_id, negotiation.selling_club_id, negotiation.buying_club_id, current_date, negotiation.current_offer.base_fee.clone(), transfer_type, ); // Add to history self.transfer_history.push(completed.clone()); Some(completed) } else { None } } pub fn update(&mut self, current_date: NaiveDate) { // Check for expired negotiations let expired_ids: Vec<u32> = self.negotiations.iter_mut() .filter_map(|(id, negotiation)| { if negotiation.check_expired(current_date) { Some(*id) } else { None } }) .collect(); // Update listings for expired negotiations for id in expired_ids { if let Some(negotiation) = self.negotiations.get(&id) { let listing_idx = negotiation.listing_id as usize; if listing_idx < self.listings.len() { let listing = &mut self.listings[listing_idx]; listing.status = TransferListingStatus::Available; } } } } pub fn check_transfer_window(&mut self, is_open: bool) { self.transfer_window_open = is_open; // If window closes, cancel all active listings and negotiations if !is_open { // Mark all available listings as cancelled for listing in &mut self.listings { if listing.status == TransferListingStatus::Available || listing.status == TransferListingStatus::InNegotiation { listing.status = TransferListingStatus::Cancelled; } } // Mark all pending negotiations as expired for (_, negotiation) in &mut self.negotiations { if negotiation.status == NegotiationStatus::Pending || negotiation.status == NegotiationStatus::Countered { negotiation.status = NegotiationStatus::Expired; } } } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/mod.rs
src/core/src/transfers/mod.rs
pub mod pool; pub mod transfer; pub mod market; pub mod negotiation; pub mod offer; pub mod window; pub use market::*; pub use negotiation::*; pub use offer::*; pub use pool::*; pub use transfer::*; pub use window::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/window.rs
src/core/src/transfers/window.rs
use crate::shared::CurrencyValue; use crate::{Person, Player, PlayerValueCalculator}; use chrono::{Datelike, NaiveDate}; use std::collections::HashMap; #[derive(Debug)] pub struct TransferWindowManager { pub windows: HashMap<u32, TransferWindow>, // Keyed by country_id } #[derive(Debug, Clone)] pub struct TransferWindow { pub summer_window: (NaiveDate, NaiveDate), pub winter_window: (NaiveDate, NaiveDate), pub country_id: u32, } impl TransferWindowManager { pub fn new() -> Self { TransferWindowManager { windows: HashMap::new(), } } pub fn add_window(&mut self, country_id: u32, window: TransferWindow) { self.windows.insert(country_id, window); } pub fn is_window_open(&self, country_id: u32, date: NaiveDate) -> bool { if let Some(window) = self.windows.get(&country_id) { self.is_date_in_window(date, &window.summer_window) || self.is_date_in_window(date, &window.winter_window) } else { // Default to European standard windows if country-specific not defined let year = date.year(); let summer_start = NaiveDate::from_ymd_opt(year, 6, 1).unwrap_or(date); let summer_end = NaiveDate::from_ymd_opt(year, 8, 31).unwrap_or(date); let winter_start = NaiveDate::from_ymd_opt(year, 1, 1).unwrap_or(date); let winter_end = NaiveDate::from_ymd_opt(year, 1, 31).unwrap_or(date); self.is_date_in_window(date, &(summer_start, summer_end)) || self.is_date_in_window(date, &(winter_start, winter_end)) } } fn is_date_in_window(&self, date: NaiveDate, window: &(NaiveDate, NaiveDate)) -> bool { date >= window.0 && date <= window.1 } } /// Generates appropriate values for players based on multiple factors pub struct PlayerValuationCalculator; impl PlayerValuationCalculator { pub fn calculate_value(player: &Player, date: NaiveDate) -> CurrencyValue { // Use the existing calculator as a base let base_value = PlayerValueCalculator::calculate(player, date); // Apply market modifiers let market_adjusted_value = Self::apply_market_factors(base_value, player, date); CurrencyValue { amount: market_adjusted_value, currency: crate::shared::Currency::Usd, } } fn apply_market_factors(base_value: f64, player: &Player, date: NaiveDate) -> f64 { let mut adjusted_value = base_value; // Contract length factor - extremely important if let Some(contract) = &player.contract { let days_remaining = contract.days_to_expiration(date.and_hms_opt(0, 0, 0).unwrap()); let years_remaining = days_remaining as f64 / 365.0; if years_remaining < 0.5 { // Less than 6 months - massive devaluation adjusted_value *= 0.3; } else if years_remaining < 1.0 { // Less than a year - significant devaluation adjusted_value *= 0.6; } else if years_remaining < 2.0 { // 1-2 years - moderate devaluation adjusted_value *= 0.8; } else if years_remaining > 4.0 { // Long contract - slight value increase adjusted_value *= 1.1; } } // Player age factor (already included in base calculator but we can fine-tune) let age = player.age(date); if age < 23 { // Young players with potential adjusted_value *= 1.2; } else if age > 32 { // Older players adjusted_value *= 0.7; } // Recent performance factor let goals = player.statistics.goals; let assists = player.statistics.assists; let played = player.statistics.played; if played > 10 { // Had significant playing time let goals_per_game = goals as f64 / played as f64; let assists_per_game = assists as f64 / played as f64; // Attackers valued by goals if player.position().is_forward() && goals_per_game > 0.5 { adjusted_value *= 1.0 + (goals_per_game - 0.5) * 2.0; } // Midfielders valued by combined contribution if player.position().is_midfielder() && (goals_per_game + assists_per_game) > 0.4 { adjusted_value *= 1.0 + ((goals_per_game + assists_per_game) - 0.4) * 1.5; } } // International status if player.player_attributes.international_apps > 10 { adjusted_value *= 1.2; } // Apply position factor (goalkeepers and defenders typically valued less) if player.position().is_goalkeeper() { adjusted_value *= 0.8; } adjusted_value } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/negotiation.rs
src/core/src/transfers/negotiation.rs
use crate::transfers::offer::TransferOffer; use chrono::NaiveDate; #[derive(Debug, Clone)] pub struct TransferNegotiation { pub id: u32, pub player_id: u32, pub listing_id: u32, pub selling_club_id: u32, pub buying_club_id: u32, pub current_offer: TransferOffer, pub counter_offers: Vec<TransferOffer>, pub status: NegotiationStatus, pub expiry_date: NaiveDate, pub created_date: NaiveDate, } #[derive(Debug, PartialEq, Clone)] pub enum NegotiationStatus { Pending, Accepted, Rejected, Countered, Expired, } impl TransferNegotiation { pub fn new( id: u32, player_id: u32, listing_id: u32, selling_club_id: u32, buying_club_id: u32, initial_offer: TransferOffer, created_date: NaiveDate, ) -> Self { // Negotiations expire after 3 days by default let expiry_date = created_date.checked_add_signed(chrono::Duration::days(3)) .unwrap_or(created_date); TransferNegotiation { id, player_id, listing_id, selling_club_id, buying_club_id, current_offer: initial_offer, counter_offers: Vec::new(), status: NegotiationStatus::Pending, expiry_date, created_date, } } pub fn counter_offer(&mut self, counter: TransferOffer) { self.counter_offers.push(self.current_offer.clone()); self.current_offer = counter; self.status = NegotiationStatus::Countered; } pub fn accept(&mut self) { self.status = NegotiationStatus::Accepted; } pub fn reject(&mut self) { self.status = NegotiationStatus::Rejected; } pub fn check_expired(&mut self, current_date: NaiveDate) -> bool { if current_date >= self.expiry_date && self.status == NegotiationStatus::Pending { self.status = NegotiationStatus::Expired; return true; } false } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/transfers/pool.rs
src/core/src/transfers/pool.rs
use std::collections::HashMap; use std::sync::Mutex; pub struct TransferPool<T> { pool: Mutex<HashMap<u32, Vec<T>>>, } impl<T> TransferPool<T> { pub fn new() -> Self { TransferPool { pool: Mutex::new(HashMap::new()), } } pub fn push_transfer(&mut self, item: T, club_id: u32) { let mut inner_map = self.pool.lock().unwrap(); let entry = inner_map.entry(club_id).or_insert_with(Vec::new); entry.push(item); } pub fn pull_transfers(&mut self, club_id: u32) -> Option<Vec<T>> { let mut inner_map = self.pool.lock().expect("lock poisoned"); if !inner_map.contains_key(&club_id) { return None; } inner_map.remove(&club_id) } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/result.rs
src/core/src/continent/result.rs
use crate::continent::{ CompetitionTier, Continent, ContinentalCompetitions, ContinentalMatchResult, ContinentalRankings, }; use crate::country::CountryResult; use crate::simulator::SimulatorData; use crate::transfers::CompletedTransfer; use crate::{Club, Country, SimulationResult}; use chrono::Datelike; use chrono::NaiveDate; use log::{debug, info}; use std::collections::HashMap; pub struct ContinentResult { pub countries: Vec<CountryResult>, // New fields for continental-level results pub competition_results: Option<ContinentalCompetitionResults>, pub rankings_update: Option<ContinentalRankingsUpdate>, pub transfer_summary: Option<CrossBorderTransferSummary>, pub economic_impact: Option<EconomicZoneImpact>, } impl ContinentResult { pub fn new(countries: Vec<CountryResult>) -> Self { ContinentResult { countries, competition_results: None, rankings_update: None, transfer_summary: None, economic_impact: None, } } pub fn process(self, data: &mut SimulatorData, result: &mut SimulationResult) { let current_date = data.date.date(); // Assuming SimulationResult has date // Phase 2: Update Continental Rankings (monthly) if current_date.day() == 1 { self.update_continental_rankings(data, result); } // Phase 3: Continental Competition Processing if self.is_competition_draw_period(current_date) { self.conduct_competition_draws(data, current_date); } let competition_results = self.simulate_continental_competitions(data, current_date); if let Some(comp_results) = competition_results { self.process_competition_results(comp_results, data, result); } // Phase 4: Continental Economic Updates (quarterly) if current_date.month() % 3 == 0 && current_date.day() == 1 { self.update_economic_zone(data, &self.countries); } // Phase 5: Continental Regulatory Updates (yearly) if current_date.month() == 1 && current_date.day() == 1 { self.update_continental_regulations(data, current_date); } // Phase 6: Continental Awards & Recognition (yearly) if current_date.month() == 12 && current_date.day() == 31 { self.process_continental_awards(data, &self.countries); } for country_result in self.countries { country_result.process(data, result); } } fn update_continental_rankings(&self, data: &mut SimulatorData, _result: &mut SimulationResult) { info!("📊 Updating continental rankings"); // Get continent from data let continent_id = self.get_continent_id(data); if let Some(continent) = data.continent_mut(continent_id) { // Update country coefficients based on club performances for country in &mut continent.countries { let coefficient = Self::calculate_country_coefficient(country, &continent.continental_competitions); continent.continental_rankings.update_country_ranking(country.id, coefficient); } // Update club rankings let all_clubs = Self::get_all_clubs(&continent.countries); for club in all_clubs { let club_points = Self::calculate_club_continental_points(club, &continent.continental_competitions); continent.continental_rankings.update_club_ranking(club.id, club_points); } // Determine continental competition qualifications Self::determine_competition_qualifications(&mut continent.continental_rankings); debug!( "Continental rankings updated - Top country: {:?}", continent.continental_rankings.get_top_country() ); } } fn is_competition_draw_period(&self, date: NaiveDate) -> bool { // Champions League draw typically in August (date.month() == 8 && date.day() == 15) || // Europa League draw (date.month() == 8 && date.day() == 20) || // Knockout stage draws in December (date.month() == 12 && date.day() == 15) } fn conduct_competition_draws(&self, data: &mut SimulatorData, date: NaiveDate) { info!("🎲 Conducting continental competition draws"); let continent_id = self.get_continent_id(data); if let Some(continent) = data.continent_mut(continent_id) { let qualified_clubs = continent.continental_rankings.get_qualified_clubs(); // Champions League draw if let Some(cl_clubs) = qualified_clubs.get(&CompetitionTier::ChampionsLeague) { continent.continental_competitions.champions_league.conduct_draw( cl_clubs, &continent.continental_rankings, date, ); } // Europa League draw if let Some(el_clubs) = qualified_clubs.get(&CompetitionTier::EuropaLeague) { continent.continental_competitions.europa_league.conduct_draw( el_clubs, &continent.continental_rankings, date, ); } // Conference League draw if let Some(conf_clubs) = qualified_clubs.get(&CompetitionTier::ConferenceLeague) { continent.continental_competitions.conference_league.conduct_draw( conf_clubs, &continent.continental_rankings, date, ); } } } fn simulate_continental_competitions( &self, data: &mut SimulatorData, date: NaiveDate, ) -> Option<ContinentalCompetitionResults> { let continent_id = self.get_continent_id(data); let continent = data.continent_mut(continent_id)?; let mut results = ContinentalCompetitionResults::new(); let clubs_map = Self::get_clubs_map(&continent.countries); // Simulate Champions League matches if continent.continental_competitions.champions_league.has_matches_today(date) { let cl_results = continent.continental_competitions.champions_league.simulate_round( &clubs_map, date, ); results.champions_league_results = Some(cl_results); } // Simulate Europa League matches if continent.continental_competitions.europa_league.has_matches_today(date) { let el_results = continent.continental_competitions.europa_league.simulate_round( &clubs_map, date, ); results.europa_league_results = Some(el_results); } // Simulate Conference League matches if continent.continental_competitions.conference_league.has_matches_today(date) { let conf_results = continent.continental_competitions.conference_league.simulate_round( &clubs_map, date, ); results.conference_league_results = Some(conf_results); } Some(results) } fn process_competition_results( &self, comp_results: ContinentalCompetitionResults, data: &mut SimulatorData, result: &mut SimulationResult, ) { info!("🏆 Processing continental competition results"); // Process Champions League results if let Some(cl_results) = comp_results.champions_league_results { for match_result in cl_results { self.process_single_match(match_result, data, result); } } // Process Europa League results if let Some(el_results) = comp_results.europa_league_results { for match_result in el_results { self.process_single_match(match_result, data, result); } } // Process Conference League results if let Some(conf_results) = comp_results.conference_league_results { for match_result in conf_results { self.process_single_match(match_result, data, result); } } // Distribute competition rewards after all matches processed self.distribute_competition_rewards(data); } fn process_single_match( &self, match_result: ContinentalMatchResult, data: &mut SimulatorData, _result: &mut SimulationResult, ) { debug!( "Processing match: {} vs {} ({}-{})", match_result.home_team, match_result.away_team, match_result.home_score, match_result.away_score ); // Update statistics for home team self.update_club_continental_stats(match_result.home_team, &match_result, true, data); // Update statistics for away team self.update_club_continental_stats(match_result.away_team, &match_result, false, data); // Store match in simulation result for output/history // _result.continental_matches.push(match_result); } fn update_club_continental_stats( &self, club_id: u32, match_result: &ContinentalMatchResult, is_home: bool, data: &mut SimulatorData, ) { if let Some(club) = data.club_mut(club_id) { // Determine match outcome for this club let (goals_for, goals_against) = if is_home { (match_result.home_score, match_result.away_score) } else { (match_result.away_score, match_result.home_score) }; let won = goals_for > goals_against; let drawn = goals_for == goals_against; let _lost = goals_for < goals_against; // Update continental record (would need to add this to Club struct) // club.continental_record.matches_played += 1; // if won { // club.continental_record.wins += 1; // } else if drawn { // club.continental_record.draws += 1; // } else { // club.continental_record.losses += 1; // } // club.continental_record.goals_for += goals_for as u32; // club.continental_record.goals_against += goals_against as u32; // Update finances with match revenue let match_revenue = self.calculate_match_revenue(match_result); club.finance.balance.push_income(match_revenue as i32); // Win bonus if won { let win_bonus = self.calculate_win_bonus(match_result); club.finance.balance.push_income(win_bonus as i32); } // Update club reputation based on result self.update_club_reputation(club, match_result, won, drawn); // Update player morale and form based on result self.update_players_after_match(club, won, drawn); debug!( "Club {} stats updated: revenue +€{:.0}", club_id, match_revenue ); } } fn calculate_match_revenue(&self, match_result: &ContinentalMatchResult) -> f64 { // Base revenue by competition tier let base_revenue = match match_result.competition { CompetitionTier::ChampionsLeague => 3_000_000.0, // €3M per match CompetitionTier::EuropaLeague => 1_000_000.0, // €1M per match CompetitionTier::ConferenceLeague => 500_000.0, // €500K per match }; // Add ticket revenue (simplified - would depend on stadium capacity) let ticket_revenue = 200_000.0; base_revenue + ticket_revenue } fn calculate_win_bonus(&self, match_result: &ContinentalMatchResult) -> f64 { match match_result.competition { CompetitionTier::ChampionsLeague => 2_800_000.0, // €2.8M win bonus CompetitionTier::EuropaLeague => 570_000.0, // €570K win bonus CompetitionTier::ConferenceLeague => 500_000.0, // €500K win bonus } } fn update_club_reputation(&self, club: &mut Club, match_result: &ContinentalMatchResult, won: bool, drawn: bool) { // Reputation changes based on continental performance let reputation_change = if won { match match_result.competition { CompetitionTier::ChampionsLeague => 5, CompetitionTier::EuropaLeague => 3, CompetitionTier::ConferenceLeague => 2, } } else if drawn { 1 } else { -2 }; // Apply reputation change (would need reputation field in Club) // club.reputation.continental = (club.reputation.continental as i32 + reputation_change) // .clamp(0, 1000) as u16; debug!("Club {} reputation change: {:+}", club.id, reputation_change); } fn update_players_after_match(&self, club: &mut Club, won: bool, _drawn: bool) { // Update player morale and form after continental match let _morale_change = if won { 5 } else { -3 }; for team in &mut club.teams.teams { for _player in &mut team.players.players { // Morale change (would need morale field in Player) // _player.morale = (_player.morale as i32 + _morale_change).clamp(0, 100) as u8; // Form change based on performance (simplified) // if won { // _player.form = (_player.form + 2).min(100); // } } } } fn distribute_competition_rewards(&self, data: &mut SimulatorData) { info!("💰 Distributing continental competition rewards"); let continent_id = self.get_continent_id(data); // Collect participating clubs data first to avoid borrow conflicts let (cl_clubs, el_clubs, conf_clubs) = if let Some(continent) = data.continent(continent_id) { ( continent.continental_competitions.champions_league.participating_clubs.clone(), continent.continental_competitions.europa_league.participating_clubs.clone(), continent.continental_competitions.conference_league.participating_clubs.clone(), ) } else { return; }; // Now we can mutably borrow data without conflicts // Distribute Champions League rewards self.distribute_competition_tier_rewards( &cl_clubs, CompetitionTier::ChampionsLeague, data, ); // Distribute Europa League rewards self.distribute_competition_tier_rewards( &el_clubs, CompetitionTier::EuropaLeague, data, ); // Distribute Conference League rewards self.distribute_competition_tier_rewards( &conf_clubs, CompetitionTier::ConferenceLeague, data, ); } fn distribute_competition_tier_rewards( &self, participating_clubs: &[u32], tier: CompetitionTier, data: &mut SimulatorData, ) { // Participation bonus let participation_bonus = match tier { CompetitionTier::ChampionsLeague => 15_640_000.0, // €15.64M base CompetitionTier::EuropaLeague => 3_630_000.0, // €3.63M base CompetitionTier::ConferenceLeague => 2_940_000.0, // €2.94M base }; for &club_id in participating_clubs { if let Some(club) = data.club_mut(club_id) { club.finance.balance.push_income(participation_bonus as i32); debug!( "Club {} received participation bonus: €{:.2}M", club_id, participation_bonus / 1_000_000.0 ); } } // Additional stage progression bonuses would be calculated here // based on how far each team progressed in the competition } fn update_economic_zone(&self, data: &mut SimulatorData, _country_results: &[CountryResult]) { info!("💰 Updating continental economic zone"); let continent_id = self.get_continent_id(data); if let Some(continent) = data.continent_mut(continent_id) { // Calculate overall economic health let mut total_revenue = 0.0; let mut total_expenses = 0.0; for country in &continent.countries { for club in &country.clubs { total_revenue += club.finance.balance.income as f64; total_expenses += club.finance.balance.outcome as f64; } } continent.economic_zone.update_indicators(total_revenue, total_expenses); // Update TV rights distribution continent.economic_zone.recalculate_tv_rights(&continent.continental_rankings); // Update sponsorship market continent.economic_zone.update_sponsorship_market(&continent.continental_rankings); } } fn update_continental_regulations(&self, data: &mut SimulatorData, date: NaiveDate) { info!("📋 Updating continental regulations"); let continent_id = self.get_continent_id(data); if let Some(continent) = data.continent_mut(continent_id) { // Financial Fair Play adjustments continent.regulations.update_ffp_thresholds(&continent.economic_zone); // Foreign player regulations continent.regulations.review_foreign_player_rules(&continent.continental_rankings); // Youth development requirements continent.regulations.update_youth_requirements(); debug!("Continental regulations updated for year {}", date.year()); } } fn process_continental_awards(&self, data: &mut SimulatorData, _country_results: &[CountryResult]) { info!("🏆 Processing continental awards"); let continent_id = self.get_continent_id(data); if let Some(continent) = data.continent(continent_id) { // Player of the Year let _player_of_year = Self::determine_player_of_year(continent); // Team of the Year let _team_of_year = Self::determine_team_of_year(continent); // Coach of the Year let _coach_of_year = Self::determine_coach_of_year(continent); // Young Player Award let _young_player = Self::determine_young_player_award(continent); debug!("Continental awards distributed"); } } // Helper methods fn get_continent_id(&self, _data: &SimulatorData) -> u32 { // Assuming we can get continent ID from the first country // You might want to store this in ContinentResult if let Some(_first_country) = self.countries.first() { // Get country from data and return its continent_id // This is a placeholder - adjust based on your actual data structure 0 // Replace with actual logic } else { 0 } } fn calculate_country_coefficient(country: &Country, competitions: &ContinentalCompetitions) -> f32 { let mut coefficient = 0.0; for club in &country.clubs { coefficient += competitions.get_club_points(club.id); } if !country.clubs.is_empty() { coefficient /= country.clubs.len() as f32; } coefficient } fn calculate_club_continental_points(club: &Club, competitions: &ContinentalCompetitions) -> f32 { let competition_points = competitions.get_club_points(club.id); let domestic_bonus = 0.0; // Would need league standings competition_points + domestic_bonus } fn determine_competition_qualifications(rankings: &mut ContinentalRankings) { // Collect country rankings data first to avoid borrow conflicts let country_rankings: Vec<(u32, f32)> = rankings.get_country_rankings().to_vec(); // Now we can mutably borrow rankings without conflicts for (rank, (country_id, _coefficient)) in country_rankings.iter().enumerate() { let cl_spots = match rank { 0..=3 => 4, 4..=5 => 3, 6..=14 => 2, _ => 1, }; let el_spots = match rank { 0..=5 => 2, _ => 1, }; rankings.set_qualification_spots(*country_id, cl_spots, el_spots); } } fn get_all_clubs(countries: &[Country]) -> Vec<&Club> { countries.iter().flat_map(|c| &c.clubs).collect() } fn get_clubs_map(countries: &[Country]) -> HashMap<u32, &Club> { countries .iter() .flat_map(|c| &c.clubs) .map(|club| (club.id, club)) .collect() } fn determine_player_of_year(_continent: &Continent) -> Option<u32> { None } fn determine_team_of_year(_continent: &Continent) -> Option<Vec<u32>> { None } fn determine_coach_of_year(_continent: &Continent) -> Option<u32> { None } fn determine_young_player_award(_continent: &Continent) -> Option<u32> { None } } // Supporting structures for the result #[derive(Debug, Clone)] pub struct ContinentalRankingsUpdate { pub country_updates: Vec<(u32, f32)>, // country_id, new coefficient pub club_updates: Vec<(u32, f32)>, // club_id, new points pub qualification_changes: Vec<QualificationChange>, } impl ContinentalRankingsUpdate { pub fn from_rankings(rankings: ContinentalRankings) -> Self { ContinentalRankingsUpdate { country_updates: rankings.country_rankings, club_updates: rankings.club_rankings, qualification_changes: Vec::new(), } } } #[derive(Debug, Clone)] pub struct QualificationChange { pub country_id: u32, pub competition: CompetitionTier, pub old_spots: u8, pub new_spots: u8, } #[derive(Debug, Clone)] pub struct CrossBorderTransferSummary { pub completed_transfers: Vec<CompletedTransfer>, pub total_value: f64, pub most_expensive: Option<CompletedTransfer>, pub by_country_flow: HashMap<u32, TransferFlow>, // country_id -> flow stats } #[derive(Debug, Clone)] pub struct TransferFlow { pub incoming_transfers: u32, pub outgoing_transfers: u32, pub net_spend: f64, } #[derive(Debug, Clone)] pub struct EconomicZoneImpact { pub economic_multiplier: f32, pub tv_rights_change: f64, pub sponsorship_change: f64, pub overall_health_change: f32, } // Extension to SimulationResult to include continental matches impl SimulationResult { // Note: This would need to be added to the actual SimulationResult struct // pub continental_matches: Vec<ContinentalMatchResult>, } #[derive(Debug)] pub struct ContinentalCompetitionResults { pub champions_league_results: Option<Vec<ContinentalMatchResult>>, pub europa_league_results: Option<Vec<ContinentalMatchResult>>, pub conference_league_results: Option<Vec<ContinentalMatchResult>>, } impl ContinentalCompetitionResults { pub fn new() -> Self { ContinentalCompetitionResults { champions_league_results: None, europa_league_results: None, conference_league_results: None, } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/mod.rs
src/core/src/continent/mod.rs
pub mod context; mod continent; mod result; mod tournaments; pub use context::*; pub use continent::*; pub use result::*; pub use tournaments::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/context.rs
src/core/src/continent/context.rs
#[derive(Clone)] pub struct ContinentContext { id: u32 } impl ContinentContext { pub fn new(id: u32) -> Self { ContinentContext { id } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/continent.rs
src/core/src/continent/continent.rs
use crate::context::GlobalContext; use crate::continent::ContinentResult; use crate::country::CountryResult; use crate::utils::Logging; use crate::{Club, Country}; use chrono::NaiveDate; use log::{debug, info}; use std::collections::HashMap; pub struct Continent { pub id: u32, pub name: String, pub countries: Vec<Country>, pub continental_competitions: ContinentalCompetitions, pub continental_rankings: ContinentalRankings, pub regulations: ContinentalRegulations, pub economic_zone: EconomicZone, } impl Continent { pub fn new(id: u32, name: String, countries: Vec<Country>) -> Self { Continent { id, name, countries, continental_competitions: ContinentalCompetitions::new(), continental_rankings: ContinentalRankings::new(), regulations: ContinentalRegulations::new(), economic_zone: EconomicZone::new(), } } pub fn simulate(&mut self, ctx: GlobalContext<'_>) -> ContinentResult { let continent_name = self.name.clone(); info!( "🌏 Simulating continent: {} ({} countries)", continent_name, self.countries.len() ); // Simulate all child entities and accumulate results let country_results = self.simulate_countries(&ctx); info!("✅ Continent {} simulation complete", continent_name); ContinentResult::new(country_results) } fn simulate_countries(&mut self, ctx: &GlobalContext<'_>) -> Vec<CountryResult> { self.countries .iter_mut() .map(|country| { let message = &format!("simulate country: {} (Continental)", &country.name); Logging::estimate_result( || country.simulate(ctx.with_country(country.id)), message, ) }) .collect() } } // Supporting structures for continental simulation #[derive(Debug, Clone)] pub struct ContinentalCompetitions { pub champions_league: ChampionsLeague, pub europa_league: EuropaLeague, pub conference_league: ConferenceLeague, pub super_cup: SuperCup, } impl Default for ContinentalCompetitions { fn default() -> Self { Self::new() } } impl ContinentalCompetitions { pub fn new() -> Self { ContinentalCompetitions { champions_league: ChampionsLeague::new(), europa_league: EuropaLeague::new(), conference_league: ConferenceLeague::new(), super_cup: SuperCup::new(), } } pub fn get_club_points(&self, club_id: u32) -> f32 { let mut points = 0.0; points += self.champions_league.get_club_points(club_id); points += self.europa_league.get_club_points(club_id); points += self.conference_league.get_club_points(club_id); points } pub fn get_total_prize_pool(&self) -> f64 { self.champions_league.prize_pool + self.europa_league.prize_pool + self.conference_league.prize_pool + self.super_cup.prize_pool } } #[derive(Debug, Clone)] pub struct ChampionsLeague { pub participating_clubs: Vec<u32>, pub current_stage: CompetitionStage, pub matches: Vec<ContinentalMatch>, pub prize_pool: f64, } impl Default for ChampionsLeague { fn default() -> Self { Self::new() } } impl ChampionsLeague { pub fn new() -> Self { ChampionsLeague { participating_clubs: Vec::new(), current_stage: CompetitionStage::NotStarted, matches: Vec::new(), prize_pool: 2_000_000_000.0, // 2 billion euros } } pub fn conduct_draw(&mut self, clubs: &[u32], _rankings: &ContinentalRankings, _date: NaiveDate) { // Implement draw logic with seeding based on rankings debug!("Champions League draw conducted with {} clubs", clubs.len()); } pub fn has_matches_today(&self, date: NaiveDate) -> bool { self.matches.iter().any(|m| m.date == date) } pub fn simulate_round( &mut self, _clubs: &HashMap<u32, &Club>, date: NaiveDate, ) -> Vec<ContinentalMatchResult> { let mut results = Vec::new(); for match_to_play in self.matches.iter_mut().filter(|m| m.date == date) { // Simulate match (simplified) let result = ContinentalMatchResult { home_team: match_to_play.home_team, away_team: match_to_play.away_team, home_score: 0, away_score: 0, competition: CompetitionTier::ChampionsLeague, }; results.push(result); } results } pub fn get_club_points(&self, club_id: u32) -> f32 { // Points based on performance if !self.participating_clubs.contains(&club_id) { return 0.0; } // Simplified: base points for participation 10.0 } } #[derive(Debug, Clone)] pub struct EuropaLeague { pub participating_clubs: Vec<u32>, pub current_stage: CompetitionStage, pub matches: Vec<ContinentalMatch>, pub prize_pool: f64, } impl EuropaLeague { pub fn new() -> Self { EuropaLeague { participating_clubs: Vec::new(), current_stage: CompetitionStage::NotStarted, matches: Vec::new(), prize_pool: 500_000_000.0, // 500 million euros } } pub fn conduct_draw(&mut self, clubs: &[u32], _rankings: &ContinentalRankings, _date: NaiveDate) { debug!("Europa League draw conducted with {} clubs", clubs.len()); } pub fn has_matches_today(&self, date: NaiveDate) -> bool { self.matches.iter().any(|m| m.date == date) } pub fn simulate_round( &mut self, _clubs: &HashMap<u32, &Club>, _date: NaiveDate, ) -> Vec<ContinentalMatchResult> { Vec::new() // Simplified } pub fn get_club_points(&self, club_id: u32) -> f32 { if !self.participating_clubs.contains(&club_id) { return 0.0; } 5.0 } } #[derive(Debug, Clone)] pub struct ConferenceLeague { pub participating_clubs: Vec<u32>, pub current_stage: CompetitionStage, pub matches: Vec<ContinentalMatch>, pub prize_pool: f64, } impl ConferenceLeague { pub fn new() -> Self { ConferenceLeague { participating_clubs: Vec::new(), current_stage: CompetitionStage::NotStarted, matches: Vec::new(), prize_pool: 250_000_000.0, // 250 million euros } } pub fn conduct_draw(&mut self, clubs: &[u32], _rankings: &ContinentalRankings, _date: NaiveDate) { debug!( "Conference League draw conducted with {} clubs", clubs.len() ); } pub fn has_matches_today(&self, _date: NaiveDate) -> bool { false // Simplified } pub fn simulate_round( &mut self, _clubs: &HashMap<u32, &Club>, _date: NaiveDate, ) -> Vec<ContinentalMatchResult> { Vec::new() // Simplified } pub fn get_club_points(&self, club_id: u32) -> f32 { if !self.participating_clubs.contains(&club_id) { return 0.0; } 3.0 } } #[derive(Debug, Clone)] pub struct ContinentalMatchResult { pub home_team: u32, // ID of the home team pub away_team: u32, // ID of the away team pub home_score: u8, // Goals scored by home team pub away_score: u8, // Goals scored by away team pub competition: CompetitionTier, // Which competition (CL/EL/Conference) } #[derive(Debug, Clone)] pub struct SuperCup { pub prize_pool: f64, } impl SuperCup { pub fn new() -> Self { SuperCup { prize_pool: 10_000_000.0, } } } #[derive(Debug, Clone)] pub enum CompetitionStage { NotStarted, Qualifying, GroupStage, RoundOf32, RoundOf16, QuarterFinals, SemiFinals, Final, } #[derive(Debug, Clone)] pub struct ContinentalMatch { pub home_team: u32, pub away_team: u32, pub date: NaiveDate, pub stage: CompetitionStage, } #[derive(Debug, Clone)] pub struct ContinentalRankings { pub country_rankings: Vec<(u32, f32)>, // country_id, coefficient pub club_rankings: Vec<(u32, f32)>, // club_id, points pub qualification_spots: HashMap<u32, QualificationSpots>, } impl ContinentalRankings { pub fn new() -> Self { ContinentalRankings { country_rankings: Vec::new(), club_rankings: Vec::new(), qualification_spots: HashMap::new(), } } pub fn update_country_ranking(&mut self, country_id: u32, coefficient: f32) { if let Some(entry) = self .country_rankings .iter_mut() .find(|(id, _)| *id == country_id) { entry.1 = coefficient; } else { self.country_rankings.push((country_id, coefficient)); } // Sort by coefficient descending self.country_rankings .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); } pub fn update_club_ranking(&mut self, club_id: u32, points: f32) { if let Some(entry) = self.club_rankings.iter_mut().find(|(id, _)| *id == club_id) { entry.1 = points; } else { self.club_rankings.push((club_id, points)); } self.club_rankings .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); } pub fn get_top_country(&self) -> Option<u32> { self.country_rankings.first().map(|(id, _)| *id) } pub fn get_country_rankings(&self) -> &[(u32, f32)] { &self.country_rankings } pub fn get_qualified_clubs(&self) -> HashMap<CompetitionTier, Vec<u32>> { // Logic to determine which clubs qualify for each competition HashMap::new() // Simplified } pub fn set_qualification_spots(&mut self, country_id: u32, cl_spots: u8, el_spots: u8) { self.qualification_spots.insert( country_id, QualificationSpots { champions_league: cl_spots, europa_league: el_spots, conference_league: 1, // Default }, ); } } #[derive(Debug, Clone)] pub struct QualificationSpots { pub champions_league: u8, pub europa_league: u8, pub conference_league: u8, } #[derive(Debug, Clone)] pub struct ContinentalRegulations { pub ffp_rules: FinancialFairPlayRules, pub foreign_player_limits: ForeignPlayerLimits, pub youth_requirements: YouthRequirements, } impl ContinentalRegulations { pub fn new() -> Self { ContinentalRegulations { ffp_rules: FinancialFairPlayRules::new(), foreign_player_limits: ForeignPlayerLimits::new(), youth_requirements: YouthRequirements::new(), } } pub fn update_ffp_thresholds(&mut self, economic_zone: &EconomicZone) { // Adjust FFP based on economic conditions self.ffp_rules .update_thresholds(economic_zone.get_overall_health()); } pub fn review_foreign_player_rules(&mut self, _rankings: &ContinentalRankings) { // Potentially adjust foreign player rules } pub fn update_youth_requirements(&mut self) { // Update youth development requirements } } #[derive(Debug, Clone)] pub struct FinancialFairPlayRules { pub max_deficit: f64, pub monitoring_period_years: u8, pub squad_cost_ratio_limit: f32, } impl FinancialFairPlayRules { pub fn new() -> Self { FinancialFairPlayRules { max_deficit: 30_000_000.0, monitoring_period_years: 3, squad_cost_ratio_limit: 0.7, } } pub fn update_thresholds(&mut self, economic_health: f32) { // Adjust based on economic conditions if economic_health < 0.5 { self.max_deficit *= 0.8; } else if economic_health > 0.8 { self.max_deficit *= 1.1; } } } #[derive(Debug, Clone)] pub struct ForeignPlayerLimits { pub max_non_eu_players: Option<u8>, pub homegrown_minimum: u8, } impl ForeignPlayerLimits { pub fn new() -> Self { ForeignPlayerLimits { max_non_eu_players: Some(3), homegrown_minimum: 8, } } } #[derive(Debug, Clone)] pub struct YouthRequirements { pub minimum_academy_investment: f64, pub minimum_youth_squad_size: u8, } impl YouthRequirements { pub fn new() -> Self { YouthRequirements { minimum_academy_investment: 1_000_000.0, minimum_youth_squad_size: 20, } } } #[derive(Debug, Clone)] pub struct EconomicZone { pub tv_rights_pool: f64, pub sponsorship_value: f64, pub economic_health_indicator: f32, } impl EconomicZone { pub fn new() -> Self { EconomicZone { tv_rights_pool: 5_000_000_000.0, sponsorship_value: 2_000_000_000.0, economic_health_indicator: 0.7, } } pub fn get_overall_health(&self) -> f32 { self.economic_health_indicator } pub fn update_indicators(&mut self, total_revenue: f64, total_expenses: f64) { let profit_margin = (total_revenue - total_expenses) / total_revenue; // Update health indicator based on profit margin self.economic_health_indicator = (self.economic_health_indicator * 0.8 + profit_margin as f32 * 0.2).clamp(0.0, 1.0); } pub fn recalculate_tv_rights(&mut self, rankings: &ContinentalRankings) { // Adjust TV rights based on competitive balance let competitive_balance = self.calculate_competitive_balance(rankings); self.tv_rights_pool *= 1.0 + competitive_balance as f64 * 0.1; } pub fn update_sponsorship_market(&mut self, _rankings: &ContinentalRankings) { // Update based on top clubs' performance self.sponsorship_value *= 1.02; // Simplified growth } fn calculate_competitive_balance(&self, _rankings: &ContinentalRankings) -> f32 { // Measure how competitive the continent is 0.5 // Simplified } } #[derive(Debug, Clone)] pub struct TransferInterest { pub player_id: u32, pub source_country: u32, pub interest_level: f32, } #[derive(Debug, Clone)] pub struct TransferNegotiation { pub player_id: u32, pub selling_club: u32, pub buying_club: u32, pub current_offer: f64, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum CompetitionTier { ChampionsLeague, EuropaLeague, ConferenceLeague, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/tournaments/league_europe.rs
src/core/src/continent/tournaments/league_europe.rs
use crate::context::GlobalContext; use crate::continent::{Tournament, TournamentContext}; pub struct LeagueEurope {} impl LeagueEurope {} impl Tournament for LeagueEurope { fn simulate(&mut self, _: &mut TournamentContext, _: GlobalContext<'_>) {} }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/tournaments/mod.rs
src/core/src/continent/tournaments/mod.rs
mod champion_league; mod context; mod league_europe; use crate::context::GlobalContext; pub use context::*; pub trait Tournament { fn simulate(&mut self, tournament_ctx: &mut TournamentContext, ctx: GlobalContext<'_>); }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/tournaments/context.rs
src/core/src/continent/tournaments/context.rs
pub struct TournamentContext {} impl TournamentContext { pub fn new() -> Self { TournamentContext {} } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/continent/tournaments/champion_league.rs
src/core/src/continent/tournaments/champion_league.rs
use crate::context::GlobalContext; use crate::continent::{Tournament, TournamentContext}; pub struct ChampionLeague {} impl ChampionLeague {} impl Tournament for ChampionLeague { fn simulate(&mut self, _: &mut TournamentContext, _: GlobalContext<'_>) {} }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/fullname.rs
src/core/src/shared/fullname.rs
use std::fmt::{Display, Formatter, Result}; #[derive(Debug)] pub struct FullName { pub first_name: String, pub last_name: String, pub middle_name: Option<String>, } impl FullName { pub fn new(first_name: String, last_name: String) -> Self { FullName { first_name, last_name, middle_name: None, } } pub fn with_full(first_name: String, last_name: String, middle_name: String) -> Self { FullName { first_name, last_name, middle_name: Some(middle_name), } } } impl Display for FullName { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let mut name = format!("{} {}", self.last_name, self.first_name); if let Some(middle_name) = self.middle_name.as_ref() { name.push_str(" "); name.push_str(middle_name); } write!(f, "{}", name) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_new_fullname() { let fullname = FullName::new("John".to_string(), "Doe".to_string()); assert_eq!(fullname.first_name, "John"); assert_eq!(fullname.last_name, "Doe"); assert_eq!(fullname.middle_name, None); } #[test] fn test_with_full_fullname() { let fullname = FullName::with_full("John".to_string(), "Doe".to_string(), "Smith".to_string()); assert_eq!(fullname.first_name, "John"); assert_eq!(fullname.last_name, "Doe"); assert_eq!(fullname.middle_name, Some("Smith".to_string())); } #[test] fn test_display_without_middle_name() { let fullname = FullName::new("John".to_string(), "Doe".to_string()); assert_eq!(format!("{}", fullname), "Doe John"); } #[test] fn test_display_with_middle_name() { let fullname = FullName::with_full("John".to_string(), "Doe".to_string(), "Smith".to_string()); assert_eq!(format!("{}", fullname), "Doe John Smith"); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/mod.rs
src/core/src/shared/mod.rs
pub mod currency; pub mod fullname; pub mod indexes; pub mod location; pub use currency::*; pub use fullname::*; pub use indexes::*; pub use location::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/currency.rs
src/core/src/shared/currency.rs
#[derive(Debug, Clone)] pub struct CurrencyValue { pub amount: f64, pub currency: Currency, } impl CurrencyValue { pub fn new(amount: f64, currency: Currency) -> Self { CurrencyValue { amount, currency } } } #[derive(Debug, Clone)] pub enum Currency { Usd, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/location.rs
src/core/src/shared/location.rs
#[derive(Debug)] pub struct Location { pub city_id: u32, } impl Location { pub fn new(city_id: u32) -> Self { Location { city_id } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/indexes/mod.rs
src/core/src/shared/indexes/mod.rs
pub mod simulator_indexes; pub use simulator_indexes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/core/src/shared/indexes/simulator_indexes.rs
src/core/src/shared/indexes/simulator_indexes.rs
use crate::SimulatorData; use std::collections::HashMap; pub struct SimulatorDataIndexes { pub league_indexes: HashMap<u32, (u32, u32)>, pub club_indexes: HashMap<u32, (u32, u32)>, pub team_indexes: HashMap<u32, (u32, u32, u32)>, pub player_indexes: HashMap<u32, (u32, u32, u32, u32)>, pub team_data_index: HashMap<u32, TeamData>, pub slug_indexes: SlugIndexes, } impl SimulatorDataIndexes { pub fn new() -> Self { SimulatorDataIndexes { league_indexes: HashMap::new(), club_indexes: HashMap::new(), team_indexes: HashMap::new(), player_indexes: HashMap::new(), team_data_index: HashMap::new(), slug_indexes: SlugIndexes::new(), } } pub fn refresh(&mut self, data: &SimulatorData) { for continent in &data.continents { for country in &continent.countries { self.slug_indexes .add_country_slug(&country.slug, country.id); //fill leagues for league in &country.leagues.leagues { self.add_league_location(league.id, continent.id, country.id); self.slug_indexes.add_league_slug(&league.slug, league.id); } //fill teams for club in &country.clubs { self.add_club_location(club.id, continent.id, country.id); for team in &club.teams.teams { self.add_team_data( team.id, TeamData { name: team.name.clone(), slug: team.slug.clone(), }, ); self.slug_indexes.add_team_slug(&team.slug, team.id); self.add_team_location(team.id, continent.id, country.id, club.id); for player in &team.players.players { self.add_player_location( player.id, continent.id, country.id, club.id, team.id, ); } } } } } } //league indexes pub fn add_league_location(&mut self, league_id: u32, continent_id: u32, country_id: u32) { self.league_indexes .insert(league_id, (continent_id, country_id)); } pub fn get_league_location(&self, league_id: u32) -> Option<(u32, u32)> { match self.league_indexes.get(&league_id) { Some((league_continent_id, league_country_id)) => { Some((*league_continent_id, *league_country_id)) } None => None, } } //club indexes pub fn add_club_location(&mut self, club_id: u32, continent_id: u32, country_id: u32) { self.club_indexes .insert(club_id, (continent_id, country_id)); } pub fn get_club_location(&self, club_id: u32) -> Option<(u32, u32)> { match self.club_indexes.get(&club_id) { Some((club_continent_id, club_country_id)) => { Some((*club_continent_id, *club_country_id)) } None => None, } } //team data indexes pub fn add_team_data(&mut self, team_id: u32, team_data: TeamData) { self.team_data_index.insert(team_id, team_data); } pub fn get_team_data(&self, team_id: u32) -> Option<&TeamData> { match self.team_data_index.get(&team_id) { Some(team_data) => Some(team_data), None => None, } } pub fn add_team_location( &mut self, team_id: u32, continent_id: u32, country_id: u32, club_id: u32, ) { self.team_indexes .insert(team_id, (continent_id, country_id, club_id)); } pub fn get_team_location(&self, team_id: u32) -> Option<(u32, u32, u32)> { match self.team_indexes.get(&team_id) { Some((team_continent_id, team_country_id, team_club_id)) => { Some((*team_continent_id, *team_country_id, *team_club_id)) } None => None, } } //player indexes pub fn add_player_location( &mut self, player_id: u32, continent_id: u32, country_id: u32, club_id: u32, team_id: u32, ) { self.player_indexes .insert(player_id, (continent_id, country_id, club_id, team_id)); } pub fn get_player_location(&self, player_id: u32) -> Option<(u32, u32, u32, u32)> { match self.player_indexes.get(&player_id) { Some((player_continent_id, player_country_id, player_club_id, player_team_id)) => { Some(( *player_continent_id, *player_country_id, *player_club_id, *player_team_id, )) } None => None, } } } pub struct SlugIndexes { country_slug_index: HashMap<String, u32>, league_slug_index: HashMap<String, u32>, team_slug_index: HashMap<String, u32>, } impl SlugIndexes { pub fn new() -> Self { SlugIndexes { country_slug_index: HashMap::new(), league_slug_index: HashMap::new(), team_slug_index: HashMap::new(), } } // team id slug index pub fn add_country_slug(&mut self, slug: &str, country_id: u32) { self.country_slug_index.insert(slug.into(), country_id); } pub fn get_country_by_slug(&self, slug: &str) -> Option<u32> { match self.country_slug_index.get(slug) { Some(country_id) => Some(*country_id), None => None, } } // team id slug index pub fn add_league_slug(&mut self, slug: &str, league_id: u32) { self.league_slug_index.insert(slug.into(), league_id); } pub fn get_league_by_slug(&self, slug: &str) -> Option<u32> { match self.league_slug_index.get(slug) { Some(league_id) => Some(*league_id), None => None, } } // team id slug index pub fn add_team_slug(&mut self, slug: &str, team_id: u32) { self.team_slug_index.insert(slug.into(), team_id); } pub fn get_team_by_slug(&self, slug: &str) -> Option<u32> { match self.team_slug_index.get(slug) { Some(team_id) => Some(*team_id), None => None, } } } pub struct TeamData { pub name: String, pub slug: String, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/lib.rs
src/server/src/lib.rs
mod countries; mod date; mod error; mod game; mod leagues; mod r#match; mod player; mod routes; mod teams; pub use error::{ApiError, ApiResult}; use crate::routes::ServerRoutes; use axum::response::IntoResponse; use core::SimulatorData; use database::DatabaseEntity; use log::{error, info}; use std::net::SocketAddr; use std::sync::Arc; use tokio::net::TcpListener; use tokio::sync::RwLock; use tower::ServiceBuilder; use tower_http::catch_panic::CatchPanicLayer; pub struct FootballSimulatorServer { data: GameAppData, } impl FootballSimulatorServer { pub fn new(data: GameAppData) -> Self { FootballSimulatorServer { data } } pub async fn run(&self) { let app = ServerRoutes::create() .layer( ServiceBuilder::new() // Catch panics in handlers and convert them to 500 errors .layer(CatchPanicLayer::custom(|err| { ( axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Internal server error - handler panicked".to_string(), ).into_response() })) ) .with_state(self.data.clone()); let addr = SocketAddr::from(([0, 0, 0, 0], 18000)); let listener = match TcpListener::bind(addr).await { Ok(listener) => listener, Err(e) => { error!("Failed to bind to address {}: {}", addr, e); panic!("Cannot start server without binding to port"); } }; info!("listen at: http://localhost:18000"); if let Err(e) = axum::serve(listener, app).await { error!("Server error: {}", e); error!("Server stopped unexpectedly, but not crashing the process"); // Don't panic here - just log and let the process stay alive // This way Docker won't restart unless the process actually exits } } } pub struct GameAppData { pub database: Arc<DatabaseEntity>, pub data: Arc<RwLock<Option<SimulatorData>>>, pub is_one_shot_game: bool, } impl Clone for GameAppData { fn clone(&self) -> Self { GameAppData { database: Arc::clone(&self.database), data: Arc::clone(&self.data), is_one_shot_game: self.is_one_shot_game } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/error.rs
src/server/src/error.rs
use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; use serde_json::json; /// Custom error type for API handlers #[derive(Debug)] pub enum ApiError { NotFound(String), InternalError(String), BadRequest(String), } impl IntoResponse for ApiError { fn into_response(self) -> Response { let (status, error_message) = match self { ApiError::NotFound(msg) => (StatusCode::NOT_FOUND, msg), ApiError::InternalError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg), ApiError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg), }; let body = Json(json!({ "error": error_message, })); (status, body).into_response() } } impl From<std::io::Error> for ApiError { fn from(err: std::io::Error) -> Self { ApiError::InternalError(format!("IO error: {}", err)) } } impl From<serde_json::Error> for ApiError { fn from(err: serde_json::Error) -> Self { ApiError::InternalError(format!("JSON error: {}", err)) } } /// Helper type for handler results pub type ApiResult<T> = Result<T, ApiError>;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/routes.rs
src/server/src/routes.rs
use crate::countries::country_routes; use crate::date::current_date_routes; use crate::game::game_routes; use crate::leagues::league_routes; use crate::player::player_routes; use crate::r#match::routes::match_routes; use crate::teams::team_routes; use crate::GameAppData; use axum::routing::get_service; use axum::Router; use tower_http::services::{ServeDir, ServeFile}; pub struct ServerRoutes; impl ServerRoutes { pub fn create() -> Router<GameAppData> { let routes = Router::<GameAppData>::new() .merge(country_routes()) .merge(game_routes()) .merge(league_routes()) .merge(team_routes()) .merge(player_routes()) .merge(match_routes()) .merge(current_date_routes()); #[cfg(debug_assertions)] let client_app_dir = "ui/dist"; #[cfg(debug_assertions)] let client_app_index_file = "./ui/dist/index.html"; #[cfg(not(debug_assertions))] let client_app_dir = "dist"; #[cfg(not(debug_assertions))] let client_app_index_file = "dist/index.html"; Router::new() .fallback(get_service(ServeFile::new(client_app_index_file))) .merge(routes) .nest_service( "/dist", ServeDir::new(client_app_dir).fallback(ServeFile::new(client_app_index_file)), ) } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/mod.rs
src/server/src/match/mod.rs
pub mod chunk; mod get; pub mod routes; pub mod stores;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/chunk.rs
src/server/src/match/chunk.rs
use crate::{ApiError, ApiResult, GameAppData}; use crate::r#match::stores::MatchStore; use axum::extract::{Path, State}; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct MatchChunkRequest { pub league_slug: String, pub match_id: String, pub chunk_number: usize, } #[derive(Deserialize)] pub struct MatchMetadataRequest { pub league_slug: String, pub match_id: String, } #[derive(Serialize)] pub struct MatchMetadataResponse { pub chunk_count: usize, pub chunk_duration_ms: u64, pub total_duration_ms: u64, } pub async fn match_chunk_action( State(_): State<GameAppData>, Path(route_params): Path<MatchChunkRequest>, ) -> ApiResult<Response> { let chunk_data = MatchStore::get_chunk( &route_params.league_slug, &route_params.match_id, route_params.chunk_number, ) .await .ok_or_else(|| { ApiError::NotFound(format!( "Chunk {} not found for match {}/{}", route_params.chunk_number, route_params.league_slug, route_params.match_id )) })?; let mut response = (StatusCode::OK, chunk_data).into_response(); response .headers_mut() .append( "Content-Type", "application/gzip" .parse() .map_err(|e| ApiError::InternalError(format!("Header parse error: {:?}", e)))?, ); response .headers_mut() .append( "Content-Encoding", "gzip" .parse() .map_err(|e| ApiError::InternalError(format!("Header parse error: {:?}", e)))?, ); Ok(response) } pub async fn match_metadata_action( State(_): State<GameAppData>, Path(route_params): Path<MatchMetadataRequest>, ) -> ApiResult<Response> { let metadata_json = MatchStore::get_metadata(&route_params.league_slug, &route_params.match_id) .await .ok_or_else(|| { ApiError::NotFound(format!( "Chunks not available for match {}/{}", route_params.league_slug, route_params.match_id )) })?; let metadata = MatchMetadataResponse { chunk_count: metadata_json["chunk_count"].as_u64().unwrap_or(1) as usize, chunk_duration_ms: metadata_json["chunk_duration_ms"].as_u64().unwrap_or(300_000), total_duration_ms: metadata_json["total_duration_ms"].as_u64().unwrap_or(0), }; Ok(Json(metadata).into_response()) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/routes.rs
src/server/src/match/routes.rs
use crate::r#match::chunk::{match_chunk_action, match_metadata_action}; use crate::GameAppData; use axum::routing::get; use axum::Router; use crate::r#match::get::match_get_action; pub fn match_routes() -> Router<GameAppData> { Router::new() .route("/api/match/{league_slug}/{match_id}", get(match_get_action)) .route("/api/match/{league_slug}/{match_id}/metadata", get(match_metadata_action)) .route("/api/match/{league_slug}/{match_id}/chunk/{chunk_number}", get(match_chunk_action)) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/get.rs
src/server/src/match/get.rs
use crate::{ApiError, ApiResult, GameAppData}; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use core::SimulatorData; use serde::{Deserialize, Serialize}; pub async fn match_get_action( State(state): State<GameAppData>, Path(route_params): Path<MatchGetRequest>, ) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard .as_ref() .ok_or_else(|| ApiError::InternalError("Simulator data not loaded".to_string()))?; let league_id = simulator_data .indexes .as_ref() .ok_or_else(|| ApiError::InternalError("Indexes not available".to_string()))? .slug_indexes .get_league_by_slug(&route_params.league_slug) .ok_or_else(|| ApiError::NotFound(format!("League '{}' not found", route_params.league_slug)))?; let league = simulator_data .league(league_id) .ok_or_else(|| ApiError::NotFound(format!("League with ID {} not found", league_id)))?; let match_result = league .matches .get(&route_params.match_id) .ok_or_else(|| ApiError::NotFound(format!("Match '{}' not found", route_params.match_id)))?; let home_team = simulator_data .team(match_result.home_team_id) .ok_or_else(|| ApiError::NotFound(format!("Home team not found")))?; let away_team = simulator_data .team(match_result.away_team_id) .ok_or_else(|| ApiError::NotFound(format!("Away team not found")))?; let result_details = match_result .details .as_ref() .ok_or_else(|| ApiError::NotFound("Match details not available".to_string()))?; let score = result_details .score .as_ref() .ok_or_else(|| ApiError::NotFound("Match score not available".to_string()))?; let goals: Vec<GoalEvent> = score .detail() .iter() .map(|goal| GoalEvent { player_id: goal.player_id, time: goal.time, is_auto_goal: goal.is_auto_goal, }) .collect(); let result = MatchGetResponse { score: MatchScore { home_goals: score.home_team.get(), away_goals: score.away_team.get() }, match_time_ms: result_details.match_time_ms, goals, home_team_name: &home_team.name, home_team_slug: &home_team.slug, home_squad: MatchSquad { main: result_details .left_team_players .main .iter() .filter_map(|player_id| to_match_player(*player_id, simulator_data)) .collect(), substitutes: result_details .left_team_players .substitutes .iter() .filter_map(|player_id| to_match_player(*player_id, simulator_data)) .collect(), }, away_team_name: &away_team.name, away_team_slug: &away_team.slug, away_squad: MatchSquad { main: result_details .right_team_players .main .iter() .filter_map(|player_id| to_match_player(*player_id, simulator_data)) .collect(), substitutes: result_details .right_team_players .substitutes .iter() .filter_map(|player_id| to_match_player(*player_id, simulator_data)) .collect(), }, }; Ok(Json(result).into_response()) } fn to_match_player( player_id: u32, simulator_data: &SimulatorData, ) -> Option<MatchPlayer<'_>> { let player = simulator_data.player(player_id)?; Some(MatchPlayer { id: player.id, shirt_number: player.shirt_number(), first_name: &player.full_name.first_name, last_name: &player.full_name.last_name, middle_name: player.full_name.middle_name.as_deref(), position: player.position().get_short_name(), }) } #[derive(Deserialize)] pub struct MatchGetRequest { pub league_slug: String, pub match_id: String, } #[derive(Serialize)] pub struct MatchGetResponse<'p> { // home pub home_team_name: &'p str, pub home_team_slug: &'p str, pub home_squad: MatchSquad<'p>, // away pub away_team_name: &'p str, pub away_team_slug: &'p str, pub away_squad: MatchSquad<'p>, pub match_time_ms: u64, pub score: MatchScore, pub goals: Vec<GoalEvent>, } #[derive(Serialize)] pub struct MatchScore { pub home_goals: u8, pub away_goals: u8, } #[derive(Serialize)] pub struct GoalEvent { pub player_id: u32, pub time: u64, pub is_auto_goal: bool, } #[derive(Serialize)] pub struct MatchSquad<'p> { pub main: Vec<MatchPlayer<'p>>, pub substitutes: Vec<MatchPlayer<'p>>, } #[derive(Serialize)] pub struct MatchPlayer<'p> { pub id: u32, pub shirt_number: u8, pub first_name: &'p str, pub last_name: &'p str, pub middle_name: Option<&'p str>, pub position: &'p str, }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/stores/match.rs
src/server/src/match/stores/match.rs
use async_compression::tokio::write::GzipEncoder; use core::r#match::{MatchResult, ResultMatchPositionData}; use log::{debug, info}; use std::path::PathBuf; use tokio::fs::File; use tokio::io::{AsyncReadExt, AsyncWriteExt}; const MATCH_DIRECTORY: &str = "matches"; const CHUNK_DURATION_MS: u64 = 300_000; // 5 minutes per chunk pub struct MatchStore; impl MatchStore { pub async fn get(league_slug: &str, match_id: &str) -> Vec<u8> { let match_file = PathBuf::from(MATCH_DIRECTORY) .join(league_slug) .join(format!("{}.json.gz", match_id)); let mut file = File::options().read(true).open(&match_file).await.unwrap(); let mut result = Vec::new(); file.read_to_end(&mut result) .await .expect(format!("failed to read match {}", match_id).as_str()); result } pub async fn get_chunk(league_slug: &str, match_id: &str, chunk_number: usize) -> Option<Vec<u8>> { let chunk_file = PathBuf::from(MATCH_DIRECTORY) .join(league_slug) .join(format!("{}_chunk_{}.json.gz", match_id, chunk_number)); let mut file = match File::options().read(true).open(&chunk_file).await { Ok(f) => f, Err(_) => { debug!("Chunk file not found: {}", chunk_file.display()); return None; } }; let mut result = Vec::new(); file.read_to_end(&mut result) .await .expect(&format!("failed to read chunk {} for match {}", chunk_number, match_id)); Some(result) } pub async fn get_metadata(league_slug: &str, match_id: &str) -> Option<serde_json::Value> { let metadata_file = PathBuf::from(MATCH_DIRECTORY) .join(league_slug) .join(format!("{}_metadata.json", match_id)); let mut file = match File::options().read(true).open(&metadata_file).await { Ok(f) => f, Err(_) => { debug!("Metadata file not found: {}", metadata_file.display()); return None; // No metadata means no chunks available } }; let mut contents = String::new(); file.read_to_string(&mut contents) .await .expect(&format!("failed to read metadata for match {}", match_id)); let metadata: serde_json::Value = serde_json::from_str(&contents) .expect("failed to parse metadata"); Some(metadata) } pub async fn store(result: MatchResult) { let out_dir = PathBuf::from(MATCH_DIRECTORY).join(&result.league_slug); if let Ok(_) = tokio::fs::create_dir_all(&out_dir).await{} let out_file = out_dir.join(format!("{}.json.gz", result.id)); let file = File::options() .write(true) .create(true) .truncate(true) .open(&out_file) .await .expect(&format!("failed to create file {}", out_file.display())); let mut compressed_file = GzipEncoder::with_quality(file, async_compression::Level::Best); if let Some(res) = result.details { //serialize and write compressed data let file_data = serde_json::to_vec(&res.position_data).expect("failed to serialize data"); compressed_file .write_all(&file_data) .await .expect("failed to write data"); compressed_file .write_all(b"\n") .await .expect("failed to write newline"); compressed_file .shutdown() .await .expect("failed to shutdown file"); // Store chunks Self::store_chunks(&result.league_slug, &result.id, &res.position_data).await; } } async fn store_chunks(league_slug: &str, match_id: &str, data: &ResultMatchPositionData) { let chunks = data.split_into_chunks(CHUNK_DURATION_MS); let chunk_count = chunks.len(); info!("Storing {} chunks for match {}", chunk_count, match_id); // Store each chunk for (idx, chunk) in chunks.iter().enumerate() { let chunk_file = PathBuf::from(MATCH_DIRECTORY) .join(league_slug) .join(format!("{}_chunk_{}.json.gz", match_id, idx)); let file = File::options() .write(true) .create(true) .truncate(true) .open(&chunk_file) .await .expect(&format!("failed to create chunk file {}", chunk_file.display())); let mut compressed_file = GzipEncoder::with_quality(file, async_compression::Level::Best); let chunk_data = serde_json::to_vec(&chunk).expect("failed to serialize chunk"); debug!("Chunk {} uncompressed size = {}", idx, chunk_data.len()); compressed_file .write_all(&chunk_data) .await .expect("failed to write chunk data"); compressed_file .shutdown() .await .expect("failed to shutdown chunk file"); } // Store metadata let metadata_file = PathBuf::from(MATCH_DIRECTORY) .join(league_slug) .join(format!("{}_metadata.json", match_id)); let metadata = serde_json::json!({ "chunk_count": chunk_count, "chunk_duration_ms": CHUNK_DURATION_MS, "total_duration_ms": data.max_timestamp() }); tokio::fs::write(&metadata_file, serde_json::to_string_pretty(&metadata).unwrap()) .await .expect(&format!("failed to write metadata file {}", metadata_file.display())); } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/match/stores/mod.rs
src/server/src/match/stores/mod.rs
pub mod r#match; pub use r#match::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/teams/schedule.rs
src/server/src/teams/schedule.rs
use crate::GameAppData; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use core::{SimulatorData, Team}; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct TeamScheduleGetRequest { team_slug: String, } #[derive(Serialize)] pub struct TeamScheduleViewModel<'t> { pub team_name: &'t str, pub team_slug: &'t str, pub league_slug: &'t str, pub league_name: &'t str, pub neighbor_teams: Vec<ClubTeam<'t>>, pub items: Vec<TeamScheduleItem<'t>>, } #[derive(Serialize)] pub struct TeamScheduleItem<'t> { pub date: String, pub time: String, pub opponent_slug: &'t str, pub opponent_name: &'t str, pub is_home: bool, pub competition_id: u32, pub competition_name: &'t str, pub result: Option<TeamScheduleItemResult<'t>>, } #[derive(Serialize)] pub struct TeamScheduleItemResult<'t> { pub match_id: &'t str, pub home_goals: u8, pub away_goals: u8, } #[derive(Serialize)] pub struct ClubTeam<'c> { pub slug: &'c str, pub name: &'c str, pub reputation: u16, } pub async fn team_schedule_get_action( State(state): State<GameAppData>, Path(route_params): Path<TeamScheduleGetRequest>, ) -> Response { let guard = state.data.read().await; let simulator_data = guard.as_ref().unwrap(); let team_id = simulator_data .indexes .as_ref() .unwrap() .slug_indexes .get_team_by_slug(&route_params.team_slug) .unwrap(); let team: &Team = simulator_data.team(team_id).unwrap(); let league = simulator_data.league(team.league_id).unwrap(); let schedule = league.schedule.get_matches_for_team(team.id); let model = TeamScheduleViewModel { team_name: &team.name, team_slug: &team.slug, league_slug: &league.slug, league_name: &league.name, neighbor_teams: get_neighbor_teams(team.club_id, simulator_data), items: schedule .iter() .map(|schedule| { let is_home = schedule.home_team_id == team.id; let home_team_data = simulator_data.team_data(schedule.home_team_id).unwrap(); let away_team_data = simulator_data.team_data(schedule.away_team_id).unwrap(); TeamScheduleItem { date: schedule.date.format("%d.%m.%Y").to_string(), time: schedule.date.format("%H:%M").to_string(), opponent_slug: if is_home { &away_team_data.slug } else { &home_team_data.slug }, opponent_name: if is_home { &away_team_data.name } else { &home_team_data.name }, is_home, competition_id: league.id, competition_name: &league.name, result: if schedule.result.is_some() { Some(TeamScheduleItemResult { match_id: &schedule.id, home_goals: schedule.result.as_ref().unwrap().home_team.get(), away_goals: schedule.result.as_ref().unwrap().away_team.get(), }) } else { None }, } }) .collect(), }; Json(model).into_response() } fn get_neighbor_teams(club_id: u32, data: &SimulatorData) -> Vec<ClubTeam<'_>> { let club = data.club(club_id).unwrap(); let mut teams: Vec<ClubTeam> = club .teams .teams .iter() .map(|team| ClubTeam { slug: &team.slug, name: &team.name, reputation: team.reputation.world, }) .collect(); teams.sort_by(|a, b| b.reputation.cmp(&a.reputation)); teams }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/teams/mod.rs
src/server/src/teams/mod.rs
mod get; pub mod routes; mod schedule; pub use get::*; pub use routes::*; pub use schedule::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/teams/routes.rs
src/server/src/teams/routes.rs
use crate::teams::{team_get_action, team_schedule_get_action}; use crate::GameAppData; use axum::routing::get; use axum::Router; pub fn team_routes() -> Router<GameAppData> { Router::new() .route("/api/teams/{team_slug}", get(team_get_action)) .route( "/api/teams/{team_slug}/schedule", get(team_schedule_get_action), ) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/teams/get.rs
src/server/src/teams/get.rs
use crate::{ApiError, ApiResult, GameAppData}; use crate::player::PlayerStatusDto; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use core::Player; use core::PlayerPositionType; use core::utils::FormattingUtils; use core::{SimulatorData, Team}; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct TeamGetRequest { pub team_slug: String, } #[derive(Serialize)] pub struct TeamGetViewModel<'c> { pub slug: &'c str, pub name: &'c str, pub league_slug: &'c str, pub league_name: &'c str, pub balance: TeamBalance, pub players: Vec<TeamPlayer<'c>>, pub neighbor_teams: Vec<ClubTeam<'c>>, } #[derive(Serialize)] pub struct ClubTeam<'c> { pub slug: &'c str, pub name: &'c str, pub reputation: u16, } #[derive(Serialize)] pub struct TeamBalance { pub amount: i32, pub income: i32, pub outcome: i32, } #[derive(Serialize)] pub struct TeamPlayer<'cp> { pub id: u32, pub last_name: &'cp str, pub first_name: &'cp str, pub behaviour: &'cp str, pub position: String, pub position_sort: PlayerPositionType, pub value: String, pub injured: bool, pub country_slug: &'cp str, pub country_code: &'cp str, pub country_name: &'cp str, pub conditions: u8, pub current_ability: u8, pub potential_ability: u8, pub status: PlayerStatusDto, } pub async fn team_get_action( State(state): State<GameAppData>, Path(route_params): Path<TeamGetRequest>, ) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard .as_ref() .ok_or_else(|| ApiError::InternalError("Simulator data not loaded".to_string()))?; let indexes = simulator_data .indexes .as_ref() .ok_or_else(|| ApiError::InternalError("Indexes not available".to_string()))?; let team_id = indexes .slug_indexes .get_team_by_slug(&route_params.team_slug) .ok_or_else(|| ApiError::NotFound(format!("Team '{}' not found", route_params.team_slug)))?; let team: &Team = simulator_data .team(team_id) .ok_or_else(|| ApiError::NotFound(format!("Team with ID {} not found", team_id)))?; let league = simulator_data .league(team.league_id) .ok_or_else(|| ApiError::NotFound(format!("League with ID {} not found", team.league_id)))?; let now = simulator_data.date.date(); let mut players: Vec<TeamPlayer> = team .players() .iter() .map(|p| { if let Some(country) = simulator_data.country(p.country_id) { let position = p.positions.display_positions().join(", "); Some(TeamPlayer { id: p.id, first_name: &p.full_name.first_name, position_sort: p.position(), position, behaviour: p.behaviour.as_str(), injured: p.player_attributes.is_injured, country_slug: &country.slug, country_code: &country.code, country_name: &country.name, last_name: &p.full_name.last_name, conditions: get_conditions(p), value: FormattingUtils::format_money(p.value(now)), current_ability: get_current_ability_stars(p), potential_ability: get_potential_ability_stars(p), status: PlayerStatusDto::new(p.statuses.get()), }) } else { None } }) .filter_map(|x| x) // Remove None values .collect(); // Use a stable sorting method that doesn't panic players.sort_by(|a, b| a.position_sort.partial_cmp(&b.position_sort).unwrap_or(std::cmp::Ordering::Equal)); let neighbor_teams = get_neighbor_teams(team.club_id, simulator_data)?; let model = TeamGetViewModel { slug: &team.slug, name: &team.name, league_slug: &league.slug, league_name: &league.name, balance: TeamBalance { amount: 0, income: 0, outcome: 0, }, players, neighbor_teams, }; Ok(Json(model).into_response()) } fn get_neighbor_teams(club_id: u32, data: &SimulatorData) -> Result<Vec<ClubTeam<'_>>, ApiError> { let club = data.club(club_id) .ok_or_else(|| ApiError::InternalError(format!("Club with ID {} not found", club_id)))?; let mut teams: Vec<ClubTeam> = club .teams .teams .iter() .map(|team| ClubTeam { slug: &team.slug, name: &team.name, reputation: team.reputation.world, }) .collect(); teams.sort_by(|a, b| b.reputation.cmp(&a.reputation)); Ok(teams) } pub fn get_conditions(player: &Player) -> u8 { (100f32 * ((player.player_attributes.condition as f32) / 10000.0)) as u8 } pub fn get_current_ability_stars(player: &Player) -> u8 { (5.0f32 * ((player.player_attributes.current_ability as f32) / 200.0)) as u8 } pub fn get_potential_ability_stars(player: &Player) -> u8 { (5.0f32 * ((player.player_attributes.potential_ability as f32) / 200.0)) as u8 }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/date/current_date.rs
src/server/src/date/current_date.rs
use crate::GameAppData; use axum::extract::State; use axum::response::{IntoResponse, Response}; use axum::Json; use chrono::Utc; use serde::Serialize; #[derive(Serialize)] pub struct CurrentDateModel { pub date: String, pub time: String, } pub async fn current_date_action(State(state): State<GameAppData>) -> Response { let data = state.data.read().await; let date = match data.as_ref() { None => Utc::now().naive_utc(), Some(data) => data.date, }; let model = CurrentDateModel { date: date.format("%d %b %Y").to_string(), time: date.format("%a %R").to_string(), }; Json(model).into_response() }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/date/mod.rs
src/server/src/date/mod.rs
pub mod current_date; pub mod routes; pub use current_date::*; pub use routes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/date/routes.rs
src/server/src/date/routes.rs
use crate::date::current_date_action; use crate::GameAppData; use axum::routing::get; use axum::Router; pub fn current_date_routes() -> Router<GameAppData> { Router::new().route("/api/date", get(current_date_action)) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/countries/list.rs
src/server/src/countries/list.rs
use crate::{ApiError, ApiResult, GameAppData}; use axum::extract::State; use axum::response::{IntoResponse, Response}; use axum::Json; use serde::Serialize; #[derive(Serialize)] pub struct CountryListViewModel<'c> { pub name: &'c str, pub countries: Vec<CountryDto<'c>>, } #[derive(Serialize)] pub struct CountryDto<'c> { pub slug: &'c str, pub code: &'c str, pub name: &'c str, pub leagues: Vec<LeagueDto<'c>>, } #[derive(Serialize)] pub struct LeagueDto<'l> { pub slug: &'l str, pub name: &'l str, } pub async fn country_list_action(State(state): State<GameAppData>) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard .as_ref() .ok_or_else(|| ApiError::InternalError("Simulator data not loaded".to_string()))?; let mut model = Vec::with_capacity(simulator_data.continents.len()); for continent in &simulator_data.continents { let item = CountryListViewModel { name: &continent.name, countries: continent .countries .iter() .filter(|c| c.leagues.leagues.len() > 0) .map(|country| CountryDto { slug: &country.slug, code: &country.code, name: &country.name, leagues: country .leagues .leagues .iter() .map(|l| LeagueDto { slug: &l.slug, name: &l.name, }) .collect(), }) .collect(), }; model.push(item); } Ok(Json(model).into_response()) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/countries/mod.rs
src/server/src/countries/mod.rs
mod get; mod list; pub mod routes; pub use get::*; pub use list::*; pub use routes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/countries/routes.rs
src/server/src/countries/routes.rs
use crate::countries::{country_get_action, country_list_action}; use crate::GameAppData; use axum::routing::get; use axum::Router; pub fn country_routes() -> Router<GameAppData> { Router::new() .route("/api/countries", get(country_list_action)) .route("/api/countries/{country_slug}", get(country_get_action)) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/countries/get.rs
src/server/src/countries/get.rs
use crate::{ApiError, ApiResult, GameAppData}; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use core::Country; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct CountryGetRequest { country_slug: String, } #[derive(Serialize)] pub struct CountryGetViewModel<'c> { pub slug: &'c str, pub name: &'c str, pub code: &'c str, pub continent_name: &'c str, pub leagues: Vec<LeagueDto<'c>>, } #[derive(Serialize)] pub struct LeagueDto<'l> { pub slug: &'l str, pub name: &'l str, } pub async fn country_get_action( State(state): State<GameAppData>, Path(route_params): Path<CountryGetRequest>, ) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard .as_ref() .ok_or_else(|| ApiError::InternalError("Simulator data not loaded".to_string()))?; let indexes = simulator_data .indexes .as_ref() .ok_or_else(|| ApiError::InternalError("Indexes not available".to_string()))?; let country_id = indexes .slug_indexes .get_country_by_slug(&route_params.country_slug) .ok_or_else(|| ApiError::NotFound(format!("Country '{}' not found", route_params.country_slug)))?; let country: &Country = simulator_data .continents .iter() .flat_map(|c| &c.countries) .find(|country| country.id == country_id) .ok_or_else(|| ApiError::NotFound(format!("Country with ID {} not found in continents", country_id)))?; let continent = simulator_data .continent(country.continent_id) .ok_or_else(|| ApiError::NotFound(format!("Continent with ID {} not found", country.continent_id)))?; let model = CountryGetViewModel { slug: &country.slug, name: &country.name, code: &country.code, continent_name: &continent.name, leagues: country .leagues .leagues .iter() .map(|l| LeagueDto { slug: &l.slug, name: &l.name, }) .collect(), }; Ok(Json(model).into_response()) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/leagues/mod.rs
src/server/src/leagues/mod.rs
mod get; pub mod routes; pub use get::*; pub use routes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/leagues/routes.rs
src/server/src/leagues/routes.rs
use crate::leagues::league_get_action; use crate::GameAppData; use axum::routing::get; use axum::Router; pub fn league_routes() -> Router<GameAppData> { Router::new().route("/api/leagues/{league_slug}", get(league_get_action)) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/leagues/get.rs
src/server/src/leagues/get.rs
use crate::{ApiError, ApiResult, GameAppData}; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use chrono::Duration; use core::league::ScheduleTour; use itertools::*; use serde::{Deserialize, Serialize}; use core::r#match::Score; use core::r#match::player::statistics::MatchStatisticType; use core::r#match::GoalDetail; #[derive(Deserialize)] pub struct LeagueGetRequest { pub league_slug: String, } #[derive(Serialize)] pub struct LeagueGetViewModel<'l> { pub id: u32, pub name: &'l str, pub slug: &'l str, pub country_slug: &'l str, pub country_name: &'l str, pub table: LeagueTableDto<'l>, pub current_tour_schedule: Vec<TourSchedule<'l>>, } #[derive(Serialize)] pub struct TourSchedule<'s> { pub date: String, pub matches: Vec<LeagueScheduleItem<'s>>, } #[derive(Serialize)] pub struct LeagueScheduleItem<'si> { pub match_id: &'si str, pub home_team_id: u32, pub home_team_name: &'si str, pub home_team_slug: &'si str, pub away_team_id: u32, pub away_team_name: &'si str, pub away_team_slug: &'si str, pub result: Option<LeagueScheduleItemResult>, } #[derive(Serialize)] pub struct LeagueScheduleItemResult { pub home_goals: u8, pub home_goalscorers: Vec<LeagueTableGoalscorer>, pub away_goals: u8, pub away_goalscorers: Vec<LeagueTableGoalscorer>, } impl From<&Score> for LeagueScheduleItemResult { fn from(value: &Score) -> Self { todo!() } } #[derive(Serialize)] pub struct LeagueTableGoalscorer { pub id: u32, pub name: String, pub time: String, pub auto_goal: bool } #[derive(Serialize)] pub struct LeagueTableDto<'l> { pub rows: Vec<LeagueTableRow<'l>>, } #[derive(Serialize)] pub struct LeagueTableRow<'l> { pub team_id: u32, pub team_name: &'l str, pub team_slug: &'l str, pub played: u8, pub win: u8, pub draft: u8, pub lost: u8, pub goal_scored: i32, pub goal_concerned: i32, pub points: u8, } pub async fn league_get_action( State(state): State<GameAppData>, Path(route_params): Path<LeagueGetRequest>, ) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard.as_ref().unwrap(); let league_id = simulator_data .indexes .as_ref() .unwrap() .slug_indexes .get_league_by_slug(&route_params.league_slug) .ok_or_else(|| ApiError::NotFound(format!("League with slug {} not found", route_params.league_slug)))?; let league = simulator_data.league(league_id).unwrap(); let country = simulator_data.country(league.country_id).unwrap(); let league_table = league.table.get(); let mut model = LeagueGetViewModel { id: league.id, name: &league.name, slug: &league.slug, country_slug: &country.slug, country_name: &country.name, table: LeagueTableDto { rows: league_table .iter() .map(|t| { let team_data = simulator_data.team_data(t.team_id).unwrap(); LeagueTableRow { team_id: t.team_id, team_name: &team_data.name, team_slug: &team_data.slug, played: t.played, win: t.win, draft: t.draft, lost: t.lost, goal_scored: t.goal_scored, goal_concerned: t.goal_concerned, points: t.points, } }) .collect(), }, current_tour_schedule: Vec::new(), }; let now = simulator_data.date.date() + Duration::days(3); let mut current_tour: Option<&ScheduleTour> = None; for tour in league.schedule.tours.iter() { if now >= tour.start_date() && now <= tour.end_date() { current_tour = Some(tour); } } if current_tour.is_none() { for tour in league.schedule.tours.iter() { if now >= tour.end_date() { current_tour = Some(tour); } } } if current_tour.is_some() { for (key, group) in &current_tour .as_ref() .unwrap() .items .iter() .chunk_by(|t| t.date.date()) { let tour_schedule = TourSchedule { date: key.format("%d.%m.%Y").to_string(), matches: group .map(|item| { let home_team_data = simulator_data.team_data(item.home_team_id).unwrap(); let home_team = simulator_data.team(item.home_team_id).unwrap(); let away_team_data = simulator_data.team_data(item.away_team_id).unwrap(); let away_team = simulator_data.team(item.away_team_id).unwrap(); LeagueScheduleItem { match_id: &item.id, result: item.result.as_ref().map(|res| { let details: Vec<&GoalDetail> = res.details.iter() .filter(|detail| detail.stat_type == MatchStatisticType::Goal) .collect(); return LeagueScheduleItemResult { home_goals: if item.home_team_id == res.home_team.team_id { res.home_team.get() } else { res.away_team.get() }, home_goalscorers: details.iter().filter_map(|detail| { let player = simulator_data.player(detail.player_id).unwrap(); if home_team.players.contains(player.id) { Some(LeagueTableGoalscorer { id: detail.player_id, name: player.full_name.to_string(), time: format!("('{})", Duration::new((detail.time / 1000) as i64, 0).unwrap().num_minutes()), auto_goal: detail.is_auto_goal }) } else { None } }).collect(), away_goals: if item.away_team_id == res.away_team.team_id { res.away_team.get() } else { res.home_team.get() }, away_goalscorers: details.iter().filter_map(|detail| { let player = simulator_data.player(detail.player_id).unwrap(); if away_team.players.contains(player.id) { Some(LeagueTableGoalscorer { id: detail.player_id, name: player.full_name.to_string(), time: format!("('{})", Duration::new((detail.time / 1000) as i64, 0).unwrap().num_minutes()), auto_goal: detail.is_auto_goal }) } else { None } }).collect(), } }), home_team_id: item.home_team_id, home_team_name: &simulator_data .team_data(item.home_team_id) .unwrap() .name, home_team_slug: &home_team_data.slug, away_team_id: item.away_team_id, away_team_name: &simulator_data .team_data(item.away_team_id) .unwrap() .name, away_team_slug: &away_team_data.slug, } }) .collect(), }; model.current_tour_schedule.push(tour_schedule) } } Ok(Json(model).into_response()) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/game/process.rs
src/server/src/game/process.rs
use crate::r#match::stores::MatchStore; use crate::GameAppData; use axum::extract::State; use axum::http::{StatusCode}; use axum::response::IntoResponse; use axum::Json; use core::FootballSimulator; use core::SimulationResult; use log::{debug}; use std::sync::Arc; use std::time::Instant; use tokio::task::JoinSet; pub async fn game_process_action(State(state): State<GameAppData>) -> impl IntoResponse { let data = Arc::clone(&state.data); let mut simulator_data_guard = data.write_owned().await; let result = tokio::task::spawn_blocking(move || { let simulator_data = simulator_data_guard.as_mut().unwrap(); if state.is_one_shot_game && simulator_data.match_played { return; } let result = FootballSimulator::simulate(simulator_data); if result.has_match_results() { tokio::task::spawn(async { write_match_results(result).await }); simulator_data.match_played = true; } }) .await; if let Ok(res) = result { (StatusCode::OK, Json(())) } else { (StatusCode::BAD_REQUEST, Json(())) } } async fn write_match_results(result: SimulationResult) { let mut tasks = JoinSet::new(); for match_result in result.match_results { tasks.spawn(MatchStore::store(match_result)); } let now = Instant::now(); tasks.join_all().await; let elapsed = now.elapsed().as_millis(); debug!("match results stored in {} ms", elapsed); }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/game/mod.rs
src/server/src/game/mod.rs
mod create; mod process; pub mod routes; pub use create::*; pub use process::*; pub use routes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/game/routes.rs
src/server/src/game/routes.rs
use crate::game::{game_create_action, game_process_action}; use crate::GameAppData; use axum::routing::{get, post}; use axum::Router; pub fn game_routes() -> Router<GameAppData> { Router::new() .route("/api/game/create", get(game_create_action)) .route("/api/game/process", post(game_process_action)) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/game/create.rs
src/server/src/game/create.rs
use crate::GameAppData; use axum::extract::State; use axum::http::{HeaderMap, StatusCode}; use axum::response::IntoResponse; use axum::Json; use core::utils::TimeEstimation; use database::DatabaseGenerator; pub async fn game_create_action(State(state): State<GameAppData>) -> impl IntoResponse { let mut state_data = state.data.write().await; let cloned_state = GameAppData::clone(&state); let generation_result = tokio::task::spawn_blocking(move || { let (generated_data, estimated) = TimeEstimation::estimate(|| DatabaseGenerator::generate(&cloned_state.database)); (generated_data, estimated) }) .await; let (data, estimated) = generation_result.unwrap(); *state_data = Some(data); let mut headers = HeaderMap::new(); headers.insert("Location", "/".parse().unwrap()); headers.insert("Estimated", estimated.to_string().parse().unwrap()); (StatusCode::OK, headers, Json(())) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/player/mod.rs
src/server/src/player/mod.rs
mod get; pub mod routes; pub use get::*; pub use routes::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/player/routes.rs
src/server/src/player/routes.rs
use crate::player::player_get_action; use crate::GameAppData; use axum::routing::get; use axum::Router; pub fn player_routes() -> Router<GameAppData> { Router::new().route( "/api/teams/{team_slug}/players/{player_id}", get(player_get_action), ) }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/server/src/player/get.rs
src/server/src/player/get.rs
use crate::{ApiError, ApiResult, GameAppData}; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum::Json; use core::Player; use core::PlayerStatusType; use core::utils::FormattingUtils; use core::SimulatorData; use core::Team; use itertools::Itertools; use serde::{Deserialize, Serialize}; use core::Person; #[derive(Deserialize)] pub struct PlayerGetRequest { pub team_slug: String, pub player_id: u32, } #[derive(Serialize)] pub struct PlayerGetViewModel<'p> { pub id: u32, pub first_name: &'p str, pub last_name: &'p str, pub middle_name: Option<&'p str>, pub position: &'p str, pub contract: Option<PlayerContractDto>, pub birth_date: String, pub age: u8, pub team_slug: &'p str, pub team_name: &'p str, pub country_slug: &'p str, pub country_code: &'p str, pub country_name: &'p str, pub skills: PlayerSkillsDto, pub conditions: u8, pub current_ability: u8, pub potential_ability: u8, pub value: &'p str, pub preferred_foot: &'p str, pub player_attributes: PlayerAttributesDto, pub neighbor_teams: Vec<ClubTeam<'p>>, pub statistics: PlayerStatistics, pub status: PlayerStatusDto, } #[derive(Serialize)] pub struct PlayerStatistics { pub played: u16, pub played_subs: u16, pub goals: u16, pub assists: u16, pub penalties: u16, pub player_of_the_match: u8, pub yellow_cards: u8, pub red_cards: u8, pub shots_on_target: f32, pub tackling: f32, pub passes: u8, pub average_rating: f32, } #[derive(Serialize)] pub struct ClubTeam<'c> { pub name: &'c str, pub slug: &'c str, pub reputation: u16, } #[derive(Serialize)] pub struct PlayerContractDto { pub salary: u32, pub expiration: String, pub squad_status: String, } #[derive(Serialize)] pub struct PlayerSkillsDto { pub technical: TechnicalDto, pub mental: MentalDto, pub physical: PhysicalDto, } #[derive(Serialize)] pub struct TechnicalDto { pub corners: u8, pub crossing: u8, pub dribbling: u8, pub finishing: u8, pub first_touch: u8, pub free_kick_taking: u8, pub heading: u8, pub long_shots: u8, pub long_throws: u8, pub marking: u8, pub passing: u8, pub penalty_taking: u8, pub tackling: u8, pub technique: u8, } #[derive(Serialize)] pub struct MentalDto { pub aggression: u8, pub anticipation: u8, pub bravery: u8, pub composure: u8, pub concentration: u8, pub decisions: u8, pub determination: u8, pub flair: u8, pub leadership: u8, pub off_the_ball: u8, pub positioning: u8, pub teamwork: u8, pub vision: u8, pub work_rate: u8, } #[derive(Serialize)] pub struct PhysicalDto { pub acceleration: u8, pub agility: u8, pub balance: u8, pub jumping_reach: u8, pub natural_fitness: u8, pub pace: u8, pub stamina: u8, pub strength: u8, pub match_readiness: u8, } #[derive(Serialize)] pub struct PlayerAttributesDto { pub international_apps: u16, pub international_goals: u16, pub under_21_international_apps: u16, pub under_21_international_goals: u16, } #[derive(Serialize)] pub struct PlayerStatusDto { pub statuses: Vec<PlayerStatusType>, } impl PlayerStatusDto { pub fn new(statuses: Vec<PlayerStatusType>) -> Self { PlayerStatusDto { statuses } } pub fn is_wanted(&self) -> bool { self.statuses.iter().contains(&PlayerStatusType::Wnt) } } pub async fn player_get_action( State(state): State<GameAppData>, Path(route_params): Path<PlayerGetRequest>, ) -> ApiResult<Response> { let guard = state.data.read().await; let simulator_data = guard .as_ref() .ok_or_else(|| ApiError::InternalError("Simulator data not loaded".to_string()))?; let indexes = simulator_data .indexes .as_ref() .ok_or_else(|| ApiError::InternalError("Indexes not available".to_string()))?; let team_id = indexes .slug_indexes .get_team_by_slug(&route_params.team_slug) .ok_or_else(|| ApiError::NotFound(format!("Team '{}' not found", route_params.team_slug)))?; let team: &Team = simulator_data .team(team_id) .ok_or_else(|| ApiError::NotFound(format!("Team with ID {} not found", team_id)))?; let player: &Player = team .players .players() .iter() .find(|p| p.id == route_params.player_id) .ok_or_else(|| ApiError::NotFound(format!("Player with ID {} not found in team", route_params.player_id)))?; let country = simulator_data .country(player.country_id) .ok_or_else(|| ApiError::NotFound(format!("Country with ID {} not found", player.country_id)))?; let now = simulator_data.date.date(); let neighbor_teams = get_neighbor_teams(team.club_id, simulator_data)?; let mut model = PlayerGetViewModel { id: player.id, first_name: &player.full_name.first_name, last_name: &player.full_name.last_name, middle_name: player.full_name.middle_name.as_deref(), position: player.position().get_short_name(), contract: None, birth_date: player.birth_date.format("%d.%m.%Y").to_string(), age: player.age(simulator_data.date.date()), team_slug: &team.slug, team_name: &team.name, country_slug: &country.slug, country_code: &country.code, country_name: &country.name, skills: get_skills(player), conditions: get_conditions(player), current_ability: get_current_ability_stars(player), potential_ability: get_potential_ability_stars(player), value: &FormattingUtils::format_money(player.value(now)), preferred_foot: player.preferred_foot_str(), player_attributes: get_attributes(player), neighbor_teams, statistics: get_statistics(player), status: PlayerStatusDto::new(player.statuses.get()), }; if let Some(contract) = &player.contract { model.contract = Some(PlayerContractDto { salary: (contract.salary / 1000), expiration: contract.expiration.format("%d.%m.%Y").to_string(), squad_status: String::from("First team player"), }); } Ok(Json(model).into_response()) } fn get_attributes(player: &Player) -> PlayerAttributesDto { PlayerAttributesDto { international_apps: player.player_attributes.international_apps, international_goals: player.player_attributes.international_goals, under_21_international_apps: player.player_attributes.under_21_international_apps, under_21_international_goals: player.player_attributes.under_21_international_goals, } } fn get_skills(player: &Player) -> PlayerSkillsDto { PlayerSkillsDto { technical: TechnicalDto { corners: player.skills.technical.corners.floor() as u8, crossing: player.skills.technical.crossing.floor() as u8, dribbling: player.skills.technical.dribbling.floor() as u8, finishing: player.skills.technical.finishing.floor() as u8, first_touch: player.skills.technical.first_touch.floor() as u8, free_kick_taking: player.skills.technical.free_kicks.floor() as u8, heading: player.skills.technical.heading.floor() as u8, long_shots: player.skills.technical.long_shots.floor() as u8, long_throws: player.skills.technical.long_throws.floor() as u8, marking: player.skills.technical.marking.floor() as u8, passing: player.skills.technical.passing.floor() as u8, penalty_taking: player.skills.technical.penalty_taking.floor() as u8, tackling: player.skills.technical.tackling.floor() as u8, technique: player.skills.technical.technique.floor() as u8, }, mental: MentalDto { aggression: player.skills.mental.aggression.floor() as u8, anticipation: player.skills.mental.anticipation.floor() as u8, bravery: player.skills.mental.bravery.floor() as u8, composure: player.skills.mental.composure.floor() as u8, concentration: player.skills.mental.concentration.floor() as u8, decisions: player.skills.mental.decisions.floor() as u8, determination: player.skills.mental.determination.floor() as u8, flair: player.skills.mental.flair.floor() as u8, leadership: player.skills.mental.leadership.floor() as u8, off_the_ball: player.skills.mental.off_the_ball.floor() as u8, positioning: player.skills.mental.positioning.floor() as u8, teamwork: player.skills.mental.teamwork.floor() as u8, vision: player.skills.mental.vision.floor() as u8, work_rate: player.skills.mental.work_rate.floor() as u8, }, physical: PhysicalDto { acceleration: player.skills.physical.acceleration.floor() as u8, agility: player.skills.physical.agility.floor() as u8, balance: player.skills.physical.balance.floor() as u8, jumping_reach: player.skills.physical.jumping.floor() as u8, natural_fitness: player.skills.physical.natural_fitness.floor() as u8, pace: player.skills.physical.pace.floor() as u8, stamina: player.skills.physical.stamina.floor() as u8, strength: player.skills.physical.strength.floor() as u8, match_readiness: player.skills.physical.match_readiness.floor() as u8, }, } } fn get_neighbor_teams(club_id: u32, data: &SimulatorData) -> Result<Vec<ClubTeam<'_>>, ApiError> { let club = data.club(club_id) .ok_or_else(|| ApiError::InternalError(format!("Club with ID {} not found", club_id)))?; let mut teams: Vec<ClubTeam> = club .teams .teams .iter() .map(|team| ClubTeam { name: &team.name, slug: &team.slug, reputation: team.reputation.world, }) .collect(); teams.sort_by(|a, b| b.reputation.cmp(&a.reputation)); Ok(teams) } fn get_statistics(player: &Player) -> PlayerStatistics { PlayerStatistics { played: player.statistics.played, played_subs: player.statistics.played_subs, goals: player.statistics.goals, assists: player.statistics.assists, penalties: player.statistics.penalties, player_of_the_match: player.statistics.player_of_the_match, yellow_cards: player.statistics.yellow_cards, red_cards: player.statistics.red_cards, shots_on_target: player.statistics.shots_on_target, tackling: player.statistics.tackling, passes: player.statistics.passes, average_rating: player.statistics.average_rating, } } pub fn get_conditions(player: &Player) -> u8 { (100f32 * ((player.player_attributes.condition as f32) / 10000.0)) as u8 } pub fn get_current_ability_stars(player: &Player) -> u8 { (5.0f32 * ((player.player_attributes.current_ability as f32) / 200.0)) as u8 } pub fn get_potential_ability_stars(player: &Player) -> u8 { (5.0f32 * ((player.player_attributes.potential_ability as f32) / 200.0)) as u8 }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/lib.rs
src/database/src/lib.rs
mod generators; mod loaders; pub use loaders::{ ClubEntity, ClubLoader, ContinentEntity, ContinentLoader, CountryEntity, CountryLoader, LeagueEntity, LeagueLoader, NamesByCountryEntity, NamesByCountryLoader, }; pub use generators::DatabaseGenerator; pub struct DatabaseEntity { pub continents: Vec<ContinentEntity>, pub countries: Vec<CountryEntity>, pub leagues: Vec<LeagueEntity>, pub clubs: Vec<ClubEntity>, pub names_by_country: Vec<NamesByCountryEntity>, } pub struct DatabaseLoader; impl DatabaseLoader { pub fn load() -> DatabaseEntity { DatabaseEntity { continents: ContinentLoader::load(), countries: CountryLoader::load(), leagues: LeagueLoader::load(), clubs: ClubLoader::load(), names_by_country: NamesByCountryLoader::load(), } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/generators/player.rs
src/database/src/generators/player.rs
use chrono::{Datelike, NaiveDate, Utc}; use core::shared::FullName; use core::utils::{FloatUtils, IntegerUtils, StringUtils}; use core::{ Mental, PeopleNameGeneratorData, PersonAttributes, Physical, Player, PlayerAttributes, PlayerClubContract, PlayerPosition, PlayerPositionType, PlayerPositions, PlayerSkills, Technical, }; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{LazyLock}; static PLAYER_ID_SEQUENCE: LazyLock<AtomicU32> = LazyLock::new(|| AtomicU32::new(1)); pub struct PlayerGenerator { people_names_data: PeopleNameGeneratorData, } impl PlayerGenerator { pub fn with_people_names(people_names: &PeopleNameGeneratorData) -> Self { PlayerGenerator { people_names_data: PeopleNameGeneratorData { first_names: people_names.first_names.clone(), last_names: people_names.last_names.clone(), }, } } } pub enum PositionType { Goalkeeper, Defender, Midfielder, Striker, } impl PlayerGenerator { pub fn generate(&mut self, country_id: u32, position: PositionType) -> Player { let now = Utc::now(); let year = IntegerUtils::random(now.year() - 35, now.year() - 15) as u32; let month = IntegerUtils::random(1, 12) as u32; let day = IntegerUtils::random(1, 29) as u32; Player::builder() .id(PLAYER_ID_SEQUENCE.fetch_add(1, Ordering::SeqCst)) .full_name(FullName::with_full( self.generate_first_name(), self.generate_last_name(), StringUtils::random_string(17), )) .birth_date(NaiveDate::from_ymd_opt(year as i32, month, day).unwrap()) .country_id(country_id) .skills(Self::generate_skills()) .attributes(Self::generate_person_attributes()) .player_attributes(Self::generate_player_attributes()) .contract(Some(PlayerClubContract::new( IntegerUtils::random(1000, 200000) as u32, NaiveDate::from_ymd_opt(now.year() + IntegerUtils::random(1, 5), 3, 14).unwrap(), ))) .positions(Self::generate_positions(position)) .build() .expect("Failed to build Player") } fn generate_skills() -> PlayerSkills { PlayerSkills { technical: Technical { corners: FloatUtils::random(1.0, 20.0), crossing: FloatUtils::random(1.0, 20.0), dribbling: FloatUtils::random(1.0, 20.0), finishing: FloatUtils::random(1.0, 20.0), first_touch: FloatUtils::random(1.0, 20.0), free_kicks: FloatUtils::random(1.0, 20.0), heading: FloatUtils::random(1.0, 20.0), long_shots: FloatUtils::random(1.0, 20.0), long_throws: FloatUtils::random(1.0, 20.0), marking: FloatUtils::random(1.0, 20.0), passing: FloatUtils::random(1.0, 20.0), penalty_taking: FloatUtils::random(1.0, 20.0), tackling: FloatUtils::random(1.0, 20.0), technique: FloatUtils::random(1.0, 20.0), }, mental: Mental { aggression: FloatUtils::random(1.0, 20.0), anticipation: FloatUtils::random(1.0, 20.0), bravery: FloatUtils::random(1.0, 20.0), composure: FloatUtils::random(1.0, 20.0), concentration: FloatUtils::random(1.0, 20.0), decisions: FloatUtils::random(1.0, 20.0), determination: FloatUtils::random(1.0, 20.0), flair: FloatUtils::random(1.0, 20.0), leadership: FloatUtils::random(1.0, 20.0), off_the_ball: FloatUtils::random(1.0, 20.0), positioning: FloatUtils::random(1.0, 20.0), teamwork: FloatUtils::random(1.0, 20.0), vision: FloatUtils::random(1.0, 20.0), work_rate: FloatUtils::random(1.0, 20.0), }, physical: Physical { acceleration: FloatUtils::random(1.0, 20.0), agility: FloatUtils::random(1.0, 20.0), balance: FloatUtils::random(1.0, 20.0), jumping: FloatUtils::random(1.0, 20.0), natural_fitness: FloatUtils::random(1.0, 20.0), pace: FloatUtils::random(1.0, 20.0), stamina: FloatUtils::random(1.0, 20.0), strength: FloatUtils::random(1.0, 20.0), match_readiness: FloatUtils::random(1.0, 20.0), }, } } fn generate_positions(position: PositionType) -> PlayerPositions { let mut positions = Vec::with_capacity(5); match position { PositionType::Goalkeeper => positions.push(PlayerPosition { position: PlayerPositionType::Goalkeeper, level: 20, }), PositionType::Defender => match IntegerUtils::random(0, 5) { 0 => { positions.push(PlayerPosition { position: PlayerPositionType::DefenderLeft, level: 20, }); } 1 => { positions.push(PlayerPosition { position: PlayerPositionType::DefenderCenterLeft, level: 20, }); } 2 => { positions.push(PlayerPosition { position: PlayerPositionType::DefenderCenter, level: 20, }); } 3 => { positions.push(PlayerPosition { position: PlayerPositionType::DefenderCenterRight, level: 20, }); } 4 => { positions.push(PlayerPosition { position: PlayerPositionType::DefenderRight, level: 20, }); } _ => {} }, PositionType::Midfielder => match IntegerUtils::random(0, 7) { 0 => { positions.push(PlayerPosition { position: PlayerPositionType::MidfielderLeft, level: 20, }); } 1 => { positions.push(PlayerPosition { position: PlayerPositionType::MidfielderCenterLeft, level: 20, }); } 2 => { positions.push(PlayerPosition { position: PlayerPositionType::MidfielderCenter, level: 20, }); } 3 => { positions.push(PlayerPosition { position: PlayerPositionType::MidfielderCenterRight, level: 20, }); } 4 => { positions.push(PlayerPosition { position: PlayerPositionType::MidfielderRight, level: 20, }); } 5 => { positions.push(PlayerPosition { position: PlayerPositionType::WingbackLeft, level: 20, }); } 6 => { positions.push(PlayerPosition { position: PlayerPositionType::WingbackRight, level: 20, }); } _ => {} }, PositionType::Striker => match IntegerUtils::random(0, 4) { 0 => { positions.push(PlayerPosition { position: PlayerPositionType::Striker, level: 20, }); } 1 => { positions.push(PlayerPosition { position: PlayerPositionType::ForwardLeft, level: 20, }); } 2 => { positions.push(PlayerPosition { position: PlayerPositionType::ForwardCenter, level: 20, }); } 3 => { positions.push(PlayerPosition { position: PlayerPositionType::ForwardRight, level: 20, }); } _ => {} }, } PlayerPositions { positions } } fn generate_person_attributes() -> PersonAttributes { PersonAttributes { adaptability: FloatUtils::random(0.0f32, 20.0f32), ambition: FloatUtils::random(0.0f32, 20.0f32), controversy: FloatUtils::random(0.0f32, 20.0f32), loyalty: FloatUtils::random(0.0f32, 20.0f32), pressure: FloatUtils::random(0.0f32, 20.0f32), professionalism: FloatUtils::random(0.0f32, 20.0f32), sportsmanship: FloatUtils::random(0.0f32, 20.0f32), temperament: FloatUtils::random(0.0f32, 20.0f32), } } fn generate_player_attributes() -> PlayerAttributes { PlayerAttributes { is_banned: false, is_injured: false, condition: IntegerUtils::random(0, 10000) as i16, fitness: IntegerUtils::random(0, 10000) as i16, jadedness: IntegerUtils::random(0, 10000) as i16, weight: IntegerUtils::random(60, 100) as u8, height: IntegerUtils::random(150, 220) as u8, value: 0, current_reputation: IntegerUtils::random(0, 3000) as i16, home_reputation: IntegerUtils::random(0, 3000) as i16, world_reputation: IntegerUtils::random(0, 1000) as i16, current_ability: IntegerUtils::random(0, 100) as u8, potential_ability: IntegerUtils::random(80, 200) as u8, international_apps: IntegerUtils::random(0, 100) as u16, international_goals: IntegerUtils::random(0, 40) as u16, under_21_international_apps: IntegerUtils::random(0, 30) as u16, under_21_international_goals: IntegerUtils::random(0, 10) as u16, } } fn generate_first_name(&self) -> String { if !self.people_names_data.first_names.is_empty() { let idx = IntegerUtils::random(0, self.people_names_data.first_names.len() as i32) as usize; self.people_names_data.first_names[idx].to_owned() } else { StringUtils::random_string(5) } } fn generate_last_name(&self) -> String { if !self.people_names_data.first_names.is_empty() { let idx = IntegerUtils::random(0, self.people_names_data.last_names.len() as i32) as usize; self.people_names_data.last_names[idx].to_owned() } else { StringUtils::random_string(12) } } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/generators/staff.rs
src/database/src/generators/staff.rs
use chrono::{Datelike, NaiveDate, Utc}; use core::shared::FullName; use core::utils::FloatUtils; use core::utils::{IntegerUtils, StringUtils}; use core::{ CoachFocus, MentalFocusType, PeopleNameGeneratorData, PersonAttributes, PhysicalFocusType, Staff, StaffAttributes, StaffClubContract, StaffCoaching, StaffDataAnalysis, StaffGoalkeeperCoaching, StaffKnowledge, StaffLicenseType, StaffMedical, StaffMental, StaffPosition, StaffStatus, TechnicalFocusType, }; use rand::Rng; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{LazyLock}; static STAFF_ID_SEQUENCE: LazyLock<AtomicU32> = LazyLock::new(|| AtomicU32::new(1)); pub struct StaffGenerator { people_names_data: PeopleNameGeneratorData, } impl StaffGenerator { pub fn with_people_names(people_names: &PeopleNameGeneratorData) -> Self { StaffGenerator { people_names_data: PeopleNameGeneratorData { first_names: people_names.first_names.clone(), last_names: people_names.last_names.clone(), }, } } } impl StaffGenerator { pub fn generate(&mut self, country_id: u32, position: StaffPosition) -> Staff { let now = Utc::now(); let year = IntegerUtils::random(now.year() - 35, now.year() - 15) as u32; let month = IntegerUtils::random(1, 12) as u32; let day = IntegerUtils::random(1, 29) as u32; Staff::new( STAFF_ID_SEQUENCE.fetch_add(1, Ordering::SeqCst), FullName::with_full( self.generate_first_name(), self.generate_last_name(), StringUtils::random_string(17), ), country_id, NaiveDate::from_ymd_opt(year as i32, month, day).unwrap(), Self::generate_staff_attributes(), Some(StaffClubContract::new( IntegerUtils::random(1000, 200000) as u32, NaiveDate::from_ymd_opt(now.year() + IntegerUtils::random(1, 5), 3, 14).unwrap(), position, StaffStatus::Active, )), Self::generate_person_attributes(), Self::generate_staff_license_type(), Some(Self::generate_staff_focus()), ) } fn generate_person_attributes() -> PersonAttributes { PersonAttributes { adaptability: FloatUtils::random(0.0, 20.0), ambition: FloatUtils::random(0.0, 20.0), controversy: FloatUtils::random(0.0, 20.0), loyalty: FloatUtils::random(0.0, 20.0), pressure: FloatUtils::random(0.0, 20.0), professionalism: FloatUtils::random(0.0, 20.0), sportsmanship: FloatUtils::random(0.0, 20.0), temperament: FloatUtils::random(0.0, 20.0), } } fn generate_staff_license_type() -> StaffLicenseType { match IntegerUtils::random(0, 6) { 0 => StaffLicenseType::ContinentalPro, 1 => StaffLicenseType::ContinentalA, 2 => StaffLicenseType::ContinentalB, 3 => StaffLicenseType::ContinentalC, 4 => StaffLicenseType::NationalA, 5 => StaffLicenseType::NationalB, 6 => StaffLicenseType::NationalC, _ => StaffLicenseType::NationalC, } } fn generate_staff_focus() -> CoachFocus { CoachFocus { technical_focus: get_random_technical(3), mental_focus: get_random_mental(5), physical_focus: get_random_physical(4), } } fn generate_staff_attributes() -> StaffAttributes { StaffAttributes { coaching: StaffCoaching { attacking: IntegerUtils::random(0, 20) as u8, defending: IntegerUtils::random(0, 20) as u8, fitness: IntegerUtils::random(0, 20) as u8, mental: IntegerUtils::random(0, 20) as u8, tactical: IntegerUtils::random(0, 20) as u8, technical: IntegerUtils::random(0, 20) as u8, working_with_youngsters: IntegerUtils::random(0, 20) as u8, }, goalkeeping: StaffGoalkeeperCoaching { distribution: IntegerUtils::random(0, 20) as u8, handling: IntegerUtils::random(0, 20) as u8, shot_stopping: IntegerUtils::random(0, 20) as u8, }, mental: StaffMental { adaptability: IntegerUtils::random(0, 20) as u8, determination: IntegerUtils::random(0, 20) as u8, discipline: IntegerUtils::random(0, 20) as u8, man_management: IntegerUtils::random(0, 20) as u8, motivating: IntegerUtils::random(0, 20) as u8, }, knowledge: StaffKnowledge { judging_player_ability: IntegerUtils::random(0, 20) as u8, judging_player_potential: IntegerUtils::random(0, 20) as u8, tactical_knowledge: IntegerUtils::random(0, 20) as u8, }, data_analysis: StaffDataAnalysis { judging_player_data: IntegerUtils::random(0, 20) as u8, judging_team_data: IntegerUtils::random(0, 20) as u8, presenting_data: IntegerUtils::random(0, 20) as u8, }, medical: StaffMedical { physiotherapy: IntegerUtils::random(0, 20) as u8, sports_science: IntegerUtils::random(0, 20) as u8, non_player_tendencies: IntegerUtils::random(0, 20) as u8, }, } } fn generate_first_name(&self) -> String { if !self.people_names_data.first_names.is_empty() { let idx = IntegerUtils::random(0, self.people_names_data.first_names.len() as i32) as usize; self.people_names_data.first_names[idx].to_owned() } else { StringUtils::random_string(5) } } fn generate_last_name(&self) -> String { if !self.people_names_data.first_names.is_empty() { let idx = IntegerUtils::random(0, self.people_names_data.last_names.len() as i32) as usize; self.people_names_data.last_names[idx].to_owned() } else { StringUtils::random_string(12) } } } const TECHNICAL_FOCUSES: &[TechnicalFocusType] = &[ TechnicalFocusType::Corners, TechnicalFocusType::Crossing, TechnicalFocusType::Dribbling, TechnicalFocusType::Finishing, TechnicalFocusType::FirstTouch, TechnicalFocusType::FreeKicks, TechnicalFocusType::Heading, TechnicalFocusType::LongShots, TechnicalFocusType::LongThrows, TechnicalFocusType::Marking, TechnicalFocusType::Passing, TechnicalFocusType::PenaltyTaking, TechnicalFocusType::Tackling, TechnicalFocusType::Technique, ]; const MENTAL_FOCUSES: &[MentalFocusType] = &[ MentalFocusType::Aggression, MentalFocusType::Anticipation, MentalFocusType::Bravery, MentalFocusType::Composure, MentalFocusType::Concentration, MentalFocusType::Decisions, MentalFocusType::Determination, MentalFocusType::Flair, MentalFocusType::Leadership, MentalFocusType::OffTheBall, MentalFocusType::Positioning, MentalFocusType::Teamwork, MentalFocusType::Vision, MentalFocusType::WorkRate, ]; const PHYSICAL_FOCUSES: &[PhysicalFocusType] = &[ PhysicalFocusType::Acceleration, PhysicalFocusType::Agility, PhysicalFocusType::Balance, PhysicalFocusType::Jumping, PhysicalFocusType::NaturalFitness, PhysicalFocusType::Pace, PhysicalFocusType::Stamina, PhysicalFocusType::Strength, PhysicalFocusType::MatchReadiness, ]; fn get_random_technical(count: usize) -> Vec<TechnicalFocusType> { let mut rng = rand::rng(); let mut random_values = Vec::with_capacity(count); while random_values.len() < count { let random_index = rng.random_range(0..TECHNICAL_FOCUSES.len() - 1); let random_value = TECHNICAL_FOCUSES[random_index]; if !random_values.contains(&random_value) { random_values.push(random_value); } } random_values } fn get_random_mental(count: usize) -> Vec<MentalFocusType> { let mut rng = rand::rng(); let mut random_values = Vec::with_capacity(count); while random_values.len() < count { let random_index = rng.random_range(0..MENTAL_FOCUSES.len() - 1); let random_value = MENTAL_FOCUSES[random_index]; if !random_values.contains(&random_value) { random_values.push(random_value); } } random_values } fn get_random_physical(count: usize) -> Vec<PhysicalFocusType> { let mut rng = rand::rng(); let mut random_values = Vec::with_capacity(count); while random_values.len() < count { let random_index = rng.random_range(0..PHYSICAL_FOCUSES.len() - 1); let random_value = PHYSICAL_FOCUSES[random_index]; if !random_values.contains(&random_value) { random_values.push(random_value); } } random_values }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/generators/generator.rs
src/database/src/generators/generator.rs
use crate::generators::{PlayerGenerator, PositionType, StaffGenerator}; use crate::loaders::ContinentEntity; use crate::DatabaseEntity; use chrono::{NaiveDate, NaiveDateTime}; use core::club::academy::ClubAcademy; use core::context::NaiveTime; use core::continent::Continent; use core::league::LeagueCollection; use core::league::{DayMonthPeriod, League, LeagueSettings}; use core::shared::Location; use core::utils::IntegerUtils; use core::ClubStatus; use core::TeamCollection; use core::{ Club, ClubBoard, ClubFinances, Country, CountryGeneratorData, Player, PlayerCollection, SimulatorData, Staff, StaffCollection, StaffPosition, Team, TeamReputation, TeamType, TrainingSchedule, }; use std::str::FromStr; pub struct DatabaseGenerator; impl DatabaseGenerator { pub fn generate(data: &DatabaseEntity) -> SimulatorData { let current_date = NaiveDateTime::new( NaiveDate::from_ymd_opt(2024, 7, 1).unwrap(), NaiveTime::default(), ); let continents = data .continents .iter() .map(|continent| Continent::new( continent.id, continent.name.clone(), DatabaseGenerator::generate_countries(continent, data) )).collect(); SimulatorData::new(current_date, continents) } fn generate_countries(continent: &ContinentEntity, data: &DatabaseEntity) -> Vec<Country> { data .countries .iter() .filter(|cn| cn.continent_id == continent.id) .map(|country| { let generator_data = match data .names_by_country .iter() .find(|c| c.country_id == country.id) { Some(names) => CountryGeneratorData::new( names.first_names.clone(), names.last_names.clone(), ), None => CountryGeneratorData::empty(), }; let mut player_generator = PlayerGenerator::with_people_names(&generator_data.people_names); let mut staff_generator = StaffGenerator::with_people_names(&generator_data.people_names); let clubs = DatabaseGenerator::generate_clubs( country.id, data, &mut player_generator, &mut staff_generator, ); let leagues = LeagueCollection::new( DatabaseGenerator::generate_leagues(country.id, data) ); Country::builder() .id(country.id) .code(country.code.clone()) .slug(country.slug.clone()) .name(country.name.clone()) .continent_id(continent.id) .leagues(leagues) .clubs(clubs) .reputation(country.reputation) .generator_data(generator_data) .build() .expect("Failed to build Country") }).collect() } fn generate_leagues(country_id: u32, data: &DatabaseEntity) -> Vec<League> { data .leagues .iter() .filter(|l| l.country_id == country_id) .map(|league| { let settings = LeagueSettings { season_starting_half: DayMonthPeriod { from_day: league.settings.season_starting_half.from_day, from_month: league.settings.season_starting_half.from_month, to_day: league.settings.season_starting_half.to_day, to_month: league.settings.season_starting_half.to_month, }, season_ending_half: DayMonthPeriod { from_day: league.settings.season_ending_half.from_day, from_month: league.settings.season_ending_half.from_month, to_day: league.settings.season_ending_half.to_day, to_month: league.settings.season_ending_half.to_month, }, }; League::new(league.id, league.name.clone(), league.slug.clone(), league.country_id, 0, settings) }) .collect() } fn generate_clubs( country_id: u32, data: &DatabaseEntity, player_generator: &mut PlayerGenerator, staff_generator: &mut StaffGenerator, ) -> Vec<Club> { data .clubs .iter() .filter(|c| c.country_id == country_id) .map(|club| Club { id: club.id, name: club.name.clone(), location: Location { city_id: club.location.city_id, }, board: ClubBoard::new(), status: ClubStatus::Professional, finance: ClubFinances::new(club.finance.balance, Vec::new()), academy: ClubAcademy::new(100), teams: TeamCollection::new( club.teams .iter() .map(|t| { Team::builder() .id(t.id) .league_id(t.league_id) .club_id(club.id) .name(t.name.clone()) .slug(t.slug.clone()) .team_type(TeamType::from_str(&t.team_type).unwrap()) .training_schedule(TrainingSchedule::new( NaiveTime::from_hms_opt(10, 0, 0).unwrap(), NaiveTime::from_hms_opt(17, 0, 0).unwrap(), )) .reputation(TeamReputation::new( t.reputation.home, t.reputation.national, t.reputation.world, )) .players(PlayerCollection::new(Self::generate_players( player_generator, country_id, ))) .staffs(StaffCollection::new( Self::generate_staffs(staff_generator, country_id) )) .build() .expect("Failed to build Team") }) .collect(), ), }) .collect() } fn generate_players(player_generator: &mut PlayerGenerator, country_id: u32) -> Vec<Player> { let mut players = Vec::with_capacity(100); let mut goalkeepers: Vec<Player> = (0..IntegerUtils::random(3, 5)) .map(|_| player_generator.generate(country_id, PositionType::Goalkeeper)) .collect(); let mut defenders: Vec<Player> = (0..IntegerUtils::random(20, 40)) .map(|_| player_generator.generate(country_id, PositionType::Defender)) .collect(); let mut midfielders: Vec<Player> = (0..IntegerUtils::random(25, 35)) .map(|_| player_generator.generate(country_id, PositionType::Midfielder)) .collect(); let mut strikers: Vec<Player> = (0..IntegerUtils::random(20, 24)) .map(|_| player_generator.generate(country_id, PositionType::Striker)) .collect(); players.append(&mut goalkeepers); players.append(&mut defenders); players.append(&mut midfielders); players.append(&mut strikers); players } fn generate_staffs(staff_generator: &mut StaffGenerator, country_id: u32) -> Vec<Staff> { let mut staffs = Vec::with_capacity(30); staffs.push(staff_generator.generate(country_id, StaffPosition::DirectorOfFootball)); staffs.push(staff_generator.generate(country_id, StaffPosition::Director)); staffs.push(staff_generator.generate(country_id, StaffPosition::AssistantManager)); staffs.push(staff_generator.generate(country_id, StaffPosition::Coach)); staffs.push(staff_generator.generate(country_id, StaffPosition::Coach)); staffs.push(staff_generator.generate(country_id, StaffPosition::Coach)); staffs.push(staff_generator.generate(country_id, StaffPosition::Physio)); staffs.push(staff_generator.generate(country_id, StaffPosition::Physio)); staffs.push(staff_generator.generate(country_id, StaffPosition::Physio)); staffs } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/generators/mod.rs
src/database/src/generators/mod.rs
pub mod generator; pub mod player; pub mod staff; pub use generator::*; pub use player::*; pub use staff::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/loaders/names.rs
src/database/src/loaders/names.rs
use serde::Deserialize; const STATIC_NAME_BY_COUNTRY_JSON: &str = include_str!("../data/names/names_by_country.json"); #[derive(Deserialize)] pub struct NamesByCountryEntity { pub country_id: u32, pub first_names: Vec<String>, pub last_names: Vec<String>, } pub struct NamesByCountryLoader; impl NamesByCountryLoader { pub fn load() -> Vec<NamesByCountryEntity> { serde_json::from_str(STATIC_NAME_BY_COUNTRY_JSON).unwrap() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/loaders/country.rs
src/database/src/loaders/country.rs
use serde::Deserialize; const STATIC_COUNTRIES_JSON: &str = include_str!("../data/countries.json"); #[derive(Deserialize)] pub struct CountryEntity { pub id: u32, pub code: String, pub slug: String, pub name: String, pub continent_id: u32, pub reputation: u16, } pub struct CountryLoader; impl CountryLoader { pub fn load() -> Vec<CountryEntity> { serde_json::from_str(STATIC_COUNTRIES_JSON).unwrap() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/loaders/club.rs
src/database/src/loaders/club.rs
use serde::Deserialize; const STATIC_CLUB_JSON: &'static str = include_str!("../data/clubs.json"); #[derive(Deserialize)] pub struct ClubEntity { pub id: u32, pub name: String, pub country_id: u32, pub location: ClubLocationEntity, pub finance: ClubFinanceEntity, pub teams: Vec<ClubTeamEntity>, } #[derive(Deserialize)] pub struct ClubLocationEntity { pub city_id: u32, } #[derive(Deserialize)] pub struct ClubFinanceEntity { pub balance: i32, } #[derive(Deserialize)] pub struct ClubReputationEntity { pub home: u16, pub national: u16, pub world: u16, } #[derive(Deserialize)] pub struct ClubTeamEntity { pub id: u32, pub name: String, pub slug: String, pub team_type: String, pub league_id: u32, pub finance: Option<ClubFinanceEntity>, pub reputation: ClubReputationEntity, } pub struct ClubLoader; impl ClubLoader { pub fn load() -> Vec<ClubEntity> { serde_json::from_str(STATIC_CLUB_JSON).unwrap() } }
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false
ZOXEXIVO/open-football
https://github.com/ZOXEXIVO/open-football/blob/7b55c8c095942c1df498d7aa02b524af6e3a896c/src/database/src/loaders/mod.rs
src/database/src/loaders/mod.rs
pub mod country; mod league; mod club; mod continent; mod names; pub use country::*; pub use league::*; pub use club::*; pub use continent::*; pub use names::*;
rust
Apache-2.0
7b55c8c095942c1df498d7aa02b524af6e3a896c
2026-01-04T20:24:06.162327Z
false