1use std::collections::HashSet;
9
10use indexmap::IndexMap;
11
12use crate::error::{Error, Result};
13use crate::formatting::{format_value, sparkline_text};
14use crate::pyops;
15use crate::value::Value;
16
17#[derive(Debug, Clone)]
19pub struct Column {
20 pub key: String,
21 pub label: String,
22 pub mask: String,
23 pub rules: Vec<Value>,
24 pub field: Value,
25}
26
27impl Column {
28 pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
29 Self {
30 key: key.into(),
31 label: label.into(),
32 mask: "str".to_string(),
33 rules: Vec::new(),
34 field: Value::Null,
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
41pub struct Table {
42 pub key: String,
43 pub columns: Vec<Column>,
44 pub rows: Vec<IndexMap<String, Value>>,
45 pub total_rows: HashSet<usize>,
46 pub note: String,
47 pub notes: Vec<(String, String)>,
48 pub chart: Option<Value>,
49}
50
51impl Table {
52 pub fn new(key: impl Into<String>, columns: Vec<Column>) -> Self {
53 Self {
54 key: key.into(),
55 columns,
56 rows: Vec::new(),
57 total_rows: HashSet::new(),
58 note: String::new(),
59 notes: Vec::new(),
60 chart: None,
61 }
62 }
63}
64
65#[derive(Debug, Clone)]
67pub struct SummaryRow {
68 pub label: String,
69 pub value: Value,
70 pub mask: String,
71}
72
73fn column_from_field(field: &Value) -> Column {
74 let object = field.as_object();
75 let key = object
76 .and_then(|object| object.get("name"))
77 .and_then(Value::as_str)
78 .unwrap_or_default()
79 .to_string();
80 let label = object
81 .and_then(|object| object.get("label"))
82 .map(pyops::py_str)
83 .unwrap_or_else(|| key.clone());
84 let mask = object
85 .and_then(|object| object.get("format_mask"))
86 .and_then(Value::as_str)
87 .unwrap_or("str")
88 .to_string();
89 let rules = object
90 .and_then(|object| object.get("cell_rules"))
91 .and_then(Value::as_array)
92 .cloned()
93 .unwrap_or_default();
94 Column {
95 key,
96 label,
97 mask,
98 rules,
99 field: field.clone(),
100 }
101}
102
103fn merge_columns(context: &[Column], table_fields: &[Value]) -> Vec<Column> {
104 let mut columns = context.to_vec();
105 let mut seen: HashSet<String> = columns.iter().map(|column| column.key.clone()).collect();
106 for field in table_fields {
107 let column = column_from_field(field);
108 if seen.insert(column.key.clone()) {
109 columns.push(column);
110 }
111 }
112 columns
113}
114
115fn notes_from_field_dicts(fields: &[Value]) -> Vec<(String, String)> {
116 let mut notes = Vec::new();
117 let mut seen = HashSet::new();
118 for field in fields {
119 let Some(note) = field.get("footnote").and_then(Value::as_object) else {
120 continue;
121 };
122 let Some(mark) = note.get("mark").and_then(Value::as_str) else {
123 continue;
124 };
125 if mark.is_empty() || !seen.insert(mark.to_string()) {
126 continue;
127 }
128 notes.push((
129 mark.to_string(),
130 note.get("text").and_then(Value::as_str).unwrap_or_default().to_string(),
131 ));
132 }
133 notes
134}
135
136fn notes_from_columns(columns: &[Column]) -> Vec<(String, String)> {
137 notes_from_field_dicts(&columns.iter().map(|column| column.field.clone()).collect::<Vec<_>>())
138}
139
140fn section_notes(section: &Value) -> Vec<(String, String)> {
141 section
142 .get("source")
143 .and_then(Value::as_str)
144 .filter(|source| !source.is_empty())
145 .map(|source| vec![("source".to_string(), source.to_string())])
146 .unwrap_or_default()
147}
148
149fn attach_notes(table: &mut Table, notes: Vec<(String, String)>) {
150 let mut known: HashSet<String> = table.notes.iter().map(|(ref_, _)| ref_.clone()).collect();
151 for (ref_, text) in notes {
152 if known.insert(ref_.clone()) {
153 table.notes.push((ref_, text));
154 }
155 }
156}
157
158fn column_mark(column: &Column) -> Option<&str> {
159 column
160 .field
161 .get("footnote")
162 .and_then(|note| note.get("mark"))
163 .and_then(Value::as_str)
164 .filter(|mark| !mark.is_empty())
165}
166
167fn column_label(column: &Column) -> String {
168 match column_mark(column) {
169 Some(mark) => format!("{} [{}]", column.label, mark),
170 None => column.label.clone(),
171 }
172}
173
174#[cfg(feature = "xlsx")]
175fn sheet_name(base: &str, used: &mut HashSet<String>) -> String {
176 let clean: String = base.chars().map(|ch| if "\\/*?:[]".contains(ch) { '-' } else { ch }).collect();
177 let clean = clean.trim();
178 let clean = if clean.is_empty() { "Sheet" } else { clean };
179 let mut name = clean.chars().take(31).collect::<String>();
180 let mut index = 2usize;
181 while used.contains(&name) {
182 let suffix = format!("_{index}");
183 let available = 31usize.saturating_sub(suffix.len());
184 name = format!("{}{suffix}", clean.chars().take(available).collect::<String>());
185 index += 1;
186 }
187 used.insert(name.clone());
188 name
189}
190
191fn crosstab_table(crosstab: &Value, meta: Option<&Value>) -> Table {
192 let object = crosstab.as_object().cloned().unwrap_or_default();
193 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
194 let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
195 let row_field = object.get("row_field").cloned().unwrap_or(Value::Null);
196 let col_field = object.get("col_field").cloned().unwrap_or(Value::Null);
197 let measure_field = object.get("measure_field").cloned().unwrap_or(Value::Null);
198 let mask = object.get("mask").and_then(Value::as_str).unwrap_or("str").to_string();
199 let row_label = object.get("row_label").and_then(Value::as_str).unwrap_or(" ");
200 let total_label = object.get("total_label").and_then(Value::as_str).unwrap_or("Total");
201 let totals = object.get("totals").and_then(Value::as_bool).unwrap_or(true);
202 let has_data = object.get("has_data").and_then(Value::as_bool).unwrap_or(false);
203 let col_headers = object.get("col_headers").and_then(Value::as_array).cloned().unwrap_or_default();
204 let col_mask = col_field.get("format_mask").and_then(Value::as_str).unwrap_or("str");
205 let mut columns = vec![Column {
206 key: "__row__".to_string(),
207 label: row_label.to_string(),
208 mask: "str".to_string(),
209 rules: Vec::new(),
210 field: row_field,
211 }];
212 for (index, header) in col_headers.iter().enumerate() {
213 let label = format_value(header, col_mask, locale, currency, Some(&col_field)).unwrap_or_else(|_| pyops::py_str(header));
214 columns.push(Column {
215 key: format!("__c{index}__"),
216 label,
217 mask: mask.clone(),
218 rules: Vec::new(),
219 field: measure_field.clone(),
220 });
221 }
222 if totals {
223 columns.push(Column {
224 key: "__total__".to_string(),
225 label: total_label.to_string(),
226 mask: mask.clone(),
227 rules: Vec::new(),
228 field: measure_field.clone(),
229 });
230 }
231 let empty_text = object.get("empty_text").and_then(Value::as_str).unwrap_or_default();
232 let mut table = Table::new("crosstab", columns);
233 table.note = if has_data { String::new() } else { empty_text.to_string() };
234 let row_headers = object.get("row_headers").and_then(Value::as_array).cloned().unwrap_or_default();
235 let cells = object.get("cells").and_then(Value::as_array).cloned().unwrap_or_default();
236 let row_totals = object.get("row_totals").and_then(Value::as_array).cloned().unwrap_or_default();
237 for (index, row_header) in row_headers.iter().enumerate() {
238 let mut record = IndexMap::new();
239 record.insert("__row__".to_string(), row_header.clone());
240 if let Some(cells) = cells.get(index).and_then(Value::as_array) {
241 for (cell_index, cell) in cells.iter().enumerate() {
242 record.insert(format!("__c{cell_index}__"), cell.clone());
243 }
244 }
245 if totals {
246 record.insert("__total__".to_string(), row_totals.get(index).cloned().unwrap_or(Value::Null));
247 }
248 table.rows.push(record);
249 }
250 if totals && has_data {
251 let mut record = IndexMap::new();
252 record.insert("__row__".to_string(), Value::String(total_label.to_string()));
253 if let Some(col_totals) = object.get("col_totals").and_then(Value::as_array) {
254 for (index, total) in col_totals.iter().enumerate() {
255 record.insert(format!("__c{index}__"), total.clone());
256 }
257 }
258 record.insert("__total__".to_string(), object.get("grand_total").cloned().unwrap_or(Value::Null));
259 table.rows.push(record);
260 table.total_rows.insert(table.rows.len() - 1);
261 }
262 table
263}
264
265fn collect_inner(dataset: &Value, layout: &Value, meta: Option<&Value>, default_name: &str) -> (Vec<Table>, Vec<SummaryRow>) {
266 let mut summaries = Vec::new();
267 let mut by_key: IndexMap<String, Table> = IndexMap::new();
268
269 fn table_for<'a>(by_key: &'a mut IndexMap<String, Table>, key: &str, columns: &[Column]) -> &'a mut Table {
270 by_key.entry(key.to_string()).or_insert_with(|| Table::new(key, columns.to_vec()))
271 }
272
273 fn visit(
274 items: &[Value],
275 fragment: &Value,
276 context: &[(Column, Value)],
277 by_key: &mut IndexMap<String, Table>,
278 summaries: &mut Vec<SummaryRow>,
279 ) {
280 let header = fragment.get("header").and_then(Value::as_array).cloned().unwrap_or_default();
281 for item in items {
282 let Some(item) = item.as_object() else {
283 continue;
284 };
285 let fields = item.get("fields").and_then(Value::as_object).cloned().unwrap_or_default();
286 let mut ctx = context.to_vec();
287 for field in &header {
288 let column = column_from_field(field);
289 let value = fields.get(&column.key).cloned().unwrap_or(Value::Null);
290 ctx.push((column, value));
291 }
292 let details = item.get("details").and_then(Value::as_object).cloned().unwrap_or_default();
293 let layouts = fragment.get("details").and_then(Value::as_object).cloned().unwrap_or_default();
294 for (table_key, table_layout) in &layouts {
295 let table_data = details.get(table_key).and_then(Value::as_object).cloned().unwrap_or_default();
296 let rows: Vec<Value> = table_data
297 .get("rows")
298 .and_then(Value::as_array)
299 .cloned()
300 .unwrap_or_default()
301 .into_iter()
302 .filter(Value::is_object)
303 .collect();
304 let footer = table_data.get("footer").and_then(Value::as_object).cloned();
305 let empty_text = table_data.get("empty_text").and_then(Value::as_str);
306 if rows.is_empty() && footer.is_none() && empty_text.is_none() {
307 continue;
308 }
309 let table_fields = table_layout.as_array().cloned().unwrap_or_default();
310 let columns = merge_columns(&ctx.iter().map(|(column, _)| column.clone()).collect::<Vec<_>>(), &table_fields);
311 let sheet = table_for(by_key, table_key, &columns);
312 if let Some(empty_text) = empty_text {
313 sheet.note = empty_text.to_string();
314 }
315 attach_notes(sheet, notes_from_columns(&columns));
316 let mut base = IndexMap::new();
317 for (column, value) in &ctx {
318 base.insert(column.key.clone(), value.clone());
319 }
320 for row in &rows {
321 let mut record: IndexMap<String, Value> = columns.iter().map(|column| (column.key.clone(), Value::Null)).collect();
322 record.extend(base.clone());
323 if let Some(row) = row.as_object() {
324 record.extend(row.clone());
325 }
326 sheet.rows.push(record);
327 }
328 if let Some(footer) = footer {
329 sheet.rows.push(footer.clone());
330 sheet.total_rows.insert(sheet.rows.len() - 1);
331 }
332 }
333 if let Some(groups) = item.get("groups").and_then(Value::as_array) {
334 if let Some(child_fragment) = fragment.get("groups") {
335 visit(groups, child_fragment, &ctx, by_key, summaries);
336 }
337 }
338 if let Some(footer) = item.get("footer").and_then(Value::as_object) {
339 if let Some(footer_layout) = fragment.get("footer").and_then(Value::as_array) {
340 let path = ctx
341 .iter()
342 .filter(|(_, value)| !value.is_null() && !matches!(value, Value::String(text) if text.is_empty()))
343 .map(|(_, value)| pyops::py_str(value))
344 .collect::<Vec<_>>()
345 .join(" / ");
346 for field in footer_layout {
347 let Some(name) = field.get("name").and_then(Value::as_str) else {
348 continue;
349 };
350 let Some(value) = footer.get(name) else {
351 continue;
352 };
353 if value.is_null() || matches!(value, Value::String(text) if text.is_empty()) {
354 continue;
355 }
356 let label = field.get("label").map(pyops::py_str).unwrap_or_else(|| name.to_string());
357 let label = if path.is_empty() { label } else { format!("{path} / {label}") };
358 summaries.push(SummaryRow {
359 label,
360 value: value.clone(),
361 mask: field.get("format_mask").and_then(Value::as_str).unwrap_or("str").to_string(),
362 });
363 }
364 }
365 }
366 }
367 }
368
369 let top = dataset.get("groups").and_then(Value::as_array).cloned().unwrap_or_default();
370 let root = layout.get("groups").cloned().unwrap_or(Value::Null);
371 visit(&top, &root, &[], &mut by_key, &mut summaries);
372
373 if let Some(summary) = dataset.get("summary").and_then(Value::as_object) {
374 if let Some(summary_layout) = layout.get("summary").and_then(Value::as_array) {
375 for field in summary_layout {
376 let Some(name) = field.get("name").and_then(Value::as_str) else {
377 continue;
378 };
379 if let Some(value) = summary.get(name) {
380 summaries.push(SummaryRow {
381 label: field.get("label").map(pyops::py_str).unwrap_or_else(|| name.to_string()),
382 value: value.clone(),
383 mask: field.get("format_mask").and_then(Value::as_str).unwrap_or("str").to_string(),
384 });
385 }
386 }
387 }
388 }
389
390 if let Some(sections) = dataset.get("sections").and_then(Value::as_array) {
391 for section in sections {
392 let Some(section) = section.as_object() else {
393 continue;
394 };
395 let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
396 match section_type {
397 "table" => {
398 let title = section.get("title").and_then(Value::as_str);
399 let sub_dataset = section.get("dataset").cloned().unwrap_or(Value::Null);
400 let sub_layout = section.get("layout").cloned().unwrap_or(Value::Null);
401 let (sub_tables, sub_summaries) = collect_inner(&sub_dataset, &sub_layout, meta, title.unwrap_or("table"));
402 for mut table in sub_tables {
403 let key = match title {
404 Some(title) if !title.is_empty() && table.key != title => {
405 format!("{title} - {}", table.key)
406 }
407 _ => table.key.clone(),
408 };
409 let mut suffix = key.clone();
410 let mut index = 2usize;
411 while by_key.contains_key(&suffix) {
412 suffix = format!("{key}_{index}");
413 index += 1;
414 }
415 table.key = suffix.clone();
416 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
417 by_key.insert(suffix, table);
418 }
419 for row in sub_summaries {
420 summaries.push(SummaryRow {
421 label: match title {
422 Some(title) if !title.is_empty() => format!("{title} / {}", row.label),
423 _ => row.label,
424 },
425 value: row.value,
426 mask: row.mask,
427 });
428 }
429 }
430 "text" => {
431 let paragraphs: Vec<String> = section
432 .get("paragraphs")
433 .and_then(Value::as_array)
434 .cloned()
435 .unwrap_or_default()
436 .iter()
437 .filter_map(|value| value.as_str().map(str::to_string))
438 .collect();
439 if !paragraphs.is_empty() {
440 let key = section.get("title").and_then(Value::as_str).unwrap_or("notes").to_string();
441 let mut table = Table::new(key.clone(), vec![Column::new("text", "Text")]);
442 table.rows = paragraphs
443 .into_iter()
444 .map(|paragraph| {
445 let mut row = IndexMap::new();
446 row.insert("text".to_string(), Value::String(paragraph));
447 row
448 })
449 .collect();
450 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
451 by_key.insert(key, table);
452 }
453 }
454 "kpi" => {
455 let items = section.get("items").and_then(Value::as_array).cloned().unwrap_or_default();
456 let rows: Vec<IndexMap<String, Value>> = items
457 .iter()
458 .filter_map(Value::as_object)
459 .map(|item| {
460 let mut row = IndexMap::new();
461 row.insert("label".to_string(), item.get("label").cloned().unwrap_or(Value::Null));
462 row.insert("value".to_string(), item.get("value").cloned().unwrap_or(Value::Null));
463 row
464 })
465 .collect();
466 if !rows.is_empty() {
467 let key = section.get("title").and_then(Value::as_str).unwrap_or("kpi").to_string();
468 let mut table = Table::new(key.clone(), vec![Column::new("label", "Label"), Column::new("value", "Value")]);
469 table.rows = rows;
470 attach_notes(&mut table, notes_from_field_dicts(&items));
471 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
472 by_key.insert(key, table);
473 }
474 }
475 "chart" => {
476 let spec = section.get("chart").and_then(Value::as_object).cloned().unwrap_or_default();
477 let labels = spec.get("labels").and_then(Value::as_array).cloned().unwrap_or_default();
478 let values = spec.get("values").and_then(Value::as_array).cloned().unwrap_or_default();
479 let mut rows = Vec::new();
480 for (label, value) in labels.iter().zip(values.iter()) {
481 let mut row = IndexMap::new();
482 row.insert("label".to_string(), label.clone());
483 row.insert("value".to_string(), value.clone());
484 rows.push(row);
485 }
486 if !rows.is_empty() {
487 let key = section
488 .get("title")
489 .and_then(Value::as_str)
490 .or_else(|| spec.get("title").and_then(Value::as_str))
491 .unwrap_or("chart")
492 .to_string();
493 let mut table = Table::new(key.clone(), vec![Column::new("label", "Label"), Column::new("value", "Value")]);
494 table.rows = rows;
495 let mut chart = IndexMap::new();
496 chart.insert(
497 "kind".to_string(),
498 spec.get("kind").cloned().unwrap_or_else(|| Value::String("bar".to_string())),
499 );
500 chart.insert("title".to_string(), Value::String(key.clone()));
501 chart.insert("color".to_string(), spec.get("color").cloned().unwrap_or(Value::Null));
502 chart.insert("orientation".to_string(), spec.get("orientation").cloned().unwrap_or(Value::Null));
503 table.chart = Some(Value::Object(chart));
504 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
505 by_key.insert(key, table);
506 }
507 }
508 "image" => {
509 let label = section
510 .get("alt")
511 .and_then(Value::as_str)
512 .or_else(|| section.get("caption").and_then(Value::as_str))
513 .unwrap_or("image");
514 let key = section.get("title").and_then(Value::as_str).unwrap_or("image");
515 let mut suffix = key.to_string();
516 let mut index = 2usize;
517 while by_key.contains_key(&suffix) {
518 suffix = format!("{key}_{index}");
519 index += 1;
520 }
521 let mut table = Table::new(suffix.clone(), vec![Column::new("image", "Image")]);
522 let mut row = IndexMap::new();
523 row.insert("image".to_string(), Value::String(label.to_string()));
524 table.rows.push(row);
525 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
526 by_key.insert(suffix, table);
527 }
528 "toc" => {
529 let rows: Vec<IndexMap<String, Value>> = section
530 .get("items")
531 .and_then(Value::as_array)
532 .cloned()
533 .unwrap_or_default()
534 .iter()
535 .filter_map(Value::as_object)
536 .filter_map(|item| item.get("title"))
537 .filter(|value| value.truthy())
538 .map(|title| {
539 let mut row = IndexMap::new();
540 row.insert("section".to_string(), title.clone());
541 row
542 })
543 .collect();
544 if !rows.is_empty() {
545 let key = section.get("title").and_then(Value::as_str).unwrap_or("contents");
546 let mut suffix = key.to_string();
547 let mut index = 2usize;
548 while by_key.contains_key(&suffix) {
549 suffix = format!("{key}_{index}");
550 index += 1;
551 }
552 let mut table = Table::new(suffix.clone(), vec![Column::new("section", "Section")]);
553 table.rows = rows;
554 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
555 by_key.insert(suffix, table);
556 }
557 }
558 "crosstab" => {
559 if let Some(crosstab) = section.get("crosstab") {
560 let mut table = crosstab_table(crosstab, meta);
561 if !table.rows.is_empty() || !table.note.is_empty() {
562 let title = section.get("title").and_then(Value::as_str);
563 let key = title.unwrap_or(table.key.as_str()).to_string();
564 let mut suffix = key.clone();
565 let mut index = 2usize;
566 while by_key.contains_key(&suffix) {
567 suffix = format!("{key}_{index}");
568 index += 1;
569 }
570 table.key = suffix.clone();
571 let notes = notes_from_columns(&table.columns);
572 attach_notes(&mut table, notes);
573 attach_notes(&mut table, section_notes(&Value::Object(section.clone())));
574 by_key.insert(suffix, table);
575 }
576 }
577 }
578 _ => {}
579 }
580 }
581 }
582
583 if by_key.is_empty() && !top.is_empty() {
584 let header = layout
585 .get("groups")
586 .and_then(|groups| groups.get("header"))
587 .and_then(Value::as_array)
588 .cloned()
589 .unwrap_or_default();
590 let columns: Vec<Column> = header.iter().map(column_from_field).collect();
591 if !columns.is_empty() {
592 let mut sheet = Table::new(default_name, columns.clone());
593 attach_notes(&mut sheet, notes_from_columns(&columns));
594 for item in &top {
595 let Some(fields) = item.get("fields").and_then(Value::as_object) else {
596 continue;
597 };
598 let mut row = IndexMap::new();
599 for column in &columns {
600 row.insert(column.key.clone(), fields.get(&column.key).cloned().unwrap_or(Value::Null));
601 }
602 sheet.rows.push(row);
603 }
604 by_key.insert(default_name.to_string(), sheet);
605 }
606 }
607
608 (by_key.into_values().collect(), summaries)
609}
610
611pub fn collect_tables(dataset: &Value, layout: &Value, meta: Option<&Value>) -> (Vec<Table>, Vec<SummaryRow>) {
613 collect_inner(dataset, layout, meta, "data")
614}
615
616fn guard_formula(value: &str, raw: &Value) -> String {
617 let numeric = matches!(
618 raw,
619 Value::Int(_) | Value::UInt(_) | Value::Float(_) | Value::Decimal(_) | Value::Bool(_)
620 );
621 if !numeric && value.starts_with(['=', '+', '-', '@', '\t', '\r']) {
622 format!("'{value}")
623 } else {
624 value.to_string()
625 }
626}
627
628fn cell_text(row: &IndexMap<String, Value>, column: &Column, meta: Option<&Value>) -> Result<String> {
629 let value = row.get(&column.key).unwrap_or(&Value::Null);
630 if column.mask == "sparkline" {
631 return Ok(sparkline_text(value));
632 }
633 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
634 let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
635 format_value(value, &column.mask, locale, currency, Some(&column.field))
636}
637
638pub fn render_csv(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>, delimiter: char) -> Result<String> {
640 if !delimiter.is_ascii() {
641 return Err(Error::option(format!(
642 "Invalid CSV delimiter (must be a single ASCII character): {delimiter:?}"
643 )));
644 }
645 let mut writer = csv::WriterBuilder::new()
646 .delimiter(delimiter as u8)
647 .terminator(csv::Terminator::Any(b'\n'))
648 .quote_style(csv::QuoteStyle::Necessary)
649 .flexible(true)
650 .from_writer(Vec::new());
651 let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
652 if let Some(title) = title {
653 writer.write_record([format!("# {title}")])?;
654 }
655 if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
656 writer.write_record([format!("# [source] {source_note}")])?;
657 }
658 for table in tables {
659 writer.write_record([format!("# table: {}", table.key)])?;
660 writer.write_record(table.columns.iter().map(column_label))?;
661 if table.rows.is_empty() && !table.note.is_empty() {
662 writer.write_record([format!("# {}", table.note)])?;
663 }
664 for row in &table.rows {
665 let mut record = Vec::with_capacity(table.columns.len());
666 for column in &table.columns {
667 let raw = row.get(&column.key).cloned().unwrap_or(Value::Null);
668 let text = cell_text(row, column, meta)?;
669 record.push(guard_formula(&text, &raw));
670 }
671 writer.write_record(record)?;
672 }
673 for (ref_, text) in &table.notes {
674 writer.write_record([format!("# [{ref_}] {text}")])?;
675 }
676 }
677 if !summaries.is_empty() {
678 writer.write_record(["# summary"])?;
679 writer.write_record(["Item", "Value"])?;
680 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
681 let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
682 for row in summaries {
683 let text = format_value(&row.value, &row.mask, locale, currency, None)?;
684 writer.write_record([row.label.clone(), guard_formula(&text, &row.value)])?;
685 }
686 }
687 let bytes = writer
688 .into_inner()
689 .map_err(|error| Error::message(format!("CSV writer error: {error}")))?;
690 String::from_utf8(bytes).map_err(|error| Error::message(format!("CSV is not UTF-8: {error}")))
691}
692
693#[cfg(feature = "xlsx")]
695pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
696 xlsx_impl::build_workbook(tables, summaries, meta)
697}
698
699#[cfg(not(feature = "xlsx"))]
701pub fn build_workbook(_tables: &[Table], _summaries: &[SummaryRow], _meta: Option<&Value>) -> Result<Vec<u8>> {
702 Err(Error::FeatureDisabled("XLSX export requires the 'xlsx' feature (rust_xlsxwriter)"))
703}
704
705#[cfg(any())]
706mod xlsx {
707 use super::*;
708 use rust_xlsxwriter::{Chart, ChartType, Color, Format, FormatAlign, FormatBorder, Workbook, Worksheet};
709
710 fn argb(spec: &str) -> String {
711 let hex = spec.trim_start_matches('#');
712 let hex = if hex.len() == 3 {
713 hex.chars().flat_map(|ch| [ch, ch]).collect::<String>()
714 } else {
715 hex.to_string()
716 };
717 if hex.len() == 6 {
718 format!("FF{hex}")
719 } else {
720 hex
721 }
722 }
723
724 fn number_format(mask: &str, currency_symbol: &str) -> Option<&'static str> {
725 match mask {
726 "int" => Some("#,##0"),
727 "float" => Some("#,##0.00"),
728 "percent" => Some("0.00%"),
729 "currency" => {
730 let _ = currency_symbol;
731 None
732 }
733 "date" => Some("yyyy-mm-dd"),
734 _ => None,
735 }
736 }
737
738 fn currency_symbol(meta: Option<&Value>) -> String {
739 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
740 let code = meta
741 .and_then(|meta| meta.get("currency"))
742 .and_then(Value::as_str)
743 .map(str::to_string)
744 .or_else(|| crate::formatting::default_currency(locale).ok())
745 .unwrap_or_else(|| "USD".to_string());
746 crate::formatting::format_currency(0.0, &code, locale)
747 .ok()
748 .map(|text| {
749 text.chars()
750 .filter(|ch| !ch.is_ascii_digit() && !matches!(ch, ',' | '.' | '-' | '\u{a0}' | ' '))
751 .collect::<String>()
752 })
753 .filter(|symbol| !symbol.is_empty())
754 .unwrap_or_else(|| "$".to_string())
755 }
756
757 fn apply_cell_style(cell: &mut rust_xlsxwriter::Cell, raw: &Value, column: &Column, base: &Format) -> Result<()> {
758 let style = crate::formatting::cell_style_dict(
759 raw,
760 &Value::Object(
761 [("cell_rules".to_string(), Value::Array(column.rules.clone()))]
762 .into_iter()
763 .collect(),
764 ),
765 )?;
766 let mut format = base.clone();
767 if let Some(color) = style.color {
768 format = format.set_font_color(Color::RGB(u32::from_str_radix(&argb(&color)[2..], 16).unwrap_or(0)));
769 }
770 if style.bold {
771 format = format.set_bold();
772 }
773 if style.italic {
774 format = format.set_italic();
775 }
776 if let Some(background) = style.background.or_else(|| crate::formatting::scale_fill(raw, &column.field)) {
777 format = format.set_background_color(Color::RGB(u32::from_str_radix(&argb(&background)[2..], 16).unwrap_or(0xFFFFFF)));
778 }
779 cell.set_format(format);
780 Ok(())
781 }
782
783 pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
784 let mut workbook = Workbook::new();
785 let mut used = HashSet::new();
786 let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
787 let sub_title = meta.and_then(|meta| meta.get("sub_title")).and_then(Value::as_str);
788 let symbol = currency_symbol(meta);
789 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
790 let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
791
792 let header_format = Format::new()
793 .set_bold()
794 .set_font_color(Color::White)
795 .set_background_color(Color::RGB(0x0A2F46));
796 let note_format = Format::new().set_italic().set_font_color(Color::RGB(0x6B7280));
797 let total_format = Format::new().set_bold().set_border_top(FormatBorder::Thin);
798 let title_format = Format::new().set_bold().set_font_size(14);
799
800 if tables.is_empty() && summaries.is_empty() {
801 let sheet = workbook.add_worksheet();
802 let name = sheet_name(title.unwrap_or("Report"), &mut used);
803 sheet.set_name(&name)?;
804 sheet.write_string_with_format(0, 0, title.unwrap_or("Report"), &title_format)?;
805 return workbook
806 .save_to_buffer()
807 .map_err(|error| Error::message(format!("XLSX error: {error}")));
808 }
809
810 for table in tables {
811 let sheet = workbook.add_worksheet();
812 sheet.set_name(sheet_name(&table.key, &mut used))?;
813 let mut row_index: u32 = 0;
814 if let Some(title) = title {
815 sheet.write_string_with_format(row_index, 0, title, &title_format)?;
816 row_index += 1;
817 }
818 if let Some(sub_title) = sub_title {
819 sheet.write_string(row_index, 0, sub_title)?;
820 row_index += 1;
821 }
822 let header_row = row_index;
823 let mut widths: Vec<usize> = vec![0; table.columns.len()];
824 for (column_index, column) in table.columns.iter().enumerate() {
825 let label = column_label(column);
826 sheet.write_string_with_format(row_index, column_index as u16, &label, &header_format)?;
827 widths[column_index] = widths[column_index].max(label.chars().count());
828 }
829 if !table.columns.is_empty() {
830 sheet.set_freeze_panes(header_row + 1, 0)?;
831 sheet.set_autofilter(header_row, 0, header_row, (table.columns.len() - 1) as u16)?;
832 sheet.set_print_title_rows(header_row, header_row)?;
833 }
834 if table.rows.is_empty() && !table.note.is_empty() {
835 row_index += 1;
836 sheet.write_string_with_format(row_index, 0, &table.note, ¬e_format)?;
837 if let Some(width) = widths.first_mut() {
838 *width = (*width).max(table.note.chars().count());
839 }
840 }
841 for (position, record) in table.rows.iter().enumerate() {
842 row_index += 1;
843 let is_total = table.total_rows.contains(&position);
844 for (column_index, column) in table.columns.iter().enumerate() {
845 let raw = record.get(&column.key).cloned().unwrap_or(Value::Null);
846 let mapped = crate::formatting::field_text(&raw, Some(&column.field))?;
847 let value = mapped.unwrap_or_else(|| match &raw {
848 Value::Null => String::new(),
849 Value::Date(date) => date.format("%Y-%m-%d").to_string(),
850 Value::DateTime(datetime) => datetime.to_rfc3339(),
851 Value::Int(value) => value.to_string(),
852 Value::UInt(value) => value.to_string(),
853 Value::Float(value) => value.to_string(),
854 Value::Decimal(value) => value.to_string(),
855 Value::Bool(value) => {
856 if *value {
857 "Yes".to_string()
858 } else {
859 "No".to_string()
860 }
861 }
862 Value::String(value) => value.clone(),
863 other => pyops::py_str(other),
864 });
865 let value = guard_formula(&value, &raw);
866 let cell = sheet.write_string(row_index, column_index as u16, &value)?;
867 if is_total {
868 cell.set_format(total_format.clone());
869 }
870 apply_cell_style(cell, &raw, column, &Format::new())?;
871 if let Some(format) = number_format(&column.mask, &symbol) {
872 if let Ok(number) = value.replace(',', ".").parse::<f64>() {
873 let cell = sheet.write_number(row_index, column_index as u16, number)?;
874 cell.set_format(Format::new().set_num_format(format));
875 }
876 } else if column.mask == "currency" {
877 if let Ok(number) = value.replace('.', "").replace(',', ".").parse::<f64>() {
878 let cell = sheet.write_number(row_index, column_index as u16, number)?;
879 cell.set_format(Format::new().set_num_format(format!("\"{symbol}\"#,##0.00")));
880 }
881 }
882 widths[column_index] = widths[column_index].max(value.chars().count());
883 }
884 }
885 for (column_index, width) in widths.iter().enumerate() {
886 let width = (*width + 2).clamp(10, 50) as f64;
887 sheet.set_column_width(column_index as u16, width)?;
888 }
889 if let Some(chart) = &table.chart {
890 let _ = chart;
891 }
892 let _: &Worksheet = sheet;
893 let _ = locale;
894 let _ = currency;
895 }
896
897 if !summaries.is_empty() {
898 let sheet = workbook.add_worksheet();
899 sheet.set_name(sheet_name("Summary", &mut used))?;
900 let mut row_index: u32 = 0;
901 if let Some(title) = title {
902 sheet.write_string_with_format(row_index, 0, title, &title_format)?;
903 row_index += 1;
904 }
905 sheet.write_string_with_format(row_index, 0, "Item", &header_format)?;
906 sheet.write_string_with_format(row_index, 1, "Value", &header_format)?;
907 let mut widths = [4usize, 5usize];
908 for row in summaries {
909 row_index += 1;
910 sheet.write_string(row_index, 0, &row.label)?;
911 let text = format_value(&row.value, &row.mask, locale, currency, None)?;
912 sheet.write_string(row_index, 1, &text)?;
913 widths[0] = widths[0].max(row.label.chars().count());
914 widths[1] = widths[1].max(text.chars().count());
915 }
916 sheet.set_column_width(0, widths[0].clamp(4, 60) as f64)?;
917 sheet.set_column_width(1, widths[1].clamp(5, 30) as f64)?;
918 }
919
920 let mut note_rows: Vec<(String, String, String)> = Vec::new();
921 if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
922 note_rows.push((String::new(), "source".to_string(), source_note.to_string()));
923 }
924 for table in tables {
925 for (ref_, text) in &table.notes {
926 note_rows.push((table.key.clone(), ref_.clone(), text.clone()));
927 }
928 }
929 if !note_rows.is_empty() {
930 let sheet = workbook.add_worksheet();
931 sheet.set_name(sheet_name("Notes", &mut used))?;
932 sheet.write_string_with_format(0, 0, "Table", &header_format)?;
933 sheet.write_string_with_format(0, 1, "Ref", &header_format)?;
934 sheet.write_string_with_format(0, 2, "Note", &header_format)?;
935 let mut widths = [5usize, 3usize, 4usize];
936 for (index, (table, ref_, text)) in note_rows.iter().enumerate() {
937 let row = index as u32 + 1;
938 sheet.write_string(row, 0, table)?;
939 sheet.write_string(row, 1, ref_)?;
940 sheet.write_string(row, 2, text)?;
941 widths[0] = widths[0].max(table.chars().count());
942 widths[1] = widths[1].max(ref_.chars().count());
943 widths[2] = widths[2].max(text.chars().count());
944 }
945 sheet.set_column_width(0, widths[0].clamp(5, 40) as f64)?;
946 sheet.set_column_width(1, widths[1].clamp(3, 12) as f64)?;
947 sheet.set_column_width(2, widths[2].clamp(4, 80) as f64)?;
948 }
949
950 workbook
951 .save_to_buffer()
952 .map_err(|error| Error::message(format!("XLSX error: {error}")))
953 }
954
955 #[allow(dead_code)]
957 fn _chart_placeholder() -> Chart {
958 Chart::new(ChartType::Bar)
959 }
960}
961
962#[cfg(feature = "xlsx")]
963mod xlsx_impl {
964 use super::*;
965 use rust_xlsxwriter::{
966 Chart, ChartFormat, ChartLine, ChartSolidFill, ChartType, Color, ConditionalFormatDataBar, ConditionalFormatType, Format,
967 FormatBorder, Workbook, Worksheet,
968 };
969
970 fn rgb(spec: &str) -> Color {
971 let hex = spec.trim_start_matches('#');
972 let hex = if hex.len() == 3 {
973 hex.chars().flat_map(|ch| [ch, ch]).collect::<String>()
974 } else {
975 hex.to_string()
976 };
977 Color::RGB(u32::from_str_radix(&hex, 16).unwrap_or(0))
978 }
979
980 fn number_format(mask: &str, symbol: &str) -> Option<String> {
981 match mask {
982 "int" => Some("#,##0".to_string()),
983 "float" => Some("#,##0.00".to_string()),
984 "percent" => Some("0.00%".to_string()),
985 "currency" => Some(format!("\"{symbol}\"#,##0.00")),
986 "date" => Some("yyyy-mm-dd".to_string()),
987 _ => None,
988 }
989 }
990
991 fn currency_symbol(meta: Option<&Value>) -> String {
992 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
993 let code = meta
994 .and_then(|meta| meta.get("currency"))
995 .and_then(Value::as_str)
996 .unwrap_or_default();
997 let symbol = crate::formatting::xlsx_currency_symbol(code, locale);
998 if symbol.is_empty() {
999 "$".to_string()
1000 } else {
1001 symbol
1002 }
1003 }
1004
1005 fn numeric_value(raw: &Value, mask: &str) -> Option<f64> {
1006 match mask {
1007 "int" => pyops::py_int(raw).ok().map(|value| value as f64),
1008 "float" | "percent" | "currency" => pyops::py_float(raw).ok(),
1009 _ => match raw {
1010 Value::Int(value) => Some(*value as f64),
1011 Value::UInt(value) => Some(*value as f64),
1012 Value::Float(value) => Some(*value),
1013 Value::Decimal(value) => value.to_string().parse::<f64>().ok(),
1014 _ => None,
1015 },
1016 }
1017 }
1018
1019 enum NativeCell {
1020 Empty,
1021 Bool(bool),
1022 Number(f64),
1023 DateTime(rust_xlsxwriter::ExcelDateTime),
1024 Text(String),
1025 }
1026
1027 fn boolean_text(raw: &Value) -> String {
1028 let truthy = match raw {
1029 Value::String(value) => matches!(value.trim().to_lowercase().as_str(), "true" | "yes" | "y" | "1"),
1030 other => other.truthy(),
1031 };
1032 if truthy { "Yes" } else { "No" }.to_string()
1033 }
1034
1035 fn excel_datetime(raw: &Value) -> Option<rust_xlsxwriter::ExcelDateTime> {
1036 use chrono::{Datelike, Timelike};
1037 match raw {
1038 Value::Date(date) => rust_xlsxwriter::ExcelDateTime::from_ymd(date.year() as u16, date.month() as u8, date.day() as u8).ok(),
1039 Value::DateTime(datetime) => {
1040 let local = datetime.naive_local();
1041 rust_xlsxwriter::ExcelDateTime::from_ymd(local.year() as u16, local.month() as u8, local.day() as u8)
1042 .ok()?
1043 .and_hms(local.hour() as u16, local.minute() as u8, local.second() as f64)
1044 .ok()
1045 }
1046 _ => None,
1047 }
1048 }
1049
1050 fn native_cell(raw: &Value, column: &Column, meta: Option<&Value>) -> Result<NativeCell> {
1051 if let Some(mapped) = crate::formatting::field_text(raw, Some(&column.field))? {
1052 return Ok(NativeCell::Text(mapped));
1053 }
1054 match column.mask.as_str() {
1055 "sparkline" => return Ok(NativeCell::Text(sparkline_text(raw))),
1056 "bool" => return Ok(NativeCell::Text(boolean_text(raw))),
1057 _ => {}
1058 }
1059 if let Some(datetime) = excel_datetime(raw) {
1060 return Ok(NativeCell::DateTime(datetime));
1061 }
1062 if let Some(number) = numeric_value(raw, &column.mask) {
1063 return Ok(NativeCell::Number(number));
1064 }
1065 Ok(match raw {
1066 Value::Null => NativeCell::Empty,
1067 Value::Bool(value) => NativeCell::Bool(*value),
1068 other => NativeCell::Text(display_text(other, column, meta)?),
1069 })
1070 }
1071
1072 fn base_format(raw: &Value, column: &Column, total: bool) -> Format {
1073 let mut format = Format::new();
1074 if total {
1075 format = format.set_bold().set_border_top(FormatBorder::Thin);
1076 }
1077 if let Ok(style) = crate::formatting::cell_style_dict(raw, &column.field) {
1078 if let Some(color) = style.color {
1079 format = format.set_font_color(rgb(&color));
1080 }
1081 if style.bold {
1082 format = format.set_bold();
1083 }
1084 if style.italic {
1085 format = format.set_italic();
1086 }
1087 if let Some(background) = style.background.or_else(|| crate::formatting::scale_fill(raw, &column.field)) {
1088 format = format.set_background_color(rgb(&background));
1089 }
1090 }
1091 format
1092 }
1093
1094 fn display_text(raw: &Value, column: &Column, meta: Option<&Value>) -> Result<String> {
1095 if let Some(mapped) = crate::formatting::field_text(raw, Some(&column.field))? {
1096 return Ok(mapped);
1097 }
1098 let locale = meta.and_then(|meta| meta.get("locale")).and_then(Value::as_str).unwrap_or("pt-BR");
1099 let currency = meta.and_then(|meta| meta.get("currency")).and_then(Value::as_str);
1100 if column.mask == "sparkline" {
1101 return Ok(sparkline_text(raw));
1102 }
1103 crate::formatting::format_value(raw, &column.mask, locale, currency, Some(&column.field))
1104 }
1105
1106 fn add_data_bars(sheet: &mut Worksheet, header_row: u32, table: &Table) -> Result<()> {
1107 if table.rows.is_empty() {
1108 return Ok(());
1109 }
1110 for (column_index, column) in table.columns.iter().enumerate() {
1111 let Some(field) = column.field.as_object() else {
1112 continue;
1113 };
1114 if field.get("data_bar") != Some(&Value::Bool(true)) {
1115 continue;
1116 }
1117 let numbers: Vec<f64> = table
1118 .rows
1119 .iter()
1120 .filter_map(|record| record.get(&column.key))
1121 .filter(|value| !matches!(value, Value::Bool(_)))
1122 .filter_map(|value| pyops::py_float(value).ok())
1123 .collect();
1124 if numbers.len() < 2 {
1125 continue;
1126 }
1127 let min = numbers.iter().copied().fold(f64::INFINITY, f64::min);
1128 let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1129 if min >= max {
1130 continue;
1131 }
1132 let format = ConditionalFormatDataBar::new()
1133 .set_minimum(ConditionalFormatType::Number, min)
1134 .set_maximum(ConditionalFormatType::Number, max)
1135 .set_fill_color(Color::RGB(0x0A2F46));
1136 sheet.add_conditional_format(
1137 header_row + 1,
1138 column_index as u16,
1139 header_row + table.rows.len() as u32,
1140 column_index as u16,
1141 &format,
1142 )?;
1143 }
1144 Ok(())
1145 }
1146
1147 fn add_native_chart(sheet: &mut Worksheet, header_row: u32, table: &Table) -> Result<()> {
1148 let Some(spec) = table.chart.as_ref().and_then(Value::as_object) else {
1149 return Ok(());
1150 };
1151 if table.rows.is_empty() || table.columns.len() < 2 {
1152 return Ok(());
1153 }
1154 let kind = spec.get("kind").and_then(Value::as_str).unwrap_or("bar");
1155 let horizontal = spec.get("orientation").and_then(Value::as_str) == Some("horizontal");
1156 let chart_type = match kind {
1157 "line" => ChartType::Line,
1158 "pie" => ChartType::Pie,
1159 "donut" | "doughnut" => ChartType::Doughnut,
1160 _ if horizontal => ChartType::Bar,
1161 _ => ChartType::Column,
1162 };
1163 let mut chart = Chart::new(chart_type);
1164 let last_row = header_row + table.rows.len() as u32;
1165 let sheet_name = sheet.name().to_string();
1166 let series_label = column_label(&table.columns[1]);
1167 let series_format = spec
1168 .get("color")
1169 .and_then(Value::as_str)
1170 .filter(|color| matches!(color.trim_start_matches('#').len(), 3 | 6))
1171 .and_then(|color| {
1172 let color = rgb(color);
1173 let mut format = ChartFormat::new();
1174 match kind {
1175 "line" => {
1176 let mut line = ChartLine::new();
1177 line.set_color(color).set_width(2.25);
1178 format.set_line(&line);
1179 }
1180 "bar" => {
1181 let mut fill = ChartSolidFill::new();
1182 fill.set_color(color);
1183 format.set_solid_fill(&fill);
1184 }
1185 _ => return None,
1186 }
1187 Some(format)
1188 });
1189 let series = chart.add_series();
1190 series
1191 .set_name(series_label.as_str())
1192 .set_values((sheet_name.as_str(), header_row + 1, 1, last_row, 1))
1193 .set_categories((sheet_name.as_str(), header_row + 1, 0, last_row, 0));
1194 if let Some(mut format) = series_format {
1195 series.set_format(&mut format);
1196 }
1197 let title = spec.get("title").and_then(Value::as_str).unwrap_or(&table.key);
1198 chart.title().set_name(title);
1199 chart.set_style(10).set_width(600).set_height(300);
1200 sheet.insert_chart(header_row, 3, &chart)?;
1201 Ok(())
1202 }
1203
1204 pub fn build_workbook(tables: &[Table], summaries: &[SummaryRow], meta: Option<&Value>) -> Result<Vec<u8>> {
1205 let mut workbook = Workbook::new();
1206 let mut used = HashSet::new();
1207 let title = meta.and_then(|meta| meta.get("title")).and_then(Value::as_str);
1208 let sub_title = meta.and_then(|meta| meta.get("sub_title")).and_then(Value::as_str);
1209 let symbol = currency_symbol(meta);
1210
1211 let header_format = Format::new()
1212 .set_bold()
1213 .set_font_color(Color::White)
1214 .set_background_color(Color::RGB(0x0A2F46));
1215 let note_format = Format::new().set_italic().set_font_color(Color::RGB(0x6B7280));
1216 let title_format = Format::new().set_bold().set_font_size(14);
1217
1218 if tables.is_empty() && summaries.is_empty() {
1219 let sheet = workbook.add_worksheet();
1220 sheet.set_name(sheet_name(title.unwrap_or("Report"), &mut used))?;
1221 sheet.write_string_with_format(0, 0, title.unwrap_or("Report"), &title_format)?;
1222 return workbook
1223 .save_to_buffer()
1224 .map_err(|error| Error::message(format!("XLSX error: {error}")));
1225 }
1226
1227 for table in tables {
1228 let sheet = workbook.add_worksheet();
1229 sheet.set_name(sheet_name(&table.key, &mut used))?;
1230 let mut row_index: u32 = 0;
1231 if let Some(title) = title {
1232 sheet.write_string_with_format(row_index, 0, title, &title_format)?;
1233 row_index += 1;
1234 }
1235 if let Some(sub_title) = sub_title {
1236 sheet.write_string(row_index, 0, sub_title)?;
1237 row_index += 1;
1238 }
1239 let header_row = row_index;
1240 let mut widths: Vec<usize> = vec![0; table.columns.len()];
1241 for (column_index, column) in table.columns.iter().enumerate() {
1242 let label = column_label(column);
1243 sheet.write_string_with_format(row_index, column_index as u16, &label, &header_format)?;
1244 widths[column_index] = widths[column_index].max(label.chars().count());
1245 }
1246 if !table.columns.is_empty() {
1247 sheet.set_freeze_panes(header_row + 1, 0)?;
1248 sheet.autofilter(header_row, 0, header_row, (table.columns.len() - 1) as u16)?;
1249 sheet.set_repeat_rows(header_row, header_row)?;
1250 }
1251 if table.rows.is_empty() && !table.note.is_empty() {
1252 row_index += 1;
1253 sheet.write_string_with_format(row_index, 0, &table.note, ¬e_format)?;
1254 if let Some(width) = widths.first_mut() {
1255 *width = (*width).max(table.note.chars().count());
1256 }
1257 }
1258 for (position, record) in table.rows.iter().enumerate() {
1259 row_index += 1;
1260 let is_total = table.total_rows.contains(&position);
1261 for (column_index, column) in table.columns.iter().enumerate() {
1262 let raw = record.get(&column.key).cloned().unwrap_or(Value::Null);
1263 let format = base_format(&raw, column, is_total);
1264 let format = match number_format(&column.mask, &symbol) {
1265 Some(number_format) => format.set_num_format(number_format),
1266 None => format,
1267 };
1268 let cell = native_cell(&raw, column, meta)?;
1269 let width_text = match &cell {
1270 NativeCell::Number(number) => number.to_string(),
1271 NativeCell::DateTime(_) => pyops::py_str(&raw),
1272 NativeCell::Bool(value) => value.to_string(),
1273 NativeCell::Text(text) => text.clone(),
1274 NativeCell::Empty => String::new(),
1275 };
1276 match cell {
1277 NativeCell::Number(number) => {
1278 sheet.write_number_with_format(row_index, column_index as u16, number, &format)?;
1279 }
1280 NativeCell::DateTime(datetime) => {
1281 sheet.write_datetime_with_format(row_index, column_index as u16, &datetime, &format)?;
1282 }
1283 NativeCell::Bool(value) => {
1284 sheet.write_boolean_with_format(row_index, column_index as u16, value, &format)?;
1285 }
1286 NativeCell::Text(text) => {
1287 let text = guard_formula(&text, &raw);
1288 sheet.write_string_with_format(row_index, column_index as u16, &text, &format)?;
1289 }
1290 NativeCell::Empty => {
1291 sheet.write_blank(row_index, column_index as u16, &format)?;
1292 }
1293 }
1294 widths[column_index] = widths[column_index].max(width_text.chars().count());
1295 }
1296 }
1297 for (column_index, width) in widths.iter().enumerate() {
1298 sheet.set_column_width(column_index as u16, (*width + 2).clamp(10, 50) as f64)?;
1299 }
1300 add_data_bars(sheet, header_row, table)?;
1301 add_native_chart(sheet, header_row, table)?;
1302 }
1303
1304 if !summaries.is_empty() {
1305 let sheet = workbook.add_worksheet();
1306 sheet.set_name(sheet_name("Summary", &mut used))?;
1307 let mut row_index: u32 = 0;
1308 if let Some(title) = title {
1309 sheet.write_string_with_format(row_index, 0, title, &title_format)?;
1310 row_index += 1;
1311 }
1312 sheet.write_string_with_format(row_index, 0, "Item", &header_format)?;
1313 sheet.write_string_with_format(row_index, 1, "Value", &header_format)?;
1314 let mut widths = [4usize, 5usize];
1315 for row in summaries {
1316 row_index += 1;
1317 sheet.write_string(row_index, 0, &row.label)?;
1318 if let Some(number) = numeric_value(&row.value, &row.mask) {
1319 let format = number_format(&row.mask, &symbol)
1320 .map(|format| Format::new().set_num_format(format))
1321 .unwrap_or_default();
1322 sheet.write_number_with_format(row_index, 1, number, &format)?;
1323 } else {
1324 let text = display_text(
1325 &row.value,
1326 &Column {
1327 key: String::new(),
1328 label: String::new(),
1329 mask: row.mask.clone(),
1330 rules: Vec::new(),
1331 field: Value::Null,
1332 },
1333 meta,
1334 )?;
1335 sheet.write_string(row_index, 1, &text)?;
1336 }
1337 widths[0] = widths[0].max(row.label.chars().count());
1338 widths[1] = widths[1].max(16);
1339 }
1340 sheet.set_column_width(0, widths[0].clamp(4, 60) as f64)?;
1341 sheet.set_column_width(1, widths[1].clamp(5, 30) as f64)?;
1342 }
1343
1344 let mut note_rows: Vec<(String, String, String)> = Vec::new();
1345 if let Some(source_note) = meta.and_then(|meta| meta.get("source_note")).and_then(Value::as_str) {
1346 note_rows.push((String::new(), "source".to_string(), source_note.to_string()));
1347 }
1348 for table in tables {
1349 for (ref_, text) in &table.notes {
1350 note_rows.push((table.key.clone(), ref_.clone(), text.clone()));
1351 }
1352 }
1353 if !note_rows.is_empty() {
1354 let sheet = workbook.add_worksheet();
1355 sheet.set_name(sheet_name("Notes", &mut used))?;
1356 sheet.write_string_with_format(0, 0, "Table", &header_format)?;
1357 sheet.write_string_with_format(0, 1, "Ref", &header_format)?;
1358 sheet.write_string_with_format(0, 2, "Note", &header_format)?;
1359 let mut widths = [5usize, 3usize, 4usize];
1360 for (index, (table, ref_, text)) in note_rows.iter().enumerate() {
1361 let row = index as u32 + 1;
1362 sheet.write_string(row, 0, table)?;
1363 sheet.write_string(row, 1, ref_)?;
1364 sheet.write_string(row, 2, text)?;
1365 widths[0] = widths[0].max(table.chars().count());
1366 widths[1] = widths[1].max(ref_.chars().count());
1367 widths[2] = widths[2].max(text.chars().count());
1368 }
1369 sheet.set_column_width(0, widths[0].clamp(5, 40) as f64)?;
1370 sheet.set_column_width(1, widths[1].clamp(3, 12) as f64)?;
1371 sheet.set_column_width(2, widths[2].clamp(4, 80) as f64)?;
1372 }
1373
1374 workbook
1375 .save_to_buffer()
1376 .map_err(|error| Error::message(format!("XLSX error: {error}")))
1377 }
1378}
1379
1380#[cfg(test)]
1381mod tests {
1382 use super::*;
1383 use crate::service::prepare_report;
1384 use serde_json::json;
1385
1386 fn value(value: serde_json::Value) -> Value {
1387 Value::from_json(value)
1388 }
1389
1390 fn prepared(payload: serde_json::Value) -> (Value, Value, Value) {
1391 let payload = value(payload);
1392 let prepared = prepare_report(&payload, None).unwrap();
1393 (prepared.dataset, prepared.layout, prepared.meta.to_value())
1394 }
1395
1396 #[test]
1397 fn collects_tables_structure() {
1398 let (dataset, layout, _meta) = prepared(json!({
1399 "meta": {"title": "Order", "mode": "exact"},
1400 "layout": {
1401 "company": {"label": "Company", "format_mask": "str", "alignment": "left"},
1402 "orders": {
1403 "order": {"label": "Code", "format_mask": "int", "alignment": "right"},
1404 "total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"},
1405 "items": {
1406 "qty": {"label": "Qty", "format_mask": "int", "alignment": "right", "aggregate": "sum"},
1407 "unit_price": {"label": "Unit", "format_mask": "float", "alignment": "right"}
1408 }
1409 }
1410 },
1411 "data": [{"company": "ACME", "orders": [
1412 {"order": 1, "total": 4000, "items": [{"qty": 1, "unit_price": 1500}, {"qty": 2, "unit_price": 1250}]},
1413 {"order": 2, "total": 2000, "items": [{"qty": 4, "unit_price": 500}]}
1414 ]}]
1415 }));
1416 let (tables, summaries) = collect_tables(&dataset, &layout, None);
1417 assert_eq!(tables.len(), 1);
1418 let items = &tables[0];
1419 assert_eq!(items.key, "items");
1420 assert_eq!(
1421 items.columns.iter().map(|column| column.label.clone()).collect::<Vec<_>>(),
1422 ["Company", "Code", "Total", "Qty", "Unit"]
1423 );
1424 assert_eq!(items.rows.len(), 5);
1425 assert_eq!(items.total_rows, HashSet::from([2, 4]));
1426 assert!(summaries.iter().any(|row| row.label == "ACME / Total"));
1427 assert!(summaries.iter().any(|row| row.label == "Total"));
1428 }
1429
1430 #[test]
1431 fn csv_content_and_delimiter() {
1432 let (dataset, layout, meta) = prepared(json!({
1433 "meta": {"title": "Order", "mode": "exact"},
1434 "layout": {
1435 "company": {"label": "Company", "format_mask": "str", "alignment": "left"},
1436 "orders": {
1437 "order": {"label": "Code", "format_mask": "int", "alignment": "right"},
1438 "total": {"label": "Total", "format_mask": "float", "alignment": "right", "aggregate": "sum"}
1439 }
1440 },
1441 "data": [{"company": "ACME", "orders": [{"order": 750, "total": 4000}]}]
1442 }));
1443 let (tables, summaries) = collect_tables(&dataset, &layout, Some(&meta));
1444 let text = render_csv(&tables, &summaries, Some(&meta), ',').unwrap();
1445 let lines: Vec<&str> = text.lines().collect();
1446 assert_eq!(lines[0], "# Order");
1447 assert_eq!(lines[1], "# table: orders");
1448 assert_eq!(lines[2], "Company,Code,Total");
1449 assert!(text.contains("ACME,750,\"4.000,00\""));
1450 assert!(text.contains("# summary"));
1451 let semi = render_csv(&tables, &summaries, Some(&meta), ';').unwrap();
1452 assert!(semi.contains("Company;Code;Total"));
1453 }
1454
1455 #[test]
1456 fn csv_guards_formulas_but_not_numbers() {
1457 let (dataset, layout, meta) = prepared(json!({
1458 "meta": {"title": "T"},
1459 "layout": {"a": {"label": "A"}, "n": {"label": "N", "format_mask": "float"}},
1460 "data": [{"a": "=1+1", "n": -5}, {"a": "@SUM(A1)", "n": 3}]
1461 }));
1462 let (tables, summaries) = collect_tables(&dataset, &layout, Some(&meta));
1463 let text = render_csv(&tables, &summaries, Some(&meta), ',').unwrap();
1464 assert!(text.contains("'=1+1"));
1465 assert!(text.contains("'@SUM(A1)"));
1466 assert!(!text.contains("'-5"));
1467 }
1468
1469 #[test]
1470 fn sections_export() {
1471 let (dataset, layout, meta) = prepared(json!({
1472 "meta": {"title": "Board Pack", "mode": "exact"},
1473 "sections": [
1474 {"type": "text", "title": "Intro", "paragraphs": ["Hello."]},
1475 {"type": "table", "title": "Sales", "layout": {"product": {"label": "Product", "format_mask": "str", "alignment": "left"}}, "data": [{"product": "Pen"}]},
1476 {"type": "kpi", "title": "Totals", "items": [{"label": "Orders", "value": 42}]},
1477 {"type": "chart", "title": "Trend", "chart": {"kind": "bar", "labels": ["Jan", "Feb"], "values": [10, 20]}}
1478 ]
1479 }));
1480 let (tables, _summaries) = collect_tables(&dataset, &layout, Some(&meta));
1481 let keys: HashSet<String> = tables.iter().map(|table| table.key.clone()).collect();
1482 assert!(keys.contains("Sales"));
1483 assert!(keys.contains("Intro"));
1484 assert!(keys.contains("Totals"));
1485 assert!(keys.contains("Trend"));
1486 let text = render_csv(&tables, &_summaries, Some(&meta), ',').unwrap();
1487 assert!(text.contains("# table: Sales"));
1488 assert!(text.contains("Pen"));
1489 }
1490}