office-automation 0.3.2

Windows CLI tool that automates PowerPoint and Excel via COM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Step 3: Swap delta indicator arrows based on value sign.
//!
//! Uses a two-pass algorithm:
//! 1. Collect all OLE+delt pairs and their metadata (safe for iteration)
//! 2. Process each pair: delete old shape, copy template, reposition
//!
//! Value sign is determined from the PPT table cell (primary) or Excel (fallback).
//! Template shapes on slide 1: tmpl_delta_pos, tmpl_delta_neg, tmpl_delta_none.
//!
//! Template sets: a `delt<N>_` shape (N ≥ 2) copies from `tmpl<N>_delta_{pos,neg,none}`
//! instead of the set-1 templates. Set number comes from `matcher::delta_set`; template
//! names from `matcher::template_name_for_set`. A set whose templates are missing is
//! skipped with a warning — never silently mapped to set 1.

use std::collections::HashMap;

use crate::com::dispatch::Dispatch;
use crate::com::variant::Variant;
use crate::config::Config;
use crate::error::OaResult;
use crate::shapes::inventory::SlideInventory;
use crate::shapes::matcher::{delta_set, strip_sign_suffix, template_name_for_set};
use crate::utils::link_parser::parse_source_full_name;

/// The three template shapes for one delta set.
struct TemplateTriple {
    pos: Dispatch,
    neg: Dispatch,
    none: Dispatch,
}

/// Metadata collected in Pass 1 for processing in Pass 2.
struct DeltaItem {
    slide_index: i32,
    ole_name: String,
    ole_source_full: String,
    delt_base_name: String, // Name with _pos/_neg/_none suffix stripped
    set: u32,               // Template set number (1 = default tmpl_delta_*)
    delt_left: f64,
    delt_top: f64,
    delt_width: f64,
    delt_height: f64,
}

/// Determine the sign of a cell value string.
///
/// Returns "pos", "neg", or "none".
pub fn determine_sign(value: &str) -> &'static str {
    let mut s = value.trim().to_string();

    // Strip trailing %
    if s.ends_with('%') {
        s.pop();
        s = s.trim().to_string();
    }

    match s.parse::<f64>() {
        Ok(num) if num > 0.0 => "pos",
        Ok(num) if num < 0.0 => "neg",
        _ => "none",
    }
}

