mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 02:33:55 -06:00
+4
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
|
||||
@@ -189,6 +189,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-16 | The web app keeps its preferences between visits (#1562): theme (dark mode), interface size, language, editing options and the rest of what the desktop app saves in `ui.json` and `prefs.json` are kept in the browser's `localStorage`, written as soon as they change |
|
||||
| 2026-10-16 | Memory: the interface and script fallback fonts are read once per run and shared with egui instead of copied into it: an empty workbook settles at 158 MB instead of 258 MB on macOS |
|
||||
| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) |
|
||||
| 2026-10-15 | XIRR matches Excel's solver bit for bit on ordinary flows (its bisection answer, about 1e-8 from the exact root, instead of the exact root), with known differences in some `#NUM!` cases; IRR uses Newton on the discount factor like Excel (`#NUM!` where Excel gives up) |
|
||||
| 2026-10-15 | File › Options › Formulas: Maximum Iterations and Maximum Change fields for iterative calculation, disabled while it is off, with Excel's limits (1 to 32767, 0 or more) |
|
||||
| 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format |
|
||||
| 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) |
|
||||
@@ -292,6 +293,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-16 | minor | Progress log: chart data outline in three colours, dragged from its corners (#4389, #4390) |
|
||||
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; the roadmap qualifies XIRR's known `#NUM!` differences |
|
||||
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
|
||||
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
|
||||
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
|
||||
@@ -332,6 +334,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-10-16 | minor | Progress log: floating pictures' textures bounded and kept per workbook |
|
||||
| 2026-10-16 | trivial | Progress log: web preferences kept between visits (#1562) |
|
||||
| 2026-10-16 | minor | Progress log: interface fonts held once instead of twice |
|
||||
| 2026-10-15 | trivial | Progress log: XIRR and IRR follow Excel's solvers |
|
||||
| 2026-10-15 | trivial | Progress log: XLSX PivotTables on a data connection or the Data Model kept on save |
|
||||
| 2026-10-15 | minor | Progress log: F8 and Shift+F8 selection modes |
|
||||
| 2026-10-14 | minor | Progress log: sorts order numbers exactly |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::sort::sort_key;
|
||||
use super::{
|
||||
AutoFilter, CellRef, EngineError, FilterCriterion, Json, Ordering, RangeRef, Result, Session, Sheet, Value, Workbook, bad, bool_param, col_param,
|
||||
current_region, data_target, edit, json,
|
||||
data_target, edit, json,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -15,14 +15,63 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let has = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.autofilter.is_some());
|
||||
let in_table = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.table_at(at).map(|t| t.name.clone()));
|
||||
if let Some(name) = in_table {
|
||||
// An explicit range over part of the table is refused, as when installing a filter on it.
|
||||
if p.get("range").is_some()
|
||||
&& let Some(sh) = s.doc()?.wb.sheet(sheet)
|
||||
&& let Some(t) = sh.tables.iter().find(|t| t.name == name)
|
||||
&& t.range.intersects(&r)
|
||||
&& !(t.header_row
|
||||
&& t.range.start.row == r.start.row
|
||||
&& t.range.contains(r.start)
|
||||
&& t.range.contains(r.end)
|
||||
&& r.start.col == t.range.start.col
|
||||
&& r.end.col == t.range.end.col
|
||||
&& t.data_range().is_none_or(|data| r.end.row >= data.end.row))
|
||||
{
|
||||
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
|
||||
}
|
||||
return edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let filtered: Vec<u32> = sh.rows.keys().copied().filter(|r| sh.is_row_filtered(*r)).collect();
|
||||
let mut cleared = false;
|
||||
if let Some(t) = sh.tables.iter_mut().find(|t| t.name == name) {
|
||||
t.filter_button = !t.filter_button;
|
||||
if !t.filter_button {
|
||||
t.filter.clear();
|
||||
// The sheet AutoFilter hosted on this table's header row is the table's filter too.
|
||||
cleared = sh.autofilter.as_ref().is_some_and(|af| af.range.start.row == t.range.start.row && af.range.intersects(&t.range));
|
||||
}
|
||||
}
|
||||
if cleared {
|
||||
sh.autofilter = None;
|
||||
for r in filtered {
|
||||
if let Some(info) = sh.rows.get_mut(&r) {
|
||||
info.hidden = false;
|
||||
}
|
||||
}
|
||||
// Rows another table's criteria hide stay hidden: evaluate each such table's saved
|
||||
// criteria through the live filter, then hide the union once (a later table would
|
||||
// unhide what an earlier one excluded) and take the filter off again.
|
||||
let others: Vec<(RangeRef, Vec<(u32, FilterCriterion)>)> =
|
||||
sh.tables.iter().filter(|t| !t.filter.is_empty()).map(|t| (t.range, t.filter.clone())).collect();
|
||||
let mut excluded: std::collections::HashSet<u32> = std::collections::HashSet::new();
|
||||
for (range, criteria) in others {
|
||||
if let Some(sh) = cx.wb.sheet_mut(sheet) {
|
||||
sh.autofilter = Some(AutoFilter { range, criteria });
|
||||
}
|
||||
apply_filter(&mut cx.wb, sheet);
|
||||
if let Some(sh) = cx.wb.sheet(sheet) {
|
||||
excluded.extend((range.start.row.saturating_add(1)..=range.end.row).filter(|r| sh.is_row_hidden(*r)));
|
||||
}
|
||||
}
|
||||
if let Some(sh) = cx.wb.sheet_mut(sheet) {
|
||||
sh.autofilter = None;
|
||||
for r in excluded {
|
||||
sh.rows.entry(r).or_default().hidden = true;
|
||||
}
|
||||
}
|
||||
cx.structural = true;
|
||||
}
|
||||
Ok(Json::Null)
|
||||
});
|
||||
}
|
||||
@@ -45,19 +94,58 @@ pub(super) fn toggle_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
|
||||
/// Turn a sheet AutoFilter on over `p.range`, or over the data range of the selection.
|
||||
///
|
||||
/// A sheet AutoFilter never overlaps a table, because a file can't hold one (Excel refuses
|
||||
/// `Range("A1:C8").AutoFilter` over part of a table, and from a cell outside a table it leaves the
|
||||
/// table's cells out of the region). Inside a table the filter covers the table from its header
|
||||
/// row, which is saved as the table's own filter, and takes over the criteria the table already
|
||||
/// had so there is one filter to save.
|
||||
fn install_filter(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (sheet, mut r) = data_target(s, p, "data.filter")?;
|
||||
// A selected header row filters the data below it (#201).
|
||||
if p.get("range").is_none() && r.height() == 1 {
|
||||
{
|
||||
let d = s.doc()?;
|
||||
let sh = d.wb.active().ok_or(EngineError::NoDocument)?;
|
||||
let below = current_region(sh, r.start).end.row;
|
||||
if below > r.end.row {
|
||||
r = RangeRef::new(r.start, CellRef::new(below, r.end.col));
|
||||
if p.get("range").is_none() && sh.table_at(d.selection.active).is_none() && d.selection.current().is_single() {
|
||||
r = crate::selection::current_region_outside_tables(sh, d.selection.active);
|
||||
}
|
||||
// A selected header row filters the data below it (#201).
|
||||
if p.get("range").is_none() && r.height() == 1 {
|
||||
let region = match sh.table_at(r.start) {
|
||||
Some(t) => t.data_range().map(|dr| RangeRef::new(t.range.start, dr.end)).unwrap_or(t.range),
|
||||
None => crate::selection::current_region_outside_tables(sh, r.start),
|
||||
};
|
||||
if region.end.row > r.end.row {
|
||||
r = RangeRef::new(r.start, CellRef::new(region.end.row, r.end.col));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(sh) = s.doc()?.wb.sheet(sheet) else { return Err(EngineError::NoDocument) };
|
||||
// The table whose header row the filter starts on, when it lies inside that table.
|
||||
let host =
|
||||
sh.tables.iter().position(|t| t.header_row && t.range.start.row == r.start.row && t.range.contains(r.start) && t.range.contains(r.end));
|
||||
if host.is_none() && sh.tables.iter().any(|t| t.range.intersects(&r)) {
|
||||
return Err(bad("data.filter", "a filter range can't overlap a table; filter inside the table instead"));
|
||||
}
|
||||
// A narrower range would leave out the table's criteria on the columns it doesn't cover, and saving would drop them.
|
||||
if let Some(t) = host.and_then(|i| sh.tables.get(i)) {
|
||||
if t.data_range().is_some_and(|data| r.end.row < data.end.row) {
|
||||
return Err(bad("data.filter", "filter the table's full data range"));
|
||||
}
|
||||
let shift = r.start.col.saturating_sub(t.range.start.col);
|
||||
if t.filter.iter().any(|(o, _)| o.checked_sub(shift).is_none_or(|c| c >= r.width())) {
|
||||
return Err(bad("data.filter", "the table is filtered on a column this range leaves out; filter the table's full width"));
|
||||
}
|
||||
}
|
||||
edit(s, |cx| {
|
||||
cx.sheet_mut(sheet)?.autofilter = Some(AutoFilter { range: r, criteria: vec![] });
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let mut criteria = vec![];
|
||||
if let Some(t) = host.and_then(|i| sh.tables.get_mut(i)) {
|
||||
// The criteria are saved with the table only while its filter buttons are on.
|
||||
t.filter_button = true;
|
||||
let shift = r.start.col.saturating_sub(t.range.start.col);
|
||||
criteria = std::mem::take(&mut t.filter).into_iter().filter_map(|(o, c)| Some((o.checked_sub(shift)?, c))).collect();
|
||||
}
|
||||
sh.autofilter = Some(AutoFilter { range: r, criteria });
|
||||
Ok(json!({"filter": true, "range": r.a1()}))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -310,7 +310,40 @@ pub fn jump(sheet: &Sheet, from: CellRef, dr: i64, dc: i64) -> CellRef {
|
||||
|
||||
/// The contiguous data region around `c` (Ctrl+A / Ctrl+Shift+8, AutoSum, sort, tables).
|
||||
pub fn current_region(sheet: &Sheet, c: CellRef) -> RangeRef {
|
||||
let filled = |c: CellRef| sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c);
|
||||
region_where(sheet, c, |_| true)
|
||||
}
|
||||
|
||||
/// The data region a sheet AutoFilter takes from `c`, a cell outside any table: the current
|
||||
/// region, kept off the tables it reaches. Observed in Windows Excel 16 (table B4:C8, text in
|
||||
/// A1:A3, A5:A8 and B3; the current region of A1 is A1:C8): from A1 the filter covers A1:A3, from
|
||||
/// A6 A5:A8, from B3 A1:B3. So the region is cut to the columns on the cell's side of the table
|
||||
/// when the cell is left or right of it, else to the rows above or below, and grown again from
|
||||
/// the cell inside that window.
|
||||
pub fn current_region_outside_tables(sheet: &Sheet, c: CellRef) -> RangeRef {
|
||||
let (mut c0, mut c1, mut r0, mut r1) = (0, MAX_COLS - 1, 0, MAX_ROWS - 1);
|
||||
let mut region = current_region(sheet, c);
|
||||
for _ in 0..=sheet.tables.len() {
|
||||
let Some(t) = sheet.tables.iter().find(|t| t.range.intersects(®ion)) else { break };
|
||||
let t = t.range;
|
||||
if c.col < t.start.col {
|
||||
c1 = c1.min(t.start.col - 1);
|
||||
} else if c.col > t.end.col {
|
||||
c0 = c0.max(t.end.col + 1);
|
||||
} else if c.row < t.start.row {
|
||||
r1 = r1.min(t.start.row - 1);
|
||||
} else if c.row > t.end.row {
|
||||
r0 = r0.max(t.end.row + 1);
|
||||
} else {
|
||||
return RangeRef::cell(c);
|
||||
}
|
||||
region = region_where(sheet, c, |x| x.col >= c0 && x.col <= c1 && x.row >= r0 && x.row <= r1 && sheet.table_at(x).is_none());
|
||||
}
|
||||
region
|
||||
}
|
||||
|
||||
/// The current region around `c`, counting only filled cells that `counts` accepts.
|
||||
fn region_where(sheet: &Sheet, c: CellRef, counts: impl Fn(CellRef) -> bool) -> RangeRef {
|
||||
let filled = |c: CellRef| (sheet.cell(c).is_some_and(gridcraft_model::Cell::has_content) || sheet.spill.contains_key(&c)) && counts(c);
|
||||
// Whether a row (or column) has a filled cell between two columns (rows), inclusive.
|
||||
let row_has = |row: u32, a: u32, b: u32| (a..=b).any(|col| filled(CellRef::new(row, col)));
|
||||
let col_has = |col: u32, a: u32, b: u32| (a..=b).any(|row| filled(CellRef::new(row, col)));
|
||||
|
||||
@@ -2164,7 +2164,7 @@ fn filter_with_a_sheet_prefix_toggles_the_table_at_the_range() {
|
||||
wb.sheet(wb.sheet_index("Prices").unwrap()).unwrap().clone()
|
||||
};
|
||||
assert!(prices(&s).tables[0].filter_button);
|
||||
s.execute("data.filter", json!({"range": "Prices!A2:B3"})).unwrap();
|
||||
s.execute("data.filter", json!({"range": "Prices!A1:B3"})).unwrap();
|
||||
assert!(!prices(&s).tables[0].filter_button);
|
||||
assert!(prices(&s).autofilter.is_none());
|
||||
assert!(s.doc().unwrap().wb.active().unwrap().autofilter.is_none());
|
||||
|
||||
@@ -32,6 +32,7 @@ mod sheet_name_quoting;
|
||||
mod sparse_clear_invalidation;
|
||||
mod stored_list_shape;
|
||||
mod structural_edit_rewrite;
|
||||
mod subtotal_filter_roundtrip;
|
||||
mod table_resize_overlap;
|
||||
mod table_style_looks;
|
||||
mod table_total_row_last_row;
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! SUBTOTAL over filtered rows keeps its value through an XLSX save and reopen.
|
||||
//!
|
||||
//! Excel (observed in Windows Excel 16 with synthetic workbooks) saves rows a filter hides as plain
|
||||
//! `hidden="1"` rows; a hidden row counts as filtered when it lies in an AutoFilter (sheet or table)
|
||||
//! that has criteria. Excel can't hold a sheet AutoFilter that overlaps a table, so GridCraft saves
|
||||
//! a table's filter in the table part and never creates a sheet AutoFilter over part of a table.
|
||||
|
||||
use gridcraft_core::{CellRef, Value};
|
||||
use gridcraft_engine::calc::Calc;
|
||||
use gridcraft_engine::model::Workbook;
|
||||
use gridcraft_engine::{Session, io};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
fn reopened(wb: &Workbook) -> Workbook {
|
||||
let bytes = io::save_bytes(wb, "t.xlsx").unwrap();
|
||||
let (mut back, _) = io::open_bytes("t.xlsx", &bytes).unwrap();
|
||||
Calc::new().recalc_all(&mut back);
|
||||
back
|
||||
}
|
||||
|
||||
/// Every formula value in memory against the same cell after a save and reopen.
|
||||
fn assert_values_survive(wb: &Workbook) {
|
||||
let back = reopened(wb);
|
||||
for (a, b) in wb.sheets.iter().zip(&back.sheets) {
|
||||
for (c, cell) in a.cells.iter() {
|
||||
if cell.formula.is_some() {
|
||||
assert_eq!(cell.value, b.value(c), "{}!{} ({:?})", a.name, c.a1(), cell.formula.as_ref().map(|f| &f.text));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn session(sample: &str, steps: &[(&str, Json)]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"sample": sample})).unwrap();
|
||||
for (id, p) in steps {
|
||||
// A refused step leaves the book as it was; the asserts check what survives.
|
||||
let _ = s.execute(id, p.clone());
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn wb(s: &Session) -> &Workbook {
|
||||
&s.doc().unwrap().wb
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bead_repro_filter_then_replace_on_the_sales_sample() {
|
||||
let s =
|
||||
session("sales", &[("data.filterBy", json!({"column":"G","top":{"count":2}})), ("edit.replace", json!({"all":true,"what":"1","with":""}))]);
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range))));
|
||||
assert_values_survive(wb(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bead_repro_subtotal_then_filter_on_the_grades_sample() {
|
||||
let s = session(
|
||||
"grades",
|
||||
&[
|
||||
("home.insertColumns", json!({})),
|
||||
("data.subtotal", json!({"columns":["G"],"function":"sum","groupBy":"J"})),
|
||||
("data.filterBy", json!({"column":"B","values":["x"]})),
|
||||
],
|
||||
);
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.autofilter.as_ref().is_none_or(|af| !sh.tables.iter().any(|t| t.range.intersects(&af.range))));
|
||||
assert_values_survive(wb(&s));
|
||||
}
|
||||
|
||||
/// A table A1:B7 (Name, Qty = 1, 10, 100...) with SUBTOTAL(9) and SUBTOTAL(109) beside it.
|
||||
fn table_book() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["Name","Qty"],["a",1],["b",10],["c",100],["d",1000],["e",10000],["f",100000]]}))
|
||||
.unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:B7","header":true})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"E1","input":"=SUBTOTAL(9,B2:B7)"})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"E2","input":"=SUBTOTAL(109,B2:B7)"})).unwrap();
|
||||
s.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn e1_e2(wb: &Workbook) -> (Value, Value) {
|
||||
let sh = wb.active().unwrap();
|
||||
(sh.value(CellRef::new(0, 4)), sh.value(CellRef::new(1, 4)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_filter_keeps_subtotal_and_criteria_through_save() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap();
|
||||
// Like Excel, a row hidden by hand inside an active filter range is left out by SUBTOTAL 9 too.
|
||||
s.execute("home.hideRows", json!({"rows":"6:6"})).unwrap();
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(100101.0), Value::Number(100101.0)));
|
||||
assert_values_survive(wb(&s));
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(e1_e2(&back), (Value::Number(100101.0), Value::Number(100101.0)));
|
||||
let t = &back.active().unwrap().tables[0];
|
||||
assert_eq!(t.filter.len(), 1, "the criteria are saved with the table: {:?}", t.filter);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_hidden_by_hand_without_a_filter_still_count_for_subtotal_9() {
|
||||
let mut s = table_book();
|
||||
s.execute("home.hideRows", json!({"rows":"3:3"})).unwrap();
|
||||
s.execute("home.hideRows", json!({"rows":"5:5"})).unwrap();
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(111111.0), Value::Number(110101.0)));
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(e1_e2(&back), (Value::Number(111111.0), Value::Number(110101.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrower_range_inside_a_filtered_table_is_refused_not_dropped() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
let back = reopened(wb(&s));
|
||||
let mut s = Session::new();
|
||||
s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s.execute("selection.set", json!({"cell":"D1"})).unwrap();
|
||||
assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err());
|
||||
assert_eq!(wb(&s).active().unwrap().tables[0].filter.len(), 1, "the table's criteria are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_a_reopened_table_again_keeps_both_criteria() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a","c","e","f"]})).unwrap();
|
||||
let back = reopened(wb(&s));
|
||||
let mut s = Session::new();
|
||||
s.add_document(gridcraft_engine::DocState::new(back, None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"B","custom":{"op":">","value":"50"}})).unwrap();
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.tables[0].filter.is_empty(), "the table's criteria moved into the live filter");
|
||||
assert_eq!(sh.autofilter.as_ref().map(|af| af.criteria.len()), Some(2));
|
||||
assert_eq!(e1_e2(wb(&s)), (Value::Number(110100.0), Value::Number(110100.0)));
|
||||
assert_values_survive(wb(&s));
|
||||
assert_eq!(reopened(wb(&s)).active().unwrap().tables[0].filter.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_filter_from_outside_a_table_leaves_the_table_out() {
|
||||
// Excel: table B4:C8 with text in A1:A3, A5:A8 and B3. AutoFilter from A1 covers A1:A3, from
|
||||
// A6 A5:A8, from B3 A1:B3; an explicit range over part of the table is refused.
|
||||
let layout = || {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["Title"],["x"],["y"]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell":"B3","input":"z"})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"B4","values":[["Name","Qty"],["n5","v5"],["n6","v6"],["n7","v7"],["n8","v8"]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"A5","values":[["a5"],["a6"],["a7"],["a8"]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"B4:C8","header":true})).unwrap();
|
||||
s
|
||||
};
|
||||
for (cell, want) in [("A1", "A1:A3"), ("A6", "A5:A8"), ("B3", "A1:B3")] {
|
||||
let mut s = layout();
|
||||
s.execute("selection.set", json!({"cell": cell})).unwrap();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
let af = wb(&s).active().unwrap().autofilter.clone();
|
||||
assert_eq!(af.map(|a| a.range.a1()), Some(want.to_string()), "from {cell}");
|
||||
}
|
||||
let mut s = layout();
|
||||
assert!(s.execute("data.filter", json!({"range":"A1:C8"})).is_err());
|
||||
assert!(wb(&s).active().unwrap().autofilter.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_a_table_filter_off_keeps_rows_another_table_still_hides() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
s.execute("range.setValues", json!({"range":"A1","values":[["K","V"],["k1",1],["k2",2],["k3",3],["k4",4],["k5",5]]})).unwrap();
|
||||
s.execute("range.setValues", json!({"range":"D1","values":[["X","Y"],["x1",1],["x2",2],["x3",3],["x4",4],["x5",5]]})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"A1:B6","header":true})).unwrap();
|
||||
s.execute("insert.table", json!({"range":"D1:E6","header":true})).unwrap();
|
||||
// The second table's criteria are saved with it, so both tables hold a filter after reopening.
|
||||
s.execute("selection.set", json!({"cell":"D2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s2.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s2.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap();
|
||||
s2.execute("data.filter", json!({})).unwrap();
|
||||
let sh = wb(&s2).active().unwrap();
|
||||
assert!(!sh.is_row_hidden(2), "only the first table hid row 3");
|
||||
for row in 3..6 {
|
||||
assert!(sh.is_row_hidden(row), "row {} is still filtered out of the second table", row + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_a_table_filter_off_hides_the_rows_of_all_other_filtered_tables() {
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
for (col, keys) in [("A", "k"), ("D", "x"), ("G", "z")] {
|
||||
let mut values = vec![json!(["K", "V"])];
|
||||
values.extend((1..=5).map(|n| json!([format!("{keys}{n}"), n])));
|
||||
s.execute("range.setValues", json!({"range": format!("{col}1"), "values": values})).unwrap();
|
||||
}
|
||||
for range in ["A1:B6", "D1:E6", "G1:H6"] {
|
||||
s.execute("insert.table", json!({"range": range, "header": true})).unwrap();
|
||||
}
|
||||
// Each filtered table's criteria are saved with it: reopening leaves both holding a filter.
|
||||
s.execute("selection.set", json!({"cell":"D2"})).unwrap();
|
||||
s.execute("data.filterBy", json!({"column":"D","values":["x1","x2"]})).unwrap();
|
||||
let mut s2 = Session::new();
|
||||
s2.add_document(gridcraft_engine::DocState::new(reopened(wb(&s)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s2.execute("selection.set", json!({"cell":"G2"})).unwrap();
|
||||
s2.execute("data.filterBy", json!({"column":"G","values":["z1","z3"]})).unwrap();
|
||||
let mut s3 = Session::new();
|
||||
s3.add_document(gridcraft_engine::DocState::new(reopened(wb(&s2)), None, "t".into(), gridcraft_engine::Trust::FromFile));
|
||||
s3.execute("selection.set", json!({"cell":"A2"})).unwrap();
|
||||
s3.execute("data.filterBy", json!({"column":"A","values":["k1"]})).unwrap();
|
||||
s3.execute("data.filter", json!({})).unwrap();
|
||||
let sh = wb(&s3).active().unwrap();
|
||||
assert!(!sh.is_row_hidden(1));
|
||||
for row in 2..6 {
|
||||
assert!(sh.is_row_hidden(row), "row {} is excluded by one of the two other tables", row + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtering_a_table_whose_buttons_were_turned_off_turns_them_back_on() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filter", json!({})).unwrap();
|
||||
assert!(!wb(&s).active().unwrap().tables[0].filter_button);
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
assert!(wb(&s).active().unwrap().tables[0].filter_button);
|
||||
let back = reopened(wb(&s));
|
||||
assert_eq!(back.active().unwrap().tables[0].filter.len(), 1, "the criteria are saved with the table");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_range_inside_the_active_table_is_refused_not_a_toggle() {
|
||||
let mut s = table_book();
|
||||
s.execute("data.filterBy", json!({"column":"A","values":["a"]})).unwrap();
|
||||
assert!(s.execute("data.filter", json!({"range":"B1:B7"})).is_err());
|
||||
let sh = wb(&s).active().unwrap();
|
||||
assert!(sh.tables[0].filter_button && sh.autofilter.is_some(), "the filter is untouched");
|
||||
}
|
||||
@@ -33,6 +33,98 @@ fn tvm() {
|
||||
is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num);
|
||||
}
|
||||
|
||||
/// XIRR of `values` on `dates`, with an optional guess, as a number or an error.
|
||||
fn xirr_of(values: &[f64], dates: &[f64], guess: Option<f64>) -> Value {
|
||||
let mut args = vec![rf(col(values)), rf(col(dates))];
|
||||
args.extend(guess.map(n));
|
||||
ev("XIRR", args)
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn xirr_is(values: &[f64], dates: &[f64], guess: Option<f64>, expected: f64) {
|
||||
assert_eq!(xirr_of(values, dates, guess), Value::Number(expected), "XIRR{values:?} {dates:?} {guess:?}");
|
||||
}
|
||||
|
||||
fn irr_of(values: &[f64], guess: Option<f64>) -> Value {
|
||||
let mut args = vec![rf(col(values))];
|
||||
args.extend(guess.map(n));
|
||||
ev("IRR", args)
|
||||
}
|
||||
|
||||
/// Expected values observed in Excel 365 with these synthetic inputs. XIRR matches bit for
|
||||
/// bit: its answer is a bisection midpoint, about 1e-8 from the exact root.
|
||||
#[test]
|
||||
fn xirr_follows_excel_bisection() {
|
||||
let (b, y1, y2) = (43831.0, 44196.0, 44561.0);
|
||||
// Root 10%: the bracket and so the answer depend on the guess, not on the flows.
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], None, 0.099_999_994_039_535_52);
|
||||
xirr_is(&[-100.0, 121.0], &[b, y2], None, 0.099_999_994_039_535_52);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.0), 0.099_999_995_117_187_5);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(0.25), 0.099_999_997_764_825_82);
|
||||
xirr_is(&[-100.0, 110.0], &[b, y1], Some(5.0), 0.100_000_002_421_438_7);
|
||||
xirr_is(&[-100.0, 60.0, 60.0], &[b, y1, y2], None, 0.130_662_387_609_481_82);
|
||||
xirr_is(&[-100.0, 150.0], &[b, y1], None, 0.499_999_994_039_535_54);
|
||||
// Fractional dates are truncated.
|
||||
xirr_is(&[-100.0, 60.0, 60.0], &[b, y1 + 0.9, y2 + 0.2], None, 0.130_662_387_609_481_82);
|
||||
// Negative roots: minus the guess, then halfway to -100% each step.
|
||||
xirr_is(&[-100.0, 73.0], &[b, y1], None, -0.269_999_996_572_733);
|
||||
xirr_is(&[-100.0, 13.0], &[b, y1], None, -0.870_000_001_043_081_1);
|
||||
xirr_is(&[-100.0, 1e-29], &[b, 45658.0], None, -0.999_999_359_104_708);
|
||||
// A guess of 100% or more steps through rates below -100% (whole years only).
|
||||
xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(2.0), -1.653_112_880_885_601);
|
||||
xirr_is(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(-0.3), -0.846_887_112_781_405_5);
|
||||
is_err(xirr_of(&[-100.0, -50.0, 10.0], &[b, y1, y2], Some(1.0)), CellError::Num);
|
||||
// One-day spans.
|
||||
xirr_is(&[-100.0, 100.01], &[b, b + 1.0], None, 0.037_172_409_892_082_23);
|
||||
xirr_is(&[-100.0, 99.99], &[b, b + 1.0], None, -0.035_843_667_387_962_34);
|
||||
xirr_is(&[-100.0, 110.0], &[b, b + 1.0], None, 1_283_305_579_426_611.5);
|
||||
// A leading zero cash flow scales the residual to 0: Excel halves the guess to a tiny
|
||||
// number whatever the flows (observed), and a negative guess is #NUM!.
|
||||
let z = [0.0, -100.0, 110.0];
|
||||
let zd = [b, y1, y2];
|
||||
xirr_is(&z, &zd, None, 2.980_232_238_769_531_4e-9);
|
||||
xirr_is(&z, &zd, Some(0.2), 2.980_232_238_769_531_4e-9);
|
||||
xirr_is(&z, &zd, Some(0.0), 4.882_812_5e-9);
|
||||
xirr_is(&z, &zd, Some(5.0), 4.656_612_873_077_392_6e-9);
|
||||
xirr_is(&[0.0, -100.0, 50.0], &zd, None, 2.980_232_238_769_531_4e-9);
|
||||
is_err(xirr_of(&z, &zd, Some(-0.5)), CellError::Num);
|
||||
// Dates before the first are allowed (time runs from the first date); in the second
|
||||
// case the search finds no sign change.
|
||||
xirr_is(&[-2416.93, 447.77, 1743.6], &[44331.0, 44498.0, 43849.0], None, -0.974_587_937_071_919_6);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b - 365.0, y2], None), CellError::Num);
|
||||
// A negative guess never reaches a positive root; a guess at or below -1 is #NUM!.
|
||||
is_err(xirr_of(&[-100.0, 110.0], &[b, y1], Some(-0.1)), CellError::Num);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, y1, y2], Some(-1.0)), CellError::Num);
|
||||
// Two roots with the guess outside them; all dates the same.
|
||||
is_err(xirr_of(&[-100.0, 300.0, -210.0], &[b, y1, y2], None), CellError::Num);
|
||||
is_err(xirr_of(&[-100.0, 60.0, 60.0], &[b, b, b], None), CellError::Num);
|
||||
}
|
||||
|
||||
/// IRR follows Excel's answers to about 1e-12 and its #NUM! cases.
|
||||
#[test]
|
||||
fn irr_follows_excel() {
|
||||
assert_eq!(irr_of(&[-100.0, 110.0], None), Value::Number(0.100_000_000_000_000_09));
|
||||
close_tol(irr_of(&[-0.0001, 0.0, 0.0, 0.0, 100.0], None), 30.622_776_600_497_09, 1e-9);
|
||||
let mut late = vec![-100.0];
|
||||
late.extend([0.0; 19]);
|
||||
late.push(1e-5);
|
||||
is_err(irr_of(&late, None), CellError::Num);
|
||||
// ...but from a guess just above -100% Newton creeps down to the root.
|
||||
let mut late18 = vec![-100.0];
|
||||
late18.extend([0.0; 18]);
|
||||
late18.push(1e-5);
|
||||
close_tol(irr_of(&late18, Some(-0.99)), -0.571_866_760_128_087_4, 1e-9);
|
||||
close_tol(irr_of(&[-100.0, 300.0, -210.0], Some(0.9)), 0.887_298_334_620_741_5, 1e-12);
|
||||
is_err(irr_of(&[-100.0, 60.0, 60.0], Some(-1.0)), CellError::Value);
|
||||
close_tol(irr_of(&[-100.0, 60.0, 60.0], Some(-0.999_999)), 0.130_662_386_291_807_5, 1e-12);
|
||||
// A small Newton step alone is not convergence when cancellation leaves a large scaled residual.
|
||||
close_tol(irr_of(&[-1e-9, 1.0, -1e8], None), 112_701_664.379_258_29, 1e-8);
|
||||
// An exact repeated root at the starting guess (zero slope) is the answer, as in Excel.
|
||||
assert_eq!(irr_of(&[1.0, -2.0, 1.0], Some(0.0)), Value::Number(0.0));
|
||||
assert_eq!(irr_of(&[-1.0, 3.0, -3.0, 1.0], Some(0.0)), Value::Number(0.0));
|
||||
close_tol(irr_of(&[1.0, -2.0, 1.0], None), 1.09e-7, 1e-7);
|
||||
}
|
||||
|
||||
/// RATE with the given arguments, as a number or an error.
|
||||
fn rate_of(args: &[f64]) -> Value {
|
||||
ev("RATE", args.iter().map(|x| n(*x)).collect())
|
||||
@@ -145,6 +237,42 @@ fn pmt_edge_cases_follow_excel() {
|
||||
close_tol(ev("PMT", vec![n(0.05), n(10.0), n(100.0), n(50.0), n(1.0)]), -16.119701185541427, 1e-15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_cash_flows_follow_excel_for_xirr_and_xnpv() {
|
||||
// Each result below was observed in Excel on a synthetic workbook: five rows, the first
|
||||
// four -10000, 2750, 4250, 3250 on 39448, 39508, 39751, 39859; the last row varies.
|
||||
let dates = col(&[39448.0, 39508.0, 39751.0, 39859.0, 39904.0]);
|
||||
let gap = arr([39448.0, 39508.0, 39751.0, 39859.0].iter().map(|x| vec![nv(*x)]).chain([vec![Value::Empty]]).collect());
|
||||
let flows = |last: Value| arr([-10000.0, 2750.0, 4250.0, 3250.0].iter().map(|x| vec![nv(*x)]).chain([vec![last]]).collect());
|
||||
let rate = 0.033791377645041754;
|
||||
// XIRR: a blank value counts as 0 and a blank date is ignored when its value is blank or 0. The answer is a bisection midpoint, within about 1e-8 of the exact rate.
|
||||
close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(dates.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(dates.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(Value::Empty)), rf(gap.clone())]), rate, 1e-7);
|
||||
close_tol(ev("XIRR", vec![rf(flows(nv(0.0))), rf(gap.clone())]), rate, 1e-7);
|
||||
is_err(ev("XIRR", vec![rf(flows(nv(2750.0))), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XIRR", vec![rf(flows(tv("-"))), rf(dates.clone())]), CellError::Value);
|
||||
// XNPV is strict: a blank value is #NUM! where 0 is a number.
|
||||
close_tol(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(dates.clone())]), -382.66, 1e-2);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(dates.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(0.0))), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(Value::Empty)), rf(gap.clone())]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(nv(2750.0))), rf(gap)]), CellError::Num);
|
||||
is_err(ev("XNPV", vec![n(0.09), rf(flows(tv("-"))), rf(dates.clone())]), CellError::Num);
|
||||
// In the first row a blank value or date is #VALUE! for XNPV; XIRR reads a blank date there as day 0.
|
||||
let first_row = |value: Value, date: Value| {
|
||||
let cells = |x: Value, rest: [f64; 4]| arr(std::iter::once(vec![x]).chain(rest.iter().map(|y| vec![nv(*y)])).collect());
|
||||
(rf(cells(value, [2750.0, 4250.0, 3250.0, 500.0])), rf(cells(date, [39508.0, 39751.0, 39859.0, 39904.0])))
|
||||
};
|
||||
let (v0, d0) = first_row(Value::Empty, nv(39448.0));
|
||||
is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value);
|
||||
let (v0, d0) = first_row(nv(0.0), Value::Empty);
|
||||
is_err(ev("XNPV", vec![n(0.09), v0, d0]), CellError::Value);
|
||||
let (v0, d0) = first_row(nv(-10000.0), Value::Empty);
|
||||
is_err(ev("XNPV", vec![n(0.09), v0.clone(), d0.clone()]), CellError::Value);
|
||||
close_tol(ev("XIRR", vec![v0, d0]), 0.000_664_654_374_122_619_6, 1e-7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cash_flows() {
|
||||
close_tol(ev("NPV", vec![n(0.1), n(-10000.0), n(3000.0), n(4200.0), n(6800.0)]), 1188.443412, 1e-9);
|
||||
|
||||
@@ -152,72 +152,6 @@ pub(super) fn cumprinc(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
cumulative(a, true)
|
||||
}
|
||||
|
||||
/// Newton iteration with a numeric derivative, keeping the rate above -1.
|
||||
fn newton(f: impl Fn(f64) -> f64, guess: f64) -> Option<f64> {
|
||||
let mut x = guess;
|
||||
for _ in 0..200 {
|
||||
let y = f(x);
|
||||
if !y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let h = 1e-6 * x.abs().max(1e-3);
|
||||
let d = (f(x + h) - f(x - h)) / (2.0 * h);
|
||||
if d == 0.0 || !d.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let mut nx = x - y / d;
|
||||
if nx <= -1.0 {
|
||||
nx = (x - 1.0) / 2.0;
|
||||
if nx <= -1.0 {
|
||||
nx = -0.999_999_999;
|
||||
}
|
||||
}
|
||||
if (nx - x).abs() < 1e-12 * nx.abs().max(1.0) {
|
||||
return Some(nx);
|
||||
}
|
||||
x = nx;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Tries Newton from the guess and a few fallback starting points; then bisection over a
|
||||
/// bracket if one can be found.
|
||||
fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R<f64> {
|
||||
let check = |r: f64| f(r).is_finite() && f(r).abs() < 1e-7 * (1.0 + f(guess).abs().min(1e12));
|
||||
for g in [guess, 0.1, 0.01, 0.5, -0.5, 1.0, 0.001, 5.0, -0.9, 10.0] {
|
||||
if let Some(r) = newton(&f, g)
|
||||
&& r > -1.0
|
||||
&& check(r)
|
||||
{
|
||||
return Ok(r);
|
||||
}
|
||||
}
|
||||
// Scan for a sign change and bisect.
|
||||
let grid: Vec<f64> = [-0.999_999, -0.99, -0.9, -0.5, -0.2, 0.0, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 100.0, 1000.0].to_vec();
|
||||
for w in grid.windows(2) {
|
||||
let (mut lo, mut hi) = match w {
|
||||
[a, b] => (*a, *b),
|
||||
_ => continue,
|
||||
};
|
||||
let (flo, fhi) = (f(lo), f(hi));
|
||||
if !(flo.is_finite() && fhi.is_finite()) || flo * fhi > 0.0 {
|
||||
continue;
|
||||
}
|
||||
let lo_neg = flo < 0.0;
|
||||
for _ in 0..200 {
|
||||
let mid = 0.5 * (lo + hi);
|
||||
let fm = f(mid);
|
||||
if (fm < 0.0) == lo_neg {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return Ok(0.5 * (lo + hi));
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus
|
||||
/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to
|
||||
/// judge how close to zero the first can get in floating point.
|
||||
@@ -314,8 +248,15 @@ pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
num_val(sum)
|
||||
}
|
||||
|
||||
/// Values and dates for XNPV/XIRR: both must be numeric and of equal length.
|
||||
fn dated_flows(values: &Value, dates: &Value) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
/// Values and dates for XNPV/XIRR: both must be numeric and of equal length. XNPV rejects a
|
||||
/// date before the first; XIRR (`lenient`) takes it, as Excel does.
|
||||
///
|
||||
/// Blank cells follow what Excel returns (observed on synthetic workbooks). With `lenient` (XIRR)
|
||||
/// a blank value counts as 0 and a blank date is ignored when its value is blank or 0; a nonzero
|
||||
/// value without a date is `#NUM!`, except in the first row, where the date is read as day 0.
|
||||
/// XNPV is strict: a blank (or text) value or a blank date is `#NUM!`, except in the first row,
|
||||
/// where it is `#VALUE!`.
|
||||
fn dated_flows(values: &Value, dates: &Value, lenient: bool) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
let va = as_array(values);
|
||||
let da = as_array(dates);
|
||||
if va.data.len() != da.data.len() {
|
||||
@@ -323,21 +264,33 @@ fn dated_flows(values: &Value, dates: &Value) -> R<(Vec<f64>, Vec<f64>)> {
|
||||
}
|
||||
let mut v = Vec::with_capacity(va.data.len());
|
||||
let mut d = Vec::with_capacity(da.data.len());
|
||||
for (x, y) in va.data.iter().zip(da.data.iter()) {
|
||||
match x {
|
||||
Value::Number(n) => v.push(*n),
|
||||
for (i, (x, y)) in va.data.iter().zip(da.data.iter()).enumerate() {
|
||||
// Excel (XNPV): a blank or text value or a blank date is #NUM!, except in the first row,
|
||||
// where it is #VALUE!.
|
||||
let strict_err = if i == 0 { CellError::Value } else { CellError::Num };
|
||||
let value = match x {
|
||||
Value::Number(n) => *n,
|
||||
Value::Empty if lenient => 0.0,
|
||||
Value::Empty => return Err(strict_err),
|
||||
Value::Error(e) => return Err(*e),
|
||||
_ => return Err(CellError::Value),
|
||||
}
|
||||
_ if lenient => return Err(CellError::Value),
|
||||
_ => return Err(strict_err),
|
||||
};
|
||||
match y {
|
||||
Value::Number(n) => d.push(n.trunc()),
|
||||
Value::Error(e) => return Err(*e),
|
||||
Value::Text(_) => d.push(y.to_number()?.trunc()),
|
||||
Value::Empty if !lenient => return Err(strict_err),
|
||||
// XIRR skips a blank date next to a 0 flow and reads one in the first row as day 0.
|
||||
Value::Empty if value == 0.0 => continue,
|
||||
Value::Empty if i == 0 => d.push(0.0),
|
||||
Value::Empty => return Err(CellError::Num),
|
||||
_ => return Err(CellError::Value),
|
||||
}
|
||||
v.push(value);
|
||||
}
|
||||
let d0 = *d.first().ok_or(CellError::Num)?;
|
||||
if d.iter().any(|&x| x < d0 || x < 0.0) {
|
||||
if d.iter().any(|&x| (x < d0 && !lenient) || x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
Ok((v, d))
|
||||
@@ -353,35 +306,219 @@ pub(super) fn xnpv(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
if rate <= -1.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value)?;
|
||||
let (v, d) = dated_flows(&a.get(1).ok_or(CellError::Value)?.value, &a.get(2).ok_or(CellError::Value)?.value, false)?;
|
||||
num_val(xnpv_calc(rate, &v, &d))
|
||||
}
|
||||
|
||||
/// Excel's XIRR solver, reconstructed by observing Excel with synthetic inputs (not from its
|
||||
/// code; its documentation says only "iteration", 100 tries and 0.000001 percent). It looks
|
||||
/// only at the sign of XNPV until the end, so its answer is the root to about 1e-8, not to the
|
||||
/// last digit:
|
||||
///
|
||||
/// - Bracket the root from the guess (0 counts as 1e-5): double the rate while XNPV keeps the
|
||||
/// sign it has at the guess and that sign differs from the first nonzero value (the root is higher).
|
||||
/// Otherwise the root is lower: bisect towards 0 if XNPV changes sign there; halve the rate
|
||||
/// towards 0 if XNPV is larger in size at 0 than at the guess; otherwise try minus the guess
|
||||
/// and then step halfway to -100% each time. A negative guess only moves towards 0 (root
|
||||
/// higher) or towards -100% (root lower).
|
||||
/// - Bisect the bracket, taking the midpoint from the upper end, until half the bracket is
|
||||
/// under 1e-8 * (|rate| + 0.5) and |XNPV| is under 2e-8 * |first nonzero value|; return that
|
||||
/// midpoint. A zero XNPV counts as the upper side.
|
||||
/// - Halving towards 0 that gets within that tolerance of 0 without a sign change goes on with
|
||||
/// the negative side; at most 100 XNPV evaluations in all; a rate of -100% or an XNPV that
|
||||
/// can't be computed (a negative base for fractional years) is #NUM!.
|
||||
struct XirrSolver<'a> {
|
||||
values: &'a [f64],
|
||||
/// First nonzero value: sets the search direction and the residual scale.
|
||||
first: f64,
|
||||
years: Vec<f64>,
|
||||
evals: usize,
|
||||
/// XNPV must be within this of 0 at the answer.
|
||||
residual: f64,
|
||||
}
|
||||
|
||||
impl XirrSolver<'_> {
|
||||
const MAX_EVALS: usize = 100;
|
||||
|
||||
fn tol(rate: f64) -> f64 {
|
||||
1e-8 * (rate.abs() + 0.5)
|
||||
}
|
||||
|
||||
fn same_sign(a: f64, b: f64) -> bool {
|
||||
a * b > 0.0
|
||||
}
|
||||
|
||||
fn f(&mut self, rate: f64) -> R<f64> {
|
||||
self.evals += 1;
|
||||
if self.evals > Self::MAX_EVALS {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let base = 1.0 + rate;
|
||||
if base == 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let mut sum = 0.0;
|
||||
for (x, t) in self.values.iter().zip(&self.years) {
|
||||
sum += x / base.powf(*t);
|
||||
}
|
||||
if sum.is_finite() { Ok(sum) } else { Err(CellError::Num) }
|
||||
}
|
||||
|
||||
fn solve(&mut self, guess: f64) -> R<f64> {
|
||||
let g = if guess == 0.0 { 1e-5 } else { guess };
|
||||
let fg = self.f(g)?;
|
||||
let higher = fg * self.first < 0.0;
|
||||
if g > 0.0 {
|
||||
if higher {
|
||||
return self.double(g, fg);
|
||||
}
|
||||
let f0 = self.f(0.0)?;
|
||||
if !Self::same_sign(f0, fg) {
|
||||
return self.bisect(g, fg, 0.0, f0);
|
||||
}
|
||||
if f0.abs() > fg.abs() {
|
||||
return self.halve(g, fg, g, fg);
|
||||
}
|
||||
return self.negative_side(g, fg);
|
||||
}
|
||||
if higher { self.halve(g, fg, g, fg) } else { self.towards_minus_one(g, fg) }
|
||||
}
|
||||
|
||||
fn double(&mut self, mut x: f64, mut fx: f64) -> R<f64> {
|
||||
loop {
|
||||
let next = 2.0 * x;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn halve(&mut self, mut x: f64, mut fx: f64, g: f64, fg: f64) -> R<f64> {
|
||||
loop {
|
||||
let step = -x / 2.0;
|
||||
let next = x + step;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
if step.abs() < Self::tol(next) {
|
||||
if next < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
return self.negative_side(g, fg);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn negative_side(&mut self, g: f64, fg: f64) -> R<f64> {
|
||||
let fm = self.f(-g)?;
|
||||
if !Self::same_sign(fm, fg) {
|
||||
return self.bisect(g, fg, -g, fm);
|
||||
}
|
||||
self.towards_minus_one(-g, fm)
|
||||
}
|
||||
|
||||
fn towards_minus_one(&mut self, mut x: f64, mut fx: f64) -> R<f64> {
|
||||
loop {
|
||||
let next = x + (-1.0 - x) / 2.0;
|
||||
let fnext = self.f(next)?;
|
||||
if !Self::same_sign(fnext, fx) {
|
||||
return self.bisect(x, fx, next, fnext);
|
||||
}
|
||||
(x, fx) = (next, fnext);
|
||||
}
|
||||
}
|
||||
|
||||
fn bisect(&mut self, a: f64, fa: f64, b: f64, fb: f64) -> R<f64> {
|
||||
let (mut lo, mut flo, mut hi) = if a < b { (a, fa, b) } else { (b, fb, a) };
|
||||
loop {
|
||||
let mid = hi - (hi - lo) / 2.0;
|
||||
let fm = self.f(mid)?;
|
||||
if (hi - lo) / 2.0 < Self::tol(mid) && fm.abs() < self.residual {
|
||||
return Ok(mid);
|
||||
}
|
||||
if Self::same_sign(fm, flo) {
|
||||
(lo, flo) = (mid, fm);
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn xirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value)?;
|
||||
let (v, d) = dated_flows(&a.first().ok_or(CellError::Value)?.value, &a.get(1).ok_or(CellError::Value)?.value, true)?;
|
||||
let guess = opt_num(a, 2, 0.1)?;
|
||||
if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
if guess <= -1.0 || !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
num_val(solve_rate(|r| xnpv_calc(r, &v, &d), guess)?)
|
||||
if v.first() == Some(&0.0) {
|
||||
// Excel with a 0 (or blank) first flow: the residual scale is 0, so the search just
|
||||
// halves the guess towards 0 until the step is under the tolerance; a negative guess is #NUM!.
|
||||
if guess < 0.0 {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let mut x = if guess == 0.0 { 1e-5 } else { guess };
|
||||
// Bounded: a huge guess halves to the tolerance within about 1100 steps.
|
||||
for _ in 0..1100 {
|
||||
if x / 2.0 < XirrSolver::tol(x / 2.0) {
|
||||
break;
|
||||
}
|
||||
x /= 2.0;
|
||||
}
|
||||
return num_val(x / 2.0);
|
||||
}
|
||||
let d0 = d.first().copied().unwrap_or(0.0);
|
||||
let first = v.iter().copied().find(|x| *x != 0.0).unwrap_or(0.0);
|
||||
let mut solver = XirrSolver { values: &v, first, years: d.iter().map(|t| (t - d0) / 365.0).collect(), evals: 0, residual: 2e-8 * first.abs() };
|
||||
num_val(solver.solve(guess)?)
|
||||
}
|
||||
|
||||
/// Excel's IRR solver, approximated from observation (Excel's documentation says 20 tries and
|
||||
/// 0.00001 percent): Newton's method on the discount factor 1/(1+rate), where the cash flows
|
||||
/// are a polynomial, from 1/(1+guess) until a step moves less than 1e-8, for at most 100 steps.
|
||||
/// Excel's answers agree with it to about 1e-12 on ordinary flows (the last digits differ) and
|
||||
/// on which flows have no answer, apart from a few far from any guess.
|
||||
fn irr_solve(v: &[f64], guess: f64) -> R<f64> {
|
||||
let mut x = 1.0 / (1.0 + guess);
|
||||
for _ in 0..100 {
|
||||
let (mut s, mut ds, mut scale) = (0.0, 0.0, 0.0);
|
||||
for c in v.iter().rev() {
|
||||
ds = ds * x + s;
|
||||
s = s * x + c;
|
||||
scale = scale * x.abs() + c.abs();
|
||||
}
|
||||
if ds == 0.0 {
|
||||
// An exact root with a zero slope (a repeated root such as {1,-2,1} at guess 0) is
|
||||
// still the answer: Excel returns 0 there.
|
||||
return if s == 0.0 && x > 0.0 { Ok(1.0 / x - 1.0) } else { Err(CellError::Num) };
|
||||
}
|
||||
let next = x - s / ds;
|
||||
if !next.is_finite() {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
if (next - x).abs() < 1e-8 && scale.is_finite() && s.abs() <= 1e-12 * scale {
|
||||
return if next > 0.0 { Ok(1.0 / next - 1.0) } else { Err(CellError::Num) };
|
||||
}
|
||||
x = next;
|
||||
}
|
||||
Err(CellError::Num)
|
||||
}
|
||||
|
||||
pub(super) fn irr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
let v = array_numbers(&a.first().ok_or(CellError::Value)?.value)?;
|
||||
let guess = opt_num(a, 1, 0.1)?;
|
||||
// Excel: a guess at or below -100% is #VALUE! for IRR (#NUM! for XIRR).
|
||||
if guess <= -1.0 {
|
||||
return Err(CellError::Value);
|
||||
}
|
||||
if !v.iter().any(|x| *x > 0.0) || !v.iter().any(|x| *x < 0.0) {
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let f = |r: f64| {
|
||||
let mut s = 0.0;
|
||||
let mut d = 1.0;
|
||||
for x in &v {
|
||||
s += x / d;
|
||||
d *= 1.0 + r;
|
||||
}
|
||||
s
|
||||
};
|
||||
num_val(solve_rate(f, guess)?)
|
||||
num_val(irr_solve(&v, guess)?)
|
||||
}
|
||||
|
||||
pub(super) fn mirr(a: &[Arg], _c: &mut dyn Ctx) -> R<Value> {
|
||||
|
||||
@@ -33,7 +33,9 @@ mod parts;
|
||||
mod rules;
|
||||
|
||||
pub(crate) use parts::password_attrs;
|
||||
use parts::{autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_name, table_xml, thread_ids, threaded_xml, vml_xml};
|
||||
use parts::{
|
||||
autofilter_xml, comments_xml, protected_ranges_xml, table_columns, table_filter, table_name, table_xml, thread_ids, threaded_xml, vml_xml,
|
||||
};
|
||||
use rules::{cf_rule_xml, solid_bar_x14, validation_xml, x14_cf_rule_xml};
|
||||
|
||||
fn sqref(ranges: &[RangeRef]) -> String {
|
||||
@@ -203,7 +205,8 @@ pub fn write_sheet(wb: &Workbook, si: usize, selected: bool, out: &mut Out) -> (
|
||||
out.table_id += 1;
|
||||
let n = out.tables;
|
||||
let name = table_name(&t.name, &mut used_names, out.table_id);
|
||||
let xml = table_xml(t, cols, &name, out.table_id, out);
|
||||
let filter = table_filter(sheet, t);
|
||||
let xml = table_xml(t, cols, &name, out.table_id, &filter, out);
|
||||
out.part(&format!("xl/tables/table{n}.xml"), Some(CT_TABLE), xml.into_bytes());
|
||||
part.features.table_parts.push(rels.add("table", &format!("../tables/table{n}.xml")));
|
||||
}
|
||||
|
||||
@@ -110,7 +110,34 @@ pub(super) fn autofilter_xml(range: RangeRef, criteria: &[(u32, FilterCriterion)
|
||||
s
|
||||
}
|
||||
|
||||
pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &mut Out) -> String {
|
||||
/// The criteria saved in a table's `<autoFilter>`: its own, plus those of a sheet AutoFilter
|
||||
/// that starts on the table's header row. GridCraft filters a table through the sheet
|
||||
/// AutoFilter, but a file can't hold a sheet AutoFilter that overlaps a table (the sheet element
|
||||
/// is left out), so without this the criteria would be lost and the rows they hide would reopen
|
||||
/// as rows hidden by hand, which SUBTOTAL 1-11 counts.
|
||||
pub(super) fn table_filter(sheet: &Sheet, t: &Table) -> Vec<(u32, FilterCriterion)> {
|
||||
let mut criteria = t.filter.clone();
|
||||
let Some(af) = sheet.autofilter.as_ref().filter(|af| {
|
||||
t.header_row
|
||||
&& t.filter_button
|
||||
&& af.range.start.row == t.range.start.row
|
||||
&& af.range.intersects(&t.range)
|
||||
&& t.data_range().is_some_and(|d| af.range.end.row >= d.end.row)
|
||||
}) else {
|
||||
return criteria;
|
||||
};
|
||||
for (off, c) in &af.criteria {
|
||||
let Some(col) = af.range.start.col.checked_add(*off).and_then(|abs| abs.checked_sub(t.range.start.col)) else { continue };
|
||||
if col < t.range.width() {
|
||||
criteria.retain(|(o, _)| *o != col);
|
||||
criteria.push((col, c.clone()));
|
||||
}
|
||||
}
|
||||
criteria.sort_by_key(|(o, _)| *o);
|
||||
criteria
|
||||
}
|
||||
|
||||
pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, filter: &[(u32, FilterCriterion)], out: &mut Out) -> String {
|
||||
let mut s =
|
||||
format!("{XML_DECL}<table xmlns=\"{NS_MAIN}\" id=\"{id}\" name=\"{0}\" displayName=\"{0}\" ref=\"{1}\"", esc_attr(name), t.range.a1());
|
||||
if !t.header_row {
|
||||
@@ -131,7 +158,7 @@ pub(super) fn table_xml(t: &Table, cols: &[String], name: &str, id: u32, out: &m
|
||||
if t.header_row && t.filter_button {
|
||||
let end_row = if t.totals_row { t.range.end.row.saturating_sub(1).max(t.range.start.row) } else { t.range.end.row };
|
||||
let r = RangeRef::new(t.range.start, CellRef::new(end_row, t.range.end.col));
|
||||
s.push_str(&autofilter_xml(r, &t.filter, out));
|
||||
s.push_str(&autofilter_xml(r, filter, out));
|
||||
}
|
||||
let _ = write!(s, "<tableColumns count=\"{}\">", cols.len());
|
||||
for (i, name) in cols.iter().enumerate() {
|
||||
|
||||
@@ -32,6 +32,7 @@ mod shared_media;
|
||||
mod sheet_data_pin;
|
||||
mod sheet_names;
|
||||
mod smooth_roundtrip;
|
||||
mod tablefilter;
|
||||
mod trendline_roundtrip;
|
||||
mod xls_dv_tests;
|
||||
mod xls_style_tests;
|
||||
|
||||
@@ -1985,9 +1985,9 @@ fn a_table_filter_criteria_survive_a_round_trip() {
|
||||
assert!(b.autofilter.is_none(), "a table's filter belongs to the table part, not the sheet");
|
||||
}
|
||||
|
||||
/// Stored `colId` offsets are relative to the filter range's first column, so criteria of a filter
|
||||
/// that starts right of the table's first column must not be folded into the table part, where
|
||||
/// they would apply to the wrong column.
|
||||
/// Stored `colId` offsets are relative to the table's first column, so criteria of a sheet filter
|
||||
/// that starts right of the table's first column are moved to the column they filter (Region), not
|
||||
/// kept at the filter's own offset (which would be Id).
|
||||
#[test]
|
||||
fn a_partial_sheet_filter_is_not_folded_into_a_table() {
|
||||
let mut wb = Workbook::new();
|
||||
@@ -2021,7 +2021,11 @@ fn a_partial_sheet_filter_is_not_folded_into_a_table() {
|
||||
assert!(rep.warnings.is_empty(), "{:?}", rep.warnings);
|
||||
let b = back.sheet(0).unwrap();
|
||||
let t = b.tables.first().expect("the table survived");
|
||||
assert!(t.filter.is_empty(), "the criteria landed on the wrong table column: {:?}", t.filter);
|
||||
assert!(
|
||||
matches!(t.filter.as_slice(), [(1, FilterCriterion::Values { values, .. })] if values == &["East".to_string()]),
|
||||
"the criteria landed on the wrong table column: {:?}",
|
||||
t.filter
|
||||
);
|
||||
assert!(b.autofilter.is_none(), "a sheet filter inside a table would be invalid");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! A sheet AutoFilter that filters a table is saved as the table's own filter (a file can't hold
|
||||
//! a sheet AutoFilter that overlaps a table), so the rows it hides reopen as filtered rows.
|
||||
|
||||
use gridcraft_core::{CellRef, RangeRef, Value};
|
||||
use gridcraft_model::*;
|
||||
|
||||
use crate::{read_xlsx, write_xlsx};
|
||||
|
||||
fn rr(a: &str) -> RangeRef {
|
||||
RangeRef::parse(a).unwrap()
|
||||
}
|
||||
|
||||
fn table(range: &str, cols: &[&str]) -> Table {
|
||||
Table {
|
||||
id: 1,
|
||||
name: "T".into(),
|
||||
range: rr(range),
|
||||
header_row: true,
|
||||
totals_row: false,
|
||||
columns: cols
|
||||
.iter()
|
||||
.map(|n| TableColumn { name: (*n).into(), totals: TotalsFn::None, totals_label: None, formula: None, unique_name: None, xml: None })
|
||||
.collect(),
|
||||
style: String::new(),
|
||||
banded_rows: true,
|
||||
banded_cols: false,
|
||||
first_col: false,
|
||||
last_col: false,
|
||||
filter_button: true,
|
||||
filter: vec![],
|
||||
table_type: None,
|
||||
connection_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Table B2:C6 (Name, Qty) with rows 4 and 6 hidden by a filter on Name.
|
||||
fn filtered(af_range: &str, af_col: u32) -> Workbook {
|
||||
let mut wb = Workbook::new();
|
||||
let s = wb.sheet_mut(0).unwrap();
|
||||
s.set_value(CellRef::new(1, 1), Value::text("Name"));
|
||||
s.set_value(CellRef::new(1, 2), Value::text("Qty"));
|
||||
for (i, n) in ["a", "b", "c", "d"].iter().enumerate() {
|
||||
let row = 2 + i as u32;
|
||||
s.set_value(CellRef::new(row, 1), Value::text(*n));
|
||||
s.set_value(CellRef::new(row, 2), Value::Number(10f64.powi(i as i32)));
|
||||
}
|
||||
let mut t = table("B2:C6", &["Name", "Qty"]);
|
||||
// A criterion the table already had (from the file it was opened from) on the Qty column.
|
||||
t.filter = vec![(1, FilterCriterion::Custom { a: (">".into(), "0".into()), b: None, and: true })];
|
||||
s.tables.push(t);
|
||||
s.autofilter = Some(AutoFilter {
|
||||
range: rr(af_range),
|
||||
criteria: vec![(af_col, FilterCriterion::Values { values: vec!["a".into(), "c".into()], blanks: false })],
|
||||
});
|
||||
for row in [3, 5] {
|
||||
s.rows.entry(row).or_default().hidden = true;
|
||||
}
|
||||
wb
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_filter_through_the_sheet_autofilter_is_saved_with_the_table() {
|
||||
let wb = filtered("B2:C6", 0);
|
||||
assert!(wb.sheets[0].is_row_filtered(3));
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
let s = back.sheet(0).unwrap();
|
||||
assert!(s.autofilter.is_none(), "no sheet AutoFilter over a table");
|
||||
let t = &s.tables[0];
|
||||
assert_eq!(t.filter.len(), 2, "{:?}", t.filter);
|
||||
assert_eq!(t.filter[0].0, 0);
|
||||
assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()]));
|
||||
assert!(matches!(&t.filter[1].1, FilterCriterion::Custom { .. }), "the table's own criterion is kept");
|
||||
for row in [3, 5] {
|
||||
assert!(s.is_row_filtered(row), "row {} reopens as filtered", row + 1);
|
||||
}
|
||||
assert!(!s.is_row_hidden(2) && !s.is_row_hidden(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_autofilter_starting_left_of_the_table_maps_its_columns() {
|
||||
// The filter starts one column left of the table on its header row: Name is column 1 of the
|
||||
// filter and column 0 of the table; a criterion on the column outside the table is dropped.
|
||||
let mut wb = filtered("A2:C6", 1);
|
||||
if let Some(af) = wb.sheet_mut(0).unwrap().autofilter.as_mut() {
|
||||
af.criteria.push((0, FilterCriterion::Values { values: vec!["zz".into()], blanks: true }));
|
||||
}
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
let t = &back.sheet(0).unwrap().tables[0];
|
||||
let cols: Vec<u32> = t.filter.iter().map(|(c, _)| *c).collect();
|
||||
assert_eq!(cols, [0, 1]);
|
||||
assert!(matches!(&t.filter[0].1, FilterCriterion::Values { values, .. } if values == &["a".to_string(), "c".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sheet_autofilter_not_on_the_header_row_is_not_folded() {
|
||||
let wb = filtered("B1:C6", 0);
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
let s = back.sheet(0).unwrap();
|
||||
assert!(s.autofilter.is_none());
|
||||
let cols: Vec<u32> = s.tables[0].filter.iter().map(|(c, _)| *c).collect();
|
||||
assert_eq!(cols, [1], "only the table's own criterion");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_table_filter_saves_no_autofilter_criteria() {
|
||||
let mut wb = filtered("B2:C6", 0);
|
||||
if let Some(t) = wb.sheet_mut(0).unwrap().tables.first_mut() {
|
||||
t.filter_button = false;
|
||||
t.filter.clear();
|
||||
}
|
||||
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
|
||||
let t = &back.sheet(0).unwrap().tables[0];
|
||||
assert!(!t.filter_button && t.filter.is_empty(), "{:?}", t.filter);
|
||||
}
|
||||
@@ -114,7 +114,7 @@ reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past
|
||||
XIRR, YIELD) are the highest-risk for last-digit differences. RATE follows Excel's own iteration, reconstructed from observation (secant from the guess and the guess ± 0.001, at most 200 steps,
|
||||
stop within 1e-7 by step and value, a looser 1e-4 check after 200 steps), so it returns the same
|
||||
iterate as Excel where convergence is slow (about -100% for `RATE(n,0,-pv,0)`) and `#NUM!` where
|
||||
Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7).
|
||||
Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7). XIRR follows Excel's own solver, reconstructed from observation: a sign-only search that brackets the root from the guess (doubling, halving towards 0, or stepping halfway to -100%) and bisects until half the bracket is under 1e-8 x (|rate| + 0.5) and XNPV is under 2e-8 x the first value, so its answer is the same midpoint as Excel's, about 1e-8 from the exact root, bit for bit in 888 of 910 synthetic cases with an answer (97.7% agreement on 1,283 cases including `#NUM!`). A 0 or blank first flow gives the tiny value Excel gives (the guess halved until the step is under the tolerance: about 2.98e-9 for the default guess, `#NUM!` for a negative guess). Known differences: flows with several sign changes where Excel returns about 3e-9 (a halving that reached 0), or `#NUM!` for two roots close to the guess. IRR uses Newton on the discount factor 1/(1+rate), at most 100 steps, stopping at a step under 1e-8; Excel's last digits differ by about 1e-12 (its exact iteration is not reconstructed) and a few far-from-guess cases differ in `#NUM!` (93.5% agreement on 708 cases, from 88%).
|
||||
|
||||
TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in
|
||||
number- and text-format test workbooks (352 TEXT cells), all match:
|
||||
@@ -141,6 +141,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-04 | minor | GCD and LCM reject negative fractional arguments before truncation; scalar and range regressions in the extracted math tests preserve positive truncation and signed-zero behavior; estimates unchanged |
|
||||
| 2026-11-03 | minor | IRR's Newton solver checks its scaled polynomial residual before accepting a small step; a tiny step with a large residual continues iterating |
|
||||
| 2026-11-03 | minor | GROUPBY: a total depth of 2 or more adds a subtotal line for each group of the leading key columns (after the group, or before it for a negative depth) and labels the last line Grand Total; a depth past the key columns, or above 1 with `field_relationship` 1, is `#VALUE!`, as in Excel (#1456 item 1) |
|
||||
| 2026-11-01 | minor | Python in cells row: Python mode in the formula bar |
|
||||
| 2026-11-01 | minor | Python in cells (stored, not run): `#PYTHON!`, `#BUSY!`, `#TIMEOUT!` and `#BLOCKED!` done, with their `ERROR.TYPE` numbers; `PY` still counted as missing |
|
||||
@@ -172,6 +173,8 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere
|
||||
| 2026-10-19 | minor | Long flat operator chains (#916): 4,096 operands (Excel's 8,192-character limit) no longer overflow the stack when entered, filled, adjusted or saved; chains past 64 operands are no longer saved as dynamic-array formulas; Spanish entry no longer refuses chains past 256 operands |
|
||||
| 2026-10-17 | minor | 15-significant-digit comparison moved from missing to done (#57), and the resolved caveats on the 3-D reference, dynamic-array and legacy-array rows cleared (#140, #133, #139, #156) |
|
||||
| 2026-10-16 | minor | FORECAST.ETS gap interpolation uses a forward-only known-point scan instead of rescanning each gap for every missing value; numerical behavior and missing-point limits are preserved (#1042) |
|
||||
| 2026-10-15 | minor | XIRR follows Excel's bisection (answers bit for bit, about 1e-8 from the exact root; dates before the first allowed; guess <= -1 is `#NUM!`); IRR uses Newton on the discount factor (`IRR` of -100, 19 zeros, 1E-5 is `#NUM!` like Excel; guess <= -1 is `#VALUE!`) |
|
||||
| 2026-10-20 | minor | XIRR counts a blank cash-flow cell as 0 and ignores a blank date next to a blank or 0 flow, instead of returning `#VALUE!`; XNPV now returns the `#NUM!` Excel gives for a blank or text value or a blank date after the first row, and `#VALUE!` for a blank value or date in the first row (observed on synthetic workbooks); XIRR with a 0 or blank first flow returns Excel's tiny value (about 2.98e-9), and a first nonzero flow with a blank date reads the date as day 0 |
|
||||
| 2026-10-15 | minor | Iterative calculation: Maximum Iterations and Maximum Change are set in File › Options › Formulas (dropped "no Options dialog yet") |
|
||||
| 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation |
|
||||
| 2026-10-15 | minor | ADDRESS quotes a sheet name the way Excel does: names that read as an A1 cell (`A1`) or an R1C1 reference (`R1C1`, `RC`) and names starting with `.` get quotes; `TRUE` / `FALSE` stay bare (#1458) |
|
||||
|
||||
Reference in New Issue
Block a user