Skip to main content

visi_core/core/
pivot.rs

1//! Pivot table definitions and the pure function that computes one.
2//!
3//! A [`PivotTable`] is a *definition*: where the records come from, which
4//! fields go in the row, column, value and filter areas, and where the result
5//! should land. [`compute_pivot`] turns that definition plus the workbook's
6//! sheets into a [`PivotGrid`], a display-ready set of header and body rows.
7//!
8//! Computing a grid never touches a sheet. Writing one into cells is
9//! `WorkbookManager::refresh_pivot_table`'s job, and -- as in Excel -- it only
10//! happens when something asks for it: **nothing recomputes a pivot table
11//! implicitly**, not `Sheet::commit` and not `WorkbookManager::evaluate`, so
12//! editing the source data leaves the rendered grid stale until a refresh.
13//! Every CRUD operation on a pivot definition refreshes explicitly afterward.
14//!
15//! Unlike an [`ExcelTable`](crate::core::table::ExcelTable), which is scoped
16//! to one sheet, a pivot table is workbook-level: its source and destination
17//! ranges may live on different sheets, so `WorkbookManager` owns the list.
18
19use serde::{Deserialize, Serialize};
20use std::collections::HashMap;
21
22use crate::core::engine::{CellRef, ResultData, Sheet};
23
24/// Where a `PivotTable` reads its source records from: either an existing
25/// `ExcelTable` (looked up by name at compute time, so renames/resizes of
26/// the table are picked up automatically on refresh) or a plain cell range
27/// whose first row is treated as column headers.
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29pub enum PivotSource {
30    /// An `ExcelTable`, resolved by name on every refresh.
31    Table {
32        /// The table's name, matched case-insensitively workbook-wide.
33        name: String,
34    },
35    /// A raw rectangular range, whose first row supplies the field names.
36    Range {
37        /// Sheet the range lives on.
38        sheet_id: u64,
39        /// First row of the range, 0-based, and the header row.
40        start_row: usize,
41        /// First column of the range, 0-based.
42        start_col: usize,
43        /// Last row of the range, 0-based and inclusive.
44        end_row: usize,
45        /// Last column of the range, 0-based and inclusive.
46        end_col: usize,
47    },
48}
49
50/// Matches the "Summarize value field by" choices Excel exposes for a data
51/// field; the five most commonly used ones plus the numeric-only count.
52#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
53pub enum PivotAggregation {
54    /// Total of the numeric values.
55    Sum,
56    /// How many non-blank values there are, text included.
57    Count,
58    /// How many values are numbers.
59    CountNumbers,
60    /// Mean of the numeric values.
61    Average,
62    /// Largest numeric value.
63    Max,
64    /// Smallest numeric value.
65    Min,
66}
67
68impl PivotAggregation {
69    /// The caption Excel uses for this aggregation in a value field's default
70    /// label ("Sum of Amount").
71    ///
72    /// [`PivotAggregation::CountNumbers`] shares `Count`'s caption, which is
73    /// why two such fields on one column collide and get disambiguated by
74    /// [`value_field_labels`].
75    pub fn label(&self) -> &'static str {
76        match self {
77            PivotAggregation::Sum => "Sum",
78            // Excel's default value-field caption for "Count Numbers" is
79            // "Count of <field>" -- identical to plain "Count" -- not
80            // "Count Numbers of <field>"; there's no separate caption text
81            // for it in Excel's own UI (confirmed via fuzz/fuzz_pivot.py
82            // against real Excel).
83            PivotAggregation::Count | PivotAggregation::CountNumbers => "Count",
84            PivotAggregation::Average => "Average",
85            PivotAggregation::Max => "Max",
86            PivotAggregation::Min => "Min",
87        }
88    }
89
90    /// Parses a user-supplied aggregation name, ignoring case, spaces,
91    /// underscores and hyphens, and accepting the common short forms (`avg`,
92    /// `countnums`, `maximum`). `None` if it names nothing.
93    pub fn parse(s: &str) -> Option<Self> {
94        match s.to_ascii_lowercase().replace(['_', '-', ' '], "").as_str() {
95            "sum" => Some(Self::Sum),
96            "count" => Some(Self::Count),
97            "countnumbers" | "countnums" => Some(Self::CountNumbers),
98            "average" | "avg" => Some(Self::Average),
99            "max" | "maximum" => Some(Self::Max),
100            "min" | "minimum" => Some(Self::Min),
101            _ => None,
102        }
103    }
104}
105
106/// One field placed in the Row or Column area.
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
108pub struct PivotField {
109    /// Name of the source column to group by, matched against the header row.
110    pub column: String,
111    /// Whether a subtotal line is emitted for this field when it isn't the
112    /// innermost field in its area (Excel's per-field "Subtotals" toggle).
113    pub subtotal: bool,
114}
115
116impl PivotField {
117    /// A field on `column` with subtotals enabled, Excel's default.
118    pub fn new(column: impl Into<String>) -> Self {
119        Self {
120            column: column.into(),
121            subtotal: true,
122        }
123    }
124}
125
126/// One field placed in the Values area.
127#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
128pub struct PivotValueField {
129    /// Name of the source column to aggregate, matched against the header row.
130    pub column: String,
131    /// How the column's values are summarized.
132    pub aggregation: PivotAggregation,
133    /// Overrides the default "Sum of Amount" caption. A custom name is used
134    /// verbatim and takes no part in [`value_field_labels`]' disambiguation.
135    pub custom_name: Option<String>,
136}
137
138impl PivotValueField {
139    /// A value field on `column` with the default caption.
140    pub fn new(column: impl Into<String>, aggregation: PivotAggregation) -> Self {
141        Self {
142            column: column.into(),
143            aggregation,
144            custom_name: None,
145        }
146    }
147
148    /// This field's caption considered on its own, ignoring any collision
149    /// with the pivot's other value fields. Use [`value_field_labels`] to
150    /// caption a whole list the way Excel would.
151    pub fn label(&self) -> String {
152        self.custom_name
153            .clone()
154            .unwrap_or_else(|| format!("{} of {}", self.aggregation.label(), self.column))
155    }
156}
157
158/// Default display labels for a pivot's whole value-field list, matching
159/// Excel's own (surprisingly convoluted) disambiguation for repeated
160/// source columns -- derived empirically against real Excel via
161/// fuzz/fuzz_pivot.py plus direct probing (see the probe script referenced
162/// in the PR that added this comment), since none of it is documented.
163///
164/// Two independent mechanisms are in play, both scoped per source column:
165///
166/// 1. **The "Sum" clone.** The *first* value field for a column that uses
167///    the `Sum` aggregation causes Excel to silently clone that column
168///    into a new pseudo-field ("Amount" -> "Amount2") for every value
169///    field *after* it in the list (not before) -- regardless of their own
170///    aggregation. A *second* `Sum` on the same column clones again
171///    ("Amount2" -> "Amount3"), but non-`Sum` aggregations never trigger a
172///    further clone; they just ride whatever clone slot is already active.
173///    E.g. `[Sum, Max, Count]` on "Amount" -> `["Sum of Amount", "Max of
174///    Amount2", "Count of Amount2"]` (both non-Sum fields share slot 2);
175///    `[Sum, Sum, Count]` -> `["Sum of Amount", "Sum of Amount2", "Count
176///    of Amount3"]` (the second Sum clones again). A column with *no* Sum
177///    value field anywhere is never cloned at all.
178/// 2. **Literal caption collision.** Independent of the above, if two
179///    value fields end up wanting the exact same caption text, Excel still
180///    has to disambiguate. If neither is in a Sum-cloned slot, it appends
181///    a plain digit straight onto the column name (`"Count of Amount"`,
182///    `"Count of Amount2"`, `"Count of Amount3"`, ...) -- this is also how
183///    `CountNumbers` colliding with `Count` gets suffixed, since both
184///    share the caption label "Count" (see `PivotAggregation::label`). If
185///    the collision instead happens *inside* an already Sum-cloned slot
186///    (two non-Sum fields sharing one clone with the same aggregation),
187///    Excel instead appends an underscored counter to the *whole* already-
188///    suffixed caption (`"Max of Amount2"`, `"Max of Amount2_2"`) rather
189///    than incrementing the clone number again.
190///
191/// An explicit `custom_name` bypasses both mechanisms entirely -- it's
192/// used as-is and doesn't consume a collision slot or trigger a clone.
193pub fn value_field_labels(value_fields: &[PivotValueField]) -> Vec<String> {
194    let mut clone_suffix: HashMap<&str, usize> = HashMap::new();
195    let mut next_clone: HashMap<&str, usize> = HashMap::new();
196    let mut label_counts: HashMap<String, usize> = HashMap::new();
197
198    value_fields
199        .iter()
200        .map(|vf| {
201            if let Some(name) = &vf.custom_name {
202                return name.clone();
203            }
204            let agg_label = vf.aggregation.label();
205            let in_clone_slot = clone_suffix.contains_key(vf.column.as_str());
206            let base_column = match clone_suffix.get(vf.column.as_str()) {
207                Some(n) => format!("{}{}", vf.column, n),
208                None => vf.column.clone(),
209            };
210            let base_label = format!("{} of {}", agg_label, base_column);
211            let count = label_counts.entry(base_label.clone()).or_insert(0);
212            *count += 1;
213            let label = if *count == 1 {
214                base_label
215            } else if in_clone_slot {
216                format!("{}_{}", base_label, count)
217            } else {
218                format!("{} of {}{}", agg_label, vf.column, count)
219            };
220            if vf.aggregation == PivotAggregation::Sum {
221                let assigned = *next_clone.entry(vf.column.as_str()).or_insert(2);
222                next_clone.insert(vf.column.as_str(), assigned + 1);
223                clone_suffix.insert(vf.column.as_str(), assigned);
224            }
225            label
226        })
227        .collect()
228}
229
230/// One field placed in the Filter (Page) area.
231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
232pub struct PivotFilterField {
233    /// Name of the source column to filter on, matched against the header row.
234    pub column: String,
235    /// `None` means every value is allowed (no filtering applied yet).
236    ///
237    /// **Reconstructed on xlsx import**, resolved through the cache's
238    /// `<sharedItems>` to plain value strings rather than kept as indices --
239    /// which is what makes it safe. The indices are trusted only against the
240    /// cache definition in the same file, which is self-consistent by
241    /// construction, and a value that no longer exists in changed source data
242    /// simply matches nothing.
243    ///
244    /// Two things do not survive, both because the format cannot hold them:
245    ///
246    /// - A selection covering *every* value marks nothing hidden, so it is
247    ///   indistinguishable from no filter and reads back as `None`. The
248    ///   grid is the same either way.
249    /// - A filter on a column that is *also* a row or column field is lost
250    ///   entirely: a pivot field carries one `axis`, so there is nowhere to
251    ///   record it. Excel cannot express that config at all -- a field has
252    ///   exactly one orientation there.
253    ///
254    /// Matching is case-insensitive, because the items themselves are merged
255    /// that way; a selection naming `east` picks the merged `East` item.
256    pub selected_values: Option<Vec<String>>,
257    /// Whether the field is in Excel's *multi-select* page mode
258    /// (`multipleItemSelectionAllowed` in the file) rather than its classic
259    /// single-select one.
260    ///
261    /// The two differ in what the page-field cell says, which is observable:
262    /// with one item chosen, multi-select shows `(Multiple Items)` while
263    /// single-select shows the **item's own name**. Both measured -- the
264    /// first through `PivotItems(x).Visible = False`, the second through
265    /// `PivotField.CurrentPage = "Widget"`, which is what puts a field into
266    /// single-select mode in the first place.
267    ///
268    /// Defaults to `true`, matching `set_pivot_filter` and the CLI, which
269    /// select a set of values rather than one page.
270    #[serde(default = "default_true")]
271    pub multiple_selection: bool,
272}
273
274fn default_true() -> bool {
275    true
276}
277
278impl PivotFilterField {
279    /// A filter field on `column` with nothing filtered out yet.
280    pub fn new(column: impl Into<String>) -> Self {
281        Self {
282            column: column.into(),
283            selected_values: None,
284            multiple_selection: true,
285        }
286    }
287}
288
289/// The area of a pivot table a field can be assigned to, used by the
290/// add/remove-field CRUD operations.
291#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
292pub enum PivotArea {
293    /// Groups down the left edge; adds to `PivotTable::row_fields`.
294    Row,
295    /// Groups across the top; adds to `PivotTable::col_fields`.
296    Column,
297    /// Aggregated data; adds to `PivotTable::value_fields`.
298    Value,
299    /// Restricts which source records take part; adds to
300    /// `PivotTable::filter_fields`.
301    Filter,
302}
303
304/// A pivot table definition: a summary of `source`, grouped by `row_fields`
305/// nested within `col_fields`, restricted by `filter_fields`, and
306/// aggregated per `value_fields`. This is a workbook-level object (like
307/// `Chart`) rather than sheet-scoped like `ExcelTable`, since its source and
308/// destination ranges may live on different sheets.
309#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
310pub struct PivotTable {
311    /// Workbook-unique identifier, stable across renames.
312    pub id: u64,
313    /// Display name, unique workbook-wide.
314    pub name: String,
315    /// Where the records come from.
316    pub source: PivotSource,
317    /// Sheet the grid is written to, which need not be the source's sheet.
318    pub dest_sheet_id: u64,
319    /// Top-left row of the output grid, 0-based.
320    pub dest_row: usize,
321    /// Top-left column of the output grid, 0-based.
322    pub dest_col: usize,
323    /// Fields grouped down the left edge, outermost first.
324    pub row_fields: Vec<PivotField>,
325    /// Fields grouped across the top, outermost first.
326    pub col_fields: Vec<PivotField>,
327    /// Fields aggregated into the body. At least one is required for
328    /// [`compute_pivot`] to succeed.
329    pub value_fields: Vec<PivotValueField>,
330    /// Fields restricting which source records take part.
331    pub filter_fields: Vec<PivotFilterField>,
332    /// Whether a grand-total row is appended below the body.
333    pub grand_totals_row: bool,
334    /// Whether a grand-total column is appended to the right of the body.
335    pub grand_totals_col: bool,
336    /// Bottom-right corner of the last rendered output grid, so a refresh
337    /// that produces a smaller grid can clear the now-stale cells.
338    #[serde(default)]
339    pub last_output_end_row: Option<usize>,
340    /// Column half of that corner; see [`PivotTable::last_output_end_row`].
341    #[serde(default)]
342    pub last_output_end_col: Option<usize>,
343}
344
345/// Width, in columns, reserved for row-field labels: one column per row
346/// field when there are any. With no row fields at all, Excel only
347/// reserves a single placeholder column when there's *exactly one* value
348/// field *and* at least one column field for it to sit to the left of --
349/// that lone cell holds the value field's own label (e.g. "Max of
350/// Amount"), the same way the header's "Row Labels | Sum of X" corner
351/// would if there were row fields. With no column fields either (the fully
352/// "flat" single-aggregate pivot) or with more than one value field (whose
353/// labels already show up elsewhere in the header), there's nothing
354/// unambiguous to put in a corner, so Excel reserves no column there at
355/// all. All three shapes verified against real Excel via
356/// fuzz/fuzz_pivot.py. Shared between `compute_pivot` (which must actually
357/// size `PivotBodyRow::row_labels` this way) and `pivot_xlsx.rs` (which
358/// needs the same number for `firstDataCol`).
359pub(crate) fn row_label_width(pivot: &PivotTable) -> usize {
360    if !pivot.row_fields.is_empty() {
361        return pivot.row_fields.len();
362    }
363    if pivot.value_fields.len() == 1 && !pivot.col_fields.is_empty() {
364        1
365    } else {
366        0
367    }
368}
369
370/// A fully computed pivot result, ready to be materialized into a sheet:
371/// `filter_rows` (if any) come first, then a blank spacer row, then
372/// `header_rows`, then one entry of `body_rows` per output row -- mirroring
373/// Excel's own report-filter placement (verified against real Excel: it
374/// always reserves one row per filter field plus a blank spacer above the
375/// row/column header grid, and captions each with a "(All)"/"(Multiple
376/// Items)" state -- never a specific value's name, since that's specific to
377/// the classic single-select page-field mode Excel no longer defaults to).
378#[derive(Debug, Clone)]
379pub struct PivotGrid {
380    /// One `(field name, state)` pair per filter field, in the order they
381    /// were added.
382    ///
383    /// The state is `"(All)"` when every value is allowed, the **item's own
384    /// name** when exactly one is selected, and `"(Multiple Items)"`
385    /// otherwise -- which is what Excel puts in the page-field cell, and what
386    /// `PivotField.CurrentPage` reports alongside it.
387    pub filter_rows: Vec<(String, String)>,
388    /// The column-header block above the body: one row per column field,
389    /// plus a value-field row when there is more than one value field.
390    pub header_rows: Vec<Vec<String>>,
391    /// The body, one entry per output row, subtotal and grand-total rows
392    /// included.
393    pub body_rows: Vec<PivotBodyRow>,
394    /// Total width in columns (row-label columns + data columns), used by
395    /// the caller to know how large a range to clear/allocate. Always >= 2,
396    /// so `filter_rows`' two columns (name, state) always fit within it.
397    pub width: usize,
398    /// The flattened row/column axis groups underlying `body_rows`/the data
399    /// columns, exposed (independent of display formatting) so an xlsx
400    /// exporter can reconstruct a native `pivotTableDefinition`'s
401    /// `rowItems`/`colItems` without re-deriving the grouping itself.
402    pub row_axis: Vec<PivotAxisItem>,
403    /// Column half of that axis pair; see [`PivotGrid::row_axis`].
404    pub col_axis: Vec<PivotAxisItem>,
405}
406
407/// One row of a computed pivot's body: its row-field labels and its
408/// aggregated values.
409#[derive(Debug, Clone)]
410pub struct PivotBodyRow {
411    /// One entry per row field (or a single "Grand Total" entry when there
412    /// are no row fields); blank entries mean "same as the row above".
413    pub row_labels: Vec<String>,
414    /// Whether this row is the grand total rather than a data or subtotal row.
415    pub is_grand_total: bool,
416    /// One entry per data column, aligned with the last `header_rows` row.
417    pub values: Vec<ResultData>,
418}
419
420/// One flattened group along a row or column axis: a label per axis field
421/// (`None` past its own depth), plus whether it's a subtotal or grand-total
422/// pseudo-group rather than a real leaf group.
423#[derive(Debug, Clone)]
424pub struct PivotAxisItem {
425    /// One entry per field in this axis, `None` past this group's own depth.
426    pub labels: Vec<Option<String>>,
427    /// Whether this is a subtotal pseudo-group rather than a leaf group.
428    pub is_subtotal: bool,
429    /// Whether this is the axis's grand-total pseudo-group.
430    pub is_grand_total: bool,
431}
432
433impl PivotGrid {
434    /// Row offset from the pivot's `dest_row` anchor to where the row/col
435    /// header + data grid actually begins: 0 with no filter fields, else
436    /// one row per filter field plus a blank spacer row.
437    pub fn grid_row_offset(&self) -> usize {
438        if self.filter_rows.is_empty() {
439            0
440        } else {
441            self.filter_rows.len() + 1
442        }
443    }
444
445    /// Total height in rows, filter rows and spacer included -- what the
446    /// caller needs to allocate or clear at the pivot's `dest_row` anchor.
447    pub fn height(&self) -> usize {
448        self.grid_row_offset() + self.header_rows.len() + self.body_rows.len()
449    }
450}
451
452/// A flattened, labeled group of source records along one axis (row or
453/// column), produced by recursively grouping by each field in that axis in
454/// turn. `record_indices` is the union of every record folded into this
455/// group -- for a leaf group that's just its own bucket, for a subtotal or
456/// grand-total pseudo-group it's every record under it.
457struct FlatGroup {
458    /// One label per field in this axis; `None` past the group's own depth
459    /// (e.g. a subtotal group has no label for deeper fields).
460    labels: Vec<Option<String>>,
461    record_indices: Vec<usize>,
462    is_subtotal: bool,
463    is_grand_total: bool,
464}
465
466struct GroupNode {
467    label: String,
468    record_indices: Vec<usize>,
469    children: Vec<GroupNode>,
470}
471
472pub(crate) fn group_key(result: &ResultData) -> String {
473    match result {
474        ResultData::None => "(blank)".to_string(),
475        ResultData::String(s) if s.is_empty() => "(blank)".to_string(),
476        other => other.to_string(),
477    }
478}
479
480/// Whether every non-blank value of `records[..][field_idx]` is a genuine
481/// number (`Integer`/`Float`), as opposed to text that merely looks
482/// numeric (e.g. a zero-padded code like `"08"`, or digits kept as text on
483/// purpose). Determines sort order for that field's pivot groups --
484/// Excel sorts a real numeric field numerically but a text field
485/// alphabetically even when its values happen to look like numbers
486/// (verified against real Excel via fuzz/fuzz_pivot.py's `NumStr` column,
487/// whose whole purpose is generating quoted numeric-looking text to probe
488/// exactly this) -- with one refinement found on Windows: a value that
489/// looks like a *negative* number sorts by its digits with the leading
490/// `-` stripped, not by the `-` character itself. See
491/// `sort_group_entries` and `text_sort_key`. Grouping already collapsed
492/// values to strings by this point (`group_key`), which can no longer
493/// tell a real `22` from a text `"22"` -- this has to be decided from the
494/// original `ResultData`s.
495pub(crate) fn field_is_numeric(records: &[Vec<ResultData>], field_idx: usize) -> bool {
496    !records.is_empty()
497        && records.iter().all(|r| {
498            matches!(
499                r.get(field_idx),
500                Some(ResultData::Integer(_)) | Some(ResultData::Float(_)) | Some(ResultData::None)
501            )
502        })
503}
504
505/// The key `sort_group_entries`'s text-field branch compares siblings by:
506/// the value itself, lowercased, *unless* it looks like a negative number
507/// (`"-7"`, `"-25"`), in which case the leading `-` is stripped first.
508/// Measured on Windows real Excel across three independent sibling sets
509/// (fuzz/fuzz_pivot.py's `NumStr` column):
510///   `{-7, .0152, 13, 34, 4}`        -> `.0152, 13, 34, 4, -7`
511///   `{-46, .097, 01, 02, 1, 10, 35}` -> `.097, 01, 02, 1, 10, 35, -46`
512///   `{-25, .0599, .0839, 01, 02, 08, 1, 12, 37}`
513///                                   -> `.0599, .0839, 01, 02, 08, 1, 12, -25, 37`
514/// A "sorts last" rule (visi's first attempt at this) fits the first two
515/// but not the third, where "-25" lands *before* "37" -- comparing "25"
516/// (the stripped digits) against the other keys fits all three: "25"
517/// falls between "12" and "37" alphabetically, exactly where Excel put
518/// "-25". Not tested (no evidence either way): two negative-looking
519/// siblings compared against each other -- both get stripped, so they
520/// fall back to comparing their digit strings.
521fn text_sort_key(s: &str) -> String {
522    let trimmed = s.trim();
523    let key = match trimmed.strip_prefix('-') {
524        Some(rest) if rest.starts_with(|c: char| c.is_ascii_digit()) => rest,
525        _ => trimmed,
526    };
527    key.to_lowercase()
528}
529
530fn sort_group_entries(pairs: &mut [(String, Vec<usize>)], numeric: bool) {
531    // A blank/empty group always sorts last, regardless of the field's
532    // otherwise-numeric-or-text order (verified against real Excel via
533    // fuzz/fuzz_pivot.py).
534    pairs.sort_by(|a, b| match (a.0 == "(blank)", b.0 == "(blank)") {
535        (true, true) => std::cmp::Ordering::Equal,
536        (true, false) => std::cmp::Ordering::Greater,
537        (false, true) => std::cmp::Ordering::Less,
538        (false, false) if numeric => {
539            let fa: f64 = a.0.trim().parse().unwrap_or(0.0);
540            let fb: f64 = b.0.trim().parse().unwrap_or(0.0);
541            fa.partial_cmp(&fb).unwrap_or(std::cmp::Ordering::Equal)
542        }
543        (false, false) => text_sort_key(&a.0).cmp(&text_sort_key(&b.0)),
544    });
545}
546
547fn build_group_tree(
548    indices: &[usize],
549    keys: &[Vec<String>],
550    depth: usize,
551    num_fields: usize,
552    numeric_by_depth: &[bool],
553) -> Vec<GroupNode> {
554    // Case-insensitive merge (verified against real Excel via
555    // fuzz/fuzz_pivot.py, whose generator deliberately mixes casings like
556    // "East"/"east" to probe this): Excel's PivotTable field grouping
557    // treats text values that differ only in case as the same group,
558    // captioned with whichever casing appeared first in the source data --
559    // which fewer distinct `groups` entries than `keys` naturally
560    // preserves here, since only the first-seen spelling of a key ever
561    // becomes `entry.0`.
562    let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
563    for &idx in indices {
564        let key = &keys[idx][depth];
565        if let Some(entry) = groups.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case(key)) {
566            entry.1.push(idx);
567        } else {
568            groups.push((key.clone(), vec![idx]));
569        }
570    }
571    sort_group_entries(&mut groups, numeric_by_depth[depth]);
572    groups
573        .into_iter()
574        .map(|(label, idxs)| {
575            let children = if depth + 1 < num_fields {
576                build_group_tree(&idxs, keys, depth + 1, num_fields, numeric_by_depth)
577            } else {
578                Vec::new()
579            };
580            GroupNode {
581                label,
582                record_indices: idxs,
583                children,
584            }
585        })
586        .collect()
587}
588
589/// Recursively flattens a group tree into a list of `FlatGroup`s: every leaf
590/// group, plus (when enabled for that field) a subtotal pseudo-group after
591/// each non-innermost group's children.
592fn flatten_groups(
593    nodes: &[GroupNode],
594    fields: &[PivotField],
595    depth: usize,
596    num_fields: usize,
597    prefix: &[Option<String>],
598    out: &mut Vec<FlatGroup>,
599) {
600    for node in nodes {
601        // `labels` holds exactly this node's own depth (depth+1 entries) so
602        // that a child's `push` lands at the right position; it's only
603        // padded out to `num_fields` at the point a `FlatGroup` is actually
604        // emitted (leaf or subtotal), never before recursing further.
605        let mut labels = prefix.to_vec();
606        labels.push(Some(node.label.clone()));
607
608        if node.children.is_empty() {
609            let mut leaf_labels = labels.clone();
610            leaf_labels.resize(num_fields, None);
611            out.push(FlatGroup {
612                labels: leaf_labels,
613                record_indices: node.record_indices.clone(),
614                is_subtotal: false,
615                is_grand_total: false,
616            });
617        } else {
618            flatten_groups(&node.children, fields, depth + 1, num_fields, &labels, out);
619            let is_innermost = depth + 1 >= num_fields;
620            if fields[depth].subtotal && !is_innermost {
621                let mut subtotal_labels = labels.clone();
622                subtotal_labels.resize(num_fields, None);
623                out.push(FlatGroup {
624                    labels: subtotal_labels,
625                    record_indices: node.record_indices.clone(),
626                    is_subtotal: true,
627                    is_grand_total: false,
628                });
629            }
630        }
631    }
632}
633
634/// Builds the flattened axis groups for `fields` over `record_indices`,
635/// optionally appending a grand-total pseudo-group. Returns a single
636/// implicit "all records" group when `fields` is empty.
637fn build_axis(
638    record_indices: &[usize],
639    keys: &[Vec<String>],
640    fields: &[PivotField],
641    grand_total: bool,
642    numeric_by_depth: &[bool],
643) -> Vec<FlatGroup> {
644    if fields.is_empty() {
645        return vec![FlatGroup {
646            labels: Vec::new(),
647            record_indices: record_indices.to_vec(),
648            is_subtotal: false,
649            is_grand_total: false,
650        }];
651    }
652    let tree = build_group_tree(record_indices, keys, 0, fields.len(), numeric_by_depth);
653    let mut flat = Vec::new();
654    flatten_groups(&tree, fields, 0, fields.len(), &[], &mut flat);
655    // Excel shows the grand total whenever the toggle is on, even when
656    // there's only one real group and the grand total would be a literal
657    // duplicate of it -- confirmed against real Excel via
658    // fuzz/fuzz_pivot.py: a column axis with a single field, filtered down
659    // to exactly one distinct value (so there's no possible subtotal
660    // either), still got its own redundant "Grand Total" column. Only
661    // skip it when there's no data to total at all.
662    if grand_total && !flat.is_empty() {
663        flat.push(FlatGroup {
664            labels: vec![None; fields.len()],
665            record_indices: record_indices.to_vec(),
666            is_subtotal: false,
667            is_grand_total: true,
668        });
669    }
670    flat
671}
672
673fn aggregate(sheet: &Sheet, values: &[ResultData], agg: PivotAggregation) -> ResultData {
674    // A row/column intersection with zero underlying records (a sparse
675    // cell in the cross-tab -- e.g. a row group and column group that
676    // simply never co-occur in the source data) renders as a genuinely
677    // blank cell in Excel, not a computed zero or #DIV/0! error, for every
678    // aggregation kind (verified against real Excel via fuzz/fuzz_pivot.py:
679    // even Count and Sum, which have an obvious "zero" answer, still show
680    // blank there). This is distinct from records existing but this
681    // column's values all being blank for them, which the per-aggregation
682    // branches below already handle on their own terms (e.g. Max/Min over
683    // an all-blank column already fall back to `ResultData::None`).
684    if values.is_empty() {
685        return ResultData::None;
686    }
687    match agg {
688        PivotAggregation::Count => ResultData::Integer(
689            values
690                .iter()
691                .filter(|v| !matches!(v, ResultData::None))
692                .count() as i64,
693        ),
694        PivotAggregation::CountNumbers => ResultData::Integer(
695            values
696                .iter()
697                .filter(|v| matches!(v, ResultData::Integer(_) | ResultData::Float(_)))
698                .count() as i64,
699        ),
700        _ => {
701            let nums: Vec<f64> = values
702                .iter()
703                .filter_map(|v| match v {
704                    ResultData::Integer(_) | ResultData::Float(_) => sheet.to_f64(v),
705                    _ => None,
706                })
707                .collect();
708            match agg {
709                PivotAggregation::Sum => {
710                    if nums.is_empty() {
711                        ResultData::Integer(0)
712                    } else {
713                        ResultData::Float(Sheet::clean_float(nums.iter().sum()))
714                    }
715                }
716                PivotAggregation::Average => {
717                    if nums.is_empty() {
718                        ResultData::Error("#DIV/0!".to_string())
719                    } else {
720                        let avg = nums.iter().sum::<f64>() / nums.len() as f64;
721                        ResultData::Float(Sheet::clean_float(avg))
722                    }
723                }
724                PivotAggregation::Max => nums
725                    .into_iter()
726                    .fold(None, |acc: Option<f64>, x| {
727                        Some(acc.map_or(x, |a| a.max(x)))
728                    })
729                    .map(ResultData::Float)
730                    .unwrap_or(ResultData::None),
731                PivotAggregation::Min => nums
732                    .into_iter()
733                    .fold(None, |acc: Option<f64>, x| {
734                        Some(acc.map_or(x, |a| a.min(x)))
735                    })
736                    .map(ResultData::Float)
737                    .unwrap_or(ResultData::None),
738                PivotAggregation::Count | PivotAggregation::CountNumbers => unreachable!(),
739            }
740        }
741    }
742}
743
744/// Resolves a `PivotSource` against the workbook's sheets, returning the
745/// owning sheet, the source's column names (in source-column order), the
746/// matching absolute sheet-column indices, and the absolute sheet-row
747/// indices holding data (i.e. excluding any header/totals row).
748/// (owning sheet, source column names, absolute sheet-column indices, absolute data-row indices).
749pub(crate) type ResolvedSource<'a> = (&'a Sheet, Vec<String>, Vec<usize>, Vec<usize>);
750
751pub(crate) fn resolve_source<'a>(
752    sheets: &'a [&'a Sheet],
753    source: &PivotSource,
754) -> Result<ResolvedSource<'a>, String> {
755    match source {
756        PivotSource::Table { name } => {
757            let (sheet, table) = sheets
758                .iter()
759                .find_map(|s| s.find_table(name).map(|t| (*s, t)))
760                .ok_or_else(|| format!("Table '{}' not found", name))?;
761            let cols: Vec<usize> = (table.start_col..=table.end_col).collect();
762            let rows: Vec<usize> = (table.data_start_row()..=table.data_end_row()).collect();
763            Ok((sheet, table.columns.clone(), cols, rows))
764        }
765        PivotSource::Range {
766            sheet_id,
767            start_row,
768            start_col,
769            end_row,
770            end_col,
771        } => {
772            let sheet = *sheets
773                .iter()
774                .find(|s| s.id == *sheet_id)
775                .ok_or_else(|| "Pivot source sheet no longer exists".to_string())?;
776            if *end_row < *start_row || *end_col < *start_col {
777                return Err("Pivot source range end must not precede its start".to_string());
778            }
779            let cols: Vec<usize> = (*start_col..=*end_col).collect();
780            let names: Vec<String> = cols
781                .iter()
782                .map(|&c| {
783                    let v = sheet.get_result_data(&CellRef::new(*start_row, c));
784                    let s = v.to_string();
785                    if s.is_empty() {
786                        crate::core::parser::col_idx_to_letters(c)
787                    } else {
788                        s
789                    }
790                })
791                .collect();
792            let rows: Vec<usize> = if *end_row > *start_row {
793                (*start_row + 1..=*end_row).collect()
794            } else {
795                Vec::new()
796            };
797            Ok((sheet, names, cols, rows))
798        }
799    }
800}
801
802pub(crate) fn column_index(names: &[String], target: &str) -> Result<usize, String> {
803    names
804        .iter()
805        .position(|c| c.eq_ignore_ascii_case(target))
806        .ok_or_else(|| {
807            format!(
808                "Source column '{}' not found (columns: {})",
809                target,
810                names.join(", ")
811            )
812        })
813}
814
815/// Computes a pivot table's result grid from the current state of `sheets`.
816/// Pure and read-only: callers materialize the returned `PivotGrid` into
817/// sheet cells themselves.
818/// Computes `pivot` against `sheets`, returning a display-ready grid.
819///
820/// Pure: it reads source records, applies the filter fields, groups by the
821/// row and column fields, aggregates the value fields, and returns the
822/// result. Nothing is written -- materializing the grid into cells is
823/// `WorkbookManager::refresh_pivot_table`'s job.
824///
825/// `sheets` must include both the source's sheet and, for a
826/// [`PivotSource::Table`] source, whichever sheet carries that table.
827///
828/// # Errors
829///
830/// Returns a message if the source cannot be resolved, if a named field is
831/// not among the source's columns, or if the pivot has no value fields.
832pub fn compute_pivot(sheets: &[&Sheet], pivot: &PivotTable) -> Result<PivotGrid, String> {
833    let (sheet, col_names, sheet_cols, data_rows) = resolve_source(sheets, &pivot.source)?;
834
835    for f in pivot.row_fields.iter().chain(pivot.col_fields.iter()) {
836        column_index(&col_names, &f.column)?;
837    }
838    for vf in &pivot.value_fields {
839        column_index(&col_names, &vf.column)?;
840    }
841    for ff in &pivot.filter_fields {
842        column_index(&col_names, &ff.column)?;
843    }
844    if pivot.value_fields.is_empty() {
845        return Err("Pivot table has no value fields".to_string());
846    }
847
848    // Read every source record unfiltered first -- the filter-row captions
849    // below need every distinct value that actually exists in the source,
850    // not just the ones that survive filtering, to tell "(All)" apart from
851    // "(Multiple Items)".
852    let mut all_rows: Vec<Vec<ResultData>> = Vec::with_capacity(data_rows.len());
853    for &r in &data_rows {
854        let mut row_vals = Vec::with_capacity(sheet_cols.len());
855        for &c in &sheet_cols {
856            row_vals.push(sheet.get_result_data(&CellRef::new(r, c)));
857        }
858        all_rows.push(row_vals);
859    }
860
861    // A filter field's selectable items are Excel pivot-cache items, which
862    // (like row/col group labels) merge case-different text into one item
863    // -- so both the "(All)"/"(Multiple Items)" state and the actual
864    // row-inclusion test below must compare case-insensitively, not by
865    // exact string equality. Verified against real Excel via
866    // fuzz/fuzz_pivot.py (iteration 8, seed 599783): a source column with
867    // both "East" and "east" rows, filtered to a selection containing
868    // "east", must include every row of either casing -- Excel's pivot
869    // cache only ever offers one merged "East"/"east" checkbox, not two.
870    let mut filter_rows: Vec<(String, String)> = Vec::new();
871    for ff in &pivot.filter_fields {
872        let idx = column_index(&col_names, &ff.column)?;
873        let distinct: std::collections::HashSet<String> = all_rows
874            .iter()
875            .map(|row| group_key(&row[idx]).to_ascii_lowercase())
876            .collect();
877        let state = match &ff.selected_values {
878            None => "(All)".to_string(),
879            Some(selected) => {
880                let selected_set: std::collections::HashSet<String> =
881                    selected.iter().map(|v| v.to_ascii_lowercase()).collect();
882                let is_all = selected_set.len() == distinct.len()
883                    && distinct.iter().all(|v| selected_set.contains(v));
884                if is_all {
885                    "(All)".to_string()
886                } else if !ff.multiple_selection && selected_set.len() == 1 {
887                    // Single-select mode names the item; multi-select says
888                    // `(Multiple Items)` even for one. Both measured -- see
889                    // `PivotFilterField::multiple_selection`. The item's own
890                    // casing is used, since the cache merges case variants
891                    // onto whichever it saw first.
892                    let wanted = &selected_set;
893                    all_rows
894                        .iter()
895                        .map(|row| group_key(&row[idx]))
896                        .find(|v| wanted.contains(&v.to_ascii_lowercase()))
897                        .unwrap_or_else(|| "(Multiple Items)".to_string())
898                } else {
899                    "(Multiple Items)".to_string()
900                }
901            }
902        };
903        filter_rows.push((ff.column.clone(), state));
904    }
905
906    let mut records: Vec<Vec<ResultData>> = Vec::new();
907    'row: for row_vals in &all_rows {
908        for ff in &pivot.filter_fields {
909            if let Some(selected) = &ff.selected_values {
910                let idx = column_index(&col_names, &ff.column)?;
911                let key = group_key(&row_vals[idx]);
912                if !selected.iter().any(|v| v.eq_ignore_ascii_case(&key)) {
913                    continue 'row;
914                }
915            }
916        }
917        records.push(row_vals.clone());
918    }
919
920    let record_indices: Vec<usize> = (0..records.len()).collect();
921
922    let row_field_idxs: Vec<usize> = pivot
923        .row_fields
924        .iter()
925        .map(|f| column_index(&col_names, &f.column))
926        .collect::<Result<_, _>>()?;
927    let col_field_idxs: Vec<usize> = pivot
928        .col_fields
929        .iter()
930        .map(|f| column_index(&col_names, &f.column))
931        .collect::<Result<_, _>>()?;
932    // The casing a case-insensitively-merged group displays under must be
933    // decided once per field, from that field's first occurrence anywhere
934    // in the source data -- not independently within whichever nested
935    // branch of the *other* axis it happens to first appear under.
936    // `build_group_tree`'s merge only sees one branch's records at a time,
937    // so canonicalizing case up front here (before grouping) is what makes
938    // every branch agree on the same casing for the same value (verified
939    // against real Excel via fuzz/fuzz_pivot.py: its pivot cache assigns
940    // one canonical spelling per distinct value field-wide).
941    let mut case_canon: HashMap<usize, HashMap<String, String>> = HashMap::new();
942    let mut canonical_key = |field_idx: usize, raw: String| -> String {
943        let map = case_canon.entry(field_idx).or_default();
944        map.entry(raw.to_ascii_lowercase()).or_insert(raw).clone()
945    };
946    // Seed the canonical casing from *every* source row, not just the ones
947    // that survive `pivot.filter_fields` -- Excel's pivot cache assigns a
948    // value's canonical casing once, field-wide, from the raw source data,
949    // and a filter only hides cached items afterward rather than rebuilding
950    // the cache from the filtered subset. Skipping this seeding step used
951    // to let a filter change which occurrence of a case-variant value
952    // counted as "first" (whichever one happened to survive the filter),
953    // even though Excel's own choice never depends on the filter at all.
954    for row_vals in &all_rows {
955        for &i in row_field_idxs.iter().chain(col_field_idxs.iter()) {
956            canonical_key(i, group_key(&row_vals[i]));
957        }
958    }
959    let row_keys: Vec<Vec<String>> = if pivot.row_fields.is_empty() {
960        Vec::new()
961    } else {
962        records
963            .iter()
964            .map(|rec| {
965                row_field_idxs
966                    .iter()
967                    .map(|&i| canonical_key(i, group_key(&rec[i])))
968                    .collect()
969            })
970            .collect()
971    };
972    let col_keys: Vec<Vec<String>> = if pivot.col_fields.is_empty() {
973        Vec::new()
974    } else {
975        records
976            .iter()
977            .map(|rec| {
978                col_field_idxs
979                    .iter()
980                    .map(|&i| canonical_key(i, group_key(&rec[i])))
981                    .collect()
982            })
983            .collect()
984    };
985    let row_numeric: Vec<bool> = row_field_idxs
986        .iter()
987        .map(|&i| field_is_numeric(&records, i))
988        .collect();
989    let col_numeric: Vec<bool> = col_field_idxs
990        .iter()
991        .map(|&i| field_is_numeric(&records, i))
992        .collect();
993
994    let row_groups = build_axis(
995        &record_indices,
996        &row_keys,
997        &pivot.row_fields,
998        pivot.grand_totals_row,
999        &row_numeric,
1000    );
1001    let col_groups = build_axis(
1002        &record_indices,
1003        &col_keys,
1004        &pivot.col_fields,
1005        pivot.grand_totals_col,
1006        &col_numeric,
1007    );
1008
1009    let value_multiplier = if pivot.value_fields.len() > 1 {
1010        pivot.value_fields.len()
1011    } else {
1012        1
1013    };
1014    let value_idxs: Vec<usize> = pivot
1015        .value_fields
1016        .iter()
1017        .map(|vf| column_index(&col_names, &vf.column))
1018        .collect::<Result<_, _>>()?;
1019    let value_labels = value_field_labels(&pivot.value_fields);
1020
1021    // --- Header rows ---
1022    // Matches Excel's default "compact form" display, verified against real
1023    // Excel via fuzz/fuzz_pivot.py (see fuzz/README.md's pivot section):
1024    // the outermost row field's caption becomes the literal text "Row
1025    // Labels" (deeper row fields keep their real name), and -- whenever
1026    // there's at least one column field -- an extra header row captioned
1027    // "Column Labels" is inserted above the column-field-value rows. Excel
1028    // can't be made to use its alternate "tabular form" (the per-field
1029    // LayoutForm VBA property that would show real field names instead is
1030    // confirmed to have no effect on Mac Excel, and the table-wide
1031    // RowAxisLayout/ColumnAxisLayout methods that do work hang Mac Excel
1032    // outright when driven via VBA/AppleScript), so matching this on visi's
1033    // side is the only tractable way to reach parity.
1034    let n_col_header_rows = pivot.col_fields.len().max(1);
1035    // The extra value-label row (needed to tell a column group's own value
1036    // apart from which value field a sub-column holds) only makes sense
1037    // when there's a column-group-values row for it to sit below in the
1038    // first place. With no column fields at all, there's no such row --
1039    // Excel just lists every value field as a plain adjacent column in the
1040    // single header row instead, exactly like a flat table's header
1041    // (verified against real Excel via fuzz/fuzz_pivot.py: 2 value fields
1042    // with no column fields produced one header row with both labels side
1043    // by side, not two stacked rows).
1044    let n_header_rows = if value_multiplier > 1 && !pivot.col_fields.is_empty() {
1045        n_col_header_rows + 1
1046    } else {
1047        n_col_header_rows
1048    };
1049    let row_label_width = row_label_width(pivot);
1050
1051    let mut header_rows: Vec<Vec<String>> = Vec::new();
1052    for r in 0..n_header_rows {
1053        let mut row: Vec<String> = Vec::new();
1054        for i in 0..row_label_width {
1055            // Row-label captions ("Row Labels" plus any deeper row fields'
1056            // real names) sit on the *last* header row -- the one right
1057            // above the data -- not the first: with multiple value fields
1058            // that's the extra value-label row, not the column-field-value
1059            // row above it (confirmed against real Excel: with 2 value
1060            // fields, "Row Labels" lands on the value-label row while the
1061            // column-value row directly above it leaves that same spot
1062            // blank).
1063            if r == n_header_rows - 1 {
1064                row.push(if i == 0 && !pivot.row_fields.is_empty() {
1065                    "Row Labels".to_string()
1066                } else {
1067                    pivot
1068                        .row_fields
1069                        .get(i)
1070                        .map(|f| f.column.clone())
1071                        .unwrap_or_default()
1072                });
1073            } else {
1074                row.push(String::new());
1075            }
1076        }
1077        // Excel merges a repeated label across the columns it spans -- a
1078        // value field fanning a single column group out into several
1079        // adjacent sub-columns is one way that happens, a shallower column
1080        // field repeating over several deeper-field sub-columns under the
1081        // *same* ancestor chain is another -- showing the label once at the
1082        // leftmost column and blank for the rest. The two cases need
1083        // different adjacency tests: within one group, every `vf` beyond
1084        // the first is *always* a repeat (they all render that group's same
1085        // `labels[r]`, `vf` doesn't affect it). Across groups, `labels[r]`
1086        // matching alone isn't enough -- two unrelated groups can
1087        // coincidentally share a leaf value at depth `r` (e.g. two
1088        // different outer-field branches both happening to have a "west"
1089        // child) without being siblings under the same parent, so merging
1090        // them would silently drop one's real value. Only merge when every
1091        // depth from 0 up to and including `r` matches the immediately
1092        // preceding group, which is exactly the condition for them being
1093        // adjacent leaves of the same parent in `col_groups`'s tree order.
1094        let mut prev_group: Option<&FlatGroup> = None;
1095        for group in &col_groups {
1096            // A subtotal group's labels hold exactly one real value, at
1097            // whichever depth it was inserted -- e.g. `[Some("-3"), None]`
1098            // for an outer-field subtotal over a 2-level axis. That's the
1099            // one row its caption becomes "<value> Total" (or, with 2+
1100            // value fields, "<value> <value field label>" per sub-column,
1101            // mirroring the grand-total column's "Total <value label>"
1102            // treatment below -- confirmed against real Excel via
1103            // fuzz/fuzz_pivot.py: with 2 value fields it repeats the value
1104            // field's own name under a subtotal group instead of the
1105            // literal word "Total", and doesn't emit a separate
1106            // value-label row beneath it the way non-subtotal groups do);
1107            // every other column-field row either inherits an ancestor's
1108            // label (already handled below) or stays blank.
1109            let subtotal_depth = group
1110                .is_subtotal
1111                .then(|| group.labels.iter().rposition(|l| l.is_some()))
1112                .flatten();
1113            for vf in 0..value_multiplier {
1114                let label = if r < pivot.col_fields.len() {
1115                    if group.is_grand_total {
1116                        // The grand-total column's caption always lands on
1117                        // the *outermost* column-field row (r == 0), not
1118                        // the deepest one -- confirmed against real Excel
1119                        // with a 2-level column axis, where "Grand Total"
1120                        // showed up on the shallow row while the deep row
1121                        // beneath it stayed blank (the two coincide, and so
1122                        // looked identical, in every single-column-field
1123                        // case tested before that).
1124                        if r == 0 {
1125                            if value_multiplier > 1 {
1126                                format!("Total {}", value_labels[vf])
1127                            } else {
1128                                "Grand Total".to_string()
1129                            }
1130                        } else {
1131                            String::new()
1132                        }
1133                    } else if subtotal_depth == Some(r) {
1134                        let value = group.labels[r].clone().unwrap();
1135                        if value_multiplier > 1 {
1136                            format!("{} {}", value, value_labels[vf])
1137                        } else {
1138                            format!("{} Total", value)
1139                        }
1140                    } else {
1141                        let is_repeat = if vf > 0 {
1142                            true
1143                        } else {
1144                            prev_group.is_some_and(|pg| {
1145                                (0..=r).all(|d| pg.labels.get(d) == group.labels.get(d))
1146                            })
1147                        };
1148                        if is_repeat {
1149                            String::new()
1150                        } else {
1151                            group
1152                                .labels
1153                                .get(r)
1154                                .and_then(|l| l.clone())
1155                                .unwrap_or_default()
1156                        }
1157                    }
1158                } else if group.is_grand_total || group.is_subtotal {
1159                    // Already captioned "Total <value label>" (grand total)
1160                    // or "<value> <value label>" (subtotal) on the
1161                    // column-field row above -- no separate value-label row
1162                    // for these groups.
1163                    String::new()
1164                } else {
1165                    value_labels.get(vf).cloned().unwrap_or_default()
1166                };
1167                row.push(label);
1168            }
1169            prev_group = Some(group);
1170        }
1171        header_rows.push(row);
1172    }
1173    // If there's exactly one column group with no column fields, put the
1174    // single value field's label directly in the header row (mirrors the
1175    // classic single-value-field pivot layout: "Row Labels | Sum of X").
1176    if pivot.col_fields.is_empty()
1177        && value_multiplier == 1
1178        && let Some(last) = header_rows.last_mut()
1179        && let Some(cell) = last.last_mut()
1180        && let Some(label) = value_labels.first()
1181    {
1182        *cell = label.clone();
1183    }
1184    // Whenever there's at least one column field, Excel prepends a header
1185    // row captioned "Column Labels" above the column-field-value rows.
1186    // Its row-label area is blank, except: when there's exactly one value
1187    // field *and* at least one row field, that field's label goes in the
1188    // very first cell (mirrors the single-value-field layout's "Row Labels
1189    // | Sum of X" convention, just one row up since the row-label area's
1190    // own first cell is taken by the "Row Labels" caption instead). With no
1191    // row fields, that label has nowhere to go here -- the row-label area
1192    // has no field caption to displace -- so it surfaces on the sole body
1193    // row's corner instead (see the "Total" fallback below).
1194    if !pivot.col_fields.is_empty() {
1195        let mut row = vec![String::new(); row_label_width];
1196        if value_multiplier == 1
1197            && !pivot.row_fields.is_empty()
1198            && let Some(label) = value_labels.first()
1199        {
1200            row[0] = label.clone();
1201        }
1202        row.push("Column Labels".to_string());
1203        row.resize(
1204            row_label_width + col_groups.len() * value_multiplier,
1205            String::new(),
1206        );
1207        header_rows.insert(0, row);
1208    }
1209
1210    // --- Body rows ---
1211    let mut body_rows: Vec<PivotBodyRow> = Vec::new();
1212    let mut prev_labels: Vec<Option<String>> = vec![None; row_label_width];
1213    for rg in &row_groups {
1214        let mut display_labels = vec![String::new(); row_label_width];
1215        if rg.is_grand_total {
1216            display_labels[0] = "Grand Total".to_string();
1217            for l in prev_labels.iter_mut() {
1218                *l = None;
1219            }
1220        } else {
1221            let mut changed = false;
1222            for d in 0..row_label_width {
1223                let cur = if pivot.row_fields.is_empty() {
1224                    None
1225                } else {
1226                    rg.labels.get(d).cloned().flatten()
1227                };
1228                let is_subtotal_marker =
1229                    rg.is_subtotal && rg.labels.get(d).map(|l| l.is_some()).unwrap_or(false);
1230                let show = changed || cur != prev_labels[d] || is_subtotal_marker;
1231                if show {
1232                    if let Some(ref v) = cur {
1233                        display_labels[d] = if is_subtotal_marker {
1234                            format!("{} Total", v)
1235                        } else {
1236                            v.clone()
1237                        };
1238                    }
1239                    changed = true;
1240                }
1241                prev_labels[d] = cur;
1242            }
1243            // When there are no row fields *and* no column fields either,
1244            // `row_label_width` is 0 (see `row_label_width`'s doc comment)
1245            // -- there's no label cell here at all, just the value itself.
1246            if pivot.row_fields.is_empty() && row_label_width > 0 {
1247                // With no row fields there's exactly one body row (the
1248                // aggregate over everything), and no "Row Labels"-captioned
1249                // header row above it to hold a single value field's label
1250                // the way the col_fields-empty layout does in the header
1251                // (see the header construction above) -- so it surfaces
1252                // here instead, on the one row that exists. Falls back to
1253                // "Total" when there's more than one value field, same as
1254                // the header's equivalent case.
1255                display_labels[0] = if !pivot.col_fields.is_empty() && value_multiplier == 1 {
1256                    value_labels.first().cloned().unwrap_or_default()
1257                } else {
1258                    "Total".to_string()
1259                };
1260            }
1261        }
1262
1263        let row_record_set: std::collections::HashSet<usize> =
1264            rg.record_indices.iter().copied().collect();
1265        let mut values: Vec<ResultData> = Vec::new();
1266        for cg in &col_groups {
1267            for (vf_pos, &vidx) in value_idxs.iter().enumerate() {
1268                if vf_pos > 0 && value_multiplier == 1 {
1269                    break;
1270                }
1271                let col_vals: Vec<ResultData> = cg
1272                    .record_indices
1273                    .iter()
1274                    .filter(|i| row_record_set.contains(i))
1275                    .map(|&i| records[i][vidx].clone())
1276                    .collect();
1277                values.push(aggregate(
1278                    sheet,
1279                    &col_vals,
1280                    pivot.value_fields[vf_pos].aggregation,
1281                ));
1282            }
1283        }
1284
1285        body_rows.push(PivotBodyRow {
1286            row_labels: display_labels,
1287            is_grand_total: rg.is_grand_total,
1288            values,
1289        });
1290    }
1291
1292    let width = row_label_width + col_groups.len() * value_multiplier;
1293    let to_axis_items = |groups: &[FlatGroup]| -> Vec<PivotAxisItem> {
1294        groups
1295            .iter()
1296            .map(|g| PivotAxisItem {
1297                labels: g.labels.clone(),
1298                is_subtotal: g.is_subtotal,
1299                is_grand_total: g.is_grand_total,
1300            })
1301            .collect()
1302    };
1303    Ok(PivotGrid {
1304        filter_rows,
1305        header_rows,
1306        body_rows,
1307        width,
1308        row_axis: to_axis_items(&row_groups),
1309        col_axis: to_axis_items(&col_groups),
1310    })
1311}
1312
1313/// Finds the unique row/col-axis group matching `criteria` -- `(field
1314/// depth, item text)` pairs restricted to one axis -- for `GETPIVOTDATA`.
1315/// Empty `criteria` means "the axis's grand total". A non-empty `criteria`
1316/// that doesn't specify every field on the axis matches the subtotal group
1317/// at that depth (mirrors Excel: naming only the outer field(s) of a nested
1318/// row/col axis returns that branch's subtotal, not an arbitrary leaf under
1319/// it); naming every field down to the innermost one matches the leaf.
1320/// Ambiguous or absent matches are both reported as `#REF!`, matching real
1321/// Excel's error for a `GETPIVOTDATA` criteria pair that doesn't resolve.
1322fn match_pivot_axis(
1323    axis: &[PivotAxisItem],
1324    criteria: &[(usize, &str)],
1325    field_count: usize,
1326) -> Result<usize, String> {
1327    if criteria.is_empty() {
1328        return axis
1329            .iter()
1330            .position(|g| g.is_grand_total)
1331            .or(if field_count == 0 && axis.len() == 1 {
1332                Some(0)
1333            } else {
1334                None
1335            })
1336            .ok_or_else(|| "#REF!".to_string());
1337    }
1338    let max_depth = criteria.iter().map(|(d, _)| *d).max().unwrap_or(0);
1339    let want_leaf = max_depth + 1 == field_count;
1340    let matches: Vec<usize> = axis
1341        .iter()
1342        .enumerate()
1343        .filter(|(_, group)| {
1344            if group.is_grand_total {
1345                return false;
1346            }
1347            if want_leaf {
1348                if group.is_subtotal {
1349                    return false;
1350                }
1351            } else {
1352                let own_depth = group.labels.iter().rposition(|l| l.is_some());
1353                if !(group.is_subtotal && own_depth == Some(max_depth)) {
1354                    return false;
1355                }
1356            }
1357            criteria.iter().all(|(depth, item)| {
1358                group
1359                    .labels
1360                    .get(*depth)
1361                    .and_then(|l| l.as_deref())
1362                    .map(|l| l.eq_ignore_ascii_case(item))
1363                    .unwrap_or(false)
1364            })
1365        })
1366        .map(|(i, _)| i)
1367        .collect();
1368    match matches.len() {
1369        1 => Ok(matches[0]),
1370        _ => Err("#REF!".to_string()),
1371    }
1372}
1373
1374/// Implements `GETPIVOTDATA`: extracts a single summarized value out of a
1375/// pivot table's computed grid by data-field name plus `(row/col field,
1376/// item)` criteria pairs, the same way real Excel's formula does when
1377/// pointed at a rendered pivot. Recomputes the grid fresh from `sheets`
1378/// rather than caching it, consistent with formulas re-evaluating from
1379/// current sheet state on every recalculation pass.
1380pub fn getpivotdata(
1381    sheets: &[&Sheet],
1382    pivot: &PivotTable,
1383    data_field: &str,
1384    criteria: &[(String, String)],
1385) -> Result<ResultData, String> {
1386    let grid = compute_pivot(sheets, pivot)?;
1387
1388    let value_labels = value_field_labels(&pivot.value_fields);
1389    let value_multiplier = if pivot.value_fields.len() > 1 {
1390        pivot.value_fields.len()
1391    } else {
1392        1
1393    };
1394    let value_field_idx = pivot
1395        .value_fields
1396        .iter()
1397        .position(|vf| vf.column.eq_ignore_ascii_case(data_field))
1398        .or_else(|| {
1399            value_labels
1400                .iter()
1401                .position(|l| l.eq_ignore_ascii_case(data_field))
1402        })
1403        .ok_or_else(|| "#VALUE!".to_string())?;
1404
1405    let mut row_criteria: Vec<(usize, &str)> = Vec::new();
1406    let mut col_criteria: Vec<(usize, &str)> = Vec::new();
1407    for (field, item) in criteria {
1408        if let Some(depth) = pivot
1409            .row_fields
1410            .iter()
1411            .position(|f| f.column.eq_ignore_ascii_case(field))
1412        {
1413            row_criteria.push((depth, item.as_str()));
1414        } else if let Some(depth) = pivot
1415            .col_fields
1416            .iter()
1417            .position(|f| f.column.eq_ignore_ascii_case(field))
1418        {
1419            col_criteria.push((depth, item.as_str()));
1420        } else {
1421            return Err("#REF!".to_string());
1422        }
1423    }
1424
1425    let row_idx = match_pivot_axis(&grid.row_axis, &row_criteria, pivot.row_fields.len())?;
1426    let col_idx = match_pivot_axis(&grid.col_axis, &col_criteria, pivot.col_fields.len())?;
1427
1428    let pos = col_idx * value_multiplier + value_field_idx;
1429    grid.body_rows
1430        .get(row_idx)
1431        .and_then(|r| r.values.get(pos))
1432        .cloned()
1433        .ok_or_else(|| "#REF!".to_string())
1434}
1435
1436/// Returns the distinct values of `values`, sorted the same way pivot
1437/// groups are (ascending numeric if every value parses as a number,
1438/// otherwise case-insensitive ascending text) -- used by the xlsx exporter
1439/// to build a pivot field's flat `<items>` enumeration.
1440pub(crate) fn sorted_distinct_strings(values: &[String], numeric: bool) -> Vec<String> {
1441    let mut pairs: Vec<(String, Vec<usize>)> = distinct_strings(values)
1442        .into_iter()
1443        .map(|s| (s, Vec::new()))
1444        .collect();
1445    sort_group_entries(&mut pairs, numeric);
1446    pairs.into_iter().map(|(s, _)| s).collect()
1447}
1448
1449/// The distinct values in **first-seen** order, which is the order a pivot
1450/// cache stores them in.
1451///
1452/// Measured: Excel's `<sharedItems>` are in source order while a pivot
1453/// field's `<items>` are sorted for display and reference sharedItems by
1454/// index, so the two orders are both needed and are different. See
1455/// `fuzz/pivot_filter_probe.py`.
1456///
1457/// Case-insensitive dedup (first-seen casing kept), matching
1458/// `build_group_tree`'s merge -- this feeds the exported pivot cache, so it
1459/// must agree with how `compute_pivot` actually groups these same values or a
1460/// reimported or refreshed pivot's item list falls out of sync with its own
1461/// displayed grouping.
1462pub(crate) fn distinct_strings(values: &[String]) -> Vec<String> {
1463    let mut seen: Vec<String> = Vec::new();
1464    for v in values {
1465        if !seen.iter().any(|s| s.eq_ignore_ascii_case(v)) {
1466            seen.push(v.clone());
1467        }
1468    }
1469    seen
1470}
1471
1472#[cfg(test)]
1473mod tests {
1474    use super::*;
1475    use crate::core::engine::SheetInit;
1476
1477    fn source_sheet() -> Sheet {
1478        let mut sheet = Sheet::new(SheetInit {
1479            name: Some("Data".to_string()),
1480            rows: 9,
1481            cols: 4,
1482            ..Default::default()
1483        });
1484        let header = ["Region", "Product", "Rep", "Amount"];
1485        for (c, h) in header.iter().enumerate() {
1486            sheet.set_cell_src(0, c, h.to_string());
1487        }
1488        let rows: [[&str; 4]; 8] = [
1489            ["East", "Widget", "Alice", "10"],
1490            ["East", "Widget", "Bob", "20"],
1491            ["East", "Gadget", "Alice", "5"],
1492            ["West", "Widget", "Carol", "30"],
1493            ["West", "Gadget", "Carol", "40"],
1494            ["West", "Gadget", "Dave", "50"],
1495            ["East", "Gadget", "Bob", "15"],
1496            ["West", "Widget", "Dave", "25"],
1497        ];
1498        for (r, row) in rows.iter().enumerate() {
1499            for (c, v) in row.iter().enumerate() {
1500                sheet.set_cell_src(r + 1, c, v.to_string());
1501            }
1502        }
1503        sheet.commit(None).unwrap();
1504        sheet
1505            .add_table("Sales".to_string(), 0, 0, 8, 3, true, false)
1506            .unwrap();
1507        sheet
1508    }
1509
1510    fn base_pivot() -> PivotTable {
1511        PivotTable {
1512            id: 1,
1513            name: "Pivot1".to_string(),
1514            source: PivotSource::Table {
1515                name: "Sales".to_string(),
1516            },
1517            dest_sheet_id: 0,
1518            dest_row: 0,
1519            dest_col: 0,
1520            row_fields: vec![PivotField::new("Region")],
1521            col_fields: vec![],
1522            value_fields: vec![PivotValueField::new("Amount", PivotAggregation::Sum)],
1523            filter_fields: vec![],
1524            grand_totals_row: true,
1525            grand_totals_col: true,
1526            last_output_end_row: None,
1527            last_output_end_col: None,
1528        }
1529    }
1530
1531    fn value_at(row: &PivotBodyRow, col: usize) -> f64 {
1532        match &row.values[col] {
1533            ResultData::Float(f) => *f,
1534            ResultData::Integer(i) => *i as f64,
1535            other => panic!("expected numeric, got {:?}", other),
1536        }
1537    }
1538
1539    #[test]
1540    fn test_single_row_field_sum_with_grand_total() {
1541        let sheet = source_sheet();
1542        let pivot = base_pivot();
1543        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1544
1545        // East: 10+20+5+15=50, West: 30+40+50+25=145, Grand Total: 195
1546        assert_eq!(grid.body_rows.len(), 3);
1547        assert_eq!(grid.body_rows[0].row_labels[0], "East");
1548        assert_eq!(value_at(&grid.body_rows[0], 0), 50.0);
1549        assert_eq!(grid.body_rows[1].row_labels[0], "West");
1550        assert_eq!(value_at(&grid.body_rows[1], 0), 145.0);
1551        assert!(grid.body_rows[2].is_grand_total);
1552        assert_eq!(grid.body_rows[2].row_labels[0], "Grand Total");
1553        assert_eq!(value_at(&grid.body_rows[2], 0), 195.0);
1554    }
1555
1556    #[test]
1557    fn test_getpivotdata_matches_a_row_group() {
1558        let sheet = source_sheet();
1559        let pivot = base_pivot();
1560        let result = getpivotdata(
1561            &[&sheet],
1562            &pivot,
1563            "Amount",
1564            &[("Region".to_string(), "East".to_string())],
1565        )
1566        .unwrap();
1567        assert!(matches!(result, ResultData::Float(f) if f == 50.0));
1568    }
1569
1570    #[test]
1571    fn test_getpivotdata_empty_criteria_matches_grand_total() {
1572        let sheet = source_sheet();
1573        let pivot = base_pivot();
1574        let result = getpivotdata(&[&sheet], &pivot, "Amount", &[]).unwrap();
1575        assert!(matches!(result, ResultData::Float(f) if f == 195.0));
1576    }
1577
1578    #[test]
1579    fn test_getpivotdata_partial_criteria_matches_subtotal() {
1580        let sheet = source_sheet();
1581        let mut pivot = base_pivot();
1582        pivot.row_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1583        // East: Widget=10+20=30, Gadget=5+15=20 -> Region subtotal 50
1584        let result = getpivotdata(
1585            &[&sheet],
1586            &pivot,
1587            "Amount",
1588            &[("Region".to_string(), "East".to_string())],
1589        )
1590        .unwrap();
1591        assert!(matches!(result, ResultData::Float(f) if f == 50.0));
1592    }
1593
1594    #[test]
1595    fn test_getpivotdata_full_path_matches_leaf() {
1596        let sheet = source_sheet();
1597        let mut pivot = base_pivot();
1598        pivot.row_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1599        let result = getpivotdata(
1600            &[&sheet],
1601            &pivot,
1602            "Amount",
1603            &[
1604                ("Region".to_string(), "East".to_string()),
1605                ("Product".to_string(), "Widget".to_string()),
1606            ],
1607        )
1608        .unwrap();
1609        assert!(matches!(result, ResultData::Float(f) if f == 30.0));
1610    }
1611
1612    #[test]
1613    fn test_getpivotdata_unknown_field_is_ref_error() {
1614        let sheet = source_sheet();
1615        let pivot = base_pivot();
1616        let err = getpivotdata(
1617            &[&sheet],
1618            &pivot,
1619            "Amount",
1620            &[("NotAField".to_string(), "East".to_string())],
1621        )
1622        .unwrap_err();
1623        assert_eq!(err, "#REF!");
1624    }
1625
1626    #[test]
1627    fn test_getpivotdata_unknown_item_is_ref_error() {
1628        let sheet = source_sheet();
1629        let pivot = base_pivot();
1630        let err = getpivotdata(
1631            &[&sheet],
1632            &pivot,
1633            "Amount",
1634            &[("Region".to_string(), "North".to_string())],
1635        )
1636        .unwrap_err();
1637        assert_eq!(err, "#REF!");
1638    }
1639
1640    #[test]
1641    fn test_getpivotdata_unknown_data_field_is_value_error() {
1642        let sheet = source_sheet();
1643        let pivot = base_pivot();
1644        let err = getpivotdata(
1645            &[&sheet],
1646            &pivot,
1647            "NotAField",
1648            &[("Region".to_string(), "East".to_string())],
1649        )
1650        .unwrap_err();
1651        assert_eq!(err, "#VALUE!");
1652    }
1653
1654    #[test]
1655    fn test_row_and_col_fields_with_subtotals() {
1656        let sheet = source_sheet();
1657        let mut pivot = base_pivot();
1658        pivot.row_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1659        pivot.col_fields = vec![PivotField::new("Rep")];
1660        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1661
1662        // Region subtotal rows should appear (2 regions x (2 products + 1 subtotal)) + grand total
1663        let subtotal_rows: Vec<&PivotBodyRow> = grid
1664            .body_rows
1665            .iter()
1666            .filter(|r| r.row_labels[0].ends_with("Total") && !r.is_grand_total)
1667            .collect();
1668        assert_eq!(subtotal_rows.len(), 2); // one per region
1669        assert!(grid.body_rows.last().unwrap().is_grand_total);
1670    }
1671
1672    #[test]
1673    fn test_nested_row_field_second_level_labels_are_not_lost() {
1674        // The second (innermost) row field's own labels must survive being
1675        // nested under the first field's groups, not be truncated away when
1676        // the group tree is flattened.
1677        let sheet = source_sheet();
1678        let mut pivot = base_pivot();
1679        pivot.row_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1680        pivot.grand_totals_row = false;
1681        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1682
1683        let leaf_rows: Vec<&PivotBodyRow> = grid
1684            .body_rows
1685            .iter()
1686            .filter(|r| !r.row_labels[0].ends_with("Total") && !r.is_grand_total)
1687            .collect();
1688        // East has Widget+Gadget, West has Widget+Gadget: 4 leaf rows.
1689        assert_eq!(leaf_rows.len(), 4);
1690        // Every leaf row must show a real (non-blank) Product label, not "".
1691        for row in &leaf_rows {
1692            assert!(
1693                !row.row_labels[1].is_empty(),
1694                "expected a Product label on leaf row {:?}, got blank",
1695                row.row_labels
1696            );
1697        }
1698        let products: Vec<&str> = leaf_rows.iter().map(|r| r.row_labels[1].as_str()).collect();
1699        assert!(products.contains(&"Widget"));
1700        assert!(products.contains(&"Gadget"));
1701    }
1702
1703    #[test]
1704    fn test_count_aggregation() {
1705        let sheet = source_sheet();
1706        let mut pivot = base_pivot();
1707        pivot.value_fields = vec![PivotValueField::new("Rep", PivotAggregation::Count)];
1708        pivot.grand_totals_row = false;
1709        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1710        assert_eq!(grid.body_rows.len(), 2);
1711        // East has 4 records, West has 4 records
1712        for row in &grid.body_rows {
1713            assert_eq!(value_at(row, 0), 4.0);
1714        }
1715    }
1716
1717    #[test]
1718    fn test_filter_field_restricts_records() {
1719        let sheet = source_sheet();
1720        let mut pivot = base_pivot();
1721        pivot.filter_fields = vec![PivotFilterField {
1722            column: "Product".to_string(),
1723            selected_values: Some(vec!["Widget".to_string()]),
1724            multiple_selection: true,
1725        }];
1726        pivot.grand_totals_row = false;
1727        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1728        // East widgets: 10+20=30, West widgets: 30+25=55
1729        assert_eq!(grid.body_rows.len(), 2);
1730        assert_eq!(value_at(&grid.body_rows[0], 0), 30.0);
1731        assert_eq!(value_at(&grid.body_rows[1], 0), 55.0);
1732    }
1733
1734    #[test]
1735    fn test_filter_field_selection_matches_case_insensitively() {
1736        // A filter field's selectable items are Excel pivot-cache items,
1737        // which merge case-different text into a single item exactly like
1738        // row/col group labels do (see
1739        // test_case_variant_values_merge_using_globally_first_seen_casing)
1740        // -- so selecting "east" must match *every* row spelled "East" or
1741        // "east", not just rows with that exact casing.
1742        let mut sheet = Sheet::new(SheetInit {
1743            name: Some("Data".to_string()),
1744            rows: 4,
1745            cols: 2,
1746            ..Default::default()
1747        });
1748        for (c, h) in ["Mixed", "Amount"].iter().enumerate() {
1749            sheet.set_cell_src(0, c, h.to_string());
1750        }
1751        let rows: [[&str; 2]; 3] = [["East", "10"], ["east", "20"], ["West", "30"]];
1752        for (r, row) in rows.iter().enumerate() {
1753            for (c, v) in row.iter().enumerate() {
1754                sheet.set_cell_src(r + 1, c, v.to_string());
1755            }
1756        }
1757        sheet.commit(None).unwrap();
1758        sheet
1759            .add_table("Sales".to_string(), 0, 0, 3, 1, true, false)
1760            .unwrap();
1761
1762        let mut pivot = base_pivot();
1763        pivot.source = PivotSource::Table {
1764            name: "Sales".to_string(),
1765        };
1766        pivot.row_fields = vec![];
1767        pivot.value_fields = vec![PivotValueField::new("Amount", PivotAggregation::Sum)];
1768        pivot.filter_fields = vec![PivotFilterField {
1769            column: "Mixed".to_string(),
1770            selected_values: Some(vec!["east".to_string()]),
1771            multiple_selection: true,
1772        }];
1773        pivot.grand_totals_row = false;
1774        pivot.grand_totals_col = false;
1775        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1776        // Both "East" (10) and "east" (20) rows must be included: 30, not 20.
1777        assert_eq!(value_at(&grid.body_rows[0], 0), 30.0);
1778    }
1779
1780    #[test]
1781    fn test_no_filter_fields_means_no_reserved_rows() {
1782        let sheet = source_sheet();
1783        let pivot = base_pivot();
1784        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1785        assert!(grid.filter_rows.is_empty());
1786        assert_eq!(grid.grid_row_offset(), 0);
1787        assert_eq!(grid.height(), grid.header_rows.len() + grid.body_rows.len());
1788    }
1789
1790    #[test]
1791    fn test_filter_field_state_label_all_vs_multiple_items() {
1792        // Product has exactly two distinct values in `source_sheet`: Widget, Gadget.
1793        let sheet = source_sheet();
1794        let mut pivot = base_pivot();
1795        pivot.filter_fields = vec![PivotFilterField {
1796            column: "Product".to_string(),
1797            selected_values: None,
1798            multiple_selection: true,
1799        }];
1800
1801        // No selection at all -> "(All)".
1802        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1803        assert_eq!(
1804            grid.filter_rows,
1805            vec![("Product".to_string(), "(All)".to_string())]
1806        );
1807        assert_eq!(grid.grid_row_offset(), 2); // 1 filter row + 1 blank spacer
1808
1809        // Explicitly selecting every existing distinct value is equivalent to "(All)".
1810        pivot.filter_fields[0].selected_values =
1811            Some(vec!["Widget".to_string(), "Gadget".to_string()]);
1812        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1813        assert_eq!(grid.filter_rows[0].1, "(All)");
1814
1815        // A strict subset -> "(Multiple Items)". Verified against real
1816        // Excel: even a single selected value out of several shows this,
1817        // never the value's own name -- that's specific to the classic
1818        // single-select page-field mode Excel no longer defaults to.
1819        pivot.filter_fields[0].selected_values = Some(vec!["Widget".to_string()]);
1820        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1821        assert_eq!(grid.filter_rows[0].1, "(Multiple Items)");
1822
1823        // ...and that single-select mode is exactly where the item's own
1824        // name does show, which is what `PivotField.CurrentPage = "Widget"`
1825        // produces. Measured: the page-field cell reads `Widget`.
1826        pivot.filter_fields[0].multiple_selection = false;
1827        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1828        assert_eq!(grid.filter_rows[0].1, "Widget");
1829    }
1830
1831    #[test]
1832    fn test_col_axis_subtotal_group_gets_total_caption_and_grand_total_stays_outermost() {
1833        // With a 2-level column axis (both fields' subtotals enabled by
1834        // default), the header logic gives a column-axis subtotal group its
1835        // own "<value> Total" caption. The grand-total column's caption is
1836        // placed on the *outermost* row.
1837        let sheet = source_sheet();
1838        let mut pivot = base_pivot();
1839        pivot.row_fields = vec![PivotField::new("Rep")];
1840        pivot.col_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1841        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1842
1843        // header_rows[0] is the prepended "Column Labels" row; [1] is the
1844        // outermost column field (Region), [2] is the deepest (Product).
1845        let region_row = &grid.header_rows[1];
1846        assert!(region_row.contains(&"East Total".to_string()));
1847        assert!(region_row.contains(&"West Total".to_string()));
1848        assert!(region_row.contains(&"Grand Total".to_string()));
1849        let product_row = &grid.header_rows[2];
1850        assert_eq!(product_row.last().unwrap(), "");
1851    }
1852
1853    #[test]
1854    fn test_col_axis_subtotal_caption_uses_value_field_label_with_multiple_value_fields() {
1855        // With 2+ value fields, a col-field subtotal group repeats the value
1856        // field's own name directly on the subtotal's caption row ("<n> Min of Amount",
1857        // "<n> Sum of Amount") and emits no separate label row underneath
1858        // for those sub-columns.
1859        let sheet = source_sheet();
1860        let mut pivot = base_pivot();
1861        pivot.row_fields = vec![];
1862        pivot.col_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1863        pivot.value_fields = vec![
1864            PivotValueField::new("Amount", PivotAggregation::Min),
1865            PivotValueField::new("Amount", PivotAggregation::Sum),
1866        ];
1867        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1868
1869        // header_rows[0] is "Column Labels", [1] is Region (outer, with the
1870        // subtotal), [2] is Product (deepest), [3] is the value-label row.
1871        let region_row = &grid.header_rows[1];
1872        // Min and Sum are different aggregations, so their default
1873        // captions are distinct on their own and Excel leaves the reused
1874        // "Amount" source column unsuffixed (see
1875        // test_value_field_labels_leaves_distinct_aggregations_on_same_column_unsuffixed).
1876        assert!(region_row.contains(&"East Min of Amount".to_string()));
1877        assert!(region_row.contains(&"East Sum of Amount".to_string()));
1878        assert!(region_row.contains(&"West Min of Amount".to_string()));
1879        assert!(region_row.contains(&"West Sum of Amount".to_string()));
1880        assert!(
1881            !region_row
1882                .iter()
1883                .any(|c| c == "East Total" || c == "West Total")
1884        );
1885
1886        // The value-label row must stay blank under the subtotal's
1887        // sub-columns (no redundant second label row for them), while still
1888        // showing the value labels under the non-subtotal leaf columns.
1889        let value_label_row = grid.header_rows.last().unwrap();
1890        assert!(value_label_row.contains(&"Min of Amount".to_string()));
1891        assert!(value_label_row.contains(&"Sum of Amount".to_string()));
1892        let east_subtotal_idx = region_row
1893            .iter()
1894            .position(|c| c == "East Min of Amount")
1895            .unwrap();
1896        assert_eq!(value_label_row[east_subtotal_idx], "");
1897        assert_eq!(value_label_row[east_subtotal_idx + 1], "");
1898    }
1899
1900    #[test]
1901    fn test_col_axis_repeated_leaf_value_under_different_parents_is_not_falsely_merged() {
1902        // Repeated leaf values under different parent groups are preserved
1903        // rather than merged across unrelated outer-field branches.
1904        let mut sheet = Sheet::new(SheetInit {
1905            name: Some("Data".to_string()),
1906            rows: 3,
1907            cols: 3,
1908            ..Default::default()
1909        });
1910        for (c, h) in ["Group", "Sub", "Amount"].iter().enumerate() {
1911            sheet.set_cell_src(0, c, h.to_string());
1912        }
1913        // GroupA's only Sub child and GroupB's only Sub child are both "X",
1914        // with nothing else between them once flattened.
1915        let rows: [[&str; 3]; 2] = [["GroupA", "X", "1"], ["GroupB", "X", "2"]];
1916        for (r, row) in rows.iter().enumerate() {
1917            for (c, v) in row.iter().enumerate() {
1918                sheet.set_cell_src(r + 1, c, v.to_string());
1919            }
1920        }
1921        sheet.commit(None).unwrap();
1922        sheet
1923            .add_table("Sales".to_string(), 0, 0, 2, 2, true, false)
1924            .unwrap();
1925
1926        let mut pivot = base_pivot();
1927        pivot.row_fields = vec![];
1928        pivot.col_fields = vec![PivotField::new("Group"), PivotField::new("Sub")];
1929        pivot.grand_totals_col = false;
1930        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1931
1932        // Deepest (Sub) row: "X" must appear for *both* groups, not just
1933        // the first (with the second silently blanked as a false "repeat").
1934        let sub_row = &grid.header_rows[2];
1935        let x_count = sub_row.iter().filter(|c| *c == "X").count();
1936        assert_eq!(
1937            x_count, 2,
1938            "expected \"X\" under both GroupA and GroupB, got {sub_row:?}"
1939        );
1940    }
1941
1942    #[test]
1943    fn test_multiple_value_fields_become_column_labels() {
1944        let sheet = source_sheet();
1945        let mut pivot = base_pivot();
1946        pivot.value_fields = vec![
1947            PivotValueField::new("Amount", PivotAggregation::Sum),
1948            PivotValueField::new("Amount", PivotAggregation::Count),
1949        ];
1950        pivot.grand_totals_row = false;
1951        pivot.grand_totals_col = false;
1952        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1953        assert_eq!(grid.header_rows.last().unwrap()[1], "Sum of Amount");
1954        // The first value field on "Amount" uses Sum, which clones the
1955        // column for every value field after it (see `value_field_labels`'s
1956        // doc comment) -- so the second value field's default label
1957        // disambiguates as "Amount2", matching real Excel.
1958        assert_eq!(grid.header_rows.last().unwrap()[2], "Count of Amount2");
1959        assert_eq!(grid.body_rows[0].values.len(), 2);
1960        assert_eq!(value_at(&grid.body_rows[0], 0), 50.0); // Sum for East
1961        assert_eq!(value_at(&grid.body_rows[0], 1), 4.0); // Count for East
1962    }
1963
1964    #[test]
1965    fn test_row_labels_caption_replaces_outermost_row_field_name() {
1966        // Matches Excel's default "compact form" display (verified against
1967        // real Excel via fuzz/fuzz_pivot.py): the outermost row field's own
1968        // name never appears in the header at all -- it's always the
1969        // literal text "Row Labels".
1970        let sheet = source_sheet();
1971        let pivot = base_pivot(); // row_fields=[Region], col_fields=[]
1972        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1973        assert_eq!(grid.header_rows.last().unwrap()[0], "Row Labels");
1974    }
1975
1976    #[test]
1977    fn test_column_labels_row_prepended_and_deeper_row_field_keeps_its_name() {
1978        let sheet = source_sheet();
1979        let mut pivot = base_pivot();
1980        pivot.row_fields = vec![PivotField::new("Region"), PivotField::new("Product")];
1981        pivot.col_fields = vec![PivotField::new("Rep")];
1982        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
1983
1984        // Whenever there's at least one column field, Excel inserts an
1985        // extra header row above the column-value rows, captioned
1986        // "Column Labels".
1987        assert!(grid.header_rows[0].iter().any(|c| c == "Column Labels"));
1988        // Row-label captions land on the last header row: the outermost
1989        // row field ("Region") becomes "Row Labels", but a *deeper* row
1990        // field ("Product") keeps its own real name.
1991        let last = grid.header_rows.last().unwrap();
1992        assert_eq!(last[0], "Row Labels");
1993        assert_eq!(last[1], "Product");
1994    }
1995
1996    #[test]
1997    fn test_grand_total_column_shows_total_prefixed_value_label_with_multiple_value_fields() {
1998        let sheet = source_sheet();
1999        let mut pivot = base_pivot();
2000        pivot.col_fields = vec![PivotField::new("Product")];
2001        pivot.value_fields = vec![
2002            PivotValueField::new("Amount", PivotAggregation::Sum),
2003            PivotValueField::new("Amount", PivotAggregation::Min),
2004        ];
2005        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2006
2007        // The grand-total column's caption lands on the column-field row
2008        // (not repeated per value field as plain "Grand Total"), combining
2009        // "Total " with each value field's own label. Sum is first on
2010        // "Amount", so it clones the column for the following value field
2011        // (see `value_field_labels`'s doc comment), giving Min the
2012        // disambiguated "Amount2".
2013        let col_values_row = &grid.header_rows[1];
2014        assert!(col_values_row.contains(&"Total Sum of Amount".to_string()));
2015        assert!(col_values_row.contains(&"Total Min of Amount2".to_string()));
2016        // The value-label row directly below leaves the grand-total's
2017        // columns blank, since the caption already appeared above it.
2018        assert_eq!(grid.header_rows.last().unwrap().last().unwrap(), "");
2019    }
2020
2021    #[test]
2022    fn test_grand_total_still_shows_with_only_one_leaf_group() {
2023        // Excel shows the grand total whenever the toggle is on, regardless of
2024        // how many groups it's summarizing (even with only one leaf group).
2025        let sheet = source_sheet();
2026        let mut pivot = base_pivot();
2027        pivot.filter_fields = vec![PivotFilterField {
2028            column: "Region".to_string(),
2029            selected_values: Some(vec!["East".to_string()]),
2030            multiple_selection: true,
2031        }];
2032        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2033        assert!(grid.body_rows.iter().any(|r| r.is_grand_total));
2034    }
2035
2036    #[test]
2037    fn test_case_variant_values_merge_using_globally_first_seen_casing() {
2038        // Case-insensitive grouping merges values consistently across all
2039        // branches using the field's first occurrence anywhere in the source data.
2040        let mut sheet = Sheet::new(SheetInit {
2041            name: Some("Data".to_string()),
2042            rows: 5,
2043            cols: 3,
2044            ..Default::default()
2045        });
2046        for (c, h) in ["Group", "Mixed", "Amount"].iter().enumerate() {
2047            sheet.set_cell_src(0, c, h.to_string());
2048        }
2049        // "EAST" (uppercase) appears first in sheet order under Group=G1;
2050        // "east" (lowercase) appears later, nested under a *different*
2051        // Group=G2 branch.
2052        let rows: [[&str; 3]; 3] = [
2053            ["G1", "EAST", "10"],
2054            ["G1", "West", "20"],
2055            ["G2", "east", "30"],
2056        ];
2057        for (r, row) in rows.iter().enumerate() {
2058            for (c, v) in row.iter().enumerate() {
2059                sheet.set_cell_src(r + 1, c, v.to_string());
2060            }
2061        }
2062        sheet.commit(None).unwrap();
2063        sheet
2064            .add_table("Sales".to_string(), 0, 0, 3, 2, true, false)
2065            .unwrap();
2066
2067        let mut pivot = base_pivot();
2068        pivot.row_fields = vec![PivotField::new("Group"), PivotField::new("Mixed")];
2069        pivot.grand_totals_row = false;
2070        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2071
2072        let mixed_labels: Vec<&str> = grid
2073            .body_rows
2074            .iter()
2075            .map(|r| r.row_labels[1].as_str())
2076            .filter(|l| !l.is_empty())
2077            .collect();
2078        assert!(
2079            mixed_labels.contains(&"EAST") && !mixed_labels.contains(&"east"),
2080            "expected every occurrence to use the globally first-seen casing \"EAST\", got {mixed_labels:?}"
2081        );
2082    }
2083
2084    #[test]
2085    fn test_case_canonicalization_uses_first_seen_casing_from_unfiltered_source_not_just_surviving_rows()
2086     {
2087        // Canonical casing for a case-insensitively merged group is determined
2088        // from the full source data field-wide, not just the filtered record set.
2089        let mut sheet = Sheet::new(SheetInit {
2090            name: Some("Data".to_string()),
2091            rows: 4,
2092            cols: 3,
2093            ..Default::default()
2094        });
2095        for (c, h) in ["Cat", "Mixed", "Amount"].iter().enumerate() {
2096            sheet.set_cell_src(0, c, h.to_string());
2097        }
2098        // The true first occurrence of the "west"/"WEST" value is "WEST"
2099        // (row 1), but it's filtered out below (Cat="Alpha" excluded);
2100        // "west" (row 3, Cat="Beta", which survives the filter) must still
2101        // canonicalize to "WEST", not to itself.
2102        let rows: [[&str; 3]; 3] = [
2103            ["Alpha", "WEST", "10"],
2104            ["Beta", "East", "20"],
2105            ["Beta", "west", "30"],
2106        ];
2107        for (r, row) in rows.iter().enumerate() {
2108            for (c, v) in row.iter().enumerate() {
2109                sheet.set_cell_src(r + 1, c, v.to_string());
2110            }
2111        }
2112        sheet.commit(None).unwrap();
2113        sheet
2114            .add_table("Sales".to_string(), 0, 0, 3, 2, true, false)
2115            .unwrap();
2116
2117        let mut pivot = base_pivot();
2118        pivot.row_fields = vec![PivotField::new("Mixed")];
2119        pivot.filter_fields = vec![PivotFilterField {
2120            column: "Cat".to_string(),
2121            selected_values: Some(vec!["Beta".to_string()]),
2122            multiple_selection: true,
2123        }];
2124        pivot.grand_totals_row = false;
2125        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2126
2127        let labels: Vec<&str> = grid
2128            .body_rows
2129            .iter()
2130            .map(|r| r.row_labels[0].as_str())
2131            .collect();
2132        assert!(
2133            labels.contains(&"WEST") && !labels.contains(&"west"),
2134            "expected the filtered-out row's casing \"WEST\" to still win, got {labels:?}"
2135        );
2136    }
2137
2138    #[test]
2139    fn test_blank_group_sorts_last_even_among_numeric_siblings() {
2140        let mut sheet = Sheet::new(SheetInit {
2141            name: Some("Data".to_string()),
2142            rows: 4,
2143            cols: 2,
2144            ..Default::default()
2145        });
2146        for (c, h) in ["Code", "Amount"].iter().enumerate() {
2147            sheet.set_cell_src(0, c, h.to_string());
2148        }
2149        // 30 < ... numerically, but the blank row's Code cell is left
2150        // empty entirely -- deliberately out of numeric order so a sort
2151        // that just treated "(blank)" as any other value would put it
2152        // first (its group_key text "(blank)" sorts alphabetically before
2153        // digits) rather than last.
2154        sheet.set_cell_src(1, 0, "30".to_string());
2155        sheet.set_cell_src(1, 1, "1".to_string());
2156        sheet.set_cell_src(3, 0, "10".to_string());
2157        sheet.set_cell_src(3, 1, "3".to_string());
2158        sheet.commit(None).unwrap();
2159        sheet
2160            .add_table("Sales".to_string(), 0, 0, 3, 1, true, false)
2161            .unwrap();
2162
2163        let mut pivot = base_pivot();
2164        pivot.row_fields = vec![PivotField::new("Code")];
2165        pivot.grand_totals_row = false;
2166        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2167
2168        let codes: Vec<&str> = grid
2169            .body_rows
2170            .iter()
2171            .map(|r| r.row_labels[0].as_str())
2172            .collect();
2173        assert_eq!(codes, vec!["10", "30", "(blank)"]);
2174    }
2175
2176    #[test]
2177    fn test_negative_looking_text_sorts_last_among_text_siblings() {
2178        // Real Windows Excel sorts negative-looking text by its digits
2179        // with the '-' stripped ("7"), which happens to land it last
2180        // among these particular siblings -- see `text_sort_key` and the
2181        // next test for a case where stripped-sign placement is *not*
2182        // last.
2183        let mut sheet = Sheet::new(SheetInit {
2184            name: Some("Data".to_string()),
2185            rows: 6,
2186            cols: 2,
2187            ..Default::default()
2188        });
2189        for (c, h) in ["Code", "Amount"].iter().enumerate() {
2190            sheet.set_cell_src(0, c, h.to_string());
2191        }
2192        let rows: [(&str, &str); 5] = [
2193            ("\"-7\"", "1"),
2194            ("\".0152\"", "2"),
2195            ("\"13\"", "3"),
2196            ("\"34\"", "4"),
2197            ("\"4\"", "5"),
2198        ];
2199        for (r, (code, amount)) in rows.iter().enumerate() {
2200            sheet.set_cell_src(r + 1, 0, code.to_string());
2201            sheet.set_cell_src(r + 1, 1, amount.to_string());
2202        }
2203        sheet.commit(None).unwrap();
2204        sheet
2205            .add_table("Sales".to_string(), 0, 0, 5, 1, true, false)
2206            .unwrap();
2207
2208        let mut pivot = base_pivot();
2209        pivot.row_fields = vec![PivotField::new("Code")];
2210        pivot.grand_totals_row = false;
2211        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2212
2213        let codes: Vec<&str> = grid
2214            .body_rows
2215            .iter()
2216            .map(|r| r.row_labels[0].as_str())
2217            .collect();
2218        assert_eq!(codes, vec![".0152", "13", "34", "4", "-7"]);
2219    }
2220
2221    #[test]
2222    fn test_negative_looking_text_sorts_by_stripped_digits_not_last() {
2223        // Harvested from fuzz/fuzz_pivot.py's win32com (Windows) run, seed
2224        // 118859: among siblings "12" and "37", real Excel placed "-25"
2225        // *between* them, not after both -- comparing "-25" by its
2226        // stripped digit string "25" (which alphabetically falls between
2227        // "12" and "37") is what predicts this; a simpler "negative always
2228        // sorts last" rule (as in the previous test) would wrongly put
2229        // "-25" after "37" here.
2230        let mut sheet = Sheet::new(SheetInit {
2231            name: Some("Data".to_string()),
2232            rows: 4,
2233            cols: 2,
2234            ..Default::default()
2235        });
2236        for (c, h) in ["Code", "Amount"].iter().enumerate() {
2237            sheet.set_cell_src(0, c, h.to_string());
2238        }
2239        let rows: [(&str, &str); 3] = [("\"12\"", "1"), ("\"37\"", "2"), ("\"-25\"", "3")];
2240        for (r, (code, amount)) in rows.iter().enumerate() {
2241            sheet.set_cell_src(r + 1, 0, code.to_string());
2242            sheet.set_cell_src(r + 1, 1, amount.to_string());
2243        }
2244        sheet.commit(None).unwrap();
2245        sheet
2246            .add_table("Sales".to_string(), 0, 0, 3, 1, true, false)
2247            .unwrap();
2248
2249        let mut pivot = base_pivot();
2250        pivot.row_fields = vec![PivotField::new("Code")];
2251        pivot.grand_totals_row = false;
2252        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2253
2254        let codes: Vec<&str> = grid
2255            .body_rows
2256            .iter()
2257            .map(|r| r.row_labels[0].as_str())
2258            .collect();
2259        assert_eq!(codes, vec!["12", "-25", "37"]);
2260    }
2261
2262    #[test]
2263    fn test_empty_row_col_intersection_renders_blank_not_zero_or_error() {
2264        // A row/column combination with zero underlying records (a sparse
2265        // cell in the cross-tab) renders as a genuinely blank cell in
2266        // Excel for every aggregation kind, not a computed zero or error
2267        // (verified against real Excel via fuzz/fuzz_pivot.py).
2268        let mut sheet = Sheet::new(SheetInit {
2269            name: Some("Data".to_string()),
2270            rows: 3,
2271            cols: 3,
2272            ..Default::default()
2273        });
2274        for (c, h) in ["Region", "Product", "Amount"].iter().enumerate() {
2275            sheet.set_cell_src(0, c, h.to_string());
2276        }
2277        // East only ever pairs with Widget; West only ever pairs with
2278        // Gadget -- so (East, Gadget) and (West, Widget) are both
2279        // genuinely empty intersections.
2280        let rows: [[&str; 3]; 2] = [["East", "Widget", "10"], ["West", "Gadget", "20"]];
2281        for (r, row) in rows.iter().enumerate() {
2282            for (c, v) in row.iter().enumerate() {
2283                sheet.set_cell_src(r + 1, c, v.to_string());
2284            }
2285        }
2286        sheet.commit(None).unwrap();
2287        sheet
2288            .add_table("Sales".to_string(), 0, 0, 2, 2, true, false)
2289            .unwrap();
2290
2291        let mut pivot = base_pivot();
2292        pivot.col_fields = vec![PivotField::new("Product")];
2293        pivot.value_fields = vec![
2294            PivotValueField::new("Amount", PivotAggregation::Sum),
2295            PivotValueField::new("Amount", PivotAggregation::Average),
2296        ];
2297        pivot.grand_totals_row = false;
2298        pivot.grand_totals_col = false;
2299        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2300
2301        // Row "East" only has Widget data, so both of its Gadget-column
2302        // cells (Sum and Average) must be blank.
2303        let east_row = grid
2304            .body_rows
2305            .iter()
2306            .find(|r| r.row_labels[0] == "East")
2307            .unwrap();
2308        for v in &east_row.values[..2] {
2309            assert!(
2310                matches!(v, ResultData::None),
2311                "expected blank for an empty intersection, got {v:?}"
2312            );
2313        }
2314    }
2315
2316    #[test]
2317    fn test_value_field_labels_distinct_aggregations_without_sum_stay_unsuffixed() {
2318        // Reusing a source column across multiple value fields with
2319        // *different*, non-Sum aggregations produces distinct default
2320        // captions on its own ("Max of Amount", "Count of Amount"), so
2321        // real Excel leaves them alone -- no "Amount2" suffix.
2322        let fields = vec![
2323            PivotValueField::new("Amount", PivotAggregation::Count),
2324            PivotValueField::new("Amount", PivotAggregation::Max),
2325        ];
2326        assert_eq!(
2327            value_field_labels(&fields),
2328            vec!["Count of Amount".to_string(), "Max of Amount".to_string()]
2329        );
2330    }
2331
2332    #[test]
2333    fn test_value_field_labels_sum_clones_column_for_later_fields() {
2334        // Unlike other aggregations, the *first* value field on a column that
2335        // uses `Sum` clones that column ("Amount" -> "Amount2") for every value
2336        // field *after* it in the list, regardless of their own aggregation.
2337        // "Rate" here has no Sum field at all, so it's unaffected and stays plain.
2338        let fields = vec![
2339            PivotValueField::new("Amount", PivotAggregation::Sum),
2340            PivotValueField::new("Rate", PivotAggregation::Average),
2341            PivotValueField::new("Amount", PivotAggregation::Min),
2342            PivotValueField::new("Amount", PivotAggregation::Max),
2343        ];
2344        assert_eq!(
2345            value_field_labels(&fields),
2346            vec![
2347                "Sum of Amount".to_string(),
2348                "Average of Rate".to_string(),
2349                "Min of Amount2".to_string(),
2350                "Max of Amount2".to_string(),
2351            ]
2352        );
2353    }
2354
2355    #[test]
2356    fn test_value_field_labels_second_sum_clones_again() {
2357        // A second `Sum` value field on the same column clones *again*
2358        // ("Amount2" -> "Amount3"), rather than reusing the first clone --
2359        // verified by direct real-Excel probing (see the test above).
2360        let fields = vec![
2361            PivotValueField::new("Amount", PivotAggregation::Sum),
2362            PivotValueField::new("Amount", PivotAggregation::Sum),
2363            PivotValueField::new("Amount", PivotAggregation::Count),
2364        ];
2365        assert_eq!(
2366            value_field_labels(&fields),
2367            vec![
2368                "Sum of Amount".to_string(),
2369                "Sum of Amount2".to_string(),
2370                "Count of Amount3".to_string(),
2371            ]
2372        );
2373    }
2374
2375    #[test]
2376    fn test_value_field_labels_disambiguates_identical_aggregation_and_column() {
2377        // Two value fields on the same column with the *same* aggregation
2378        // do produce an identical default caption ("Sum of Amount" twice),
2379        // so this is the one shape where real Excel's plain digit-suffix
2380        // disambiguation kicks in even without any preceding clone.
2381        let fields = vec![
2382            PivotValueField::new("Amount", PivotAggregation::Sum),
2383            PivotValueField::new("Amount", PivotAggregation::Sum),
2384            PivotValueField::new("Amount", PivotAggregation::Sum),
2385        ];
2386        assert_eq!(
2387            value_field_labels(&fields),
2388            vec![
2389                "Sum of Amount".to_string(),
2390                "Sum of Amount2".to_string(),
2391                "Sum of Amount3".to_string(),
2392            ]
2393        );
2394    }
2395
2396    #[test]
2397    fn test_value_field_labels_collision_within_sum_clone_uses_underscore_suffix() {
2398        // When a caption collision happens *inside* an already Sum-cloned
2399        // slot (two non-Sum fields on the same clone sharing an
2400        // aggregation), real Excel disambiguates by appending an
2401        // underscored counter to the whole already-suffixed caption
2402        // instead of incrementing the clone number again -- verified by
2403        // direct real-Excel probing.
2404        let fields = vec![
2405            PivotValueField::new("Amount", PivotAggregation::Sum),
2406            PivotValueField::new("Amount", PivotAggregation::Max),
2407            PivotValueField::new("Amount", PivotAggregation::Max),
2408        ];
2409        assert_eq!(
2410            value_field_labels(&fields),
2411            vec![
2412                "Sum of Amount".to_string(),
2413                "Max of Amount2".to_string(),
2414                "Max of Amount2_2".to_string(),
2415            ]
2416        );
2417    }
2418
2419    #[test]
2420    fn test_value_field_labels_count_numbers_shares_plain_count_caption() {
2421        // Excel's default caption for the "Count Numbers" summary function
2422        // is "Count of <field>" -- identical to plain "Count" -- not
2423        // "Count Numbers of <field>". Since both aggregations generate
2424        // the same caption text, using both on the same column is exactly
2425        // the collide-and-suffix case above.
2426        let fields = vec![
2427            PivotValueField::new("Rate", PivotAggregation::CountNumbers),
2428            PivotValueField::new("Rate", PivotAggregation::Count),
2429        ];
2430        assert_eq!(
2431            value_field_labels(&fields),
2432            vec!["Count of Rate".to_string(), "Count of Rate2".to_string()]
2433        );
2434    }
2435
2436    #[test]
2437    fn test_value_field_labels_leaves_custom_name_untouched() {
2438        let mut fields = vec![
2439            PivotValueField::new("Amount", PivotAggregation::Sum),
2440            PivotValueField::new("Amount", PivotAggregation::Min),
2441        ];
2442        fields[1].custom_name = Some("Lowest Amount".to_string());
2443        assert_eq!(
2444            value_field_labels(&fields),
2445            vec!["Sum of Amount".to_string(), "Lowest Amount".to_string()]
2446        );
2447    }
2448
2449    #[test]
2450    fn test_flat_pivot_with_no_row_or_col_fields_has_no_reserved_label_column() {
2451        // With neither row nor column fields (a single aggregate value, no
2452        // grouping at all), Excel doesn't reserve a separate row-label
2453        // column the way it does whenever *either* axis has fields -- the
2454        // value field's own header sits directly above the value, one column
2455        // wide total.
2456        let sheet = source_sheet();
2457        let mut pivot = base_pivot();
2458        pivot.row_fields = vec![];
2459        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2460
2461        assert_eq!(grid.width, 1);
2462        assert_eq!(
2463            grid.header_rows.last().unwrap(),
2464            &vec!["Sum of Amount".to_string()]
2465        );
2466        assert_eq!(grid.body_rows.len(), 1);
2467        assert!(grid.body_rows[0].row_labels.is_empty());
2468        assert_eq!(value_at(&grid.body_rows[0], 0), 195.0);
2469    }
2470
2471    #[test]
2472    fn test_no_row_fields_with_multiple_value_fields_has_no_reserved_label_column_either() {
2473        // Unlike the single-value-field case (which reserves one corner
2474        // column for that field's own label, e.g. "Max of Amount"), with
2475        // *multiple* value fields and no row fields there's no single
2476        // unambiguous label to put in a corner -- each value field's label
2477        // already shows up in its own column further along the header -- so
2478        // Excel reserves no column for it at all, regardless of whether
2479        // column fields are present.
2480        let sheet = source_sheet();
2481        let mut pivot = base_pivot();
2482        pivot.row_fields = vec![];
2483        pivot.col_fields = vec![PivotField::new("Product")];
2484        pivot.value_fields = vec![
2485            PivotValueField::new("Amount", PivotAggregation::Sum),
2486            PivotValueField::new("Amount", PivotAggregation::Count),
2487        ];
2488        pivot.grand_totals_col = false;
2489        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2490
2491        // width = 0 reserved + 2 column groups (Gadget, Widget) * 2 value
2492        // fields.
2493        assert_eq!(grid.width, 4);
2494        assert_eq!(grid.body_rows.len(), 1);
2495        assert!(grid.body_rows[0].row_labels.is_empty());
2496    }
2497
2498    #[test]
2499    fn test_multiple_value_fields_with_no_column_fields_share_one_header_row() {
2500        // With no column fields at all there's no column-group-values row
2501        // in the first place, so Excel lists each value field as a
2502        // plain adjacent column in the single header row, like an ordinary
2503        // flat table.
2504        let sheet = source_sheet();
2505        let mut pivot = base_pivot();
2506        pivot.value_fields = vec![
2507            PivotValueField::new("Amount", PivotAggregation::Sum),
2508            PivotValueField::new("Amount", PivotAggregation::Count),
2509        ];
2510        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2511
2512        assert_eq!(grid.header_rows.len(), 1);
2513        // Sum is first on "Amount", so it clones the column for the
2514        // following value field (see `value_field_labels`'s doc comment).
2515        assert_eq!(
2516            grid.header_rows[0],
2517            vec![
2518                "Row Labels".to_string(),
2519                "Sum of Amount".to_string(),
2520                "Count of Amount2".to_string(),
2521            ]
2522        );
2523    }
2524
2525    #[test]
2526    fn test_missing_column_errors() {
2527        let sheet = source_sheet();
2528        let mut pivot = base_pivot();
2529        pivot.row_fields = vec![PivotField::new("Nope")];
2530        let err = compute_pivot(&[&sheet], &pivot).unwrap_err();
2531        assert!(err.contains("not found"));
2532    }
2533
2534    #[test]
2535    fn test_range_source_matches_table_source() {
2536        // A pivot sourced from a raw range covering exactly a table's
2537        // declared bounds must produce the same grid as one sourced from
2538        // the table itself.
2539        let sheet = source_sheet();
2540        let mut pivot = base_pivot();
2541        pivot.source = PivotSource::Range {
2542            sheet_id: sheet.id,
2543            start_row: 0,
2544            start_col: 0,
2545            end_row: 8,
2546            end_col: 3,
2547        };
2548        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2549        assert_eq!(grid.body_rows.len(), 3);
2550        assert_eq!(value_at(&grid.body_rows[0], 0), 50.0);
2551        assert_eq!(value_at(&grid.body_rows[1], 0), 145.0);
2552        assert_eq!(value_at(&grid.body_rows[2], 0), 195.0);
2553    }
2554
2555    #[test]
2556    fn test_zero_data_rows_produces_empty_grid_without_panicking() {
2557        let mut sheet = Sheet::new(SheetInit {
2558            name: Some("Empty".to_string()),
2559            rows: 1,
2560            cols: 2,
2561            ..Default::default()
2562        });
2563        sheet.set_cell_src(0, 0, "Region".to_string());
2564        sheet.set_cell_src(0, 1, "Amount".to_string());
2565        sheet.commit(None).unwrap();
2566        sheet
2567            .add_table("Empty".to_string(), 0, 0, 0, 1, true, false)
2568            .unwrap();
2569
2570        let pivot = PivotTable {
2571            id: 1,
2572            name: "EmptyPivot".to_string(),
2573            source: PivotSource::Table {
2574                name: "Empty".to_string(),
2575            },
2576            dest_sheet_id: sheet.id,
2577            dest_row: 0,
2578            dest_col: 0,
2579            row_fields: vec![PivotField::new("Region")],
2580            col_fields: vec![],
2581            value_fields: vec![PivotValueField::new("Amount", PivotAggregation::Sum)],
2582            filter_fields: vec![],
2583            grand_totals_row: true,
2584            grand_totals_col: true,
2585            last_output_end_row: None,
2586            last_output_end_col: None,
2587        };
2588        let grid = compute_pivot(&[&sheet], &pivot).unwrap();
2589        // No records at all -> no groups, and (per `build_axis`) a grand
2590        // total is only appended when there's more than one group, so none
2591        // is emitted here either.
2592        assert!(grid.body_rows.is_empty());
2593        assert!(grid.row_axis.is_empty());
2594    }
2595
2596    // ---- Randomized invariant fuzzing --------------------------------
2597    //
2598    // Builds many random source sheets + pivot configurations and checks
2599    // internal self-consistency (never panics; every output cell, whether
2600    // leaf/subtotal/grand-total, equals an independently-derived aggregate
2601    // over the same filtered records; xlsx export/import round-trips
2602    // field assignments faithfully). This is a self-consistency fuzzer,
2603    // not a check against real Excel -- that's `fuzz/fuzz_pivot.py`'s job
2604    // -- but it's cheap to run in `cargo test` and catches crashes and logic
2605    // issues in the group-tree flattening/subtotal/grand-total code.
2606    use rand::rngs::StdRng;
2607    use rand::{Rng, SeedableRng};
2608
2609    const FUZZ_COLS: [&str; 6] = ["Cat", "Mixed", "NumStr", "Amount", "Rate", "Flag"];
2610    const FUZZ_CATEGORIES: [&str; 5] = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"];
2611    const FUZZ_CASE_VARIANTS: [&str; 5] = ["East", "east", "WEST", "west", "North"];
2612
2613    /// Builds a random source sheet with columns chosen to exercise
2614    /// grouping edge cases: a low-cardinality category column with
2615    /// occasional blanks, a case-variant category column (case-insensitive
2616    /// grouping parity), a quoted numeric-looking-string column (the
2617    /// numeric-vs-text sort ambiguity `sort_group_entries` has to resolve),
2618    /// two numeric columns (ints and floats, including negative/zero), and
2619    /// a boolean column (ignored by Sum/Average/Max/Min).
2620    fn fuzz_source_sheet(rng: &mut StdRng, num_rows: usize) -> (Sheet, Vec<String>) {
2621        let mut sheet = Sheet::new(SheetInit {
2622            name: Some("FuzzData".to_string()),
2623            rows: num_rows + 1,
2624            cols: FUZZ_COLS.len(),
2625            ..Default::default()
2626        });
2627        for (c, h) in FUZZ_COLS.iter().enumerate() {
2628            sheet.set_cell_src(0, c, h.to_string());
2629        }
2630        for r in 0..num_rows {
2631            let cat = if rng.gen_bool(0.1) {
2632                String::new()
2633            } else {
2634                FUZZ_CATEGORIES[rng.gen_range(0..FUZZ_CATEGORIES.len())].to_string()
2635            };
2636            sheet.set_cell_src(r + 1, 0, cat);
2637
2638            let mixed = FUZZ_CASE_VARIANTS[rng.gen_range(0..FUZZ_CASE_VARIANTS.len())].to_string();
2639            sheet.set_cell_src(r + 1, 1, mixed);
2640
2641            let numstr = match rng.gen_range(0u8..4u8) {
2642                0 => String::new(),
2643                1 => format!("\"0{}\"", rng.gen_range(0u32..10u32)),
2644                2 => format!("\".0{}\"", rng.gen_range(0u32..1000u32)),
2645                _ => format!("\"{}\"", rng.gen_range(-50i64..50i64)),
2646            };
2647            sheet.set_cell_src(r + 1, 2, numstr);
2648
2649            sheet.set_cell_src(r + 1, 3, rng.gen_range(-100i64..=100i64).to_string());
2650
2651            let rate =
2652                (rng.gen_range(-500i64..=500i64) as f64) / (rng.gen_range(1i64..=100i64) as f64);
2653            sheet.set_cell_src(r + 1, 4, format!("{:.4}", rate));
2654
2655            sheet.set_cell_src(r + 1, 5, rng.gen_bool(0.5).to_string());
2656        }
2657        sheet.commit(None).unwrap();
2658        (sheet, FUZZ_COLS.iter().map(|s| s.to_string()).collect())
2659    }
2660
2661    fn random_aggregation(rng: &mut StdRng) -> PivotAggregation {
2662        match rng.gen_range(0u8..6u8) {
2663            0 => PivotAggregation::Sum,
2664            1 => PivotAggregation::Count,
2665            2 => PivotAggregation::CountNumbers,
2666            3 => PivotAggregation::Average,
2667            4 => PivotAggregation::Max,
2668            _ => PivotAggregation::Min,
2669        }
2670    }
2671
2672    /// Builds a random, always-valid `PivotTable` config over `sheet`:
2673    /// 0-2 row fields and 0-2 col fields (drawn without replacement from
2674    /// the categorical columns), 1-2 value fields (from the numeric
2675    /// columns), an optional filter field with a random subset of its
2676    /// actual distinct values selected (including the all-excluded case),
2677    /// and random per-field subtotal / grand-total toggles.
2678    fn fuzz_pivot_config(
2679        rng: &mut StdRng,
2680        sheet: &Sheet,
2681        col_names: &[String],
2682        num_rows: usize,
2683        use_table: bool,
2684    ) -> PivotTable {
2685        let mut pool: Vec<usize> = vec![0, 1, 2]; // Cat, Mixed, NumStr
2686        let numeric: [usize; 2] = [3, 4]; // Amount, Rate
2687
2688        let n_row = rng.gen_range(0..=pool.len().min(2));
2689        let row_cols: Vec<usize> = (0..n_row)
2690            .map(|_| pool.remove(rng.gen_range(0..pool.len())))
2691            .collect();
2692        let n_col = rng.gen_range(0..=pool.len().min(2));
2693        let col_cols: Vec<usize> = (0..n_col)
2694            .map(|_| pool.remove(rng.gen_range(0..pool.len())))
2695            .collect();
2696
2697        let row_fields: Vec<PivotField> = row_cols
2698            .iter()
2699            .map(|&i| PivotField {
2700                column: col_names[i].clone(),
2701                subtotal: rng.gen_bool(0.7),
2702            })
2703            .collect();
2704        let col_fields: Vec<PivotField> = col_cols
2705            .iter()
2706            .map(|&i| PivotField {
2707                column: col_names[i].clone(),
2708                subtotal: rng.gen_bool(0.7),
2709            })
2710            .collect();
2711
2712        let n_value = rng.gen_range(1..=2);
2713        let value_fields: Vec<PivotValueField> = (0..n_value)
2714            .map(|_| {
2715                let col = numeric[rng.gen_range(0..numeric.len())];
2716                PivotValueField::new(col_names[col].clone(), random_aggregation(rng))
2717            })
2718            .collect();
2719
2720        let mut filter_fields = Vec::new();
2721        if rng.gen_bool(0.5) {
2722            let candidates = [0usize, 1, 2, 5];
2723            let fcol = candidates[rng.gen_range(0..candidates.len())];
2724            let mut distinct: Vec<String> = (1..=num_rows)
2725                .map(|r| group_key(&sheet.get_result_data(&CellRef::new(r, fcol))))
2726                .collect();
2727            distinct.sort();
2728            distinct.dedup();
2729            let selected = if distinct.is_empty() || rng.gen_bool(0.2) {
2730                None
2731            } else {
2732                // May legitimately come out empty -> filters out every record.
2733                Some(distinct.into_iter().filter(|_| rng.gen_bool(0.5)).collect())
2734            };
2735            filter_fields.push(PivotFilterField {
2736                column: col_names[fcol].clone(),
2737                selected_values: selected,
2738                multiple_selection: true,
2739            });
2740        }
2741
2742        let source = if use_table {
2743            PivotSource::Table {
2744                name: "FuzzTable".to_string(),
2745            }
2746        } else {
2747            PivotSource::Range {
2748                sheet_id: sheet.id,
2749                start_row: 0,
2750                start_col: 0,
2751                end_row: num_rows,
2752                end_col: col_names.len() - 1,
2753            }
2754        };
2755
2756        PivotTable {
2757            id: 1,
2758            name: "FuzzPivot".to_string(),
2759            source,
2760            dest_sheet_id: sheet.id,
2761            dest_row: num_rows + 20,
2762            dest_col: 0,
2763            row_fields,
2764            col_fields,
2765            value_fields,
2766            filter_fields,
2767            grand_totals_row: rng.gen_bool(0.7),
2768            grand_totals_col: rng.gen_bool(0.7),
2769            last_output_end_row: None,
2770            last_output_end_col: None,
2771        }
2772    }
2773
2774    fn results_close(a: &ResultData, b: &ResultData) -> bool {
2775        match (a, b) {
2776            (ResultData::Integer(x), ResultData::Integer(y)) => x == y,
2777            (ResultData::Float(x), ResultData::Float(y)) => (x - y).abs() < 1e-6,
2778            (ResultData::Integer(x), ResultData::Float(y))
2779            | (ResultData::Float(y), ResultData::Integer(x)) => (*x as f64 - y).abs() < 1e-6,
2780            (ResultData::None, ResultData::None) => true,
2781            (ResultData::Error(x), ResultData::Error(y)) => x == y,
2782            (ResultData::String(x), ResultData::String(y)) => x == y,
2783            (ResultData::Boolean(x), ResultData::Boolean(y)) => x == y,
2784            _ => false,
2785        }
2786    }
2787
2788    /// A row/col axis label vector (`Some` per own depth, `None` past it --
2789    /// see `FlatGroup`) is a *partial key*: `None` positions are wildcards.
2790    /// This is exactly what a subtotal or grand-total group represents, so
2791    /// the same matcher works uniformly for leaf, subtotal, and grand-total
2792    /// groups.
2793    fn matches_partial(key: &[String], labels: &[Option<String>]) -> bool {
2794        // Case-insensitive, matching `build_group_tree`'s merge: an axis
2795        // label is whichever casing was first seen for that group, so a
2796        // record whose own key differs only in case must still match it.
2797        key.iter()
2798            .zip(labels)
2799            .all(|(k, want)| want.as_ref().is_none_or(|w| w.eq_ignore_ascii_case(k)))
2800    }
2801
2802    /// Cross-checks every cell of `grid` against an aggregate computed by a
2803    /// structurally independent path: instead of `compute_pivot`'s
2804    /// recursive group-tree + flatten, this filters the same record set by
2805    /// simple partial-key matching against each axis item's labels. Catches
2806    /// bugs in the tree-based grouping/flattening/subtotal-insertion logic
2807    /// specifically, since the aggregation math itself (`aggregate`) is
2808    /// shared and already covered by the fixed-data tests above.
2809    fn verify_grid_matches_records(sheet: &Sheet, pivot: &PivotTable, grid: &PivotGrid) {
2810        let (_, col_names, sheet_cols, data_rows) =
2811            resolve_source(&[sheet], &pivot.source).unwrap();
2812        let row_idxs: Vec<usize> = pivot
2813            .row_fields
2814            .iter()
2815            .map(|f| column_index(&col_names, &f.column).unwrap())
2816            .collect();
2817        let col_idxs: Vec<usize> = pivot
2818            .col_fields
2819            .iter()
2820            .map(|f| column_index(&col_names, &f.column).unwrap())
2821            .collect();
2822
2823        let mut records: Vec<(Vec<String>, Vec<String>, Vec<ResultData>)> = Vec::new();
2824        'row: for &r in &data_rows {
2825            let row_vals: Vec<ResultData> = sheet_cols
2826                .iter()
2827                .map(|&c| sheet.get_result_data(&CellRef::new(r, c)))
2828                .collect();
2829            for ff in &pivot.filter_fields {
2830                if let Some(selected) = &ff.selected_values {
2831                    let idx = column_index(&col_names, &ff.column).unwrap();
2832                    let key = group_key(&row_vals[idx]);
2833                    // Case-insensitive, matching `compute_pivot`'s own filter
2834                    // step (a filter field's items are merged case-different
2835                    // text, same as row/col group labels).
2836                    if !selected.iter().any(|v| v.eq_ignore_ascii_case(&key)) {
2837                        continue 'row;
2838                    }
2839                }
2840            }
2841            let row_key: Vec<String> = row_idxs.iter().map(|&i| group_key(&row_vals[i])).collect();
2842            let col_key: Vec<String> = col_idxs.iter().map(|&i| group_key(&row_vals[i])).collect();
2843            records.push((row_key, col_key, row_vals));
2844        }
2845
2846        let value_idxs: Vec<usize> = pivot
2847            .value_fields
2848            .iter()
2849            .map(|vf| column_index(&col_names, &vf.column).unwrap())
2850            .collect();
2851        let value_multiplier = if pivot.value_fields.len() > 1 {
2852            pivot.value_fields.len()
2853        } else {
2854            1
2855        };
2856        let width = row_label_width(pivot);
2857
2858        assert_eq!(grid.body_rows.len(), grid.row_axis.len());
2859        assert_eq!(grid.width, width + grid.col_axis.len() * value_multiplier);
2860        for hrow in &grid.header_rows {
2861            assert_eq!(hrow.len(), grid.width);
2862        }
2863
2864        for (i, (body_row, row_axis)) in grid.body_rows.iter().zip(grid.row_axis.iter()).enumerate()
2865        {
2866            assert_eq!(
2867                body_row.is_grand_total, row_axis.is_grand_total,
2868                "row {i} grand-total flag mismatch"
2869            );
2870            assert_eq!(body_row.row_labels.len(), width, "row {i} label width");
2871            assert_eq!(
2872                body_row.values.len(),
2873                grid.col_axis.len() * value_multiplier,
2874                "row {i} value count"
2875            );
2876
2877            for (j, col_axis) in grid.col_axis.iter().enumerate() {
2878                let matching: Vec<&Vec<ResultData>> = records
2879                    .iter()
2880                    .filter(|(rk, ck, _)| {
2881                        matches_partial(rk, &row_axis.labels)
2882                            && matches_partial(ck, &col_axis.labels)
2883                    })
2884                    .map(|(_, _, row)| row)
2885                    .collect();
2886
2887                for (vf_pos, &vidx) in value_idxs.iter().enumerate() {
2888                    if vf_pos > 0 && value_multiplier == 1 {
2889                        break;
2890                    }
2891                    let col_vals: Vec<ResultData> =
2892                        matching.iter().map(|row| row[vidx].clone()).collect();
2893                    let expected =
2894                        aggregate(sheet, &col_vals, pivot.value_fields[vf_pos].aggregation);
2895                    let actual = &body_row.values[j * value_multiplier + vf_pos];
2896                    assert!(
2897                        results_close(&expected, actual),
2898                        "row {i} col {j} value-field {vf_pos}: expected {expected:?}, got {actual:?} \
2899                         (row_labels={:?}, col_labels={:?})",
2900                        row_axis.labels,
2901                        col_axis.labels,
2902                    );
2903                }
2904            }
2905        }
2906    }
2907
2908    /// A grand-total pseudo-group is appended whenever the toggle is on,
2909    /// *except* when the axis has no fields at all (`build_axis`'s
2910    /// no-fields early return never adds one -- there's no separate
2911    /// grouping to total distinctly from the single implicit group).
2912    /// Otherwise Excel shows it regardless of how many real groups exist,
2913    /// even just one (confirmed against real Excel via fuzz/fuzz_pivot.py).
2914    fn verify_grand_total_placement(
2915        axis: &[PivotAxisItem],
2916        grand_total_requested: bool,
2917        axis_has_fields: bool,
2918        label: &str,
2919    ) {
2920        let grand_count = axis.iter().filter(|a| a.is_grand_total).count();
2921        let has_any_real_group = axis.iter().any(|a| !a.is_grand_total);
2922        assert!(grand_count <= 1, "{label}: more than one grand-total group");
2923        if grand_total_requested && axis_has_fields && has_any_real_group {
2924            assert_eq!(
2925                grand_count, 1,
2926                "{label}: expected a grand total to be appended"
2927            );
2928        } else {
2929            assert_eq!(grand_count, 0, "{label}: did not expect a grand total");
2930        }
2931    }
2932
2933    #[test]
2934    fn test_fuzz_pivot_random_invariants() {
2935        for seed in 0u64..300 {
2936            let mut rng: StdRng = SeedableRng::seed_from_u64(seed);
2937            let use_table = seed % 2 == 0;
2938            // Zero-data-row (header-only) Excel Table coverage.
2939            let num_rows = rng.gen_range(0..=40usize);
2940            let (mut sheet, col_names) = fuzz_source_sheet(&mut rng, num_rows);
2941            if use_table {
2942                sheet
2943                    .add_table(
2944                        "FuzzTable".to_string(),
2945                        0,
2946                        0,
2947                        num_rows,
2948                        col_names.len() - 1,
2949                        true,
2950                        false,
2951                    )
2952                    .unwrap();
2953            }
2954            let pivot = fuzz_pivot_config(&mut rng, &sheet, &col_names, num_rows, use_table);
2955
2956            let grid = compute_pivot(&[&sheet], &pivot)
2957                .unwrap_or_else(|e| panic!("seed {seed}: compute_pivot failed: {e}"));
2958
2959            verify_grid_matches_records(&sheet, &pivot, &grid);
2960            verify_grand_total_placement(
2961                &grid.row_axis,
2962                pivot.grand_totals_row,
2963                !pivot.row_fields.is_empty(),
2964                "row axis",
2965            );
2966            verify_grand_total_placement(
2967                &grid.col_axis,
2968                pivot.grand_totals_col,
2969                !pivot.col_fields.is_empty(),
2970                "col axis",
2971            );
2972
2973            // Round-trip through xlsx export/import: field/aggregation
2974            // assignments, grand-total flags, and subtotal toggles must
2975            // survive; filter selections are documented (pivot_xlsx.rs) as
2976            // resetting to "all" rather than surviving.
2977            let xlsx = crate::core::xlsx::export_xlsx_data(
2978                std::slice::from_ref(&sheet),
2979                &[],
2980                std::slice::from_ref(&pivot),
2981                None,
2982            )
2983            .unwrap_or_else(|e| panic!("seed {seed}: export failed: {e}"));
2984            let (imported_sheets, _, imported_pivots, _) =
2985                crate::core::xlsx::import_xlsx_data(&xlsx, &[], |_, _, _| {})
2986                    .unwrap_or_else(|e| panic!("seed {seed}: import failed: {e}"));
2987            assert_eq!(
2988                imported_pivots.len(),
2989                1,
2990                "seed {seed}: pivot lost on round-trip"
2991            );
2992            let reimported = &imported_pivots[0];
2993
2994            assert_eq!(
2995                reimported
2996                    .row_fields
2997                    .iter()
2998                    .map(|f| &f.column)
2999                    .collect::<Vec<_>>(),
3000                pivot
3001                    .row_fields
3002                    .iter()
3003                    .map(|f| &f.column)
3004                    .collect::<Vec<_>>(),
3005                "seed {seed}: row field columns changed on round-trip"
3006            );
3007            assert_eq!(
3008                reimported
3009                    .col_fields
3010                    .iter()
3011                    .map(|f| &f.column)
3012                    .collect::<Vec<_>>(),
3013                pivot
3014                    .col_fields
3015                    .iter()
3016                    .map(|f| &f.column)
3017                    .collect::<Vec<_>>(),
3018                "seed {seed}: col field columns changed on round-trip"
3019            );
3020            assert_eq!(
3021                reimported
3022                    .value_fields
3023                    .iter()
3024                    .map(|f| (&f.column, f.aggregation))
3025                    .collect::<Vec<_>>(),
3026                pivot
3027                    .value_fields
3028                    .iter()
3029                    .map(|f| (&f.column, f.aggregation))
3030                    .collect::<Vec<_>>(),
3031                "seed {seed}: value fields changed on round-trip"
3032            );
3033            assert_eq!(reimported.grand_totals_row, pivot.grand_totals_row);
3034            assert_eq!(reimported.grand_totals_col, pivot.grand_totals_col);
3035            assert_eq!(
3036                reimported
3037                    .row_fields
3038                    .iter()
3039                    .map(|f| f.subtotal)
3040                    .collect::<Vec<_>>(),
3041                pivot
3042                    .row_fields
3043                    .iter()
3044                    .map(|f| f.subtotal)
3045                    .collect::<Vec<_>>(),
3046                "seed {seed}: row field subtotal toggle should round-trip"
3047            );
3048            assert_eq!(
3049                reimported
3050                    .col_fields
3051                    .iter()
3052                    .map(|f| f.subtotal)
3053                    .collect::<Vec<_>>(),
3054                pivot
3055                    .col_fields
3056                    .iter()
3057                    .map(|f| f.subtotal)
3058                    .collect::<Vec<_>>(),
3059                "seed {seed}: col field subtotal toggle should round-trip"
3060            );
3061            // If nothing lossy was actually in play, the reimported grid
3062            // must be structurally identical -- this is where a genuine
3063            // round-trip bug (e.g. losing a value field's aggregation)
3064            // would show up as a shape mismatch rather than a field-list
3065            // diff the assertions above already caught. Subtotal toggles
3066            // now round-trip exactly, so only filter selections remain
3067            // lossy.
3068            // Filter selections round-trip now too, so a lossless round trip
3069            // is the ordinary case rather than the exception.
3070            let nothing_lossy = true;
3071            let any_filter_is_also_an_axis_field = pivot.filter_fields.iter().any(|ff| {
3072                pivot
3073                    .row_fields
3074                    .iter()
3075                    .chain(pivot.col_fields.iter())
3076                    .any(|f| f.column.eq_ignore_ascii_case(&ff.column))
3077            });
3078            let reimported_sheets: Vec<Sheet> =
3079                imported_sheets.into_iter().map(|s| s.sheet).collect();
3080            let reimported_sheet_refs: Vec<&Sheet> = reimported_sheets.iter().collect();
3081            let reimported_grid = compute_pivot(&reimported_sheet_refs, reimported)
3082                .unwrap_or_else(|e| panic!("seed {seed}: reimported compute_pivot failed: {e}"));
3083            // A field Excel could not represent at all -- see
3084            // `axis_bound` below -- is excluded from the shape check for the
3085            // same reason it is excluded from the selection check.
3086            if nothing_lossy && !any_filter_is_also_an_axis_field {
3087                assert_eq!(
3088                    reimported_grid.body_rows.len(),
3089                    grid.body_rows.len(),
3090                    "seed {seed}: grid shape changed on lossless round-trip"
3091                );
3092            }
3093
3094            // Filter selections round-trip now: they are written as indices
3095            // into the cache's `<sharedItems>` and resolved back to plain
3096            // values on import. What must match is the *set* of selected
3097            // values, since the file stores them in the cache's first-seen
3098            // order rather than the caller's.
3099            //
3100            // The one legitimate difference: a selection covering every
3101            // value marks nothing hidden, so it is indistinguishable from no
3102            // filter once written and comes back as `None`. That is only
3103            // acceptable if it really was a no-op, which the grid proves.
3104            // Compared case-insensitively, because the engine merges
3105            // case-variant values into one item (keyed by the first casing
3106            // seen in the source). So a selection naming both `WEST` and
3107            // `west` picks a single item and legitimately reads back as
3108            // whichever casing the cache stored -- a canonicalization, not a
3109            // loss.
3110            let sorted = |f: &PivotFilterField| {
3111                f.selected_values.as_ref().map(|v| {
3112                    let mut v: Vec<String> = v.iter().map(|s| s.to_lowercase()).collect();
3113                    v.sort();
3114                    v.dedup();
3115                    v
3116                })
3117            };
3118            // A filter column that is *also* a row or column field has no
3119            // representation in the file: a pivot field carries one `axis`,
3120            // so the row/column orientation wins and there is nowhere left to
3121            // record the selection. Excel cannot express that config either
3122            // -- a field has exactly one orientation there -- so this is a
3123            // shape visi's model admits and the format does not, rather than
3124            // a round-trip bug.
3125            let axis_bound = |column: &str| {
3126                pivot
3127                    .row_fields
3128                    .iter()
3129                    .chain(pivot.col_fields.iter())
3130                    .any(|f| f.column.eq_ignore_ascii_case(column))
3131            };
3132            for (before, after) in pivot
3133                .filter_fields
3134                .iter()
3135                .zip(reimported.filter_fields.iter())
3136            {
3137                if axis_bound(&before.column) {
3138                    continue;
3139                }
3140                if before.selected_values.is_some() && after.selected_values.is_none() {
3141                    assert_eq!(
3142                        reimported_grid.body_rows.len(),
3143                        grid.body_rows.len(),
3144                        "seed {seed}: filter on '{}' was dropped and it mattered",
3145                        before.column
3146                    );
3147                } else {
3148                    assert_eq!(
3149                        sorted(before),
3150                        sorted(after),
3151                        "seed {seed}: filter selection should round-trip for '{}'",
3152                        before.column
3153                    );
3154                }
3155            }
3156        }
3157    }
3158}