Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions 16/umbraco-commerce/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
* [List of notification events](key-concepts/events/list-of-notification-events.md)
* [Fluent API](key-concepts/fluent-api.md)
* [Order Calculation State](key-concepts/order-calculation-state.md)
* [Order Number Generators](key-concepts/order-number-generators.md)
* [Payment Forms](key-concepts/payment-forms.md)
* [Payment Providers](key-concepts/payment-providers.md)
* [Pipelines](key-concepts/pipelines.md)
Expand Down
99 changes: 90 additions & 9 deletions 16/umbraco-commerce/how-to-guides/order-number-customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,122 @@ description: Learn how to customize the default order number generated in Umbrac

# Order Number Customization

In Umbraco Commerce, the default order number generation can be customized by implementing the `IOrderNumberGenerator` interface. This interface defines two methods: `GenerateCartNumber(Guid storeId)` and `GenerateOrderNumber(Guid storeId)`, which you can override to create a custom numbering system.​
Umbraco Commerce provides flexible options for customizing order numbers to meet your business requirements. This guide covers different approaches, from template-based customization to implementing fully custom generators.

## Built-in Generators

Before implementing a custom solution, understand that Umbraco Commerce includes two built-in order number generators:

- **CompactSortableOrderNumberGenerator** (Recommended) - Produces compact, time-sortable identifiers with high scalability and multi-node support
- **DateHashOrderNumberGenerator** (Legacy) - Date-based format maintained for backward compatibility

For detailed information about these generators and how they work, see the [Order Number Generators](../key-concepts/order-number-generators.md) key concepts documentation.

## Before Creating a Custom Generator

Consider these alternatives before implementing a custom generator:

### 1. Using Store Templates

You can customize order numbers through store-level templates. Templates allow you to add prefixes, suffixes, or formatting without writing any code:

```csharp
// Configure templates via the Store entity
await store.SetCartNumberTemplateAsync("CART-{0}");
await store.SetOrderNumberTemplateAsync("ORDER-{0}");
```

**Examples:**
- Template: `"ORDER-{0}"` + Generated: `"22345-67ABC"` = Final: `"ORDER-22345-67ABC"`
- Template: `"SO-{0}-2025"` + Generated: `"12345"` = Final: `"SO-12345-2025"`

This approach works with any generator and requires no custom code.

### 2. Using CompactSortableOrderNumberGenerator

The `CompactSortableOrderNumberGenerator` handles most common requirements:
- Compact format (10-11 characters)
- Time-sortable
- Multi-node safe
- High-volume capable (1,024 orders/sec per node)

If your store was upgraded from an earlier version and is using the legacy generator, you can explicitly switch to the recommended generator:

```csharp
public class MyComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IOrderNumberGenerator, CompactSortableOrderNumberGenerator>();
}
}
```

## Implementing a Custom Order Number Generator

To create a custom order number generator, define a class that implements the `IOrderNumberGenerator` interface, for example, `CustomOrderNumberGenerator.cs`:
If the built-in generators don't meet your needs, you can create a custom implementation by implementing the `IOrderNumberGenerator` interface.

### Creating the Custom Generator

Define a class that implements the `IOrderNumberGenerator` interface:

{% code title="CustomOrderNumberGenerator.cs" %}

```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Umbraco.Commerce.Core.Generators;
using Umbraco.Commerce.Core.Services;

public class CustomOrderNumberGenerator : IOrderNumberGenerator
{
public string GenerateCartNumber(Guid storeId)
private readonly IStoreService _storeService;

public CustomOrderNumberGenerator(IStoreService storeService)
{
// Implement custom logic for cart numbers
_storeService = storeService;
}

public string GenerateOrderNumber(Guid storeId)
public async Task<string> GenerateCartNumberAsync(Guid storeId, CancellationToken cancellationToken = default)
{
// Implement custom logic for order numbers
var store = await _storeService.GetStoreAsync(storeId);

// Implement your custom logic for cart numbers
var cartNumber = $"{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}";

// Apply store template if configured
return string.Format(store.CartNumberTemplate ?? "{0}", cartNumber);
}

public async Task<string> GenerateOrderNumberAsync(Guid storeId, CancellationToken cancellationToken = default)
{
var store = await _storeService.GetStoreAsync(storeId);

// Implement your custom logic for order numbers
var orderNumber = $"{DateTime.UtcNow:yyyyMMdd}-{Random.Shared.Next(1000, 9999)}";

// Apply store template if configured
return string.Format(store.OrderNumberTemplate ?? "{0}", orderNumber);
}
}
```

{% endcode %}

## Registering the Custom Implementation
### Registering the Custom Implementation

After creating your custom generator, register it in `Program.cs` to replace the default implementation:

{% code title="Program.cs" %}

