Skip to main content

Add a business rule as a calculation

Implement a calculation to maintain availability from price, stock and market state. Vox records its reads and reruns it when those inputs change.

For the team workflow, see Calculate a result once.

1. Give the result an owner​

Marking the fields as calculated makes it explicit that integrations and editors do not write the value:

public class ProductAvailability
{
public bool IsAvailable { get; set; }
public DateTime? AvailableUntilUtc { get; set; }
}

public class Product : IVoxEntity
{
// Other fields omitted.
[VoxCalculated(typeof(ProductAvailabilityCalculation))]
public ProductAvailability Availability { get; set; } = new();
}

Once a calculation owns these fields, actions and imports cannot change them accidentally, and the calculation can change nothing else.

2. Express the rule from domain data​

The calculation loads what it needs through IVoxCalculationContext:

public class ProductAvailabilityCalculation(TimeProvider timeProvider) : IVoxCalculation<Product>
{
public async Task CalculateAsync(
Product product,
Product result,
IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var prices = await context.LoadRelatedAsync<Price>(product, cancellationToken);
var stock = await context.LoadRelatedAsync<StockLevel>(product, cancellationToken);
var now = timeProvider.GetUtcNow().UtcDateTime;

var validPrices = prices.Where(price =>
(price.ValidFromUtc == null || price.ValidFromUtc <= now) &&
(price.ValidToUtc == null || now < price.ValidToUtc)).ToList();

foreach (var boundary in validPrices.Select(price => price.ValidToUtc).OfType<DateTime>())
{
context.ReevaluateAt(boundary);
}

result.Availability.IsAvailable = validPrices.Count > 0 &&
stock.Any(level => level.OnHand > level.Reserved);
result.Availability.AvailableUntilUtc =
validPrices.MinBy(price => price.ValidToUtc)?.ValidToUtc;
}
}

Entity reads, missing entities, relations, context memberships and other calculated values accessed through the context become dependencies. If a price, stock level or relevant link changes, Vox knows which products to recalculate.

3. Include time as a dependency​

Some answers change even when no entity is written. ReevaluateAt records the next instant at which the current answer can become wrong. Vox durably schedules that work, so a price can expire or a campaign can begin without a request first noticing the boundary.

If a calculation requests several future instants, Vox retains the earliest one needed by that run. A later recalculation replaces the schedule with the new dependency picture.

4. Let consistency settle​

When a price changes, the save evaluates the product's own calculations that read it, and publishes the product with its recalculated values, so readers and subscribers never see the new price with an old calculated result. One entity event is sent per published change, and an import is no different. The calculations of other entities that read the product, eg its category's price range, run afterwards in Vox's change processing.

Vox stores dependency changes and recalculation work durably. If the same product changes repeatedly before the processing reaches it, it's calculated once, against its latest state, without losing the fact that it needs calculation.

5. Expose the result, not the rule​

The calculated fields are ordinary entity data after they settle. They can be returned by the API, indexed for filtering or search, included in projections and used by other calculations. Consumers no longer need to know which source owns price or stock or when a campaign boundary occurs.

Use an entity assessment instead when the result is quality, readiness or risk that should be queried separately without changing the entity. Use an action when a person or system is requesting a business transition rather than deriving a value.

A calculation can also create entities, eg a customer's renewal contract, or calculate fields of related entities, eg the order lines' share of a discount. See Create entities and calculate related entities.

See Calculations, Actions, validation and workflows and Dependency and change tracking.