---
title: O2C Demo Data Generator - Complete PowerShell Script (Refactored)
description: Complete PowerShell 7+ script for generating Order-to-Cash demo data with BPM metadata, multi-format message payloads (JSON, XML, CSV, PSV), and Repository Binding for the Nodinite Log API.
---

# O2C Demo Data Generator - Complete Script

This page contains the complete **refactored PowerShell 7+ script** that generates Order-to-Cash demo data for the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> [Log API][LogAPI]. For parameters, use cases, and execution steps, see the [usage guide][Generate-O2C-Demo-Data].

## <i class="fal fa-circle-info" aria-hidden="true"></i> What This Script Does

The script generates realistic integration demo data with business process metadata for testing and demonstrations. It creates Order-to-Cash [Log Events][JSON formatted Log Event] with complete [BPM][] relationships, multi-format message payloads, and [Repository Binding][] metadata.

### Key Improvements

* ✅ Cross-platform compatible (PowerShell 7+ with ternary operators)  
* ✅ Consolidated message payload generation  
* ✅ Streamlined BPM relationship logic  
* ✅ Separate SequenceNo (per-order) and EventNumber (global) counters  
* ✅ Errors only on BPM-visible events (IsBiz = true)  
* ✅ Orders vary: six fictitious customers in four cities and two countries, three products, and quantities 1 to 5, so a [Log View][Log Views] can group them (Country > City > ZIP > Customer). Order 1 is always CUST-001 with one Demo Widget  

## <i class="fal fa-diagram-project" aria-hidden="true"></i> Understanding the Script

<div class="mermaid">
graph LR
    Defs["fa:fa-table Step templates<br/>Event definitions<br/>Milestones, flows"] --> Payload["fa:fa-file-code New-MessagePayload<br/>JSON, XML, CSV, PSV"]
    Defs --> Event["fa:fa-gears New-NodiniteLogEvent<br/>Repository Binding + BPM"]
    Payload --> Event
    Event --> Out["fa:fa-file-export DryRun preview<br/>or JSON export"]
    style Defs fill:#2678BD
    style Payload fill:#E47528
    style Event fill:#E47528
    style Out fill:#93d16d
</div>

*The data definitions (blue) feed the two builder functions (orange), which produce the [Log Events][Log Event] that the script previews or exports (green).*

### Consolidated Functions

The script uses these helper functions:

|Function|Role|
|---|---|
|`ConvertTo-Base64`|Base64 encoding for message bodies|
|`Get-FileExtension`|Format-specific file extensions|
|`Get-ShortMilestone`|Shortened milestone names for the [BPM][] visualization|
|`Get-OrderProfile`|The customer, product, quantity, total, and priority of one order|
|`New-MessagePayload`|Message payload generation (all 7 steps)|
|`New-NodiniteLogEvent`|Complete [Log Event][] construction with [BPM][] metadata|

### From the Definitions to C4 Diagrams

<sup><span class="nodinite-new-badge">New 7.12</span></sup> The definitions also feed the [O2C C4 Diagrams][]:

* Each event's `Endpoint`, `Service`, and `MessageType` form the Service's [Transport Contract][Transport Contracts]. The Endpoints are the bound Components of each Service's L3 (`Portal-OrderReceived-Drop` on INT1337-RCV-Order-Incoming's). Generated Flows carry the sender's [Message Type][Message Types]: forwarders carry `O2C.Forwarding/1.0`.
* `ProcessingMachineName` names the three unbound servers of the O2C Deployment (ERP-Finance runs on erp-server-01).

See [Build the Order-to-Cash C4 set][].

## <i class="fal fa-clipboard-check" aria-hidden="true"></i> Script Requirements

* **PowerShell Version**: 7.0 or later
* **Cross-Platform**: Works on Windows, Linux, and macOS
* **Dependencies**: None (built-in cmdlets)

## <i class="fal fa-code" aria-hidden="true"></i> Complete Script

The script, ready to save as a .ps1 file:

```powershell
# Generate-O2C-Demo-Data.ps1 (REFACTORED - PowerShell 7+ Required)
#
# PowerShell script to generate 100 Order-to-Cash (O2C) demo orders and log them to Nodinite Log API
# Refactored version with consolidated message generation, BPM logic, and helper functions
# REQUIRES: PowerShell 7.0+ for ternary operators and null-coalescing (cross-platform compatible)
#
# Usage:
#   pwsh .\Generate-O2C-Demo-Data.ps1 -LogApiUrl "https://nodinite.contoso.com:40002/LogAPI/api/LogEvent" `
#                                      -ApiKey "your-api-key" `
#                                      -OutputFile "/tmp/O2C-Orders.json"

