//! The chart face's series: a table's records gathered by month, week or //! day, each period's amounts or numbers summed or its records counted. //! //! One place the arithmetic lives, so a tile and an assistant draw //! the same bars. An amount is summed in integer minor units and carries its //! currency; amounts in two currencies are never added together. use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, TimeZone, Timelike}; use serde::Serialize; use serde_json::{json, Value}; use super::{get_or_null, holds, parse_where, sum_numbers, Data, Found, RecordError, Wanted}; use crate::definitions::{ChartFace, ChartKind, ChartPeriod, ChartSign, ColumnType, TableDefinition}; /// A chart as the face draws it: one bucket per period of the window, oldest /// first. `currency` is the amounts' currency (none for a count or a number); /// `left_out` names the rows in other currencies the chart did not add in. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ChartSeries { pub kind: ChartKind, pub by: ChartPeriod, pub x: String, pub y: String, #[serde(skip_serializing_if = "Option::is_none")] pub currency: Option, pub buckets: Vec, /// Every bucket's value together. pub total: Value, #[serde(skip_serializing_if = "Vec::is_empty")] pub left_out: Vec, } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct ChartBucket { /// The period's first day, YYYY-MM-DD. pub start: String, /// The count, or the sum — whole when every value is (an amount always). pub value: Value, /// The value as the face writes it (`page::figure_words`). pub words: Option, } /// Rows of the window in a currency the chart does not draw. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct LeftOut { pub currency: Option, pub rows: usize, } /// The series of `face` over `rows` — the live records of `definition` — in /// the window of whole periods ending with the one `today` falls in. A record /// is placed by its `x` date as written (an instant on its own offset's day); /// one with no date, outside the window, not held by the face's `where` or on /// the other side of zero from its `sign` is left out. pub fn chart( face: &ChartFace, definition: &TableDefinition, rows: &[Data], today: NaiveDate, words: &super::page::Words, ) -> Result { chart_at(face, definition, rows, today.and_hms_opt(23, 0, 0).unwrap().and_utc().fixed_offset(), words) } /// A chart anchored at an instant. Hour windows use the definition's timezone, /// while the original day/week/month windows retain the caller's civil day. pub fn chart_at( face: &ChartFace, definition: &TableDefinition, rows: &[Data], at: DateTime, words: &super::page::Words, ) -> Result { let wrong = |column: &str, wanted: Wanted| RecordError::WrongType { column: format!("{}.{column}", definition.id), wanted, found: Found::AnotherType, }; let unknown = |column: &str| RecordError::UnknownColumn { plural: definition.plural.clone(), column: column.to_string() }; match definition.column(&face.x).map(|column| column.column_type) { Some(ColumnType::Date) => {} Some(_) => return Err(wrong(&face.x, Wanted::DateColumn)), None => return Err(unknown(&face.x)), } let y = if face.counts() { None } else { match definition.column(&face.y) { Some(column) if matches!(column.column_type, ColumnType::Number | ColumnType::Amount) => Some(column), Some(_) => return Err(wrong(&face.y, Wanted::NumberOrAmountColumn)), None => return Err(unknown(&face.y)), } }; let filter = face.where_.as_ref().map(|filter| serde_json::to_value(filter).expect("an ordered map is JSON")); let clauses = parse_where(definition, filter.as_ref())?; let periods = face.periods().clamp(1, ChartFace::MAX_PERIODS) as usize; let timezone = face.timezone.as_deref().unwrap_or("UTC").parse::() .map_err(|_| wrong("timezone", Wanted::Timezone))?; let (starts, labels, after): (Vec, Vec, i64) = if face.by == ChartPeriod::Hour { let local = at.with_timezone(&timezone); let last = local - Duration::seconds(i64::from(local.minute() * 60 + local.second())) - Duration::nanoseconds(i64::from(local.nanosecond())); let hours: Vec<_> = (0..periods).rev().map(|back| last - Duration::hours(back as i64)).collect(); (hours.iter().map(|hour| hour.timestamp()).collect(), hours.iter().map(DateTime::to_rfc3339).collect(), (last + Duration::hours(1)).timestamp()) } else { let days = window(face.by, at.date_naive(), periods); let after = advance(face.by, *days.last().unwrap(), 1).and_hms_opt(0, 0, 0).unwrap().and_utc().timestamp(); (days.iter().map(|day| day.and_hms_opt(0, 0, 0).unwrap().and_utc().timestamp()).collect(), days.iter().map(|day| day.format("%Y-%m-%d").to_string()).collect(), after) }; let first = starts[0]; // Each kept row with its bucket; a `sign` keeps one side of zero. let on_its_side = |row: &Data| { let value = y.map(|column| get_or_null(row, &column.key).as_f64()); match (face.sign, value) { (None, _) => true, (Some(ChartSign::Negative), Some(Some(value))) => value < 0.0, (Some(ChartSign::Positive), Some(Some(value))) => value > 0.0, (Some(_), _) => false, } }; let placed: Vec<(usize, &Data)> = rows .iter() .filter(|row| clauses.iter().all(|clause| holds(row, clause, &super::Zone { tz: timezone, today: at.date_naive() })) && on_its_side(row)) .filter_map(|row| { let position = if face.by == ChartPeriod::Hour { if let Some(hour) = &face.hour { let value = get_or_null(row, hour).as_f64()?; if !(0.0..24.0).contains(&value) || value.fract() != 0.0 { return None; } let civil = day_of(get_or_null(row, &face.x))?.and_hms_opt(value as u32, 0, 0)?; // A split civil hour cannot distinguish a repeated DST // hour. Refuse to invent which instant its row means. timezone.from_local_datetime(&civil).single()?.timestamp() } else { DateTime::parse_from_rfc3339(get_or_null(row, &face.x).as_str()?).ok()?.timestamp() } } else { day_of(get_or_null(row, &face.x))?.and_hms_opt(0, 0, 0)?.and_utc().timestamp() }; if position < first || position >= after { return None; } let at = starts.partition_point(|start| *start <= position) - 1; Some((at, row)) }) .collect(); // An amount draws one currency: the one most rows hold, ties to the // first by name; the others are named, never added in. let currency_of = |row: &Data| -> Option { let column = y.filter(|column| column.column_type == ColumnType::Amount)?; let currency = column.currency.as_deref()?; if definition.column(currency).is_none() { return Some(currency.to_string()); } get_or_null(row, currency).as_str().map(str::to_string) }; let mut counts: Vec<(Option, usize)> = Vec::new(); for (_, row) in &placed { let currency = currency_of(row); match counts.iter_mut().find(|(one, _)| *one == currency) { Some((_, n)) => *n += 1, None => counts.push((currency, 1)), } } counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); let drawn = counts.first().and_then(|(currency, _)| currency.clone()); let left_out: Vec = counts .iter() .skip(1) .map(|(currency, rows)| LeftOut { currency: currency.clone(), rows: *rows }) .collect(); let mut values: Vec> = vec![Vec::new(); starts.len()]; for (at, row) in placed { if currency_of(row) != drawn { continue; } values[at].push(match y { None => json!(1), Some(column) => get_or_null(row, &column.key).clone(), }); } let buckets: Vec = labels .iter() .zip(&values) .map(|(start, values)| { let value = sum_numbers(values.iter()); let amount = y.is_some_and(|column| column.column_type == ColumnType::Amount); let said = super::page::figure_words(&value, amount, drawn.as_deref(), &words.money); ChartBucket { start: start.clone(), value, words: said } }) .collect(); let total = sum_numbers(buckets.iter().map(|bucket| &bucket.value)); Ok(ChartSeries { kind: face.kind, by: face.by, x: face.x.clone(), y: face.y.clone(), currency: drawn, buckets, total, left_out, }) } /// The first day of each of the `periods` periods ending with today's. fn window(by: ChartPeriod, today: NaiveDate, periods: usize) -> Vec { let last = match by { ChartPeriod::Hour => unreachable!("hour windows are anchored at an instant"), ChartPeriod::Day => today, ChartPeriod::Week => today - Duration::days(i64::from(today.weekday().num_days_from_monday())), ChartPeriod::Month => today.with_day(1).expect("every month has a first"), }; (0..periods).rev().map(|back| advance(by, last, -(back as i32))).collect() } /// `start` moved by `n` periods. fn advance(by: ChartPeriod, start: NaiveDate, n: i32) -> NaiveDate { match by { ChartPeriod::Hour => unreachable!("hour windows advance elapsed hours"), ChartPeriod::Day => start + Duration::days(i64::from(n)), ChartPeriod::Week => start + Duration::weeks(i64::from(n)), ChartPeriod::Month => { let months = start.year() * 12 + start.month0() as i32 + n; NaiveDate::from_ymd_opt(months.div_euclid(12), months.rem_euclid(12) as u32 + 1, 1) .expect("a month's first day") } } } /// A date as written, or an instant on its own offset's day. fn day_of(value: &Value) -> Option { let text = value.as_str()?; chrono::DateTime::parse_from_rfc3339(text) .map(|instant| instant.date_naive()) .ok() .or_else(|| NaiveDate::parse_from_str(text, "%Y-%m-%d").ok()) } #[cfg(test)] #[path = "chart_tests.rs"] mod tests;