1use std::collections::HashMap;
12use std::time::Duration;
13
14use chrono::{DateTime, Local, Utc};
15
16use crate::usage::{ResetCredit, ResetCredits};
17
18pub fn money(v: f64, currency: &str) -> String {
29 let magnitude = format!("{:.2}", v.abs());
30 let sign = if v < 0.0 && magnitude != "0.00" {
31 "-"
32 } else {
33 ""
34 };
35 with_currency(sign, &magnitude, Some(currency))
36}
37
38pub fn with_currency(sign: &str, number: &str, currency: Option<&str>) -> String {
51 match currency {
52 None | Some("USD") => format!("{sign}${number}"),
53 Some("BRL") => format!("{sign}R${number}"),
54 Some("EUR") => format!("{sign}€{number}"),
55 Some("GBP") => format!("{sign}£{number}"),
56 Some("JPY") | Some("CNY") => format!("{sign}¥{number}"),
57 Some(other) => format!("{sign}{number} {other}"),
58 }
59}
60
61pub fn capitalize(s: &str) -> String {
67 let mut chars = s.chars();
68 match chars.next() {
69 Some(first) => {
70 let mut out = String::with_capacity(s.len());
71 out.extend(first.to_uppercase());
72 out.push_str(chars.as_str());
73 out
74 }
75 None => String::new(),
76 }
77}
78
79pub fn usd(v: f64) -> String {
81 money(v, "USD")
82}
83
84pub fn local_time_hm(when: DateTime<Utc>) -> String {
85 when.with_timezone(&Local).format("%H:%M").to_string()
86}
87
88pub fn local_time_hms(when: DateTime<Utc>) -> String {
89 when.with_timezone(&Local).format("%H:%M:%S").to_string()
90}
91
92pub fn local_date_hm(when: DateTime<Utc>) -> String {
93 when.with_timezone(&Local)
94 .format("%b %-d %H:%M")
95 .to_string()
96}
97
98pub fn reset_credits(credits: &ResetCredits) -> String {
100 let noun = if credits.available == 1 {
101 "reset"
102 } else {
103 "resets"
104 };
105 format!("{} {noun} available", credits.available)
106}
107
108pub fn reset_credit_lines(credits: &ResetCredits, now: DateTime<Utc>) -> Vec<String> {
112 let mut items = credits.credits.clone();
113 items.sort_by_key(|credit| credit.expires_at);
114 let mut lines: Vec<String> = items
115 .iter()
116 .map(|credit| reset_credit_line(credit, now))
117 .collect();
118 if lines.is_empty() && credits.available > 0 {
119 lines.push(reset_credits(credits));
120 }
121 lines
122}
123
124fn reset_credit_line(credit: &ResetCredit, now: DateTime<Utc>) -> String {
125 let expiry = match credit.expires_at {
126 Some(expires) if expires <= now => format!("expired {}", local_date_hm(expires)),
127 Some(expires) => format!(
128 "expires {} ({})",
129 local_date_hm(expires),
130 crate::countdown::format(Some(expires), now)
131 ),
132 None => "no expiry reported".into(),
133 };
134 match credit
135 .title
136 .as_deref()
137 .map(str::trim)
138 .filter(|title| !title.is_empty())
139 {
140 Some(title) => format!("{title} · {expiry}"),
141 None => capitalize(&expiry),
142 }
143}
144
145pub fn updated_at_hm(now: DateTime<Utc>, cache_age: Option<Duration>) -> String {
146 match cache_age {
147 Some(age) => local_time_hm(now - chrono::Duration::from_std(age).unwrap_or_default()),
148 None => "—".to_string(),
149 }
150}
151
152pub fn substitute(template: &str, values: &HashMap<&str, String>) -> String {
159 let mut out = String::with_capacity(template.len());
160 let mut rest = template;
161 while !rest.is_empty() {
162 match rest.find('{') {
163 None => {
164 out.push_str(rest);
165 break;
166 }
167 Some(open) => {
168 out.push_str(&rest[..open]);
170 let after_open = &rest[open + 1..];
171 if let Some(close) = after_open.find('}') {
172 let key = &after_open[..close];
173 if let Some(val) = values.get(key) {
174 out.push_str(val);
175 rest = &after_open[close + 1..];
176 continue;
177 }
178 }
179 out.push('{');
181 rest = after_open;
182 }
183 }
184 }
185 out
186}
187
188pub fn placeholders<I, V>(pairs: I) -> HashMap<&'static str, String>
190where
191 I: IntoIterator<Item = (&'static str, V)>,
192 V: Into<String>,
193{
194 pairs.into_iter().map(|(k, v)| (k, v.into())).collect()
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 fn pm(pairs: &[(&'static str, &str)]) -> HashMap<&'static str, String> {
202 placeholders(pairs.iter().map(|(k, v)| (*k, v.to_string())))
203 }
204
205 fn offer(title: Option<&str>, expires: &str) -> ResetCredit {
206 ResetCredit {
207 title: title.map(str::to_string),
208 expires_at: Some(expires.parse().unwrap()),
209 }
210 }
211
212 #[test]
213 fn a_reset_inventory_lists_each_credit_soonest_first() {
214 let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
215 let credits = ResetCredits {
216 available: 2,
217 credits: vec![
218 offer(Some("Full reset (Weekly + 5 hr)"), "2026-08-01T00:00:00Z"),
219 offer(Some("Full reset (Weekly + 5 hr)"), "2026-07-17T00:00:00Z"),
220 ],
221 };
222 assert_eq!(reset_credits(&credits), "2 resets available");
223 let lines = reset_credit_lines(&credits, now);
224 assert_eq!(lines.len(), 2, "{lines:?}");
225 assert!(lines[0].contains("Full reset (Weekly + 5 hr)"), "{lines:?}");
226 assert!(lines[0].contains("(13d 0h)"), "{lines:?}");
227 assert!(lines[1].contains("(28d 0h)"), "{lines:?}");
228 }
229
230 #[test]
231 fn a_lapsed_deadline_reads_as_expired_rather_than_now() {
232 let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
233 let lines = reset_credit_lines(
234 &ResetCredits {
235 available: 1,
236 credits: vec![offer(None, "2026-07-01T00:00:00Z")],
237 },
238 now,
239 );
240 assert_eq!(lines.len(), 1);
241 assert!(lines[0].starts_with("Expired "), "{lines:?}");
242 assert!(!lines[0].contains("(now)"), "{lines:?}");
243 }
244
245 #[test]
246 fn a_count_without_detail_still_renders_the_inventory() {
247 let now = "2026-07-04T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
248 assert_eq!(
249 reset_credit_lines(
250 &ResetCredits {
251 available: 2,
252 credits: vec![]
253 },
254 now
255 ),
256 vec!["2 resets available"]
257 );
258 }
259
260 #[test]
261 fn single_substitution() {
262 let v = pm(&[("session_pct", "42")]);
263 assert_eq!(substitute("{session_pct}%", &v), "42%");
264 }
265
266 #[test]
267 fn usd_keeps_the_sign_outside_the_symbol() {
268 assert_eq!(usd(74.5), "$74.50");
269 assert_eq!(usd(0.0), "$0.00");
270 assert_eq!(usd(-5.71), "-$5.71");
271 assert_eq!(usd(-0.0), "$0.00");
274 assert_eq!(usd(-0.001), "$0.00");
276 assert_eq!(usd(-0.006), "-$0.01");
278 }
279
280 #[test]
281 fn money_places_the_sign_ahead_of_every_currency() {
282 assert_eq!(money(20.0, "CNY"), "¥20.00");
283 assert_eq!(money(-20.0, "CNY"), "-¥20.00");
284 assert_eq!(money(3.5, "SEK"), "3.50 SEK");
287 assert_eq!(money(-3.5, "SEK"), "-3.50 SEK");
288 assert_eq!(money(-5.71, "USD"), usd(-5.71));
290 assert_eq!(money(-0.0, "CNY"), "¥0.00");
291 }
292
293 #[test]
299 fn the_two_money_formatters_agree_on_every_symbol() {
300 for (code, symbol) in [
301 ("USD", "$"),
302 ("BRL", "R$"),
303 ("EUR", "€"),
304 ("GBP", "£"),
305 ("JPY", "¥"),
306 ("CNY", "¥"),
307 ] {
308 assert_eq!(money(3.5, code), format!("{symbol}3.50"), "money {code}");
309 assert_eq!(
310 crate::usage::fmt_minor(350, 2, Some(code)),
311 format!("{symbol}3.50"),
312 "fmt_minor {code}"
313 );
314 }
315 assert_eq!(money(3.5, "SEK"), "3.50 SEK");
317 assert_eq!(crate::usage::fmt_minor(350, 2, Some("SEK")), "3.50 SEK");
318 assert_eq!(crate::usage::fmt_minor(350, 0, Some("JPY")), "¥350");
320 }
321
322 #[test]
323 fn multiple_substitutions() {
324 let v = pm(&[("a", "1"), ("b", "2")]);
325 assert_eq!(substitute("{a}-{b}-{a}", &v), "1-2-1");
326 }
327
328 #[test]
329 fn unknown_placeholder_passes_through() {
330 let v = pm(&[("a", "1")]);
331 assert_eq!(substitute("{a} {unknown}", &v), "1 {unknown}");
332 }
333
334 #[test]
335 fn no_re_substitution_in_replacement_text() {
336 let v = pm(&[("a", "{a}"), ("b", "X")]);
338 assert_eq!(substitute("{b}{a}{b}", &v), "X{a}X");
339 }
340
341 #[test]
342 fn empty_template() {
343 let v = pm(&[("a", "1")]);
344 assert_eq!(substitute("", &v), "");
345 }
346
347 #[test]
348 fn template_without_braces() {
349 let v = pm(&[("a", "1")]);
350 assert_eq!(substitute("hello world", &v), "hello world");
351 }
352
353 #[test]
354 fn unmatched_open_brace_is_literal() {
355 let v = pm(&[("a", "1")]);
356 assert_eq!(substitute("{a {x", &v), "{a {x");
357 }
358
359 #[test]
360 fn placeholders_with_underscores_and_digits() {
361 let v = pm(&[("session_pct_2", "x")]);
362 assert_eq!(substitute("{session_pct_2}", &v), "x");
363 }
364
365 #[test]
366 fn utf8_around_braces() {
367 let v = pm(&[("x", "→")]);
368 assert_eq!(substitute("α{x}β", &v), "α→β");
369 }
370}