param(
    [Parameter(Mandatory = $false)]
    [string]$LogApiUrl = "https://localhost:40002/LogAPI/api/LogEvent",
    
    [Parameter(Mandatory = $false)]
    [string]$ApiKey = "YOUR_API_KEY_HERE",
    
    [Parameter(Mandatory = $false)]
    [string]$OutputFile = "C:\Temp\O2C-Demo-Data.json",
    
    [Parameter(Mandatory = $false)]
    [int]$OrderCount = 100,
    
    [Parameter(Mandatory = $false)]
    [switch]$ExportToFile,
    
    [Parameter(Mandatory = $false)]
    [switch]$DryRun
)

$LOG_AGENT_VALUE_ID = 5
$ENDPOINT_TYPE_ID = 60
$PROGRESSION_PROBABILITY = 0.90

$today = (Get-Date).Date
$baseDate = [DateTime]::SpecifyKind((Get-Date -Year $today.Year -Month $today.Month -Day $today.Day -Hour 6 -Minute 0 -Second 0 -Millisecond 0), [DateTimeKind]::Utc)
$executionDate = (Get-Date).ToString("yyyyMMdd")
$customerPrefix = "PIC"

# Fictitious customers and products, so orders differ and a Log View can group them by place and customer
# (Country > City > ZIP > Customer). Order 1 is always CUST-001 with one Demo Widget, the order the docs show.
$customers = @(
    @{ Id = "CUST-001"; Name = "Contoso Corporation"; Email = "orders@Contoso.example.com"; Street = "100 Commerce Drive, Suite 100"; City = "Springfield"; Region = "IL"; Zip = "62701"; Country = "US"; Warehouse = "WH-01"; Carrier = "Standard Courier" }
    @{ Id = "CUST-002"; Name = "Fabrikam Inc."; Email = "purchasing@fabrikam.example.com"; Street = "2500 Lakeview Road"; City = "Springfield"; Region = "IL"; Zip = "62704"; Country = "US"; Warehouse = "WH-01"; Carrier = "Standard Courier" }
    @{ Id = "CUST-003"; Name = "Northwind Traders"; Email = "orders@northwind.example.com"; Street = "1 Harbor Street"; City = "Seattle"; Region = "WA"; Zip = "98101"; Country = "US"; Warehouse = "WH-02"; Carrier = "Pacific Express" }
    @{ Id = "CUST-004"; Name = "Adventure Works"; Email = "buyer@adventure-works.example.com"; Street = "800 Mercer Street"; City = "Seattle"; Region = "WA"; Zip = "98109"; Country = "US"; Warehouse = "WH-02"; Carrier = "Pacific Express" }
    @{ Id = "CUST-005"; Name = "Tailspin Toys"; Email = "inkop@tailspin.example.com"; Street = "Drottninggatan 10"; City = "Stockholm"; Region = "AB"; Zip = "111 51"; Country = "SE"; Warehouse = "WH-03"; Carrier = "Nordic Freight" }
    @{ Id = "CUST-006"; Name = "Wide World Importers"; Email = "orders@wideworld.example.com"; Street = "Kungsportsavenyen 5"; City = "Gothenburg"; Region = "O"; Zip = "411 36"; Country = "SE"; Warehouse = "WH-03"; Carrier = "Nordic Freight" }
)
$products = @(
    @{ Sku = "SKU-DEMO-001"; Description = "Demo Widget"; UnitPrice = 99.95 }
    @{ Sku = "SKU-DEMO-002"; Description = "Demo Gadget"; UnitPrice = 249.00 }
    @{ Sku = "SKU-DEMO-003"; Description = "Demo Sprocket"; UnitPrice = 12.50 }
)

function Get-OrderProfile {
    param([int]$OrderNum)
    # Customers rotate, so every run has all six; product and quantity vary per order
    $customer = $customers[($OrderNum - 1) % $customers.Count]
    $product = $OrderNum -eq 1 ? $products[0] : $products[(Get-Random -Minimum 0 -Maximum $products.Count)]
    $quantity = $OrderNum -eq 1 ? 1 : (Get-Random -Minimum 1 -Maximum 6)
    $total = [Math]::Round($product.UnitPrice * $quantity, 2)
    $inv = [Globalization.CultureInfo]::InvariantCulture
    return @{
        Customer = $customer; Product = $product; Quantity = $quantity
        Total = $total.ToString("0.00", $inv); UnitPrice = $product.UnitPrice.ToString("0.00", $inv)
        Priority = $total -ge 500 ? "HIGH" : "NORMAL"
        Address = "$($customer.Street), $($customer.City), $($customer.Region) $($customer.Zip)" + ($customer.Country -eq "US" ? "" : ", $($customer.Country)")
    }
}