/// Update all delta indicator shapes in the presentation.
///
/// Two-pass: collect metadata (Pass 1), then process (Pass 2).
/// Returns the count of deltas updated.
pub fn update_deltas(
    inventory: &SlideInventory,
    config: &Config,
    presentation: &mut Dispatch,
    excel_path: &str,
    excel_app: &mut Dispatch,
) -> OaResult<usize> {
    let template_slide = config.delta.template_slide;

    // --- Pass 1: Collect metadata ---
    let mut items: Vec<DeltaItem> = Vec::new();

    for ole_ref in &inventory.ole_shapes {
        let key = (ole_ref.slide_index, ole_ref.name.clone());

        if let Some(delt_ref) = inventory.delts.get(&key) {
            // Skip template slide
            if ole_ref.slide_index <= template_slide {
                continue;
            }

            let mut delt_shape = delt_ref.dispatch.clone();
            let delt_base = strip_sign_suffix(&delt_ref.name).to_string();
            let set = delta_set(&delt_ref.name).unwrap_or(1);

            let left = delt_shape.get("Left").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let top = delt_shape.get("Top").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let width = delt_shape.get("Width").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let height = delt_shape.get("Height").and_then(|v| v.as_f64()).unwrap_or(0.0);

            // Get OLE source link for Excel fallback
            let ole_source = {
                let mut ole_shape = ole_ref.dispatch.clone();
                ole_shape.nav("LinkFormat")
                    .and_then(|mut lf| lf.get("SourceFullName"))
                    .and_then(|v| v.as_string())
                    .unwrap_or_default()
            };

            items.push(DeltaItem {
                slide_index: ole_ref.slide_index,
                ole_name: ole_ref.name.clone(),
                ole_source_full: ole_source,
                delt_base_name: delt_base,
                set,
                delt_left: left,
                delt_top: top,
                delt_width: width,
                delt_height: height,
            });
        }
    }

    if items.is_empty() {
        return Ok(0);
    }

    // --- Resolve template triples for every set present ---
    // One scan of the template slide, then per-set lookup by derived name.
    let slide_shapes_by_name = collect_slide_shapes_by_name(presentation, template_slide);
    let mut templates: HashMap<u32, TemplateTriple> = HashMap::new();

    let mut sets_present: Vec<u32> = items.iter().map(|i| i.set).collect();
    sets_present.sort_unstable();
    sets_present.dedup();

    for set in sets_present {
        match resolve_template_set(&slide_shapes_by_name, config, set) {
            Ok(triple) => {
                templates.insert(set, triple);
            }
            Err(missing) => {
                if set == 1 {
                    eprintln!("Warning: missing delta template shapes on slide {} — skipping deltas", template_slide);
                } else {
                    eprintln!(
                        "Warning: missing delta template shapes for set {set} on slide {} ({}) — skipping delt{set}_ deltas",
                        template_slide,
                        missing.join(", ")
                    );
                }
            }
        }
    }

    if templates.is_empty() {
        return Ok(0);
    }

    // --- Pass 2: Process each delta ---
    let mut slides = Dispatch::new(presentation.get("Slides")?.as_dispatch()?);
    let mut count = 0;

    for item in &items {
        // Skip items whose template set is unavailable (already warned above)
        let Some(triple) = templates.get_mut(&item.set) else {
            continue;
        };

        // Get the cell value (primary: from PPT table, fallback: from Excel)
        let cell_value = get_delta_value(
            inventory,
            item,
            Some(&mut *excel_app),
            excel_path,
        );

        // Empty/missing data → treat as "none" (no change indicator).
        // Previously this skipped the delta entirely, leaving stale _pos/_neg
        // shapes from the template or a previous run.
        let sign = match cell_value {
            Some(ref v) if !v.is_empty() => determine_sign(v),
            _ => "none",
        };

        // Pick template by set, then by sign
        let template = match sign {
            "pos" => &mut triple.pos,
            "neg" => &mut triple.neg,
            _ => &mut triple.none,
        };

        // Get slide
        let slide_variant = match slides.call("Item", &[Variant::from(item.slide_index)]) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let mut slide = match slide_variant.as_dispatch() {
            Ok(d) => Dispatch::new(d),
            Err(_) => continue,
        };

        // Delete old delt_ shape (find by base name, ignoring sign suffix)
        delete_old_delta(&mut slide, &item.delt_base_name);

        // Copy template to slide
        if template.call0("Copy").is_err() {
            continue;
        }

        let mut slide_shapes = match slide.get("Shapes") {
            Ok(v) => match v.as_dispatch() {
                Ok(d) => Dispatch::new(d),
                Err(_) => continue,
            },
            Err(_) => continue,
        };

        if slide_shapes.call0("Paste").is_err() {
            continue;
        }

        // The pasted shape is the last one
        let shape_count = slide_shapes.get("Count")
            .and_then(|v| v.as_i32())
            .unwrap_or(0);

        let new_variant = match slide_shapes.call("Item", &[Variant::from(shape_count)]) {
            Ok(v) => v,
            Err(_) => continue,
        };
        let mut new_shape = match new_variant.as_dispatch() {
            Ok(d) => Dispatch::new(d),
            Err(_) => continue,
        };

        // Reposition and rename
        let _ = new_shape.put("Left", Variant::from(item.delt_left));
        let _ = new_shape.put("Top", Variant::from(item.delt_top));
        let _ = new_shape.put("Width", Variant::from(item.delt_width));
        let _ = new_shape.put("Height", Variant::from(item.delt_height));
        let new_name = format!("{}_{sign}", item.delt_base_name);
        let _ = new_shape.put("Name", Variant::from(new_name.as_str()));

        count += 1;
        let display_value = cell_value.as_deref().unwrap_or("(empty)");
        let detail = if item.set == 1 {
            format!("{display_value}{sign}")
        } else {
            format!("{display_value}{sign} (set {})", item.set)
        };
        super::verbose::detail(item.slide_index, &item.delt_base_name, &detail);
    }

    Ok(count)
}

/// Resolve the three template shapes for `set` from the pre-scanned template slide.
///
/// Set 1 uses the configured names verbatim; set N ≥ 2 derives `tmpl<N>_delta_*`
/// via `template_name_for_set`. On failure returns the list of missing names.
fn resolve_template_set(
    shapes_by_name: &HashMap<String, Dispatch>,
    config: &Config,
    set: u32,
) -> Result<TemplateTriple, Vec<String>> {
    let name_pos = template_name_for_set(&config.delta.template_positive, set, "pos");
    let name_neg = template_name_for_set(&config.delta.template_negative, set, "neg");
    let name_none = template_name_for_set(&config.delta.template_none, set, "none");

    let mut missing = Vec::new();
    for n in [&name_pos, &name_neg, &name_none] {
        if !shapes_by_name.contains_key(n.as_str()) {
            missing.push(n.clone());
        }
    }
    if !missing.is_empty() {
        return Err(missing);
    }

    Ok(TemplateTriple {
        pos: shapes_by_name[&name_pos].clone(),
        neg: shapes_by_name[&name_neg].clone(),
        none: shapes_by_name[&name_none].clone(),
    })
}

/// Scan one slide once and index its top-level shapes by name.
///
/// Returns an empty map if the slide cannot be read (caller reports missing templates).
fn collect_slide_shapes_by_name(presentation: &mut Dispatch, slide_index: i32) -> HashMap<String, Dispatch> {
    let mut map = HashMap::new();

    let Some(mut shapes) = presentation.get("Slides").ok()
        .and_then(|v| v.as_dispatch().ok())
        .map(Dispatch::new)
        .and_then(|mut slides| slides.call("Item", &[Variant::from(slide_index)]).ok())
        .and_then(|v| v.as_dispatch().ok())
        .map(Dispatch::new)
        .and_then(|mut slide| slide.get("Shapes").ok())
        .and_then(|v| v.as_dispatch().ok())
        .map(Dispatch::new)
    else {
        return map;
    };

    let count = shapes.get("Count").and_then(|v| v.as_i32()).unwrap_or(0);
    for i in 1..=count {
        if let Ok(v) = shapes.call("Item", &[Variant::from(i)])
            && let Ok(d) = v.as_dispatch()
        {
            let mut shape = Dispatch::new(d);
            if let Ok(name) = shape.get("Name").and_then(|v| v.as_string()) {
                // First occurrence wins, matching the old find_template linear scan
                map.entry(name).or_insert(shape);
            }
        }
    }

    map
}

