diff --git a/crates/core/src/date.rs b/crates/core/src/date.rs index 606d3dacf3..c44e63968f 100644 --- a/crates/core/src/date.rs +++ b/crates/core/src/date.rs @@ -162,6 +162,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti Some(serial as f64) } +/// The calendar date a pivot cache's ISO 8601 date items (``, `minDate`, `startDate`…) give +/// a date of a date system's calendar, as [`datetime_from_serial`] returns it. Those dates count +/// real days: from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to +/// February 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious +/// 1900-02-29, runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30, +/// serial 1 is 1899-12-31 and serial 60 is 1900-02-28. Excel writes its caches that way. +pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) { + if sys == DateSystem::D1900 && year == 1900 && month <= 2 { + let serial = if month <= 1 { day } else { 31 + day }; + return civil_from_days(i64::from(serial) + UNIX_1899_12_30); + } + (year, month, day) +} + +/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`] +/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid. +/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the +/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date, +/// or one before the epoch or after 9999-12-31. +pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option { + let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?); + match (sys, y, m, d) { + (DateSystem::D1900, 1900, 2, 29) => return Some(60.0), + (DateSystem::D1904, 1899, 12, 30) => return Some(0.0), + _ => {} + } + if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) { + return None; + } + let base = match sys { + DateSystem::D1900 => UNIX_1899_12_30, + DateSystem::D1904 => UNIX_1904_01_01, + }; + let serial = days_from_civil(y, m, d) - base; + (0..=max_serial(sys)).contains(&serial).then_some(serial as f64) +} + /// Date/time from a serial. `None` for negative or too-large serials. pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option { if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) { @@ -384,4 +421,32 @@ mod tests { assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar Ok(()) } + + #[test] + fn iso_dates_count_real_days() { + let s = DateSystem::D1900; + // Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31. + for (serial, ymd) in + [(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))] + { + let d = datetime_from_serial(s, serial as f64).unwrap(); + assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}"); + assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}"); + } + assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0)); + assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None); + assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None); + assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None); + assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0)); + assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None); + assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None); + // The 1904 system has no offset; 1899-12-30 stands for a time's date part there too. + let s = DateSystem::D1904; + let d = datetime_from_serial(s, 0.5).unwrap(); + assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1)); + assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0)); + assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0)); + assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0)); + assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None); + } } diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 13f7a3e652..8af8be0df7 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -118,7 +118,15 @@ pub fn specs() -> Vec { value_settings ), cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter), - cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort), + cmd!( + "pivot.sort", + "Sort Field", + [], + None, + "{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}", + has_doc, + sort + ), cmd!( "pivot.group", "Group Field", diff --git a/crates/engine/src/cmd/pivot/create.rs b/crates/engine/src/cmd/pivot/create.rs index 0cec82b546..2c29eb5975 100644 --- a/crates/engine/src/cmd/pivot/create.rs +++ b/crates/engine/src/cmd/pivot/create.rs @@ -1,8 +1,8 @@ use super::fields::{AreaPlacement, add_to_area, in_axes}; use super::params::{func_name, func_param, group_name, group_param, layout_name, show_as_name, sort_name}; use super::{ - Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, bad, - bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with, + Arc, Cell, CellRef, Ctx, EngineError, Json, NumFmt, PivotDateGroup, PivotField, PivotTable, RangeRef, Result, Session, Sheet, StyleId, Workbook, + bad, bool_param, cell_param, current_region, edit, find_pivot, json, other, pv, str_param, with, }; // ---------------------------------------------------------------- insert @@ -327,6 +327,18 @@ pub(super) fn summarize_table(s: &mut Session, p: &Json) -> Result { // ---------------------------------------------------------------- queries +fn field_json(f: &PivotField) -> Json { + json!({ + "field": f.source_col, + "caption": f.caption, + "sort": sort_name(f.sort), + "sortBy": f.sort_by, + "group": group_name(f.date_group), + "numberFormat": f.number_format, + "collapsed": f.collapsed_items, + }) +} + pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { json!({ "id": pt.id, @@ -335,8 +347,8 @@ pub(super) fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { "anchor": pt.anchor.a1(), "range": pt.last_range.map(|r| r.a1()), "source": pt.source, - "rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), - "columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), + "rows": pt.rows.iter().map(field_json).collect::>(), + "columns": pt.columns.iter().map(field_json).collect::>(), "values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::>(), "filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::>(), "layout": layout_name(pt.layout), diff --git a/crates/engine/src/cmd/pivot/fields.rs b/crates/engine/src/cmd/pivot/fields.rs index 7d8c729aed..70d6f991cc 100644 --- a/crates/engine/src/cmd/pivot/fields.rs +++ b/crates/engine/src/cmd/pivot/fields.rs @@ -551,6 +551,12 @@ pub(super) fn value_settings(s: &mut Session, p: &Json) -> Result { None => {} } let name = v.name.clone(); + // Fields sorted by this value field follow its new caption. + for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) { + if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) { + f.sort_by = Some(name.clone()); + } + } if let Some(slot) = pt.values.get_mut(i) { *slot = v; } diff --git a/crates/engine/src/cmd/pivot/layout.rs b/crates/engine/src/cmd/pivot/layout.rs index 9b6a9527e8..2522df8b09 100644 --- a/crates/engine/src/cmd/pivot/layout.rs +++ b/crates/engine/src/cmd/pivot/layout.rs @@ -71,8 +71,24 @@ pub(super) fn sort(s: &mut Session, p: &Json) -> Result { "none" | "manual" | "source" => PivotSort::None, o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))), }; + // Sort by a value field (its caption or source field) instead of by the item labels. + let by = str_param(p, "by").map(str::to_string); update(s, p, |pt, _, _| { - axis_field(C, pt, &field)?.sort = order; + let by = match by { + Some(b) => Some( + pt.values + .iter() + .find(|v| v.name.eq_ignore_ascii_case(&b)) + .or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b))) + .map(|v| v.name.clone()) + .ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?, + ), + None => None, + }; + let f = axis_field(C, pt, &field)?; + f.sort = order; + f.sort_by = by; + f.sort_scope.clear(); Ok(json!({})) }) } @@ -164,7 +180,11 @@ pub(super) fn layout(s: &mut Session, p: &Json) -> Result { } } if let Some((on, top)) = subtotals { + // Design › Subtotals applies to every field, replacing per-field settings. pt.subtotals = on; + for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) { + f.subtotal = None; + } if let Some(t) = top { pt.subtotals_top = t; } diff --git a/crates/engine/src/cmd/pivot/tests.rs b/crates/engine/src/cmd/pivot/tests.rs index 3c697f6236..5dfac1d21f 100644 --- a/crates/engine/src/cmd/pivot/tests.rs +++ b/crates/engine/src/cmd/pivot/tests.rs @@ -1,4 +1,5 @@ use gridcraft_core::{CellError, CellRef, Value}; +use gridcraft_model::{PivotLayout, PivotSort}; use serde_json::{Value as Json, json}; use crate::Session; @@ -317,6 +318,10 @@ fn assert_values_on_rows_tabular(s: &mut Session) { assert_eq!(text(s, "A3"), "Region"); assert_eq!(text(s, "B3"), "Values"); assert_eq!(text(s, "C3"), "Total"); + // The Values field's caption heads its column, as in Excel's saved reports. + edit_pt(s, |p| p.data_caption = Some("Data".into())); + assert_eq!(text(s, "B3"), "Data"); + edit_pt(s, |p| p.data_caption = None); } fn assert_values_on_rows_position(s: &mut Session) { @@ -501,6 +506,231 @@ fn refresh_after_source_edits() { s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap(); } +/// Edits the active sheet's last PivotTable in the model (settings only a file sets) and +/// refreshes it. +fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let si = wb.active_sheet(); + f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap()); + s.execute("pivot.refresh", json!({})).unwrap(); +} + +#[test] +fn sort_by_value_within_each_parent() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap(); + // East 415, West 285, North 135. + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales")); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]); + s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]); + assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err()); + // The sort follows a renamed value field; sorting without `by` sorts by label again. + s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue")); + assert_eq!(text(&s, "A4"), "North"); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by, None); + assert_eq!(text(&s, "A4"), "West"); + // Inner items sort within their parent; subtotals stay with their group. + s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap(); + // East: Pears 195, Apples 160, Plums 60. + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], ["East", "Pears", "Apples", "Plums", "East Total"]); + assert_eq!(val(&s, "C4"), Value::Number(195.0)); + // West: Apples 170, Plums 70, Pears 45. + assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]); + // Columns sort by their row totals. + s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap(); + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]); +} + +#[test] +fn captions_renamed_items_and_manual_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + p.row_header_caption = Some("Area".into()); + p.col_header_caption = Some("Fruit".into()); + p.grand_total_caption = Some("Everything".into()); + p.rows[0].item_captions = vec![("East".into(), "Eastern".into())]; + p.columns[0].sort = PivotSort::None; + p.columns[0].item_order = vec!["Plums".into(), "Pears".into()]; + }); + assert_eq!(text(&s, "A4"), "Area"); + assert_eq!(text(&s, "B3"), "Fruit"); + // Listed items first, the rest after. + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(text(&s, "A8"), "Everything"); + // A renamed item sorts by its label still, and a filter still names it by its label. + s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap(); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(val(&s, "E5"), Value::Number(415.0)); + // Outline layout: the field's custom name heads its column. + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Outline; + p.rows[0].caption = Some("Sales area".into()); + p.columns[0].caption = Some("Kind".into()); + }); + assert_eq!(text(&s, "A4"), "Sales area"); + assert_eq!(text(&s, "B3"), "Kind"); +} + +#[test] +fn field_subtotals_repeat_labels_and_values_row() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + assert_eq!(text(&s, "A7"), "East Total"); + // Region without subtotals although the table has them; labels repeated on every row. + edit_pt(&mut s, |p| { + p.rows[0].subtotal = Some(false); + p.rows[0].repeat_labels = true; + }); + assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]); + assert_eq!(text(&s, "B7"), "Apples"); + // Outline repeats the labels too. + s.execute("pivot.layout", json!({"layout": "outline"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]); + // Two values without a column field: the Values row (Outline/Tabular) holds the caption. + s.execute("pivot.removeField", json!({"field": "Product"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap(); + assert_eq!(text(&s, "B3"), "Values"); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]); + edit_pt(&mut s, |p| p.data_caption = Some("Data".into())); + assert_eq!(text(&s, "B3"), "Data"); + edit_pt(&mut s, |p| p.show_values_row = false); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]); + // Compact layout never shows it. + edit_pt(&mut s, |p| { + p.show_values_row = true; + p.layout = PivotLayout::Compact; + }); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]); +} + +#[test] +fn empty_cell_caption_classic_layout_and_date_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap(); + // East has no record with 1 unit: blank, or the "For empty cells show" caption. + assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]); + edit_pt(&mut s, |p| p.empty_caption = Some("0".into())); + assert_eq!(text(&s, "B5"), "0"); + // Classic layout, one value and no column field: the value caption above the row + // headers and a "Total" column. + s.execute("pivot.removeField", json!({"field": "Units"})).unwrap(); + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Tabular; + p.classic_layout = true; + }); + assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]); + assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1); + // A field number format applies to the item labels; date items sort after text, as in + // Excel. + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + s.execute("pivot.removeField", json!({"field": "Region"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap(); + edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into())); + assert_eq!(text(&s, "A5"), "NA"); +} + +#[test] +fn only_date_formatted_cells_sort_as_dates() { + // The two mixed columns of ClosedXML's VariousDataTypesInTableColumns, in source order. + // Excel caches each date-formatted cell as `` and each General one as ``, and its + // saved items list numbers first and dates after errors, whatever the first cell is. + let mixed = ["", "TRUE", "14.5", "10", "ABC", "=1/0", "8/10/2020", "16:30"]; + // 1 and 1.52… are 12/31/1899 and 12/31/1899 12:30, which typed input reads as text. + let with_num = ["1", "1.5208333333333333", "12/24/2020", "16:30", "0.1", "45000", ""]; + let order = |inputs: &[&str], dates: Option<&str>| -> Vec { + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "K"})).unwrap(); + s.execute("cell.set", json!({"cell": "B1", "input": "V"})).unwrap(); + for (i, input) in inputs.iter().enumerate() { + s.execute("cell.set", json!({"cell": format!("A{}", i + 2), "input": input})).unwrap(); + s.execute("cell.set", json!({"cell": format!("B{}", i + 2), "input": "1"})).unwrap(); + } + if let Some(range) = dates { + s.execute("home.formatCells", json!({"range": range, "style": {"num_fmt": "m/d/yyyy h:mm"}})).unwrap(); + } + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"]})).unwrap(); + edit_pt(&mut s, |p| p.rows[0].sort = PivotSort::Asc); + let wb = &s.doc().unwrap().wb; + let si = wb.active_sheet(); + let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap(); + out.grid.iter().skip(1).filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l != "Grand Total").collect() + }; + // Excel's saved order for each field. + let excel_mixed = ["10", "14.5", "ABC", "TRUE", "#DIV/0!", "0.6875", "44053", "(blank)"]; + let excel_with_num = ["0.1", "45000", "0.6875", "1", "1.52083333333333", "44189", "(blank)"]; + assert_eq!(order(&mixed, None), excel_mixed); + assert_eq!(order(&with_num, Some("A2:A3")), excel_with_num); + // One number in a date cell and in a General cell is one item, which sorts as a number + // whichever cell comes first. + let number = ["5", "44053", "ABC"]; + assert_eq!(order(&["5", "8/10/2020", "44053", "ABC"], None), number); + assert_eq!(order(&["5", "44053", "8/10/2020", "ABC"], None), number); +} + +#[test] +fn a_general_cell_filtered_out_still_makes_its_number_sort_as_a_number() { + // 3/15/2023 is 45000: the General 45000 in row 3 makes that item a number, as in Excel's + // cache, even when the report filter leaves only the date cell. + let order = |filter: bool| -> Vec { + let mut s = Session::new(); + s.new_workbook(); + for (cell, input) in [("A1", "K"), ("B1", "V"), ("C1", "R"), ("A2", "3/15/2023"), ("A3", "45000"), ("A4", "ABC")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + for (row, r) in [(2, "a"), (3, "b"), (4, "a")] { + s.execute("cell.set", json!({"cell": format!("B{row}"), "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": format!("C{row}"), "input": r})).unwrap(); + } + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["K"], "values": ["V"], "filters": ["R"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "K", "order": "asc"})).unwrap(); + if filter { + s.execute("pivot.filter", json!({"field": "R", "selected": ["a"]})).unwrap(); + } + let wb = &s.doc().unwrap().wb; + let si = wb.active_sheet(); + let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap(); + out.grid.iter().filter_map(|r| r.first().map(|c| c.value.display())).filter(|l| l == "45000" || l == "ABC").collect() + }; + assert_eq!(order(false), ["45000", "ABC"]); + assert_eq!(order(true), ["45000", "ABC"]); +} + +#[test] +fn dates_sort_after_logicals_and_errors() { + // Excel's ascending item order: numbers, text, logicals, errors, dates, blanks. + let mut s = sales(); + s.execute("cell.set", json!({"cell": "C11", "input": "TRUE"})).unwrap(); + s.execute("cell.set", json!({"cell": "C12", "input": "=1/0"})).unwrap(); + s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + p.rows[0].number_format = None; + p.rows[0].sort = PivotSort::Asc; + }); + let p = pt(&s); + let r = p.last_range.unwrap(); + let labels: Vec = (r.start.row + 1..=r.end.row).map(|row| text(&s, &CellRef::new(row, r.start.col).a1())).collect(); + // 46037 is 1/15/2026, the first date. + assert_eq!(labels[..4], ["NA", "TRUE", "#DIV/0!", "46037"]); +} + fn pivot_chart(s: &Session) -> gridcraft_model::Chart { s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone() } @@ -1153,12 +1383,289 @@ fn collapsed_column_items_count_as_one_column_group() { s.execute("pivot.addField", json!({"field": "Sub", "area": "columns"})).unwrap(); } +#[test] +fn design_subtotals_replace_field_settings() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + // A file's field can override the table default (`defaultSubtotal`). + edit_pt(&mut s, |p| { + p.subtotals = false; + p.rows[0].subtotal = Some(true); + }); + assert!(find_row(&s, "East Total").is_some()); + // Design › Subtotals › Do Not Show Subtotals applies to every field. + s.execute("pivot.subtotals", json!({"mode": "none"})).unwrap(); + assert!(pt(&s).rows.iter().all(|f| f.subtotal.is_none())); + assert_eq!(find_row(&s, "East Total"), None); + edit_pt(&mut s, |p| p.rows[0].subtotal = Some(false)); + s.execute("pivot.subtotals", json!({"mode": "bottom"})).unwrap(); + assert!(find_row(&s, "East Total").is_some()); +} + +#[test] +fn numeric_empty_cell_caption_is_a_number() { + let mut s = sales(); + s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + // South has no Apples: the cell shows the caption, a number as Excel stores it. + edit_pt(&mut s, |p| p.empty_caption = Some("0".into())); + let south = find_row(&s, "South").unwrap(); + let apples = CellRef::new(south, 1); + assert_eq!(text(&s, &CellRef::new(south - 3, 1).a1()), "Apples"); + assert_eq!(val(&s, &apples.a1()), Value::Number(0.0)); + edit_pt(&mut s, |p| p.empty_caption = Some("n/a".into())); + assert_eq!(val(&s, &apples.a1()), Value::text("n/a")); +} + +/// Saves the active workbook, applies `patch` to the first PivotTable part and reopens it. +fn reopen_patched(s: &Session, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec) { + reopen_patched_part(s, "xl/pivotTables/pivotTable1.xml", patch) +} +/// Saves the active workbook, applies `patch` to `part` and reopens it. +fn reopen_patched_part(s: &Session, part: &str, patch: impl Fn(&str) -> String) -> (gridcraft_model::Workbook, Vec) { + use std::io::{Read, Write}; + let bytes = crate::io::save_bytes(&s.doc().unwrap().wb, "t.xlsx").unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).unwrap(); + let name = f.name().unwrap().to_string(); + let mut b = Vec::new(); + f.read_to_end(&mut b).unwrap(); + if name == part { + b = patch(&String::from_utf8(b).unwrap()).into_bytes(); + } + out.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + out.write_all(&b).unwrap(); + } + let bytes = out.finish().unwrap().into_inner(); + crate::io::open_bytes("t.xlsx", &bytes).unwrap() +} + +#[test] +fn sort_by_value_in_a_column_keeps_its_scope() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + // Excel's "sort by the values in the Apples column": the scope also names Product's + // item 0 (Apples). Apples: East 160, West 170, North 90; totals East 415, West 285. + let one = ""; + let values_ref = ""; + let two = format!("{values_ref}"); + let (wb, _) = reopen_patched(&s, |x| { + assert!(x.contains(one), "{x}"); + x.replace(one, &two) + }); + let si = wb.active_sheet(); + let p = wb.sheet(si).unwrap().pivots.last().unwrap(); + let apples = gridcraft_model::PivotScopeItem { source_col: "Product".into(), item: "Apples".into(), ..Default::default() }; + assert_eq!(p.rows[0].sort_scope, vec![apples]); + let out = crate::pivot::compute(&wb, p, si).unwrap(); + let labels: Vec = out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).collect(); + let order: Vec<&str> = labels.iter().map(String::as_str).filter(|l| ["East", "West", "North"].contains(l)).collect(); + assert_eq!(order, ["West", "East", "North"]); + // Saving writes the scope back. + let again = crate::io::save_bytes(&wb, "t.xlsx").unwrap(); + let (back, _) = crate::io::open_bytes("t.xlsx", &again).unwrap(); + assert_eq!(back.sheet(si).unwrap().pivots.last().unwrap().rows[0].sort_scope, p.rows[0].sort_scope); + // A scope GridCraft can't represent (two Product items) loads as a sort by label, with + // a warning, instead of as a sort by the grand total. + let bad = format!("{values_ref}"); + let (wb2, warnings) = reopen_patched(&s, |x| x.replace(one, &bad)); + let p2 = wb2.sheet(wb2.active_sheet()).unwrap().pivots.last().unwrap(); + assert_eq!(p2.rows[0].sort_by, None); + assert!(p2.rows[0].sort_scope.is_empty()); + assert!(warnings.iter().any(|w| w.contains("scope")), "{warnings:?}"); +} + +/// Saves and reopens a workbook. +fn reopen_wb(wb: &gridcraft_model::Workbook) -> gridcraft_model::Workbook { + let bytes = crate::io::save_bytes(wb, "t.xlsx").unwrap(); + crate::io::open_bytes("t.xlsx", &bytes).unwrap().0 +} +/// The labels in the report's first column, as computed from `wb`, keeping only `keep`. +fn first_col(wb: &gridcraft_model::Workbook, keep: &[&str]) -> Vec { + let si = wb.active_sheet(); + let p = wb.sheet(si).unwrap().pivots.last().unwrap(); + let out = crate::pivot::compute(wb, p, si).unwrap(); + out.grid.iter().filter_map(|r| r.first()).map(|c| c.value.display()).filter(|l| keep.contains(&l.as_str())).collect() +} +const VALUES_REF: &str = ""; +/// The Values-only sort scope the writer emits, as a `` opening. +fn values_only() -> String { + format!("{VALUES_REF}") +} + +#[test] +fn sort_scope_tells_date_levels_of_one_column_apart() { + use gridcraft_model::{PivotDateGroup, PivotField}; + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Date"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + let date = p.columns[0].clone(); + p.columns = + vec![PivotField { date_group: PivotDateGroup::Years, ..date.clone() }, PivotField { date_group: PivotDateGroup::Quarters, ..date }]; + }); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + // Sort by the values in the 2026 › Qtr2 column: Years is cache field 5 (item 1 = 2026, + // after "<1/15/2026"), Quarters the Date field 2 (item 2 = Qtr2). Qtr2 holds West 70, + // East 60, North 30; the totals are East 415, West 285, North 135. + let refs = format!( + "{VALUES_REF}" + ); + let (wb, _) = reopen_patched(&s, |x| { + assert!(x.contains(&values_only()), "{x}"); + x.replace(&values_only(), &refs) + }); + let regions = ["East", "West", "North"]; + assert_eq!(first_col(&wb, ®ions), ["West", "East", "North"]); + // Saving writes both references back. + let back = reopen_wb(&wb); + let scope = |wb: &gridcraft_model::Workbook| wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.clone(); + assert_eq!(scope(&back).len(), 2); + assert_eq!(scope(&back), scope(&wb)); + assert_eq!(first_col(&back, ®ions), ["West", "East", "North"]); +} + +#[test] +fn custom_subtotal_functions_keep_the_subtotal_rows() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + // Field Settings › Subtotals › Custom (Sum and Count) on Product, as Excel stores it. + let (wb, warnings) = reopen_patched(&s, |x| { + let start = x.match_indices("").unwrap(); + let field = x[start..end] + .replacen("", ""); + assert!(field.contains("t=\"sum\""), "{field}"); + format!("{}{field}{}", &x[..start], &x[end..]) + }); + let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap(); + assert_ne!(p.rows[1].subtotal, Some(false)); + // Shown with the automatic subtotal, with a warning. + let plain = reopen_wb(&s.doc().unwrap().wb); + let all = |wb: &gridcraft_model::Workbook| { + let si = wb.active_sheet(); + let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap(); + out.grid.iter().map(|r| r.iter().map(|c| c.value.display()).collect::>()).collect::>() + }; + assert_eq!(all(&wb), all(&plain)); + assert!(warnings.iter().any(|w| w.contains("subtotal")), "{warnings:?}"); +} + +#[test] +fn custom_subtotals_on_the_first_field_keep_the_table_default() { + use std::io::Read; + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Units"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + // Custom Sum subtotal on Region (cache field 0, the first axis field), no xpdl extension. + let (wb, _) = reopen_patched(&s, |x| { + assert!(!x.contains("pivotTableDefinition16"), "{x}"); + let start = x.find("").unwrap(); + let field = x[start..end] + .replacen("", ""); + assert!(field.contains("t=\"sum\""), "{field}"); + format!("{}{field}{}", &x[..start], &x[end..]) + }); + let p = wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap(); + assert!(p.subtotals); + assert_eq!([p.rows[0].subtotal, p.rows[1].subtotal], [None, None]); + // Saving doesn't add a table default of "off" the file never had. + let bytes = crate::io::save_bytes(&wb, "t.xlsx").unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + z.by_name("xl/pivotTables/pivotTable1.xml").unwrap().read_to_string(&mut xml).unwrap(); + assert!(!xml.contains("EnabledSubtotalsDefault=\"0\""), "{xml}"); +} + +#[test] +fn sort_scope_on_a_vanished_item_sorts_as_after_saving() { + let mut s = sales(); + s.execute("range.setValues", json!({"range": "A14", "values": [["South", "Kiwis", "1/1/2026", 1, 10]]})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + // Sorted by the values in the Kiwis column (Product item 3)… + let refs = format!("{VALUES_REF}"); + let (mut wb, _) = reopen_patched(&s, |x| x.replace(&values_only(), &refs)); + assert_eq!(wb.sheet(wb.active_sheet()).unwrap().pivots.last().unwrap().rows[0].sort_scope.len(), 1); + // …then Kiwis leaves the source: the rows sort by the grand total, before and after saving. + let src = wb.sheets.iter().position(|sh| sh.name == "Sheet1").unwrap(); + wb.sheet_mut(src).unwrap().set_value(CellRef::parse("B14").unwrap(), Value::text("Apples")); + let regions = ["East", "West", "North", "South"]; + let total_order = ["East", "West", "North", "South"]; + assert_eq!(first_col(&wb, ®ions), total_order); + assert_eq!(first_col(&reopen_wb(&wb), ®ions), total_order); +} + +#[test] +fn date_groups_not_sorted_are_in_date_order() { + let mut s = sales(); + // The first record is in Qtr4. + s.execute("cell.set", json!({"cell": "C2", "input": "12/1/2026"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Date"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.group", json!({"field": "Date", "by": "quarters"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Date", "order": "none"})).unwrap(); + let quarters = ["Qtr1", "Qtr2", "Qtr3", "Qtr4"]; + assert_eq!(first_col(&s.doc().unwrap().wb, &quarters), quarters); + let back = reopen_wb(&s.doc().unwrap().wb); + assert_eq!(first_col(&back, &quarters), quarters); + // A reordered list still wins; items it doesn't name follow in date order. + let mut wb = back; + let si = wb.active_sheet(); + wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap().rows[0].item_order = vec!["Qtr3".into()]; + assert_eq!(first_col(&wb, &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]); + assert_eq!(first_col(&reopen_wb(&wb), &quarters), ["Qtr3", "Qtr1", "Qtr2", "Qtr4"]); +} + +#[test] +fn manual_order_of_time_items_from_an_excel_cache() { + // Excel caches times as ``: those items must name the + // report's 8:00 and 9:30, or a refresh puts the blank ahead of them. + let mut s = Session::new(); + s.new_workbook(); + for (cell, input) in [("A1", "Shift"), ("B1", "Sales"), ("A2", "8:00"), ("B2", "10"), ("A3", "9:30"), ("B3", "20"), ("B4", "5")] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + s.execute("selection.set", json!({"range": "A1"})).unwrap(); + s.execute("insert.pivotTable", json!({"rows": ["Shift"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.sort", json!({"field": "Shift", "order": "none"})).unwrap(); + // The report's first column: times as minutes, and the blank item. + let shifts = |wb: &gridcraft_model::Workbook| -> Vec { + let si = wb.active_sheet(); + let out = crate::pivot::compute(wb, wb.sheet(si).unwrap().pivots.last().unwrap(), si).unwrap(); + out.grid + .iter() + .filter_map(|r| match &r.first()?.value { + Value::Number(n) => Some(format!("{}", (n * 1440.0).round())), + v if v.display() == "(blank)" => Some(v.display()), + _ => None, + }) + .collect() + }; + let order = ["480", "570", "(blank)"]; + assert_eq!(shifts(&s.doc().unwrap().wb), order); + let excel_items = ""; + let (back, _) = reopen_patched_part(&s, "xl/pivotCache/pivotCacheDefinition1.xml", |x| { + let ours = ""; + assert!(x.contains(ours), "{x}"); + x.replace(ours, excel_items) + }); + assert_eq!(shifts(&back), order); + // Saving writes that order back. + assert_eq!(shifts(&reopen_wb(&back)), order); +} + #[test] fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() { let mut s = sales(); s.execute("insert.pivotTable", json!({"source": "Sheet1!A1:E13", "destination": "Sheet1!H10", "rows": ["Region"], "values": ["Sales"]})).unwrap(); assert_eq!(pt(&s).last_range.unwrap().a1(), "H10:I14"); - // Rows above the report (and below the source) move the report only. s.execute("home.insertRows", json!({"rows": "16:17"})).unwrap(); s.execute("home.insertRows", json!({"rows": "6:7"})).unwrap(); assert_eq!(text(&s, "H12"), "Row Labels"); @@ -1166,7 +1673,6 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() { assert_eq!(l[0]["anchor"], "H12"); assert_eq!(l[0]["range"], "H12:I16"); assert_eq!(l[0]["source"], "Sheet1!A1:E15"); - // A row above the source moves both. s.execute("home.insertRows", json!({"rows": "1:1"})).unwrap(); let p = pt(&s); assert_eq!(p.source, "Sheet1!A2:E16"); @@ -1175,12 +1681,10 @@ fn inserting_or_deleting_lines_moves_the_pivot_with_its_cells() { assert_eq!(pt(&s).last_range.unwrap().a1(), "H13:I17"); assert_eq!(text(&s, "H13"), "Row Labels"); assert_eq!(val(&s, "I17"), Value::Number(TOTAL)); - // Deleting a column left of the report moves it left. s.execute("home.deleteColumns", json!({"cols": "F:F"})).unwrap(); let p = pt(&s); assert_eq!(p.anchor.a1(), "G13"); assert_eq!(p.last_range.unwrap().a1(), "G13:H17"); - // Deleting rows above moves it up. s.execute("home.deleteRows", json!({"rows": "1:1"})).unwrap(); assert_eq!(pt(&s).source, "Sheet1!A1:E15"); assert_eq!(pt(&s).anchor.a1(), "G12"); diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 37a8b3527d..ea1953db2e 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -10,7 +10,7 @@ use std::collections::{HashMap, HashSet}; use gridcraft_core::date::datetime_from_serial; pub use gridcraft_core::quote_sheet; -use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, split_sheet}; +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text, split_sheet}; use gridcraft_model::{ BorderLine, BorderStyle, Cell, Chart, Color, Fill, HAlign, NumFmt, PivotDataCell, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotItemRef, PivotLayout, PivotLookup, PivotShowAs, PivotSort, PivotTable, PivotValue, Series, Style, StyleId, Workbook, @@ -32,7 +32,6 @@ pub use items::{distinct_labels, func_caption, item_label}; use output::data_cols_exceed_sheet; pub use output::{CellKind, OutCell, Output, RowKind}; use output::{cell_style, look}; - /// Largest source block read (cells). pub const MAX_SOURCE_CELLS: u64 = 10_000_000; /// Largest report written (cells). @@ -61,12 +60,52 @@ pub struct Source { /// Numeric with a date number format. pub dates: Vec, pub rows: Vec>, + /// The sheet row of each record (blank rows are skipped). + pub record_rows: Vec, } impl Source { pub fn col(&self, name: &str) -> Option { self.headers.iter().position(|h| h.eq_ignore_ascii_case(name)) } + /// Per record: the column's cell is a number whose own format is a date (Excel caches such + /// a number as `` and sorts it after errors), and no cell of the column holds that number + /// with a non-date format: a number in any General cell is a number item, whatever the row + /// order or report filter. Looks up each distinct style once. + pub fn date_cells(&self, wb: &Workbook, col: usize) -> Vec { + let (Some(sh), Ok(off)) = (wb.sheet(self.sheet), u32::try_from(col)) else { + return vec![false; self.rows.len()]; + }; + let c = self.range.start.col + off; + let mut memo: HashMap = HashMap::new(); + let mut dates: Vec = self + .rows + .iter() + .zip(&self.record_rows) + .map(|(rec, &row)| { + rec.get(col).is_some_and(Value::is_number) + && *memo + .entry(sh.style_id(CellRef::new(row, c))) + .or_insert_with_key(|id| crate::display::number_format(wb.styles.get(*id).num_fmt.as_str()).is_date()) + }) + .collect(); + if !dates.contains(&true) { + return dates; + } + let number = |rec: &Vec| match rec.get(col) { + Some(Value::Number(n)) => Some(n.to_bits()), + _ => None, + }; + let general: HashSet = dates.iter().zip(&self.rows).filter(|(d, _)| !**d).filter_map(|(_, rec)| number(rec)).collect(); + if !general.is_empty() { + for (d, rec) in dates.iter_mut().zip(&self.rows) { + if *d && number(rec).is_some_and(|n| general.contains(&n)) { + *d = false; + } + } + } + dates + } } /// Absolute reference text for a range on a sheet: `Sheet1!$A$1:$E$20`. @@ -159,6 +198,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result r.start.row { @@ -179,6 +219,7 @@ pub fn read_source(wb: &Workbook, text: &str, default_sheet: usize) -> Result Result { filter_sets: &'a [Option>], row_fmts: &'a [String], col_fmts: &'a [String], + row_dates: &'a [Vec], + col_dates: &'a [Vec], empty: bool, } @@ -119,12 +121,14 @@ fn aggregate_record( return Ok(()); } let mut row_path = Vec::with_capacity(input.rows.len()); - for (((column, field), items), fmt) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts) { - row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri)); + for ((((column, field), items), fmt), dates) in input.rows.iter().zip(data.row_items.iter_mut()).zip(input.row_fmts).zip(input.row_dates) { + let date = dates.get(ri).copied().unwrap_or(false); + row_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri)); } let mut col_path = Vec::with_capacity(input.cols.len()); - for (((column, field), items), fmt) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts) { - col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, ri)); + for ((((column, field), items), fmt), dates) in input.cols.iter().zip(data.col_items.iter_mut()).zip(input.col_fmts).zip(input.col_dates) { + let date = dates.get(ri).copied().unwrap_or(false); + col_path.push(items.intern(input.wb, rec.get(*column).unwrap_or(&Value::Empty), field.date_group, fmt, date, ri)); } for row_depth in 0..=row_path.len() { for col_depth in 0..=col_path.len() { @@ -197,23 +201,49 @@ struct HeaderInput<'a> { k: usize, l: usize, headers_on: bool, + row_caption: Option<&'a str>, + data_caption: Option<&'a str>, + col_caption: Option<&'a str>, + grand_caption: &'a str, + classic: bool, + show_values_row: bool, } fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { - let HeaderInput { vals, row_fields, col_fields, col_items, col_fmts, vpos, data_cols, specs, row_levels, compact, on_rows, k, l, headers_on } = - input; + let HeaderInput { + vals, + row_fields, + col_fields, + col_items, + col_fmts, + vpos, + data_cols, + specs, + row_levels, + compact, + on_rows, + k, + l, + headers_on, + row_caption, + data_caption, + col_caption, + grand_caption, + classic, + show_values_row, + } = input; let val_name = |vi: usize| vals.get(vi).map(|(_, v)| v.name.clone()).unwrap_or_default(); let row_header = |g: &mut Grid, r: usize| { if row_levels == 0 || !headers_on { return; } if compact { - g.set(r, 0, Value::text("Row Labels"), CellKind::Header, 0, None); + g.set(r, 0, Value::text(row_caption.unwrap_or("Row Labels")), CellKind::Header, 0, None); } else { - // One column per row field, Σ Values ("Values") at its place. - let mut names: Vec<&str> = row_fields.iter().map(|f| f.source_col.as_str()).collect(); + // One column per row field, Σ Values (its caption, "Values" by default) at its place. + let mut names: Vec<&str> = row_fields.iter().map(|f| f.header()).collect(); if let Some(p) = vpos { - names.insert(p.min(names.len()), "Values"); + names.insert(p.min(names.len()), data_caption.unwrap_or("Values")); } for (i, name) in names.into_iter().enumerate() { g.set(r, i, Value::text(name), CellKind::Header, 0, None); @@ -223,12 +253,23 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { // ---- header rows if col_fields.is_empty() { + let classic = classic && !compact && k == 1 && headers_on; + if classic { + let r = g.push_row(RowKind::Header)?; + g.set(r, 0, Value::text(val_name(0)), CellKind::Header, 0, None); + } + if !compact && k > 1 && !on_rows && show_values_row && headers_on { + let r = g.push_row(RowKind::Header)?; + g.set(r, l, Value::text(data_caption.unwrap_or("Values")), CellKind::Header, 0, None); + } let r = g.push_row(RowKind::Header)?; row_header(g, r); for (j, (_, vi)) in data_cols.iter().enumerate() { match vi { - Some(vi) => g.set(r, l + j, Value::text(val_name(*vi)), CellKind::Header, 0, None), - // Values on rows, no column field: the one data column is the grand total. + Some(vi) => { + let caption = if classic { "Total".to_string() } else { val_name(*vi) }; + g.set(r, l + j, Value::text(caption), CellKind::Header, 0, None); + } None if on_rows => g.set(r, l + j, Value::text("Total"), CellKind::Header, 0, None), None => {} } @@ -239,7 +280,11 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { g.set(cap, 0, Value::text(val_name(0)), CellKind::Header, 0, None); } if headers_on { - let caption = if compact { "Column Labels".to_string() } else { col_fields.first().map(|f| f.source_col.clone()).unwrap_or_default() }; + let caption = if compact { + col_caption.unwrap_or("Column Labels").to_string() + } else { + col_fields.first().map(|f| f.header().to_string()).unwrap_or_default() + }; g.set(cap, l, Value::text(caption), CellKind::Header, 0, None); } let levels = col_fields.len() + usize::from(k > 1 && !on_rows); @@ -257,8 +302,8 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { let same = prev.is_some_and(|p| p.kind != ColKind::Grand && p.path.get(..=lv) == spec.path.get(..=lv)); if !same { let Some(item) = col_items.get(lv).and_then(|fi| fi.get(it)) else { continue }; - let fmt = if item.formatted { col_fmts.get(lv).cloned() } else { None }; - g.set(first_level + lv, c, item.value.clone(), CellKind::ColLabel, 0, fmt); + let fmt = if item.formatted && item.caption.is_none() { col_fmts.get(lv).cloned() } else { None }; + g.set(first_level + lv, c, item.shown_value(), CellKind::ColLabel, 0, fmt); } } if k > 1 @@ -269,7 +314,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { } ColKind::Subtotal => { let lv = spec.path.len().saturating_sub(1); - let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.label(*it))).unwrap_or_default(); + let label = spec.path.last().and_then(|it| col_items.get(lv).map(|fi| fi.shown_label(*it))).unwrap_or_default(); let text = match vi { Some(vi) if k > 1 => caption(&label, &val_name(*vi)), _ => caption(&label, "Total"), @@ -279,7 +324,7 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { ColKind::Grand => { let text = match vi { Some(vi) if k > 1 => format!("Total {}", val_name(*vi)), - _ => "Grand Total".to_string(), + _ => grand_caption.to_string(), }; g.set(first_level, c, Value::text(text), CellKind::ColLabel, 0, None); } @@ -292,7 +337,6 @@ fn write_headers(g: &mut Grid, input: HeaderInput<'_>) -> Result<(), String> { Ok(()) } - struct ValueLookup<'a> { wb: &'a Workbook, source: &'a Source, @@ -539,8 +583,11 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro let filter_fmts: Vec = filters.iter().map(|f| fmt_of(f.0)).collect(); let filter_sets: Vec>> = filters.iter().map(|(_, field, _, _)| field.selected.as_ref().map(|s| s.iter().map(|v| v.to_ascii_lowercase()).collect())).collect(); - let row_fmts: Vec = rows.iter().map(|(c, _)| fmt_of(*c)).collect(); - let col_fmts: Vec = cols.iter().map(|(c, _)| fmt_of(*c)).collect(); + let field_fmt = |c: usize, f: &PivotField| f.number_format.clone().unwrap_or_else(|| fmt_of(c)); + let row_fmts: Vec = rows.iter().map(|(c, f)| field_fmt(*c, f)).collect(); + let col_fmts: Vec = cols.iter().map(|(c, f)| field_fmt(*c, f)).collect(); + let row_dates: Vec> = rows.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect(); + let col_dates: Vec> = cols.iter().map(|(c, f)| date_flags(wb, src, *c, f.date_group)).collect(); let aggregate = aggregate_source( AggregateInput { wb, @@ -555,33 +602,83 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro filter_sets: &filter_sets, row_fmts: &row_fmts, col_fmts: &col_fmts, + row_dates: &row_dates, + col_dates: &col_dates, empty, }, &mut probe, )?; - let AggregateData { row_items, col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate; + let AggregateData { mut row_items, mut col_items, aggs, row_set, col_set, col_leaves: _ } = aggregate; + + for (fi, (_, f)) in row_items.iter_mut().zip(rows.iter()) { + fi.apply(f); + } + for (fi, (_, f)) in col_items.iter_mut().zip(cols.iter()) { + fi.apply(f); + } + + let get = |rp: &[u32], cp: &[u32], vi: usize| -> Option { + let (vs, v) = vals.get(vi)?; + let accs = aggs.get(&(rp.to_vec(), cp.to_vec()))?; + match vs { + ValSrc::Col(_) => accs.get(vi).map(|a| a.result(v.func)), + ValSrc::Calc(i) => { + let sum = |name: &str| -> Value { + src.col(name) + .and_then(|c| extra.iter().position(|x| *x == c)) + .and_then(|j| accs.get(k + j)) + .map(|a| a.result(PivotFunc::Sum)) + .unwrap_or(Value::Number(0.0)) + }; + Some(calc.value(wb, *i, &sum)) + } + } + }; // ---- axes let row_fields: Vec<&PivotField> = rows.iter().map(|(_, f)| *f).collect(); let col_fields: Vec<&PivotField> = cols.iter().map(|(_, f)| *f).collect(); let row_paths: Vec<&[u32]> = row_set.iter().map(Vec::as_slice).collect(); let col_paths: Vec<&[u32]> = col_set.iter().map(Vec::as_slice).collect(); - let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items); - let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items); + // The other-axis path a sort scope names: its items of the other axis's fields, outer first, + // up to the first field it doesn't name. A scope naming an item that isn't there sorts by the + // grand total, as the writer then drops it. + let scope_path = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| -> Vec { + let mut path = Vec::new(); + for ((_, o), oi) in others.iter().zip(other_items) { + let Some(e) = f.sort_scope.iter().find(|e| e.is_of(o)) else { break }; + match oi.find(&e.item) { + Some(i) => path.push(i), + None => return Vec::new(), + } + } + path + }; + let sorting = |f: &PivotField, others: &[(usize, &PivotField)], other_items: &[FieldItems]| { + let vi = f.sort_by.as_deref().and_then(|n| vals.iter().position(|(_, v)| v.name.eq_ignore_ascii_case(n)))?; + Some((vi, scope_path(f, others, other_items))) + }; + let row_value = |p: &[u32], other: &[u32], vi: usize| get(p, other, vi).as_ref().and_then(Value::as_f64); + let col_value = |p: &[u32], other: &[u32], vi: usize| get(other, p, vi).as_ref().and_then(Value::as_f64); + let row_by = ByValue { fields: row_fields.iter().map(|f| sorting(f, &cols, &col_items)).collect(), value: &row_value }; + let col_by = ByValue { fields: col_fields.iter().map(|f| sorting(f, &rows, &row_items)).collect(), value: &col_value }; + let row_tree = build_tree(&row_paths, 0, &row_fields, &row_items, &row_by); + let col_tree = build_tree(&col_paths, 0, &col_fields, &col_items, &col_by); let mut siblings: HashMap, Vec> = HashMap::new(); collect_siblings(&row_tree, &mut Vec::new(), &mut siblings); let level0: Vec = row_tree.iter().map(|n| n.item).collect(); let val_names: Vec = vals.iter().map(|(_, v)| v.name.clone()).collect(); + let grand_caption = pt.grand_total_caption.as_deref().unwrap_or("Grand Total"); let ctx = Ctx { pt, rows: row_fields.clone(), row_items, row_fmts: row_fmts.clone(), vpos, val_names: val_names.clone() }; let mut lines: Vec = Vec::new(); if row_levels == 0 { lines.push(Line { kind: LineKind::Item(false), leaf: true, path: vec![], values: true, labels: vec![], vi: None }); } else { if pt.layout == PivotLayout::Tabular { - ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut lines); + ctx.flatten_tabular(&row_tree, 0, None, &mut Vec::new(), &[], &mut Vec::new(), &mut lines); } else { - ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut lines); + ctx.flatten(&row_tree, 0, None, &mut Vec::new(), &mut Vec::new(), &mut lines); } // With only Σ Values in Rows its items are the totals already. if pt.grand_totals_cols && !rows.is_empty() { @@ -596,7 +693,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro if on_rows { lines.extend(val_names.iter().enumerate().map(|(vi, name)| grand(format!("Total {name}"), Some(vi)))); } else { - lines.push(grand("Grand Total".into(), None)); + lines.push(grand(grand_caption.into(), None)); } } } @@ -604,7 +701,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro if cols.is_empty() { specs.push(ColSpec { kind: ColKind::Leaf, path: vec![] }); } else { - flatten_cols(&col_tree, 0, &col_fields, &col_items, pt.subtotals, &mut Vec::new(), &mut specs); + flatten_cols(&col_tree, 0, &col_fields, &col_items, pt, &mut Vec::new(), &mut specs); if pt.grand_totals_rows { specs.push(ColSpec { kind: ColKind::Grand, path: vec![] }); } @@ -678,6 +775,12 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro k, l, headers_on: pt.show_headers, + row_caption: pt.row_header_caption.as_deref(), + data_caption: pt.data_caption.as_deref(), + col_caption: pt.col_header_caption.as_deref(), + grand_caption: pt.grand_total_caption.as_deref().unwrap_or("Grand Total"), + classic: pt.classic_layout, + show_values_row: pt.show_values_row, }, )?; let val_name = |vi: usize| vals.get(vi).map(|(_, value)| value.name.clone()).unwrap_or_default(); @@ -714,7 +817,7 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro return None; } let mut parts: Vec = - spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.label(*it)).unwrap_or_default()).collect(); + spec.path.iter().enumerate().map(|(lv, it)| col_items.get(lv).map(|fi| fi.shown_label(*it)).unwrap_or_default()).collect(); if let Some(vi) = vi && (k > 1 || parts.is_empty()) { @@ -733,15 +836,6 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro } else { Some(row_levels.saturating_sub(1) as u32) }; - let item_refs = |fields: &[&PivotField], items: &[FieldItems], path: &[u32]| -> Vec { - path.iter() - .enumerate() - .filter_map(|(d, it)| { - let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?); - Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() }) - }) - .collect() - }; let mut data: Vec = Vec::new(); for line in &lines { let rk = match line.kind { @@ -764,40 +858,102 @@ pub(super) fn compute_from(wb: &Workbook, pt: &PivotTable, src: &Source, mut pro if !line.values { continue; } - let rp = line.path.as_slice(); - for (j, (si, col_vi)) in data_cols.iter().enumerate() { - let line_vi = col_vi.or(line.vi); - let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue }; - let Some((_, vdef)) = vals.get(*vi) else { continue }; - let cp = spec.path.as_slice(); - let Some(raw) = lookup.get(rp, cp, *vi) else { continue }; - let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0: &level0, siblings: &siblings, cache: &show_cache }; - let shown = show_value(vdef, raw, &lookup, &context); - // Every value cell of the report is indexed, so a report that needs more cells than - // the index cap is rejected outright — never written with a truncated index that - // would answer #REF! for the values the sheet shows. - if data.len() >= MAX_INDEXED_CELLS { - return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells.")); - } - let mut items = item_refs(&ctx.rows, &ctx.row_items, rp); - items.extend(item_refs(&col_fields, &col_items, cp)); - data.push(PivotDataCell { - data_field: vdef.name.clone(), - source_col: vdef.source_col.clone(), - items, - row: u32::try_from(r).unwrap_or(u32::MAX), - col: u32::try_from(l + j).unwrap_or(u32::MAX), - }); - if let Some(pr) = probe.as_deref_mut() { - if pr.at == Some((r, l + j)) { - pr.hit = Some((rp.to_vec(), cp.to_vec())); - } - if let Some(cells) = pr.cells.as_mut() { - cells.insert((r, l + j)); - } - } - g.set(r, l + j, shown, ck.1, 0, data_fmt.get(*vi).cloned().flatten()); - } + fill_line_values( + &mut g, + r, + line, + &data_cols, + &specs, + &vals, + &data_fmt, + l, + ck.1, + pt, + &ctx, + &col_fields, + &col_items, + &lookup, + &level0, + &siblings, + &show_cache, + &mut probe, + &mut data, + )?; } Ok(Output { width: g.width as u32, grid: g.rows, row_kinds: g.kinds, body_offset, chart_rows, chart_cols, label_col, data }) } + +#[allow(clippy::too_many_arguments)] +fn fill_line_values( + g: &mut Grid, + r: usize, + line: &Line, + data_cols: &[(usize, Option)], + specs: &[ColSpec], + vals: &[(ValSrc, &PivotValue)], + data_fmt: &[Option], + l: usize, + ck: CellKind, + pt: &PivotTable, + ctx: &Ctx<'_>, + col_fields: &[&PivotField], + col_items: &[FieldItems], + lookup: &ValueLookup<'_>, + level0: &[u32], + siblings: &HashMap, Vec>, + show_cache: &ShowCache, + probe: &mut Option<&mut Probe>, + data: &mut Vec, +) -> Result<(), String> { + let rp = line.path.as_slice(); + for (j, (si, col_vi)) in data_cols.iter().enumerate() { + let line_vi = col_vi.or(line.vi); + let (Some(spec), Some(vi)) = (specs.get(*si), &line_vi) else { continue }; + let Some((_, vdef)) = vals.get(*vi) else { continue }; + let cp = spec.path.as_slice(); + let Some(raw) = lookup.get(rp, cp, *vi) else { + // No records: blank, or the "For empty cells show" caption (a number when it + // reads as one, as Excel stores `missingCaption="0"`). + if let Some(c) = &pt.empty_caption { + let v = c.trim().parse::().ok().filter(|x| x.is_finite()).map(Value::number).unwrap_or_else(|| Value::text(c.as_str())); + let fmt = if matches!(v, Value::Number(_)) { data_fmt.get(*vi).cloned().flatten() } else { None }; + g.set(r, l + j, v, ck, 0, fmt); + } + continue; + }; + let context = ShowContext { row_path: rp, col_path: cp, value_index: *vi, level0, siblings, cache: show_cache }; + let shown = show_value(vdef, raw, lookup, &context); + if data.len() >= MAX_INDEXED_CELLS { + return Err(format!("A PivotTable report can have at most {MAX_INDEXED_CELLS} value cells.")); + } + let mut items = item_refs(&ctx.rows, &ctx.row_items, rp); + items.extend(item_refs(col_fields, col_items, cp)); + data.push(PivotDataCell { + data_field: vdef.name.clone(), + source_col: vdef.source_col.clone(), + items, + row: u32::try_from(r).unwrap_or(u32::MAX), + col: u32::try_from(l + j).unwrap_or(u32::MAX), + }); + if let Some(pr) = probe.as_deref_mut() { + if pr.at == Some((r, l + j)) { + pr.hit = Some((rp.to_vec(), cp.to_vec())); + } + if let Some(cells) = pr.cells.as_mut() { + cells.insert((r, l + j)); + } + } + g.set(r, l + j, shown, ck, 0, data_fmt.get(*vi).cloned().flatten()); + } + Ok(()) +} + +fn item_refs(fields: &[&PivotField], items: &[FieldItems], path: &[u32]) -> Vec { + path.iter() + .enumerate() + .filter_map(|(d, it)| { + let (f, item) = (fields.get(d)?, items.get(d)?.get(*it)?); + Some(PivotItemRef { field: f.source_col.clone(), label: item.label.clone(), value: item.value.clone() }) + }) + .collect() +} diff --git a/crates/engine/src/pivot/items.rs b/crates/engine/src/pivot/items.rs index dfbea7e99b..a984dc5d6c 100644 --- a/crates/engine/src/pivot/items.rs +++ b/crates/engine/src/pivot/items.rs @@ -1,6 +1,9 @@ use std::collections::HashSet; -use super::{CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial}; +use super::{ + CellError, HashMap, MONTHS, Ordering, PivotDateGroup, PivotField, PivotFunc, PivotSort, Source, Value, Workbook, datetime_from_serial, + number_to_text, +}; // ---------------------------------------------------------------- items @@ -14,6 +17,20 @@ pub(super) struct Item { first: usize, /// The value is a number shown with the source format. pub(super) formatted: bool, + /// The item's custom name (a renamed item). + pub(super) caption: Option, + /// Position in the field's manual item order. + rank: Option, +} + +impl Item { + /// The value shown: the custom name, else the item's value. + pub(super) fn shown_value(&self) -> Value { + self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone()) + } + pub(super) fn shown_label(&self) -> &str { + self.caption.as_deref().unwrap_or(&self.label) + } } #[derive(Default)] @@ -22,12 +39,15 @@ pub(super) struct FieldItems { index: HashMap, } +/// Sort classes: numbers, text, logicals, errors, dates (a number whose own cell has a date +/// format, which Excel caches as `` and sorts after errors), blanks. fn cmp_items(a: &Item, b: &Item) -> Ordering { a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| gridcraft_core::compare_text(&a.text, &b.text)) } -/// (identity key, item) for a source value under a field's date grouping. -fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> (String, Item) { +/// (identity key, item) for a source value under a field's date grouping; `date` marks a number +/// whose cell has a date format. +fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> (String, Item) { let it = |value: Value, label: String, class: u8, num: f64, formatted: bool| Item { text: label.to_lowercase(), value, @@ -36,9 +56,11 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: num, first, formatted, + caption: None, + rank: None, }; match v { - Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)), + Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)), Value::Number(n) => { if group != PivotDateGroup::None && let Some(dt) = datetime_from_serial(wb.date_system, *n) @@ -55,8 +77,9 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: }; return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); } - let label = crate::display::format(v, fmt, wb).text; - (format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true)) + let shown = crate::display::format(v, fmt, wb); + let class = if date { 4 } else { 0 }; + (format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true)) } Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), Value::Bool(b) => { @@ -64,13 +87,13 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) } Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), - Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), + Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, date, first), } } impl FieldItems { - pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: usize) -> u32 { - let (key, item) = make_item(wb, v, group, fmt, first); + pub(super) fn intern(&mut self, wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, date: bool, first: usize) -> u32 { + let (key, item) = make_item(wb, v, group, fmt, date, first); if let Some(i) = self.index.get(&key) { return *i; } @@ -85,20 +108,50 @@ impl FieldItems { pub(super) fn label(&self, i: u32) -> String { self.get(i).map(|x| x.label.clone()).unwrap_or_default() } + pub(super) fn shown_label(&self, i: u32) -> String { + self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default() + } + /// The item a setting names by label (or, for a number item, its unformatted number text). + pub(super) fn find(&self, label: &str) -> Option { + let l = label.to_lowercase(); + let i = self.items.iter().position(|it| it.text == l || (it.formatted && number_to_text(it.num).to_lowercase() == l))?; + u32::try_from(i).ok() + } + /// Applies a field's renamed items and manual item order. Settings name items by label; a + /// number item also matches its unformatted number text (how a file's cache names it). + pub(super) fn apply(&mut self, f: &PivotField) { + if f.item_captions.is_empty() && f.item_order.is_empty() { + return; + } + let mut order: HashMap = HashMap::new(); + for (i, l) in f.item_order.iter().enumerate() { + order.entry(l.to_lowercase()).or_insert(i); + } + let mut captions: HashMap = HashMap::new(); + for (l, c) in &f.item_captions { + captions.entry(l.to_lowercase()).or_insert(c.as_str()); + } + for it in &mut self.items { + let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None }; + it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied(); + it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string()); + } + } } /// The label of a source value under a date grouping (for filters and field lists). pub fn item_label(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str) -> String { - make_item(wb, v, group, fmt, 0).1.label + make_item(wb, v, group, fmt, false, 0).1.label } /// Distinct item labels of a source column, sorted like the field list shows them. pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup, limit: usize) -> Vec { let mut fi = FieldItems::default(); let fmt = src.formats.get(col).map(String::as_str).unwrap_or("General"); + let dates = date_flags(wb, src, col, group); for (i, r) in src.rows.iter().enumerate() { if let Some(v) = r.get(col) { - fi.intern(wb, v, group, fmt, i); + fi.intern(wb, v, group, fmt, dates.get(i).copied().unwrap_or(false), i); } if fi.items.len() > 100_000 { break; @@ -109,6 +162,11 @@ pub fn distinct_labels(wb: &Workbook, src: &Source, col: usize, group: PivotDate items.into_iter().take(limit).map(|i| i.label).collect() } +/// [`Source::date_cells`] for an ungrouped field; a date-grouped field doesn't use them. +pub(super) fn date_flags(wb: &Workbook, src: &Source, col: usize, group: PivotDateGroup) -> Vec { + if group == PivotDateGroup::None { src.date_cells(wb, col) } else { Vec::new() } +} + // ---------------------------------------------------------------- aggregation #[derive(Clone, Debug, Default)] @@ -252,7 +310,17 @@ pub(super) struct Node { pub(super) children: Vec, } -pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec { +/// Sorting of an axis by value fields: per axis field, the value field it sorts by and the path +/// on the other axis whose values it uses (empty = the total); and the value of an axis path at +/// an other-axis path. +pub(super) type ValueLookup<'a> = &'a dyn Fn(&[u32], &[u32], usize) -> Option; + +pub(super) struct ByValue<'a> { + pub(super) fields: Vec)>>, + pub(super) value: ValueLookup<'a>, +} + +pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec { let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] }; let mut order: Vec = Vec::new(); let mut groups: HashMap> = HashMap::new(); @@ -265,23 +333,36 @@ pub(super) fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], g.push(p); } } - let mut nodes: Vec = order + let vi = by_value.fields.get(depth).and_then(Option::as_ref).filter(|_| field.sort != PivotSort::None); + let mut nodes: Vec<(Option, Node)> = order .into_iter() .map(|it| { let ps = groups.remove(&it).unwrap_or_default(); - Node { item: it, children: build_tree(&ps, depth + 1, fields, items) } + let key = vi.and_then(|(vi, other)| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, other, *vi))); + (key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) }) }) .collect(); - let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { + let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { (Some(x), Some(y)) => match field.sort { PivotSort::Asc => cmp_items(x, y), PivotSort::Desc => cmp_items(y, x), - PivotSort::None => x.first.cmp(&y.first), + PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then_with(|| { + // Date groups are in date order, like the groups Excel's cache lists. + if field.date_group == PivotDateGroup::None { x.first.cmp(&y.first) } else { cmp_items(x, y) } + }), }, _ => Ordering::Equal, }; - nodes.sort_by(by); - nodes + // By value: numbers in the sort direction, then items without a number; ties by label. + let by_key = |a: &Option, b: &Option| match (a, b) { + (Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x), + (Some(x), Some(y)) => x.total_cmp(y), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + }; + nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b))); + nodes.into_iter().map(|(_, n)| n).collect() } pub(super) fn is_collapsed(field: &PivotField, label: &str) -> bool { diff --git a/crates/engine/src/pivot/output.rs b/crates/engine/src/pivot/output.rs index 2d57fc21a3..56dbf526ef 100644 --- a/crates/engine/src/pivot/output.rs +++ b/crates/engine/src/pivot/output.rs @@ -151,11 +151,22 @@ pub(super) struct Ctx<'a> { pub(super) val_names: Vec, } +/// A label cell of a report line: (column, value, indent, number format). +type Label = (usize, Value, u8, Option); + +/// Whether an axis field shows subtotals (its own setting, else the table's). +pub(super) fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool { + f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals) +} + impl Ctx<'_> { - fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String) { - let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) }; - let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None }; - (it.value.clone(), fmt, it.label.clone()) + /// (shown value, number format, item label, shown label) of a row item. + fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String, String) { + let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { + return (Value::Empty, None, String::new(), String::new()); + }; + let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None }; + (it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string()) } /// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form. @@ -184,86 +195,87 @@ impl Ctx<'_> { /// The Σ Values level at row field depth `depth`: one item per value field, each followed by /// the row fields below it (`nodes`) or, innermost, holding that value. - fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, out: &mut Vec) { + fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, repeat: &mut Vec"); + // Sort by a value field: the scope references the Values field's data item, then + // the other axis's items it takes the values from (index into their ``), as + // the engine resolves them: outer field first, up to the first field it doesn't + // name; none when it names an item that isn't there (the grand total). + write_auto_sort_scope(s, pt, c, vals, af); + if af.is_some_and(|f| f.repeat_labels) { + let _ = + write!(s, ""); + } + s.push_str(""); } else { s.push_str("/>"); } @@ -846,6 +924,37 @@ fn write_pivot_fields(s: &mut String, pt: &PivotTable, c: &Cache, layout: &Pivot s.push_str(""); } +fn write_auto_sort_scope(s: &mut String, pt: &PivotTable, c: &Cache, vals: &[(usize, &PivotValue)], af: Option<&PivotField>) { + let Some(d) = + af.filter(|f| f.sort != PivotSort::None).and_then(|f| f.sort_by.as_deref()).and_then(|n| vals.iter().position(|(_, v)| same(&v.name, n))) + else { + return; + }; + let mut refs = vec![(VALUES_FIELD.to_string(), d)]; + if let Some(af) = af { + let on_rows = pt.rows.iter().any(|r| std::ptr::eq(r, af)); + let (others, base) = if on_rows { (&pt.columns, pt.rows.len()) } else { (&pt.rows, 0) }; + for (q, o) in others.iter().enumerate() { + // A field without a source column isn't on the axis (the engine skips it too). + let Some(j) = c.axis_map.get(base + q).copied().flatten() else { continue }; + let Some(e) = af.sort_scope.iter().find(|e| e.is_of(o)) else { break }; + let labels = c.fields.get(j).map(CField::item_labels).unwrap_or_default(); + match written_order(&labels, Some(o)).iter().position(|x| labels.get(*x).is_some_and(|l| same(l, &e.item))) { + Some(pos) => refs.push((j.to_string(), pos)), + None => { + refs.truncate(1); + break; + } + } + } + } + let _ = write!(s, "", refs.len()); + for (field, x) in &refs { + let _ = write!(s, ""); + } + s.push_str(""); +} + fn write_page_fields(s: &mut String, c: &Cache, layout: &PivotTableLayout<'_>) { if layout.page_fields.is_empty() { return; @@ -938,3 +1047,5 @@ fn axis_fields_xml(s: &mut String, tag: &str, idx: &[usize], values_at: Option"); } + +// ================================================================ reading diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0eebcfaa39..b0fde5c9cf 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -939,6 +939,11 @@ fn read_craft_formula_text( /// `2024-03-15`, `2024-03-15T10:30:00Z`, `10:30:00` → serial. pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { + parse_iso_datetime_with(s, |y, m, d| serial_from_ymd(sys, y, m, d)) +} + +/// [`parse_iso_datetime`] with `ymd` turning the date part (year, month 1–12, day 1–31) into a serial. +pub(crate) fn parse_iso_datetime_with(s: &str, ymd: impl Fn(i64, i64, i64) -> Option) -> Option { let s = s.trim_end_matches('Z'); let (date, time) = match s.split_once('T') { Some((d, t)) => (d, Some(t)), @@ -954,7 +959,7 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { if !(1..=12).contains(&m) || !(1..=31).contains(&d) { return None; } - serial = serial_from_ymd(sys, y, m, d)?; + serial = ymd(y, m, d)?; } if let Some(t) = time { // Drop a time-zone offset. diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index fda2375c5b..3ebb5c309c 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -87,8 +87,20 @@ fn workbook() -> Workbook { name: "Sales by Region".into(), source: "Data!$A$1:$F$9".into(), anchor: at("A4"), - rows: vec![PivotField { source_col: "Region".into(), sort: PivotSort::Asc, collapsed_items: vec!["East".into()], ..PivotField::default() }], - columns: vec![PivotField { sort: PivotSort::None, ..field("Product") }], + rows: vec![PivotField { + source_col: "Region".into(), + sort: PivotSort::Desc, + collapsed_items: vec!["East".into()], + caption: Some("Area".into()), + sort_by: Some("Sum of Sales".into()), + sort_scope: vec![PivotScopeItem { source_col: "Product".into(), item: "B".into(), ..PivotScopeItem::default() }], + item_captions: vec![("West".into(), "**West".into())], + subtotal: Some(true), + repeat_labels: true, + number_format: Some("0.0".into()), + ..PivotField::default() + }], + columns: vec![PivotField { sort: PivotSort::None, item_order: vec!["C".into(), "A".into(), "B".into()], ..field("Product") }], values: vec![ PivotValue { source_col: "Sales".into(), @@ -115,6 +127,13 @@ fn workbook() -> Workbook { style: "PivotStyleMedium9".into(), show_headers: false, last_range: Some(rr("A2:H12")), + row_header_caption: Some("Vehicle".into()), + col_header_caption: Some("Type".into()), + data_caption: Some("Data".into()), + grand_total_caption: Some("Days".into()), + empty_caption: Some("0".into()), + show_values_row: false, + classic_layout: true, calculated_fields: vec![], data_index: Default::default(), values_on_rows: false, @@ -128,8 +147,14 @@ fn workbook() -> Workbook { source: "SalesTbl".into(), anchor: at("K4"), rows: vec![ - PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Years, sort: PivotSort::None, collapsed_items: vec!["2024".into()] }, - PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Months, sort: PivotSort::Asc, collapsed_items: vec![] }, + PivotField { + source_col: "Date".into(), + date_group: PivotDateGroup::Years, + sort: PivotSort::None, + collapsed_items: vec!["2024".into()], + ..PivotField::default() + }, + PivotField { source_col: "Date".into(), date_group: PivotDateGroup::Months, sort: PivotSort::Asc, ..PivotField::default() }, ], columns: vec![PivotField { sort: PivotSort::Desc, ..field("Product") }], values: vec![ @@ -176,10 +201,7 @@ fn workbook() -> Workbook { style: "PivotStyleDark3".into(), show_headers: true, last_range: Some(rr("K2:Z30")), - calculated_fields: vec![], - data_index: Default::default(), - values_on_rows: false, - values_position: None, + ..PivotTable::default() }; // Pivot 3: defaults, defined-name source, compact. let p3 = PivotTable { @@ -362,6 +384,11 @@ fn pivot_xml_details() { "{t1}" ); assert!(t1.contains("")); + // Sort by the values in the "B" column: Product's item B sits third in its ``. + assert!( + t1.contains(""), + "{t1}" + ); assert!(t1.contains("subtotal=\"count\"")); assert!(t1.contains("numFmtId=\"4\"")); assert!(t1.contains("axis=\"axisPage\"")); @@ -775,6 +802,57 @@ fn data_on_rows_with_one_value_field_reads_without_warning() { assert!(back.sheet(0).unwrap().pivots[0].values_on_rows); } +#[test] +fn manual_order_in_cache_order_is_kept() { + // Not auto-sorted, items written in cache order: the order is still the file's, so a + // refresh over reordered source rows keeps it. + let mut wb = workbook(); + wb.sheet_mut(1).unwrap().pivots[0].columns[0].item_order.clear(); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert_eq!(back.sheet(1).unwrap().pivots[0].columns[0].item_order, ["A", "B", "C"]); +} + +#[test] +fn early_dates_in_caches_count_real_days() { + // Excel writes serial 1 as 1899-12-31 (ISO dates count days from 1899-12-30), not as the + // 1900 calendar's 1900-01-01, which it reads as serial 2. + let mut wb = workbook(); + let date_style = wb.sheet(0).unwrap().cells.get(at("C2")).unwrap().style; + wb.sheet_mut(0).unwrap().cells.set(at("C2"), Cell { value: Value::number(1.5), formula: None, style: date_style, py: None }); + let parts = unzip(&write_xlsx(&wb).unwrap()); + let caches: String = + parts.iter().filter(|(k, _)| k.contains("pivotCacheDefinition")).map(|(_, v)| String::from_utf8_lossy(v).into_owned()).collect(); + assert!(caches.contains("minDate=\"1899-12-31T12:00:00\"") && caches.contains("startDate=\"1899-12-31T00:00:00\""), "{caches}"); + assert!(!caches.contains("1900-01-01T"), "{caches}"); +} + +#[test] +fn location_without_field_headers_has_no_values_row() { + let mut wb = workbook(); + { + let p = &mut wb.sheet_mut(1).unwrap().pivots[2]; + p.values.push(PivotValue { source_col: "Sales".into(), name: "Sum of Sales".into(), ..PivotValue::default() }); + p.layout = PivotLayout::Outline; + p.show_headers = false; + } + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains("firstHeaderRow=\"1\" firstDataRow=\"1\""), "{t3}"); + wb.sheet_mut(1).unwrap().pivots[2].show_headers = true; + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains("firstHeaderRow=\"1\" firstDataRow=\"2\""), "{t3}"); + { + let p = &mut wb.sheet_mut(1).unwrap().pivots[2]; + p.values.push(PivotValue { source_col: "Sales".into(), name: "Sum of Sales".into(), ..PivotValue::default() }); + p.show_values_row = false; + } + let parts = unzip(&write_xlsx(&wb).unwrap()); + let t3 = String::from_utf8(parts.get("xl/pivotTables/pivotTable3.xml").unwrap().clone()).unwrap(); + assert!(t3.contains("firstHeaderRow=\"0\""), "{t3}"); + assert!(t3.contains(""), "{t3}"); +} + const SIMPLE_TABLE: &str = r#""#; const CACHE_PART: &str = "xl/pivotCache/pivotCacheDefinition1.xml"; @@ -860,7 +938,7 @@ fn two_value_fields_without_columns_hide_the_values_row() { }); let t = &two["xl/pivotTables/pivotTable1.xml"]; assert!(t.contains("firstHeaderRow=\"0\" firstDataRow=\"1\""), "{t}"); - assert!(t.contains(""), "{t}"); + assert!(!t.contains("hideValuesRow"), "{t}"); let one = small_pivot(&cols, |p| { p.rows = vec![field("Region")]; p.values = vec![value("Sales")]; @@ -868,6 +946,16 @@ fn two_value_fields_without_columns_hide_the_values_row() { let t = &one["xl/pivotTables/pivotTable1.xml"]; assert!(t.contains("firstHeaderRow=\"1\""), "{t}"); assert!(!t.contains("hideValuesRow"), "{t}"); + + let mut wb = workbook(); + let p = &mut wb.sheet_mut(1).unwrap().pivots[2]; + p.filters.clear(); + p.layout = PivotLayout::Outline; + p.show_headers = true; + p.show_values_row = true; + p.values.push(value("Sales")); + let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap(); + assert!(back.sheet(1).unwrap().pivots[2].show_values_row); } /// The "Trend" pivot of [`workbook`] with `values` as its value fields, written; returns the file diff --git a/docs/gaps.md b/docs/gaps.md index 9502ed64d7..b4c92137c5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -105,7 +105,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- values on rows and GETPIVOTDATA done). Show Details (double-click a value, subtotal or grand total cell) lists its source records on a new sheet. The "Enable show details" option (`pivot.options` `enableShowDetails`, saved as `enableDrill`) turns it off; it has no PivotTable Options dialog - yet (command only). + yet (command only). Refreshing a file's pivot keeps its sort-by-value, captions, item order and layout settings; Excel's order among items with equal sort values is not reproduced. - **Impact:** pivots are the analyst's main tool. - **Estimate:** 20–30 h for beta (25–40 h full). @@ -221,6 +221,7 @@ No alpha blockers: every core workflow passes the [alpha gate](roadmap.md#alpha- | 2026-10-17 | minor | Conditional formatting: the 2-/3-colour scale branch of the New Formatting Rule dialog edits per-stop type/value/colour and updates rules in place (part of #1165) | | 2026-10-15 | minor | §6: Maximum Iterations and Maximum Change in File › Options › Formulas; dropped the stale "no Options dialog yet" | | 2026-10-15 | minor | §13: Solver prepares reports before committing the solution, model and report sheets together; report refusal preserves the workbook and Undo/Redo (#1050) | +| 2026-10-13 | minor | §8: refresh fidelity for file pivots (sort by value, captions, item order, layout settings) | | 2026-10-13 | minor | §3: Excel 2010 conditional formats (`x14:conditionalFormattings`, cross-sheet rules) read, evaluated and written back in the extension | | 2026-10-13 | trivial | §4: multi-level category axes landed | | 2026-10-12 | minor | §9: next/previous sheet commands retain the current visible sheet and selection when there is no visible destination | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3c89484a69..e9699beec2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -85,7 +85,7 @@ performance 8, stability 8, localization 4, hardware 2, platforms 2, ecosystem 2 | Editing, navigation, clipboard, fill | 12 | ~90% | ~70% | 15–25 | Point mode, F4, AutoComplete, Paste Special, AutoFill, Flash Fill, Find/Replace, Go To Special. Bugs: rectangular drag-select (#28), monthly fill (#132), cut across sheets (#128), Insert Copied Cells missing (#21), key tips only on part of the Home tab (#43; #33, #49). [ui-parity.md](ui-parity.md) | | Cell formatting, styles, conditional formatting | 10 | ~95% | ~80% | 8–14 | Full number-format language, borders, 47 cell styles, 60 table styles, all CF rule kinds including data bars, colour scales and icon sets. Gaps: font weights beyond regular/bold (#168), system fonts list (#4), themes | | Sort, filter, tables, validation, outline | 8 | ~82% | ~70% | 10–16 | Multi-level sort, AutoFilter, Advanced Filter, tables with totals, validation, outline, subtotals, consolidate. Advanced Filter copy-to preserves cells outside its result and rejects worksheet overflow (#1031). Bugs: subtotal header (#131), validation edits (#129), table style panic caught (#130); no slicers on tables | -| PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, GETPIVOTDATA, XLSX round-trip. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, Generate GetPivotData, data-model pivots. Round-trip never checked in Excel | +| PivotTables | 7 | ~65% | ~45% | 25–40 | Insert/Recommended, field list, three layouts, values on rows or columns, date grouping, show-values-as, refresh, calculated fields, GETPIVOTDATA, sort by a value field, custom captions and item names, XLSX round-trip of the layout settings refreshed file pivots need. Missing: slicers, timelines, calculated items, PivotCharts, value/label filters, number grouping, Generate GetPivotData, data-model pivots. Round-trip never checked in Excel | | Charts and sparklines | 8 | ~50% | ~30% | 40–60 | 25 chart kinds, all 2-D. Doughnut charts draw every series as a concentric ring (first series innermost), with editable hole size and first slice angle. The chart model holds title, legend position, a data-labels flag, gridlines flag, axis titles and chart data tables (legend keys, borders, XLSX round-trip and print/PDF); no axis scaling, error bars, per-point formatting, chart sheets, 3-D, surface, map, Pareto. Kinds survive XLSX round trip (#158, #161), except stock charts: only 3–4 series are a stock chart, and any other count is written and reimported as a line chart. [chart-parity.md](chart-parity.md) | | Page layout, print, PDF | 5 | ~80% | ~55% | 12–20 | Page setup, print titles, breaks, page order, Page Break Preview, headers/footers, PDF export and printing. Paper sizes match Japanese Excel: B4/B5/B6 are the JIS sizes, ISO B4/B5/B6 stay reachable by name, and Japanese Postcard (はがき), Japanese Double Postcard (往復はがき), the chou/kaku envelopes and A6 are available. No true Page Layout view; the PDF writer uses only the 14 standard fonts without embedding (no CJK or other non-Latin text in PDF); web print only exports (#141, #143) | | What-if and analysis | 4 | ~50% | ~40% | 22–35 | Goal Seek, Scenario Manager, data tables, Analysis ToolPak (all 19 tools, no charts), Solver (Simplex LP, a local nonlinear method and Evolutionary; Answer, Sensitivity and Limits reports; Load/Save Model, Reset All and Solver Options; no Population report), Forecast Sheet. Missing: Analyze Data | @@ -367,6 +367,7 @@ The inventory carried over from the 2026-10-07 ROADMAP.md, updated for what land | 2026-10-15 | minor | Row auto-fit: line breaks count only in wrapping cells (Excel: wrap off shows one line, AutoFit gives one line); unwrapped multi-line cells from files no longer grow rows on open (no score change) | | 2026-10-12 | minor | Worksheet functions 514 / 523 (98.3%; 505 working): GETPIVOTDATA | | 2026-10-21 | minor | Automation: typed macros in the engine and `macro.*` commands, no interface yet (no score change); catalog 274 / 290 → 275 / 291 (View › Macros › Record Macro) | +| 2026-10-13 | minor | PivotTables: sort by a value field (`pivot.sort by:`), row/column/data/grand-total/empty-cell captions, field and item custom names, manual item order, per-field subtotals and number formats, Repeat Item Labels, Values row, classic layout. Refreshing 26 PivotTables from 11 real workbooks: 7,271 cell differences against Excel's saved output on main (6e984bb) → 3,446, the rest filters (#498) and Excel's order among tied values | | 2026-10-12 | minor | Essentials AutoFit evidence: rows auto-fit oversized fonts on open and row formatting (#833) | | 2026-10-12 | minor | Sheet tabs: reveal the selected tab on navigation and resize while preserving manual scrolling (#681); no score change | | 2026-10-12 | minor | PivotTables: values on rows (Σ Values in Rows at any position, all three layouts; `pivot.moveField` and the field pane move it; `dataOnRows` round-trips) (no score change) |