Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
da6a4e7
docs: Add OSS-274 order recalculation design spec
grolmus Jul 6, 2026
e83b2bf
docs: Add OSS-274 order recalculation implementation plan
grolmus Jul 6, 2026
5405a63
feat(core): Add OrderRecalculationStrategy with TTL built-in
grolmus Jul 6, 2026
52abb64
feat(core): Add orderRecalculationStrategy to OrderOptions
grolmus Jul 6, 2026
708bb69
feat(core): Add applyPriceAdjustmentsIfStale and pricingUpdatedAt bump
grolmus Jul 6, 2026
a32568f
feat(core): Recalculate stale active order on read
grolmus Jul 6, 2026
688a96c
feat(core): Recalculate and verify shipping eligibility at checkout
grolmus Jul 6, 2026
90a7217
fix(core): Exclude shipping from read-time order recalculation
grolmus Jul 6, 2026
6af0e24
Merge remote-tracking branch 'upstream/master' into mgrolmus/oss-274-…
grolmus Jul 6, 2026
3d5a714
fix(core): Register orderRecalculationStrategy for injectable lifecycle
grolmus Jul 6, 2026
a86ee61
fix(core): Make read-time order recalculation transactional and locked
grolmus Jul 6, 2026
37b4b2e
fix(core): Recalculate at checkout only after all guards pass
grolmus Jul 6, 2026
67404e2
docs(core): Correct order recalculation shipping/docs annotations
grolmus Jul 6, 2026
935b5df
test(core): Tighten order recalculation e2e assertions
grolmus Jul 6, 2026
b4835bc
docs(core): Clarify read-time recalc excludes shipping in applyPriceA…
grolmus Jul 6, 2026
6e32e49
chore: Remove OSS-274 planning docs from branch
grolmus Jul 7, 2026
b08d211
fix(core): Re-test shipping promotions on read and gate checkout elig…
grolmus Jul 10, 2026
ff22971
fix(core): Recalculate prices at checkout regardless of shipping pres…
grolmus Jul 10, 2026
22d88c3
fix(core): Store pricingUpdatedAt with fractional-second precision to…
grolmus Jul 10, 2026
7dab28d
docs(core): Correct OrderRecalculationStrategy docs for shipping-prom…
grolmus Jul 13, 2026
594245e
Merge remote-tracking branch 'origin/minor' into mgrolmus/oss-274-car…
grolmus Jul 15, 2026
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
629 changes: 629 additions & 0 deletions packages/core/e2e/order-recalculation.e2e-spec.ts

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/core/src/config/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export class ConfigModule implements OnApplicationBootstrap, OnApplicationShutdo
orderSellerStrategy,
guestCheckoutStrategy,
orderInterceptors,
orderRecalculationStrategy,
} = this.configService.orderOptions;
const {
customFulfillmentProcess,
Expand Down Expand Up @@ -154,6 +155,7 @@ export class ConfigModule implements OnApplicationBootstrap, OnApplicationShutdo
...errorHandlers,
assetImportStrategy,
changedPriceHandlingStrategy,
...(orderRecalculationStrategy ? [orderRecalculationStrategy] : []),
orderLineDiscountDistributionStrategy,
...(Array.isArray(activeOrderStrategy) ? activeOrderStrategy : [activeOrderStrategy]),
orderSellerStrategy,
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/config/default-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import { defaultOrderProcess } from './order/default-order-process';
import { DefaultOrderSellerStrategy } from './order/default-order-seller-strategy';
import { DefaultStockAllocationStrategy } from './order/default-stock-allocation-strategy';
import { MergeOrdersStrategy } from './order/merge-orders-strategy';
import { NoOrderRecalculationStrategy } from './order/no-order-recalculation-strategy';
import { DefaultOrderByCodeAccessStrategy } from './order/order-by-code-access-strategy';
import { DefaultOrderCodeStrategy } from './order/order-code-strategy';
import { UseGuestStrategy } from './order/use-guest-strategy';
Expand Down Expand Up @@ -189,6 +190,7 @@ export const defaultConfig: RuntimeVendureConfig = {
orderSellerStrategy: new DefaultOrderSellerStrategy(),
guestCheckoutStrategy: new DefaultGuestCheckoutStrategy(),
orderInterceptors: [],
orderRecalculationStrategy: new NoOrderRecalculationStrategy(),
},
paymentOptions: {
paymentMethodEligibilityCheckers: [],
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export * from './order/default-order-seller-strategy';
export * from './order/default-stock-allocation-strategy';
export * from './order/guest-checkout-strategy';
export * from './order/merge-orders-strategy';
export * from './order/no-order-recalculation-strategy';
export * from './order/order-by-code-access-strategy';
export * from './order/order-code-strategy';
export * from './order/order-interceptor';
Expand All @@ -76,8 +77,10 @@ export * from './order/order-line-discount-distribution-strategy';
export * from './order/order-merge-strategy';
export * from './order/order-placed-strategy';
export * from './order/order-process';
export * from './order/order-recalculation-strategy';
export * from './order/order-seller-strategy';
export * from './order/stock-allocation-strategy';
export * from './order/ttl-order-recalculation-strategy';
export * from './order/use-existing-strategy';
export * from './order/use-guest-if-existing-empty-strategy';
export * from './order/use-guest-strategy';
Expand Down
35 changes: 34 additions & 1 deletion packages/core/src/config/order/default-order-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { ID } from '@vendure/common/lib/shared-types';
import { unique } from '@vendure/common/lib/unique';

import { RequestContext } from '../../api/common/request-context';
import { idsAreEqual } from '../../common/utils';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { Order } from '../../entity/order/order.entity';
import { OrderLine } from '../../entity/order-line/order-line.entity';
import { OrderModification } from '../../entity/order-modification/order-modification.entity';
import { Order } from '../../entity/order/order.entity';
import { Payment } from '../../entity/payment/payment.entity';
import { ProductVariant } from '../../entity/product-variant/product-variant.entity';
import { OrderPlacedEvent } from '../../event-bus/events/order-placed-event';
Expand Down Expand Up @@ -169,6 +170,7 @@ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions
let stockLevelService: import('../../service/index').StockLevelService;
let historyService: import('../../service/index').HistoryService;
let orderSplitter: import('../../service/index').OrderSplitter;
let orderService: import('../../service/index').OrderService;

const orderProcess: OrderProcess<OrderState> = {
transitions: {
Expand Down Expand Up @@ -248,6 +250,7 @@ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions
const ProductVariantService = await import('../../service/index.js').then(
m => m.ProductVariantService,
);
const OrderService = await import('../../service/index.js').then(m => m.OrderService);
connection = injector.get(TransactionalConnection);
productVariantService = injector.get(ProductVariantService);
configService = injector.get(ConfigService);
Expand All @@ -256,6 +259,7 @@ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions
stockLevelService = injector.get(StockLevelService);
historyService = injector.get(HistoryService);
orderSplitter = injector.get(OrderSplitter);
orderService = injector.get(OrderService);
},

async onTransitionStart(fromState, toState, { ctx, order }) {
Expand Down Expand Up @@ -327,6 +331,29 @@ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions
) {
return 'message.cannot-transition-to-payment-without-shipping-method';
}
// Recalculate prices, promotions and shipping promotions for every transition to
// ArrangingPayment — including shipping-less checkouts — so payment always runs
// against fresh totals. This is done WITHOUT re-selecting the shipping method, so
// eligibility is judged (below) on current prices and the customer's chosen method
// is never swapped silently. Doing it before the eligibility check is essential:
// otherwise a recalculation that makes the chosen method ineligible slips past the
// guard and applyShipping would silently swap it to another method.
await orderService.applyPriceAdjustments(ctx, order, order.lines, undefined, {
recalculateShipping: false,
recalculateShippingPromotions: true,
});
if (options.arrangingPaymentRequiresShipping !== false && order.shippingLines?.length) {
const eligibleMethods = await orderService.getEligibleShippingMethods(ctx, order.id);
const eligibleIds = eligibleMethods.map(m => m.id);
const hasIneligible = order.shippingLines.some(
line =>
line.shippingMethodId != null &&
!eligibleIds.some(id => idsAreEqual(id, line.shippingMethodId)),
);
if (hasIneligible) {
return 'message.cannot-transition-to-payment-with-ineligible-shipping-method';
}
}
if (options.arrangingPaymentRequiresStock !== false) {
const variantsWithInsufficientSaleableStock: ProductVariant[] = [];
for (const line of order.lines) {
Expand All @@ -349,6 +376,12 @@ export function configureDefaultOrderProcess(options: DefaultOrderProcessOptions
);
}
}
// All refusal guards passed — do a full recalculation (prices, promotions, taxes
// and shipping rate) before payment. The chosen method was verified eligible
// above, so applyShipping refreshes its rate without swapping the method.
if (options.arrangingPaymentRequiresShipping !== false && order.shippingLines?.length) {
await orderService.applyPriceAdjustments(ctx, order, order.lines);
}
}
if (options.checkPaymentsCoverTotal !== false) {
if (toState === 'PaymentAuthorized') {
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/config/order/no-order-recalculation-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { OrderRecalculationStrategy } from './order-recalculation-strategy';

/**
* @description
* The default {@link OrderRecalculationStrategy} which never triggers a read-time recalculation.
* This preserves the behaviour of Vendure prior to v3.8.0, where an active Order's prices are only
* re-calculated on write mutations.
*
* @docsCategory orders
* @docsPage OrderRecalculationStrategy
* @since 3.8.0
*/
export class NoOrderRecalculationStrategy implements OrderRecalculationStrategy {
shouldRecalculate(): boolean {
return false;
}
}
42 changes: 42 additions & 0 deletions packages/core/src/config/order/order-recalculation-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { RequestContext } from '../../api/common/request-context';
import { InjectableStrategy } from '../../common/types/injectable-strategy';
import { Order } from '../../entity/order/order.entity';

/**
* @description
* This strategy determines whether an active Order's prices, promotions, taxes and shipping
* promotions should be re-calculated when the Order is read (e.g. via the `activeOrder` query).
* Recalculation is only ever attempted for Orders in the `AddingItems` state.
*
* **Note:** the shipping *method* and *rate* are NOT re-evaluated on read, so a read never silently
* swaps the customer's chosen method — those are re-evaluated when the Order transitions to
* `ArrangingPayment` (checkout). Shipping *promotions* are re-tested, so a now-inactive shipping
* promotion's discount is cleared rather than surviving on the Order.
*
* The default {@link NoOrderRecalculationStrategy} never triggers a recalculation, preserving the
* historical behaviour whereby an active Order's prices are only updated on write mutations. Use
* {@link TtlOrderRecalculationStrategy} (or a custom implementation) to keep long-lived carts in
* sync with changing product prices and promotions.
*
* :::info
*
* This is configured via the `orderOptions.orderRecalculationStrategy` property of your VendureConfig.
*
* :::
*
* @docsCategory orders
* @docsPage OrderRecalculationStrategy
* @since 3.8.0
*/
export interface OrderRecalculationStrategy extends InjectableStrategy {
/**
* @description
* Return `true` to trigger a recalculation of the Order's prices, promotions and taxes before
* it is returned from the active-order read path.
*
* **Note:** Implementations should rely only on fields that are always present on the Order
* (e.g. `pricingUpdatedAt`, `state`, `active`). Deep relations (lines, promotions, etc.) may
* not be loaded on the Order passed to this method.
*/
shouldRecalculate(ctx: RequestContext, order: Order): boolean | Promise<boolean>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest';

import { Order } from '../../entity/order/order.entity';

import { TtlOrderRecalculationStrategy } from './ttl-order-recalculation-strategy';

describe('TtlOrderRecalculationStrategy', () => {
const ctx = {} as any;
const strategy = new TtlOrderRecalculationStrategy({ ttlMs: 60_000 });

function orderWith(pricingUpdatedAt: Date | undefined): Order {
return { pricingUpdatedAt } as Order;
}

it('is stale when pricingUpdatedAt is null/undefined', () => {
expect(strategy.shouldRecalculate(ctx, orderWith(undefined))).toBe(true);
});

it('is not stale within the TTL window', () => {
expect(strategy.shouldRecalculate(ctx, orderWith(new Date(Date.now() - 1_000)))).toBe(false);
});

it('is stale past the TTL window', () => {
expect(strategy.shouldRecalculate(ctx, orderWith(new Date(Date.now() - 120_000)))).toBe(true);
});

it('is stale at exactly the TTL boundary (>= comparison)', () => {
// At exactly Date.now() - ttlMs the order is considered stale (>= comparison).
expect(strategy.shouldRecalculate(ctx, orderWith(new Date(Date.now() - 60_000)))).toBe(true);
});
});
38 changes: 38 additions & 0 deletions packages/core/src/config/order/ttl-order-recalculation-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { RequestContext } from '../../api/common/request-context';
import { Order } from '../../entity/order/order.entity';

import { OrderRecalculationStrategy } from './order-recalculation-strategy';

/**
* @description
* An {@link OrderRecalculationStrategy} which recalculates an active Order when the time since its
* last recalculation exceeds the configured `ttlMs`. This mirrors the "price freeze period" model
* used by other e-commerce platforms: quoted prices remain stable for a period, then refresh on the
* next access.
*
* @example
* ```ts
* import { TtlOrderRecalculationStrategy, VendureConfig } from '@vendure/core';
*
* export const config: VendureConfig = {
* // ...
* orderOptions: {
* orderRecalculationStrategy: new TtlOrderRecalculationStrategy({ ttlMs: 5 * 60 * 1000 }),
* },
* };
* ```
*
* @docsCategory orders
* @docsPage OrderRecalculationStrategy
* @since 3.8.0
*/
export class TtlOrderRecalculationStrategy implements OrderRecalculationStrategy {
constructor(private options: { ttlMs: number }) {}

shouldRecalculate(ctx: RequestContext, order: Order): boolean {
if (order.pricingUpdatedAt == null) {
return true;
}
return Date.now() - order.pricingUpdatedAt.getTime() >= this.options.ttlMs;
}
}
14 changes: 14 additions & 0 deletions packages/core/src/config/vendure-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { OrderLineDiscountDistributionStrategy } from './order/order-line-discou
import { OrderMergeStrategy } from './order/order-merge-strategy';
import { OrderPlacedStrategy } from './order/order-placed-strategy';
import { OrderProcess } from './order/order-process';
import { OrderRecalculationStrategy } from './order/order-recalculation-strategy';
import { OrderSellerStrategy } from './order/order-seller-strategy';
import { StockAllocationStrategy } from './order/stock-allocation-strategy';
import { PaymentMethodEligibilityChecker } from './payment/payment-method-eligibility-checker';
Expand Down Expand Up @@ -725,6 +726,19 @@ export interface OrderOptions {
* @default []
*/
orderInterceptors?: OrderInterceptor[];
/**
* @description
* Defines whether and when an active Order's prices, promotions and taxes are re-calculated
* when the Order is read (e.g. via the `activeOrder` query). By default no read-time
* recalculation occurs (prices only change on write mutations). Use
* {@link TtlOrderRecalculationStrategy} to keep long-lived carts in sync with changing prices
* and promotions. Shipping method eligibility and rates are NOT re-evaluated on read; they are
* re-evaluated when the order transitions to `ArrangingPayment`.
*
* @default NoOrderRecalculationStrategy
* @since 3.8.0
*/
orderRecalculationStrategy?: OrderRecalculationStrategy;
}

/**
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/entity/order/order.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ export class Order extends VendureEntity implements ChannelAware, HasCustomField
@Index()
orderPlacedAt?: Date;

/**
* @description
* The date & time that the Order's prices, promotions and taxes were last recalculated via
* {@link OrderService.applyPriceAdjustments}. Used by the configured {@link OrderRecalculationStrategy}
* to determine whether an active Order is stale and should be recalculated on read.
* Shipping method eligibility and rates are NOT included in read-time recalculation.
*
* @since 3.8.0
*/
// `precision: 6` stores fractional seconds. Without it, MySQL's `DATETIME` has
// second-level precision and *rounds* the stored value, which can push a freshly
// stamped timestamp into the future relative to `Date.now()` — making the
// OrderRecalculationStrategy staleness check (e.g. TTL 0) incorrectly report "not
// stale" and skip the read-time recalculation.
@Column({ nullable: true, precision: 6 })
pricingUpdatedAt?: Date;

@Index()
@ManyToOne(type => Customer, customer => customer.orders)
customer?: Customer;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/i18n/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
"cannot-transition-to-payment-due-to-insufficient-stock": "Cannot transition Order to the \"ArrangingPayment\" state due to insufficient stock of { productVariantNames }",
"cannot-transition-to-payment-without-customer": "Cannot transition Order to the \"ArrangingPayment\" state without Customer details",
"cannot-transition-to-payment-without-shipping-method": "Cannot transition Order to the \"ArrangingPayment\" state without a ShippingMethod",
"cannot-transition-to-payment-with-ineligible-shipping-method": "Cannot transition Order to the \"ArrangingPayment\" state because the selected ShippingMethod is no longer eligible",
"cannot-transition-unless-all-cancelled": "Cannot transition Order to the \"Cancelled\" state unless all OrderItems are cancelled",
"cannot-transition-unless-all-order-items-delivered": "Cannot transition Order to the \"Delivered\" state unless all OrderItems are delivered",
"cannot-transition-unless-some-order-items-delivered": "Cannot transition Order to the \"PartiallyDelivered\" state unless some OrderItems are delivered",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ export class ActiveOrderService {
}
}
}
if (order) {
order = await this.orderService.applyPriceAdjustmentsIfStale(ctx, order);
}
return order || undefined;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,33 @@ import { ShippingCalculator } from '../shipping-calculator/shipping-calculator';

import { prorate } from './prorate';

/**
* @description
* Options passed to {@link OrderService.applyPriceAdjustments} and {@link OrderCalculator.applyPriceAdjustments}.
*
* @docsCategory orders
* @docsPage OrderRecalculationStrategy
* @since 3.8.0
*/
export interface ApplyPriceAdjustmentsOptions {
/**
* @description
* Whether the shipping method & rate should be re-evaluated — which may swap the Order's
* shipping method to a different eligible one. Defaults to `true`.
*/
recalculateShipping?: boolean;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking (CodeRabbit flagged this too): recalculateShippingPromotions has a thorough doc block whose meaning depends on this flag, but this one has none.

Suggested change
recalculateShipping?: boolean;
/**
* @description
* Whether the shipping method & rate should be re-evaluated which may swap the Order's
* shipping method to a different eligible one. Defaults to `true`.
*/
recalculateShipping?: boolean;

/**
* @description
* When `recalculateShipping` is `false` (the chosen shipping method & rate are left
* untouched), this controls whether shipping *promotions* are still re-tested and their
* adjustments cleared/re-applied. Defaults to the value of `recalculateShipping`, so
* callers that freeze shipping entirely (e.g. order modification) are unaffected, while
* read-time recalculation can drop a now-inactive shipping promotion's discount without
* re-selecting the method.
*/
recalculateShippingPromotions?: boolean;
}

/**
* @description
* This helper is used when making changes to an Order, to apply all applicable price adjustments to that Order,
Expand Down Expand Up @@ -55,7 +82,7 @@ export class OrderCalculator {
order: Order,
promotions: Promotion[],
updatedOrderLines: OrderLine[] = [],
options?: { recalculateShipping?: boolean },
options?: ApplyPriceAdjustmentsOptions,
): Promise<Order> {
const { taxZoneStrategy } = this.configService.taxOptions;
// We reset the promotions array as all promotions
Expand Down Expand Up @@ -101,8 +128,16 @@ export class OrderCalculator {
await this.applyTaxes(ctx, order, activeTaxZone);
}
}
if (options?.recalculateShipping !== false) {
const recalculateShipping = options?.recalculateShipping !== false;
// Shipping promotions default to following `recalculateShipping`, but can be re-tested
// independently: read-time recalculation freezes the chosen method/rate yet must still
// clear a now-inactive shipping promotion's adjustment (clearAdjustments() only runs
// inside applyShippingPromotions).
const recalculateShippingPromotions = options?.recalculateShippingPromotions ?? recalculateShipping;
if (recalculateShipping) {
await this.applyShipping(ctx, order);
}
if (recalculateShippingPromotions) {
await this.applyShippingPromotions(ctx, order, promotions);
}
this.calculateOrderTotals(order);
Expand Down
Loading
Loading