Create entities and calculate related entities
A calculation can create entities and calculate fields on related entities.
For the team workflow, see When an input changes.
A calculation usually calculates fields of its own entity: a variant's margin from its purchase price. Sometimes the rule's result belongs somewhere else. Two things are possible:
- Create entities. A customer calculation proposes the customer's renewal contract, or a variant calculation creates the price periods of a campaign.
- Calculate fields of related entities. An order calculation distributes the order's discount to its lines, even though it changes nothing on the order.
Both keep working like other calculations. Vox records what the run read, runs it again when that changes, and the changes are published on their own, per entity. This guide shows both; for the rest of the model see Add a business rule as a calculation.
Create an entity
Mark the class of the entity with the calculation that may create it, and create it with context.Create<T> in the
calculation. Here a customer's calculation proposes next year's renewal contract:
[VoxCalculated(typeof(CustomerRenewalCalculation))]
public class RenewalContract : IVoxEntity
{
// Built-in entity properties omitted.
public virtual string CustomerId { get; set; } = "";
public virtual int Year { get; set; }
public virtual string Status { get; set; } = "";
}
public class CustomerRenewalCalculation : IVoxCalculation<Customer>
{
public Task CalculateAsync(Customer customer, Customer result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
if (customer.IsEligibleForRenewal)
{
context.Create<RenewalContract>($"{customer.Id}-{customer.RenewalYear}", contract =>
{
contract.CustomerId = customer.Id;
contract.Year = customer.RenewalYear;
contract.Status = "Proposed";
});
}
return Task.CompletedTask;
}
}
The class declaration says which calculation creates the type. It doesn't create anything by itself: the C# in the calculation decides when a contract is needed. It doesn't prevent creating contracts in other ways either, eg with an action. Nothing is written while the calculation runs. A save of the customer in published content creates the contracts it proposes in the same save, with the calculations of their own type (the contract's label, say) calculated first; a proposal of a contract that exists already is left to the processing, which keeps the contract as it is. The editor who changed the customer only needs permission to change the customer; they don't need permission to create contracts.
Stock works the same way. A replenishment calculation can suggest a ReplenishmentRequest when the stock of an
inventory level runs low, and a draft of a stock count, eg of the red rain jacket in Stockholm, previews the request on
the inventory level's Effects tab before the count is published.
The id decides what is new
You always give the id, and what you choose decides what repeated runs do:
- A stable id, like the customer and year above, means the same contract every time. If the calculation runs again before the contract is published, eg because the customer changed again, the proposal is refreshed with the latest values.
- A new
Guid.NewGuid()each time creates a new entity each time the calculation runs. Vox doesn't prevent duplicates here; that's what you asked for. Do this only when each run should make a new thing.
An entity is created only if it doesn't exist. A calculation proposes what the customer leads to every time it runs, as the example does, and doesn't check first: proposing a contract that exists, eg one an earlier run created or an editor created, keeps it as it is, without an error. That also holds when two runs overlap, eg the customer changed again before the first run's contract was published. Proposing the same contract again with the same values does nothing at all. Read the entity only when the calculation decides from its state, eg not to renew a contract that was cancelled.
If a contract that was created is deleted, it's created again the next time the calculation runs and proposes it, eg when the customer changes, rather than at once.
Ids are per root: if a calculation of another customer proposes a contract that this customer's calculation created, that proposal is dropped and logged as an error, and shows as Dropped in its Effects. Give the entities that different roots create ids of their own, eg made of the root's id.
What a created entity may contain
The initializer may set the entity's owned and calculated fields. It may not set imported fields, which stay at their defaults until their import supplies them, nor the version and audit fields, which Vox manages. Vox validates the entity as it does any other.
Only ordinary full entity types that Vox owns can be created: not external, light, context or singleton types. And
since the creation isn't a field of the customer, a calculation that only creates entities, with no varying field of
its own entity, can't be [VoxRunsPerContext]. It runs once for the customer, and reads the markets or languages it
needs itself, eg to create one contract per market with an id that includes the market.
Example: price periods
A campaign price is valid in periods, and a variant calculation can create the periods that its campaigns call for:
[VoxCalculated(typeof(VariantPricePeriodCalculation))]
public class PricePeriod : IVoxEntity
{
// Built-in entity properties omitted.
public required virtual VoxReference<Variant> Variant { get; set; }
public virtual DateTime FromUtc { get; set; }
public virtual DateTime? ToUtc { get; set; }
public virtual decimal Amount { get; set; }
}
public class VariantPricePeriodCalculation : IVoxCalculation<Variant>
{
public async Task CalculateAsync(Variant variant, Variant result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var campaigns = await context.LoadRelatedAsync<Campaign>(variant, cancellationToken);
foreach (var campaign in campaigns)
{
context.Create<PricePeriod>($"{variant.Id}-{campaign.Id}", period =>
{
period.Variant = new VoxReference<Variant>(variant.Id);
period.FromUtc = campaign.StartsUtc;
period.ToUtc = campaign.EndsUtc;
period.Amount = campaign.PriceFor(variant);
});
}
}
}
A published period is history: if the campaign is later changed, the existing period is kept as it was, and the calculation can create another one with a new id for the new terms.
A run may propose at most VoxProcessingOptions.MaxCalculationOutputs outputs (1000 by default); more fails the run
with an error that says so. A calculation whose outputs can be that many, eg one that creates a period for every
variant of a large product range, should be rooted on the smaller entity, here the variant, so that Vox runs it for
each variant in turn.
Calculate fields of related entities
A property of another entity type can be marked with a calculation of another root. An order's calculation can then maintain a field of its lines:
public class OrderLine : IVoxEntity
{
// Built-in entity properties omitted.
public required virtual VoxReference<Order> Order { get; set; }
public virtual int Quantity { get; set; }
[VoxCalculated(typeof(OrderDiscountCalculation))]
public virtual decimal DiscountAllocation { get; set; }
}
public class OrderDiscountCalculation : IVoxCalculation<Order>
{
public async Task CalculateAsync(Order order, Order result, IVoxCalculationContext context,
CancellationToken cancellationToken)
{
var lines = await context.LoadRelatedAsync<OrderLine>(order, cancellationToken);
var total = lines.Sum(line => line.Quantity);
foreach (var line in lines)
{
context.ResultFor(line).DiscountAllocation =
total == 0 ? 0 : order.Discount * line.Quantity / total;
}
}
}
The calculation is rooted on the order, and the order doesn't need a calculated field. It reads its lines like any
calculation, asks context.ResultFor(line) for a copy of a line to write to, and sets the fields that it calculates.
Setting any other field of the line fails the calculation, as does a line that doesn't belong to this order.
- Finding the order of a line. Each line must belong to exactly one order. Vox finds it through the only relation
between the two types. If there are several relations, name the right one with
Via:[VoxCalculated(typeof(OrderDiscountCalculation), Via = [nameof(OrderLine.Order)])]. Several names make a longer route, eg from a period through its variant to a product, where every step towards the root must refer to one entity. - When it runs. Changing the order's discount, or a line's quantity, or adding, removing or moving a line, runs the order's calculation, for a moved line for both the old and the new order. A new line gets its share before it's first published.
- When the result is visible. The order and its lines are a group that's saved together: a save of the order, or of a line whose change the order's calculation reads, runs the order's calculation in the save, and publishes the order and every line whose share changed together. Readers never see the new discount or quantity with an old share. See Settled saves.
- The size of a group. A proportional discount changes every share, so a line's save of an order with 200 lines
writes 201 entities. An evaluation can propose at most
VoxOptions.Processing.MaxCalculationOutputs(1,000) outputs; more fails the save with an error that tells you to calculate from narrower roots. The order's calculation reads its lines through the relation, eg withLoadRelatedAsync, so it sees the saved line's new values; one that finds its lines with a query fails the save. A line's save that changes nothing the order reads, eg its note, saves the line alone. - A share calculated before the line changed. The order's calculation can finish after a line it read has changed again, eg its quantity changed while the order was being calculated. Vox records which fields of the line the order read, and applies the share only if they still have the values the order read. Otherwise the share is dropped and the order is calculated again from the line as it is. A change of a field the order doesn't read, eg the line's note, doesn't hold the share back. A line whose read fields keep changing faster than the order is calculated, eg from a feed that updates it every second, keeps the order recalculating, and its processing fails once that chain gets too long; calculate such values from fields that settle.
A calculation must do something: it needs fields of its own entity, fields of related entities, or entities that it creates. One that has none is invalid. Fields of related entities are only those of its own root's related entities; it can't change fields that another calculation owns.
Drafts and releases preview what would be created
For an entity type with drafts, calculations run in drafts and releases too, and that includes creation. When an editor changes a customer in a draft so that the customer becomes eligible, the draft reads the proposed renewal contract, though no published reader can:
- The contract exists only in that draft or release. Published reads, lists, queries and counts don't include it, and nothing is delivered to subscriptions or projections.
- A later change of the draft refreshes the proposal, and when the draft no longer leads to it, eg it's reverted, or the calculation stops proposing it, the proposed contract is removed from the draft.
- Other calculations in the draft read the proposed contract like any other entity, so anything that depends on contracts is calculated against it.
- When the customer is published, published content calculates the contract again and creates it, with the values of that run. The draft then reads the published contract.
- Deleting the customer removes the contracts its calculation proposed in drafts and releases. Contracts it already created in published content stay.
In a draft, the calculation itself reads contracts without the draft's proposals, as published content has them. So a calculation that checks whether the contract exists before it proposes it, as in the example above, still proposes it in the draft on every run, and the proposal is removed exactly when the draft no longer leads to it, whichever order the calculation checks things in. Other calculations, and everyone else reading the draft, see the proposal.
A proposed entity isn't something the editor authors: it has no draft of its own to edit and isn't an item of a release. The type doesn't need to be authored either.
A type that editors author, IVoxAuthoredEntity, isn't previewed, since a proposal would look like an editor's own
draft. In a draft or release, its creation shows as Dropped in Effects, with the reason that it's created when the
change that leads to it is published, and published content creates it then. If an editor has a draft of an entity
with the same id that isn't published, the editor's draft is kept, as with an id that's already published, and the
calculation's creation shows as Exists already. If the editor reverts that draft, the entity is created the next
time the calculation proposes it.
See what a draft creates
The customer's Effects tab in the admin lists what its calculations create or calculate in the draft, under Created and calculated by its calculations, eg "Renewal 2027 · Creates by Customer renewal", with the values that differ from published content. A row can show Pending while its entity hasn't received the output yet, eg when the processing calculated it in the background, Exists already when a proposed entity exists and was kept as it is, and Dropped with the reason when an output wasn't applied, eg a contract that another customer's calculation created. A draft whose calculation only creates entities still shows the draft bar's effects and the tab's dot, although nothing reads the fields it changed.
Opening the proposed contract in the draft shows it as a Calculated preview: which customer's calculation creates it, that it doesn't exist in published content and can't be edited there, the creation's explanation, and the entities that read it in the draft. A line whose discount the order's calculation calculates names the order the same way. In a release's overview, a proposed entity is marked Created by a calculation and isn't an item of the release.
In published content, the tab lists what the calculations calculate of other entities, eg the discounts of an order's lines. A creation leaves that list once the calculation finds the created entity and stops proposing it.
The API has it at GET /api/{entityType}/{id}/effects/outputs, a page at a time, and the producers of an entity in
the producers of GET /api/{entityType}/{id}/effects. Both show only the entities the principal may read.
Explain what a calculation creates
Explanations name what they explain by its subject: a field of the calculation's own entity type by its path, a field
of another entity type by the type and the path, and a creation by create: and the type:
[VoxFieldExplanation("create:RenewalContract",
"A renewal contract for each eligible customer and year. The contract's id is the customer and the year, so the " +
"same contract is never created twice.")]
public class CustomerRenewalCalculation : IVoxCalculation<Customer>
[VoxFieldExplanation("OrderLine:discountAllocation", "The order's discount, shared between its lines by their quantities.")]
public class OrderDiscountCalculation : IVoxCalculation<Order>
Say when an entity is created and what identifies it, so editors understand why one exists and why another isn't
created. vox-explain generates the subjects that aren't written, like other fields, and mapping files use the same
subjects. The explanation of a related field is shown with that field, and the creation's on the created entity type.
Storage and model changes
Calculations that create entities or calculate fields of other entity types need Entity Framework storage for the entity types they involve. A model that uses them with Redis storage, or with the types stored in different providers, fails at startup. Transient entity types, the only ones stored in Redis, can't have calculations at all, since they aren't tracked.
Changing which calculation creates a type, or which calculation calculates a field, makes the next model activation calculate that calculation again for all of its roots. Adding such a calculation can therefore create entities for every existing customer or variant that qualifies. That's useful for a backfill, but plan for it, and let the calculation decide eligibility.
See Calculations, Owned and mirrored data and Drafts and publishing.