Skip to content

Stream Reconciliation

This program pairs invoices and ledger settlements by position with Zip, expands multi-line invoices with FlatMap, isolates mismatched entries using TryMap, groups discrepancies by region via GroupBy, and sums total variance using Reduce.

What It Exercises

  • Lockstep multi-stream pairing with FromSlice, FromSeq, Zip, and Pair
  • 1-to-many expansion via FlatMap and slices.Values
  • Filtering discrepancies cleanly with TryMap and ErrSkip
  • Map grouping (GroupBy) and folding (Reduce) terminals

Complete Program

package main

import (
    "context"
    "fmt"
    "iter"
    "os"
    "slices"

    "github.com/vladimirvivien/automi"
)

type Invoice struct {
    ID      string
    Region  string
    Lines   []int // expected cents per line item
}

type Settlement struct {
    ID          string
    SettledSum  int
}

type Discrepancy struct {
    InvoiceID string
    Region    string
    DiffCents int
}

func main() {
    invoices := []Invoice{
        {ID: "inv-1", Region: "us", Lines: []int{500, 700}},
        {ID: "inv-2", Region: "eu", Lines: []int{1000, 200}},
        {ID: "inv-3", Region: "us", Lines: []int{300, 400}},
    }
    settlements := []Settlement{
        {ID: "inv-1", SettledSum: 1200}, // balanced
        {ID: "inv-2", SettledSum: 1050}, // -150 discrepancy
        {ID: "inv-3", SettledSum: 900},  // +200 discrepancy
    }

    ctx := context.Background()

    // Compare paired invoice totals against settlements, skipping balanced records.
    discrepancies, err := automi.Zip(
        automi.FromSlice(invoices),
        automi.FromSeq(slices.Values(settlements)),
    ).
        TryMap(func(_ context.Context, p automi.Pair[Invoice, Settlement]) (Discrepancy, error) {
            expected := 0
            for _, line := range p.First.Lines {
                expected += line
            }
            diff := p.Second.SettledSum - expected
            if diff == 0 {
                return Discrepancy{}, automi.ErrSkip
            }
            return Discrepancy{
                InvoiceID: p.First.ID,
                Region:    p.First.Region,
                DiffCents: diff,
            }, nil
        }).
        GroupBy(ctx, func(d Discrepancy) string { return d.Region })
    if err != nil {
        fmt.Fprintf(os.Stderr, "group error: %v\n", err)
        os.Exit(1)
    }

    fmt.Println("=== Discrepancies by Region ===")
    for region, items := range discrepancies {
        fmt.Printf("%s: %+v\n", region, items)
    }

    // Flatten all line items across invoices and reduce to expected gross volume.
    totalExpected, err := automi.FromSlice(invoices).
        FlatMap(func(inv Invoice) iter.Seq[int] {
            return slices.Values(inv.Lines)
        }).
        Reduce(ctx, 0, func(acc, cents int) int {
            return acc + cents
        })
    if err != nil {
        fmt.Fprintf(os.Stderr, "reduce error: %v\n", err)
        os.Exit(1)
    }

    fmt.Printf("Total expected invoice cents: %d\n", totalExpected)
}

Expected Output

=== Discrepancies by Region ===
eu: [{InvoiceID:inv-2 Region:eu DiffCents:-150}]
us: [{InvoiceID:inv-3 Region:us DiffCents:200}]
Total expected invoice cents: 3100