# Compact step definitions - only unique properties per step
$stepTemplates = @{
    0 = @{ System = "Portal"; Domain = "Sales"; DomainIndex = 0; MessageType = "O2C.Order.Received/1.0"; ProcessName = "O2C-Order-Reception"; ProcessingMachineName = "portal-server-01" }
    1 = @{ System = "ERP"; Domain = "Planning"; DomainIndex = 1; MessageType = "O2C.Order.Entry/1.0"; ProcessName = "O2C-Order-Entry"; ProcessingMachineName = "erp-server-01" }
    2 = @{ System = "Portal"; Domain = "Sales"; DomainIndex = 0; MessageType = "O2C.Order.Confirmation/1.0"; ProcessName = "O2C-Confirmation"; ProcessingMachineName = "portal-server-01" }
    3 = @{ System = "ERP"; Domain = "Planning"; DomainIndex = 1; MessageType = "O2C.Order.Scheduled/1.0"; ProcessName = "O2C-Planning"; ProcessingMachineName = "erp-server-01" }
    4 = @{ System = "WMS"; Domain = "Logistics"; DomainIndex = 2; MessageType = "O2C.Order.Ready/1.0"; ProcessName = "O2C-Packing"; ProcessingMachineName = "wms-server-01" }
    5 = @{ System = "WMS"; Domain = "Logistics"; DomainIndex = 2; MessageType = "O2C.Order.Delivered/1.0"; ProcessName = "O2C-Delivery"; ProcessingMachineName = "wms-server-01" }
    6 = @{ System = "ERP-Finance"; Domain = "Finance"; DomainIndex = 3; MessageType = "O2C.Order.Invoice/1.0"; ProcessName = "O2C-Invoicing"; ProcessingMachineName = "erp-server-01" }
}

$eventDefs = @(
    @{ StepNumber = 0; Direction = 0; Format = "JSON"; Service = "INT1337-RCV-Order-Incoming"; Endpoint = "Portal-OrderReceived-Drop"; Uri = "C:\Integration\Portal\Orders\In"; Module = "Portal.OrderService.Receiver"; IsBiz = $true }
    @{ StepNumber = 0; Direction = 1; Format = "JSON"; Service = "INT1337-SND-Order-Incoming"; Endpoint = "Portal-Order-Send"; Uri = "C:\Integration\Portal\Orders\Out"; Module = "Portal.OrderService.Forwarder"; IsBiz = $false }
    @{ StepNumber = 1; Direction = 0; Format = "XML"; Service = "INT1337-RCV-Order-Entry"; Endpoint = "ERP-OrderEntry-Receive"; Uri = "C:\Integration\ERP\Orders\In"; Module = "ERP.Order.EntryService.Receiver"; IsBiz = $false }
    @{ StepNumber = 1; Direction = 1; Format = "XML"; Service = "INT1337-ENT-Order-Entry"; Endpoint = "ERP-OrderEntry-Send"; Uri = "C:\Integration\ERP\Orders\Out"; Module = "ERP.Order.EntryService"; IsBiz = $true }
    @{ StepNumber = 2; Direction = 0; Format = "CSV"; Service = "INT1337-RCV-Confirm-Incoming"; Endpoint = "Portal-Confirmation-Receive"; Uri = "C:\Integration\Portal\Confirmations\In"; Module = "Portal.ConfirmationService.Receiver"; IsBiz = $false }
    @{ StepNumber = 2; Direction = 1; Format = "CSV"; Service = "INT1337-SND-Confirm-Outgoing"; Endpoint = "Portal-Confirmation-Send"; Uri = "C:\Integration\Portal\Confirmations\Out"; Module = "Portal.ConfirmationService.Sender"; IsBiz = $true }
    @{ StepNumber = 3; Direction = 0; Format = "JSON"; Service = "INT1337-RCV-Planned-Incoming"; Endpoint = "ERP-Planning-Receive"; Uri = "C:\Integration\ERP\Planning\In"; Module = "ERP.PlanningService.Receiver"; IsBiz = $false }
    @{ StepNumber = 3; Direction = 1; Format = "JSON"; Service = "INT1337-PLN-Order-Scheduled"; Endpoint = "ERP-Planning-Send"; Uri = "C:\Integration\ERP\Planning\Out"; Module = "ERP.PlanningService.Scheduler"; IsBiz = $true }
    @{ StepNumber = 4; Direction = 0; Format = "XML"; Service = "INT1337-RCV-Packing-Incoming"; Endpoint = "WMS-Packing-Receive"; Uri = "C:\Integration\WMS\Packing\In"; Module = "WMS.PackingService.Receiver"; IsBiz = $false }
    @{ StepNumber = 4; Direction = 1; Format = "XML"; Service = "INT1337-PKG-Order-Packed"; Endpoint = "WMS-Packing-Send"; Uri = "C:\Integration\WMS\Packing\Out"; Module = "WMS.PackingService.Completer"; IsBiz = $true }
    @{ StepNumber = 5; Direction = 0; Format = "PSV"; Service = "INT1337-RCV-Order-Delivered-Incoming"; Endpoint = "WMS-Delivery-Receive"; Uri = "C:\Integration\WMS\Delivery\In"; Module = "WMS.DeliveryService.Receiver"; IsBiz = $false }
    @{ StepNumber = 5; Direction = 1; Format = "PSV"; Service = "INT1337-RCV-Order-Delivered"; Endpoint = "WMS-Delivery-Send"; Uri = "C:\Integration\WMS\Delivery\Out"; Module = "WMS.DeliveryService.Sender"; IsBiz = $true }
    @{ StepNumber = 6; Direction = 0; Format = "JSON"; Service = "INT1337-RCV-Invoice-Incoming"; Endpoint = "ERP-Finance-Invoice-Receive"; Uri = "C:\Integration\ERP\Finance\Invoices\In"; Module = "ERP.FinanceService.Receiver"; IsBiz = $false }
    @{ StepNumber = 6; Direction = 1; Format = "JSON"; Service = "INT1337-INV-Order-Invoiced"; Endpoint = "ERP-Finance-Invoice-Send"; Uri = "C:\Integration\ERP\Finance\Invoices\Out"; Module = "ERP.FinanceService.Invoicer"; IsBiz = $true }
)

