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
4 changes: 3 additions & 1 deletion packages/core/src/config/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ export class ConfigModule implements OnApplicationBootstrap, OnApplicationShutdo
shopApiKeyStrategy,
entityAccessControlStrategy,
} = this.configService.authOptions;
const { taxZoneStrategy, taxLineCalculationStrategy } = this.configService.taxOptions;
const { taxZoneStrategy, taxLineCalculationStrategy, orderTaxCalculationStrategy } =
this.configService.taxOptions;
const { jobQueueStrategy, jobBufferStorageStrategy } = this.configService.jobQueueOptions;
const { schedulerStrategy } = this.configService.schedulerOptions;
const {
Expand Down Expand Up @@ -129,6 +130,7 @@ export class ConfigModule implements OnApplicationBootstrap, OnApplicationShutdo
assetStorageStrategy,
taxZoneStrategy,
taxLineCalculationStrategy,
orderTaxCalculationStrategy,
jobQueueStrategy,
jobBufferStorageStrategy,
mergeStrategy,
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 @@ -58,6 +58,7 @@ import { defaultShippingEligibilityChecker } from './shipping-method/default-shi
import { DefaultShippingLineAssignmentStrategy } from './shipping-method/default-shipping-line-assignment-strategy';
import { InMemoryCacheStrategy } from './system/in-memory-cache-strategy';
import { NoopInstrumentationStrategy } from './system/noop-instrumentation-strategy';
import { DefaultOrderTaxCalculationStrategy } from './tax/default-order-tax-calculation-strategy';
import { DefaultTaxLineCalculationStrategy } from './tax/default-tax-line-calculation-strategy';
import { DefaultTaxZoneStrategy } from './tax/default-tax-zone-strategy';
import { RuntimeVendureConfig } from './vendure-config';
Expand Down Expand Up @@ -195,6 +196,7 @@ export const defaultConfig: RuntimeVendureConfig = {
taxOptions: {
taxZoneStrategy: new DefaultTaxZoneStrategy(),
taxLineCalculationStrategy: new DefaultTaxLineCalculationStrategy(),
orderTaxCalculationStrategy: new DefaultOrderTaxCalculationStrategy(),
},
importExportOptions: {
importAssetsDir: __dirname,
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 @@ -100,8 +100,11 @@ export * from './system/error-handler-strategy';
export * from './system/health-check-strategy';
export * from './system/instrumentation-strategy';
export * from './tax/address-based-tax-zone-strategy';
export * from './tax/default-order-tax-calculation-strategy';
export * from './tax/default-tax-line-calculation-strategy';
export * from './tax/default-tax-zone-strategy';
export * from './tax/order-level-tax-calculation-strategy';
export * from './tax/order-tax-calculation-strategy';
export * from './tax/tax-line-calculation-strategy';
export * from './tax/tax-zone-strategy';
export * from './vendure-config';
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { OrderTaxSummary, TaxLine } from '@vendure/common/lib/generated-types';
import { summate } from '@vendure/common/lib/shared-utils';

import { OrderLine } from '../../entity/order-line/order-line.entity';
import { Order } from '../../entity/order/order.entity';
import { Surcharge } from '../../entity/surcharge/surcharge.entity';

import { OrderTaxCalculationStrategy, OrderTotalsResult } from './order-tax-calculation-strategy';

/**
* @description
* The default {@link OrderTaxCalculationStrategy}. Tax is rounded at the
* individual line level and then summed. This matches the standard Vendure behaviour
* prior to the introduction of this strategy.
*
* @docsCategory tax
* @docsPage OrderTaxCalculationStrategy
* @since 3.6.0
*/
export class DefaultOrderTaxCalculationStrategy implements OrderTaxCalculationStrategy {
calculateOrderTotals(order: Order): OrderTotalsResult {
let subTotal = 0;
let subTotalWithTax = 0;
for (const line of order.lines ?? []) {
subTotal += line.proratedLinePrice;
subTotalWithTax += line.proratedLinePriceWithTax;
}
for (const surcharge of order.surcharges ?? []) {
subTotal += surcharge.price;
subTotalWithTax += surcharge.priceWithTax;
}

let shipping = 0;
let shippingWithTax = 0;
for (const shippingLine of order.shippingLines ?? []) {
shipping += shippingLine.discountedPrice;
shippingWithTax += shippingLine.discountedPriceWithTax;
}

return { subTotal, subTotalWithTax, shipping, shippingWithTax };
}

calculateTaxSummary(order: Order): OrderTaxSummary[] {
const taxRateMap = new Map<
string,
{ rate: number; base: number; tax: number; description: string }
>();
const taxId = (taxLine: TaxLine): string => `${taxLine.description}:${taxLine.taxRate}`;
const taxableLines = [
...(order.lines ?? []),
...(order.shippingLines ?? []),
...(order.surcharges ?? []),
];
for (const line of taxableLines) {
if (!line.taxLines?.length) {
continue;
}
const taxRateTotal = summate(line.taxLines, 'taxRate');
for (const taxLine of line.taxLines) {
const id = taxId(taxLine);
const row = taxRateMap.get(id);
const proportionOfTotalRate = 0 < taxLine.taxRate ? taxLine.taxRate / taxRateTotal : 0;

const lineBase =
line instanceof OrderLine
? line.proratedLinePrice
: line instanceof Surcharge
? line.price
: line.discountedPrice;
const lineWithTax =
line instanceof OrderLine
? line.proratedLinePriceWithTax
: line instanceof Surcharge
? line.priceWithTax
: line.discountedPriceWithTax;
const amount = Math.round((lineWithTax - lineBase) * proportionOfTotalRate);
if (row) {
row.tax += amount;
row.base += lineBase;
} else {
taxRateMap.set(id, {
tax: amount,
base: lineBase,
description: taxLine.description,
rate: taxLine.taxRate,
});
}
}
}
return Array.from(taxRateMap.entries()).map(([, row]) => ({
taxRate: row.rate,
description: row.description,
taxBase: row.base,
taxTotal: row.tax,
}));
}
}
136 changes: 136 additions & 0 deletions packages/core/src/config/tax/order-level-tax-calculation-strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { OrderTaxSummary, TaxLine } from '@vendure/common/lib/generated-types';

import { taxPayableOn } from '../../common/tax-utils';
import { Order } from '../../entity/order/order.entity';

import { OrderTaxCalculationStrategy, OrderTotalsResult } from './order-tax-calculation-strategy';

interface TaxGroup {
rate: number;
description: string;
netBase: number;
}

/**
* @description
* An {@link OrderTaxCalculationStrategy} that groups net subtotals by tax rate
* and rounds once per group. This eliminates per-line rounding accumulation errors
* present in the {@link DefaultOrderTaxCalculationStrategy}.
*
* This approach is required by certain jurisdictions and ERP systems that expect
* tax to be calculated on the subtotal per tax rate rather than per line.
*
* Note that when using this strategy, the `taxTotal` in the tax summary may differ
* by ±1 minor unit from the sum of individual line-level `proratedLineTax` values.
* This is expected and is the intended behaviour.
*
* @example
* ```ts
* import { OrderLevelTaxCalculationStrategy, VendureConfig } from '\@vendure/core';
*
* export const config: VendureConfig = {
* taxOptions: {
* orderTaxCalculationStrategy: new OrderLevelTaxCalculationStrategy(),
* },
* };
* ```
*
* @docsCategory tax
* @docsPage OrderTaxCalculationStrategy
* @since 3.6.0
*/
export class OrderLevelTaxCalculationStrategy implements OrderTaxCalculationStrategy {
calculateOrderTotals(order: Order): OrderTotalsResult {
const { subTotal, subTotalGroups, shipping, shippingGroups } = this.groupOrder(order);

let subTotalTax = 0;
for (const [, group] of subTotalGroups) {
subTotalTax += Math.round(taxPayableOn(group.netBase, group.rate));
}

let shippingTax = 0;
for (const [, group] of shippingGroups) {
shippingTax += Math.round(taxPayableOn(group.netBase, group.rate));
}

return {
subTotal,
subTotalWithTax: subTotal + subTotalTax,
shipping,
shippingWithTax: shipping + shippingTax,
};
}

calculateTaxSummary(order: Order): OrderTaxSummary[] {
const { subTotalGroups, shippingGroups } = this.groupOrder(order);

const merged = new Map<string, TaxGroup & { tax: number }>();
for (const groups of [subTotalGroups, shippingGroups]) {
for (const [key, group] of groups) {
const roundedTax = Math.round(taxPayableOn(group.netBase, group.rate));
const existing = merged.get(key);
if (existing) {
existing.netBase += group.netBase;
existing.tax += roundedTax;
} else {
merged.set(key, { ...group, tax: roundedTax });
}
}
}
const taxSummary: OrderTaxSummary[] = [];
for (const [, group] of merged) {
taxSummary.push({
taxRate: group.rate,
description: group.description,
taxBase: group.netBase,
taxTotal: group.tax,
});
}
return taxSummary;
}

private groupOrder(order: Order) {
let subTotal = 0;
let shipping = 0;
const subTotalGroups = new Map<string, TaxGroup>();
const shippingGroups = new Map<string, TaxGroup>();

for (const line of order.lines ?? []) {
subTotal += line.proratedLinePrice;
this.accumulateIntoGroups(subTotalGroups, line.taxLines, line.proratedLinePrice);
}
for (const surcharge of order.surcharges ?? []) {
subTotal += surcharge.price;
this.accumulateIntoGroups(subTotalGroups, surcharge.taxLines, surcharge.price);
}
for (const shippingLine of order.shippingLines ?? []) {
shipping += shippingLine.discountedPrice;
this.accumulateIntoGroups(shippingGroups, shippingLine.taxLines, shippingLine.discountedPrice);
}

return { subTotal, subTotalGroups, shipping, shippingGroups };
}

private accumulateIntoGroups(
groups: Map<string, TaxGroup>,
taxLines: TaxLine[] | undefined,
lineNetBase: number,
) {
if (!taxLines?.length) {
return;
}
for (const taxLine of taxLines) {
const key = `${taxLine.description}:${taxLine.taxRate}`;
const existing = groups.get(key);
if (existing) {
existing.netBase += lineNetBase;
} else {
groups.set(key, {
rate: taxLine.taxRate,
description: taxLine.description,
netBase: lineNetBase,
});
}
}
}
}
Loading
Loading