```csharp
builder.Services.AddUnique<IOrderNumberGenerator, MyOrderNumberGenerator>();
builder.Services.AddUnique<IOrderNumberGenerator, CustomOrderNumberGenerator>();
```

{% endcode %}

The `AddUnique` method ensures that your custom generator replaces the default `IOrderNumberGenerator`. For more details on dependency injection, see the [Dependency Injection](dependency-injection.md) article.
The `AddUnique` method ensures that your custom generator replaces the default `IOrderNumberGenerator`, overriding both the automatic selection system and the built-in generators. For more details on dependency injection, see the [Dependency Injection](dependency-injection.md) article.

## Important Considerations

Expand All @@ -54,3 +130,8 @@ Before implementing a custom order number generator, be aware of the following:
- **Accounting Considerations:** Umbraco Commerce is not designed as an accounting platform. If strict sequential numbering is required for accounting purposes, it is recommended to integrate with a dedicated accounting system to handle such requirements.

By understanding these factors, you can implement a custom order number generator that aligns with your specific requirements while maintaining optimal performance and compliance.

## Related Documentation

- [Order Number Generators](../key-concepts/order-number-generators.md) - Detailed documentation about the built-in generators
- [Dependency Injection](dependency-injection.md) - Learn more about registering services in Umbraco Commerce
217 changes: 217 additions & 0 deletions 16/umbraco-commerce/key-concepts/order-number-generators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
---
title: Order Number Generators
description: Learn about the `IOrderNumberGenerator` interface in Umbraco Commerce
---

# Order Number Generators

Order Number Generators are responsible for generating unique, human-readable identifiers for carts and orders in Umbraco Commerce. These generators ensure that each cart and order receives a distinct number that can be used for tracking, customer communication, and administrative purposes.

## IOrderNumberGenerator Interface

The `IOrderNumberGenerator` interface defines the contract for generating order and cart numbers:

```csharp
public interface IOrderNumberGenerator
{
Task<string> GenerateCartNumberAsync(Guid storeId, CancellationToken cancellationToken = default);
Task<string> GenerateOrderNumberAsync(Guid storeId, CancellationToken cancellationToken = default);
}
```

The interface provides two key methods:

- **GenerateCartNumberAsync** - Generates a unique number for shopping carts (orders that haven't been finalized)
- **GenerateOrderNumberAsync** - Generates a unique number for finalized orders

Both methods are store-scoped, allowing different stores in a multi-tenant environment to have independent number sequences.

## Built-in Generators

Umbraco Commerce includes two built-in order number generators:

### CompactSortableOrderNumberGenerator (Recommended)

The `CompactSortableOrderNumberGenerator` is the recommended generator introduced in Umbraco Commerce 16.4. It produces compact, time-sortable identifiers with high scalability characteristics.

**Format:** 10-character Base32 encoded ID with hyphen formatting

Where:
- `timeComponent` - 7 Base32 characters encoding seconds since January 1, 2025 (supports ~1089 years)
- `nodeId` - 1 Base32 character representing the server/node ID (0-31)
- `sequence` - 2 Base32 characters encoding a per-second sequence number (0-1023)

**Example:** `22345-67ABC` (hyphen inserted at position 5 for readability)

**Characteristics:**
- **Compact** - Only 10 characters (11 with hyphen formatting)
- **Time-sortable** - Lexicographic ordering matches chronological ordering
- **Scalable** - Supports up to 1,024 orders per second per node (gracefully waits for the next second if capacity is exceeded rather than failing)
- **Multi-node safe** - Node ID prevents collisions in clustered environments
- **Visual variety** - Character rotation based on time reduces visual repetition

**Base32 Alphabet:** Uses Crockford-like Base32 (`23456789ABCDEFGHJKLMNPQRSTUVWXYZ`) which excludes ambiguous characters (0, 1, I, O).

**Number Template Support:**
Cart and order numbers can be formatted using the store's `CartNumberTemplate` and `OrderNumberTemplate` settings (defaults: `"CART-{0}"` and `"ORDER-{0}"`).

### DateHashOrderNumberGenerator (Legacy)

The `DateHashOrderNumberGenerator` is the legacy generator from earlier versions of Umbraco Commerce. It creates order numbers based on the current date and time, combined with a random string component.

{% hint style="info" %}
This generator is maintained for backward compatibility with existing stores, but will eventually be deprecated. New implementations should use `CompactSortableOrderNumberGenerator`.
{% endhint %}

**Format:** `{dayCount:00000}-{timeCount:000000}-{randomString}`

Where:
- `dayCount` - Number of days since January 1, 2020 (5 digits)
- `timeCount` - Number of seconds elapsed in the current day (6 digits for carts, 5 for orders)
- `randomString` - 5 random characters from the set `BCDFGHJKLMNPQRSTVWXYZ3456789`

**Example:** `02103-45678-H4K9P`

**Characteristics:**
- Human-readable with embedded date information
- Random component reduces predictability
- No sequential ordering within the same second
- Collision risk increases if multiple orders are placed simultaneously
- Not suitable for high-volume or multi-node scenarios

## How Generators Are Chosen

Since Umbraco Commerce 16.4, the platform automatically selects the appropriate generator based on your store's state:

- **New installations (16.4+)** - Uses `CompactSortableOrderNumberGenerator` for all new stores
- **Upgrades with existing orders** - Continues using `DateHashOrderNumberGenerator` for stores that already have orders, ensuring consistent number formats
- **Upgrades without orders** - Switches to `CompactSortableOrderNumberGenerator` for stores with no existing orders

Prior to version 16.4, all installations used `DateHashOrderNumberGenerator` by default.

This automatic selection ensures backward compatibility while enabling improved functionality for new stores.

## Explicitly Choosing a Generator

If you want to explicitly choose which generator to use, you can override the registration in your application startup.

### Using CompactSortableOrderNumberGenerator (Recommended)

To explicitly use the compact sortable generator (for example, when migrating an existing store to the new format):

```csharp
public class MyComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IOrderNumberGenerator, CompactSortableOrderNumberGenerator>();
}
}
```

### Using DateHashOrderNumberGenerator (Legacy Only)

Only use this if you need to maintain the legacy format on a system that was upgraded:

```csharp
public class MyComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IOrderNumberGenerator, DateHashOrderNumberGenerator>();
}
}
```

{% hint style="warning" %}
Changing the order number generator on an existing store will result in different number formats for new orders. Ensure your business processes and integrations can handle mixed formats before making changes.
{% endhint %}

## Creating a Custom Generator

You can create custom order number generators by implementing the `IOrderNumberGenerator` interface:

```csharp
public class CustomOrderNumberGenerator : IOrderNumberGenerator
{
private readonly IStoreService _storeService;

public CustomOrderNumberGenerator(IStoreService storeService)
{
_storeService = storeService;
}

public async Task<string> GenerateCartNumberAsync(Guid storeId, CancellationToken cancellationToken = default)
{
var store = await _storeService.GetStoreAsync(storeId);

// Your custom cart number generation logic
var cartNumber = Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();

// Apply store template if configured
return string.Format(store.CartNumberTemplate ?? "{0}", cartNumber);
}

public async Task<string> GenerateOrderNumberAsync(Guid storeId, CancellationToken cancellationToken = default)
{
var store = await _storeService.GetStoreAsync(storeId);

// Your custom order number generation logic
var orderNumber = DateTime.UtcNow.ToString("yyyyMMdd") + "-" +
Random.Shared.Next(1000, 9999);

// Apply store template if configured
return string.Format(store.OrderNumberTemplate ?? "{0}", orderNumber);
}
}
```

### Registering a Custom Generator

Register your custom generator during application startup to replace the default implementation:

```csharp
public class MyComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IOrderNumberGenerator, CustomOrderNumberGenerator>();
}
}
```

### Important Considerations for Custom Generators

When implementing a custom generator, ensure:

1. **Uniqueness** - Generated numbers must be globally unique across all time
2. **Consistency** - The same store should produce numbers in a consistent format
3. **Thread-safety** - Handle concurrent calls safely, especially for sequential numbering
4. **Template support** - Apply the store's `CartNumberTemplate` and `OrderNumberTemplate` settings
5. **Store isolation** - Consider supporting store-specific sequences in multi-store scenarios
6. **Scalability** - Handle high-volume scenarios if your store expects significant traffic
7. **Cluster-awareness** - In multi-node environments, ensure numbers don't collide across nodes
8. **Readability** - Balance uniqueness with human readability for customer communication

{% hint style="warning" %}
Order numbers may have gaps if customers cancel or modify orders during the checkout process. Umbraco Commerce is not designed as an accounting platform. If you require strict sequential numbering for accounting purposes, integration with a dedicated accounting system is recommended. Additionally, sequential numbering can impact performance due to potential database access requirements.
{% endhint %}

## Configuration

Order number templates are configured at the store level and provide a way to add prefixes or suffixes to generated numbers:

```csharp
// Set via the Store entity
await store.SetCartNumberTemplateAsync("CART-{0}");
await store.SetOrderNumberTemplateAsync("ORDER-{0}");
```

The `{0}` placeholder is replaced with the generated number from the active generator.

**Examples:**
- Template: `"ORDER-{0}"` + Generated: `"22345-67ABC"` = Final: `"ORDER-22345-67ABC"`
- Template: `"{0}"` + Generated: `"02103-45678-H4K9P"` = Final: `"02103-45678-H4K9P"`
- Template: `"SO-{0}-2025"` + Generated: `"12345"` = Final: `"SO-12345-2025"`

Templates are applied regardless of which generator is active, providing consistent branding across your order numbers.