$milestones = @{
    0 = @{ Rcv = "Order Received from Customer"; Snd = "Order Forwarded to ERP" }
    1 = @{ Rcv = "Order Entry Received"; Snd = "Order Entry in ERP Finished" }
    2 = @{ Rcv = "Confirmation Received"; Snd = "Order Confirmation Delivered to Customer" }
    3 = @{ Rcv = "Planning Request Received"; Snd = "Production Scheduled in ERP" }
    4 = @{ Rcv = "Packing Request Received"; Snd = "Order Completed for Transport" }
    5 = @{ Rcv = "Order Delivered Received"; Snd = "Order Delivered" }
    6 = @{ Rcv = "Invoice Request Received"; Snd = "Order Invoiced" }
}

$downstreamFlows = @{
    0 = @(1); 1 = @(2, 3); 2 = @(3); 3 = @(4); 4 = @(5); 5 = @(6); 6 = @()
}

function ConvertTo-Base64 {
    param([string]$Text)
    return [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Text))
}

function Get-FileExtension {
    param([string]$Format)
    return $Format -eq "JSON" ? ".json" : $Format -eq "XML" ? ".xml" : $Format -eq "CSV" ? ".csv" : $Format -eq "PSV" ? ".psv" : ".dat"
}

function Get-ShortMilestone {
    param([string]$Milestone)
    $m = $Milestone -replace " from Customer| to Customer| in ERP Finished| in ERP", ""
    $words = $m -split ' '
    if ($words.Count -ge 3) {
        $m = $m -eq "Order Confirmation Delivered" ? "Confirmation Sent" : $m -eq "Order Completed for Transport" ? "Ready for Transport" : $words.Count -gt 3 ? "$($words[0]) $($words[-2]) $($words[-1])" : $m
    }
    return $m
}

