Cotton code
194 lines · 10.4 KB · RustRaw
use super::*;use crate::definitions::{DefinitionError, TableDefinition};use chrono::NaiveDate;use serde_json::json;/// A synthetic table a person might define: a sale with a day, an amount in/// minor units whose currency another column names, a plain number and a/// status.fn sale(chart: Value) -> Result<TableDefinition, DefinitionError> {    let definition = TableDefinition::from_json(        &json!({            "id": "sale",            "name": "Sale",            "plural": "Sales",            "picture": null,            "builtin": false,            "engine": null,            "columns": [                { "key": "title", "type": "text", "required": true },                { "key": "sold_on", "type": "date" },                { "key": "total", "type": "amount", "currency": "currency" },                { "key": "currency", "type": "text" },                { "key": "weight", "type": "number" },                { "key": "status", "type": "choice", "choices": ["paid", "cancelled"] }            ],            "title": "title",            "slip": { "title": "title" },            "tile": { "face": "chart", "chart": chart },            "page": [ { "heading": null, "columns": ["title"] } ],            "instructions": "A sale is one order paid for."        })        .to_string(),    )    .expect("parses");    definition.validate()?;    Ok(definition)}fn rows(values: Value) -> Vec<Data> {    values.as_array().unwrap().iter().map(|row| row.as_object().unwrap().clone()).collect()}fn day(text: &str) -> NaiveDate {    NaiveDate::parse_from_str(text, "%Y-%m-%d").unwrap()}fn series(definition: &TableDefinition, data: &[Data], today: &str) -> ChartSeries {    let face = definition.tile.chart.as_ref().expect("a chart face");    chart(face, definition, data, day(today), crate::records::page::Words::shipped()).expect("charts")}fn starts(series: &ChartSeries) -> Vec<String> {    series.buckets.iter().map(|bucket| bucket.start.clone()).collect()}fn values(series: &ChartSeries) -> Vec<Value> {    series.buckets.iter().map(|bucket| bucket.value.clone()).collect()}/// RULE: Hourly charts retain split date/hour records and draw the last 48 elapsed hours in their declared timezone; invalid and future hours cannot enter the total.#[test]fn hourly_charts_keep_split_hours_and_an_offset_independent_window() {    let mut definition = sale(json!({"kind":"bar", "x":"sold_on", "y":"weight", "by":"hour", "hour":"weight", "timezone":"Asia/Kolkata", "periods":48})).unwrap();    let mut hour = definition.column("weight").unwrap().clone();    hour.key = "hour".into();    definition.columns.push(hour);    definition.tile.chart.as_mut().unwrap().hour = Some("hour".into());    definition.validate().unwrap();    let face = definition.tile.chart.as_ref().unwrap();    let data = rows(json!([        {"sold_on":"2026-10-13", "hour":23, "weight":2},        {"sold_on":"2026-10-14", "hour":0, "weight":3},        {"sold_on":"2026-10-14", "hour":1, "weight":100},        {"sold_on":"2026-10-14", "hour":0.5, "weight":100},        {"sold_on":"2026-10-14", "hour":24, "weight":100},        {"sold_on":"2026-10-14", "hour":-1, "weight":100},        {"sold_on":"2026-10-11", "hour":23, "weight":100}    ]));    let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T00:12:00+05:30").unwrap();    let series = chart_at(face, &definition, &data, now, crate::records::page::Words::shipped()).unwrap();    assert_eq!(series.buckets.len(), 48);    assert_eq!(series.buckets.first().unwrap().start, "2026-10-12T01:00:00+05:30");    assert_eq!(series.buckets.last().unwrap().start, "2026-10-14T00:00:00+05:30");    assert_eq!(series.total, json!(5));    assert_eq!(series.buckets[46].value, json!(2));    assert_eq!(series.buckets[47].value, json!(3));    assert_eq!(chart_at(face, &definition, &data, now.with_timezone(&chrono::FixedOffset::east_opt(0).unwrap()), crate::records::page::Words::shipped()).unwrap(), series);}/// RULE: A chart over an amount column sums integer minor units — never a/// float, never rounded — and carries the currency the amounts are in. Rows in/// another currency are never added in: the chart draws the currency most of/// its rows hold and names what it left out.#[test]fn an_amount_chart_sums_minor_units_and_labels_its_currency() {    let definition = sale(json!({ "kind": "bar", "x": "sold_on", "y": "total", "by": "month", "periods": 3 })).unwrap();    let data = rows(json!([        { "title": "a", "sold_on": "2026-08-03", "total": 12_345, "currency": "INR" },        { "title": "b", "sold_on": "2026-10-01", "total": 99, "currency": "INR" },        { "title": "c", "sold_on": "2026-10-31", "total": 9_007_199_254_740_000_i64, "currency": "INR" },        { "title": "d", "sold_on": "2026-10-12", "total": 500, "currency": "USD" },        { "title": "e", "sold_on": "2026-07-31", "total": 1, "currency": "INR" }    ]));    let drawn = series(&definition, &data, "2026-10-12");    assert_eq!(starts(&drawn), ["2026-08-01", "2026-09-01", "2026-10-01"]);    assert_eq!(values(&drawn), [json!(12_345), json!(0), json!(9_007_199_254_740_099_i64)], "summed as whole minor units");    assert!(drawn.buckets.iter().all(|bucket| bucket.value.is_i64()), "an amount is never a float");    assert_eq!(drawn.currency.as_deref(), Some("INR"));    assert_eq!(drawn.left_out, vec![LeftOut { currency: Some("USD".into()), rows: 1 }], "the dollar sale is named, not added");    assert_eq!(drawn.total, json!(9_007_199_254_752_444_i64));    // `negative` keeps money out alone, summed with its sign.    let mut out = definition.clone();    out.tile.chart.as_mut().unwrap().sign = Some(crate::definitions::ChartSign::Negative);    let signed = rows(json!([        { "title": "spent", "sold_on": "2026-10-02", "total": -45_050, "currency": "INR" },        { "title": "earned", "sold_on": "2026-10-03", "total": 500_000, "currency": "INR" },        { "title": "spent again", "sold_on": "2026-09-05", "total": -120_000, "currency": "INR" }    ]));    let drawn = series(&out, &signed, "2026-10-12");    assert_eq!(values(&drawn), [json!(0), json!(-120_000), json!(-45_050)], "money in is not money out");    // A literal currency on the column is every row's.    let mut literal = definition.clone();    literal.columns.iter_mut().find(|c| c.key == "total").unwrap().currency = Some("EUR".into());    let drawn = series(&literal, &data, "2026-10-12");    assert_eq!(drawn.currency.as_deref(), Some("EUR"));    assert!(drawn.left_out.is_empty());}/// RULE: Every period of the window is drawn, oldest first, an empty one as 0;/// a week starts on Monday, a month on its first; a record outside the window,/// without a date, or that the chart's `where` does not hold for is not counted.#[test]fn a_count_chart_draws_every_period_of_its_window() {    let definition = sale(json!({ "kind": "line", "x": "sold_on", "y": "count", "by": "week", "periods": 3, "where": { "status": "paid" } })).unwrap();    let data = rows(json!([        { "title": "sunday before", "sold_on": "2026-09-27", "status": "paid" },        { "title": "monday", "sold_on": "2026-09-28", "status": "paid" },        { "title": "sunday", "sold_on": "2026-10-04", "status": "paid" },        { "title": "today", "sold_on": "2026-10-12", "status": "paid" },        { "title": "cancelled", "sold_on": "2026-10-12", "status": "cancelled" },        { "title": "undated", "status": "paid" },        { "title": "tomorrow", "sold_on": "2026-10-13", "status": "paid" }    ]));    // 12 Oct 2026 is a Monday.    let drawn = series(&definition, &data, "2026-10-12");    assert_eq!(starts(&drawn), ["2026-09-28", "2026-10-05", "2026-10-12"]);    assert_eq!(values(&drawn), [json!(2), json!(0), json!(2)], "Monday's week runs to Sunday; the window ends with this week");    assert_eq!(drawn.currency, None, "a count has no currency");    let by_day = sale(json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "day", "periods": 2 })).unwrap();    let drawn = series(&by_day, &data, "2026-10-12");    assert_eq!(starts(&drawn), ["2026-10-11", "2026-10-12"]);    assert_eq!(values(&drawn), [json!(0), json!(2)]);}/// RULE: An instant is placed on the day it is written in — its own offset's/// date — so a mood written at 23:30 in its owner's evening is that evening's.#[test]fn an_instant_falls_on_the_day_it_is_written_in() {    let definition = sale(json!({ "kind": "bar", "x": "sold_on", "y": "weight", "by": "day", "periods": 2 })).unwrap();    let data = rows(json!([        { "title": "late", "sold_on": "2026-10-11T23:30:00+05:30", "weight": 1.5 },        { "title": "utc", "sold_on": "2026-10-12T00:10:00Z", "weight": 2 }    ]));    let drawn = series(&definition, &data, "2026-10-12");    assert_eq!(values(&drawn), [json!(1.5), json!(2)]);}/// RULE: A chart face names a date `x`, an amount or number `y` (or `count`)/// and a window of 1 to 366 periods, comes with the chart face and only with/// it — refused where the definition is checked, so an imported tool's/// mistake is caught at import, never drawn.#[test]fn a_chart_face_is_checked_with_its_definition() {    for (chart, said) in [        (json!({ "kind": "bar", "x": "title", "y": "count", "by": "month" }), "date"),        (json!({ "kind": "bar", "x": "nowhere", "y": "count", "by": "month" }), "not a column"),        (json!({ "kind": "bar", "x": "sold_on", "y": "title", "by": "month" }), "amount or number"),        (json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "month", "periods": 0 }), "1 to 366"),        (json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "month", "where": { "status": "lost" } }), "where"),        (json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "month", "sign": "negative" }), "count"),    ] {        let refused = sale(chart.clone()).expect_err(&chart.to_string());        assert!(matches!(&refused, DefinitionError::BadChart(why) if why.contains(said)), "{chart}: {refused}");    }    let mut no_chart = sale(json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "month" })).unwrap();    no_chart.tile.chart = None;    assert!(matches!(no_chart.validate(), Err(DefinitionError::BadChart(_))), "the chart face needs tile.chart");    let mut other_face = sale(json!({ "kind": "bar", "x": "sold_on", "y": "count", "by": "month" })).unwrap();    other_face.tile.face = crate::definitions::TileFace::SlipList;    assert!(matches!(other_face.validate(), Err(DefinitionError::BadChart(_))), "tile.chart only with the chart face");}