corp-finance-core 1.1.0

Institutional-grade corporate finance calculations with 128-bit decimal precision — DCF, WACC, comps, LBO, credit metrics, derivatives, fixed income, options, and 60+ specialty modules. No f64 in financials. WASM-compatible.
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! CIM (Confidential Information Memorandum) template — converts a [`CimInput`]
//! into a [`WordDocSpec`] in one call.
//!
//! Gated on the `office` feature only; no compute-result dependency.

// ---------------------------------------------------------------------------
// Input struct
// ---------------------------------------------------------------------------

/// All data required to render a sell-side CIM (deal book).
#[cfg(feature = "office")]
#[cfg_attr(feature = "schema_gen", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CimInput {
    pub project_name: String,
    pub target_company: String,
    pub date: String,
    pub author: String,
    pub confidentiality_notice: String,
    /// Multi-paragraph; split on blank lines (`\n\n`).
    pub executive_summary: String,
    /// 4-8 investment-highlight bullets.
    pub investment_highlights: Vec<String>,
    /// Multi-paragraph; split on blank lines (`\n\n`).
    pub business_overview: String,
    /// Multi-paragraph; split on blank lines (`\n\n`).
    pub market_overview: String,
    /// Table data; first inner Vec is the header row.
    pub financial_summary: Vec<Vec<String>>,
    /// (name, title) pairs.
    pub management_team: Vec<(String, String)>,
    /// Multi-paragraph; split on blank lines (`\n\n`).
    pub transaction_overview: String,
    /// (milestone, date) pairs.
    pub process_timeline: Vec<(String, String)>,
    /// 4-6 key risks.
    pub key_risks: Vec<String>,
    /// Single paragraph.
    pub disclaimer: String,
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Convert a [`CimInput`] into a [`crate::office::WordDocSpec`] ready for
/// [`crate::office::docx::write_word_doc`].
///
/// Section layout:
///  1. Cover — H1 title, bold project name, target company, italic date, PageBreak.
///  2. Confidentiality Notice — H2 + paragraphs + PageBreak.
///  3. Executive Summary — H2 + multi-paragraph body.
///  4. Investment Highlights — H2 + BulletList (omitted when empty).
///  5. Business Overview — H2 + multi-paragraph + PageBreak.
///  6. Market Overview — H2 + multi-paragraph.
///  7. Financial Summary — H2 + Table (or fallback paragraph when empty).
///  8. Management Team — H2 + Table with Name/Title columns (omitted when empty).
///  9. Transaction Overview — H2 + multi-paragraph + PageBreak.
/// 10. Process Timeline — H2 + Table with Milestone/Date columns (omitted when empty).
/// 11. Key Risks — H2 + NumberedList (omitted when empty).
/// 12. Disclaimer — H2 + italic body + italic "Prepared by {author}".
#[cfg(feature = "office")]
pub fn cim_to_doc(input: &CimInput) -> crate::office::WordDocSpec {
    use crate::office::types::{DocSection, WordDocSpec, WorkbookProperties};

    let mut sections: Vec<DocSection> = Vec::new();

    sections.push(build_cover(input));
    sections.push(build_confidentiality_notice(input));
    sections.push(build_text_section(
        "Executive Summary",
        &input.executive_summary,
    ));

    if !input.investment_highlights.is_empty() {
        sections.push(build_bullet_section(
            "Investment Highlights",
            &input.investment_highlights,
        ));
    }

    sections.push(build_text_section_with_page_break(
        "Business Overview",
        &input.business_overview,
    ));
    sections.push(build_text_section(
        "Market Overview",
        &input.market_overview,
    ));
    sections.push(build_financial_summary(input));

    if !input.management_team.is_empty() {
        sections.push(build_management_team(input));
    }

    sections.push(build_text_section_with_page_break(
        "Transaction Overview",
        &input.transaction_overview,
    ));

    if !input.process_timeline.is_empty() {
        sections.push(build_process_timeline(input));
    }

    if !input.key_risks.is_empty() {
        sections.push(build_numbered_section("Key Risks", &input.key_risks));
    }

    sections.push(build_disclaimer(input));

    WordDocSpec {
        sections,
        properties: WorkbookProperties {
            title: Some(format!("CIM \u{2014} {}", input.project_name)),
            author: Some(input.author.clone()),
            company: None,
            subject: Some("Confidential Information Memorandum".into()),
        },
    }
}