function New-MessagePayload {
    param([int]$StepNum, [string]$OrderId, [string]$CorrelationId, [hashtable]$Order)
    
    $ordNum = $OrderId.Substring(4)
    $c = $Order.Customer; $p = $Order.Product; $q = $Order.Quantity; $u = $Order.UnitPrice; $tot = $Order.Total
    
    $payloads = @{
        0 = @{
            batchId = "batch-2025-10-14-001"
            generatedAt = $baseDate.ToString("O")
            orderId = $OrderId
            customer = @{ customerId = $c.Id; name = $c.Name; email = $c.Email }
            shipTo = @{ street = $c.Street; city = $c.City; region = $c.Region; zip = $c.Zip; country = $c.Country }
            orderDate = $baseDate.ToString("O")
            orderRows = @(@{ rowId = 1; sku = $p.Sku; description = $p.Description; quantity = $q; unitPrice = $p.UnitPrice; lineTotal = [double]$tot })
            orderTotal = [double]$tot
            currency = "USD"
        } | ConvertTo-Json -Depth 10
        
        1 = @"
<?xml version="1.0" encoding="utf-8"?>
<OrderEntry xmlns="http://schemas.Contoso.example/O2C/1.0">
  <OrderHeader><OrderId>$OrderId</OrderId><OrderDate>2025-10-14T09:15:00Z</OrderDate><EntryDate>2025-10-14T09:18:30Z</EntryDate><OrderStatus>ENTERED</OrderStatus></OrderHeader>
  <Customer><CustomerId>$($c.Id)</CustomerId><CustomerName>$($c.Name)</CustomerName><CustomerEmail>$($c.Email)</CustomerEmail></Customer>
  <OrderLines><OrderLine><LineId>1</LineId><SKU>$($p.Sku)</SKU><Description>$($p.Description)</Description><Quantity>$q</Quantity><UnitPrice>$u</UnitPrice><LineTotal>$tot</LineTotal><InventoryReserved>true</InventoryReserved></OrderLine></OrderLines>
  <OrderTotal>$tot</OrderTotal><Currency>USD</Currency><ERPReferenceNumber>ERP-2025-$ordNum</ERPReferenceNumber>
</OrderEntry>
"@
        
        2 = @"
OrderConfirmationHeader
ConfirmationId,ConfirmationDate,CorrelationId,OrderId,OrderDate,CustomerID,CustomerName,CustomerEmail,ConfirmationStatus
CONF-2025-$ordNum,2025-10-14T09:22:15Z,$CorrelationId,ORD-$ordNum,2025-10-14T09:15:00Z,$($c.Id),$($c.Name),$($c.Email),CONFIRMED

OrderConfirmationDetails
LineNumber,SKU,Description,QuantityOrdered,UnitPrice,LineTotal
1,$($p.Sku),$($p.Description),$q,$u,$tot

OrderConfirmationFooter
OrderTotal,Currency,EstimatedShipDate,TrackingEnabled
$tot,USD,2025-10-21,true
"@
        
        3 = @{
            scheduleId = "SCH-2025-$ordNum"; orderId = $OrderId; customerId = $c.Id; customerName = $c.Name
            orderDate = "2025-10-14T09:15:00Z"; scheduleDate = "2025-10-14T09:37:45Z"
            productionLines = @(@{ lineId = "LINE-01"; lineName = "Assembly Line A"; scheduledStart = "2025-10-16T06:00:00Z"; scheduledEnd = "2025-10-16T14:30:00Z"; expectedDuration = 510; shift = "DAY"; capacity = 50 })
            materials = @(@{ materialId = "MAT-$($p.Sku)"; sku = $p.Sku; description = $p.Description; quantityRequired = $q; quantityAllocated = $q; availableAtScheduleTime = $true })
            orderQuantity = $q; orderAmount = [double]$tot; currency = "USD"; priorityLevel = $Order.Priority; schedulingStatus = "CONFIRMED"; estimatedCompletionDate = "2025-10-16T14:30:00Z"
        } | ConvertTo-Json -Depth 10
        
        4 = @"
<?xml version="1.0" encoding="utf-8"?>
<OrderPacking xmlns="http://schemas.Contoso.example/O2C/1.0">
  <PackingHeader><PackingId>PKG-2025-$ordNum</PackingId><OrderId>$OrderId</OrderId><PackingDate>2025-10-16T16:45:30Z</PackingDate><PackingStatus>COMPLETED</PackingStatus><Warehouse>$($c.Warehouse)</Warehouse><Zone>ZONE-A</Zone></PackingHeader>
  <Customer><CustomerId>$($c.Id)</CustomerId><CustomerName>$($c.Name)</CustomerName><ShippingAddress>$($Order.Address)</ShippingAddress></Customer>
  <PackedItems><PackedItem><LineId>1</LineId><SKU>$($p.Sku)</SKU><Description>$($p.Description)</Description><OrderedQuantity>$q</OrderedQuantity><PackedQuantity>$q</PackedQuantity><SerialNumber>SN-DW-2025$ordNum</SerialNumber><Condition>NEW</Condition></PackedItem></PackedItems>
  <ShipmentInfo><TrackingNumber>TRK-20251016-$ordNum</TrackingNumber><Carrier>$($c.Carrier)</Carrier><ShippingMethod>GROUND</ShippingMethod><EstimatedDeliveryDate>2025-10-21</EstimatedDeliveryDate><ShipmentWeight>5.0</ShipmentWeight><WeightUnit>LBS</WeightUnit></ShipmentInfo>
  <OrderTotal>$tot</OrderTotal><Currency>USD</Currency>
</OrderPacking>
"@
        
        5 = @"
DeliveryConfirmationHeader
DeliveryId|DeliveryDate|CorrelationId|OrderId|CustomerID|CustomerName|ShippingAddress|DeliveryStatus
DLVY-2025-$ordNum|2025-10-20T14:32:15Z|$CorrelationId|$OrderId|$($c.Id)|$($c.Name)|$($Order.Address)|DELIVERED

DeliveryDetails
LineNumber|SKU|Description|QuantityOrdered|QuantityDelivered|Condition
1|$($p.Sku)|$($p.Description)|$q|$q|GOOD

DeliveryProof
TrackingNumber|Carrier|DeliverySignature|DeliveryTime|RecipientName|ProofOfDeliveryLocation|PhotoUrl
TRK-20251016-$ordNum|$($c.Carrier)|ACM-AUTO-SIGN|2025-10-20T14:32:15Z|Auto-confirmed|Front Porch|https://pod.courier.example/2025/10/dlvy-$ordNum.jpg

DeliveryFooter
OrderTotal|Currency|ReturnWindow|ReturnInstructions
$tot|USD|30|Visit returns.contoso.com
"@
        
        6 = @{
            invoiceId = "INV-2025-$ordNum"; orderId = $OrderId; customerId = $c.Id; customerName = $c.Name; customerEmail = $c.Email
            invoiceDate = "2025-10-21T09:15:00Z"; dueDate = "2025-11-20"; paymentTerms = "NET30"; invoiceStatus = "ISSUED"
            invoiceItems = @(@{ lineNumber = 1; description = $p.Description; sku = $p.Sku; quantity = $q; unitPrice = $p.UnitPrice; lineTotal = [double]$tot; taxCode = "STANDARD"; taxRate = 0.0; taxAmount = 0.0 })
            subtotal = [double]$tot; taxTotal = 0.0; shippingCharge = 0.0; invoiceTotal = [double]$tot; currency = "USD"; paymentMethod = "INVOICE"
            purchaseOrder = "PO-2025-$ordNum"; trackingNumber = "TRK-20251016-$ordNum"; gl_account = "4100-Sales-Revenue"; revenue_recognition_date = "2025-10-20"
        } | ConvertTo-Json -Depth 10
    }
    
    return ConvertTo-Base64 $payloads[$StepNum]
}

