This is the third article in a series of five on SAP Commerce Order Management. In the previous one, How SAP Commerce Picks a Warehouse, we looked at how warehouse fitness is calculated during sourcing and mentioned in passing that the allocation factor reads a map of available stock. Now let's see where that map comes from.

As in the rest of the series, the focus is on runtime execution mechanics and project-level configuration, a layer below the overview guides on the SAP Help Portal.

About the code in this article

The Java snippets below are an illustrative reconstruction: a simplified retelling of the algorithm with renamed variables and collapsed branches, written as a sketch to explain how the calculation works. The Spring XML, ImpEx and items.xml snippets are configuration files shipped with the platform, and I quote them as is.

Kinds of stock in retail

In retail, "how much of this item do we have" can be answered in several ways, and the answer depends on the task.

On hand is what a physical count finds on the shelf. It is the only number with a physical meaning, but on its own it is of little use to the storefront: some of those units are already promised to other orders.

Available to promise (ATP) is on-hand stock minus commitments plus expected receipts. This is the number the storefront shows, and the hard part is agreeing on which commitments and which deliveries to count. A unit set aside for an order placed ten minutes ago is obviously subtracted. An item sitting in someone's cart usually isn't. A shipment arriving at the warehouse on Thursday counts if the business is willing to promise delivery with Thursday in mind.

Capable to promise (CTP) adds production capacity or the option to buy from a supplier. The concept comes from manufacturing, but in retail it shows up wherever there is drop shipping or pre-orders.

Allocated to promise is the same arithmetic restricted to a sales channel or customer category, when a contract B2B buyer and an anonymous site visitor see different stock from the same shelf.

On top of the base numbers come adjustments for real warehouse life. Safety stock holds back a buffer against mis-sorts and theft. Shrinkage and wastage write off goods that are on the books but are physically damaged or lost. An overselling allowance, on the other hand, lets you sell slightly more than you have, counting on a known share of future cancellations.

Implementations differ first of all in whether to store or compute available stock: keep a ready-made number and update it in every transaction, or keep the primary records and recalculate stock on read. A stored number reads instantly but drifts from reality after any missed update; a computed one is always internally consistent but costs database queries on every read. The other decision is whether to reserve up front: does visible stock go down for everyone else when a shopper adds an item to the cart or proceeds to payment? Reservation removes the race for the last unit but requires a whole subsystem: reservations need an expiry, a collector has to sweep up expired ones, and the collector has to handle clock skew carefully.

SAP Commerce goes with the computed model and leaves pre-allocation reservation up to the project. Both decisions are visible in the data model.

StockLevel, InventoryEvent and AtpFormula

StockLevel is one row per product and warehouse pair; it holds the available quantity, the reserved quantity, an inStockStatus and a string field bin. bin holds a plain text label with no hierarchy of zones, aisles and racks. StockLevel describes commercial availability, and bin-level location management stays with the warehouse management system (WMS).

InventoryEvent is an abstract type with six concrete subtypes. Each is an append-only record of a quantity of goods tied to a specific StockLevel:

Event Sign out of the box When it's created
AllocationEvent − when a consignment is created
CancellationEvent + when an order or an entry is canceled
IncreaseEvent + on a stock adjustment with reason INCREASE
ShrinkageEvent − on a stock adjustment with reason SHRINKAGE
WastageEvent − on a stock adjustment with reason WASTAGE
ReservationEvent — declared in the schema; out-of-the-box code neither writes nor reads it

The data model has a type for reservations, but the project writes the logic around it itself.

AtpFormula is a data type with a code and nine Boolean attributes. The storefront points to one such formula through BaseStore.defaultAtpFormula, and that formula answers every availability request within that BaseStore. There is no override at the level of an individual point of service (PointOfService): stock for a particular store and stock for the online storefront are calculated with the same formula, just over different sets of warehouses.

Anatomy of the ATP formula: filtering StockLevel records, reading StockLevel columns and summing InventoryEvent subtypes

By how they take part in the calculation, the flags fall into three groups.

Two flags, availability and reserved, sum columns directly from the StockLevel table:

SELECT SUM({available}) FROM {StockLevel}
WHERE {pk} IN (?stockLevels)

SELECT SUM({reserved})  FROM {StockLevel}
WHERE {pk} IN (?stockLevels)

Five flags, allocation, cancellation, increase, shrinkage and wastage, aggregate the corresponding InventoryEvent subtype:

SELECT SUM({quantity}) FROM {AllocationEvent as ae}
WHERE {ae.stockLevel} IN (?stockLevels)

The remaining two flags, returned and external, don't run queries of their own. They determine which StockLevel records make it into the ?stockLevels selection in the first place. With external = false, stock in warehouses flagged as external is filtered out; with returned = false, records whose bin matches the configured returns bin (RETURNED_BIN) are filtered out.

Two more filters apply unconditionally, before the formula flags are checked: records with status FORCEOUTOFSTOCK are excluded, as are records tied to a canceled advance shipping notice (ASN). A separate check short-circuits: if at least one of the participating StockLevel records has status FORCEINSTOCK, the calculation immediately returns null without running any formula queries. To the calling code, that means unlimited stock.

The sample data shipped with the platform enables every flag except external. That gives the maximal formula:

ATP = SUM(StockLevel.available)
    − SUM(StockLevel.reserved)
    − SUM(AllocationEvent.quantity)
    + SUM(CancellationEvent.quantity)
    + SUM(IncreaseEvent.quantity)
    − SUM(ShrinkageEvent.quantity)
    − SUM(WastageEvent.quantity)

The sums run over the StockLevel records that passed filtering, and because returned is enabled, items in the returns bin go straight back into sellable stock. Seven enabled terms mean seven separate aggregating FlexibleSearch queries on every availability calculation. That's why the StockLevel list is collected once at the start and passed to every query as a parameter.

The base project data (projectdata) doesn't create a default formula for a new storefront, so adding an AtpFormula and linking it to the BaseStore is part of the initial project setup. Which flags to enable depends on the specific retailer's business processes, and the sample data configuration serves as an example with every possible term.

How formula flags map to DAO methods

A Boolean field on the model is tied to a DAO method through reflection. This mechanism determines how to add a custom factor to the formula and in which cases the formula starts calculating wrong.

How a Boolean attribute on AtpFormula is matched to a DAO method by substring

As a reconstruction, evaluating the formula looks like this:

// illustration
long evaluate(AtpFormulaModel formula, Map<String, Object> params) {
    long total = 0L;
    for (PropertyDescriptor p : introspect(formula.getClass())) {
        if (!Boolean.class.equals(p.getPropertyType())) {
            continue;
        }
        String variable = p.getName().toLowerCase();
        // these two flags are filters; they have already been applied
        if ("returned".equals(variable)
                || "external".equals(variable)) {
            continue;
        }
        if (!Boolean.TRUE.equals(p.getReadMethod().invoke(formula))) {
            continue;
        }
        String sign = signMap.get(variable);
        if (!"+".equals(sign) && !"-".equals(sign)) {
            log.error("no arithmetic sign for {}", variable);
            continue;
        }
        for (Method m : atpDao.getClass().getMethods()) {
            if (m.getName().toLowerCase().contains(variable)) {
                long value = (Long) m.invoke(atpDao, params);
                total += "-".equals(sign) ? -value : value;
            }
        }
    }
    return total;
}

The set of variables is collected through introspection of the model class. Every Boolean property on AtpFormulaModel becomes a candidate. If you add a Boolean attribute to AtpFormula for an unrelated purpose, say a UI toggle or a technical migration flag, it also enters the loop as a formula variable. If such a flag is set to true, an ERROR about the missing sign shows up in the log, and if its name happens to be in the sign map, whatever the substring-matched DAO methods return gets added to the result.

The arithmetic sign is stored separately from the model, in Spring configuration:

<util:map id="defaultAtpFormulaVar2ArithmeticOperatorMap"
          key-type="java.lang.String"
          value-type="java.lang.String">
  <entry key="availability"  value="+"/>
  <entry key="allocation"    value="-"/>
  <entry key="cancellation"  value="+"/>
  <entry key="increase"      value="+"/>
  <entry key="reserved"      value="-"/>
  <entry key="shrinkage"     value="-"/>
  <entry key="wastage"       value="-"/>
  <entry key="returned"      value="+"/>
  <entry key="external"      value="+"/>