// ---------------------------------------------------------------------------
// Section builders
// ---------------------------------------------------------------------------

#[cfg(feature = "office")]
fn build_cover(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection, TextRun};

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 1,
                text: "CONFIDENTIAL INFORMATION MEMORANDUM".into(),
            },
            DocBlock::Paragraph {
                runs: vec![TextRun {
                    text: input.project_name.clone(),
                    bold: true,
                    italic: false,
                }],
            },
            DocBlock::Paragraph {
                runs: vec![TextRun {
                    text: input.target_company.clone(),
                    bold: false,
                    italic: false,
                }],
            },
            DocBlock::Paragraph {
                runs: vec![TextRun {
                    text: input.date.clone(),
                    bold: false,
                    italic: true,
                }],
            },
            DocBlock::PageBreak,
        ],
    }
}

#[cfg(feature = "office")]
fn build_confidentiality_notice(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection, TextRun};

    let mut blocks = vec![DocBlock::Heading {
        level: 2,
        text: "Confidentiality Notice".into(),
    }];

    for para in split_paragraphs(&input.confidentiality_notice) {
        blocks.push(DocBlock::Paragraph {
            runs: vec![TextRun {
                text: para,
                bold: false,
                italic: false,
            }],
        });
    }

    blocks.push(DocBlock::PageBreak);

    DocSection { blocks }
}

/// Build a level-2 section with one paragraph per blank-line-separated chunk.
#[cfg(feature = "office")]
fn build_text_section(heading: &str, body: &str) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection, TextRun};

    let mut blocks = vec![DocBlock::Heading {
        level: 2,
        text: heading.to_owned(),
    }];

    for para in split_paragraphs(body) {
        blocks.push(DocBlock::Paragraph {
            runs: vec![TextRun {
                text: para,
                bold: false,
                italic: false,
            }],
        });
    }

    DocSection { blocks }
}

/// Like [`build_text_section`] but appends a [`DocBlock::PageBreak`] at the end.
#[cfg(feature = "office")]
fn build_text_section_with_page_break(
    heading: &str,
    body: &str,
) -> crate::office::types::DocSection {
    use crate::office::types::DocBlock;

    let mut section = build_text_section(heading, body);
    section.blocks.push(DocBlock::PageBreak);
    section
}

#[cfg(feature = "office")]
fn build_bullet_section(heading: &str, items: &[String]) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection};

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 2,
                text: heading.to_owned(),
            },
            DocBlock::BulletList {
                items: items.to_vec(),
            },
        ],
    }
}

#[cfg(feature = "office")]
fn build_financial_summary(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection, TextRun};

    let mut blocks = vec![DocBlock::Heading {
        level: 2,
        text: "Financial Summary".into(),
    }];

    if input.financial_summary.is_empty() {
        blocks.push(DocBlock::Paragraph {
            runs: vec![TextRun {
                text: "No financial summary provided.".into(),
                bold: false,
                italic: false,
            }],
        });
    } else {
        let headers = input.financial_summary[0].clone();
        let rows = input.financial_summary[1..].to_vec();
        blocks.push(DocBlock::Table { headers, rows });
    }

    DocSection { blocks }
}

#[cfg(feature = "office")]
fn build_management_team(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection};

    let rows: Vec<Vec<String>> = input
        .management_team
        .iter()
        .map(|(name, title)| vec![name.clone(), title.clone()])
        .collect();

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 2,
                text: "Management Team".into(),
            },
            DocBlock::Table {
                headers: vec!["Name".into(), "Title".into()],
                rows,
            },
        ],
    }
}

#[cfg(feature = "office")]
fn build_process_timeline(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection};

    let rows: Vec<Vec<String>> = input
        .process_timeline
        .iter()
        .map(|(milestone, date)| vec![milestone.clone(), date.clone()])
        .collect();

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 2,
                text: "Process Timeline".into(),
            },
            DocBlock::Table {
                headers: vec!["Milestone".into(), "Date".into()],
                rows,
            },
        ],
    }
}

#[cfg(feature = "office")]
fn build_numbered_section(heading: &str, items: &[String]) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection};

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 2,
                text: heading.to_owned(),
            },
            DocBlock::NumberedList {
                items: items.to_vec(),
            },
        ],
    }
}