function New-NodiniteLogEvent {
    param([hashtable]$EventDef, [string]$OrderId, [string]$CorrelationId, [DateTime]$LogDateTime, [int]$SequenceNo, [int]$EventNumber, [int]$ProcessingTimeMs, [int]$LogStatus, [string]$Body, [hashtable]$PrevSendService, [hashtable]$SameStepRecvService, [hashtable]$Order)
    
    $stepNum = $EventDef.StepNumber
    $stepTemplate = $stepTemplates[$stepNum]
    $isDir0 = $EventDef.Direction -eq 0
    $milestone = $milestones[$stepNum][$isDir0 ? "Rcv" : "Snd"]
    
    # Build Repository Binding
    $repBinding = @{
        Name = "Standard Transport Contract"
        Service = @{
            Name = $EventDef.Service
            Direction = $isDir0 ? "Receive" : "Send"
            System = @{ Name = $stepTemplate.System }
            Integration = @{ Name = "INT1337 - Order-to-Cash" }
        }
    }
    
    if ($isDir0 -and $null -ne $PrevSendService) {
        $repBinding.Service.ExternalServiceRelations = @(@{ 
            Name = $PrevSendService.Service
            Direction = $PrevSendService.Direction -eq 0 ? "Receive" : "Send"
            System = @{ Name = $PrevSendService.System }
        })
    }
    
    if (-not $isDir0 -and $null -ne $SameStepRecvService) {
        $repBinding.Service.InternalServiceRelations = @(@{ 
            Name = $SameStepRecvService.Service
            Direction = $SameStepRecvService.Direction -eq 0 ? "Receive" : "Send"
            System = @{ Name = $SameStepRecvService.System }
        })
    }
    
    if ($EventDef.IsBiz) {
        $bpmRels = @()
        foreach ($downStep in $downstreamFlows[$stepNum]) {
            $dnEvent = $eventDefs | Where-Object { $_.StepNumber -eq $downStep -and $_.IsBiz }
            if ($dnEvent) {
                $dnTemplate = $stepTemplates[$downStep]
                $dnMilestone = $milestones[$downStep]["Snd"]
                $shortMile = Get-ShortMilestone $dnMilestone
                $label = $downStep -eq 3 ? "Order Planned" : $shortMile
                
                $bpmRels += @{
                    Name = $dnEvent.Service
                    ArtifactRenaming = $shortMile
                    Direction = $dnEvent.Direction -eq 0 ? "Receive" : "Send"
                    Domain = @{ Name = $dnTemplate.Domain; Index = $dnTemplate.DomainIndex }
                    System = @{ Name = $dnTemplate.System }
                    Step = $downStep
                    Label = $label
                    ConnectorStyle = 0
                    SourceAttachmentPoint = 3
                    TargetAttachmentPoint = 1
                }
            }
        }
        
        $shortMile = Get-ShortMilestone $milestone
        $repBinding.Service.BPMs = @(@{
            Name = "INT1337 - Order-to-Cash Flow"
            ArtifactRenaming = $shortMile
            Domain = @{ Name = $stepTemplate.Domain; Index = $stepTemplate.DomainIndex }
            Step = $stepNum
            ServiceRelations = $bpmRels
        })
    }
    
    $bindingJson = ($repBinding | ConvertTo-Json -Depth 10) -replace '\r?\n\s*', ''
    
    $context = New-Object PSObject
    $context | Add-Member -MemberType NoteProperty -Name "FileName" -Value "$OrderId-$($milestone.ToLower() -replace ' ', '-')$(Get-FileExtension $EventDef.Format)"
    $context | Add-Member -MemberType NoteProperty -Name "OrderNumber" -Value $OrderId
    $context | Add-Member -MemberType NoteProperty -Name "CustomerId" -Value $Order.Customer.Id
    $context | Add-Member -MemberType NoteProperty -Name "CustomerName" -Value $Order.Customer.Name
    $context | Add-Member -MemberType NoteProperty -Name "OrderAmount" -Value $Order.Total
    $context | Add-Member -MemberType NoteProperty -Name "ExtendedProperties/1.0#RepositoryBinding" -Value $bindingJson
    
    return @{
        LogAgentValueId = $LOG_AGENT_VALUE_ID
        EndPointName = $EventDef.Endpoint
        EndPointUri = $EventDef.Uri
        EndPointDirection = $EventDef.Direction
        EndPointTypeId = $ENDPOINT_TYPE_ID
        OriginalMessageTypeName = $EventDef.IsBiz ? $stepTemplate.MessageType : "O2C.Forwarding/1.0"
        LogDateTime = $LogDateTime.ToString("O")
        EventDirection = $isDir0 ? 17 : 18
        ProcessingUser = "$($stepTemplate.System)\OrderService"
        SequenceNo = $SequenceNo
        EventNumber = $EventNumber
        LogText = $milestone
        ApplicationInterchangeId = $CorrelationId
        LocalInterchangeId = $null
        LogStatus = $LogStatus
        ProcessName = $stepTemplate.ProcessName
        ProcessingMachineName = $stepTemplate.ProcessingMachineName
        ProcessingModuleName = $EventDef.Module
        ProcessingModuleType = "WindowsService"
        ServiceInstanceActivityId = $null
        ProcessingTime = $ProcessingTimeMs
        Body = $Body
        Context = $context
    }
}