</util:map>

The comment above this map in the shipped XML warns explicitly: a variable missing from the map (or mapped to anything other than + or -) is skipped during calculation, even if the flag is enabled in the formula. If a new custom factor contributes nothing to the result, check this map first and search the logs for an ERROR line with the variable name.

Matching to a DAO method works by substring across all public DAO methods. The variable shrinkage finds getShrinkageQuantityForStockLevels because its lowercased name contains the substring "shrinkage". The loop doesn't stop at the first match: if two methods match, both are called. When a project adds a method like getShrinkageQuantityExcludingDamaged to the same DAO, both methods fire and their results add up, doubling the write-off. The simplest safeguard is to make sure helper method names in a custom DAO don't contain existing formula variable names as substrings.

Since addition is commutative, the order in which properties are visited doesn't matter, and the loop can iterate over a HashSet of property descriptors. A formula built this way can only compute a sum of signed terms. For a percentage buffer or a min() across warehouses, a single flag is no longer enough, and you'll need your own implementation of the calculation strategy.

Adding a custom factor

Say you need to subtract quarantined stock (quarantine) from available stock:

  1. Add a quarantine attribute of type Boolean to the AtpFormula type in your extension's items.xml.
  2. Add a DAO method with the substring quarantine in its name that takes the same parameter map and returns a Long.
  3. Add the entry <entry key="quarantine" value="-"/> to the sign map in Spring XML.

There's no need to register a strategy or override WarehousingAvailabilityCalculationStrategy; the extension point picks it up automatically.

Previewing a formula in Backoffice

Backoffice has an ATP Views screen for checking formulas: you enter a product code, pick a BaseStore, optionally narrow it down to a point of service, and immediately see the resulting number for each formula next to its expanded text form.

The controller, in memory and without saving to the database, plugs each formula in turn into BaseStore.defaultAtpFormula and calls the same StockService method the storefront uses, so the number on the screen matches what a shopper will see. When investigating incidents where an item unexpectedly shows as out of stock, this screen gets you the answer fastest, and it's also a convenient place to check the effect of toggling flags before you change the production formula.

Until allocation, stock isn't held for anyone

Availability is recalculated on every read from tables shared by all visitors. Neither adding an item to the cart nor placing an order writes anything to the stock tables. The first record that reduces available stock under the ATP formula is an AllocationEvent, and allocation runs only after the order has been saved, at the step that creates consignments.

Order timeline: available stock doesn't go down between add-to-cart and allocation

As a result, two shoppers can both see the last unit of an item on the storefront, go through checkout and get an order confirmation. The conflict is resolved after the fact during sourcing: the first order gets the item and a consignment is created, while the second has nothing left to allocate and is left with an unallocated quantity (quantityUnallocated) that the business has to deal with. This is done for the sake of conversion. If every add-to-cart locked the item, a noticeable share of stock would end up frozen in abandoned carts.

For a broad assortment with deep stock, this approach is justified. With single-unit items (limited editions, high-demand drops, in-store pickup where the shelf holds one or two units), two people buying the last unit at the same time happens regularly.

Ready-made primitives for closing this window sit one layer below Order Management, in the platform's core StockService. Its reserve and release methods move units between the available and reserved fields of a StockLevel record and throw InsufficientStockLevelException if there isn't enough free stock:

// illustration
void reserve(ProductModel product, WarehouseModel warehouse,
             int amount, String comment) {
    StockLevelModel level = requireStockLevel(product, warehouse);
    Integer reserved = stockLevelDao.reserve(level, amount);
    if (reserved == null) {
        throw new InsufficientStockLevelException(
            "insufficient available amount");
    }
    clearCacheForItem(level);
    recordHistory(level, CUSTOMER_RESERVE, reserved, comment);
}

The standard accelerator checkout doesn't call these methods (out of the box, only the Chinese payments extension uses them), but the reserved term in the ATP formula is already configured and subtracts whatever is written to that column. So a project that needs to hold stock during payment only has to add a reserve call at the right point in checkout, a release on cancellation or on the move to allocation, and a background job that cleans up expired reservations.

