Skip to main content

sheetkit_core/workbook/
data.rs

1use super::io::serialize_xml;
2use super::*;
3use crate::traversal::{checked_output_add, CheckedRect, TraversalLimits};
4
5struct PivotOutputBudget {
6    limits: TraversalLimits,
7    used: u64,
8}
9
10impl PivotOutputBudget {
11    fn new(limits: TraversalLimits) -> Self {
12        Self { limits, used: 0 }
13    }
14
15    fn charge(&mut self, bytes: u64) -> Result<()> {
16        let remaining = self.limits.max_output_bytes().saturating_sub(self.used);
17        let admitted = bytes.min(remaining.saturating_add(1));
18        self.used = checked_output_add(self.used, admitted, self.limits)?;
19        Ok(())
20    }
21
22    fn charge_usize(&mut self, bytes: usize) -> Result<()> {
23        self.charge(u64::try_from(bytes).unwrap_or(u64::MAX))
24    }
25
26    fn charge_array<T>(&mut self, count: usize) -> Result<()> {
27        let bytes = count.saturating_mul(std::mem::size_of::<T>());
28        self.charge_usize(bytes)
29    }
30}
31
32struct PivotXmlCounter<'a> {
33    budget: &'a mut PivotOutputBudget,
34    budget_error: Option<Error>,
35}
36
37impl std::fmt::Write for PivotXmlCounter<'_> {
38    fn write_str(&mut self, value: &str) -> std::fmt::Result {
39        if let Err(error) = self.budget.charge_usize(value.len()) {
40            self.budget_error = Some(error);
41            return Err(std::fmt::Error);
42        }
43        Ok(())
44    }
45}
46
47fn charge_pivot_xml<T: serde::Serialize>(budget: &mut PivotOutputBudget, value: &T) -> Result<()> {
48    budget.charge_usize(XML_DECLARATION.len() + 1)?;
49    let mut counter = PivotXmlCounter {
50        budget,
51        budget_error: None,
52    };
53    let result = value.serialize(quick_xml::se::Serializer::new(&mut counter));
54    if let Some(error) = counter.budget_error {
55        return Err(error);
56    }
57    result.map_err(|error| Error::XmlParse(error.to_string()))
58}
59
60fn pivot_cache_string_bytes(value: &CellValue) -> usize {
61    match value {
62        CellValue::Empty => 0,
63        CellValue::Bool(value) => {
64            if *value {
65                4
66            } else {
67                5
68            }
69        }
70        CellValue::Number(value) | CellValue::Date(value) if value.is_finite() => 0,
71        CellValue::String(value) | CellValue::Error(value) => value.len(),
72        CellValue::RichString(runs) => runs.iter().map(|run| run.text.len()).sum(),
73        CellValue::Formula {
74            result: Some(result),
75            ..
76        } => pivot_cache_string_bytes(result),
77        CellValue::Formula { expr, result: None } => expr.len().saturating_add(1),
78        CellValue::Number(_) | CellValue::Date(_) => 32,
79    }
80}
81
82impl Workbook {
83    /// Add a pivot table to the workbook.
84    ///
85    /// The pivot table summarizes data from `config.source_sheet` /
86    /// `config.source_range` and places its output on `config.target_sheet`
87    /// starting at `config.target_cell`.
88    pub fn add_pivot_table(&mut self, config: &PivotTableConfig) -> Result<()> {
89        self.add_pivot_table_with_limits(config, TraversalLimits::default())
90    }
91
92    /// Add a pivot table with explicit finite source traversal limits.
93    pub fn add_pivot_table_with_limits(
94        &mut self,
95        config: &PivotTableConfig,
96        limits: TraversalLimits,
97    ) -> Result<()> {
98        let mut output_budget = PivotOutputBudget::new(limits);
99        Self::charge_pivot_config(config, &mut output_budget)?;
100        self.sheet_index(&config.source_sheet)?;
101        let target_idx = self.sheet_index(&config.target_sheet)?;
102
103        if self
104            .get_pivot_tables()
105            .iter()
106            .any(|pivot| pivot.name == config.name)
107        {
108            return Err(Error::PivotTableAlreadyExists {
109                name: config.name.clone(),
110            });
111        }
112
113        // Admit the complete dense source before allocating rows or mutating
114        // deferred/typed pivot state.
115        let (field_names, source_rows) = self.read_pivot_source_with_limits(
116            &config.source_sheet,
117            &config.source_range,
118            limits,
119            &mut output_budget,
120        )?;
121        if field_names.is_empty() || field_names.iter().any(String::is_empty) {
122            return Err(Error::InvalidSourceRange(
123                "source range contains an empty header".to_string(),
124            ));
125        }
126
127        // Lowest unused cache ID across pivot tables and workbook caches;
128        // gaps are reused and parsed IDs near u32::MAX cannot overflow.
129        let used_cache_ids: std::collections::HashSet<u32> = self
130            .pivot_tables
131            .iter()
132            .map(|(_, pt)| pt.cache_id)
133            .chain(
134                self.workbook_xml
135                    .pivot_caches
136                    .iter()
137                    .flat_map(|caches| caches.caches.iter().map(|cache| cache.cache_id)),
138            )
139            .collect();
140        let cache_id = (0..=u32::MAX)
141            .find(|id| !used_cache_ids.contains(id))
142            .ok_or_else(|| Error::InvalidArgument("no unused pivot cache ID available".into()))?;
143
144        let mut occupied_paths = self.occupied_part_paths();
145        let allocate_part =
146            |prefix: &str,
147             has_relationship_part: bool,
148             occupied: &mut std::collections::HashSet<String>| {
149                let mut number = 1usize;
150                loop {
151                    let path = format!("{prefix}{number}.xml");
152                    let rels_path = relationship_part_path(&path);
153                    if !occupied.contains(&path)
154                        && (!has_relationship_part || !occupied.contains(&rels_path))
155                    {
156                        occupied.insert(path.clone());
157                        if has_relationship_part {
158                            occupied.insert(rels_path);
159                        }
160                        break path;
161                    }
162                    number += 1;
163                }
164            };
165        let pt_path = allocate_part("xl/pivotTables/pivotTable", true, &mut occupied_paths);
166        let pcd_path = allocate_part(
167            "xl/pivotCache/pivotCacheDefinition",
168            true,
169            &mut occupied_paths,
170        );
171        let pcr_path = allocate_part(
172            "xl/pivotCache/pivotCacheRecords",
173            false,
174            &mut occupied_paths,
175        );
176
177        let cache_records_rid = "rId1".to_string();
178        Self::charge_pivot_table_construction(
179            config,
180            &field_names,
181            source_rows.len(),
182            &mut output_budget,
183        )?;
184        self.charge_pivot_cache_construction(&field_names, &source_rows, &mut output_budget)?;
185        let (pcd, pcr, item_counts) = crate::pivot::build_pivot_cache_parts(
186            &config.source_sheet,
187            &config.source_range,
188            &field_names,
189            &source_rows,
190            cache_records_rid.clone(),
191        );
192        let pt_def = crate::pivot::build_pivot_table_xml_with_items(
193            config,
194            cache_id,
195            &field_names,
196            &item_counts,
197        )?;
198
199        let cache_rels = Relationships {
200            xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
201            relationships: vec![Relationship {
202                id: cache_records_rid,
203                rel_type: rel_types::PIVOT_CACHE_RECORDS.to_string(),
204                target: relative_relationship_target(&pcd_path, &pcr_path),
205                target_mode: None,
206            }],
207        };
208        let table_rels = Relationships {
209            xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
210            relationships: vec![Relationship {
211                id: "rId1".to_string(),
212                rel_type: rel_types::PIVOT_CACHE_DEF.to_string(),
213                target: relative_relationship_target(&pt_path, &pcd_path),
214                target_mode: None,
215            }],
216        };
217        let cache_rels_bytes = serialize_xml(&cache_rels)?.into_bytes();
218        let table_rels_bytes = serialize_xml(&table_rels)?.into_bytes();
219
220        charge_pivot_xml(&mut output_budget, &pcd)?;
221        charge_pivot_xml(&mut output_budget, &pcr)?;
222        charge_pivot_xml(&mut output_budget, &pt_def)?;
223        output_budget.charge_usize(cache_rels_bytes.len())?;
224        output_budget.charge_usize(table_rels_bytes.len())?;
225
226        let wb_rid = crate::sheet::next_rid(&self.workbook_rels.relationships);
227        let ws_rid = self.next_worksheet_rid(target_idx);
228        let ws_target = relative_relationship_target(&self.sheet_part_path(target_idx), &pt_path);
229
230        // All parsing, allocation, construction, and serialization has
231        // succeeded. Hydrate and commit the staged graph in one final phase.
232        self.hydrate_pivot_tables();
233        self.pivot_tables.push((pt_path.clone(), pt_def));
234        self.pivot_cache_defs.push((pcd_path.clone(), pcd));
235        self.pivot_cache_records.push((pcr_path.clone(), pcr));
236        self.raw_graph_parts
237            .insert(relationship_part_path(&pt_path), table_rels_bytes);
238        self.raw_graph_parts
239            .insert(relationship_part_path(&pcd_path), cache_rels_bytes);
240
241        self.content_types.overrides.push(ContentTypeOverride {
242            part_name: format!("/{}", pt_path),
243            content_type: mime_types::PIVOT_TABLE.to_string(),
244        });
245        self.content_types.overrides.push(ContentTypeOverride {
246            part_name: format!("/{}", pcd_path),
247            content_type: mime_types::PIVOT_CACHE_DEFINITION.to_string(),
248        });
249        self.content_types.overrides.push(ContentTypeOverride {
250            part_name: format!("/{}", pcr_path),
251            content_type: mime_types::PIVOT_CACHE_RECORDS.to_string(),
252        });
253
254        self.workbook_rels.relationships.push(Relationship {
255            id: wb_rid.clone(),
256            rel_type: rel_types::PIVOT_CACHE_DEF.to_string(),
257            target: relative_relationship_target("xl/workbook.xml", &pcd_path),
258            target_mode: None,
259        });
260
261        // Update workbook_xml.pivot_caches.
262        let pivot_caches = self
263            .workbook_xml
264            .pivot_caches
265            .get_or_insert_with(|| sheetkit_xml::workbook::PivotCaches { caches: vec![] });
266        pivot_caches
267            .caches
268            .push(sheetkit_xml::workbook::PivotCacheEntry {
269                cache_id,
270                r_id: wb_rid,
271            });
272
273        let ws_rels = self
274            .worksheet_rels
275            .entry(target_idx)
276            .or_insert_with(|| Relationships {
277                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
278                relationships: vec![],
279            });
280        ws_rels.relationships.push(Relationship {
281            id: ws_rid,
282            rel_type: rel_types::PIVOT_TABLE.to_string(),
283            target: ws_target,
284            target_mode: None,
285        });
286
287        Ok(())
288    }
289
290    /// Get information about all pivot tables in the workbook.
291    pub fn get_pivot_tables(&self) -> Vec<PivotTableInfo> {
292        use crate::workbook::aux::AuxCategory;
293
294        let mut pivot_tables = self.pivot_tables.clone();
295        if let Some(entries) = self.deferred_parts.entries(AuxCategory::PivotTables) {
296            for (path, bytes) in entries {
297                if pivot_tables.iter().any(|(existing, _)| existing == path) {
298                    continue;
299                }
300                let xml_str = String::from_utf8_lossy(bytes);
301                if let Ok(pt) = quick_xml::de::from_str::<
302                    sheetkit_xml::pivot_table::PivotTableDefinition,
303                >(&xml_str)
304                {
305                    pivot_tables.push((path.clone(), pt));
306                }
307            }
308        }
309
310        let mut pivot_cache_defs = self.pivot_cache_defs.clone();
311        if let Some(entries) = self.deferred_parts.entries(AuxCategory::PivotCaches) {
312            for (path, bytes) in entries {
313                if !path.contains("pivotCacheDefinition")
314                    || pivot_cache_defs
315                        .iter()
316                        .any(|(existing, _)| existing == path)
317                {
318                    continue;
319                }
320                let xml_str = String::from_utf8_lossy(bytes);
321                if let Ok(pcd) = quick_xml::de::from_str::<
322                    sheetkit_xml::pivot_cache::PivotCacheDefinition,
323                >(&xml_str)
324                {
325                    pivot_cache_defs.push((path.clone(), pcd));
326                }
327            }
328        }
329
330        pivot_tables
331            .iter()
332            .map(|(path, pt)| {
333                let cache_path = self.workbook_xml.pivot_caches.as_ref().and_then(|caches| {
334                    let entry = caches
335                        .caches
336                        .iter()
337                        .find(|entry| entry.cache_id == pt.cache_id)?;
338                    let relationship = self
339                        .workbook_rels
340                        .relationships
341                        .iter()
342                        .find(|relationship| relationship.id == entry.r_id)?;
343                    Some(resolve_relationship_target(
344                        "xl/workbook.xml",
345                        &relationship.target,
346                    ))
347                });
348                let (source_sheet, source_range) = cache_path
349                    .as_ref()
350                    .and_then(|cache_path| {
351                        pivot_cache_defs.iter().find(|(path, _)| path == cache_path)
352                    })
353                    .and_then(|(_, pcd)| {
354                        pcd.cache_source
355                            .worksheet_source
356                            .as_ref()
357                            .map(|ws| (ws.sheet.clone(), ws.reference.clone()))
358                    })
359                    .unwrap_or_default();
360
361                // Determine target sheet from the pivot table path.
362                let target_sheet = self
363                    .find_pivot_table_target_sheet_by_path(path)
364                    .unwrap_or_default();
365
366                PivotTableInfo {
367                    name: pt.name.clone(),
368                    source_sheet,
369                    source_range,
370                    target_sheet,
371                    location: pt.location.reference.clone(),
372                }
373            })
374            .collect()
375    }
376
377    /// Delete a pivot table by name.
378    pub fn delete_pivot_table(&mut self, name: &str) -> Result<()> {
379        self.hydrate_pivot_tables();
380        // Find the pivot table.
381        let pt_idx = self
382            .pivot_tables
383            .iter()
384            .position(|(_, pt)| pt.name == name)
385            .ok_or_else(|| Error::PivotTableNotFound {
386                name: name.to_string(),
387            })?;
388
389        let (pt_path, pt_def) = self.pivot_tables.remove(pt_idx);
390        let cache_id = pt_def.cache_id;
391        let pt_rels_path = relationship_part_path(&pt_path);
392        self.raw_graph_parts.remove(&pt_rels_path);
393        self.dirty_graph_parts.remove(&pt_rels_path);
394        self.unknown_parts.retain(|(path, _)| path != &pt_rels_path);
395
396        let cache_still_used = self
397            .pivot_tables
398            .iter()
399            .any(|(_, table)| table.cache_id == cache_id);
400
401        let mut wb_cache_rid = None;
402        if !cache_still_used {
403            if let Some(ref mut pivot_caches) = self.workbook_xml.pivot_caches {
404                if let Some(pos) = pivot_caches
405                    .caches
406                    .iter()
407                    .position(|e| e.cache_id == cache_id)
408                {
409                    wb_cache_rid = Some(pivot_caches.caches[pos].r_id.clone());
410                    pivot_caches.caches.remove(pos);
411                }
412                if pivot_caches.caches.is_empty() {
413                    self.workbook_xml.pivot_caches = None;
414                }
415            }
416        }
417
418        if let Some(ref rid) = wb_cache_rid {
419            let cache_path = self
420                .workbook_rels
421                .relationships
422                .iter()
423                .find(|r| r.id == *rid)
424                .map(|relationship| {
425                    resolve_relationship_target("xl/workbook.xml", &relationship.target)
426                });
427            if let Some(cache_path) = cache_path {
428                let cache_rels_path = relationship_part_path(&cache_path);
429                let relationship_bytes = self
430                    .raw_graph_parts
431                    .get(&cache_rels_path)
432                    .map(Vec::as_slice)
433                    .or_else(|| {
434                        self.unknown_parts
435                            .iter()
436                            .find(|(path, _)| path == &cache_rels_path)
437                            .map(|(_, bytes)| bytes.as_slice())
438                    });
439                let records_path = relationship_bytes
440                    .and_then(|bytes| quick_xml::de::from_reader::<_, Relationships>(bytes).ok())
441                    .and_then(|relationships| {
442                        relationships
443                            .relationships
444                            .into_iter()
445                            .find(|relationship| {
446                                relationship.rel_type == rel_types::PIVOT_CACHE_RECORDS
447                            })
448                    })
449                    .map(|relationship| {
450                        resolve_relationship_target(&cache_path, &relationship.target)
451                    });
452
453                self.pivot_cache_defs
454                    .retain(|(path, _)| path != &cache_path);
455                if let Some(records_path) = records_path {
456                    self.pivot_cache_records
457                        .retain(|(path, _)| path != &records_path);
458                }
459                self.raw_graph_parts.remove(&cache_rels_path);
460                self.dirty_graph_parts.remove(&cache_rels_path);
461                self.unknown_parts
462                    .retain(|(path, _)| path != &cache_rels_path);
463            }
464            self.workbook_rels.relationships.retain(|r| r.id != *rid);
465        }
466
467        // Remove content type overrides for the removed parts.
468        let pt_part = format!("/{}", pt_path);
469        self.content_types
470            .overrides
471            .retain(|o| o.part_name != pt_part);
472
473        // Also remove cache def and records content types if the paths were removed.
474        self.content_types.overrides.retain(|o| {
475            let p = o.part_name.trim_start_matches('/');
476            // Keep if it is still in our live lists.
477            if o.content_type == mime_types::PIVOT_CACHE_DEFINITION {
478                return self.pivot_cache_defs.iter().any(|(path, _)| path == p);
479            }
480            if o.content_type == mime_types::PIVOT_CACHE_RECORDS {
481                return self.pivot_cache_records.iter().any(|(path, _)| path == p);
482            }
483            if o.content_type == mime_types::PIVOT_TABLE {
484                return self.pivot_tables.iter().any(|(path, _)| path == p);
485            }
486            true
487        });
488
489        // Remove worksheet relationship for this pivot table.
490        for rels in self.worksheet_rels.values_mut() {
491            rels.relationships.retain(|r| {
492                if r.rel_type != rel_types::PIVOT_TABLE {
493                    return true;
494                }
495                // Check if the target matches the removed pivot table.
496                let full_target = format!(
497                    "xl/pivotTables/{}",
498                    r.target.trim_start_matches("../pivotTables/")
499                );
500                full_target != pt_path
501            });
502        }
503
504        Ok(())
505    }
506
507    /// Add a sparkline to a worksheet.
508    pub fn add_sparkline(
509        &mut self,
510        sheet: &str,
511        config: &crate::sparkline::SparklineConfig,
512    ) -> Result<()> {
513        let idx = self.sheet_index(sheet)?;
514        crate::sparkline::validate_sparkline_config(config)?;
515        self.hydrate_sparklines_for_sheet(idx);
516        while self.sheet_sparklines.len() <= idx {
517            self.sheet_sparklines.push(vec![]);
518            self.sheet_sparklines_hydrated.push(true);
519        }
520        self.sheet_sparklines[idx].push(config.clone());
521        self.mark_sheet_dirty(idx);
522        Ok(())
523    }
524
525    /// Get all sparklines for a worksheet.
526    pub fn get_sparklines(&self, sheet: &str) -> Result<Vec<crate::sparkline::SparklineConfig>> {
527        let idx = self.sheet_index(sheet)?;
528        Ok(self.sparklines_for_sheet(idx))
529    }
530
531    /// Remove a sparkline by its location cell reference.
532    pub fn remove_sparkline(&mut self, sheet: &str, location: &str) -> Result<()> {
533        let idx = self.sheet_index(sheet)?;
534        self.hydrate_sparklines_for_sheet(idx);
535        let sparklines = self
536            .sheet_sparklines
537            .get_mut(idx)
538            .ok_or_else(|| Error::Internal(format!("no sparkline data for sheet '{sheet}'")))?;
539        let pos = sparklines
540            .iter()
541            .position(|s| s.location == location)
542            .ok_or_else(|| {
543                Error::Internal(format!(
544                    "sparkline at location '{location}' not found on sheet '{sheet}'"
545                ))
546            })?;
547        sparklines.remove(pos);
548        self.mark_sheet_dirty(idx);
549        Ok(())
550    }
551
552    /// Return sparklines from typed data or a read-only parse of lazy sheet XML.
553    fn sparklines_for_sheet(&self, sheet_idx: usize) -> Vec<crate::sparkline::SparklineConfig> {
554        if self
555            .sheet_sparklines_hydrated
556            .get(sheet_idx)
557            .copied()
558            .unwrap_or(false)
559        {
560            return self
561                .sheet_sparklines
562                .get(sheet_idx)
563                .cloned()
564                .unwrap_or_default();
565        }
566        if let Some(bytes) = self.raw_sheet_xml.get(sheet_idx).and_then(Option::as_deref) {
567            return crate::workbook::io::parse_sparklines_from_xml(&String::from_utf8_lossy(bytes));
568        }
569        if let Some(bytes) = self
570            .raw_sheet_extensions
571            .get(sheet_idx)
572            .and_then(Option::as_deref)
573        {
574            return crate::workbook::io::parse_sparklines_from_xml(&String::from_utf8_lossy(bytes));
575        }
576        if self
577            .sheet_package_backed
578            .get(sheet_idx)
579            .copied()
580            .unwrap_or(false)
581        {
582            self.package_source
583                .as_ref()
584                .and_then(|source| {
585                    source
586                        .worksheet_extension_fragment(&self.sheet_part_path(sheet_idx))
587                        .ok()
588                        .flatten()
589                })
590                .map(|bytes| {
591                    crate::workbook::io::parse_sparklines_from_xml(&String::from_utf8_lossy(&bytes))
592                })
593                .unwrap_or_default()
594        } else {
595            Vec::new()
596        }
597    }
598
599    /// Materialize lazy sparkline data before mutating it.
600    pub(super) fn hydrate_sparklines_for_sheet(&mut self, sheet_idx: usize) {
601        if self
602            .sheet_sparklines_hydrated
603            .get(sheet_idx)
604            .copied()
605            .unwrap_or(false)
606        {
607            return;
608        }
609        while self.raw_sheet_extensions.len() <= sheet_idx {
610            self.raw_sheet_extensions.push(None);
611        }
612        if self
613            .raw_sheet_xml
614            .get(sheet_idx)
615            .and_then(Option::as_ref)
616            .is_none()
617            && self.raw_sheet_extensions[sheet_idx].is_none()
618        {
619            let extension = if self
620                .sheet_package_backed
621                .get(sheet_idx)
622                .copied()
623                .unwrap_or(false)
624            {
625                self.package_source.as_ref().and_then(|source| {
626                    source
627                        .worksheet_extension_fragment(&self.sheet_part_path(sheet_idx))
628                        .ok()
629                        .flatten()
630                })
631            } else {
632                None
633            };
634            self.raw_sheet_extensions[sheet_idx] = extension;
635        }
636        let sparklines = self.sparklines_for_sheet(sheet_idx);
637        while self.sheet_sparklines.len() <= sheet_idx {
638            self.sheet_sparklines.push(vec![]);
639            self.sheet_sparklines_hydrated.push(false);
640        }
641        self.sheet_sparklines[sheet_idx] = sparklines;
642        self.sheet_sparklines_hydrated[sheet_idx] = true;
643    }
644
645    /// Evaluate a single formula string in the context of `sheet`.
646    ///
647    /// A [`CellSnapshot`](crate::formula::eval::CellSnapshot) is built from the current workbook state so
648    /// that cell references within the formula can be resolved.
649    pub fn evaluate_formula(&self, sheet: &str, formula: &str) -> Result<CellValue> {
650        self.evaluate_formula_with_limits(
651            sheet,
652            formula,
653            crate::formula::budget::FormulaLimits::secure_default(),
654        )
655    }
656
657    /// Evaluates one formula with finite, validated resource limits.
658    pub fn evaluate_formula_with_limits(
659        &self,
660        sheet: &str,
661        formula: &str,
662        limits: crate::formula::budget::FormulaLimits,
663    ) -> Result<CellValue> {
664        // Validate the sheet exists.
665        let _ = self.sheet_index(sheet)?;
666        let budget = crate::formula::budget::FormulaBudget::for_calculation(limits)?;
667        let parsed = crate::formula::parser::parse_formula_with_budget(formula, &budget)?;
668        let snapshot = self.build_cell_snapshot(sheet)?;
669        let mut evaluator = crate::formula::eval::Evaluator::with_budget(&snapshot, budget);
670        evaluator.eval_expr(&parsed)
671    }
672
673    /// Recalculate every formula cell across all sheets and store the
674    /// computed result back into each cell. Uses a dependency graph and
675    /// topological sort so formulas are evaluated after their dependencies.
676    pub fn calculate_all(&mut self) -> Result<()> {
677        self.calculate_all_with_limits(crate::formula::budget::FormulaLimits::secure_default())
678    }
679
680    /// Recalculate all formulas with finite, validated resource limits.
681    pub fn calculate_all_with_limits(
682        &mut self,
683        limits: crate::formula::budget::FormulaLimits,
684    ) -> Result<()> {
685        use crate::formula::eval::{
686            build_dependency_graph_from_parsed_with_budget, topological_sort_with_budget, CellCoord,
687        };
688
689        let budget = crate::formula::budget::FormulaBudget::for_calculation(limits)?;
690
691        let sheet_names: Vec<String> = self.sheet_names().iter().map(|s| s.to_string()).collect();
692
693        // Parse as formulas are discovered so cumulative limits are enforced
694        // before retaining attacker-controlled formula collections.
695        let mut parsed_cells = Vec::new();
696        let mut results = Vec::new();
697        for (idx, sn) in sheet_names.iter().enumerate() {
698            self.ensure_hydrated(idx)?;
699            let ws = self.worksheets[idx].1.get().ok_or_else(|| {
700                Error::Internal("formula source sheet is not hydrated".to_string())
701            })?;
702            for row in &ws.sheet_data.rows {
703                for cell in &row.cells {
704                    if let Some(ref f) = cell.f {
705                        let formula_str = f.value.as_deref().unwrap_or_default();
706                        if !formula_str.is_empty() {
707                            let (c, r) = cell_name_to_coordinates(cell.r.as_str())?;
708                            let coord = CellCoord {
709                                sheet: sn.clone(),
710                                col: c,
711                                row: r,
712                            };
713                            match crate::formula::parser::parse_formula_with_budget(
714                                formula_str,
715                                &budget,
716                            ) {
717                                Ok(expr) => parsed_cells.push((coord, expr)),
718                                Err(error @ Error::ResourceLimitExceeded(_)) => return Err(error),
719                                Err(_) => {
720                                    budget.charge_output_bytes(7)?;
721                                    results.push((coord, CellValue::Error("#VALUE!".to_string())))
722                                }
723                            }
724                        }
725                    }
726                }
727            }
728        }
729
730        if parsed_cells.is_empty() && results.is_empty() {
731            return Ok(());
732        }
733
734        // Build the graph only from valid expressions. Invalid formulas are
735        // written to the progressive snapshot before dependent expressions run.
736        let mut parsed_coords = Vec::new();
737        parsed_coords
738            .try_reserve_exact(parsed_cells.len())
739            .map_err(|_| Error::Internal("formula coordinate allocation failed".to_string()))?;
740        parsed_coords.extend(parsed_cells.iter().map(|(coord, _)| coord.clone()));
741        let deps = build_dependency_graph_from_parsed_with_budget(&parsed_cells, &budget)?;
742        let eval_order = topological_sort_with_budget(&parsed_coords, &deps, &budget)?;
743
744        // Build a lookup from coord to its already-parsed formula expression.
745        let mut formula_map: HashMap<CellCoord, crate::formula::ast::Expr> = HashMap::new();
746        formula_map
747            .try_reserve(parsed_cells.len())
748            .map_err(|_| Error::Internal("formula lookup allocation failed".to_string()))?;
749        formula_map.extend(parsed_cells);
750
751        // Build a snapshot of all cell data.
752        let first_sheet = sheet_names.first().cloned().unwrap_or_default();
753        let mut snapshot = self.build_cell_snapshot(&first_sheet)?;
754
755        // Evaluate in dependency order, updating the snapshot progressively
756        // so later formulas see already-computed results.
757        for (coord, result) in &results {
758            snapshot.set_cell(&coord.sheet, coord.col, coord.row, result.clone());
759        }
760
761        for coord in &eval_order {
762            if let Some(parsed) = formula_map.get(coord) {
763                snapshot.set_current_sheet(&coord.sheet);
764                let mut evaluator =
765                    crate::formula::eval::Evaluator::with_budget(&snapshot, budget.clone());
766                evaluator.set_position(coord.col, coord.row);
767                let result = match evaluator.eval_expr(parsed) {
768                    Ok(result) => result,
769                    Err(error) => {
770                        let cached = formula_error_to_cached_value(&error).ok_or(error)?;
771                        let output_bytes = match &cached {
772                            CellValue::String(value) | CellValue::Error(value) => {
773                                value.len() as u64
774                            }
775                            _ => 0,
776                        };
777                        budget.charge_output_bytes(output_bytes)?;
778                        cached
779                    }
780                };
781                snapshot.set_cell(&coord.sheet, coord.col, coord.row, result.clone());
782                results.push((coord.clone(), result));
783            }
784        }
785
786        // Write results back directly to the XML cells, preserving the
787        // formula element and storing the computed value in the v/t fields.
788        let sheet_name_to_idx: HashMap<String, usize> = sheet_names
789            .iter()
790            .enumerate()
791            .map(|(idx, name)| (name.clone(), idx))
792            .collect();
793
794        for (coord, result) in results {
795            let cell_ref = crate::utils::cell_ref::coordinates_to_cell_name(coord.col, coord.row)?;
796            let sheet_idx = *sheet_name_to_idx.get(&coord.sheet).ok_or_else(|| {
797                Error::Internal(format!("formula result sheet '{}' is missing", coord.sheet))
798            })?;
799            let ws = self.worksheets[sheet_idx].1.get_mut().ok_or_else(|| {
800                Error::Internal(format!(
801                    "formula result sheet '{}' is not hydrated",
802                    coord.sheet
803                ))
804            })?;
805            let row = ws
806                .sheet_data
807                .rows
808                .iter_mut()
809                .find(|r| r.r == coord.row)
810                .ok_or_else(|| {
811                    Error::Internal(format!("formula result row {} is missing", coord.row))
812                })?;
813            let cell = row
814                .cells
815                .iter_mut()
816                .find(|c| c.r == *cell_ref)
817                .ok_or_else(|| {
818                    Error::Internal(format!("formula result cell {cell_ref} is missing"))
819                })?;
820            let (new_v, new_t) = match &result {
821                CellValue::Number(n) => (Some(n.to_string()), CellTypeTag::None),
822                CellValue::String(s) => (Some(s.clone()), CellTypeTag::FormulaString),
823                CellValue::Bool(b) => (
824                    Some(if *b { "1".to_string() } else { "0".to_string() }),
825                    CellTypeTag::Boolean,
826                ),
827                CellValue::Error(e) => (Some(e.clone()), CellTypeTag::Error),
828                CellValue::Date(n) => (Some(n.to_string()), CellTypeTag::None),
829                _ => continue,
830            };
831
832            let changed = cell.v != new_v || cell.t != new_t;
833            if changed {
834                cell.v = new_v;
835                cell.t = new_t;
836                self.mark_sheet_dirty(sheet_idx);
837            }
838        }
839
840        Ok(())
841    }
842
843    /// Build a [`CellSnapshot`] for formula evaluation, with the given
844    /// sheet as the current-sheet context.
845    fn build_cell_snapshot(
846        &self,
847        current_sheet: &str,
848    ) -> Result<crate::formula::eval::CellSnapshot> {
849        let mut snapshot = crate::formula::eval::CellSnapshot::new(current_sheet.to_string());
850        for (idx, (sn, _)) in self.worksheets.iter().enumerate() {
851            let ws = self.worksheet_ref_by_index(idx)?;
852            for row in &ws.sheet_data.rows {
853                for cell in &row.cells {
854                    if let Ok((c, r)) = cell_name_to_coordinates(cell.r.as_str()) {
855                        let cv = self.xml_cell_to_value(cell)?;
856                        snapshot.set_cell(sn, c, r, cv);
857                    }
858                }
859            }
860        }
861        Ok(snapshot)
862    }
863
864    /// Return `(col, row)` pairs for all occupied cells on the named sheet.
865    pub fn get_occupied_cells(&self, sheet: &str) -> Result<Vec<(u32, u32)>> {
866        let ws = self.worksheet_ref(sheet)?;
867        let mut cells = Vec::new();
868        for row in &ws.sheet_data.rows {
869            for cell in &row.cells {
870                if let Ok((c, r)) = cell_name_to_coordinates(cell.r.as_str()) {
871                    cells.push((c, r));
872                }
873            }
874        }
875        Ok(cells)
876    }
877
878    fn charge_pivot_config(
879        config: &PivotTableConfig,
880        budget: &mut PivotOutputBudget,
881    ) -> Result<()> {
882        use sheetkit_xml::pivot_table::{DataFieldDef, FieldRef};
883
884        for value in [
885            config.name.as_str(),
886            config.source_sheet.as_str(),
887            config.source_range.as_str(),
888            config.target_sheet.as_str(),
889            config.target_cell.as_str(),
890        ] {
891            budget.charge_usize(value.len())?;
892        }
893        for field in config.rows.iter().chain(&config.columns) {
894            budget.charge_usize(field.name.len())?;
895        }
896        for field in &config.data {
897            budget.charge_usize(field.name.len())?;
898            if let Some(display_name) = field.display_name.as_ref() {
899                budget.charge_usize(display_name.len())?;
900            } else {
901                budget.charge_usize(
902                    field
903                        .function
904                        .to_xml_str()
905                        .len()
906                        .saturating_add(" of ".len())
907                        .saturating_add(field.name.len()),
908                )?;
909            }
910            budget.charge_usize(field.function.to_xml_str().len())?;
911        }
912
913        budget.charge_array::<FieldRef>(config.rows.len().saturating_add(config.columns.len()))?;
914        budget.charge_array::<DataFieldDef>(config.data.len())?;
915        // The target is uppercased and then copied into the final location.
916        budget.charge_usize(
917            config
918                .target_cell
919                .len()
920                .saturating_mul(2)
921                .saturating_add(11),
922        )?;
923        Ok(())
924    }
925
926    fn charge_pivot_table_construction(
927        config: &PivotTableConfig,
928        field_names: &[String],
929        source_row_count: usize,
930        budget: &mut PivotOutputBudget,
931    ) -> Result<()> {
932        use sheetkit_xml::pivot_table::{FieldItem, PivotFieldDef};
933
934        budget.charge_array::<PivotFieldDef>(field_names.len())?;
935        for field_name in field_names {
936            let row_field = config.rows.iter().any(|field| field.name == *field_name);
937            let column_field = config.columns.iter().any(|field| field.name == *field_name);
938            if row_field || column_field {
939                budget.charge_array::<FieldItem>(source_row_count.saturating_add(1))?;
940                budget.charge_usize("default".len())?;
941                budget.charge_usize(if row_field {
942                    "axisRow".len()
943                } else {
944                    "axisCol".len()
945                })?;
946            }
947        }
948        Ok(())
949    }
950
951    fn pivot_cell_retained_bytes(&self, cell: &sheetkit_xml::worksheet::Cell) -> Result<usize> {
952        use sheetkit_xml::worksheet::CellTypeTag;
953
954        if let Some(formula) = cell.f.as_ref() {
955            let expression = formula.value.as_ref().map_or(0, String::len);
956            let cached = match cell.t {
957                CellTypeTag::Error | CellTypeTag::FormulaString => {
958                    cell.v.as_ref().map_or(0, String::len)
959                }
960                _ => 0,
961            };
962            let cached_value = if cell.v.is_some() {
963                std::mem::size_of::<CellValue>()
964            } else {
965                0
966            };
967            return Ok(expression
968                .saturating_add(cached)
969                .saturating_add(cached_value));
970        }
971
972        match cell.t {
973            CellTypeTag::SharedString => {
974                let Some(index) = cell.v.as_deref() else {
975                    return Ok(0);
976                };
977                let index = index
978                    .parse::<usize>()
979                    .map_err(|_| Error::Internal(format!("invalid SST index: {index}")))?;
980                self.sst_runtime
981                    .get(index)
982                    .map(str::len)
983                    .ok_or_else(|| Error::Internal(format!("SST index {index} out of bounds")))
984            }
985            CellTypeTag::InlineString => Ok(cell
986                .is
987                .as_ref()
988                .and_then(|inline| inline.t.as_ref())
989                .map_or(0, String::len)),
990            CellTypeTag::Error | CellTypeTag::FormulaString => {
991                Ok(cell.v.as_ref().map_or(0, String::len))
992            }
993            _ => Ok(0),
994        }
995    }
996
997    fn charge_pivot_cache_construction(
998        &self,
999        field_names: &[String],
1000        rows: &[Vec<CellValue>],
1001        budget: &mut PivotOutputBudget,
1002    ) -> Result<()> {
1003        use sheetkit_xml::pivot_cache::{CacheField, CacheRecord, IndexField, NumberField};
1004
1005        let cell_count = rows.iter().try_fold(0usize, |total, row| {
1006            total.checked_add(row.len()).ok_or_else(|| {
1007                Error::Internal("pivot source cell count overflowed usize".to_string())
1008            })
1009        })?;
1010        budget.charge_array::<Vec<CellValue>>(rows.len())?;
1011        budget.charge_array::<CellValue>(cell_count)?;
1012        budget.charge_array::<CacheField>(field_names.len())?;
1013        budget.charge_array::<Vec<u32>>(field_names.len())?;
1014        budget.charge_array::<u32>(field_names.len())?;
1015        budget.charge_array::<bool>(field_names.len())?;
1016        budget.charge_array::<u32>(cell_count)?;
1017        budget.charge_array::<(&str, u32)>(cell_count)?;
1018        budget.charge_array::<(u64, u32)>(cell_count)?;
1019        budget.charge_array::<CacheRecord>(rows.len())?;
1020        budget.charge_array::<IndexField>(cell_count)?;
1021        budget.charge_array::<NumberField>(cell_count)?;
1022
1023        for name in field_names {
1024            budget.charge_usize(name.len())?;
1025        }
1026        for value in rows.iter().flatten() {
1027            let string_bytes = pivot_cache_string_bytes(value);
1028            // CacheValue retains one copy. SharedItems may retain another;
1029            // charging every value is a conservative preflight that avoids
1030            // allocating an attacker-controlled deduplication set here.
1031            budget.charge_usize(string_bytes)?;
1032            budget.charge_usize(string_bytes)?;
1033        }
1034        Ok(())
1035    }
1036
1037    fn read_pivot_row(
1038        &self,
1039        worksheet: &sheetkit_xml::worksheet::WorksheetXml,
1040        row_number: u32,
1041        start_col: u32,
1042        end_col: u32,
1043        width: usize,
1044        output_budget: &mut PivotOutputBudget,
1045    ) -> Result<Vec<CellValue>> {
1046        let xml_row = worksheet
1047            .sheet_data
1048            .rows
1049            .binary_search_by_key(&row_number, |row| row.r)
1050            .ok()
1051            .map(|index| &worksheet.sheet_data.rows[index]);
1052        output_budget.charge_array::<CellValue>(width)?;
1053        let mut values = Vec::new();
1054        values
1055            .try_reserve_exact(width)
1056            .map_err(|_| Error::Internal("failed to allocate admitted pivot row".to_string()))?;
1057        for col in start_col..=end_col {
1058            let xml_cell = xml_row.and_then(|row| {
1059                row.cells
1060                    .binary_search_by_key(&col, |cell| cell.col)
1061                    .ok()
1062                    .map(|index| &row.cells[index])
1063            });
1064            let value = match xml_cell {
1065                Some(cell) => {
1066                    output_budget.charge_usize(self.pivot_cell_retained_bytes(cell)?)?;
1067                    self.xml_cell_to_value(cell)?
1068                }
1069                None => CellValue::Empty,
1070            };
1071            values.push(value);
1072        }
1073        Ok(values)
1074    }
1075
1076    fn read_pivot_source_with_limits(
1077        &self,
1078        sheet: &str,
1079        range: &str,
1080        limits: TraversalLimits,
1081        output_budget: &mut PivotOutputBudget,
1082    ) -> Result<(Vec<String>, Vec<Vec<CellValue>>)> {
1083        let (start, end) = range
1084            .split_once(':')
1085            .ok_or_else(|| Error::InvalidSourceRange(range.to_string()))?;
1086        let (start_col, start_row) = cell_name_to_coordinates(start)
1087            .map_err(|_| Error::InvalidSourceRange(range.to_string()))?;
1088        let (end_col, end_row) = cell_name_to_coordinates(end)
1089            .map_err(|_| Error::InvalidSourceRange(range.to_string()))?;
1090        if start_col > end_col || start_row > end_row {
1091            return Err(Error::InvalidSourceRange(range.to_string()));
1092        }
1093
1094        let rect = CheckedRect::new(start_row, end_row, start_col, end_col, limits)?;
1095        let width = usize::try_from(rect.column_count())
1096            .map_err(|_| Error::InvalidSourceRange(range.to_string()))?;
1097        let data_height = usize::try_from(rect.row_count().saturating_sub(1))
1098            .map_err(|_| Error::InvalidSourceRange(range.to_string()))?;
1099        let ws = self.worksheet_ref(sheet)?;
1100
1101        output_budget.charge_array::<String>(width)?;
1102        output_budget.charge_array::<Vec<CellValue>>(data_height)?;
1103
1104        let header_values =
1105            self.read_pivot_row(ws, start_row, start_col, end_col, width, output_budget)?;
1106        for value in &header_values {
1107            let allocated = match value {
1108                CellValue::Number(_) => 32,
1109                CellValue::Bool(value) => {
1110                    if *value {
1111                        4
1112                    } else {
1113                        5
1114                    }
1115                }
1116                CellValue::RichString(runs) => runs.iter().map(|run| run.text.len()).sum(),
1117                _ => 0,
1118            };
1119            output_budget.charge_usize(allocated)?;
1120        }
1121        let field_names = header_values
1122            .into_iter()
1123            .map(|value| match value {
1124                CellValue::String(value) => value,
1125                CellValue::Number(value) => value.to_string(),
1126                CellValue::Bool(value) => value.to_string(),
1127                CellValue::RichString(runs) => crate::rich_text::rich_text_to_plain(&runs),
1128                _ => String::new(),
1129            })
1130            .collect();
1131
1132        let mut rows = Vec::new();
1133        rows.try_reserve_exact(data_height)
1134            .map_err(|_| Error::Internal("failed to allocate admitted pivot rows".to_string()))?;
1135        for row in start_row.saturating_add(1)..=end_row {
1136            rows.push(self.read_pivot_row(ws, row, start_col, end_col, width, output_budget)?);
1137        }
1138        Ok((field_names, rows))
1139    }
1140
1141    /// Find the target sheet name for a pivot table by its part path.
1142    fn find_pivot_table_target_sheet_by_path(&self, pt_path: &str) -> Option<String> {
1143        // Find which worksheet has a relationship pointing to this pivot table.
1144        for (sheet_idx, rels) in &self.worksheet_rels {
1145            for r in &rels.relationships {
1146                if r.rel_type == rel_types::PIVOT_TABLE {
1147                    let full_target = format!(
1148                        "xl/pivotTables/{}",
1149                        r.target.trim_start_matches("../pivotTables/")
1150                    );
1151                    if full_target == pt_path {
1152                        return self
1153                            .worksheets
1154                            .get(*sheet_idx)
1155                            .map(|(name, _)| name.clone());
1156                    }
1157                }
1158            }
1159        }
1160        None
1161    }
1162
1163    /// Set the core document properties (title, author, etc.).
1164    pub fn set_doc_props(&mut self, props: crate::doc_props::DocProperties) {
1165        self.hydrate_doc_props();
1166        self.core_properties = Some(props.to_core_properties());
1167        self.mark_doc_prop_dirty("docProps/core.xml");
1168        self.ensure_doc_props_content_types();
1169    }
1170
1171    /// Get the core document properties.
1172    pub fn get_doc_props(&self) -> crate::doc_props::DocProperties {
1173        use crate::workbook::aux::AuxCategory;
1174
1175        if let Some(props) = self.core_properties.as_ref() {
1176            return crate::doc_props::DocProperties::from(props);
1177        }
1178
1179        self.deferred_parts
1180            .get_path(AuxCategory::DocProperties, "docProps/core.xml")
1181            .and_then(|bytes| {
1182                let xml_str = String::from_utf8_lossy(bytes);
1183                sheetkit_xml::doc_props::deserialize_core_properties(&xml_str).ok()
1184            })
1185            .as_ref()
1186            .map(crate::doc_props::DocProperties::from)
1187            .unwrap_or_default()
1188    }
1189
1190    /// Set the application properties (company, app version, etc.).
1191    pub fn set_app_props(&mut self, props: crate::doc_props::AppProperties) {
1192        self.hydrate_doc_props();
1193        self.app_properties = Some(props.to_extended_properties());
1194        self.mark_doc_prop_dirty("docProps/app.xml");
1195        self.ensure_doc_props_content_types();
1196    }
1197
1198    /// Get the application properties.
1199    pub fn get_app_props(&self) -> crate::doc_props::AppProperties {
1200        use crate::workbook::aux::AuxCategory;
1201
1202        if let Some(props) = self.app_properties.as_ref() {
1203            return crate::doc_props::AppProperties::from(props);
1204        }
1205
1206        self.deferred_parts
1207            .get_path(AuxCategory::DocProperties, "docProps/app.xml")
1208            .and_then(|bytes| {
1209                let xml_str = String::from_utf8_lossy(bytes);
1210                quick_xml::de::from_str::<sheetkit_xml::doc_props::ExtendedProperties>(&xml_str)
1211                    .ok()
1212            })
1213            .as_ref()
1214            .map(crate::doc_props::AppProperties::from)
1215            .unwrap_or_default()
1216    }
1217
1218    /// Set a custom property by name. If a property with the same name already
1219    /// exists, its value is replaced.
1220    ///
1221    /// A new property gets the lowest unused pid (>= 2). In the unreachable
1222    /// case that every pid is taken, the workbook is left unchanged.
1223    pub fn set_custom_property(
1224        &mut self,
1225        name: &str,
1226        value: crate::doc_props::CustomPropertyValue,
1227    ) {
1228        self.hydrate_doc_props();
1229        let props = self
1230            .custom_properties
1231            .get_or_insert_with(sheetkit_xml::doc_props::CustomProperties::default);
1232        // Exhaustion needs more than four billion properties; the signature
1233        // has no error channel, so skip the write rather than panic.
1234        if crate::doc_props::set_custom_property(props, name, value).is_err() {
1235            return;
1236        }
1237        self.mark_doc_prop_dirty("docProps/custom.xml");
1238        self.ensure_custom_props_content_types();
1239    }
1240
1241    /// Get a custom property value by name, or `None` if it does not exist.
1242    pub fn get_custom_property(&self, name: &str) -> Option<crate::doc_props::CustomPropertyValue> {
1243        use crate::workbook::aux::AuxCategory;
1244
1245        if let Some(props) = self.custom_properties.as_ref() {
1246            return crate::doc_props::find_custom_property(props, name);
1247        }
1248
1249        self.deferred_parts
1250            .get_path(AuxCategory::DocProperties, "docProps/custom.xml")
1251            .and_then(|bytes| {
1252                let xml_str = String::from_utf8_lossy(bytes);
1253                sheetkit_xml::doc_props::deserialize_custom_properties(&xml_str).ok()
1254            })
1255            .as_ref()
1256            .and_then(|props| crate::doc_props::find_custom_property(props, name))
1257    }
1258
1259    /// Remove a custom property by name. Returns `true` if a property was
1260    /// found and removed.
1261    pub fn delete_custom_property(&mut self, name: &str) -> bool {
1262        self.hydrate_doc_props();
1263        if let Some(ref mut props) = self.custom_properties {
1264            let deleted = crate::doc_props::delete_custom_property(props, name);
1265            if deleted {
1266                self.mark_doc_prop_dirty("docProps/custom.xml");
1267            }
1268            deleted
1269        } else {
1270            false
1271        }
1272    }
1273
1274    /// Ensure content types contains entries for core and extended properties.
1275    fn ensure_doc_props_content_types(&mut self) {
1276        let core_part = "/docProps/core.xml";
1277        let app_part = "/docProps/app.xml";
1278
1279        let has_core = self
1280            .content_types
1281            .overrides
1282            .iter()
1283            .any(|o| o.part_name == core_part);
1284        if !has_core {
1285            self.content_types.overrides.push(ContentTypeOverride {
1286                part_name: core_part.to_string(),
1287                content_type: mime_types::CORE_PROPERTIES.to_string(),
1288            });
1289        }
1290
1291        let has_app = self
1292            .content_types
1293            .overrides
1294            .iter()
1295            .any(|o| o.part_name == app_part);
1296        if !has_app {
1297            self.content_types.overrides.push(ContentTypeOverride {
1298                part_name: app_part.to_string(),
1299                content_type: mime_types::EXTENDED_PROPERTIES.to_string(),
1300            });
1301        }
1302    }
1303
1304    /// Ensure content types and package rels contain entries for custom properties.
1305    fn ensure_custom_props_content_types(&mut self) {
1306        self.ensure_doc_props_content_types();
1307
1308        let custom_part = "/docProps/custom.xml";
1309        let has_custom = self
1310            .content_types
1311            .overrides
1312            .iter()
1313            .any(|o| o.part_name == custom_part);
1314        if !has_custom {
1315            self.content_types.overrides.push(ContentTypeOverride {
1316                part_name: custom_part.to_string(),
1317                content_type: mime_types::CUSTOM_PROPERTIES.to_string(),
1318            });
1319        }
1320
1321        let has_custom_rel = self
1322            .package_rels
1323            .relationships
1324            .iter()
1325            .any(|r| r.rel_type == rel_types::CUSTOM_PROPERTIES);
1326        if !has_custom_rel {
1327            let rid = crate::sheet::next_rid(&self.package_rels.relationships);
1328            self.package_rels.relationships.push(Relationship {
1329                id: rid,
1330                rel_type: rel_types::CUSTOM_PROPERTIES.to_string(),
1331                target: "docProps/custom.xml".to_string(),
1332                target_mode: None,
1333            });
1334        }
1335    }
1336
1337    /// Look up a table by name across all sheets. Returns a reference to the
1338    /// table XML, path, and sheet index from the main table storage.
1339    fn find_table_by_name(
1340        &self,
1341        name: &str,
1342    ) -> Option<(&String, &sheetkit_xml::table::TableXml, usize)> {
1343        self.tables
1344            .iter()
1345            .find(|(_, t, _)| t.name == name)
1346            .map(|(path, t, idx)| (path, t, *idx))
1347    }
1348
1349    /// Add a slicer to a sheet targeting a table column.
1350    ///
1351    /// Creates the slicer definition, slicer cache, content type overrides,
1352    /// and worksheet relationships needed for Excel to render the slicer.
1353    pub fn add_slicer(&mut self, sheet: &str, config: &crate::slicer::SlicerConfig) -> Result<()> {
1354        use sheetkit_xml::content_types::ContentTypeOverride;
1355        use sheetkit_xml::slicer::{
1356            SlicerCacheDefinition, SlicerDefinition, SlicerDefinitions, TableSlicerCache,
1357        };
1358
1359        self.hydrate_slicers();
1360        self.hydrate_tables();
1361        crate::slicer::validate_slicer_config(config)?;
1362
1363        let sheet_idx = self.sheet_index(sheet)?;
1364
1365        // Check for duplicate name across all slicer definitions.
1366        for (_, sd) in &self.slicer_defs {
1367            for s in &sd.slicers {
1368                if s.name == config.name {
1369                    return Err(Error::SlicerAlreadyExists {
1370                        name: config.name.clone(),
1371                    });
1372                }
1373            }
1374        }
1375
1376        let cache_name = crate::slicer::slicer_cache_name(&config.name);
1377        if self
1378            .workbook_xml
1379            .defined_names
1380            .as_ref()
1381            .is_some_and(|names| {
1382                names
1383                    .defined_names
1384                    .iter()
1385                    .any(|defined| defined.name.eq_ignore_ascii_case(&cache_name))
1386            })
1387        {
1388            return Err(Error::InvalidArgument(format!(
1389                "slicer cache name already exists: {cache_name}"
1390            )));
1391        }
1392        let caption = config
1393            .caption
1394            .clone()
1395            .unwrap_or_else(|| config.column_name.clone());
1396
1397        // Allocate package paths from the complete occupied graph, not vector
1398        // lengths; reopened workbooks commonly have sparse part numbers.
1399        let slicer_path = self.next_available_part_path("xl/slicers/slicer", ".xml");
1400        let cache_path = self.next_available_part_path("xl/slicerCaches/slicerCache", ".xml");
1401
1402        // Build the slicer definition.
1403        let slicer_def = SlicerDefinition {
1404            name: config.name.clone(),
1405            cache: cache_name.clone(),
1406            caption: Some(caption),
1407            start_item: None,
1408            column_count: config.column_count,
1409            show_caption: config.show_caption,
1410            style: config.style.clone(),
1411            locked_position: None,
1412            row_height: crate::slicer::DEFAULT_ROW_HEIGHT_EMU,
1413        };
1414
1415        let slicer_defs = SlicerDefinitions {
1416            xmlns: sheetkit_xml::namespaces::SLICER_2009.to_string(),
1417            xmlns_mc: Some(sheetkit_xml::namespaces::MC.to_string()),
1418            slicers: vec![slicer_def],
1419        };
1420
1421        // Look up the actual table by name and validate it exists on this sheet.
1422        let (_path, table_xml, table_sheet_idx) = self
1423            .find_table_by_name(&config.table_name)
1424            .ok_or_else(|| Error::TableNotFound {
1425                name: config.table_name.clone(),
1426            })?;
1427
1428        // The placement sheet may differ from the table's owner sheet.
1429        let _ = table_sheet_idx;
1430
1431        // CT_TableSlicerCache uses tableColumn@id, not its vector position.
1432        let column = table_xml
1433            .table_columns
1434            .columns
1435            .iter()
1436            .find(|c| c.name == config.column_name)
1437            .ok_or_else(|| Error::TableColumnNotFound {
1438                table: config.table_name.clone(),
1439                column: config.column_name.clone(),
1440            })?;
1441
1442        let real_table_id = table_xml.id;
1443        let real_column = column.id;
1444
1445        // Build the slicer cache definition with real table metadata.
1446        let slicer_cache = SlicerCacheDefinition {
1447            name: cache_name.clone(),
1448            source_name: config.column_name.clone(),
1449            table_slicer_cache: Some(TableSlicerCache {
1450                table_id: real_table_id,
1451                column: real_column,
1452            }),
1453        };
1454
1455        // Prove the anchor can be allocated before committing package state.
1456        self.validate_slicer_anchor(sheet_idx, &config.cell)?;
1457        crate::defined_names::set_defined_name(
1458            &mut self.workbook_xml,
1459            &cache_name,
1460            "#N/A",
1461            crate::defined_names::DefinedNameScope::Workbook,
1462            None,
1463        )?;
1464
1465        // Store parts after all fallible validation has completed.
1466        self.slicer_defs.push((slicer_path.clone(), slicer_defs));
1467        self.slicer_caches.push((cache_path.clone(), slicer_cache));
1468
1469        // Add content type overrides.
1470        for (path, content_type) in [
1471            (&slicer_path, mime_types::SLICER),
1472            (&cache_path, mime_types::SLICER_CACHE),
1473        ] {
1474            if !self
1475                .content_types
1476                .overrides
1477                .iter()
1478                .any(|entry| entry.part_name == format!("/{path}"))
1479            {
1480                self.content_types.overrides.push(ContentTypeOverride {
1481                    part_name: format!("/{path}"),
1482                    content_type: content_type.to_string(),
1483                });
1484            }
1485        }
1486
1487        // Add workbook relationship for slicer cache.
1488        let wb_rid = crate::sheet::next_rid(&self.workbook_rels.relationships);
1489        self.workbook_rels.relationships.push(Relationship {
1490            id: wb_rid,
1491            rel_type: rel_types::SLICER_CACHE.to_string(),
1492            target: crate::workbook_paths::relative_relationship_target(
1493                "xl/workbook.xml",
1494                &cache_path,
1495            ),
1496            target_mode: None,
1497        });
1498
1499        // Add worksheet relationship for slicer part.
1500        let ws_rid = self.next_worksheet_rid(sheet_idx);
1501        let sheet_path = self.sheet_part_path(sheet_idx);
1502        let slicer_target =
1503            crate::workbook_paths::relative_relationship_target(&sheet_path, &slicer_path);
1504        let ws_rels = self
1505            .worksheet_rels
1506            .entry(sheet_idx)
1507            .or_insert_with(|| Relationships {
1508                xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
1509                relationships: vec![],
1510            });
1511        ws_rels.relationships.push(Relationship {
1512            id: ws_rid,
1513            rel_type: rel_types::SLICER.to_string(),
1514            target: slicer_target,
1515            target_mode: None,
1516        });
1517
1518        self.add_slicer_anchor(
1519            sheet_idx,
1520            &config.cell,
1521            config.width.unwrap_or(crate::slicer::DEFAULT_WIDTH_PX),
1522            config.height.unwrap_or(crate::slicer::DEFAULT_HEIGHT_PX),
1523            &config.name,
1524            &config
1525                .caption
1526                .clone()
1527                .unwrap_or_else(|| config.column_name.clone()),
1528        )?;
1529
1530        Ok(())
1531    }
1532
1533    /// Get information about all slicers on a sheet.
1534    pub fn get_slicers(&self, sheet: &str) -> Result<Vec<crate::slicer::SlicerInfo>> {
1535        use crate::workbook::aux::AuxCategory;
1536
1537        let sheet_idx = self.sheet_index(sheet)?;
1538        let mut result = Vec::new();
1539        let mut slicer_defs = self.slicer_defs.clone();
1540        let mut slicer_caches = self.slicer_caches.clone();
1541        let mut tables = self.tables.clone();
1542
1543        if let Some(entries) = self.deferred_parts.entries(AuxCategory::Slicers) {
1544            for (path, bytes) in entries {
1545                if slicer_defs.iter().any(|(existing, _)| existing == path) {
1546                    continue;
1547                }
1548                let xml_str = String::from_utf8_lossy(bytes);
1549                if let Ok(sd) =
1550                    quick_xml::de::from_str::<sheetkit_xml::slicer::SlicerDefinitions>(&xml_str)
1551                {
1552                    slicer_defs.push((path.clone(), sd));
1553                }
1554            }
1555        }
1556
1557        if let Some(entries) = self.deferred_parts.entries(AuxCategory::SlicerCaches) {
1558            for (path, bytes) in entries {
1559                if slicer_caches.iter().any(|(existing, _)| existing == path) {
1560                    continue;
1561                }
1562                let xml_str = String::from_utf8_lossy(bytes);
1563                if let Some(cache) = sheetkit_xml::slicer::parse_slicer_cache(&xml_str) {
1564                    slicer_caches.push((path.clone(), cache));
1565                }
1566            }
1567        }
1568
1569        let resolve_table_sheet_idx = |table_path: &str| -> usize {
1570            for (idx, rels) in &self.worksheet_rels {
1571                for rel in &rels.relationships {
1572                    if rel.rel_type != rel_types::TABLE {
1573                        continue;
1574                    }
1575                    let resolved = crate::workbook_paths::resolve_relationship_target(
1576                        &self.sheet_part_path(*idx),
1577                        &rel.target,
1578                    );
1579                    if resolved == table_path {
1580                        return *idx;
1581                    }
1582                }
1583            }
1584            0
1585        };
1586
1587        if let Some(entries) = self.deferred_parts.entries(AuxCategory::Tables) {
1588            for (path, bytes) in entries {
1589                if tables.iter().any(|(existing, _, _)| existing == path) {
1590                    continue;
1591                }
1592                let xml_str = String::from_utf8_lossy(bytes);
1593                if let Ok(table_xml) =
1594                    quick_xml::de::from_str::<sheetkit_xml::table::TableXml>(&xml_str)
1595                {
1596                    let table_sheet_idx = resolve_table_sheet_idx(path);
1597                    tables.push((path.clone(), table_xml, table_sheet_idx));
1598                }
1599            }
1600        }
1601
1602        // Find slicer parts referenced by this sheet's relationships.
1603        let empty_rels = Relationships {
1604            xmlns: sheetkit_xml::namespaces::PACKAGE_RELATIONSHIPS.to_string(),
1605            relationships: vec![],
1606        };
1607        let rels = self.worksheet_rels.get(&sheet_idx).unwrap_or(&empty_rels);
1608
1609        let slicer_targets: Vec<String> = rels
1610            .relationships
1611            .iter()
1612            .filter(|r| r.rel_type == rel_types::SLICER)
1613            .map(|r| {
1614                let sheet_path = self.sheet_part_path(sheet_idx);
1615                crate::workbook_paths::resolve_relationship_target(&sheet_path, &r.target)
1616            })
1617            .collect();
1618
1619        for (path, sd) in &slicer_defs {
1620            if !slicer_targets.contains(path) {
1621                continue;
1622            }
1623            for slicer in &sd.slicers {
1624                // Find the matching cache to get source info.
1625                let cache = slicer_caches.iter().find(|(_, sc)| sc.name == slicer.cache);
1626
1627                let (table_name, column_name) = if let Some((_, sc)) = cache {
1628                    let tname = sc
1629                        .table_slicer_cache
1630                        .as_ref()
1631                        .and_then(|tsc| {
1632                            tables
1633                                .iter()
1634                                .find(|(_, t, _)| t.id == tsc.table_id)
1635                                .map(|(_, t, _)| t.name.clone())
1636                        })
1637                        .unwrap_or_default();
1638                    let cname = sc
1639                        .table_slicer_cache
1640                        .as_ref()
1641                        .and_then(|tsc| {
1642                            tables
1643                                .iter()
1644                                .find(|(_, t, _)| t.id == tsc.table_id)
1645                                .and_then(|(_, t, _)| {
1646                                    t.table_columns
1647                                        .columns
1648                                        .iter()
1649                                        .find(|column| column.id == tsc.column)
1650                                })
1651                                .map(|c| c.name.clone())
1652                        })
1653                        .unwrap_or_else(|| sc.source_name.clone());
1654                    (tname, cname)
1655                } else {
1656                    (String::new(), String::new())
1657                };
1658
1659                result.push(crate::slicer::SlicerInfo {
1660                    name: slicer.name.clone(),
1661                    caption: slicer
1662                        .caption
1663                        .clone()
1664                        .unwrap_or_else(|| slicer.name.clone()),
1665                    table_name,
1666                    column_name,
1667                    style: slicer.style.clone(),
1668                });
1669            }
1670        }
1671
1672        Ok(result)
1673    }
1674
1675    /// Delete a slicer by name from a sheet.
1676    ///
1677    /// Removes the slicer definition, cache, content types, and relationships.
1678    pub fn delete_slicer(&mut self, sheet: &str, name: &str) -> Result<()> {
1679        self.hydrate_slicers();
1680        let sheet_idx = self.sheet_index(sheet)?;
1681        let sheet_path = self.sheet_part_path(sheet_idx);
1682        let slicer_targets: Vec<String> = self
1683            .worksheet_rels
1684            .get(&sheet_idx)
1685            .into_iter()
1686            .flat_map(|relationships| &relationships.relationships)
1687            .filter(|relationship| relationship.rel_type == rel_types::SLICER)
1688            .map(|relationship| {
1689                crate::workbook_paths::resolve_relationship_target(
1690                    &sheet_path,
1691                    &relationship.target,
1692                )
1693            })
1694            .collect();
1695
1696        let sd_idx = self
1697            .slicer_defs
1698            .iter()
1699            .position(|(path, definitions)| {
1700                slicer_targets.contains(path)
1701                    && definitions.slicers.iter().any(|slicer| slicer.name == name)
1702            })
1703            .ok_or_else(|| Error::SlicerNotFound {
1704                name: name.to_string(),
1705            })?;
1706
1707        self.ensure_owned_drawing_hydratable(sheet_idx)?;
1708        self.hydrate_drawings();
1709        self.ensure_owned_drawing_parsed(sheet_idx)?;
1710        self.ensure_hydrated(sheet_idx)?;
1711
1712        let (sd_path, sd) = &self.slicer_defs[sd_idx];
1713
1714        // Find the cache name linked to this slicer.
1715        let cache_name = sd
1716            .slicers
1717            .iter()
1718            .find(|s| s.name == name)
1719            .map(|s| s.cache.clone())
1720            .unwrap_or_default();
1721
1722        // If this is the only slicer in this definitions part, remove the whole part.
1723        let remove_whole_part = sd.slicers.len() == 1;
1724
1725        if remove_whole_part {
1726            let sd_path_clone = sd_path.clone();
1727            self.slicer_defs.remove(sd_idx);
1728
1729            // Remove content type override.
1730            let sd_part = format!("/{}", sd_path_clone);
1731            self.content_types
1732                .overrides
1733                .retain(|o| o.part_name != sd_part);
1734
1735            // Remove worksheet relationship pointing to this slicer part.
1736            if let Some(rels) = self.worksheet_rels.get_mut(&sheet_idx) {
1737                rels.relationships.retain(|r| {
1738                    if r.rel_type != rel_types::SLICER {
1739                        return true;
1740                    }
1741                    let target =
1742                        crate::workbook_paths::resolve_relationship_target(&sheet_path, &r.target);
1743                    target != sd_path_clone
1744                });
1745            }
1746        } else {
1747            // Remove just this slicer from the definitions.
1748            self.slicer_defs[sd_idx]
1749                .1
1750                .slicers
1751                .retain(|s| s.name != name);
1752        }
1753
1754        let cache_is_still_used = self.slicer_defs.iter().any(|(_, definitions)| {
1755            definitions
1756                .slicers
1757                .iter()
1758                .any(|slicer| slicer.cache == cache_name)
1759        });
1760
1761        // Remove the matching slicer cache after its final view is removed.
1762        if !cache_name.is_empty() && !cache_is_still_used {
1763            if let Some(sc_idx) = self
1764                .slicer_caches
1765                .iter()
1766                .position(|(_, sc)| sc.name == cache_name)
1767            {
1768                let (sc_path, _) = self.slicer_caches.remove(sc_idx);
1769                let sc_part = format!("/{}", sc_path);
1770                self.content_types
1771                    .overrides
1772                    .retain(|o| o.part_name != sc_part);
1773
1774                // Remove workbook relationship for this cache.
1775                self.workbook_rels.relationships.retain(|r| {
1776                    if r.rel_type != rel_types::SLICER_CACHE {
1777                        return true;
1778                    }
1779                    crate::workbook_paths::resolve_relationship_target("xl/workbook.xml", &r.target)
1780                        != sc_path
1781                });
1782            }
1783            if let Some(defined_names) = self.workbook_xml.defined_names.as_mut() {
1784                defined_names
1785                    .defined_names
1786                    .retain(|defined| !defined.name.eq_ignore_ascii_case(&cache_name));
1787                if defined_names.defined_names.is_empty() {
1788                    self.workbook_xml.defined_names = None;
1789                }
1790            }
1791        }
1792
1793        // Remove the visible one-cell slicer anchor from the owning drawing.
1794        let mut empty_drawing = None;
1795        if let Some(&drawing_idx) = self.worksheet_drawings.get(&sheet_idx) {
1796            let mut anchor_removed = false;
1797            let mut anchors_empty = false;
1798            if let Some((_, drawing)) = self.drawings.get_mut(drawing_idx) {
1799                let before = drawing.one_cell_anchors.len();
1800                drawing.one_cell_anchors.retain(|anchor| {
1801                    anchor.alternate_content.as_ref().is_none_or(|content| {
1802                        content
1803                            .choice
1804                            .graphic_frame
1805                            .graphic
1806                            .graphic_data
1807                            .slicer
1808                            .name
1809                            != name
1810                    })
1811                });
1812                anchor_removed = drawing.one_cell_anchors.len() != before;
1813                anchors_empty =
1814                    drawing.one_cell_anchors.is_empty() && drawing.two_cell_anchors.is_empty();
1815            }
1816            if anchor_removed {
1817                self.mark_drawing_dirty(drawing_idx);
1818            }
1819            if anchors_empty
1820                && self
1821                    .drawing_rels
1822                    .get(&drawing_idx)
1823                    .is_none_or(|relationships| relationships.relationships.is_empty())
1824            {
1825                empty_drawing = Some(drawing_idx);
1826            }
1827        }
1828        if let Some(drawing_idx) = empty_drawing {
1829            self.remove_empty_drawing(sheet_idx, drawing_idx);
1830        }
1831        self.mark_sheet_dirty(sheet_idx);
1832
1833        Ok(())
1834    }
1835
1836    fn remove_empty_drawing(&mut self, sheet_idx: usize, drawing_idx: usize) {
1837        let last_idx = self.drawings.len() - 1;
1838        let (drawing_path, _) = self.drawings.swap_remove(drawing_idx);
1839        let relationships_path = relationship_part_path(&drawing_path);
1840        self.drawing_rels.remove(&drawing_idx);
1841        self.remove_graph_part(&drawing_path);
1842        self.remove_graph_part(&relationships_path);
1843        self.worksheet_drawings.remove(&sheet_idx);
1844
1845        if drawing_idx != last_idx {
1846            if let Some(relationships) = self.drawing_rels.remove(&last_idx) {
1847                self.drawing_rels.insert(drawing_idx, relationships);
1848            }
1849            for existing_idx in self.worksheet_drawings.values_mut() {
1850                if *existing_idx == last_idx {
1851                    *existing_idx = drawing_idx;
1852                }
1853            }
1854        }
1855
1856        self.content_types
1857            .overrides
1858            .retain(|override_| override_.part_name != format!("/{drawing_path}"));
1859        let sheet_path = self.sheet_part_path(sheet_idx);
1860        if let Some(relationships) = self.worksheet_rels.get_mut(&sheet_idx) {
1861            relationships.relationships.retain(|relationship| {
1862                if relationship.rel_type != rel_types::DRAWING {
1863                    return true;
1864                }
1865                crate::workbook_paths::resolve_relationship_target(
1866                    &sheet_path,
1867                    &relationship.target,
1868                ) != drawing_path
1869            });
1870        }
1871        if let Some(worksheet) = self.worksheets[sheet_idx].1.get_mut() {
1872            worksheet.drawing = None;
1873        }
1874    }
1875}
1876
1877fn formula_error_to_cached_value(error: &Error) -> Option<CellValue> {
1878    match error {
1879        Error::UnknownFunction { .. } => Some(CellValue::Error("#NAME?".to_string())),
1880        Error::WrongArgCount { .. } => Some(CellValue::Error("#VALUE!".to_string())),
1881        Error::FormulaError(message) => {
1882            let code = match message.as_str() {
1883                "#DIV/0!" | "#N/A" | "#NAME?" | "#NULL!" | "#NUM!" | "#REF!" | "#VALUE!" => {
1884                    message.as_str()
1885                }
1886                _ => "#VALUE!",
1887            };
1888            Some(CellValue::Error(code.to_string()))
1889        }
1890        _ => None,
1891    }
1892}
1893
1894#[cfg(test)]
1895mod tests {
1896    use super::*;
1897    use crate::workbook::open_options::{AuxParts, OpenOptions, ReadMode};
1898    use tempfile::TempDir;
1899
1900    fn make_pivot_workbook() -> Workbook {
1901        let mut wb = Workbook::new();
1902        wb.set_cell_value("Sheet1", "A1", "Name").unwrap();
1903        wb.set_cell_value("Sheet1", "B1", "Region").unwrap();
1904        wb.set_cell_value("Sheet1", "C1", "Sales").unwrap();
1905        wb.set_cell_value("Sheet1", "A2", "Alice").unwrap();
1906        wb.set_cell_value("Sheet1", "B2", "North").unwrap();
1907        wb.set_cell_value("Sheet1", "C2", 100.0).unwrap();
1908        wb.set_cell_value("Sheet1", "A3", "Bob").unwrap();
1909        wb.set_cell_value("Sheet1", "B3", "South").unwrap();
1910        wb.set_cell_value("Sheet1", "C3", 200.0).unwrap();
1911        wb.set_cell_value("Sheet1", "A4", "Carol").unwrap();
1912        wb.set_cell_value("Sheet1", "B4", "North").unwrap();
1913        wb.set_cell_value("Sheet1", "C4", 150.0).unwrap();
1914        wb
1915    }
1916
1917    fn basic_pivot_config() -> PivotTableConfig {
1918        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
1919        PivotTableConfig {
1920            name: "PivotTable1".to_string(),
1921            source_sheet: "Sheet1".to_string(),
1922            source_range: "A1:C4".to_string(),
1923            target_sheet: "Sheet1".to_string(),
1924            target_cell: "E1".to_string(),
1925            rows: vec![PivotField {
1926                name: "Name".to_string(),
1927            }],
1928            columns: vec![],
1929            data: vec![PivotDataField {
1930                name: "Sales".to_string(),
1931                function: AggregateFunction::Sum,
1932                display_name: None,
1933            }],
1934        }
1935    }
1936
1937    #[test]
1938    fn test_add_pivot_table_basic() {
1939        let mut wb = make_pivot_workbook();
1940        let config = basic_pivot_config();
1941        wb.add_pivot_table(&config).unwrap();
1942
1943        assert_eq!(wb.pivot_tables.len(), 1);
1944        assert_eq!(wb.pivot_cache_defs.len(), 1);
1945        assert_eq!(wb.pivot_cache_records.len(), 1);
1946        assert_eq!(wb.pivot_tables[0].1.name, "PivotTable1");
1947        assert_eq!(wb.pivot_tables[0].1.cache_id, 0);
1948    }
1949
1950    #[test]
1951    fn test_add_pivot_table_with_columns() {
1952        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
1953        let mut wb = make_pivot_workbook();
1954        let config = PivotTableConfig {
1955            name: "PT2".to_string(),
1956            source_sheet: "Sheet1".to_string(),
1957            source_range: "A1:C4".to_string(),
1958            target_sheet: "Sheet1".to_string(),
1959            target_cell: "E1".to_string(),
1960            rows: vec![PivotField {
1961                name: "Name".to_string(),
1962            }],
1963            columns: vec![PivotField {
1964                name: "Region".to_string(),
1965            }],
1966            data: vec![PivotDataField {
1967                name: "Sales".to_string(),
1968                function: AggregateFunction::Average,
1969                display_name: Some("Avg Sales".to_string()),
1970            }],
1971        };
1972        wb.add_pivot_table(&config).unwrap();
1973
1974        let pt = &wb.pivot_tables[0].1;
1975        assert!(pt.row_fields.is_some());
1976        assert!(pt.col_fields.is_some());
1977        assert!(pt.data_fields.is_some());
1978    }
1979
1980    #[test]
1981    fn test_add_pivot_table_source_sheet_not_found() {
1982        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
1983        let mut wb = Workbook::new();
1984        let config = PivotTableConfig {
1985            name: "PT".to_string(),
1986            source_sheet: "NonExistent".to_string(),
1987            source_range: "A1:B2".to_string(),
1988            target_sheet: "Sheet1".to_string(),
1989            target_cell: "A1".to_string(),
1990            rows: vec![PivotField {
1991                name: "Col1".to_string(),
1992            }],
1993            columns: vec![],
1994            data: vec![PivotDataField {
1995                name: "Col2".to_string(),
1996                function: AggregateFunction::Sum,
1997                display_name: None,
1998            }],
1999        };
2000        let result = wb.add_pivot_table(&config);
2001        assert!(result.is_err());
2002        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2003    }
2004
2005    #[test]
2006    fn test_add_pivot_table_target_sheet_not_found() {
2007        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2008        let mut wb = make_pivot_workbook();
2009        let config = PivotTableConfig {
2010            name: "PT".to_string(),
2011            source_sheet: "Sheet1".to_string(),
2012            source_range: "A1:C4".to_string(),
2013            target_sheet: "Report".to_string(),
2014            target_cell: "A1".to_string(),
2015            rows: vec![PivotField {
2016                name: "Name".to_string(),
2017            }],
2018            columns: vec![],
2019            data: vec![PivotDataField {
2020                name: "Sales".to_string(),
2021                function: AggregateFunction::Sum,
2022                display_name: None,
2023            }],
2024        };
2025        let result = wb.add_pivot_table(&config);
2026        assert!(result.is_err());
2027        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
2028    }
2029
2030    #[test]
2031    fn test_add_pivot_table_duplicate_name() {
2032        let mut wb = make_pivot_workbook();
2033        let config = basic_pivot_config();
2034        wb.add_pivot_table(&config).unwrap();
2035
2036        let result = wb.add_pivot_table(&config);
2037        assert!(result.is_err());
2038        assert!(matches!(
2039            result.unwrap_err(),
2040            Error::PivotTableAlreadyExists { .. }
2041        ));
2042    }
2043
2044    #[test]
2045    fn test_get_pivot_tables_empty() {
2046        let wb = Workbook::new();
2047        let pts = wb.get_pivot_tables();
2048        assert!(pts.is_empty());
2049    }
2050
2051    #[test]
2052    fn test_get_pivot_tables_after_add() {
2053        let mut wb = make_pivot_workbook();
2054        let config = basic_pivot_config();
2055        wb.add_pivot_table(&config).unwrap();
2056
2057        let pts = wb.get_pivot_tables();
2058        assert_eq!(pts.len(), 1);
2059        assert_eq!(pts[0].name, "PivotTable1");
2060        assert_eq!(pts[0].source_sheet, "Sheet1");
2061        assert_eq!(pts[0].source_range, "A1:C4");
2062        assert_eq!(pts[0].target_sheet, "Sheet1");
2063        assert_eq!(pts[0].location, "E1:F5");
2064    }
2065
2066    #[test]
2067    fn test_lazy_get_pivot_tables_without_mutation() {
2068        let mut wb = make_pivot_workbook();
2069        wb.add_pivot_table(&basic_pivot_config()).unwrap();
2070        let buf = wb.save_to_buffer().unwrap();
2071
2072        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
2073        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
2074        let pts = wb2.get_pivot_tables();
2075        assert_eq!(pts.len(), 1);
2076        assert_eq!(pts[0].name, "PivotTable1");
2077        assert_eq!(pts[0].source_sheet, "Sheet1");
2078        assert_eq!(pts[0].source_range, "A1:C4");
2079        assert_eq!(pts[0].target_sheet, "Sheet1");
2080    }
2081
2082    #[test]
2083    fn test_delete_pivot_table() {
2084        let mut wb = make_pivot_workbook();
2085        let config = basic_pivot_config();
2086        wb.add_pivot_table(&config).unwrap();
2087        let table_rels_path = relationship_part_path(&wb.pivot_tables[0].0);
2088        let cache_rels_path = relationship_part_path(&wb.pivot_cache_defs[0].0);
2089        assert_eq!(wb.pivot_tables.len(), 1);
2090
2091        wb.delete_pivot_table("PivotTable1").unwrap();
2092        assert!(wb.pivot_tables.is_empty());
2093        assert!(wb.pivot_cache_defs.is_empty());
2094        assert!(wb.pivot_cache_records.is_empty());
2095        assert!(wb.workbook_xml.pivot_caches.is_none());
2096        assert!(!wb.raw_graph_parts.contains_key(&table_rels_path));
2097        assert!(!wb.raw_graph_parts.contains_key(&cache_rels_path));
2098        // Content type overrides for pivot parts should be gone.
2099        let pivot_overrides: Vec<_> = wb
2100            .content_types
2101            .overrides
2102            .iter()
2103            .filter(|o| {
2104                o.content_type == mime_types::PIVOT_TABLE
2105                    || o.content_type == mime_types::PIVOT_CACHE_DEFINITION
2106                    || o.content_type == mime_types::PIVOT_CACHE_RECORDS
2107            })
2108            .collect();
2109        assert!(pivot_overrides.is_empty());
2110    }
2111
2112    #[test]
2113    fn test_delete_pivot_table_not_found() {
2114        let wb_result = Workbook::new().delete_pivot_table("NonExistent");
2115        assert!(wb_result.is_err());
2116        assert!(matches!(
2117            wb_result.unwrap_err(),
2118            Error::PivotTableNotFound { .. }
2119        ));
2120    }
2121
2122    #[test]
2123    fn test_pivot_table_save_open_roundtrip() {
2124        let dir = TempDir::new().unwrap();
2125        let path = dir.path().join("pivot_roundtrip.xlsx");
2126
2127        let mut wb = make_pivot_workbook();
2128        let config = basic_pivot_config();
2129        wb.add_pivot_table(&config).unwrap();
2130
2131        wb.save(&path).unwrap();
2132
2133        // Verify the ZIP contains pivot parts.
2134        let file = std::fs::File::open(&path).unwrap();
2135        let mut archive = zip::ZipArchive::new(file).unwrap();
2136        assert!(archive.by_name("xl/pivotTables/pivotTable1.xml").is_ok());
2137        assert!(archive
2138            .by_name("xl/pivotCache/pivotCacheDefinition1.xml")
2139            .is_ok());
2140        assert!(archive
2141            .by_name("xl/pivotCache/pivotCacheRecords1.xml")
2142            .is_ok());
2143        // Re-open and verify pivot table is parsed.
2144        let opts = OpenOptions::new()
2145            .read_mode(ReadMode::Eager)
2146            .aux_parts(AuxParts::EagerLoad);
2147        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
2148        assert_eq!(wb2.pivot_tables.len(), 1);
2149        assert_eq!(wb2.pivot_tables[0].1.name, "PivotTable1");
2150        assert_eq!(wb2.pivot_cache_defs.len(), 1);
2151        assert_eq!(wb2.pivot_cache_records.len(), 1);
2152    }
2153
2154    #[test]
2155    fn test_add_multiple_pivot_tables() {
2156        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2157        let mut wb = make_pivot_workbook();
2158
2159        let config1 = basic_pivot_config();
2160        wb.add_pivot_table(&config1).unwrap();
2161
2162        let config2 = PivotTableConfig {
2163            name: "PivotTable2".to_string(),
2164            source_sheet: "Sheet1".to_string(),
2165            source_range: "A1:C4".to_string(),
2166            target_sheet: "Sheet1".to_string(),
2167            target_cell: "H1".to_string(),
2168            rows: vec![PivotField {
2169                name: "Region".to_string(),
2170            }],
2171            columns: vec![],
2172            data: vec![PivotDataField {
2173                name: "Sales".to_string(),
2174                function: AggregateFunction::Count,
2175                display_name: None,
2176            }],
2177        };
2178        wb.add_pivot_table(&config2).unwrap();
2179
2180        assert_eq!(wb.pivot_tables.len(), 2);
2181        assert_eq!(wb.pivot_cache_defs.len(), 2);
2182        assert_eq!(wb.pivot_tables[0].1.cache_id, 0);
2183        assert_eq!(wb.pivot_tables[1].1.cache_id, 1);
2184
2185        let pts = wb.get_pivot_tables();
2186        assert_eq!(pts.len(), 2);
2187        assert_eq!(pts[0].name, "PivotTable1");
2188        assert_eq!(pts[1].name, "PivotTable2");
2189    }
2190
2191    #[test]
2192    fn test_add_pivot_table_content_types_added() {
2193        let mut wb = make_pivot_workbook();
2194        let config = basic_pivot_config();
2195        wb.add_pivot_table(&config).unwrap();
2196
2197        let has_pt_ct = wb.content_types.overrides.iter().any(|o| {
2198            o.content_type == mime_types::PIVOT_TABLE
2199                && o.part_name == "/xl/pivotTables/pivotTable1.xml"
2200        });
2201        assert!(has_pt_ct);
2202
2203        let has_pcd_ct = wb.content_types.overrides.iter().any(|o| {
2204            o.content_type == mime_types::PIVOT_CACHE_DEFINITION
2205                && o.part_name == "/xl/pivotCache/pivotCacheDefinition1.xml"
2206        });
2207        assert!(has_pcd_ct);
2208
2209        let has_pcr_ct = wb.content_types.overrides.iter().any(|o| {
2210            o.content_type == mime_types::PIVOT_CACHE_RECORDS
2211                && o.part_name == "/xl/pivotCache/pivotCacheRecords1.xml"
2212        });
2213        assert!(has_pcr_ct);
2214    }
2215
2216    #[test]
2217    fn test_add_pivot_table_avoids_existing_part_and_relationship_paths() {
2218        let mut wb = make_pivot_workbook();
2219        wb.unknown_parts.push((
2220            "xl/pivotTables/_rels/pivotTable1.xml.rels".to_string(),
2221            b"preserved".to_vec(),
2222        ));
2223        wb.unknown_parts.push((
2224            "xl/pivotCache/pivotCacheDefinition1.xml".to_string(),
2225            b"preserved".to_vec(),
2226        ));
2227        wb.unknown_parts.push((
2228            "xl/pivotCache/pivotCacheRecords1.xml".to_string(),
2229            b"preserved".to_vec(),
2230        ));
2231
2232        wb.add_pivot_table(&basic_pivot_config()).unwrap();
2233
2234        assert_eq!(wb.pivot_tables[0].0, "xl/pivotTables/pivotTable2.xml");
2235        assert_eq!(
2236            wb.pivot_cache_defs[0].0,
2237            "xl/pivotCache/pivotCacheDefinition2.xml"
2238        );
2239        assert_eq!(
2240            wb.pivot_cache_records[0].0,
2241            "xl/pivotCache/pivotCacheRecords2.xml"
2242        );
2243    }
2244
2245    #[test]
2246    fn test_add_pivot_table_workbook_rels_and_pivot_caches() {
2247        let mut wb = make_pivot_workbook();
2248        let config = basic_pivot_config();
2249        wb.add_pivot_table(&config).unwrap();
2250
2251        // Workbook rels should have a pivot cache definition relationship.
2252        let cache_rel = wb
2253            .workbook_rels
2254            .relationships
2255            .iter()
2256            .find(|r| r.rel_type == rel_types::PIVOT_CACHE_DEF);
2257        assert!(cache_rel.is_some());
2258        let cache_rel = cache_rel.unwrap();
2259        assert_eq!(cache_rel.target, "pivotCache/pivotCacheDefinition1.xml");
2260
2261        // Workbook XML should have pivot caches.
2262        let pivot_caches = wb.workbook_xml.pivot_caches.as_ref().unwrap();
2263        assert_eq!(pivot_caches.caches.len(), 1);
2264        assert_eq!(pivot_caches.caches[0].cache_id, 0);
2265        assert_eq!(pivot_caches.caches[0].r_id, cache_rel.id);
2266    }
2267
2268    #[test]
2269    fn test_add_pivot_table_worksheet_rels_added() {
2270        let mut wb = make_pivot_workbook();
2271        let config = basic_pivot_config();
2272        wb.add_pivot_table(&config).unwrap();
2273
2274        // Sheet1 is index 0; its rels should have a pivot table relationship.
2275        let ws_rels = wb.worksheet_rels.get(&0).unwrap();
2276        let pt_rel = ws_rels
2277            .relationships
2278            .iter()
2279            .find(|r| r.rel_type == rel_types::PIVOT_TABLE);
2280        assert!(pt_rel.is_some());
2281        assert_eq!(pt_rel.unwrap().target, "../pivotTables/pivotTable1.xml");
2282    }
2283
2284    #[test]
2285    fn test_add_pivot_table_on_separate_target_sheet() {
2286        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2287        let mut wb = make_pivot_workbook();
2288        wb.new_sheet("Report").unwrap();
2289
2290        let config = PivotTableConfig {
2291            name: "CrossSheet".to_string(),
2292            source_sheet: "Sheet1".to_string(),
2293            source_range: "A1:C4".to_string(),
2294            target_sheet: "Report".to_string(),
2295            target_cell: "A1".to_string(),
2296            rows: vec![PivotField {
2297                name: "Name".to_string(),
2298            }],
2299            columns: vec![],
2300            data: vec![PivotDataField {
2301                name: "Sales".to_string(),
2302                function: AggregateFunction::Sum,
2303                display_name: None,
2304            }],
2305        };
2306        wb.add_pivot_table(&config).unwrap();
2307
2308        let pts = wb.get_pivot_tables();
2309        assert_eq!(pts.len(), 1);
2310        assert_eq!(pts[0].target_sheet, "Report");
2311        assert_eq!(pts[0].source_sheet, "Sheet1");
2312
2313        // Worksheet rels should be on the Report sheet (index 1).
2314        let ws_rels = wb.worksheet_rels.get(&1).unwrap();
2315        let pt_rel = ws_rels
2316            .relationships
2317            .iter()
2318            .find(|r| r.rel_type == rel_types::PIVOT_TABLE);
2319        assert!(pt_rel.is_some());
2320    }
2321
2322    #[test]
2323    fn test_pivot_table_invalid_source_range() {
2324        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2325        let mut wb = make_pivot_workbook();
2326        let config = PivotTableConfig {
2327            name: "BadRange".to_string(),
2328            source_sheet: "Sheet1".to_string(),
2329            source_range: "INVALID".to_string(),
2330            target_sheet: "Sheet1".to_string(),
2331            target_cell: "E1".to_string(),
2332            rows: vec![PivotField {
2333                name: "Name".to_string(),
2334            }],
2335            columns: vec![],
2336            data: vec![PivotDataField {
2337                name: "Sales".to_string(),
2338                function: AggregateFunction::Sum,
2339                display_name: None,
2340            }],
2341        };
2342        let result = wb.add_pivot_table(&config);
2343        assert!(result.is_err());
2344    }
2345
2346    #[test]
2347    fn test_delete_pivot_table_then_add_another() {
2348        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2349        let mut wb = make_pivot_workbook();
2350        let config1 = basic_pivot_config();
2351        wb.add_pivot_table(&config1).unwrap();
2352        wb.delete_pivot_table("PivotTable1").unwrap();
2353
2354        let config2 = PivotTableConfig {
2355            name: "PivotTable2".to_string(),
2356            source_sheet: "Sheet1".to_string(),
2357            source_range: "A1:C4".to_string(),
2358            target_sheet: "Sheet1".to_string(),
2359            target_cell: "E1".to_string(),
2360            rows: vec![PivotField {
2361                name: "Region".to_string(),
2362            }],
2363            columns: vec![],
2364            data: vec![PivotDataField {
2365                name: "Sales".to_string(),
2366                function: AggregateFunction::Max,
2367                display_name: None,
2368            }],
2369        };
2370        wb.add_pivot_table(&config2).unwrap();
2371
2372        assert_eq!(wb.pivot_tables.len(), 1);
2373        assert_eq!(wb.pivot_tables[0].1.name, "PivotTable2");
2374        assert_eq!(wb.pivot_cache_defs.len(), 1);
2375        assert_eq!(wb.pivot_cache_records.len(), 1);
2376        assert!(wb
2377            .raw_graph_parts
2378            .contains_key(&relationship_part_path(&wb.pivot_tables[0].0)));
2379        assert!(wb
2380            .raw_graph_parts
2381            .contains_key(&relationship_part_path(&wb.pivot_cache_defs[0].0)));
2382    }
2383
2384    #[test]
2385    fn test_pivot_table_cache_definition_stores_source_info() {
2386        let mut wb = make_pivot_workbook();
2387        let config = basic_pivot_config();
2388        wb.add_pivot_table(&config).unwrap();
2389
2390        let pcd = &wb.pivot_cache_defs[0].1;
2391        let ws_source = pcd.cache_source.worksheet_source.as_ref().unwrap();
2392        assert_eq!(ws_source.sheet, "Sheet1");
2393        assert_eq!(ws_source.reference, "A1:C4");
2394        assert_eq!(pcd.cache_fields.fields.len(), 3);
2395        assert_eq!(pcd.cache_fields.fields[0].name, "Name");
2396        assert_eq!(pcd.cache_fields.fields[1].name, "Region");
2397        assert_eq!(pcd.cache_fields.fields[2].name, "Sales");
2398    }
2399
2400    #[test]
2401    fn test_pivot_table_populates_cache_records_and_shared_items() {
2402        let mut wb = make_pivot_workbook();
2403        wb.add_pivot_table(&basic_pivot_config()).unwrap();
2404
2405        let pcd = &wb.pivot_cache_defs[0].1;
2406        assert_eq!(pcd.record_count, Some(3));
2407        assert_eq!(pcd.refresh_on_load, Some(true));
2408        assert_eq!(pcd.r_id.as_deref(), Some("rId1"));
2409        assert_eq!(
2410            pcd.cache_fields.fields[0]
2411                .shared_items
2412                .as_ref()
2413                .unwrap()
2414                .count,
2415            Some(3)
2416        );
2417        assert_eq!(
2418            pcd.cache_fields.fields[1]
2419                .shared_items
2420                .as_ref()
2421                .unwrap()
2422                .count,
2423            Some(2)
2424        );
2425        assert_eq!(
2426            pcd.cache_fields.fields[2]
2427                .shared_items
2428                .as_ref()
2429                .unwrap()
2430                .number_items
2431                .len(),
2432            3
2433        );
2434
2435        let records = &wb.pivot_cache_records[0].1;
2436        assert_eq!(records.count, Some(3));
2437        assert_eq!(records.records.len(), 3);
2438        assert!(records
2439            .records
2440            .iter()
2441            .all(|record| { record.index_fields.len() == 2 && record.number_fields.len() == 1 }));
2442    }
2443
2444    #[test]
2445    fn test_pivot_table_builds_complete_part_relationship_graph() {
2446        let mut wb = make_pivot_workbook();
2447        wb.add_pivot_table(&basic_pivot_config()).unwrap();
2448
2449        let pt_path = &wb.pivot_tables[0].0;
2450        let cache_path = &wb.pivot_cache_defs[0].0;
2451        let pt_rels_path = relationship_part_path(pt_path);
2452        let cache_rels_path = relationship_part_path(cache_path);
2453        let pt_rels: Relationships =
2454            quick_xml::de::from_reader(wb.raw_graph_parts.get(&pt_rels_path).unwrap().as_slice())
2455                .unwrap();
2456        let cache_rels: Relationships = quick_xml::de::from_reader(
2457            wb.raw_graph_parts.get(&cache_rels_path).unwrap().as_slice(),
2458        )
2459        .unwrap();
2460
2461        assert_eq!(pt_rels.relationships.len(), 1);
2462        assert_eq!(
2463            pt_rels.relationships[0].rel_type,
2464            rel_types::PIVOT_CACHE_DEF
2465        );
2466        assert_eq!(cache_rels.relationships.len(), 1);
2467        assert_eq!(
2468            cache_rels.relationships[0].rel_type,
2469            rel_types::PIVOT_CACHE_RECORDS
2470        );
2471        assert_eq!(
2472            wb.pivot_cache_defs[0].1.r_id.as_deref(),
2473            Some(cache_rels.relationships[0].id.as_str())
2474        );
2475    }
2476
2477    #[test]
2478    fn test_pivot_table_axis_items_and_output_location_range() {
2479        let mut wb = make_pivot_workbook();
2480        wb.add_pivot_table(&basic_pivot_config()).unwrap();
2481
2482        let pt = &wb.pivot_tables[0].1;
2483        let row_items = pt.pivot_fields.fields[0].items.as_ref().unwrap();
2484        assert_eq!(row_items.items.len(), 4);
2485        assert_eq!(
2486            row_items.items.last().unwrap().item_type.as_deref(),
2487            Some("default")
2488        );
2489        assert_eq!(pt.location.reference, "E1:F5");
2490    }
2491
2492    #[test]
2493    fn test_get_pivot_tables_resolves_cache_through_workbook_relationship() {
2494        let mut wb = make_pivot_workbook();
2495        let first = basic_pivot_config();
2496        wb.add_pivot_table(&first).unwrap();
2497
2498        let mut second = basic_pivot_config();
2499        second.name = "PivotTable2".to_string();
2500        second.source_range = "A1:B4".to_string();
2501        second.target_cell = "H1".to_string();
2502        second.data[0].name = "Region".to_string();
2503        wb.add_pivot_table(&second).unwrap();
2504
2505        wb.pivot_cache_defs.swap(0, 1);
2506        let infos = wb.get_pivot_tables();
2507        assert_eq!(infos[0].source_range, "A1:C4");
2508        assert_eq!(infos[1].source_range, "A1:B4");
2509    }
2510
2511    #[test]
2512    fn test_pivot_table_field_names_from_data() {
2513        let mut wb = make_pivot_workbook();
2514        let config = basic_pivot_config();
2515        wb.add_pivot_table(&config).unwrap();
2516
2517        let pt = &wb.pivot_tables[0].1;
2518        assert_eq!(pt.pivot_fields.fields.len(), 3);
2519        // Name is a row field.
2520        assert_eq!(pt.pivot_fields.fields[0].axis, Some("axisRow".to_string()));
2521        // Region is not used.
2522        assert_eq!(pt.pivot_fields.fields[1].axis, None);
2523        // Sales is a data field.
2524        assert_eq!(pt.pivot_fields.fields[2].data_field, Some(true));
2525    }
2526
2527    #[test]
2528    fn test_pivot_table_empty_header_row_error() {
2529        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2530        let mut wb = Workbook::new();
2531        // No data set in the sheet.
2532        let config = PivotTableConfig {
2533            name: "Empty".to_string(),
2534            source_sheet: "Sheet1".to_string(),
2535            source_range: "A1:B1".to_string(),
2536            target_sheet: "Sheet1".to_string(),
2537            target_cell: "D1".to_string(),
2538            rows: vec![PivotField {
2539                name: "X".to_string(),
2540            }],
2541            columns: vec![],
2542            data: vec![PivotDataField {
2543                name: "Y".to_string(),
2544                function: AggregateFunction::Sum,
2545                display_name: None,
2546            }],
2547        };
2548        let result = wb.add_pivot_table(&config);
2549        assert!(result.is_err());
2550    }
2551
2552    #[test]
2553    fn pivot_source_limits_accept_exact_area_and_reject_plus_one_atomically() {
2554        let config = basic_pivot_config();
2555        let mut exact = make_pivot_workbook();
2556        let limits = TraversalLimits::new(4, 3, 12, 64 * 1024).unwrap();
2557        exact.add_pivot_table_with_limits(&config, limits).unwrap();
2558        assert_eq!(exact.pivot_tables.len(), 1);
2559
2560        let mut over = make_pivot_workbook();
2561        let before_graph_parts = over.raw_graph_parts.len();
2562        let before_overrides = over.content_types.overrides.len();
2563        let before_workbook_rels = over.workbook_rels.relationships.len();
2564        let before_worksheet_rels = over.worksheet_rels.len();
2565        let before_pivot_caches = over
2566            .workbook_xml
2567            .pivot_caches
2568            .as_ref()
2569            .map_or(0, |caches| caches.caches.len());
2570        let limits = TraversalLimits::new(4, 3, 11, 64 * 1024).unwrap();
2571        let error = over
2572            .add_pivot_table_with_limits(&config, limits)
2573            .unwrap_err();
2574        let Error::ResourceLimitExceeded(metadata) = error else {
2575            panic!("expected resource limit error");
2576        };
2577        assert_eq!(
2578            metadata.dimension(),
2579            crate::resource::ResourceDimension::CellCount
2580        );
2581        assert_eq!(metadata.limit(), 11);
2582        assert_eq!(metadata.observed(), 12);
2583        assert!(over.pivot_tables.is_empty());
2584        assert!(over.pivot_cache_defs.is_empty());
2585        assert!(over.pivot_cache_records.is_empty());
2586        assert_eq!(over.raw_graph_parts.len(), before_graph_parts);
2587        assert_eq!(over.content_types.overrides.len(), before_overrides);
2588        assert_eq!(over.workbook_rels.relationships.len(), before_workbook_rels);
2589        assert_eq!(over.worksheet_rels.len(), before_worksheet_rels);
2590        assert_eq!(
2591            over.workbook_xml
2592                .pivot_caches
2593                .as_ref()
2594                .map_or(0, |caches| caches.caches.len()),
2595            before_pivot_caches
2596        );
2597    }
2598
2599    #[test]
2600    fn pivot_output_budget_accepts_exact_and_rejects_plus_one() {
2601        let config = basic_pivot_config();
2602        let accepts = |max_output_bytes| {
2603            let mut workbook = make_pivot_workbook();
2604            let limits = TraversalLimits::new(4, 3, 12, max_output_bytes).unwrap();
2605            workbook.add_pivot_table_with_limits(&config, limits)
2606        };
2607
2608        let mut low = 1_u64;
2609        let mut high = 64 * 1024_u64;
2610        accepts(high).unwrap();
2611        while low < high {
2612            let midpoint = low + (high - low) / 2;
2613            if accepts(midpoint).is_ok() {
2614                high = midpoint;
2615            } else {
2616                low = midpoint + 1;
2617            }
2618        }
2619        let exact = low;
2620        accepts(exact).unwrap();
2621
2622        let error = accepts(exact - 1).unwrap_err();
2623        let Error::ResourceLimitExceeded(metadata) = error else {
2624            panic!("expected output resource limit error");
2625        };
2626        assert_eq!(
2627            metadata.dimension(),
2628            crate::resource::ResourceDimension::OutputBytes
2629        );
2630        assert_eq!(metadata.limit(), exact - 1);
2631        assert_eq!(metadata.observed(), exact);
2632    }
2633
2634    #[test]
2635    fn pivot_config_strings_are_admitted_before_source_parsing() {
2636        let mut workbook = make_pivot_workbook();
2637        let before = workbook.save_to_buffer().unwrap();
2638        let mut config = basic_pivot_config();
2639        config.name = "x".repeat(32_000);
2640        config.source_range = "not-a-range".to_string();
2641
2642        let limits = TraversalLimits::new(4, 3, 12, 1024).unwrap();
2643        let error = workbook
2644            .add_pivot_table_with_limits(&config, limits)
2645            .unwrap_err();
2646        let Error::ResourceLimitExceeded(metadata) = error else {
2647            panic!("expected config output limit error before source parsing");
2648        };
2649        assert_eq!(
2650            metadata.dimension(),
2651            crate::resource::ResourceDimension::OutputBytes
2652        );
2653        assert_eq!(metadata.limit(), 1024);
2654        assert_eq!(metadata.observed(), 1025);
2655        assert_eq!(workbook.save_to_buffer().unwrap(), before);
2656    }
2657
2658    #[test]
2659    fn pivot_config_collections_are_admitted_before_definition_allocation() {
2660        let mut workbook = make_pivot_workbook();
2661        let before = workbook.save_to_buffer().unwrap();
2662        let mut config = basic_pivot_config();
2663        config.source_range = "not-a-range".to_string();
2664        config.rows = (0..50_000)
2665            .map(|_| crate::pivot::PivotField {
2666                name: "Name".to_string(),
2667            })
2668            .collect();
2669
2670        let limits = TraversalLimits::new(4, 3, 12, 64 * 1024).unwrap();
2671        let error = workbook
2672            .add_pivot_table_with_limits(&config, limits)
2673            .unwrap_err();
2674        let Error::ResourceLimitExceeded(metadata) = error else {
2675            panic!("expected definition output limit error before source parsing");
2676        };
2677        assert_eq!(
2678            metadata.dimension(),
2679            crate::resource::ResourceDimension::OutputBytes
2680        );
2681        assert_eq!(metadata.limit(), 64 * 1024);
2682        assert_eq!(metadata.observed(), 64 * 1024 + 1);
2683        assert_eq!(workbook.save_to_buffer().unwrap(), before);
2684    }
2685
2686    #[test]
2687    fn pivot_repeated_sst_amplification_is_bounded_and_atomic() {
2688        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2689
2690        let mut workbook = Workbook::new();
2691        workbook.set_cell_value("Sheet1", "A1", "Category").unwrap();
2692        let repeated = "x".repeat(32_000);
2693        for row in 2..=33 {
2694            workbook
2695                .set_cell_value("Sheet1", &format!("A{row}"), repeated.as_str())
2696                .unwrap();
2697        }
2698        assert_eq!(workbook.sst_runtime.len(), 2);
2699
2700        let config = PivotTableConfig {
2701            name: "RepeatedSst".to_string(),
2702            source_sheet: "Sheet1".to_string(),
2703            source_range: "A1:A33".to_string(),
2704            target_sheet: "Sheet1".to_string(),
2705            target_cell: "C1".to_string(),
2706            rows: vec![PivotField {
2707                name: "Category".to_string(),
2708            }],
2709            columns: vec![],
2710            data: vec![PivotDataField {
2711                name: "Category".to_string(),
2712                function: AggregateFunction::Count,
2713                display_name: None,
2714            }],
2715        };
2716        let before = workbook.save_to_buffer().unwrap();
2717        let limits = TraversalLimits::new(33, 1, 33, 256 * 1024).unwrap();
2718        let error = workbook
2719            .add_pivot_table_with_limits(&config, limits)
2720            .unwrap_err();
2721        let Error::ResourceLimitExceeded(metadata) = error else {
2722            panic!("expected output resource limit error");
2723        };
2724        assert_eq!(
2725            metadata.dimension(),
2726            crate::resource::ResourceDimension::OutputBytes
2727        );
2728        assert_eq!(metadata.limit(), 256 * 1024);
2729        assert_eq!(metadata.observed(), 256 * 1024 + 1);
2730        assert!(workbook.pivot_tables.is_empty());
2731        assert!(workbook.pivot_cache_defs.is_empty());
2732        assert!(workbook.pivot_cache_records.is_empty());
2733        assert_eq!(workbook.save_to_buffer().unwrap(), before);
2734    }
2735
2736    #[test]
2737    fn pivot_source_preserves_far_rows_and_save_reopen_roundtrip() {
2738        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2739
2740        let mut wb = Workbook::new();
2741        wb.set_cell_value("Sheet1", "A1048575", "Category").unwrap();
2742        wb.set_cell_value("Sheet1", "A1048576", "North").unwrap();
2743        let config = PivotTableConfig {
2744            name: "FarRows".to_string(),
2745            source_sheet: "Sheet1".to_string(),
2746            source_range: "A1048575:A1048576".to_string(),
2747            target_sheet: "Sheet1".to_string(),
2748            target_cell: "C1".to_string(),
2749            rows: vec![PivotField {
2750                name: "Category".to_string(),
2751            }],
2752            columns: vec![],
2753            data: vec![PivotDataField {
2754                name: "Category".to_string(),
2755                function: AggregateFunction::Count,
2756                display_name: None,
2757            }],
2758        };
2759        let limits = TraversalLimits::new(2, 1, 2, 64 * 1024).unwrap();
2760        wb.add_pivot_table_with_limits(&config, limits).unwrap();
2761        assert_eq!(wb.pivot_cache_records[0].1.count, Some(1));
2762
2763        let dir = TempDir::new().unwrap();
2764        let path = dir.path().join("far-row-pivot.xlsx");
2765        wb.save(&path).unwrap();
2766        let reopened = Workbook::open(&path).unwrap();
2767        let pivots = reopened.get_pivot_tables();
2768        assert_eq!(pivots.len(), 1);
2769        assert_eq!(pivots[0].source_range, "A1048575:A1048576");
2770    }
2771
2772    #[test]
2773    fn test_pivot_table_multiple_save_roundtrip() {
2774        use crate::pivot::{AggregateFunction, PivotDataField, PivotField};
2775        let dir = TempDir::new().unwrap();
2776        let path = dir.path().join("multi_pivot.xlsx");
2777
2778        let mut wb = make_pivot_workbook();
2779        let config1 = basic_pivot_config();
2780        wb.add_pivot_table(&config1).unwrap();
2781
2782        let config2 = PivotTableConfig {
2783            name: "PT2".to_string(),
2784            source_sheet: "Sheet1".to_string(),
2785            source_range: "A1:C4".to_string(),
2786            target_sheet: "Sheet1".to_string(),
2787            target_cell: "H1".to_string(),
2788            rows: vec![PivotField {
2789                name: "Region".to_string(),
2790            }],
2791            columns: vec![],
2792            data: vec![PivotDataField {
2793                name: "Sales".to_string(),
2794                function: AggregateFunction::Min,
2795                display_name: None,
2796            }],
2797        };
2798        wb.add_pivot_table(&config2).unwrap();
2799        wb.save(&path).unwrap();
2800
2801        let opts = OpenOptions::new()
2802            .read_mode(ReadMode::Eager)
2803            .aux_parts(AuxParts::EagerLoad);
2804        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
2805        assert_eq!(wb2.pivot_tables.len(), 2);
2806        let names: Vec<&str> = wb2
2807            .pivot_tables
2808            .iter()
2809            .map(|(_, pt)| pt.name.as_str())
2810            .collect();
2811        assert!(names.contains(&"PivotTable1"));
2812        assert!(names.contains(&"PT2"));
2813    }
2814
2815    #[test]
2816    fn test_add_slicer_drawing_id_overflow_is_atomic() {
2817        let mut wb = make_slicer_workbook();
2818        wb.add_shape(
2819            "Sheet1",
2820            &crate::shape::ShapeConfig {
2821                shape_type: crate::shape::ShapeType::Rect,
2822                from_cell: "J1".to_string(),
2823                to_cell: "K2".to_string(),
2824                text: None,
2825                fill_color: None,
2826                line_color: None,
2827                line_width: None,
2828            },
2829        )
2830        .unwrap();
2831        wb.drawings[0].1.two_cell_anchors[0]
2832            .shape
2833            .as_mut()
2834            .unwrap()
2835            .nv_sp_pr
2836            .c_nv_pr
2837            .id = u32::MAX;
2838        let before = wb.save_to_buffer().unwrap();
2839
2840        let result = wb.add_slicer("Sheet1", &make_slicer_config("S1", "Status"));
2841
2842        assert!(
2843            matches!(result, Err(Error::InvalidArgument(message)) if message == "drawing object ID overflow")
2844        );
2845        assert!(wb.slicer_defs.is_empty());
2846        assert!(wb.slicer_caches.is_empty());
2847        assert!(wb.workbook_xml.defined_names.is_none());
2848        assert_eq!(wb.save_to_buffer().unwrap(), before);
2849    }
2850
2851    #[test]
2852    fn test_calculate_all_with_dependency_order() {
2853        let mut wb = Workbook::new();
2854        // A1 = 10 (value)
2855        wb.set_cell_value("Sheet1", "A1", 10.0).unwrap();
2856        // A2 = A1 * 2 (formula depends on A1)
2857        wb.set_cell_value(
2858            "Sheet1",
2859            "A2",
2860            CellValue::Formula {
2861                expr: "A1*2".to_string(),
2862                result: None,
2863            },
2864        )
2865        .unwrap();
2866        // A3 = A2 + A1 (formula depends on A2 and A1)
2867        wb.set_cell_value(
2868            "Sheet1",
2869            "A3",
2870            CellValue::Formula {
2871                expr: "A2+A1".to_string(),
2872                result: None,
2873            },
2874        )
2875        .unwrap();
2876
2877        wb.calculate_all().unwrap();
2878
2879        // A2 should be 20 (10 * 2)
2880        let a2 = wb.get_cell_value("Sheet1", "A2").unwrap();
2881        match a2 {
2882            CellValue::Formula { result, .. } => {
2883                assert_eq!(*result.unwrap(), CellValue::Number(20.0));
2884            }
2885            _ => panic!("A2 should be a formula cell"),
2886        }
2887
2888        // A3 should be 30 (20 + 10)
2889        let a3 = wb.get_cell_value("Sheet1", "A3").unwrap();
2890        match a3 {
2891            CellValue::Formula { result, .. } => {
2892                assert_eq!(*result.unwrap(), CellValue::Number(30.0));
2893            }
2894            _ => panic!("A3 should be a formula cell"),
2895        }
2896    }
2897
2898    #[test]
2899    fn test_calculate_all_isolates_formula_errors() {
2900        let mut wb = Workbook::new();
2901        for (cell, expr) in [
2902            ("A1", "1+1"),
2903            ("B1", "1+\"abc\""),
2904            ("C1", "NONEXISTENT(1)"),
2905            ("D1", "SUM(A:A)"),
2906            ("E1", "A1+3"),
2907            ("F1", "B1+1"),
2908            ("G1", "#N/A+1"),
2909        ] {
2910            wb.set_cell_value(
2911                "Sheet1",
2912                cell,
2913                CellValue::Formula {
2914                    expr: expr.to_string(),
2915                    result: None,
2916                },
2917            )
2918            .unwrap();
2919        }
2920
2921        wb.calculate_all().unwrap();
2922
2923        let cached = |cell: &str| match wb.get_cell_value("Sheet1", cell).unwrap() {
2924            CellValue::Formula {
2925                result: Some(result),
2926                ..
2927            } => *result,
2928            value => panic!("{cell} should have a cached formula result, got {value:?}"),
2929        };
2930
2931        assert_eq!(cached("A1"), CellValue::Number(2.0));
2932        assert_eq!(cached("B1"), CellValue::Error("#VALUE!".to_string()));
2933        assert_eq!(cached("C1"), CellValue::Error("#NAME?".to_string()));
2934        assert_eq!(cached("D1"), CellValue::Error("#VALUE!".to_string()));
2935        assert_eq!(cached("E1"), CellValue::Number(5.0));
2936        assert_eq!(cached("F1"), CellValue::Error("#VALUE!".to_string()));
2937        assert_eq!(cached("G1"), CellValue::Error("#N/A".to_string()));
2938    }
2939
2940    #[test]
2941    fn test_calculate_all_caches_range_errors_and_continues() {
2942        let mut wb = Workbook::new();
2943        for (cell, expr) in [
2944            ("A1", "1/0"),
2945            ("B1", "SUM(A1:A2)"),
2946            ("C1", "2+2"),
2947            ("C5", "ROW()"),
2948            ("D5", "COLUMN()"),
2949        ] {
2950            wb.set_cell_value(
2951                "Sheet1",
2952                cell,
2953                CellValue::Formula {
2954                    expr: expr.to_string(),
2955                    result: None,
2956                },
2957            )
2958            .unwrap();
2959        }
2960
2961        wb.calculate_all().unwrap();
2962
2963        let cached = |cell: &str| match wb.get_cell_value("Sheet1", cell).unwrap() {
2964            CellValue::Formula {
2965                result: Some(result),
2966                ..
2967            } => *result,
2968            value => panic!("{cell} should have a cached formula result, got {value:?}"),
2969        };
2970
2971        assert_eq!(cached("A1"), CellValue::Error("#DIV/0!".to_string()));
2972        assert_eq!(cached("B1"), CellValue::Error("#DIV/0!".to_string()));
2973        assert_eq!(cached("C1"), CellValue::Number(4.0));
2974        assert_eq!(cached("C5"), CellValue::Number(5.0));
2975        assert_eq!(cached("D5"), CellValue::Number(4.0));
2976    }
2977
2978    #[test]
2979    fn test_calculate_all_no_formulas() {
2980        let mut wb = Workbook::new();
2981        wb.set_cell_value("Sheet1", "A1", 10.0).unwrap();
2982        wb.set_cell_value("Sheet1", "B1", 20.0).unwrap();
2983        // Should succeed without error when there are no formulas.
2984        wb.calculate_all().unwrap();
2985    }
2986
2987    #[test]
2988    fn test_calculate_all_no_formulas_keeps_lazy_sheet_clean() {
2989        let mut wb = Workbook::new();
2990        wb.set_cell_value("Sheet1", "A1", 10.0).unwrap();
2991        let buf = wb.save_to_buffer().unwrap();
2992
2993        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
2994        let mut wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
2995        assert!(!wb2.is_sheet_dirty(0));
2996
2997        wb2.calculate_all().unwrap();
2998        assert!(
2999            !wb2.is_sheet_dirty(0),
3000            "calculate_all without formulas must not dirty the sheet"
3001        );
3002    }
3003
3004    #[test]
3005    fn test_calculate_all_cycle_detection() {
3006        let mut wb = Workbook::new();
3007        // A1 = B1, B1 = A1
3008        wb.set_cell_value(
3009            "Sheet1",
3010            "A1",
3011            CellValue::Formula {
3012                expr: "B1".to_string(),
3013                result: None,
3014            },
3015        )
3016        .unwrap();
3017        wb.set_cell_value(
3018            "Sheet1",
3019            "B1",
3020            CellValue::Formula {
3021                expr: "A1".to_string(),
3022                result: None,
3023            },
3024        )
3025        .unwrap();
3026
3027        let result = wb.calculate_all();
3028        assert!(result.is_err());
3029        let err_str = result.unwrap_err().to_string();
3030        assert!(
3031            err_str.contains("circular reference"),
3032            "expected circular reference error, got: {err_str}"
3033        );
3034    }
3035
3036    #[test]
3037    fn test_calculate_all_resource_failure_is_atomic() {
3038        let mut wb = Workbook::new();
3039        wb.set_cell_value(
3040            "Sheet1",
3041            "A1",
3042            CellValue::Formula {
3043                expr: "1+1".to_string(),
3044                result: Some(Box::new(CellValue::Number(7.0))),
3045            },
3046        )
3047        .unwrap();
3048        wb.set_cell_value(
3049            "Sheet1",
3050            "B1",
3051            CellValue::Formula {
3052                expr: "A1+1".to_string(),
3053                result: Some(Box::new(CellValue::Number(8.0))),
3054            },
3055        )
3056        .unwrap();
3057        let buffer = wb.save_to_buffer().unwrap();
3058        let options = OpenOptions::new().read_mode(ReadMode::Lazy);
3059        let mut wb = Workbook::open_from_buffer_with_options(&buffer, &options).unwrap();
3060        let before_a1 = wb.get_cell_value("Sheet1", "A1").unwrap();
3061        let before_b1 = wb.get_cell_value("Sheet1", "B1").unwrap();
3062        assert!(!wb.is_sheet_dirty(0));
3063        let limits = crate::formula::budget::FormulaLimits {
3064            operation_input_bytes: 3,
3065            ..crate::formula::budget::FormulaLimits::secure_default()
3066        };
3067
3068        let error = wb.calculate_all_with_limits(limits).unwrap_err();
3069
3070        assert_eq!(
3071            error.resource_metadata().unwrap().dimension_code(),
3072            "input_bytes"
3073        );
3074        assert_eq!(wb.get_cell_value("Sheet1", "A1").unwrap(), before_a1);
3075        assert_eq!(wb.get_cell_value("Sheet1", "B1").unwrap(), before_b1);
3076        assert!(!wb.is_sheet_dirty(0));
3077    }
3078
3079    #[test]
3080    fn test_set_get_doc_props() {
3081        let mut wb = Workbook::new();
3082        let props = crate::doc_props::DocProperties {
3083            title: Some("My Title".to_string()),
3084            subject: Some("My Subject".to_string()),
3085            creator: Some("Author".to_string()),
3086            keywords: Some("rust, excel".to_string()),
3087            description: Some("A test workbook".to_string()),
3088            last_modified_by: Some("Editor".to_string()),
3089            revision: Some("2".to_string()),
3090            created: Some("2024-01-01T00:00:00Z".to_string()),
3091            modified: Some("2024-06-01T12:00:00Z".to_string()),
3092            category: Some("Testing".to_string()),
3093            content_status: Some("Draft".to_string()),
3094        };
3095        wb.set_doc_props(props);
3096
3097        let got = wb.get_doc_props();
3098        assert_eq!(got.title.as_deref(), Some("My Title"));
3099        assert_eq!(got.subject.as_deref(), Some("My Subject"));
3100        assert_eq!(got.creator.as_deref(), Some("Author"));
3101        assert_eq!(got.keywords.as_deref(), Some("rust, excel"));
3102        assert_eq!(got.description.as_deref(), Some("A test workbook"));
3103        assert_eq!(got.last_modified_by.as_deref(), Some("Editor"));
3104        assert_eq!(got.revision.as_deref(), Some("2"));
3105        assert_eq!(got.created.as_deref(), Some("2024-01-01T00:00:00Z"));
3106        assert_eq!(got.modified.as_deref(), Some("2024-06-01T12:00:00Z"));
3107        assert_eq!(got.category.as_deref(), Some("Testing"));
3108        assert_eq!(got.content_status.as_deref(), Some("Draft"));
3109    }
3110
3111    #[test]
3112    fn test_set_get_app_props() {
3113        let mut wb = Workbook::new();
3114        let props = crate::doc_props::AppProperties {
3115            application: Some("SheetKit".to_string()),
3116            doc_security: Some(0),
3117            company: Some("Acme Corp".to_string()),
3118            app_version: Some("1.0.0".to_string()),
3119            manager: Some("Boss".to_string()),
3120            template: Some("default.xltx".to_string()),
3121        };
3122        wb.set_app_props(props);
3123
3124        let got = wb.get_app_props();
3125        assert_eq!(got.application.as_deref(), Some("SheetKit"));
3126        assert_eq!(got.doc_security, Some(0));
3127        assert_eq!(got.company.as_deref(), Some("Acme Corp"));
3128        assert_eq!(got.app_version.as_deref(), Some("1.0.0"));
3129        assert_eq!(got.manager.as_deref(), Some("Boss"));
3130        assert_eq!(got.template.as_deref(), Some("default.xltx"));
3131    }
3132
3133    #[test]
3134    fn test_add_pivot_table_after_parsed_u32_max_cache_id() {
3135        let mut wb = make_pivot_workbook();
3136        wb.add_pivot_table(&basic_pivot_config()).unwrap();
3137        wb.pivot_tables[0].1.cache_id = u32::MAX;
3138        wb.workbook_xml.pivot_caches.as_mut().unwrap().caches[0].cache_id = u32::MAX;
3139
3140        let mut config = basic_pivot_config();
3141        config.name = "PivotTable2".to_string();
3142        config.target_cell = "I1".to_string();
3143        wb.add_pivot_table(&config).unwrap();
3144
3145        assert_eq!(wb.pivot_tables[1].1.cache_id, 0);
3146        let caches = &wb.workbook_xml.pivot_caches.as_ref().unwrap().caches;
3147        let ids: Vec<u32> = caches.iter().map(|cache| cache.cache_id).collect();
3148        assert_eq!(ids, vec![u32::MAX, 0]);
3149    }
3150
3151    #[test]
3152    fn test_add_pivot_table_reuses_lowest_free_cache_id() {
3153        let mut wb = make_pivot_workbook();
3154        wb.add_pivot_table(&basic_pivot_config()).unwrap();
3155        wb.pivot_tables[0].1.cache_id = 5;
3156        wb.workbook_xml.pivot_caches.as_mut().unwrap().caches[0].cache_id = 5;
3157
3158        let mut config = basic_pivot_config();
3159        config.name = "PivotTable2".to_string();
3160        config.target_cell = "I1".to_string();
3161        wb.add_pivot_table(&config).unwrap();
3162
3163        assert_eq!(wb.pivot_tables[1].1.cache_id, 0);
3164    }
3165
3166    #[test]
3167    fn test_custom_property_package_rel_id_does_not_collide() {
3168        let mut wb = Workbook::new();
3169        let count = wb.package_rels.relationships.len();
3170        wb.package_rels.relationships[0].id = format!("rId{}", count + 1);
3171
3172        wb.set_custom_property("Key", crate::doc_props::CustomPropertyValue::Int(1));
3173
3174        let ids: std::collections::HashSet<&str> = wb
3175            .package_rels
3176            .relationships
3177            .iter()
3178            .map(|rel| rel.id.as_str())
3179            .collect();
3180        assert_eq!(ids.len(), wb.package_rels.relationships.len());
3181        assert!(wb
3182            .package_rels
3183            .relationships
3184            .iter()
3185            .any(|rel| rel.rel_type == rel_types::CUSTOM_PROPERTIES));
3186    }
3187
3188    #[test]
3189    fn test_custom_property_crud() {
3190        let mut wb = Workbook::new();
3191
3192        // Set
3193        wb.set_custom_property(
3194            "Project",
3195            crate::doc_props::CustomPropertyValue::String("SheetKit".to_string()),
3196        );
3197
3198        // Get
3199        let val = wb.get_custom_property("Project");
3200        assert_eq!(
3201            val,
3202            Some(crate::doc_props::CustomPropertyValue::String(
3203                "SheetKit".to_string()
3204            ))
3205        );
3206
3207        // Update
3208        wb.set_custom_property(
3209            "Project",
3210            crate::doc_props::CustomPropertyValue::String("Updated".to_string()),
3211        );
3212        let val = wb.get_custom_property("Project");
3213        assert_eq!(
3214            val,
3215            Some(crate::doc_props::CustomPropertyValue::String(
3216                "Updated".to_string()
3217            ))
3218        );
3219
3220        // Delete
3221        assert!(wb.delete_custom_property("Project"));
3222        assert!(wb.get_custom_property("Project").is_none());
3223        assert!(!wb.delete_custom_property("Project")); // already gone
3224    }
3225
3226    #[test]
3227    fn test_doc_props_save_open_roundtrip() {
3228        let dir = TempDir::new().unwrap();
3229        let path = dir.path().join("doc_props.xlsx");
3230
3231        let mut wb = Workbook::new();
3232        wb.set_doc_props(crate::doc_props::DocProperties {
3233            title: Some("Test Title".to_string()),
3234            creator: Some("Test Author".to_string()),
3235            created: Some("2024-01-01T00:00:00Z".to_string()),
3236            ..Default::default()
3237        });
3238        wb.set_app_props(crate::doc_props::AppProperties {
3239            application: Some("SheetKit".to_string()),
3240            company: Some("TestCorp".to_string()),
3241            ..Default::default()
3242        });
3243        wb.set_custom_property("Version", crate::doc_props::CustomPropertyValue::Int(42));
3244        wb.save(&path).unwrap();
3245
3246        let wb2 = Workbook::open(&path).unwrap();
3247        let doc = wb2.get_doc_props();
3248        assert_eq!(doc.title.as_deref(), Some("Test Title"));
3249        assert_eq!(doc.creator.as_deref(), Some("Test Author"));
3250        assert_eq!(doc.created.as_deref(), Some("2024-01-01T00:00:00Z"));
3251
3252        let app = wb2.get_app_props();
3253        assert_eq!(app.application.as_deref(), Some("SheetKit"));
3254        assert_eq!(app.company.as_deref(), Some("TestCorp"));
3255
3256        let custom = wb2.get_custom_property("Version");
3257        assert_eq!(custom, Some(crate::doc_props::CustomPropertyValue::Int(42)));
3258    }
3259
3260    #[test]
3261    fn test_open_without_doc_props() {
3262        // A newly created workbook saved without setting doc props should
3263        // still open gracefully (core/app/custom properties are all None).
3264        let dir = TempDir::new().unwrap();
3265        let path = dir.path().join("no_props.xlsx");
3266
3267        let wb = Workbook::new();
3268        wb.save(&path).unwrap();
3269
3270        let wb2 = Workbook::open(&path).unwrap();
3271        let doc = wb2.get_doc_props();
3272        assert!(doc.title.is_none());
3273        assert!(doc.creator.is_none());
3274
3275        let app = wb2.get_app_props();
3276        assert!(app.application.is_none());
3277
3278        assert!(wb2.get_custom_property("anything").is_none());
3279    }
3280
3281    #[test]
3282    fn test_custom_property_multiple_types() {
3283        let mut wb = Workbook::new();
3284
3285        wb.set_custom_property(
3286            "StringProp",
3287            crate::doc_props::CustomPropertyValue::String("hello".to_string()),
3288        );
3289        wb.set_custom_property("IntProp", crate::doc_props::CustomPropertyValue::Int(-7));
3290        wb.set_custom_property(
3291            "FloatProp",
3292            crate::doc_props::CustomPropertyValue::Float(3.15),
3293        );
3294        wb.set_custom_property(
3295            "BoolProp",
3296            crate::doc_props::CustomPropertyValue::Bool(true),
3297        );
3298        wb.set_custom_property(
3299            "DateProp",
3300            crate::doc_props::CustomPropertyValue::DateTime("2024-01-01T00:00:00Z".to_string()),
3301        );
3302
3303        assert_eq!(
3304            wb.get_custom_property("StringProp"),
3305            Some(crate::doc_props::CustomPropertyValue::String(
3306                "hello".to_string()
3307            ))
3308        );
3309        assert_eq!(
3310            wb.get_custom_property("IntProp"),
3311            Some(crate::doc_props::CustomPropertyValue::Int(-7))
3312        );
3313        assert_eq!(
3314            wb.get_custom_property("FloatProp"),
3315            Some(crate::doc_props::CustomPropertyValue::Float(3.15))
3316        );
3317        assert_eq!(
3318            wb.get_custom_property("BoolProp"),
3319            Some(crate::doc_props::CustomPropertyValue::Bool(true))
3320        );
3321        assert_eq!(
3322            wb.get_custom_property("DateProp"),
3323            Some(crate::doc_props::CustomPropertyValue::DateTime(
3324                "2024-01-01T00:00:00Z".to_string()
3325            ))
3326        );
3327    }
3328
3329    #[test]
3330    fn test_doc_props_default_values() {
3331        let wb = Workbook::new();
3332        let doc = wb.get_doc_props();
3333        assert!(doc.title.is_none());
3334        assert!(doc.subject.is_none());
3335        assert!(doc.creator.is_none());
3336        assert!(doc.keywords.is_none());
3337        assert!(doc.description.is_none());
3338        assert!(doc.last_modified_by.is_none());
3339        assert!(doc.revision.is_none());
3340        assert!(doc.created.is_none());
3341        assert!(doc.modified.is_none());
3342        assert!(doc.category.is_none());
3343        assert!(doc.content_status.is_none());
3344
3345        let app = wb.get_app_props();
3346        assert!(app.application.is_none());
3347        assert!(app.doc_security.is_none());
3348        assert!(app.company.is_none());
3349        assert!(app.app_version.is_none());
3350        assert!(app.manager.is_none());
3351        assert!(app.template.is_none());
3352    }
3353
3354    #[test]
3355    fn test_lazy_get_doc_properties_without_mutation() {
3356        let mut wb = Workbook::new();
3357        wb.set_doc_props(crate::doc_props::DocProperties {
3358            title: Some("Deferred Title".to_string()),
3359            creator: Some("Deferred Author".to_string()),
3360            ..Default::default()
3361        });
3362        wb.set_app_props(crate::doc_props::AppProperties {
3363            company: Some("Deferred Corp".to_string()),
3364            application: Some("SheetKit".to_string()),
3365            ..Default::default()
3366        });
3367        wb.set_custom_property(
3368            "DeferredVersion",
3369            crate::doc_props::CustomPropertyValue::Int(7),
3370        );
3371        let buf = wb.save_to_buffer().unwrap();
3372
3373        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
3374        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
3375
3376        let doc = wb2.get_doc_props();
3377        assert_eq!(doc.title.as_deref(), Some("Deferred Title"));
3378        assert_eq!(doc.creator.as_deref(), Some("Deferred Author"));
3379
3380        let app = wb2.get_app_props();
3381        assert_eq!(app.company.as_deref(), Some("Deferred Corp"));
3382        assert_eq!(app.application.as_deref(), Some("SheetKit"));
3383
3384        assert_eq!(
3385            wb2.get_custom_property("DeferredVersion"),
3386            Some(crate::doc_props::CustomPropertyValue::Int(7))
3387        );
3388    }
3389
3390    #[test]
3391    fn test_add_sparkline_and_get_sparklines() {
3392        let mut wb = Workbook::new();
3393        let config = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B1");
3394        wb.add_sparkline("Sheet1", &config).unwrap();
3395
3396        let sparklines = wb.get_sparklines("Sheet1").unwrap();
3397        assert_eq!(sparklines.len(), 1);
3398        assert_eq!(sparklines[0].data_range, "Sheet1!A1:A10");
3399        assert_eq!(sparklines[0].location, "B1");
3400    }
3401
3402    #[test]
3403    fn test_add_multiple_sparklines_to_same_sheet() {
3404        let mut wb = Workbook::new();
3405        let config1 = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B1");
3406        let config2 = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B2");
3407        let mut config3 = crate::sparkline::SparklineConfig::new("Sheet1!C1:C10", "D1");
3408        config3.sparkline_type = crate::sparkline::SparklineType::Column;
3409
3410        wb.add_sparkline("Sheet1", &config1).unwrap();
3411        wb.add_sparkline("Sheet1", &config2).unwrap();
3412        wb.add_sparkline("Sheet1", &config3).unwrap();
3413
3414        let sparklines = wb.get_sparklines("Sheet1").unwrap();
3415        assert_eq!(sparklines.len(), 3);
3416        assert_eq!(
3417            sparklines[2].sparkline_type,
3418            crate::sparkline::SparklineType::Column
3419        );
3420    }
3421
3422    #[test]
3423    fn test_remove_sparkline_by_location() {
3424        let mut wb = Workbook::new();
3425        let config1 = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B1");
3426        let config2 = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B2");
3427        wb.add_sparkline("Sheet1", &config1).unwrap();
3428        wb.add_sparkline("Sheet1", &config2).unwrap();
3429
3430        wb.remove_sparkline("Sheet1", "B1").unwrap();
3431
3432        let sparklines = wb.get_sparklines("Sheet1").unwrap();
3433        assert_eq!(sparklines.len(), 1);
3434        assert_eq!(sparklines[0].location, "B2");
3435    }
3436
3437    #[test]
3438    fn test_remove_nonexistent_sparkline_returns_error() {
3439        let mut wb = Workbook::new();
3440        let result = wb.remove_sparkline("Sheet1", "Z99");
3441        assert!(result.is_err());
3442    }
3443
3444    #[test]
3445    fn test_sparkline_on_nonexistent_sheet_returns_error() {
3446        let mut wb = Workbook::new();
3447        let config = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B1");
3448        let result = wb.add_sparkline("NoSuchSheet", &config);
3449        assert!(result.is_err());
3450        assert!(matches!(result.unwrap_err(), Error::SheetNotFound { .. }));
3451
3452        let result = wb.get_sparklines("NoSuchSheet");
3453        assert!(result.is_err());
3454    }
3455
3456    #[test]
3457    fn test_sparkline_save_open_roundtrip() {
3458        let dir = TempDir::new().unwrap();
3459        let path = dir.path().join("sparkline_roundtrip.xlsx");
3460
3461        let mut wb = Workbook::new();
3462        for i in 1..=10 {
3463            wb.set_cell_value(
3464                "Sheet1",
3465                &format!("A{i}"),
3466                CellValue::Number(i as f64 * 10.0),
3467            )
3468            .unwrap();
3469        }
3470
3471        let mut config = crate::sparkline::SparklineConfig::new("Sheet1!A1:A10", "B1");
3472        config.sparkline_type = crate::sparkline::SparklineType::Column;
3473        config.markers = true;
3474        config.high_point = true;
3475        config.line_weight = Some(1.5);
3476
3477        wb.add_sparkline("Sheet1", &config).unwrap();
3478
3479        let config2 = crate::sparkline::SparklineConfig::new("Sheet1!A1:A5", "C1");
3480        wb.add_sparkline("Sheet1", &config2).unwrap();
3481
3482        wb.save(&path).unwrap();
3483
3484        let opts = OpenOptions::new()
3485            .read_mode(ReadMode::Eager)
3486            .aux_parts(AuxParts::EagerLoad);
3487        let wb2 = Workbook::open_with_options(&path, &opts).unwrap();
3488        let sparklines = wb2.get_sparklines("Sheet1").unwrap();
3489        assert_eq!(sparklines.len(), 2);
3490        assert_eq!(sparklines[0].data_range, "Sheet1!A1:A10");
3491        assert_eq!(sparklines[0].location, "B1");
3492        assert_eq!(
3493            sparklines[0].sparkline_type,
3494            crate::sparkline::SparklineType::Column
3495        );
3496        assert!(sparklines[0].markers);
3497        assert!(sparklines[0].high_point);
3498        assert_eq!(sparklines[0].line_weight, Some(1.5));
3499        assert_eq!(sparklines[1].data_range, "Sheet1!A1:A5");
3500        assert_eq!(sparklines[1].location, "C1");
3501    }
3502
3503    #[test]
3504    fn lazy_sparklines_match_eager_and_preserve_existing_configs_on_mutation() {
3505        let mut source = Workbook::new();
3506        let mut existing = crate::sparkline::SparklineConfig::new("Sheet1!A1:A3", "B1");
3507        existing.sparkline_type = crate::sparkline::SparklineType::Column;
3508        existing.markers = true;
3509        existing.line_weight = Some(1.5);
3510        source.add_sparkline("Sheet1", &existing).unwrap();
3511        let bytes = source.save_to_buffer().unwrap();
3512
3513        let eager_options = OpenOptions::new()
3514            .read_mode(ReadMode::Eager)
3515            .aux_parts(AuxParts::EagerLoad);
3516        let eager = Workbook::open_from_buffer_with_options(&bytes, &eager_options).unwrap();
3517        let mut lazy = Workbook::open_from_buffer(&bytes).unwrap();
3518        let lazy_configs = lazy.get_sparklines("Sheet1").unwrap();
3519        let eager_configs = eager.get_sparklines("Sheet1").unwrap();
3520        assert_eq!(lazy_configs.len(), 1);
3521        assert_eq!(lazy_configs[0].data_range, eager_configs[0].data_range);
3522        assert_eq!(lazy_configs[0].location, eager_configs[0].location);
3523        assert_eq!(
3524            lazy_configs[0].sparkline_type,
3525            eager_configs[0].sparkline_type
3526        );
3527        assert_eq!(lazy_configs[0].markers, eager_configs[0].markers);
3528        assert_eq!(lazy_configs[0].line_weight, eager_configs[0].line_weight);
3529
3530        let added = crate::sparkline::SparklineConfig::new("Sheet1!C1:C3", "D1");
3531        lazy.add_sparkline("Sheet1", &added).unwrap();
3532        let reopened = Workbook::open_from_buffer(&lazy.save_to_buffer().unwrap()).unwrap();
3533        let configs = reopened.get_sparklines("Sheet1").unwrap();
3534        assert_eq!(configs.len(), 2);
3535        assert_eq!(configs[0].data_range, existing.data_range);
3536        assert_eq!(configs[0].location, existing.location);
3537        assert_eq!(configs[0].sparkline_type, existing.sparkline_type);
3538        assert_eq!(configs[0].markers, existing.markers);
3539        assert_eq!(configs[0].line_weight, existing.line_weight);
3540        assert_eq!(configs[1].data_range, added.data_range);
3541        assert_eq!(configs[1].location, added.location);
3542
3543        let mut lazy = Workbook::open_from_buffer(&bytes).unwrap();
3544        lazy.remove_sparkline("Sheet1", "B1").unwrap();
3545        assert!(lazy.get_sparklines("Sheet1").unwrap().is_empty());
3546        let reopened = Workbook::open_from_buffer(&lazy.save_to_buffer().unwrap()).unwrap();
3547        assert!(reopened.get_sparklines("Sheet1").unwrap().is_empty());
3548    }
3549
3550    #[test]
3551    fn test_sparkline_empty_sheet_returns_empty_vec() {
3552        let wb = Workbook::new();
3553        let sparklines = wb.get_sparklines("Sheet1").unwrap();
3554        assert!(sparklines.is_empty());
3555    }
3556
3557    fn make_table_config(cols: &[&str]) -> crate::table::TableConfig {
3558        let end = crate::utils::cell_ref::coordinates_to_cell_name(cols.len() as u32, 10)
3559            .expect("test table columns must fit within worksheet bounds");
3560        crate::table::TableConfig {
3561            name: "Table1".to_string(),
3562            display_name: "Table1".to_string(),
3563            range: format!("A1:{end}"),
3564            columns: cols
3565                .iter()
3566                .map(|c| crate::table::TableColumn {
3567                    name: c.to_string(),
3568                    totals_row_function: None,
3569                    totals_row_label: None,
3570                })
3571                .collect(),
3572            ..crate::table::TableConfig::default()
3573        }
3574    }
3575
3576    fn make_slicer_workbook() -> Workbook {
3577        let mut wb = Workbook::new();
3578        let table = make_table_config(&["Status", "Region", "Category", "Col1", "Col2"]);
3579        wb.add_table("Sheet1", &table).unwrap();
3580        wb
3581    }
3582
3583    fn make_slicer_config(name: &str, col: &str) -> crate::slicer::SlicerConfig {
3584        crate::slicer::SlicerConfig {
3585            name: name.to_string(),
3586            cell: "F1".to_string(),
3587            table_name: "Table1".to_string(),
3588            column_name: col.to_string(),
3589            caption: None,
3590            style: None,
3591            width: None,
3592            height: None,
3593            show_caption: None,
3594            column_count: None,
3595        }
3596    }
3597
3598    #[test]
3599    fn test_add_slicer_basic() {
3600        let mut wb = make_slicer_workbook();
3601        let config = make_slicer_config("StatusFilter", "Status");
3602        wb.add_slicer("Sheet1", &config).unwrap();
3603
3604        let slicers = wb.get_slicers("Sheet1").unwrap();
3605        assert_eq!(slicers.len(), 1);
3606        assert_eq!(slicers[0].name, "StatusFilter");
3607        assert_eq!(slicers[0].column_name, "Status");
3608        assert_eq!(slicers[0].table_name, "Table1");
3609    }
3610
3611    #[test]
3612    fn test_add_slicer_with_options() {
3613        let mut wb = make_slicer_workbook();
3614        let config = crate::slicer::SlicerConfig {
3615            name: "RegionSlicer".to_string(),
3616            cell: "G2".to_string(),
3617            table_name: "Table1".to_string(),
3618            column_name: "Region".to_string(),
3619            caption: Some("Filter by Region".to_string()),
3620            style: Some("SlicerStyleLight1".to_string()),
3621            width: Some(300),
3622            height: Some(250),
3623            show_caption: Some(true),
3624            column_count: Some(2),
3625        };
3626        wb.add_slicer("Sheet1", &config).unwrap();
3627
3628        let slicers = wb.get_slicers("Sheet1").unwrap();
3629        assert_eq!(slicers.len(), 1);
3630        assert_eq!(slicers[0].caption, "Filter by Region");
3631        assert_eq!(slicers[0].style, Some("SlicerStyleLight1".to_string()));
3632    }
3633
3634    #[test]
3635    fn test_add_slicer_duplicate_name() {
3636        let mut wb = make_slicer_workbook();
3637        let config = make_slicer_config("MySlicer", "Status");
3638        wb.add_slicer("Sheet1", &config).unwrap();
3639
3640        let result = wb.add_slicer("Sheet1", &config);
3641        assert!(result.is_err());
3642        assert!(result.unwrap_err().to_string().contains("already exists"));
3643    }
3644
3645    #[test]
3646    fn test_add_slicer_invalid_sheet() {
3647        let mut wb = make_slicer_workbook();
3648        let config = make_slicer_config("S1", "Status");
3649        let result = wb.add_slicer("NoSuchSheet", &config);
3650        assert!(result.is_err());
3651    }
3652
3653    #[test]
3654    fn test_add_slicer_table_not_found() {
3655        let mut wb = Workbook::new();
3656        let config = crate::slicer::SlicerConfig {
3657            name: "S1".to_string(),
3658            cell: "F1".to_string(),
3659            table_name: "NonExistent".to_string(),
3660            column_name: "Col".to_string(),
3661            caption: None,
3662            style: None,
3663            width: None,
3664            height: None,
3665            show_caption: None,
3666            column_count: None,
3667        };
3668        let result = wb.add_slicer("Sheet1", &config);
3669        assert!(result.is_err());
3670        assert!(matches!(result.unwrap_err(), Error::TableNotFound { .. }));
3671    }
3672
3673    #[test]
3674    fn test_add_slicer_column_not_found() {
3675        let mut wb = make_slicer_workbook();
3676        let config = crate::slicer::SlicerConfig {
3677            name: "S1".to_string(),
3678            cell: "F1".to_string(),
3679            table_name: "Table1".to_string(),
3680            column_name: "NonExistentColumn".to_string(),
3681            caption: None,
3682            style: None,
3683            width: None,
3684            height: None,
3685            show_caption: None,
3686            column_count: None,
3687        };
3688        let result = wb.add_slicer("Sheet1", &config);
3689        assert!(result.is_err());
3690        assert!(matches!(
3691            result.unwrap_err(),
3692            Error::TableColumnNotFound { .. }
3693        ));
3694    }
3695
3696    #[test]
3697    fn test_add_slicer_correct_table_id_and_column() {
3698        let mut wb = make_slicer_workbook();
3699        let config = make_slicer_config("RegFilter", "Region");
3700        wb.add_slicer("Sheet1", &config).unwrap();
3701
3702        // Region is at index 1 (0-based), so column should be 2 (1-based).
3703        let cache = &wb.slicer_caches[0].1;
3704        let tsc = cache.table_slicer_cache.as_ref().unwrap();
3705        assert_eq!(tsc.table_id, 1);
3706        assert_eq!(tsc.column, 2);
3707    }
3708
3709    #[test]
3710    fn test_get_slicers_resolves_table_name() {
3711        let mut wb = make_slicer_workbook();
3712        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Category"))
3713            .unwrap();
3714
3715        let slicers = wb.get_slicers("Sheet1").unwrap();
3716        assert_eq!(slicers.len(), 1);
3717        assert_eq!(slicers[0].table_name, "Table1");
3718        assert_eq!(slicers[0].column_name, "Category");
3719    }
3720
3721    #[test]
3722    fn test_get_slicers_resolves_nonsequential_table_column_id() {
3723        let mut wb = make_slicer_workbook();
3724        wb.tables[0].1.table_columns.columns[2].id = 17;
3725        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Category"))
3726            .unwrap();
3727
3728        let slicers = wb.get_slicers("Sheet1").unwrap();
3729        assert_eq!(slicers[0].column_name, "Category");
3730        assert_eq!(
3731            wb.slicer_caches[0]
3732                .1
3733                .table_slicer_cache
3734                .as_ref()
3735                .unwrap()
3736                .column,
3737            17
3738        );
3739    }
3740
3741    #[test]
3742    fn test_get_slicers_empty() {
3743        let wb = Workbook::new();
3744        let slicers = wb.get_slicers("Sheet1").unwrap();
3745        assert!(slicers.is_empty());
3746    }
3747
3748    #[test]
3749    fn test_delete_slicer() {
3750        let mut wb = make_slicer_workbook();
3751        let config = make_slicer_config("S1", "Status");
3752        wb.add_slicer("Sheet1", &config).unwrap();
3753
3754        assert_eq!(wb.get_slicers("Sheet1").unwrap().len(), 1);
3755
3756        wb.delete_slicer("Sheet1", "S1").unwrap();
3757        assert_eq!(wb.get_slicers("Sheet1").unwrap().len(), 0);
3758    }
3759
3760    #[test]
3761    fn test_delete_slicer_not_found() {
3762        let mut wb = Workbook::new();
3763        let result = wb.delete_slicer("Sheet1", "NonExistent");
3764        assert!(result.is_err());
3765        assert!(result.unwrap_err().to_string().contains("not found"));
3766    }
3767
3768    #[test]
3769    fn test_delete_slicer_rejects_name_from_another_sheet_without_mutation() {
3770        let mut wb = make_slicer_workbook();
3771        wb.new_sheet("Other").unwrap();
3772        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Status"))
3773            .unwrap();
3774        let before = wb.save_to_buffer().unwrap();
3775
3776        let result = wb.delete_slicer("Other", "S1");
3777
3778        assert!(matches!(result, Err(Error::SlicerNotFound { .. })));
3779        assert_eq!(wb.get_slicers("Sheet1").unwrap().len(), 1);
3780        assert_eq!(wb.save_to_buffer().unwrap(), before);
3781    }
3782
3783    #[test]
3784    fn test_delete_slicer_cleans_content_types() {
3785        let mut wb = make_slicer_workbook();
3786        let config = make_slicer_config("S1", "Status");
3787        wb.add_slicer("Sheet1", &config).unwrap();
3788
3789        let ct_before = wb.content_types.overrides.len();
3790        wb.delete_slicer("Sheet1", "S1").unwrap();
3791        let ct_after = wb.content_types.overrides.len();
3792
3793        // The slicer, cache, and now-empty drawing overrides are removed.
3794        assert_eq!(ct_before - ct_after, 3);
3795    }
3796
3797    #[test]
3798    fn test_delete_slicer_cleans_workbook_rels() {
3799        let mut wb = make_slicer_workbook();
3800        let config = make_slicer_config("S1", "Status");
3801        wb.add_slicer("Sheet1", &config).unwrap();
3802
3803        let has_cache_rel = wb
3804            .workbook_rels
3805            .relationships
3806            .iter()
3807            .any(|r| r.rel_type == rel_types::SLICER_CACHE);
3808        assert!(has_cache_rel);
3809
3810        wb.delete_slicer("Sheet1", "S1").unwrap();
3811
3812        let has_cache_rel = wb
3813            .workbook_rels
3814            .relationships
3815            .iter()
3816            .any(|r| r.rel_type == rel_types::SLICER_CACHE);
3817        assert!(!has_cache_rel);
3818    }
3819
3820    #[test]
3821    fn test_delete_slicer_preserves_a_cache_used_by_another_view() {
3822        let mut wb = make_slicer_workbook();
3823        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Status"))
3824            .unwrap();
3825        wb.add_slicer("Sheet1", &make_slicer_config("S2", "Region"))
3826            .unwrap();
3827        let shared_cache = wb.slicer_defs[0].1.slicers[0].cache.clone();
3828        wb.slicer_defs[1].1.slicers[0].cache = shared_cache.clone();
3829
3830        wb.delete_slicer("Sheet1", "S1").unwrap();
3831
3832        assert!(wb
3833            .slicer_caches
3834            .iter()
3835            .any(|(_, cache)| cache.name == shared_cache));
3836        assert!(wb
3837            .workbook_rels
3838            .relationships
3839            .iter()
3840            .any(|relationship| relationship.rel_type == rel_types::SLICER_CACHE));
3841        assert!(wb.workbook_xml.defined_names.as_ref().is_some_and(|names| {
3842            names
3843                .defined_names
3844                .iter()
3845                .any(|defined| defined.name == shared_cache)
3846        }));
3847    }
3848
3849    #[test]
3850    fn test_multiple_slicers_on_same_sheet() {
3851        let mut wb = make_slicer_workbook();
3852        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Col1"))
3853            .unwrap();
3854        wb.add_slicer("Sheet1", &make_slicer_config("S2", "Col2"))
3855            .unwrap();
3856
3857        let slicers = wb.get_slicers("Sheet1").unwrap();
3858        assert_eq!(slicers.len(), 2);
3859    }
3860
3861    #[test]
3862    fn test_slicer_roundtrip() {
3863        let tmp = TempDir::new().unwrap();
3864        let path = tmp.path().join("slicer_rt.xlsx");
3865
3866        let mut wb = make_slicer_workbook();
3867        wb.add_slicer("Sheet1", &make_slicer_config("MySlicer", "Category"))
3868            .unwrap();
3869        wb.save(&path).unwrap();
3870
3871        let wb2 = Workbook::open(&path).unwrap();
3872        let slicers = wb2.get_slicers("Sheet1").unwrap();
3873        assert_eq!(slicers.len(), 1);
3874        assert_eq!(slicers[0].name, "MySlicer");
3875        assert_eq!(slicers[0].column_name, "Category");
3876        assert_eq!(slicers[0].table_name, "Table1");
3877    }
3878
3879    #[test]
3880    fn test_lazy_get_slicers_without_mutation() {
3881        let mut wb = make_slicer_workbook();
3882        wb.add_slicer("Sheet1", &make_slicer_config("LazySlicer", "Status"))
3883            .unwrap();
3884        let buf = wb.save_to_buffer().unwrap();
3885
3886        let opts = OpenOptions::new().read_mode(ReadMode::Lazy);
3887        let wb2 = Workbook::open_from_buffer_with_options(&buf, &opts).unwrap();
3888        let slicers = wb2.get_slicers("Sheet1").unwrap();
3889        assert_eq!(slicers.len(), 1);
3890        assert_eq!(slicers[0].name, "LazySlicer");
3891        assert_eq!(slicers[0].column_name, "Status");
3892        assert_eq!(slicers[0].table_name, "Table1");
3893    }
3894
3895    #[test]
3896    fn test_slicer_content_types_added() {
3897        let mut wb = make_slicer_workbook();
3898        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Status"))
3899            .unwrap();
3900
3901        let has_slicer_ct = wb
3902            .content_types
3903            .overrides
3904            .iter()
3905            .any(|o| o.content_type == mime_types::SLICER);
3906        let has_cache_ct = wb
3907            .content_types
3908            .overrides
3909            .iter()
3910            .any(|o| o.content_type == mime_types::SLICER_CACHE);
3911
3912        assert!(has_slicer_ct);
3913        assert!(has_cache_ct);
3914    }
3915
3916    #[test]
3917    fn test_slicer_worksheet_rels_added() {
3918        let mut wb = make_slicer_workbook();
3919        wb.add_slicer("Sheet1", &make_slicer_config("S1", "Status"))
3920            .unwrap();
3921
3922        let rels = wb.worksheet_rels.get(&0).unwrap();
3923        let has_slicer_rel = rels
3924            .relationships
3925            .iter()
3926            .any(|r| r.rel_type == rel_types::SLICER);
3927        assert!(has_slicer_rel);
3928    }
3929
3930    #[test]
3931    fn test_slicer_error_display() {
3932        let err = Error::SlicerNotFound {
3933            name: "Missing".to_string(),
3934        };
3935        assert_eq!(err.to_string(), "slicer 'Missing' not found");
3936
3937        let err = Error::SlicerAlreadyExists {
3938            name: "Dup".to_string(),
3939        };
3940        assert_eq!(err.to_string(), "slicer 'Dup' already exists");
3941    }
3942
3943    #[test]
3944    fn test_add_table_and_get_tables() {
3945        let mut wb = Workbook::new();
3946        let table = make_table_config(&["Name", "Age", "City"]);
3947        wb.add_table("Sheet1", &table).unwrap();
3948
3949        let tables = wb.get_tables("Sheet1").unwrap();
3950        assert_eq!(tables.len(), 1);
3951        assert_eq!(tables[0].name, "Table1");
3952        assert_eq!(tables[0].columns, vec!["Name", "Age", "City"]);
3953    }
3954
3955    #[test]
3956    fn test_add_table_duplicate_name() {
3957        let mut wb = Workbook::new();
3958        let table = make_table_config(&["Col"]);
3959        wb.add_table("Sheet1", &table).unwrap();
3960
3961        let result = wb.add_table("Sheet1", &table);
3962        assert!(result.is_err());
3963        assert!(result.unwrap_err().to_string().contains("already exists"));
3964    }
3965
3966    #[test]
3967    fn test_slicer_can_be_placed_away_from_its_source_table() {
3968        let mut wb = Workbook::new();
3969        wb.new_sheet("Sheet2").unwrap();
3970        let table = make_table_config(&["Status"]);
3971        wb.add_table("Sheet2", &table).unwrap();
3972
3973        let config = make_slicer_config("S1", "Status");
3974        wb.add_slicer("Sheet1", &config).unwrap();
3975        assert_eq!(wb.get_slicers("Sheet1").unwrap().len(), 1);
3976    }
3977}