Write-Host "Order-to-Cash (O2C) Demo Data Generator [REFACTORED]" -ForegroundColor Cyan
Write-Host "====================================================" -ForegroundColor Cyan
Write-Host "Generating $OrderCount orders with probabilistic step completion..." -ForegroundColor Yellow
Write-Host ""

$allLogEvents = @()
$globalDateTime = $baseDate
$eventNumber = 0  # Global event counter across all orders

for ($orderNum = 1; $orderNum -le $OrderCount; $orderNum++) {
    $orderId = "ORD-" + (10000 + $orderNum).ToString()
    $currentTime = Get-Date -Format "HHmm"
    $correlationId = "$customerPrefix-$executionDate-$currentTime-" + $orderNum.ToString("D4")
    $order = Get-OrderProfile $orderNum
    
    # Determine which steps this order will complete (first order always completes all 7 steps)
    # Ensure incomplete orders complete at least step 1 so errors appear on BPM-visible events
    $completedSteps = $orderNum -eq 1 ? 7 : {
        $steps = 1
        for ($s = 1; $s -le 6; $s++) {
            if ((Get-Random -Minimum 0 -Maximum 100) / 100 -le $PROGRESSION_PROBABILITY) { $steps = $s + 1 }
            else { break }
        }
        # Ensure at least step 2 is attempted (so errors occur on BPM-visible send events)
        $steps -lt 2 ? 2 : [int]$steps
    }.Invoke()[0]
    
    $previousSendService = $null
    $currentDateTime = $globalDateTime
    $sequenceNo = 0  # Reset sequence number for each order (interchange)
    
    for ($stepNum = 0; $stepNum -lt $completedSteps; $stepNum++) {
        $rcvEvent = $eventDefs | Where-Object { $_.StepNumber -eq $stepNum -and $_.Direction -eq 0 }
        $sndEvent = $eventDefs | Where-Object { $_.StepNumber -eq $stepNum -and $_.Direction -eq 1 }
        $body = New-MessagePayload $stepNum $orderId $correlationId $order
        $isLastStep = $stepNum -eq ($completedSteps - 1)
        $isIncomplete = $completedSteps -lt 7
        
        $currentDateTime = $currentDateTime.AddSeconds((Get-Random -Minimum 30 -Maximum 300))
        $sequenceNo++
        $eventNumber++
        
        $allLogEvents += New-NodiniteLogEvent $rcvEvent $orderId $correlationId $currentDateTime $sequenceNo $eventNumber (Get-Random -Minimum 5 -Maximum 50) 0 $body $previousSendService $null $order
        
        $currentDateTime = $currentDateTime.AddSeconds((Get-Random -Minimum 1 -Maximum 5))
        # Only set errors on BPM-visible events (IsBiz = true) for incomplete orders
        $sendStatus = ($isLastStep -and $isIncomplete -and $sndEvent.IsBiz) ? -1337 : 0
        $sequenceNo++
        $eventNumber++
        
        $rcvEventInfo = @{ Service = $rcvEvent.Service; Direction = $rcvEvent.Direction; System = $stepTemplates[$stepNum].System }
        $allLogEvents += New-NodiniteLogEvent $sndEvent $orderId $correlationId $currentDateTime $sequenceNo $eventNumber (Get-Random -Minimum 40 -Maximum 300) $sendStatus $body $null $rcvEventInfo $order
        
        $previousSendService = @{ Service = $sndEvent.Service; Direction = $sndEvent.Direction; System = $stepTemplates[$stepNum].System }
    }
    
    $globalDateTime = $currentDateTime.AddSeconds((Get-Random -Minimum 120 -Maximum 600))
    
    if ($orderNum % 10 -eq 0) {
        Write-Host "Generated $orderNum/$OrderCount orders..." -ForegroundColor Green
    }
}