#[cfg(feature = "office")]
fn build_disclaimer(input: &CimInput) -> crate::office::types::DocSection {
    use crate::office::types::{DocBlock, DocSection, TextRun};

    DocSection {
        blocks: vec![
            DocBlock::Heading {
                level: 2,
                text: "Disclaimer".into(),
            },
            DocBlock::Paragraph {
                runs: vec![TextRun {
                    text: input.disclaimer.clone(),
                    bold: false,
                    italic: true,
                }],
            },
            DocBlock::Paragraph {
                runs: vec![TextRun {
                    text: format!("Prepared by {}", input.author),
                    bold: false,
                    italic: true,
                }],
            },
        ],
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Split a multi-paragraph string on blank lines (`\n\n`).
/// Trims each chunk and discards empties.
#[cfg(feature = "office")]
fn split_paragraphs(text: &str) -> Vec<String> {
    text.split("\n\n")
        .map(|s| s.trim().to_owned())
        .filter(|s| !s.is_empty())
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "office"))]
mod tests {
    use super::*;
    use crate::office::types::DocBlock;

    fn minimal_input() -> CimInput {
        CimInput {
            project_name: "Project Falcon".into(),
            target_company: "Falcon Industries Ltd.".into(),
            date: "2026-05-08".into(),
            author: "Jane Banker, CFA".into(),
            confidentiality_notice: "This document is strictly confidential and is being furnished solely for informational purposes.".into(),
            executive_summary: "Falcon Industries is a leading manufacturer of precision components.\n\nThe company has achieved consistent double-digit revenue growth over the past five years.".into(),
            investment_highlights: vec!["Market leader with 35% share in core segment".into()],
            business_overview: "Founded in 1998, Falcon Industries operates across three business segments.".into(),
            market_overview: "The global precision components market is estimated at $12 billion and growing at 8% per annum.".into(),
            financial_summary: vec![
                vec!["Year".into(), "Revenue ($M)".into(), "EBITDA ($M)".into()],
                vec!["2025A".into(), "480".into(), "96".into()],
            ],
            management_team: vec![("John Smith".into(), "Chief Executive Officer".into())],
            transaction_overview: "The Company is seeking a strategic buyer or financial sponsor to support its next phase of growth.".into(),
            process_timeline: vec![("Management Presentations".into(), "June 2026".into())],
            key_risks: vec!["Customer concentration risk with top-3 customers representing ~45% of revenue".into()],
            disclaimer: "This Confidential Information Memorandum has been prepared by Falcon Advisory LLC solely for informational purposes.".into(),
        }
    }

    #[test]
    fn cim_to_doc_basic() {
        let input = minimal_input();
        let doc = cim_to_doc(&input);

        let count = doc.sections.len();
        assert!(
            (9..=12).contains(&count),
            "expected 9-12 sections, got {count}"
        );

        // First block of first section must be Heading level 1 with exact text.
        let first_block = &doc.sections[0].blocks[0];
        assert!(
            matches!(
                first_block,
                DocBlock::Heading { level: 1, text }
                    if text == "CONFIDENTIAL INFORMATION MEMORANDUM"
            ),
            "first block must be H1 'CONFIDENTIAL INFORMATION MEMORANDUM', got: {first_block:?}"
        );

        // properties.title must contain the project name.
        let title = doc.properties.title.as_deref().unwrap_or("");
        assert!(
            title.contains(&input.project_name),
            "properties.title should contain project_name; got: {title:?}"
        );
    }

    #[test]
    fn cim_to_doc_round_trips_through_writer() {
        use crate::office::docx::write_word_doc;
        use tempfile::tempdir;

        let input = minimal_input();
        let doc = cim_to_doc(&input);

        let dir = tempdir().expect("tempdir creation failed");
        let path = dir.path().join("cim.docx");

        let result = write_word_doc(&doc, &path).expect("write_word_doc failed");

        assert!(path.exists(), "output file does not exist");
        assert!(
            result.bytes_written > 0,
            "expected nonzero bytes, got {}",
            result.bytes_written
        );

        let bytes = std::fs::read(&path).expect("failed to read output file");
        assert_eq!(
            &bytes[..4],
            b"PK\x03\x04",
            "docx must begin with ZIP magic bytes PK\\x03\\x04"
        );
    }
}