From 1614b39ca18c96e85af430cfb20d51acf73c5eac Mon Sep 17 00:00:00 2001 From: kevinxft Date: Thu, 19 Dec 2024 20:58:36 +0800 Subject: [PATCH] update logic --- src/readme_updater.rs | 73 ++++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 28 deletions(-) diff --git a/src/readme_updater.rs b/src/readme_updater.rs index f369650..a28cb2b 100644 --- a/src/readme_updater.rs +++ b/src/readme_updater.rs @@ -125,39 +125,48 @@ pub fn update_readme(history: &Map) -> Result<(), Box().ok()) - .unwrap_or(0.0); let remaining = data["remaining_amount"] .as_str() .and_then(|s| s.parse::().ok()) .unwrap_or(0.0); - daily_stats.insert(date.clone(), (used, remaining, 0.0)); // 第三个值用于存储当日消耗 + daily_stats.insert(date.clone(), (0.0, remaining, 0.0)); } - // 计算每日消耗 + // 计算每日消耗,并处理充值情况 let dates: Vec = daily_stats.keys().cloned().collect(); + let mut last_valid_date = dates.first().cloned(); + for i in 1..dates.len() { let current_date = &dates[i]; let prev_date = &dates[i - 1]; - if let (Some(&(current_used, _, _)), Some(&(prev_used, _, _))) = + + if let (Some(&(_, current_remaining, _)), Some(&(_, prev_remaining, _))) = (daily_stats.get(current_date), daily_stats.get(prev_date)) { - let daily_usage = current_used - prev_used; - if let Some(stat) = daily_stats.get_mut(current_date) { - stat.2 = daily_usage; + // 检查是否发生充值(剩余额度增加) + if current_remaining > prev_remaining { + // 发生充值,清除之前的统计数据 + for j in 0..i { + if let Some(stat) = daily_stats.get_mut(&dates[j]) { + stat.2 = 0.0; // 清除之前的消耗统计 + } + } + // 更新最后有效日期 + last_valid_date = Some(current_date.clone()); + // 当天消耗设为0 + if let Some(stat) = daily_stats.get_mut(current_date) { + stat.2 = 0.0; + } + } else { + // 正常计算消耗 + let daily_usage = prev_remaining - current_remaining; + if let Some(stat) = daily_stats.get_mut(current_date) { + stat.2 = daily_usage; + } } } } - // 为第一天设置初始消耗量 - if let Some(first_date) = dates.first() { - if let Some(stat) = daily_stats.get_mut(first_date) { - stat.2 = stat.0; // 第一天的消耗就是其总使用量 - } - } - // 生成 README 内容 let mut readme_content = String::from( r#"# Suno API 使用量统计 @@ -169,11 +178,20 @@ pub fn update_readme(history: &Map) -> Result<(), Box= &last_valid { + valid_consumption += daily; + valid_days += 1.0; + } + } + } + + let daily_average = if valid_days > 0.0 { valid_consumption / valid_days } else { 0.0 }; let latest_remaining = daily_stats.values().next_back().map(|(_, remaining, _)| remaining).unwrap_or(&0.0); let estimated_days = if daily_average > 0.0 { latest_remaining / daily_average } else { 0.0 }; @@ -203,16 +221,16 @@ pub fn update_readme(history: &Map) -> Result<(), Box) -> Result<(), Box