Write-Host ""
Write-Host "Generated $(($allLogEvents | Measure-Object).Count) total log events" -ForegroundColor Cyan

if ($DryRun) {
    Write-Host ""
    Write-Host "DRY RUN MODE - First order only (14 events):" -ForegroundColor Yellow
    $allLogEvents | Select-Object -First 14 | ConvertTo-Json -Depth 20 | Write-Host
}
elseif ($ExportToFile) {
    Write-Host ""
    Write-Host "Exporting to file: $OutputFile" -ForegroundColor Cyan
    $allLogEvents | ConvertTo-Json -Depth 20 | Out-File -FilePath $OutputFile -Encoding UTF8
    Write-Host "Export completed successfully" -ForegroundColor Green
}
else {
    Write-Host ""
    Write-Host "Would call Log API at: $LogApiUrl" -ForegroundColor Cyan
    Write-Host "With $($allLogEvents.Count) events" -ForegroundColor Cyan
}

Write-Host ""
Write-Host "Summary:" -ForegroundColor Cyan
Write-Host "  Orders: $OrderCount" -ForegroundColor White
Write-Host "  Log Events: $($allLogEvents.Count)" -ForegroundColor White
Write-Host "  Average Events per Order: $([Math]::Round($allLogEvents.Count / $OrderCount, 2))" -ForegroundColor White
Write-Host ""
```

## <i class="fal fa-play" aria-hidden="true"></i> Usage Examples

See the [O2C Demo Data Generator Usage Guide][Generate-O2C-Demo-Data] for usage examples, parameters, and use cases: run the script with `-DryRun` to preview the first order, or `-ExportToFile` to write the orders to a file.

## <i class="fal fa-hand-point-right" aria-hidden="true"></i> Next Steps

* <i class="fal fa-book-open" aria-hidden="true"></i> [O2C Demo Usage Guide][Generate-O2C-Demo-Data] - Save the script, then run it with `-DryRun` to preview the generated data  
* <i class="fal fa-diagram-project" aria-hidden="true"></i> [BPM Expected Layout][] - The BPM that the generated Log Events create  

## <i class="fal fa-link-horizontal" aria-hidden="true"></i> Related Topics

* <i class="fal fa-house" aria-hidden="true"></i> [O2C Demo Overview][Overview] - Complete Order-to-Cash scenario documentation  
* <i class="fal fa-tower-broadcast" aria-hidden="true"></i> [Log API Reference][LogAPI] - Integration with the <span class="nodinite-product-name" title="The node that unites different systems. Or as we call it Nodinite">Nodinite</span> Log API  
* <i class="fal fa-palette" aria-hidden="true"></i> [Order Received Stylesheet][Order-Stylesheet] - Message visualization examples  
* <i class="fal fa-sitemap" aria-hidden="true"></i> [Repository Binding][]  
* <i class="fal fa-layer-group" aria-hidden="true"></i> [O2C C4 Diagrams][] - C4 diagrams built from the same entities  
* <i class="fal fa-cubes" aria-hidden="true"></i> [Build the Order-to-Cash C4 set][] - The full C4 demo set, built in the product  

[BPM]:https://docs.nodinite.com/repository-model/bpms/overview/
[BPM Expected Layout]:https://docs.nodinite.com/repository-model/bpms/examples/order-to-cash/bpm-expected-layout/
[Build the Order-to-Cash C4 set]:https://docs.nodinite.com/repository-model/c4-diagrams/getting-started/examples/order-to-cash/build-the-order-to-cash-c4-set/
[Generate-O2C-Demo-Data]:https://docs.nodinite.com/repository-model/bpms/examples/order-to-cash/generate-o2c-demo-data/
[JSON formatted Log Event]:https://docs.nodinite.com/core-services/log-event/features/json-log-event/
[Log Event]:https://docs.nodinite.com/core-services/log-event/overview/
[Log Views]:https://docs.nodinite.com/administration/log-management/log-views/features/what-is-a-log-view/
[LogAPI]:https://docs.nodinite.com/core-services/log-api/overview/
[Message Types]:https://docs.nodinite.com/repository-model/message-types/overview/
[O2C C4 Diagrams]:https://docs.nodinite.com/repository-model/bpms/examples/order-to-cash/o2c-c4-diagrams/
[Order-Stylesheet]:https://docs.nodinite.com/repository-model/bpms/examples/order-to-cash/stylesheets/1-order-received/
[Overview]:https://docs.nodinite.com/repository-model/bpms/examples/order-to-cash/overview/
[Repository Binding]:https://docs.nodinite.com/core-services/log-event/features/repository-binding/
[Transport Contracts]:https://docs.nodinite.com/repository-model/services/overview/#fa-microchip-transport-contracts-the-heart-of-service-definitions