-
-
Notifications
You must be signed in to change notification settings - Fork 935
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat(core): variant price calculator #1614
Closed
JMPJNS
wants to merge
4
commits into
vendure-ecommerce:minor
from
JMPJNS:feature/variant-price-calculator
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
135 changes: 135 additions & 0 deletions
135
packages/core/src/service/helpers/variant-calculator/variant-calculator.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
import { Test } from '@nestjs/testing'; | ||
import { LanguageCode } from '@vendure/common/lib/generated-types'; | ||
|
||
import { TestOrderItemPriceCalculationStrategy } from '../../../../e2e/fixtures/test-order-item-price-calculation-strategy'; | ||
import { RequestContext } from '../../../api'; | ||
import { RequestContextCacheService } from '../../../cache'; | ||
import { | ||
ConfigService, | ||
DefaultTaxLineCalculationStrategy, | ||
DefaultTaxZoneStrategy, | ||
PromotionCondition, | ||
PromotionItemAction, | ||
ShippingCalculator, | ||
} from '../../../config'; | ||
import { DefaultProductVariantPriceCalculationStrategy } from '../../../config/catalog/default-product-variant-price-calculation-strategy'; | ||
import { MockConfigService } from '../../../config/config.service.mock'; | ||
import { Order, ProductVariant, Promotion } from '../../../entity'; | ||
import { EventBus } from '../../../event-bus'; | ||
import { createRequestContext, MockTaxRateService } from '../../../testing/order-test-utils'; | ||
import { CustomerService } from '../../services/customer.service'; | ||
import { OrderService } from '../../services/order.service'; | ||
import { ShippingMethodService } from '../../services/shipping-method.service'; | ||
import { TaxRateService } from '../../services/tax-rate.service'; | ||
import { ZoneService } from '../../services/zone.service'; | ||
import { ListQueryBuilder } from '../list-query-builder/list-query-builder'; | ||
import { OrderCalculator } from '../order-calculator/order-calculator'; | ||
import { ProductPriceApplicator } from '../product-price-applicator/product-price-applicator'; | ||
|
||
import { VariantCalculator } from './variant-calculator'; | ||
|
||
describe('OrderCalculator', () => { | ||
let variantCalculator: VariantCalculator; | ||
|
||
beforeAll(async () => { | ||
const module = await createTestModule(); | ||
variantCalculator = module.get(VariantCalculator); | ||
const mockConfigService = module.get<ConfigService, MockConfigService>(ConfigService); | ||
mockConfigService.taxOptions = { | ||
taxZoneStrategy: new DefaultTaxZoneStrategy(), | ||
taxLineCalculationStrategy: new DefaultTaxLineCalculationStrategy(), | ||
}; | ||
mockConfigService.orderOptions = { | ||
orderItemPriceCalculationStrategy: new TestOrderItemPriceCalculationStrategy(), | ||
}; | ||
mockConfigService.catalogOptions = { | ||
productVariantPriceCalculationStrategy: new DefaultProductVariantPriceCalculationStrategy(), | ||
}; | ||
}); | ||
|
||
describe('variant price calculator', () => { | ||
it('calculates the correct price for provided order', async () => { | ||
const ctx = createRequestContext({ pricesIncludeTax: false }); | ||
const order = new Order({ active: true, shippingAddress: {}, customer: { id: 1 } }); | ||
const variant = new ProductVariant({ | ||
listPrice: 50, | ||
productVariantPrices: [{ channelId: 1, price: 50 }], | ||
taxCategory: { id: 1 }, | ||
}); | ||
|
||
const alwaysTrueCondition = new PromotionCondition({ | ||
args: {}, | ||
code: 'always_true_condition', | ||
description: [{ languageCode: LanguageCode.en, value: '' }], | ||
check() { | ||
return true; | ||
}, | ||
}); | ||
|
||
const fixedPriceItemAction = new PromotionItemAction({ | ||
code: 'fixed_price_item_action', | ||
description: [{ languageCode: LanguageCode.en, value: '' }], | ||
args: {}, | ||
execute(context, item) { | ||
return -8; | ||
}, | ||
}); | ||
|
||
const promotion = new Promotion({ | ||
conditions: [{ code: alwaysTrueCondition.code, args: [] }], | ||
promotionConditions: [alwaysTrueCondition], | ||
actions: [ | ||
{ | ||
code: fixedPriceItemAction.code, | ||
args: [], | ||
}, | ||
], | ||
promotionActions: [fixedPriceItemAction], | ||
}); | ||
|
||
const calculated = await variantCalculator.applyVariantPromotions( | ||
ctx, | ||
variant, | ||
[promotion], | ||
1, | ||
order, | ||
); | ||
expect(calculated).toBe(50 - 8); | ||
}); | ||
}); | ||
}); | ||
|
||
function createTestModule() { | ||
return Test.createTestingModule({ | ||
providers: [ | ||
VariantCalculator, | ||
ProductPriceApplicator, | ||
RequestContextCacheService, | ||
{ provide: TaxRateService, useClass: MockTaxRateService }, | ||
{ provide: ShippingCalculator, useValue: { getEligibleShippingMethods: () => [] } }, | ||
{ | ||
provide: ShippingMethodService, | ||
useValue: { | ||
findOne: (ctx: RequestContext) => ({ | ||
id: 'T_2', | ||
test: () => true, | ||
apply() { | ||
return { | ||
price: 500, | ||
priceIncludesTax: ctx.channel.pricesIncludeTax, | ||
taxRate: 20, | ||
}; | ||
}, | ||
}), | ||
}, | ||
}, | ||
{ provide: ListQueryBuilder, useValue: {} }, | ||
{ provide: ConfigService, useClass: MockConfigService }, | ||
{ provide: EventBus, useValue: { publish: () => ({}) } }, | ||
{ provide: ZoneService, useValue: { findAll: () => [] } }, | ||
{ provide: CustomerService, useValue: {} }, | ||
{ provide: OrderService, useValue: {} }, | ||
OrderCalculator, | ||
], | ||
}).compile(); | ||
} |
128 changes: 128 additions & 0 deletions
128
packages/core/src/service/helpers/variant-calculator/variant-calculator.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { CreateAddressInput } from '@vendure/common/lib/generated-types'; | ||
|
||
import { RequestContext } from '../../../api'; | ||
import { InternalServerError } from '../../../common'; | ||
import { ConfigService } from '../../../config'; | ||
import { Order, OrderItem, OrderLine, ProductVariant, Promotion, ShippingLine } from '../../../entity'; | ||
import { CustomerService } from '../../services/customer.service'; | ||
import { OrderService } from '../../services/order.service'; | ||
import { OrderCalculator } from '../order-calculator/order-calculator'; | ||
import { ProductPriceApplicator } from '../product-price-applicator/product-price-applicator'; | ||
|
||
@Injectable() | ||
export class VariantCalculator { | ||
constructor( | ||
private configService: ConfigService, | ||
private orderService: OrderService, | ||
private customerService: CustomerService, | ||
private productPriceApplicator: ProductPriceApplicator, | ||
private orderCalculator: OrderCalculator, | ||
) {} | ||
|
||
/** | ||
* @description adds the variant to a new order based on `initialOrder` and applies all `promotions`, | ||
* | ||
* if no `initialOrder` is supplied, it is based on the users active order | ||
*/ | ||
public async applyVariantPromotions( | ||
ctx: RequestContext, | ||
variant: ProductVariant, | ||
promotions: Promotion[], | ||
quantity = 1, | ||
initialOrder?: Order, | ||
) { | ||
const customerId = initialOrder?.customer?.id ?? ctx.activeUserId; | ||
if (!customerId) { | ||
throw new InternalServerError('no active user or order customer'); | ||
} | ||
|
||
const { orderItemPriceCalculationStrategy } = this.configService.orderOptions; | ||
if (!orderItemPriceCalculationStrategy) { | ||
throw new InternalServerError('no item price calculation strategy found'); | ||
} | ||
|
||
let order: Order; | ||
if (initialOrder) { | ||
order = new Order(initialOrder); | ||
} else if (ctx.session?.activeOrderId) { | ||
order = (await this.orderService.findOne(ctx, ctx.session?.activeOrderId)) ?? new Order(); | ||
} else { | ||
order = new Order(); | ||
} | ||
order.lines ??= []; | ||
order.surcharges ??= []; | ||
order.modifications ??= []; | ||
|
||
if (!order.customer) { | ||
order.customer = await this.customerService.findOne(ctx, customerId); | ||
} | ||
|
||
if (!order.shippingAddress) { | ||
const addrs = await this.customerService.findAddressesByCustomerId(ctx, customerId); | ||
// FIXME use correct Error type | ||
if (addrs.length === 0) throw new Error(`no Address for Customer ${customerId} found`); | ||
|
||
const shippingAddress = addrs.find(x => x.defaultShippingAddress) ?? addrs[0]; | ||
const billingAddress = addrs.find(x => x.defaultBillingAddress) ?? addrs[0]; | ||
|
||
order.shippingAddress = { | ||
...shippingAddress, | ||
countryCode: shippingAddress.country.code, | ||
} as CreateAddressInput; | ||
order.billingAddress = { | ||
...billingAddress, | ||
countryCode: billingAddress.country.code, | ||
} as CreateAddressInput; | ||
} | ||
|
||
const adjustedVariant = await this.productPriceApplicator.applyChannelPriceAndTax( | ||
variant, | ||
ctx, | ||
order, | ||
); | ||
const orderLine = new OrderLine({ | ||
productVariant: variant, | ||
items: [], | ||
taxCategory: variant.taxCategory, | ||
}); | ||
|
||
const { price, priceIncludesTax } = await orderItemPriceCalculationStrategy.calculateUnitPrice( | ||
ctx, | ||
adjustedVariant, | ||
{}, | ||
); | ||
const taxRate = adjustedVariant.taxRateApplied; | ||
const unitPrice = priceIncludesTax ? taxRate.netPriceOf(price) : price; | ||
|
||
for (let i = 0; i < quantity; i++) { | ||
const orderItem = new OrderItem({ | ||
id: adjustedVariant.id, | ||
listPrice: price, | ||
listPriceIncludesTax: priceIncludesTax, | ||
adjustments: [], | ||
taxLines: [], | ||
}); | ||
orderLine.items.push(orderItem); | ||
} | ||
|
||
order.shippingLines = [ | ||
new ShippingLine({ | ||
listPrice: 0, | ||
listPriceIncludesTax: ctx.channel.pricesIncludeTax, | ||
taxLines: [], | ||
adjustments: [], | ||
}), | ||
]; | ||
|
||
order.lines.push(orderLine); | ||
const adjustedItems = await this.orderCalculator.applyPriceAdjustments(ctx, order, promotions); | ||
const item = adjustedItems.find(x => x.line?.productVariant.id === variant.id); | ||
if (!item) | ||
// TODO figure out how to handle this case and why it can happen | ||
// since this methods usecase is mostly to display a discounted price | ||
// it should probably just return the original price when it can't be calculated | ||
throw new Error('variant was not adjusted'); | ||
return item.discountedUnitPrice; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the
initialOrder
is of typeOrder
, you should not need to construct a new one here right? Or is there some reason you need to?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wouldn't adding orderLines to initialOrder mutate the order that is passed to the function, since its members are references and not copied values