If a reservation has to outlive a single checkout session, it's easier to model it with ReservationEvent: this is exactly the kind of task the subtype is in the schema for. Write events of this type and add a DAO method with reservation in its name, and they hook into the formula through the mechanism described above.

Quantities you can't query the database for

The quantities that describe the current state of an order entry are declared in the model as dynamic attributes. There are nine of them, six on OrderEntry and three on ConsignmentEntry:

Type Attribute How it's computed
OrderEntry quantityAllocated from consignment entries of non-canceled consignments
OrderEntry quantityUnallocated ordered quantity minus quantityAllocated
OrderEntry quantityShipped sum over consignment entries
OrderEntry quantityPending ordered quantity minus quantityShipped
OrderEntry quantityCancelled aggregate over cancellation records
OrderEntry quantityReturned aggregate over return request entries
ConsignmentEntry quantityShipped aggregating query over shipment events
ConsignmentEntry quantityPending consignment quantity minus quantityShipped
ConsignmentEntry quantityDeclined aggregate over decline events (DeclineEvent)

None of these fields is stored in a table column. Each is computed in Java on read, and some are nested: to calculate quantityShipped on an order entry, the code walks all of its ConsignmentEntry records and asks each for its own quantityShipped, which is backed by a separate aggregating database query. An order with five entries split across three consignments can run fifteen SQL queries just to answer "how many units have shipped."

You can't write a FlexibleSearch or SQL condition on these fields. A perfectly natural support query, "find all order entries with an unallocated quantity older than two days," doesn't translate directly into the database, and iterating over candidate orders in Java memory doesn't scale to reporting volumes. Projects that need such queries usually add stored mirror columns and update them in interceptors (PrepareInterceptor), keeping the dynamic attribute as the source of truth and the column as a projection for search and reporting.

Reading these attributes in a loop also creates load that isn't visible in tests with a single order. A Backoffice list or an export that reads quantityShipped on a thousand order entries generates thousands of small aggregating queries. If the order list in Backoffice starts to slow down, check that list's columns first.

On the other hand, these numbers can't drift apart. There is no stored counter to forget to update on some rare status transition, and no nightly reconciliation job is needed. The price is extra queries on every read.

Stubs in AtpFormulaService

The AtpFormulaService interface declares five methods. getAllAtpFormula delegates to the DAO and works as expected. Three methods, getAtpFormulaByCode, createAtpFormula and updateAtpFormula, are left as stubs that return null, and deleteAtpFormula calls getAtpFormulaByCode internally and therefore does nothing either.

In normal operation this never surfaces, because out-of-the-box code doesn't call them: Backoffice creates and edits formulas through the platform's standard mechanism (ModelService), and the delete handler in Backoffice checks directly that the formula isn't linked to any BaseStore. You'll only run into these stubs when calling AtpFormulaService from your own code, for example from an admin API or migration scripts. If needed, they're easy to override in a project extension: the DAO underneath implements all the required methods in full.

Pre-production checklist

Area What to check and decide on the project
Storefront formula make sure defaultAtpFormula is set on every live BaseStore
Flag selection decide explicitly on external and returned, since they change the set of StockLevel records itself
Safety stock model the buffer (simplest is a permanent write-off event or a custom term)
Single-unit stock decide whether to hold stock during checkout and, if so, implement reservation expiry
DAO method names check that no custom DAO method contains an existing variable name as a substring
Sign map make sure every new formula variable has + or - in the sign map (defaultAtpFormulaVar2ArithmeticOperatorMap)
Reporting and queries add stored projection columns for the dynamic quantities you need to search on in the database
Backoffice lists check whether lists and exports read dynamic quantities in a loop over hundreds of orders
FORCEINSTOCK keep track of which StockLevel records have this status: one such record makes the whole stock unlimited

The next article in the series covers cancellation, on hold and returns: how canceling a single unit rebuilds every consignment containing that item, what happens to allocation events when an order is put on hold, and how the pick-decline reason table works.