/// Try to read the delta value from the associated PPT table, then fall back to Excel.
fn get_delta_value(
    inventory: &SlideInventory,
    item: &DeltaItem,
    excel_app: Option<&mut Dispatch>,
    excel_path: &str,
) -> Option<String> {
    let key = (item.slide_index, item.ole_name.clone());

    // Primary: read from PPT table cell (1,1)
    if let Some(table_info) = inventory.tables.get(&key) {
        let mut tbl_shape = table_info.dispatch.clone();
        let value = tbl_shape.get("Table")
            .and_then(|v| v.as_dispatch())
            .and_then(|d| {
                let mut tbl = Dispatch::new(d);
                tbl.call("Cell", &[Variant::from(1i32), Variant::from(1i32)])
            })
            .and_then(|v| v.as_dispatch())
            .and_then(|d| Dispatch::new(d).nav("Shape.TextFrame.TextRange"))
            .and_then(|mut tr| tr.get("Text"))
            .and_then(|v| v.as_string())
            .ok();

        if let Some(v) = value {
            let trimmed = v.trim().to_string();
            if !trimmed.is_empty() {
                return Some(trimmed);
            }
        }
    }

    // Fallback: read from Excel (for delt-only OLE shapes with no table)
    if let Some(excel) = excel_app
        && !item.ole_source_full.is_empty() && !excel_path.is_empty() {
            let parts = parse_source_full_name(&item.ole_source_full);
            if parts.range_address != "Not Specified" && parts.sheet_name != "Not Specified" {
                // Use CLI excel_path, not the old SourceFullName path (GOTCHA #29)
                if let Ok(mut workbooks) = excel.get("Workbooks")
                    .and_then(|v| v.as_dispatch())
                    .map(Dispatch::new)
                    && let Ok(mut wb) = crate::pipeline::table_updater::open_or_get_workbook(&mut workbooks, excel_path) {
                        let cell_text = wb.get("Worksheets")
                            .and_then(|v| v.as_dispatch())
                            .and_then(|d| Dispatch::new(d).call("Item", &[Variant::from(parts.sheet_name.as_str())]))
                            .and_then(|v| v.as_dispatch())
                            .and_then(|d| Dispatch::new(d).call("Range", &[Variant::from(parts.range_address.as_str())]))
                            .and_then(|v| v.as_dispatch())
                            .and_then(|d| Dispatch::new(d).get("Text"))
                            .and_then(|v| v.as_string())
                            .ok();

                        if let Some(text) = cell_text {
                            let trimmed = text.trim().to_string();
                            if !trimmed.is_empty() {
                                return Some(trimmed);
                            }
                        }
                    }
            }
        }

    None
}

/// Delete the old delta shape from a slide (find by base name, ignoring sign suffix).
fn delete_old_delta(slide: &mut Dispatch, base_name: &str) {
    let mut shapes = match slide.get("Shapes") {
        Ok(v) => match v.as_dispatch() {
            Ok(d) => Dispatch::new(d),
            Err(_) => return,
        },
        Err(_) => return,
    };

    let count = shapes.get("Count")
        .and_then(|v| v.as_i32())
        .unwrap_or(0);

    for i in 1..=count {
        if let Ok(v) = shapes.call("Item", &[Variant::from(i)])
            && let Ok(d) = v.as_dispatch() {
                let mut shp = Dispatch::new(d);
                let name = shp.get("Name")
                    .and_then(|v| v.as_string())
                    .unwrap_or_default();

                if strip_sign_suffix(&name) == base_name {
                    let _ = shp.call0("Delete");
                    return; // Only delete the first match
                }
            }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_determine_sign_positive() {
        assert_eq!(determine_sign("1.5"), "pos");
        assert_eq!(determine_sign("+0.3"), "pos");
        assert_eq!(determine_sign("1.5%"), "pos");
    }

    #[test]
    fn test_determine_sign_negative() {
        assert_eq!(determine_sign("-0.3"), "neg");
        assert_eq!(determine_sign("-100"), "neg");
        assert_eq!(determine_sign("-0.5%"), "neg");
    }

    #[test]
    fn test_determine_sign_zero() {
        assert_eq!(determine_sign("0"), "none");
        assert_eq!(determine_sign("0.0"), "none");
        assert_eq!(determine_sign("0%"), "none");
    }

    #[test]
    fn test_determine_sign_non_numeric() {
        assert_eq!(determine_sign("N/A"), "none");
        assert_eq!(determine_sign(""), "none");
        assert_eq!(determine_sign("text"), "none");
    }
}